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
ANIMATIONRELATED OPERATIONS put keyvalue pair into BST
animatePut(key, val) { let animations = []; animations.push(new Animation("display", `Putting ${key}`, "")); this.root = this.animatePutHelper( this.root, key, val, this.rootX, this.rootY, this.rootDeltaX, this.rootDeltaY, animations ); animations.push(new Animation("display", `Put ${key}`, "")); return animations; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function bst({ root, key }) {\n if(!root) {\n root = { key };\n }\n else if (key < root.key) {\n root.left = bst({ root: root.left, key });\n }\n else {\n root.right = bst({ root: root.right, key });\n }\n return root;\n}", "insert (key, value) {\n value = value || key;\n\n //leafs need to insert the value at themself and make new leaf children\n if(this.height == 0) {\n this.key = key;\n this.value = value || key;\n this.left = new BinarySearchTree(this);\n this.right = new BinarySearchTree(this);\n this.height = 1;\n this.numLeftChildren = 1;\n this.numRightChildren = 1;\n return;\n }\n\n if(key == this.key) return;\n\n if(key < this.key) {\n this.numLeftChildren++;\n this.left.insert(key);\n this.height = Math.max(this.height, 1 + this.left.height);\n }\n if(key >= this.key) {\n this.numRightChildren++;\n this.right.insert(key);\n this.height = Math.max(this.height, 1 + this.right.height);\n }\n\n this.rebalance();\n }", "async function splay(node_, key)\n{\n\n\n\n // Base cases: node_ is NULL or\n // key is present at node_\n if (node_ == \"null\" || parseInt( $(\"#\"+node_+\"treeval\").text(),10) == key) return node_;\n\n await hilight(node_, \"rgb(109,209,0,1)\" , \"1200ms\" , 1300 )\n hilight(node_, defaultcolor , \"1200ms\" , 1300 )\n\n\n // Key lies in left subtree\n if (parseInt( $(\"#\"+node_+\"treeval\").text(),10) > key)\n {\n // Key is not in tree, we are done\n if (tree[node_+\"treeleft\"] == \"null\") return node_;\n\n // Zig-Zig (Left Left)\n if ( parseInt( $(\"#\"+tree[node_+\"treeleft\"]+\"treeval\").text(),10) > key)\n {\n // First recursively bring the\n // key as node_ of left-left\n let left = tree[node_+\"treeleft\"];\n\n tree[left+\"treeleft\"] = await splay(tree[left+\"treeleft\"], key);\n\n // Do first rotation for node_,\n // second rotation is done after else\n node_ = await splayrightRotate(node_);\n\n\n }\n else if (parseInt( $(\"#\"+tree[node_+\"treeleft\"]+\"treeval\").text(),10) < key) // Zig-Zag (Left Right)\n {\n // First recursively bring\n // the key as node_ of left-right\n let left = tree[node_+\"treeleft\"];\n\n tree[left+\"treeright\"] = await splay(tree[left+\"treeright\"], key);\n\n // Do first rotation for node_->left\n if (tree[left+\"treeright\"] != \"null\")\n tree[node_+\"treeleft\"] = await splayleftRotate(tree[node_+\"treeleft\"]);\n\n\n }\n\n Shiftright(node_)\n Shiftleft(node_)\n\n await waitforme(speed+100);\n\n // Do second rotation for node_\n return (tree[node_+\"treeleft\"] == \"null\")? node_: await splayrightRotate(node_);\n }\n\n\n else // Key lies in right subtree\n {\n // Key is not in tree, we are done\n let right = tree[node_+\"treeright\"];\n\n if (right == \"null\") return node_;\n\n // Zag-Zig (Right Left)\n if ( parseInt( $(\"#\"+right+\"treeval\").text(),10) > key)\n {\n // Bring the key as node_ of right-left\n tree[right+\"treeleft\"] = await splay(tree[right+\"treeleft\"], key);\n\n // Do first rotation for node_->right\n if (tree[right+\"treeleft\"] != \"null\")\n tree[node_+\"treeright\"] = await splayrightRotate(tree[node_+\"treeright\"]);\n }\n else if (parseInt( $(\"#\"+right+\"treeval\").text(),10) < key)// Zag-Zag (Right Right)\n {\n // Bring the key as node_ of\n // right-right and do first rotation\n tree[right+\"treeright\"] = await splay(tree[right+\"treeright\"] , key);\n node_ = await splayleftRotate(node_);\n }\n\n\n Shiftright(node_)\n Shiftleft(node_)\n\n await waitforme(speed+100);\n\n\n\n // Do second rotation for node_\n return (tree[node_+\"treeright\"] == \"null\")? node_: await splayleftRotate(node_);\n }\n\n\n\n\n}", "insertAutomatic(node,key,scene) {\n\n if (node.key == 'null') {\n\n node.setKey(key);\n node.setNodeGraphics();\n\n // // create left child\n // var childL = new NodeBST(scene, node.posX-this.w, node.posY+this.z, 'null',node.dpth+1,node);\n // childL.distanceFromParent = -this.w;\n \n // // create right child\n // var childR = new NodeBST(scene, node.posX+this.w, node.posY+this.z, 'null',node.dpth+1,node);\n // childR.distanceFromParent = this.w;\n\n // node.setChildren(childL,childR);\n\n if (this.isRB) {\n\n if (node != this.root) {\n node.isRed = true;\n }\n node.changeLinkColour(scene);\n\n // create left child\n var childL = new NodeBST(scene, this.nodeColor, node.posX-this.w, node.posY+this.z, 'null',node.dpth+1,node,true);\n childL.distanceFromParent = -this.w;\n \n // create right child\n var childR = new NodeBST(scene, this.nodeColor, node.posX+this.w, node.posY+this.z, 'null',node.dpth+1,node,true);\n childR.distanceFromParent = this.w;\n\n node.setChildren(childL,childR);\n\n this.nodearray.push(childL);\n this.nodearray.push(childR);\n\n // update depth of the tree\n if (childL.dpth > this.treedpth) {\n this.treedpth = childL.dpth;\n }\n\n this.checkRBLinksInserted(scene,node);\n this.check(scene);\n\n } else {\n\n // create left child\n var childL = new NodeBST(scene, this.nodeColor, node.posX-this.w, node.posY+this.z, 'null',node.dpth+1,node,false);\n childL.distanceFromParent = -this.w;\n \n // create right child\n var childR = new NodeBST(scene, this.nodeColor, node.posX+this.w, node.posY+this.z, 'null',node.dpth+1,node,false);\n childR.distanceFromParent = this.w;\n\n node.setChildren(childL,childR);\n\n this.checkCollisions(childL);\n \n this.checkCollisions(childR);\n \n // update depth of the tree\n if (childL.dpth > this.treedpth) {\n this.treedpth = childL.dpth;\n }\n \n // this.traverseAndCheckCollisions(scene);\n this.traverseAndCheckCrossings(scene);\n this.traverseAndCheckCollisions(scene);\n }\n\n } else if (node.key > key) {\n if (node.left != null) { // we might not need this if statement check cause we dont have a node.left that is null\n this.insertAutomatic(node.left, key, scene);\n }\n } else if (node.key < key) {\n if (node.right != null) {\n this.insertAutomatic(node.right, key, scene);\n }\n }\n }", "insert(key) {\n\n const insertNode = (node, key) => {\n if(key < node.key) {\n if(node.left === null) {\n node.left = new Node(key)\n } else {\n return insertNode(node.left, key)\n }\n } else {\n if (node.right === null) {\n node.right = new Node(key)\n } else {\n return insertNode(node.right, key)\n }\n }\n }\n\n if( this.root === null ) {\n \n this.root = new Node( key )\n \n } else {\n return insertNode(this.root, key)\n }\n }", "_insert(key, value, root) {\n // Perform regular BST insertion\n if (root === null) {\n return new Node(key, value);\n }\n if (this.compare(key, root.key) < 0) {\n root.left = this._insert(key, value, root.left);\n }\n else if (this.compare(key, root.key) > 0) {\n root.right = this._insert(key, value, root.right);\n }\n else {\n return root;\n }\n // Update height and rebalance tree\n root.height = Math.max(root.leftHeight, root.rightHeight) + 1;\n const balanceState = this._getBalanceState(root);\n if (balanceState === 4 /* UNBALANCED_LEFT */) {\n if (this.compare(key, root.left.key) < 0) {\n // Left left case\n root = root.rotateRight();\n }\n else {\n // Left right case\n root.left = root.left.rotateLeft();\n return root.rotateRight();\n }\n }\n if (balanceState === 0 /* UNBALANCED_RIGHT */) {\n if (this.compare(key, root.right.key) > 0) {\n // Right right case\n root = root.rotateLeft();\n }\n else {\n // Right left case\n root.right = root.right.rotateRight();\n return root.rotateLeft();\n }\n }\n return root;\n }", "insert(key, value) {\n //if the tree is empty => then key being inserted is the root node of the tree\n if (this.key == null) {\n this.key = key; \n this.value = value; \n }\n //if tree already exists => start at the root & compare it to key you want to insert\n //if new key is less than node's key then new node need to live in the left-hand branch\n else if (key < this.key) {\n if (this.left == null) {\n this.left = new BinarySearchTree(key, value, this);\n }\n else {\n //if node has existing left child => recursively call `insert` method\n //so node is added futher down the tree\n this.left.insert(key, value);\n }\n }\n //if new key is > than nodes' key => put it on the right side \n else {\n if (this.right == null) {\n this.right = new BinarySearchTree(key, value, this);\n }\n else {\n this.right.insert(key, value)\n }\n }\n }", "insert (key, value) {\n const newTree = this.tree.insert(key, value)\n\n // If newTree is undefined, that means its structure was not modified\n if (newTree) { this.tree = newTree }\n }", "insertManual(node, key, scene) {\n if (node.key == 'null') {\n node.setKey(key);\n node.setNodeGraphics();\n\n if(this.isRB) {\n node.isRed = true;\n \n if(node == this.root) {\n node.isRed = false;\n }\n \n node.changeLinkColour(scene);\n \n // create left child\n var childL = new NodeBST(scene, this.nodeColor, node.posX-this.w, node.posY+this.z, 'null',node.dpth+1,node,true);\n childL.distanceFromParent = -this.w;\n childL.drawLinkToParentRB(scene)\n this.nodearray.push(childL);\n\n \n // create right child\n var childR = new NodeBST(scene, this.nodeColor, node.posX+this.w, node.posY+this.z, 'null',node.dpth+1,node,true);\n childR.distanceFromParent = this.w;\n childR.drawLinkToParentRB(scene)\n this.nodearray.push(childR);\n\n\n node.setChildren(childL,childR);\n \n // update depth of the tree\n if (childL.dpth > this.treedpth) {\n this.treedpth = childL.dpth;\n // this.redraw(scene)\n }\n } else {\n\n // create left child\n var childL = new NodeBST(scene, this.nodeColor, node.posX-this.w, node.posY+this.z, 'null',node.dpth+1,node,false);\n childL.distanceFromParent = -this.w;\n childL.drawLinkToParent(scene)\n\n \n // create right child\n var childR = new NodeBST(scene, this.nodeColor, node.posX+this.w, node.posY+this.z, 'null',node.dpth+1,node,false);\n childR.distanceFromParent = this.w;\n childR.drawLinkToParent(scene)\n\n \n node.setChildren(childL,childR);\n \n this.checkCollisions(childL);\n \n this.checkCollisions(childR);\n \n // update depth of the tree\n if (childL.dpth > this.treedpth) {\n this.treedpth = childL.dpth;\n }\n \n // this.traverseAndCheckCollisions(scene);\n this.traverseAndCheckCrossings(scene);\n this.traverseAndCheckCollisions(scene);\n\n }\n\n } else if (node.key > key) {\n if (node.left != null) { \n this.insertManual(node.left, key, scene);\n }\n } else if (node.key < key) {\n if (node.right != null) {\n this.insertManual(node.right, key, scene);\n }\n }\n }", "function step2(map) {\n\tconst root = { name: '/', nodes: [] };\n\treturn (function next(map, parent, level) {\n\t\tObject.keys(map).forEach(key => {\n\t\t\tlet val = map[key];\n\t\t\tlet node = { name: key };\n\t\t\tif (typeof val === 'object') {\n\t\t\t\tnode.nodes = [];\n\t\t\t\tnode.open = level < 1;\n\t\t\t\tnext(val, node, level + 1);\n\t\t\t} else {\n\t\t\t\tnode.src = val;\n\t\t\t}\n\t\t\tparent.nodes.push(node);\n\t\t});\n\t\treturn parent;\n\t})(map, root, 0);\n}", "insert(key, value) {\n this.root = this._insert(key, value, this.root);\n }", "insert(key, value) {\n // if the tree is empty then this key being inserted is the root node of the tree\n if (this.key === null) {\n this.key = key;\n this.value = value;\n }\n /* If the existing node does not have a left child, \n meaning that if the `left` pointer is empty, \n then we can just instantiate and insert the new node \n as the left child of that node, passing `this` as the parent */\n else if (key < this.key) {\n if (this.left === null) {\n this.left = new BinarySearchTree(key, value, this)\n }\n /* If the node has an existing left child, \n then we recursively call the `insert` method \n so the node is added further down the tree */\n else {\n this.left.insert(key, value);\n }\n }\n // Similarly, if the new key is greater than the node's key then you do the same thing, but on the right-hand side */\n else {\n if (this.right == null) {\n this.right = new BinarySearchTree(key, value, this)\n } else {\n this.right.insert(key, value);\n }\n }\n }", "constructor(key = null, value = null, parent = null) {\n this.key = key;\n this.value = value;\n this.parent = parent;\n this.left = null;\n this.right = null;\n }", "constructor(key = null, value = null, parent = null) {\n this.key = key;\n this.value = value;\n this.parent = parent;\n this.left = null;\n this.right = null;\n }", "insert(value) {\n if (value === this.key) {\n return;\n }\n\n if (value < this.key) {\n if (this.left) {\n return this.left.insert(value);\n }\n\n this.left = new Node(value);\n\n return value;\n }\n\n if (this.right) {\n return this.right.insert(value);\n }\n\n this.right = new Node(value);\n\n return value;\n }", "insert (key, value) {\n const insertPath = []\n let currentNode = this\n\n // Empty tree, insert as root\n if (!Object.prototype.hasOwnProperty.call(this, 'key')) {\n this.key = key\n this.data.push(value)\n this.height = 1\n return this\n }\n\n // Insert new leaf at the right place\n while (true) {\n // Same key: no change in the tree structure\n if (currentNode.compareKeys(currentNode.key, key) === 0) {\n if (currentNode.unique) {\n const err = new Error(`Can't insert key ${key}, it violates the unique constraint`)\n err.key = key\n err.errorType = 'uniqueViolated'\n throw err\n } else currentNode.data.push(value)\n return this\n }\n\n insertPath.push(currentNode)\n\n if (currentNode.compareKeys(key, currentNode.key) < 0) {\n if (!currentNode.left) {\n insertPath.push(currentNode.createLeftChild({ key: key, value: value }))\n break\n } else currentNode = currentNode.left\n } else {\n if (!currentNode.right) {\n insertPath.push(currentNode.createRightChild({ key: key, value: value }))\n break\n } else currentNode = currentNode.right\n }\n }\n\n return this.rebalanceAlongPath(insertPath)\n }", "insert(key, value) {\n if (this.key == null) {\n this.key = key;\n this.value = value;\n // If tree already exists, start at the root, and compare it to the key you want to insert.\n } else if (key < this.key) {\n // If the existing node does not have a left child (`left` pointer is empty), then instantiate and insert the new node as the left child of that node, passing `this` as the parent\n if (this.left == null) {\n this.left = new BinarySearchTree(key, value, this);\n // If the node has an existing left child, recursively call the `insert` method so the node is added further down the tree\n } else {\n this.left.insert(key, value);\n }\n // if the new key is greater than the node's key, recursively call the `insert` method so the node is added further down the tree, but on the right-hand side\n } else {\n this.right.insert(key, value);\n }\n }", "remove(key) {\n if (this.key == key) {\n if (this.left && this.right) {\n const successor = this.right._findMin()\n this.key = successor.key; \n this.value = successor.key; \n successor.remove(successor.key)\n }\n //if node only has a left child => you'd replace the node with its left child\n else if (this.left) {\n this.replaceWith(this.left);\n }\n //if node only has right child => you'd replce the node with its right child \n else if (this.right) {\n this.replaceWith(this.right);\n }\n //if node has no children => remove it & any references to it by calling replaceWith(null)\n else {\n this._replaceWith(null);\n }\n }\n else if (key < this.key && this.left) {\n this.left.remove(key);\n }\n else if (key > this.key && this.right) {\n this.right.remove(key);\n }\n else {\n throw new Error('Key Error')\n }\n }", "put(key, val) {\r\n this.root = this.putHelper(\r\n this.root,\r\n key,\r\n val,\r\n this.rootX,\r\n this.rootY,\r\n this.rootDeltaX,\r\n this.rootDeltaY\r\n );\r\n }", "_insert(node, value) {\n if (node === null) {\n return new Node(value, null, null);\n }\n\n // Passing to childnodes and update\n var side = ~~(value > node.value);\n node.children[side] = this._insert(node.children[side], value);\n\n // Keep it balance\n if (node.children[side].key < node.key) {\n return node.rotate(side);\n }\n return node.resize();\n }", "set(key, value) {\n if (!this.rootKey) {\n this.rootKey = key;\n this.rootValue = value;\n this.preReference = new SortedTreeMap(this.comparisonMethod, this);\n this.postReference = new SortedTreeMap(this.comparisonMethod, this);\n return value;\n }\n\n const comparisonResult = this.comparisonMethod(this.rootKey, key);\n if (comparisonResult < 0) {\n return this.preReference.set(key, value);\n } else if (comparisonResult > 0) {\n return this.postReference.set(key, value);\n } else {\n const result = this.rootValue;\n this.rootValue = value;\n return result;\n }\n }", "function set (p, key, value) {\n let n, r\n if (p !== null && p.branch === 0) { // found\n n = p.node\n r = Node (key, value, n.level, n.l, n.r)\n p = p.parent }\n else\n r = Node (key, value, 1, EMPTY, EMPTY)\n while (p !== null) {\n n = p.node\n r = (p.branch === RIGHT)\n ? Node (n.key, n.value, n.level, n.l, r)\n : Node (n.key, n.value, n.level, r, n.r)\n r = split (skew (r))\n p = p.parent }\n return r }", "insert(value) {\n // Write your code here.\n // Do not edit the return statement of this method.\n let current = this;\n while (true) {\n if (value < current.value) {\n if (current.left === null) {\n current.left = new BST(value)\n break;\n } else {\n current = current.left\n }\n } else {\n if (current.right === null) {\n current.right = new BST(value)\n break;\n } else {\n current = current.right\n }\n }\n }\n return this;\n }", "add(key, value) {\n let newNode = new TreeNode(key, value);\n\n if (this.root === null) {\n this.root = newNode;\n } else {\n this.insertNode(this.root, newNode);\n }\n }", "insert(value){\n // if value is already in tree I won't add it, another option\n // can be keeping a frequency property for each node and increamenting\n // the value for every repeat\n\n let newNode = new Node(value);\n\n if(!this.root){\n this.root = newNode;\n return this;\n }\n\n let current = this.root;\n while(true){\n if(value === current.value) return undefined;\n if(value < current.value){ //go left\n if(!current.left){\n current.left = newNode;\n return this;\n }\n current = current.left;\n }else{ // go right\n if(!current.right){\n current.right = newNode;\n return this;\n }\n current = current.right;\n }\n }\n }", "constructor(key, value) {\n this.key = key;\n this.value = value;\n this.left = null;\n this.right = null;\n this.height = 0;\n }", "_replaceWith(node) {\n if (this.parent) {\n if (this == this.parent.left) {\n this.parent.left = node;\n } else if (this == this.parent.right) {\n this.parent.right = node;\n }\n\n if (node) {\n node.parent = this.parent;\n }\n } else {\n if (node) {\n this.key = node.key;\n this.value = node.value;\n this.left = node.left;\n this.right = node.right;\n } else {\n this.key = null;\n this.value = null;\n this.left = null;\n this.right = null;\n }\n }\n }", "insert(value) {\n this.count++;\n let newNode = new Node(value)\n const searchTree = (node) => {\n // if value < node.value, go left\n if (value < node.value) {\n // if no left child, append new node\n if (!node.left) {\n node.left = newNode; \n // if left child, look left again\n } else {\n searchTree(node.left);\n }\n }\n // if value > node.value, go right\n if (value > node.value ) {\n // if no right child, append new node\n if (!node.right) {\n node.right = newNode;\n // if right child, look right again\n } else {\n searchTree(node.right);\n }\n }\n }\n searchTree(this.root);\n }", "map(callback) {\n const tree = new IntervalTree();\n this.tree_walk(this.root, (node) => tree.insert(node.item.key, callback(node.item.value, node.item.key)));\n return tree;\n }", "constructor(root) {\n this.key = root;\n this.leftChild = null;\n this.rightChild = null;\n }", "insertAfter(key, value) {\n if(this.head === null) {\n this.head = new _Node(value, this.head)\n }\n let currNode = this.head\n while(currNode !== null & currNode.value !== key) {\n currNode = currNode.next\n }\n currNode.next = new _Node(value, currNode.next)\n }", "insert(value) {\n let swapCompleted = false;\n const newNode = new BinarySearchTree(value);\n let root = this;\n \n while (!swapCompleted) {\n if (root.value >= value) {\n if (!root.left) {\n root.left = newNode;\n swapCompleted = true;\n }\n root = root.left;\n } else {\n if (!root.right) {\n root.right = newNode;\n swapCompleted = true;\n }\n root = root.right;\n } \n }\n return newNode; \n }", "insert(value) {\n const node = new BinarySearchTree(value);// create the new node\n // console.log(node);\n let current = this; // root node\n // console.log(current);\n let parent;\n while (true) { // keep looping over the tree until we find an empty tree that fits and call break\n // handle node value is less than current value\n parent = current;\n if (value < current.value) {\n current = current.left; // focus on left node\n if (current == null) { // node is empty, insert new node\n parent.left = node;\n break;\n }\n } else { // we focus on the right node for this iteration\n current = current.right; // move focus onto child right node\n if (current == null) {\n parent.right = node;\n break;\n }\n }\n }\n }", "function selection_data(value, key) {\n if (!value) {\n var data = new Array(this.size()), i = -1;\n this.each(function(d) { data[++i] = d; });\n return data;\n }\n\n var depth = this._depth - 1,\n stack = new Array(depth * 2),\n bind = key ? bindKey : bindIndex;\n\n if (typeof value !== \"function\") value = valueOf_(value);\n visit(this._root, this.enter()._root, this.exit()._root, depth);\n\n function visit(update, enter, exit, depth) {\n var i = -1,\n n,\n node;\n\n if (depth--) {\n var stack0 = depth * 2,\n stack1 = stack0 + 1;\n\n n = update.length;\n\n while (++i < n) {\n if (node = update[i]) {\n stack[stack0] = node._parent.__data__, stack[stack1] = i;\n visit(node, enter[i], exit[i], depth);\n }\n }\n }\n\n else {\n var j = 0,\n before;\n\n bind(update, enter, exit, value.apply(update._parent, stack));\n n = update.length;\n\n // Now connect the enter nodes to their following update node, such that\n // appendChild can insert the materialized enter node before this node,\n // rather than at the end of the parent node.\n while (++i < n) {\n if (before = enter[i]) {\n if (i >= j) j = i + 1;\n while (!(node = update[j]) && ++j < n);\n before._next = node || null;\n }\n }\n }\n }\n\n function bindIndex(update, enter, exit, data) {\n var i = 0,\n node,\n nodeLength = update.length,\n dataLength = data.length,\n minLength = Math.min(nodeLength, dataLength);\n\n // Clear the enter and exit arrays, and then initialize to the new length.\n enter.length = 0, enter.length = dataLength;\n exit.length = 0, exit.length = nodeLength;\n\n for (; i < minLength; ++i) {\n if (node = update[i]) {\n node.__data__ = data[i];\n } else {\n enter[i] = new EnterNode(update._parent, data[i]);\n }\n }\n\n // Note: we don’t need to delete update[i] here because this loop only\n // runs when the data length is greater than the node length.\n for (; i < dataLength; ++i) {\n enter[i] = new EnterNode(update._parent, data[i]);\n }\n\n // Note: and, we don’t need to delete update[i] here because immediately\n // following this loop we set the update length to data length.\n for (; i < nodeLength; ++i) {\n if (node = update[i]) {\n exit[i] = update[i];\n }\n }\n\n update.length = dataLength;\n }\n\n function bindKey(update, enter, exit, data) {\n var i,\n node,\n dataLength = data.length,\n nodeLength = update.length,\n nodeByKeyValue = {},\n keyStack = new Array(2).concat(stack),\n keyValues = new Array(nodeLength),\n keyValue;\n\n // Clear the enter and exit arrays, and then initialize to the new length.\n enter.length = 0, enter.length = dataLength;\n exit.length = 0, exit.length = nodeLength;\n\n // Compute the keys for each node.\n for (i = 0; i < nodeLength; ++i) {\n if (node = update[i]) {\n keyStack[0] = node.__data__, keyStack[1] = i;\n keyValues[i] = keyValue = keyPrefix + key.apply(node, keyStack);\n\n // Is this a duplicate of a key we’ve previously seen?\n // If so, this node is moved to the exit selection.\n if (nodeByKeyValue[keyValue]) {\n exit[i] = node;\n }\n\n // Otherwise, record the mapping from key to node.\n else {\n nodeByKeyValue[keyValue] = node;\n }\n }\n }\n\n // Now clear the update array and initialize to the new length.\n update.length = 0, update.length = dataLength;\n\n // Compute the keys for each datum.\n for (i = 0; i < dataLength; ++i) {\n keyStack[0] = data[i], keyStack[1] = i;\n keyValue = keyPrefix + key.apply(update._parent, keyStack);\n\n // Is there a node associated with this key?\n // If not, this datum is added to the enter selection.\n if (!(node = nodeByKeyValue[keyValue])) {\n enter[i] = new EnterNode(update._parent, data[i]);\n }\n\n // Did we already bind a node using this key? (Or is a duplicate?)\n // If unique, the node and datum are joined in the update selection.\n // Otherwise, the datum is ignored, neither entering nor exiting.\n else if (node !== true) {\n update[i] = node;\n node.__data__ = data[i];\n }\n\n // Record that we consumed this key, either to enter or update.\n nodeByKeyValue[keyValue] = true;\n }\n\n // Take any remaining nodes that were not bound to data,\n // and place them in the exit selection.\n for (i = 0; i < nodeLength; ++i) {\n if ((node = nodeByKeyValue[keyValues[i]]) !== true) {\n exit[i] = node;\n }\n }\n }\n\n return this;\n }", "mergeToLeft(leftNode, rightNode) {\n if (!rightNode.empty()) {\n let leftNodeLastRightChildOldValue = leftNode.last().rightChild;\n leftNode.last().rightChild = rightNode.getLeftmostChild();\n this.addAtLastIndexOfCallStack(\n () => {\n leftNode.last().rightChild = leftNodeLastRightChildOldValue;\n }\n )\n if (leftNode.hasRightmostChild()) {\n let leftNodeLastRightChildParentOldValue = leftNode.last().rightChild.parent;\n leftNode.last().rightChild.parent = leftNode;\n this.addAtLastIndexOfCallStack(\n () => {\n leftNode.last().rightChild.parent = leftNodeLastRightChildParentOldValue;\n }\n );\n }\n while (!rightNode.empty()) {\n let rightNodeElement = rightNode.popFirst();\n this.addAtLastIndexOfCallStack(\n this.undoPopFirst.bind(this, rightNodeElement, rightNode)\n );\n leftNode.addLast(rightNodeElement);\n this.addAtLastIndexOfCallStack(\n this.undoAddLast.bind(this, leftNode)\n )\n if (leftNode.last().leftChild != null) {\n let leftNodeLastLeftChildParentOldValue = leftNode.last().leftChild.parent;\n leftNode.last().leftChild.parent = leftNode;\n this.addAtLastIndexOfCallStack(\n () => {\n leftNode.last().leftChild.parent = leftNodeLastLeftChildParentOldValue;\n }\n )\n }\n if (leftNode.last().rightChild != null) {\n let leftNodeLastRightChildParentOldValue = leftNode.last().rightChild.parent;\n leftNode.last().rightChild.parent = leftNode;\n this.addAtLastIndexOfCallStack(\n () => {\n leftNode.last().rightChild.parent = leftNodeLastRightChildParentOldValue\n }\n );\n }\n }\n }\n\n let rightNodeParentOldValue = rightNode.parent;\n rightNode.parent = null;\n this.addAtLastIndexOfCallStack(\n () => {\n rightNode.parent = rightNodeParentOldValue;\n }\n );\n\n let rightNodeOldValue = rightNode;\n rightNode = null;\n this.addAtLastIndexOfCallStack(\n () => {\n rightNode = rightNodeOldValue;\n }\n );\n }", "insert(value) {\n let currentNode = this;\n while (true) {\n if (value < currentNode.value) {\n if (currentNode.left === null) {\n currentNode.left = new BST(value);\n break;\n } else {\n currentNode = currentNode.left;\n }\n } else {\n if (currentNode.right === null) {\n currentNode.right = new BST(value);\n break;\n } else {\n currentNode = currentNode.right;\n }\n }\n }\n return this;\n }", "set(key: K, val: V) {\n this.tree.remove([key, null]);\n this.tree.insert([key, val]);\n }", "insert(value) { // delegate behaviors to the child trees\n // const nextTree = new BinarySearchTree(value);\n // console.log(this); // this === parent\n // console.log(nextTree); // nexxtTree === child\n // console.log(value); // the value we want to insert into the tree (make a new node with)\n\n if (value < this.value) {\n // is there a left\n if (this.left) { // the left node exists\n this.left.insert(value); // insert the value as the child of the this.left\n } else {\n this.left = new BinarySearchTree(value);\n }\n // this.left.insert(value);\n } else if (value > this.value) {\n if (this.right) {\n this.right.insert(value);\n } else {\n this.right = new BinarySearchTree(value);\n }\n }\n }", "function initNode(key) {\n var n = {};\n n.key = key;\n n.color = \"Black\";\n n.left = null;\n n.right = null;\n n.p = null;\n return n;\n}", "buildTree() {\n\t\tthis.assignLevel(this.nodesList[0], 0);\n\t\tthis.positionMap = new Map();\n\t\tthis.assignPosition(this.nodesList[0], 0);\n\t}", "insert(val) {\n // if there is no root values in the tree we should isnert one \n if(this.root === null){\n // create a new node\n this.root = new Node(val);\n // return the tree (which is what this is referring to)\n return this;\n }\n // if it has values then we should find a spot for it on the tree\n // very similar to searching for a value \n // have our current Node available if there is one\n let currentNode = this.root;\n // should run until the value is placed and the return statements will break us out of the loop\n while(true){\n // if the value of our current node is less than the value that we want to insert it will go to the right \n if(currentNode.val < val){\n // if there is no right value existing then we can create a new node to be the right value of the current node\n if(currentNode.right === null){\n currentNode.right = new Node(val);\n // we return the tree\n return this;\n // otherwise we have to traverse to the existing right node and then we check it again because the while loop wont break unless the value is inserted\n } else{\n currentNode = currentNode.right;\n }\n // this is the inverse where we insert values to the left\n } else if(currentNode.val > val){\n // if there is no left valye\n if(currentNode.left === null){\n // create a new node at the left valye\n currentNode.left = new Node(val);\n // return the tree\n return this;\n // otherwise we traverse to that node and the loop starts again \n } else{\n currentNode = currentNode.left;\n }\n }\n\n }\n }", "insertNewNode(root, node){\n /*\n ** [6, 53, 5, 3, 50]\n ** -> root = 6. -> insertNewNode(6, 53) -> { \n root: { \n data: 6, \n left: null, \n right: { \n data: 53, \n left: null, \n right: null \n } \n }\n } (1st Iteration)\n ** -> root = 6 -> insertNewNode(6, 5) -> {\n root: {\n data: 6,\n left: {\n data: 5,\n left: null,\n right: null\n },\n right: { \n data: 53, \n left: null, \n right: null \n } \n }\n } (2nd Iteration)\n ** -> root = 6 -> insertNewNode(6, 3) -> duplicate left node -> insertNewNode(5, 3) -> {\n root: {\n data: 6,\n left: { \n data: 5, \n left: { \n data: 5, \n left: { data: 3, left: null, right: null }, \n right: null \n }\n },\n right:{\n data: 53,\n left: null,\n right: null\n }\n }\n } (3rd Iteration)\n ** -> root = 6, insertNewNode(6, 50) -> duplicate right node -> \n insertNewNode(53, 50) -> insert into left position since 50 is less than of the root at the current level. -> {\n root: {\n data: 6,\n left: {\n data: 5,\n left: {\n data: 3,\n left: null, \n right: null\n }\n right:null\n },\n right: {\n data: 53,\n left: {\n data: 50,\n left: null,\n right: null\n },\n right: null\n } \n }\n }\\(4th iteration)\n */\n if(node.data < root.data) {\n if(!root.left) return root.left = node;\n return this.insertNewNode(root.left, node);\n }\n\n if(root.data < node.data) {\n if(!root.right) return root.right = node;\n return this.insertNewNode(root.right, node);\n }\n }", "function postorder(node){\n if(!_.isNull(node.left)) postorder(node.left)\n if(!_.isNull(node.right)) postorder(node.right)\n trav.push({\"key\": node.key, \"value\": node.value, \"children\": [_.get(node, \"left.value\", \"null\"), _.get(node, \"right.value\", \"null\")]})\n}", "insert(value) {\n if (value < this.value) {\n if (this.left === null) {\n this.left = new BinarySearchTree(value);\n } else {\n this.left.insert(value);\n }\n } else if (value > this.value) {\n if (this.right === null) {\n this.right = new BinarySearchTree(value);\n } else {\n this.right.insert(value);\n }\n }\n }", "push(node, process_node = this.numeric_ordinal) { // makes a BST by default\n if(process_node(node.val, this.val) && !this.right){\n this.right = node;\n return this;\n }\n if(!process_node(node.val, this.val) && !this.left){\n this.left = node;\n return this;\n }\n //if(process_node(node.val, this.val)) {\n // return this.push(node, process_node);\n //} else {\n this.push(node, process_node);\n //return this;\n //}\n }", "insert (key, value) {\n // Empty tree, insert as root\n if (!Object.prototype.hasOwnProperty.call(this, 'key')) {\n this.key = key\n this.data.push(value)\n return\n }\n\n // Same key as root\n if (this.compareKeys(this.key, key) === 0) {\n if (this.unique) {\n const err = new Error(`Can't insert key ${key}, it violates the unique constraint`)\n err.key = key\n err.errorType = 'uniqueViolated'\n throw err\n } else this.data.push(value)\n return\n }\n\n if (this.compareKeys(key, this.key) < 0) {\n // Insert in left subtree\n if (this.left) this.left.insert(key, value)\n else this.createLeftChild({ key: key, value: value })\n } else {\n // Insert in right subtree\n if (this.right) this.right.insert(key, value)\n else this.createRightChild({ key: key, value: value })\n }\n }", "insert(value) {\n // Create a new node with the value passed\n let newNode = new Node(value);\n // Check edge case (if tree is empty)\n if (!this.root) {\n this.root = newNode;\n } else {\n // If edge case is not true, first set a current value, we always start with the node\n let previous = this.root;\n // We can set any statement here to loop that is true, I used while previous is true which is always true, we will break out of looping with the break keyword\n while (previous) {\n // If the value of the new node is less than the current node, then we either traverse down the left of the list, or we set the .left of the node to the new node. We do the second case if and only if the .left property is null. We cannot trasverse directly until we hit null because then we will end up just setting null to the node instead of appending to the list\n if ((value = previous.value)) return;\n if (newNode.value < previous.value) {\n if (!previous.left) {\n previous.left = newNode;\n break;\n } else {\n previous = previous.left;\n }\n } else {\n // Likewise for the explanation above, this is the same\n if (!previous.right) {\n previous.right = newNode;\n break;\n } else {\n previous = previous.right;\n }\n }\n }\n }\n // Finally return the binary search tree\n return this;\n }", "function preorder(node){\n trav.push({\"key\": node.key, \"value\": node.value, \"children\": [_.get(node, \"left.value\", \"null\"), _.get(node, \"right.value\", \"null\")]})\n if(!_.isNull(node.left)) preorder(node.left)\n if(!_.isNull(node.right)) preorder(node.right)\n}", "mergeToRight(leftNode, rightNode) {\n if (!leftNode.empty()) {\n\n let rightNodeFirstLeftChildOldValue = rightNode.first().leftChild;\n rightNode.first().leftChild = leftNode.getRightmostChild();\n this.addAtLastIndexOfCallStack(\n () => {\n rightNode.first().leftChild = rightNodeFirstLeftChildOldValue;\n }\n );\n\n if (rightNode.hasLeftmostChild()) {\n let rightNodeFirstLeftChildParentOldValue = rightNode.first().leftChild.parent;\n rightNode.first().leftChild.parent = rightNode;\n this.addAtLastIndexOfCallStack(\n () => {\n rightNode.first().leftChild.parent = rightNodeFirstLeftChildParentOldValue;\n }\n );\n }\n while (!leftNode.empty()) {\n let leftNodeElement = leftNode.popLast();\n this.addAtLastIndexOfCallStack(\n this.undoPopLast.bind(this, leftNodeElement, leftNode)\n );\n\n rightNode.addFirst(leftNodeElement);\n this.addAtLastIndexOfCallStack(\n this.undoAddFirst.bind(this, rightNode)\n );\n\n if (rightNode.first().leftChild !== null) {\n let rightNodeFirstLeftChildParentOldValue = rightNode.first().leftChild.parent;\n rightNode.first().leftChild.parent = rightNode;\n this.addAtLastIndexOfCallStack(\n () => {\n rightNode.first().leftChild.parent = rightNodeFirstLeftChildParentOldValue;\n }\n );\n }\n if (rightNode.first().rightChild !== null) {\n let rightNodeFirstRightChildParentOldValue = rightNode.first().rightChild.parent;\n rightNode.first().rightChild.parent = rightNode;\n this.addAtLastIndexOfCallStack(\n () => {\n rightNode.first().rightChild.parent = rightNodeFirstRightChildParentOldValue;\n }\n );\n }\n }\n }\n\n let leftNodeParentOldValue = leftNode.parent;\n leftNode.parent = null;\n this.addAtLastIndexOfCallStack(\n () => {\n leftNode.parent = leftNodeParentOldValue;\n }\n )\n\n let leftNodeOldValue = leftNode;\n leftNode = null;\n this.addAtLastIndexOfCallStack(\n () => {\n leftNode = leftNodeOldValue;\n }\n );\n\n }", "function inorder(node){\n if(!_.isNull(node.left)) inorder(node.left)\n trav.push({\"key\": node.key, \"value\": node.value, \"children\": [_.get(node, \"left.value\", \"null\"), _.get(node, \"right.value\", \"null\")]})\n if(!_.isNull(node.right)) inorder(node.right)\n}", "function BST(){\n\t\t//Default Properties\n\t\tthis.root = null;\n\t\tthis.tree = null;\n\n\t\t/************************************\n\t\t\t\tPrivate functions\n\t\t************************************/\n\t\tvar inOrder= function(obj, callback){\n\t if (obj){\n\n\t if (obj.left !== null){\n\t inOrder(obj.leftchild, callback);\n\t } \n\n\t callback.call(this,obj.element);\n\n\t if (obj.right !== null){\n\t inOrder(obj.rightchild, callback);\n\t }\n\t }\n\t }\n\n\t var preOrder = function(obj, callback){\n\t if (obj){\n\n\t \tcallback.call(this,obj.element);\n\n\t if (obj.left !== null){\n\t preOrder(obj.leftchild, callback);\n\t } \n\n\t if (obj.right !== null){\n\t preOrder(obj.rightchild, callback);\n\t }\n\t }\n\t }\n\n\t var postOrder = function(obj, callback){\n\t if (obj){\n\n\t if (obj.left !== null){\n\t postOrder(obj.leftchild, callback);\n\t } \n\n\t if (obj.right !== null){\n\t postOrder(obj.rightchild, callback);\n\t }\n\n\t callback.call(this,obj.element);\n\n\t }\n\t }\n\n\t /************************************\n\t\t\t\tExposed Functions\n\t\t************************************/\n\n\t\t//Add a new element\n\t\tthis.add = function(x){\n\t\t\tvar flag = true,\n\t\t\t\tdata = this.tree;\n\n\t\t\tif(this.root === null){\n\t\t\t\tthis.tree = {\n\t\t\t\t\telement : x,\n\t\t\t\t\tleftchild : null,\n\t\t\t\t\trightchild : null\n\t\t\t\t};\n\t\t\t\tthis.root = x;\n\t\t\t\tflag = false;\n\t\t\t}else{\n\t\t\t\twhile(flag){\n\t\t\t\t\tif(data.element === x){\n\t\t\t\t\t\treturn false;\n\t\t\t\t\t}else if(x > data.element){\n\t\t\t\t\t\tif(data.rightchild === null){\n\t\t\t\t\t\t\tdata.rightchild = {\n\t\t\t\t\t\t\t\telement : x,\n\t\t\t\t\t\t\t\tleftchild : null,\n\t\t\t\t\t\t\t\trightchild : null\t\t\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\tflag = false;\n\t\t\t\t\t\t}else{\n\t\t\t\t\t\t\tdata = data.rightchild;\n\t\t\t\t\t\t}\n\t\t\t\t\t\t\n\t\t\t\t\t}else if(x < data.element){\n\t\t\t\t\t\tif(data.leftchild === null){\n\t\t\t\t\t\t\tdata.leftchild = {\n\t\t\t\t\t\t\t\telement : x,\n\t\t\t\t\t\t\t\tleftchild : null,\n\t\t\t\t\t\t\t\trightchild : null\t\t\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\tflag = false;\n\t\t\t\t\t\t}else{\n\t\t\t\t\t\t\tdata = data.leftchild;\n\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}\n\t\t\t\t\n\t\t\t}\n\t\t};\n\t\t//Find whether element exist in exisiting BST\n\t\tthis.contains = function(x){\n\t\t\tvar flag = true,\n\t\t\t\tnode = this.tree;\n\n\t\t\twhile(flag){\n\t\t\t\tif(node != null){\n\t\t\t\t\tif(x === node.element){\n\t\t\t\t\t\tflag = false;\n\t\t\t\t\t\treturn true;\n\t\t\t\t\t}else if(x > node.element){\n\t\t\t\t\t\tnode = node.rightchildchild;\n\t\t\t\t\t}else if(x < node.element){\n\t\t\t\t\t\tnode = node.leftchildchild;\n\t\t\t\t\t}\t\n\t\t\t\t}else{\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t}\n\t\t};\n\t\t//Find element in BST with minimum value\n\t\tthis.minValue = function(){\n\t\t\tvar flag = true,\n\t\t\t\tnode = this.tree;\n\n\t\t\t\tif(node != null){\n\t\t\t\t\twhile(flag){\n\t\t\t\t\t\tif(node.leftchildchild){\n\t\t\t\t\t\t\tnode = node.leftchildchild;\n\t\t\t\t\t\t}else{\n\t\t\t\t\t\t\tflag = false;\n\t\t\t\t\t\t\treturn node.element;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}else{\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t};\n\t\t//Find element in BST with maximum value\n\t\tthis.maxValue = function(){\n\t\t\tvar flag = true,\n\t\t\t\tnode = this.tree;\n\n\t\t\t\tif(node != null){\n\t\t\t\t\twhile(flag){\n\t\t\t\t\t\tif(node.rightchildchild){\n\t\t\t\t\t\t\tnode = node.rightchildchild;\n\t\t\t\t\t\t}else{\n\t\t\t\t\t\t\tflag = false;\n\t\t\t\t\t\t\treturn node.element;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}else{\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t};\n\t\t//Delete whole BST \n\t\tthis.removeTree = function(){\n\t\t\tthis.root = null;\n\t\t\tthis.tree = null;\n\t\t};\n\t\t//Traverse BST tree, you can traverse BST in inOrder,preOrder & postOrder fashion.\n\t\tthis.traversalTree = function(options,callback){\n\t\t\tvar obj = this.tree;\n\n\t\t\t//inOrder traversal\n\t\t\tif(options.type === \"inorder\"){\n\t\t inOrder(obj,callback);\n\t\t\t}\n\t\t\t//preOrder traversal\n\t\t\tif(options.type === \"preorder\"){\n\t\t preOrder(obj, callback);\n\t\t\t}\n\t\t\t//postOrder traversal\n\t\t\tif(options.type === \"postorder\"){\n\t\t postOrder(obj, callback);\n\t\t\t}\n\t\t};\n\t\t//Get BST size \n\t\tthis.size = function(){\n\t\t\tvar obj = this.tree,\n\t\t\t\tsize = 0;\n\t\t\tfunction inOrder(obj){\n\t\t if (obj){\n\n\t\t if (obj.left !== null){\n\t\t inOrder(obj.leftchild);\n\t\t } \n\n\t\t size = size+1;\n\n\t\t if (obj.right !== null){\n\t\t inOrder(obj.rightchild);\n\t\t }\n\t\t }\n\t\t }\n\t inOrder(obj);\n\n\t return size;\n\t\t};\n\t\t//Convert BST tree to Array \n\t\tthis.toArray = function(type){\n\t\t\tvar obj = this.tree,\n\t\t\t\tarr = [],\n\t\t\t\tmethod = \"inorder\";\n\n\t\t\tif(!type){\n\t\t\t\ttype = method;\n\t\t\t}\n\n\t\t\tfunction inOrder(obj){\n\t\t if (obj){\n\n\t\t if (obj.left !== null){\n\t\t inOrder(obj.leftchild);\n\t\t } \n\n\t\t arr.push(obj.element);\n\n\t\t if (obj.right !== null){\n\t\t inOrder(obj.rightchild);\n\t\t }\n\t\t }\n\t\t }\n\t\t function preOrder(obj){\n\t\t if (obj){\n\n\t\t arr.push(obj.element);\n\n\t\t if (obj.left !== null){\n\t\t preOrder(obj.leftchild);\n\t\t } \n\n\t\t if (obj.right !== null){\n\t\t preOrder(obj.rightchild);\n\t\t }\n\t\t }\n\t\t }\n\t\t function postOrder(obj){\n\t\t if (obj){\n\n\t\t if (obj.left !== null){\n\t\t postOrder(obj.leftchild);\n\t\t } \n\n\t\t \n\n\t\t if (obj.right !== null){\n\t\t postOrder(obj.rightchild);\n\t\t }\n\n\t\t arr.push(obj.element);\n\n\t\t }\n\t\t }\n\n\t\t if(type === \"inorder\"){\n\t \tinOrder(obj);\t\n\t\t\t}else if(type === \"preorder\"){\n\t\t\t\tpreOrder(obj);\n\t\t\t}else if(type === \"postorder\"){\n\t\t\t\tpostOrder(obj);\n\t\t\t}\n\t return arr;\n\t\t};\n\t\t//Convert BST tree to String\n\t\tthis.toString = function(){\n\t\t\tvar obj = this.tree,\n\t\t\t\tarr = [];\n\t\t\tfunction inOrder(obj){\n\t\t if (obj){\n\n\t\t if (obj.left !== null){\n\t\t inOrder(obj.leftchild);\n\t\t } \n\n\t\t // callback.call(this,obj.element);\n\t\t arr.push(obj.element);\n\n\t\t if (obj.right !== null){\n\t\t inOrder(obj.rightchild);\n\t\t }\n\t\t }\n\t\t }\n\t //start with the root\n\t inOrder(obj);\n\n\t return arr.toString();\n\t\t};\n\t\t//Check maximum Depth in BST\n\t\tthis.maxDepth = function(){\n\t\t\tvar obj = this.tree,\n\t\t\t\tsize = 0,\n\t\t\t\tPathArr = [],\n\t\t\t\ttraverseTopNode = false,\n\t\t\t\troot = this.root;\n\n\t\t\tfunction inOrder(obj){\n\n\t\t if (obj){\n\t\t \tif (obj.leftchild !== null){\n\t\t \t\tsize = size+1;\n\t\t inOrder(obj.leftchild);\n\t\t }else{\n\t\t \tPathArr.push(size);\n\t\t } \n\n\t\t if(obj.element === root){\n\t\t \t\ttraverseTopNode = true;\n\t\t \t\tsize = 1;\n\t\t \t}\n\t\t if (obj.rightchild !== null){\n\t\t size = size+1;\n\t\t inOrder(obj.rightchild);\n\n\t\t }else{\n\t\t \tPathArr.push(size);\n\t\t \tsize = size -1;\n\t\t }\n\n\t\t }else{\n\t\t \treturn 0;\n\t\t }\n\t\t }\n\n\t //start with the root\n\t inOrder(obj);\n\n\t PathArr.sort();\n\t PathArr.reverse();\n\t return PathArr[0];\n\t\t};\n\t\t//Remove element in BST\n\t\tthis.remove = function(value){\n\t \n\t var found = false,\n\t parent = null,\n\t node = this.tree,\n\t childCount,\n\t replacement,\n\t replacementParent;\n\t \n\t //make sure there's a node to search\n\t while(!found && node){\n\t \n\t //if the value is less than the node node's, go left\n\t if (value < node.element){\n\t parent = node;\n\t node = node.leftchild;\n\t \n\t //if the value is greater than the node node's, go right\n\t } else if (value > node.element){\n\t parent = node;\n\t node = node.rightchild;\n\t \n\t //values are equal, found it!\n\t } else {\n\t found = true;\n\t }\n\t }\n\t \n\t //only proceed if the node was found\n\t if (found){\n\t \n\t //figure out how many children\n\t childCount = (node.leftchild !== null ? 1 : 0) + (node.rightchild !== null ? 1 : 0);\n\t \n\t //special case: the value is at the root\n\t if (node === this.tree){\n\t switch(childCount){\n\t \n\t //no children, just erase the root\n\t case 0:\n\t this.tree = null;\n\t this.root = null;\n\t break;\n\t \n\t //one child, use one as the root\n\t case 1:\n\t this.tree = (node.rightchild === null ? node.leftchild : node.rightchild);\n\t break;\n\t \n\t //two children, little work to do\n\t case 2:\n\n\t //new root will be the old root's left child...maybe\n\t replacement = this.tree.leftchild;\n\t \n\t //find the right-most leaf node to be the real new root\n\t while (replacement.rightchild !== null){\n\t replacementParent = replacement;\n\t replacement = replacement.rightchild;\n\t }\n\t \n\t //it's not the first node on the left\n\t if (replacementParent !== null){\n\t \n\t //remove the new root from it's previous position\n\t replacementParent.rightchild = replacement.leftchild;\n\t \n\t //give the new root all of the old root's children\n\t replacement.rightchild = this.tree.rightchild;\n\t replacement.leftchild = this.tree.leftchild;\n\t } else {\n\t \n\t //just assign the children\n\t replacement.rightchild = this.tree.rightchild;\n\t }\n\t \n\t //officially assign new root\n\t this.tree = replacement;\n\t this.root = replacement.element;\n\t \n\t //no default\n\t \n\t } \n\n\t //non-root values\n\t } else {\n\t \n\t switch (childCount){\n\t \n\t //no children, just remove it from the parent\n\t case 0:\n\t //if the node value is less than its parent's, null out the left pointer\n\t if (node.element < parent.element){\n\t parent.leftchild = null;\n\t \n\t //if the node value is greater than its parent's, null out the right pointer\n\t } else {\n\t parent.rightchild = null;\n\t }\n\t break;\n\t \n\t //one child, just reassign to parent\n\t case 1:\n\t //if the node value is less than its parent's, reset the left pointer\n\t if (node.element < parent.element){\n\t parent.leftchild = (node.leftchild === null ? node.rightchild : node.leftchild);\n\t \n\t //if the node value is greater than its parent's, reset the right pointer\n\t } else {\n\t parent.rightchild = (node.leftchild === null ? node.rightchild : node.leftchild);\n\t }\n\t break; \n\n\t //two children, a bit more complicated\n\t case 2:\n\t \n\t //reset pointers for new traversal\n\t replacement = node.leftchild;\n\t replacementParent = node;\n\t \n\t //find the right-most node\n\t while(replacement.rightchild !== null){\n\t replacementParent = replacement;\n\t replacement = replacement.rightchild; \n\t }\n\t \n\t if (replacementParent.rightchild === replacement) {\n\t replacementParent.rightchild = replacement.leftchild;\n\t } else { \n\t //replacement will be on the left when the left most subtree\n\t //of the node to remove has no children to the right\n\t replacementParent.leftchild = replacement.leftchild;\n\t }\n\t \n\t //assign children to the replacement\n\t replacement.rightchild = node.rightchild;\n\t replacement.leftchild = node.leftchild;\n\t \n\t //place the replacement in the right spot\n\t if (node.element < parent.element){\n\t parent.leftchild = replacement;\n\t } else {\n\t parent.rightchild = replacement;\n\t } \n\t }\n\t \n\t }\n\t \n\t }else{\n\t \treturn false;\n\t } \n\t }\n\t}", "animateGet(key) {\r\n const animations = [];\r\n animations.push(new Animation(\"display\", `Getting ${key}`, \"'\"));\r\n\r\n const node = this.animateGetHelper(this.root, key, animations);\r\n\r\n // highlight last node in red if not found\r\n if (node === null) {\r\n animations[animations.length - 1].setClass(\"search-failed-node\");\r\n animations.push(new Animation(\"display\", \"Not Found\", \"'\"));\r\n }\r\n // highlight last node in green if found\r\n else if (compareTo(key, node.key) === 0) {\r\n animations[animations.length - 1].setClass(\"found-node\");\r\n animations.push(new Animation(\"display\", node.value, \"'\"));\r\n }\r\n\r\n return [node, animations];\r\n }", "function TNodes_doPasteBranchFromJson(myjson,target,action){ \n // check to deny the action\n if (target.HasChild==true){\n return false; \n }\n\n action=action||'append';\n var data = {};\n var nodeAttr=new TComAttr();\n var boxnodeAttr=new TComAttr();\n var cAttr=new TComContainerAttr();\n /* STICKER_mp var sAttr= new TComStickerAttr(); */\n var myorientation='';\n \n var partcount=0;\n var updata ={};\n var downdata={};\n \n var zeronodeflag=false;\n var firstsplitflag=false;\n var startwithcontainerflag=false;\n \n var mytargetnode={}; // defines the current target for adding the split\n var mytargetnds={}; // obj for the TNodes of the current target, triggers the doADD()\n var mytargetparentid='';\n var builditems=new Array(); // stores the added, new splits with the source-indexes \n var splitindex=0; // keeps track to the buildorder of data.index (AbsoluteIndex of the original structure)\n // is S in CopyBranchToNode()\n var parentsplitindex=0; // means the split-linking in terms of parent and child (skiping the link over node)\n var parentspin=0;\n\n var lastzeronode={};\n\n var containernode={};\n var buildcontainer=new Array();\n var lastcontainer={};\n var lastcontainerindex=0;\n var lastcontainerhasnode=false;\n \n /* STICKER_mp var stickernode={}; \n var buildsticker=new Array();\n var laststicker={};\n var laststickerindex=0;\n var laststickerhasnode=false;\n\n\n // stacks\n var builditemsstack=new Array();\n var mytargetndsstack=new Array();\n \n \n // holds the differences (heigth and width) between source to target \n var dh=0;\n var dw=0;\n \n nodeAttr.action=action;\n \n var firstelement=myjson[0]; // get the element e=0\n\n mytargetnode=target; // defines the target for the first action\n mytargetnds=target.Owner;\n mytargetparentid=target.Parent.Ident;\n \n switch (firstelement.datatype){\n case 'node':\n firstsplitflag=true;\n break;\n case 'container':\n startwithcontainerflag=true;\n case 'command':\n break;\n default: \n }\n \n // sequential process the json-object\n for (var e in myjson){\n \n data=myjson[e];\n \n // distinguish the different element-types\n\n /* **************************************************************\n * control - not a real dataelement\n */\n if (data.datatype=='command'){\n switch (data.todo){\n case 'stackup':\n // nodes-stack one up (TNodes-bifork)\n mytargetndsstack.unshift(mytargetnds); \n \n if (lastzeronode.ZeroNodeType=='container'){\n mytargetnds=lastcontainer.Nodes;\n }\n /* STICKER_mp\n if (lastzeronode.ZeroNodeType=='sticker'){\n mytargetnds=laststicker.Nodes;\n }*/\n \n // builditemsstack one up\n builditemsstack.unshift(builditems);\n builditems=new Array();\n break;\n \n case 'stackdown':\n // nodes-stack one down (TNodes-bifork)\n mytargetnds=mytargetndsstack.shift();\n // builditemsstack one down\n builditems=builditemsstack.shift();\n break;\n }\n }\n \n /* ****************************************************\n * node\n */\n if (data.datatype=='node'){\n \n if (data.align=='fit'){\n zeronodeflag=true;\n }else{\n zeronodeflag=false;\n }\n \n // handle zeronode \n if (partcount==0 && zeronodeflag==true){\n myorientation='n';\n splitindex=0;updata.index;\n parentsplitindex=0;\n parentspin=0;\n \n if (action=='append' || action=='insert'){\n nodeAttr.uid='';\n }else{\n nodeAttr.uid=data.ident;\n } \n \n //mytargetnode=lastcontainer; // defines the target for the first split\n //mytargetparentid=target.Parent.Ident;\n \n if (lastcontainerhasnode){\n //mytargetnode.ContainerList.Item[lastcontainerindex].doAddZeroSplit(lastcontainer.Ident,nodeAttr);\n lastzeronode=lastcontainer.doAddZeroSplit(lastcontainer.Ident,nodeAttr);\n lastcontainerhasnode=false; \n }\n /* STICKER_mp\n if (laststickerhasnode){\n lastzeronode=laststicker.doAddZeroSplit(laststicker.Ident,nodeAttr); \n laststickerhasnode=false;\n }\n */\n }\n \n if (partcount==0 && zeronodeflag==false){\n updata=data;\n }\n \n if (zeronodeflag==false){\n partcount++;\n }\n \n // waits for down node\n if (partcount==2 && zeronodeflag==false){\n \n downdata=data;\n \n // set the splitorientation\n switch(updata.align){\n case 'left': myorientation='v';\n break;\n case 'top': myorientation='h';\n break;\n default: myorientation='n';\n }\n \n splitindex=updata.index;\n parentsplitindex=updata.parentindex; // parent means in terms of s\n parentspin=updata.parentspin; \n \n // for the first split target-parameter)\n // firstsplitflag \n \n /* if (firstsplitflag){\n \n mytargetnode=target; // defines the target for the first split\n mytargetnds=target.Owner;\n mytargetparentid=target.Parent.Ident;\n \n }else{ // targets for the next splits are in builditems \n */\n \n if (firstsplitflag==false){\n \n switch (parentspin){\n case 1: mytargetnode=builditems[parentsplitindex].UpNode;\n mytargetparentid=mytargetnode.Ident;\n break; \n case -1: mytargetnode=builditems[parentsplitindex].DownNode;\n mytargetparentid=mytargetnode.Ident;\n break;\n case 0: mytargetnode=lastcontainer.Nodes.Item[0];\n mytargetparentid=mytargetnode.Ident; \n break;\n default:\n }\n }\n \n // get the differences (heigth and width) between source to target \n if (updata.align=='left'){\n dh=mytargetnode.Height-updata.height;\n dw=mytargetnode.Width-(updata.width+downdata.width);\n \n } else if (updata.align=='top'){\n dh=mytargetnode.Height-(updata.height+downdata.height);\n dw=mytargetnode.Width-updata.width; \n } else {\n dh=mytargetnode.Height-updata.height;\n dw=mytargetnode.Width-updata.width; \n }\n \n \n if (action=='append' || action=='insert'){\n nodeAttr.uid='';\n nodeAttr.did='';\n \n }else{\n nodeAttr.uid=updata.ident;\n nodeAttr.did=downdata.ident;\n \n } \n \n // append -> build split like clicking splitbuttons\n // insert -> take the heights and widths form source \n switch (action){\n case 'append':\n nodeAttr.uh=updata.height;\n nodeAttr.uw=updata.width;\n nodeAttr.dh=downdata.height;\n nodeAttr.dw=downdata.width;\n break;\n case 'insert':\n switch(updata.align){\n case 'left':\n nodeAttr.uh=updata.height+dh; //nodeAttr.uh=updata.height\n nodeAttr.uw=updata.width;\n nodeAttr.dh=downdata.height+dh; //nodeAttr.dh=downdata.height\n nodeAttr.dw=downdata.width+dw; \n break;\n case 'top':\n //if (builditems[cursplitindex].Parent.Spin==1){\n nodeAttr.uh=updata.height\n nodeAttr.uw=updata.width+dw; //nodeAttr.uw=updata.width\n nodeAttr.dh=downdata.height+dh;\n nodeAttr.dw=downdata.width+dw; //nodeAttr.dw=downdata.width \n break;\n default:\n nodeAttr.uh=updata.height;\n nodeAttr.uw=updata.width;\n nodeAttr.dh=downdata.height;\n nodeAttr.dw=downdata.width; \n }\n break;\n case 'relink':\n switch(updata.align){\n case 'left':\n nodeAttr.uh=updata.height+dh; //nodeAttr.uh=updata.height\n nodeAttr.uw=updata.width;\n nodeAttr.dh=downdata.height+dh; //nodeAttr.dh=downdata.height\n nodeAttr.dw=downdata.width+dw; \n break;\n case 'top':\n //if (builditems[cursplitindex].Parent.Spin==1){\n nodeAttr.uh=updata.height\n nodeAttr.uw=updata.width+dw; //nodeAttr.uw=updata.width\n nodeAttr.dh=downdata.height+dh;\n nodeAttr.dw=downdata.width+dw; //nodeAttr.dw=downdata.width \n break;\n default:\n nodeAttr.uh=updata.height;\n nodeAttr.uw=updata.width;\n nodeAttr.dh=downdata.height;\n nodeAttr.dw=downdata.width; \n }\n break;\n default:\n nodeAttr.uh=updata.height;\n nodeAttr.uw=updata.width;\n nodeAttr.dh=downdata.height;\n nodeAttr.dw=downdata.width;\n }\n \n builditems[splitindex]={}; \n builditems[splitindex]=mytargetnds.doAdd(mytargetnode, myorientation, 'split made by id -> ' + mytargetparentid,nodeAttr); \n \n partcount=0;\n firstsplitflag=false; \n \n }//partcount\n \n // show current node-element\n doPrint('pasteobj->' + e + '|type:' + data.datatype \n + '|ident:' + data.ident\n + '|parentindex:' + data.parentindex\n + '|parentspin:' + data.parentspin);\n \n \n }//node\n \n /* ******************************\n * container\n */\n if (data.datatype=='container'){\n \n cAttr.action=action;\n \n if (action=='append' || action=='insert'){\n cAttr.id='';\n \n } else {\n cAttr.Ident=data.ident; \n }\n // SaVe\n cAttr.Height=data.height;\n cAttr.Width=data.width;\n cAttr.Given=data.given;\n cAttr.Kind=data.kind;\n cAttr.Attributes=data.styles;\n cAttr.HasRightScrollbar=data.rightscrollbar;\n cAttr.IsFitToParent=data.fit_height;\n cAttr.Wrap = data.wrap;\n cAttr.Label = data.label;\n cAttr.Html = data.html;\n cAttr.Nature = data.nature;\n cAttr.Options = data.options;\n cAttr.RelatedContainer = data.relatedcontainer;\n\n if (data.buildorder=='container'){\n \n mytargetnode=target; // defines the target for the first split\n mytargetnds=target.Owner;\n mytargetparentid=target.Parent.Ident;\n\n containernode=target;\n \n }\n \n \n else{ \n // targets for the next containers are in builditems \n switch (data.parentspin){\n case 1: containernode=builditems[splitindex].UpNode;\n break;\n case -1: containernode=builditems[splitindex].DownNode;\n break;\n default: containernode=builditems[splitindex].UpNode;\n }\n }\n \n //lastcontainer=containernode.doAddContainer(null,cAttr); \n lastcontainerindex=lastcontainer.AbsoluteIndex;\n \n // startobject is container in a node (no children)\n if (firstsplitflag){\n //mytargetnds=lastcontainer.Nodes;\n firstsplitflag=false; \n }\n \n if (data.nodescount!=undefined){\n lastcontainerhasnode=true;\n }else{\n lastcontainerhasnode=false;\n }\n \n // show current container-element\n doPrint('pasteobj->' + e + '|type:' + data.datatype \n + '|ident:' + data.ident\n + '|parentindex:' + data.parentindex\n + '|parentspin:' + data.parentspin);\n \n }// container\n \n \n }// end PasteBranchFromJson ", "function update(tree, k = 170, b = 26) {\n return {\n __springK: k,\n __springB: b,\n value: tree,\n };\n}", "insert(value) {\n let newNode = new Node(value);\n if (!this.root) {\n return this.root = newNode;\n } else {\n let current = this.root;\n while (current) {\n if (value < current.value) {\n if (!current.left) {\n return current.left = newNode;\n }\n current = current.left;\n } else {\n if (!current.right) {\n return current.right = newNode;\n }\n current = current.right;\n }\n }\n }\n }", "function node(key) {\n var self = this;\n this.key = key;\n this.left = null;\n this.right = null;\n}", "insert(value) {\n const newNode = new Node(value);\n if (this.root === null) {\n this.root = newNode;\n return this;\n }\n let current = this.root;\n while (true) {\n if (value === current.value) return undefined;\n if (value < current.value) {\n if (current.left === null) {\n current.left = newNode;\n return this;\n }\n current = current.left;\n } else {\n if (current.right === null) {\n current.right = newNode;\n return this;\n }\n current = current.right;\n }\n }\n }", "insert(newData) {\n if (newData < this.data && this.left) {\n this.left.insert(newData)\n } else if (newData < this.data) {\n this.left = new BST(newData)\n }\n \n if (newData > this.data && this.right) {\n this.right.insert(newData)\n } else if (newData > this.data) {\n this.right = new BST(newData)\n }\n }", "remove(key) {\n if (this.key == key) {\n if (this.left && this.right) {\n const successor = this.right._findMin();\n this.key = succesor.key;\n this.value = succesor.value;\n successor.remove(successor.key);\n }\n // If node only has a left child, then replace the node with its left child\n else if (this.left) {\n this._replaceWith(this.left);\n } else if (this.right) {\n this._replaceWith(this.right);\n }\n // If node has no children, then simply remove it and any references to it\n else {\n this._replaceWith(null);\n }\n } else if (key < this.key && this.left) {\n this.left.remove(key);\n } else if (key > this.key && this.right) {\n this.right.remove(key);\n } else {\n throw new Error(\"Key error\");\n }\n }", "treeInsert(x) {\n var node = this.root\n var y = NIL\n while (node !== NIL) {\n y = node\n if (x.interval.low <= node.interval.low) {\n node = node.left\n } else {\n node = node.right\n }\n }\n x.parent = y\n\n if (y === NIL) {\n this.root = x\n x.left = x.right = NIL\n } else {\n if (x.interval.low <= y.interval.low) {\n y.left = x\n } else {\n y.right = x\n }\n }\n\n applyUpdate.call(this, x)\n }", "animateDelete(key) {\r\n const animations = [];\r\n animations.push(new Animation(\"display\", `Deleting ${key}`));\r\n\r\n this.root = this.animateDeleteHelper(this.root, key, animations);\r\n this.positionReset(); // reset x,y positions of nodes\r\n\r\n // highlight last node in green if found\r\n if (compareTo(animations[animations.length - 1].getItem(), key) === 0) {\r\n animations[animations.length - 1].setClass(\"found-node\");\r\n animations.push(new Animation(\"display\", `Deleted ${key}`));\r\n return [key, animations];\r\n } // highlight last node in red if not found\r\n else {\r\n animations[animations.length - 1].setClass(\"search-failed-node\");\r\n animations.push(new Animation(\"display\", \"Not Found\"));\r\n\r\n return [null, animations];\r\n }\r\n }", "insert(value) {\n if (this.value === null || this.value === undefined) {\n this.value = value;\n\n return this;\n }\n if (value < this.value) {\n if (this.left) {\n return this.left.insert(value);\n }\n const newNode = new BinarySearchTreeNodes(value);\n this.setLeft(newNode);\n this.left.parent = this;\n\n return newNode;\n } else if (value > this.value) {\n if (this.right) {\n return this.right.insert(value);\n }\n const newNode = new BinarySearchTreeNodes(value);\n this.setRight(newNode);\n this.right.parent = this;\n\n return newNode;\n }\n return this;\n }", "treeShake(){\n let open = this.toResolve;\n\n let failsafe = 100;\n while(open.length > 0 && (failsafe-->0)){\n let cur = open.pop();\n let val = this.findRvalue(cur.loc);\n if(val){\n cur.value = val;\n console.log(JSON.stringify(cur));\n } else {\n cur.tries ++;\n open.push(cur);\n // tODO: shuffle before pushing? \n }\n }\n }", "insert_fixup(insert_node) {\n let current_node;\n let uncle_node;\n\n current_node = insert_node;\n while (current_node != this.root && current_node.parent.color == RB_TREE_COLOR_RED) {\n if (current_node.parent == current_node.parent.parent.left) { // parent is left child of grandfather\n uncle_node = current_node.parent.parent.right; // right brother of parent\n if (uncle_node.color == RB_TREE_COLOR_RED) { // Case 1. Uncle is red\n // re-color father and uncle into black\n current_node.parent.color = RB_TREE_COLOR_BLACK;\n uncle_node.color = RB_TREE_COLOR_BLACK;\n current_node.parent.parent.color = RB_TREE_COLOR_RED;\n current_node = current_node.parent.parent;\n }\n else { // Case 2 & 3. Uncle is black\n if (current_node == current_node.parent.right) { // Case 2. Current if right child\n // This case is transformed into Case 3.\n current_node = current_node.parent;\n this.rotate_left(current_node);\n }\n current_node.parent.color = RB_TREE_COLOR_BLACK; // Case 3. Current is left child.\n // Re-color father and grandfather, rotate grandfather right\n current_node.parent.parent.color = RB_TREE_COLOR_RED;\n this.rotate_right(current_node.parent.parent);\n }\n }\n else { // parent is right child of grandfather\n uncle_node = current_node.parent.parent.left; // left brother of parent\n if (uncle_node.color == RB_TREE_COLOR_RED) { // Case 4. Uncle is red\n // re-color father and uncle into black\n current_node.parent.color = RB_TREE_COLOR_BLACK;\n uncle_node.color = RB_TREE_COLOR_BLACK;\n current_node.parent.parent.color = RB_TREE_COLOR_RED;\n current_node = current_node.parent.parent;\n }\n else {\n if (current_node == current_node.parent.left) { // Case 5. Current is left child\n // Transform into case 6\n current_node = current_node.parent;\n this.rotate_right(current_node);\n }\n current_node.parent.color = RB_TREE_COLOR_BLACK; // Case 6. Current is right child.\n // Re-color father and grandfather, rotate grandfather left\n current_node.parent.parent.color = RB_TREE_COLOR_RED;\n this.rotate_left(current_node.parent.parent);\n }\n }\n }\n\n this.root.color = RB_TREE_COLOR_BLACK;\n }", "insertionFix(tree, child){\n let node = this;\n // While node and parent are both Red\n while(node.color === Red && node.parent.color === Red){\n const parent = node.parent;\n const uncle = parent.getSibling();\n if(uncle && uncle.color === Red){ // Parent's sibling is Red\n uncle.color = Black;\n parent.color = Black;\n parent.parent.color = Red;\n node = parent.parent;\n }else{\n if((parent.left === node) !== (parent.parent.left === parent)){\n node.rotate(tree);\n node.rotate(tree);\n }else{\n parent.rotate(tree);\n node = parent;\n }\n }\n if(!node.parent){\n break;\n }\n }\n if(!node.parent){\n node.color = Black;\n }\n }", "function TNodes_doCopyBranchToJson(source){\n \n var mysplit={};\n var splitnodecollection=new Array();\n var nodeAttr=new TComAttr();\n var boxnodeAttr=new TComAttr();\n var tmpnds=new TNodes('tempNodes',source.Owner,source.Owner.Ident);\n var e=0;\n var maxlevel=-1;\n var list=[]; // array for json-bifork-objects\n var myitemlist={}; // subelementlist container or sticker\n var myitemnds={}; // Nodes in subelement\n var partlist={}; // return-receiver for recursive callings \n var curindex=0;\n var mybuildorder='noinfo';\n\n switch (source.Type){\n case 'node':\n var mysourcends=source.Owner;\n var myzeronode=null;\n var zeronodeflag=false; \n break;\n \n case 'nodes':\n var myzeronode=new TNode();\n myzeronode.doAssign(source.Item[0]);\n var mysourcends=source;\n source=mysourcends.Item[0];\n var zeronodeflag=true; \n break;\n\n case 'container':\n var mysourcends=source.Nodes;\n source=mysourcends.Item[0];\n tmpnds.Item[0]=source; \n break;\n /* STICKER_mp\n case 'sticker':\n var mysourcends=source.Nodes;\n \n break;*/\n default:\n return null;\n } \n \n /* ====================================\n * Node with childs == bifork-structure\n * ==================================== \n */ \n \n if (source.HasChild==true){\n \n mybuildorder='child';\n \n // set the startlevel\n var minlevel=source.Child.Level;\n\n // get all objects with ident from this branch\n // load it into the tmpnds\n for (var i=source.Child.AbsoluteIndex;i<=mysourcends.Count;i++){\n \n mysplit=mysourcends.Item[i];\n if (i>source.Child.AbsoluteIndex && mysplit.Level<=source.Child.Level){\n break;\n }\n tmpnds.Item[i] = new TSplit();\n tmpnds.Item[i].doAssign(mysplit);\n tmpnds.Item[i].ParentIndex=mysplit.Parent.Parent.AbsoluteIndex;\n if (mysplit.Level>maxlevel){\n maxlevel=mysplit.Level;\n }\n \n // show copy-result\n doPrint('copy to node -> ' + i + ' type:' + mysplit.Type);\n doPrint('copy-target -> ' + i + ' type:' + tmpnds.Item[i].Type);\n \n // + ' ident: ' + myobjectlist[e].Ident + ' ->' , myobjectlist[e]);\n \n }\n \n // initialize the two-dimensional horizontal array\n var levellist = new Array(maxlevel-minlevel+1);\n for (var L=minlevel;L<=maxlevel;L++){\n levellist[L] = new Array();\n }\n \n // sort the elements of tmpnds in levellist[level, absoluteindex]\n for (var S in tmpnds.Item){\n mysplit=tmpnds.Item[S];\n levellist[mysplit.Level][S]=tmpnds.Item[S];\n }\n\n if (zeronodeflag){\n curindex=list.length;\n list[list.length]=myzeronode.doDBTreeDataobject();\n list[curindex].buildorder='zeronode'; \n }\n \n for (L=minlevel;L<=maxlevel;L++){ \n for (S in levellist[L]){\n \n mysplit=levellist[L][S];\n \n curindex=list.length;\n list[curindex]=mysplit.UpNode.doDBTreeDataobject();\n list[curindex].buildorder=mybuildorder; //'U'+mysplit.AbsoluteIndex;\n curindex=list.length;\n list[curindex]=mysplit.DownNode.doDBTreeDataobject();\n list[curindex].buildorder=mybuildorder; //'D'+mysplit.AbsoluteIndex;\n\n // scanning the sub-elements\n\n // the two nodes in a mini-array for dry-code\n // UpNode\n splitnodecollection[1]=mysplit.UpNode;\n // DownNode\n splitnodecollection[2]=mysplit.DownNode;\n \n // container and splits \n // seq. up- and downnode => 1, then 2\n for (var i=1;i<=2;i++){\n // t iterats 1 and 2 for container und splits to keep the code dry \n for (var t=1;t<=2;t++){ \n \n switch (t){\n case 1: myitemlist=splitnodecollection[i].ContainerList;\n break;\n case 2: myitemlist=splitnodecollection[i].StickerList;\n break;\n }\n \n for (var j=1;j<=myitemlist.Count;j++){\n curindex=list.length;\n list[curindex]=myitemlist.Item[j].doDBTreeDataobject();\n list[curindex].buildorder=mybuildorder;\n \n myitemnds=myitemlist.Item[j].Nodes;\n \n // scanning for bifork in container\n if (myitemnds.Item !=undefined){\n\n // recursive calling over object TNodes -> incl. zeronode\n partlist = myitemnds.doCopyBranchToJson(myitemlist.Item[j].Nodes); \n\n for (e in partlist) { \n if (e==1){ \n // insert a control-command between the data\n // at zeronode-position in container-elementlist\n list[list.length]={\n 'datatype': 'command',\n 'todo': 'stackup'\n }\n }\n curindex=list.length;\n list[curindex]=partlist[e];\n list[curindex].buildorder=mybuildorder;\n }\n // mark last element\n curindex=list.length-1;\n list[curindex].buildorder='lastelement';\n \n // insert a control-command between the data\n list[list.length]={\n 'datatype': 'command',\n 'todo': 'stackdown'\n }\n \n }//if != undefined\n }// for itemlist\n\n }// for t container and sticker\n }// for i, up und down\n }//for levellist\n }// for levellist\n\n // list of objects to console\n for (var e in list){\n doPrint('copy to json -> [' + e + ']' \n + ' ident: ' + list[e].ident \n + ' type: ' + list[e].datatype\n + ' buildorder: ' + list[e].buildorder\n + ' ->' , list[e]);\n }\n\n delete levellist;\n\n }// end node-child\n\n\n /* ======================================\n * Zeronode without children in container\n * ====================================== \n */ \n\n if (source.HasChild==false && source.ZeroNodeType=='container'){\n mybuildorder='nochild';\n curindex=list.length;\n list[curindex]=source.doDBTreeDataobject();\n list[curindex].buildorder=mybuildorder;\n \n // list of objects to console\n for (var e in list){\n doPrint('copy to json -> [' + e + ']' \n + ' ident: ' + list[e].ident \n + ' type: ' + list[e].datatype \n + ' ->' , list[e]);\n }\n \n }\n\n /* ======================================\n * Zeronode without children in sticker\n * ====================================== \n */ \n/* STICKER_mp\n if (source.HasChild==false && source.ZeroNodeType=='sticker'){\n mybuildorder='nochild';\n curindex=list.length;\n list[curindex]=source.doDBTreeDataobject();\n list[curindex].buildorder=mybuildorder;\n \n // list of objects to console\n for (var e in list){\n doPrint('copy to json -> [' + e + ']' \n + ' ident: ' + list[e].ident \n + ' type: ' + list[e].datatype \n + ' ->' , list[e]);\n }\n \n }*/\n\n /* ====================================\n * Node with containerlist\n * ==================================== \n */ \n\n if (source.ContainerList.Count>0){\n mybuildorder='container';\n myitemlist=source.ContainerList;\n\n for (var j=1;j<=myitemlist.Count;j++){\n\n curindex=list.length;\n list[curindex]=myitemlist.Item[j].doDBTreeDataobject();\n list[curindex].buildorder=mybuildorder;\n /* STICKER_mpif (myitemlist.Owner.ZeroNodeType=='sticker'){\n list[curindex].buildorder='sticker'; \n }*/\n \n myitemnds=myitemlist.Item[j].Nodes;\n \n // scanning for bifork in container\n if (myitemnds.Item !=undefined){\n\n // recursive calling over object TNodes -> incl. zeronode\n partlist = myitemnds.doCopyBranchToJson(myitemlist.Item[j].Nodes); \n\n for (e in partlist) { \n if (e==1){ \n // insert a control-command between the data\n // at zeronode-position in container-elementlist\n list[list.length]={\n 'datatype': 'command',\n 'todo': 'stackup'\n }\n }\n \n list[list.length]=partlist[e];\n }\n\n // insert a control-command between the data\n list[list.length]={\n 'datatype': 'command',\n 'todo': 'stackdown'\n }\n }//----\n \n }\n\n // list of objects to console\n for (var e in list){\n doPrint('copy to json -> [' + e + ']' \n + ' ident: ' + list[e].ident \n + ' type: ' + list[e].datatype \n + ' ->' , list[e]);\n }\n\n\n }// end node-container\n\n\n /* ====================================\n * Node with stickerlist\n * ==================================== \n */ \n/* STICKER_mp\n if (source.StickerList.Count>0){\n mybuildorder='sticker';\n myitemlist=source.StickerList;\n\n for (var j=1;j<=myitemlist.Count;j++){\n\n curindex=list.length;\n list[curindex]=myitemlist.Item[j].doDBTreeDataobject();\n list[curindex].buildorder=mybuildorder;\n \n myitemnds=myitemlist.Item[j].Nodes;\n \n // scanning for bifork in container\n if (myitemnds.Item !=undefined){\n\n // recursive calling over object TNodes -> incl. zeronode\n partlist = myitemnds.doCopyBranchToJson(myitemlist.Item[j].Nodes); \n\n for (e in partlist) { \n if (e==1){ \n // insert a control-command between the data\n // at zeronode-position in container-elementlist\n list[list.length]={\n 'datatype': 'command',\n 'todo': 'stackup'\n }\n }\n \n list[list.length]=partlist[e];\n }\n\n // insert a control-command between the data\n list[list.length]={\n 'datatype': 'command',\n 'todo': 'stackdown'\n }\n }//----\n \n }\n\n // list of objects to console\n for (var e in list){\n doPrint('copy to json -> [' + e + ']' \n + ' ident: ' + list[e].ident \n + ' type: ' + list[e].datatype \n + ' ->' , list[e]);\n }\n\n\n }// end node-sticker */\n\n delete tmpnds;\n \n return list;\n\n }", "function Node(key, value, left, right, color) {\n this._key = key;\n this._left = left;\n this._right = right;\n this._value = value;\n this._color = color;\n }", "insertKey(k) {\n\n this.harr.push(k)\n let i = this.harr.length - 1\n\n let parentInd = this.parent(i)\n\n while (i != 0 && parentInd > harr[i]) {\n\n this.swap(i, parentInd)\n\n i = parentInd\n parentInd = this.parent(i)\n\n }\n\n }", "insertBefore(key, value) {\n if(this.head === null) {\n this.head = new _Node(value, this.head)\n } else {\n let currNode = this.head\n let prevNode = this.head\n while(currNode !== null && currNode.value !== key) {\n prevNode = currNode\n currNode = currNode.next\n }\n prevNode.next = new _Node(value, currNode)\n }\n }", "insert(val) {\n // If we have an empty tree, insert new val at the root\n if(this.root === null){\n this.root = new Node(val);\n return this;\n }\n\n // If not we find the right spot for the node\n let current = this.root;\n while (true){\n if(val < current.val){\n if(current.left === null){\n current.left = new Node(val);\n return this;\n } else {\n current = current.left;\n }\n } else if(current.val < val){\n if(current.right === null) {\n current.right = new Node(val);\n return this;\n } else {\n current = current.right;\n }\n\n }\n }\n\n }", "function preOrder(tree) {\n //break case; if tree is null\n if (!tree) {\n return;\n }\n\n console.log(tree.key);\n\n if (tree.left){\n preOrder(tree.left);\n }\n\n if (tree.right){\n preOrder(tree.right);\n }\n\n}", "function animation_insertion_key (direccion, sat){\n if (sat) {\n animation_insertion_with_saturation (direccion);\n } else \n {\n\t animation_insertion_without_saturation ();\n }\t\n}", "preOrder(node) {\n if (node != null) {\n document.write(node.key + \" \");\n this.preOrder(node.left);\n this.preOrder(node.right);\n }\n }", "insertRecursive(value){\n var newNode = new Node(value);\n if (traverse(this.root)) this.root = newNode;\n \n function traverse(current){\n if (current === null) return true;\n \n if (newNode.value > current.value) {\n if (traverse(current.right)) current.right = newNode;\n } else if (newNode.value < current.value) {\n if (traverse(current.left)) current.left = newNode;\n }\n \n return false;\n }\n \n return this;\n }", "function BinarySearchTree(keys) {\n let Node = function(key) {\n this.key = key;\n this.left = null;\n this.right = null;\n };\n let root = null;\n let insertNode = (node, newNode) => {\n if (newNode.key < node.key) {\n if (node.left === null) {\n node.left = newNode;\n } else {\n insertNode(node.left, newNode);\n }\n } else {\n if (node.right === null) {\n node.right = newNode;\n } else {\n insertNode(node.right, newNode);\n }\n }\n };\n this.insert = key => {\n let newNode = new Node(key);\n if (root === null) {\n root = newNode;\n } else {\n insertNode(root, newNode);\n }\n };\n\n keys.forEach(key => {\n console.log(this);\n this.insert(key);\n });\n\n return root;\n}", "insert(val) {\n const newNode = new Node(val);\n if(!this.root){\n this.root = newNode;\n return this; \n }\n\n let currentNode = this.root;\n while (currentNode) {\n if(currentNode.val > val){\n if(!currentNode.left) {\n currentNode.left = newNode;\n return this;\n }\n currentNode = currentNode.left;\n }else if(currentNode.val < val){\n if(!currentNode.right) {\n currentNode.right = newNode;\n return this;\n }\n currentNode = currentNode.right;\n }\n }\n }", "function makeTree(){\n introNode.leftChild = day_0_Job_Selection;\n \n day_0_Job_Selection.leftChild = day_1_Choosing_Savings;\n \n day_1_Choosing_Savings.leftChild = day_2_Moving;\n}", "set(key, value) {\n let steps = key.split(\".\");\n let node = this._root;\n\n steps.slice(0, steps.length - 1).forEach((name) => {\n if(!node.hasOwnProperty(name)) {\n node[name] = {};\n }\n node = node[name];\n });\n node[steps[steps.length - 1]] = value;\n }", "function tree(t) {\n if (!t) {\n return 0;\n }\n return tree(t.left) + t.key + tree(t.right);\n}", "function key(key) {\n this.key = key;\n\n this.x = 600;\n this.y = 100;\n this.radius = 15;\n this.bottom = 500;\n this.insetX;\n this.insetY = 6;\n this.gap;\n\n this.sorted = false;\n\n this.father;\n this.leftson;\n this.rightson;\n\n this.edge;\n\n this.setKey = setKey;\n this.graphics = graphics;\n\n this.setKey(this.key);\n\n function setKey(value) {\n this.key = value;\n if (this.key > 9) {\n if (this.key > 99) {\n this.key = 99;\n }\n this.insetX = 9;\n }\n else {\n if (this.key < 1) {\n this.key = 1;\n }\n this.insetX = 4;\n }\n }\n\n function graphics() {\n\n\n var myGradient = ctx.createLinearGradient(this.x - this.radius, this.x - this.radius, this.x + this.radius, this.x - this.radius);\n myGradient.addColorStop(0, \"#BA0000\");\n myGradient.addColorStop(1, \"#560000\");\n ctx.fillStyle = myGradient;\n\n if (!this.sorted) {\n ctx.fillRect(this.x - this.radius, this.y - this.radius, this.radius * 2, this.radius * 2);\n ctx.fillStyle = \"black\";\n }\n else {\n ctx.fillStyle = \"red\";\n }\n ctx.fillText(this.key, this.x - this.insetX, this.y + this.insetY);\n }\n}", "tidy(root) {\n let orderedNodes = [];\n this.postTraverse(root, orderedNodes);\n let modMap = {};\n let centerMap = {};\n let min_dist = 100;\n for (let node of orderedNodes) {\n centerMap[node.id] = 0;\n node.cx = 0;\n if (node.children.length != 0) {\n node.children[0].cx == 0;\n for (let i = 1; i < node.children.length; i++) {\n node.children[i].cx = node.children[i - 1].cx + min_dist;\n }\n centerMap[node.id] = (node.children[0].cx + node.children[node.children.length - 1].cx) / 2;\n }\n }\n // console.log(centerMap);\n for (let node of orderedNodes) {\n // console.log(node.label);\n //Set the top y value\n node.cy = node.depth * 75 + 50;\n let leftSiblings = (node.parents[0] != undefined && node.parents[0].children[0] !== node);\n // console.log(leftSiblings);\n // console.log(centeredValue);\n if (!leftSiblings) {\n node.cx = centerMap[node.id];\n modMap[node.id] = 0;\n }\n else {\n node.cx = node.parents[0].children[node.parents[0].children.indexOf(node) - 1].cx + min_dist;\n modMap[node.id] = node.cx - centerMap[node.id];\n }\n }\n this.shiftChildrenByMod(root, 0, modMap);\n modMap = this.clearModMap(modMap);\n //dealing with conflicts, twice.\n // modMap = this.fixConflicts(root, orderedNodes, modMap);\n modMap = this.fixConflicts(root, orderedNodes, modMap);\n this.fixOffScreen(root, modMap);\n root.cx = (root.children[0].cx + root.children[root.children.length - 1].cx) / 2;\n }", "add(value){\n let addNode = { value, left: null, right: null};\n\n // set the root if we don't have one\n if(this.root === null){\n this.root = addNode;\n return;\n }\n\n let current = this.root;\n\n while(true){\n // check for right\n if(value > current.value){\n // add right\n if(!current.right){ current.right = addNode; break; }\n\n current = current.right;\n\n // check for left\n } else if(value < current.value){\n // add left\n if(!current.left){ current.left = addNode; break; }\n\n current = current.left;\n } else {\n // if it's the same ignore\n break;\n }\n }\n }", "animateLevelorderNodes() {\r\n let queue = [];\r\n let nodeQueue = [];\r\n let animations = [];\r\n animations.push(new Animation(\"display\", \"Traversing Levelorder\", \"\"));\r\n\r\n nodeQueue.push(this.root);\r\n\r\n while (nodeQueue.length !== 0) {\r\n const node = nodeQueue.shift();\r\n if (node === null) continue;\r\n queue.push(node);\r\n\r\n // insert animations\r\n if (this.root && !node.isEqual(this.root))\r\n animations.push(new Animation(\"line\", node.key, \"line-highlighted\"));\r\n animations.push(new Animation(\"node\", node.key, \"found-node\"));\r\n\r\n nodeQueue.push(node.left);\r\n nodeQueue.push(node.right);\r\n }\r\n\r\n animations.push(new Animation(\"display\", \"Finished Traversing\", \"\"));\r\n\r\n return [queue, animations];\r\n }", "function appendBuiltContent( ancestorBranches, key, node ){\n \n nodeOf( head( ancestorBranches))[key] = node;\n }", "function appendBuiltContent( ancestorBranches, key, node ){\n \n nodeOf( head( ancestorBranches))[key] = node;\n }", "function appendBuiltContent( ancestorBranches, key, node ){\n \n nodeOf( head( ancestorBranches))[key] = node;\n }", "function appendBuiltContent( ancestorBranches, key, node ){\n \n nodeOf( head( ancestorBranches))[key] = node;\n }", "function appendBuiltContent( ancestorBranches, key, node ){\n \n nodeOf( head( ancestorBranches))[key] = node;\n }", "function appendBuiltContent( ancestorBranches, key, node ){\n \n nodeOf( head( ancestorBranches))[key] = node;\n }", "function appendBuiltContent( ancestorBranches, key, node ){\n \n nodeOf( head( ancestorBranches))[key] = node;\n }", "function appendBuiltContent( ancestorBranches, key, node ){\n \n nodeOf( head( ancestorBranches))[key] = node;\n }", "function appendBuiltContent( ancestorBranches, key, node ){\n \n nodeOf( head( ancestorBranches))[key] = node;\n }", "function appendBuiltContent( ancestorBranches, key, node ){\n \n nodeOf( head( ancestorBranches))[key] = node;\n }", "function appendBuiltContent( ancestorBranches, key, node ){\n \n nodeOf( head( ancestorBranches))[key] = node;\n }", "function appendBuiltContent( ancestorBranches, key, node ){\n \n nodeOf( head( ancestorBranches))[key] = node;\n }", "function appendBuiltContent( ancestorBranches, key, node ){\n \n nodeOf( head( ancestorBranches))[key] = node;\n }", "function appendBuiltContent( branch, leaf ){\n \n nodeOf(branch)[keyOf(leaf)] = nodeOf(leaf);\n }", "buildTree(tree) {\n alphabet = new Set();\n id_map = [];\n // Prepare initial node\n id = 0;\n followpos = [];\n this.type = CONCAT;\n this.c1 = new Node();\n this.c2 = new Node();\n this.c2.buildNodes({ type: \"Char\", value: \"#\" });\n this.c1.buildNodes(tree);\n this.nullable = this.c1.nullable && this.c2.nullable;\n\n // Set firstpos\n this.firstpos = new Set(this.c1.firstpos);\n if (this.c1.nullable) {\n for (let each of this.c2.firstpos) {\n this.firstpos.add(each);\n }\n }\n // Set lastpos\n this.lastpos = new Set(this.c2.lastpos);\n if (this.c2.nullable) {\n for (let each of this.c1.lastpos) {\n this.lastpos.add(each);\n }\n }\n // Set followpos\n for (let i of this.c1.lastpos) {\n for (let each of this.c2.firstpos) {\n followpos[i].add(each);\n }\n }\n\n alphabet.delete(\"#\");\n }", "bfs(tree, values = []) {\n const queue = new queue(); //Assuming a Queue is implemented\n const node = tree.root; \n queue.enqueue = tree.root; \n while (queue.length) {\n const node = queue.dequeue(); //remove from the queue\n values.push(node.value); //add that value from queue to an array\n\n if (node.left) {\n queue.dequeue(node.left) //add left child to the queue\n }\n if (node.right) {\n queue.enqueue(node.rigth) //add right child to the queue\n }\n return values; \n }\n }", "insert(value) {\n const newNode = new Node(value);\n if (!this.root) {\n this.root = newNode;\n return this;\n } \n // traverse it as if you would traverse a linked list\n let current = this.root;\n while (true) {\n // if duplicates are not handled, ill get an infinite loop!\n if (value === current.value) {\n return undefined;\n }\n if (value > current.value) {\n if (!current.right) {\n current.right = newNode;\n return this;\n }\n // update current if there is already a right\n current = current.right;\n } else {\n if (!current.left) {\n current.left = newNode;\n return this;\n }\n // update current if there is already a left\n current = current.left;\n }\n }\n }" ]
[ "0.6494019", "0.64919895", "0.6320114", "0.6282188", "0.6202963", "0.6142242", "0.6137095", "0.6115002", "0.6074625", "0.6048915", "0.60057634", "0.5926925", "0.59215504", "0.59215504", "0.58945984", "0.58928645", "0.58810455", "0.58547956", "0.5854308", "0.58109164", "0.57595044", "0.5713909", "0.5701204", "0.5693353", "0.5673332", "0.5668982", "0.5657284", "0.5655796", "0.5626027", "0.5625153", "0.5613835", "0.5592342", "0.55823874", "0.5580875", "0.5555894", "0.55454963", "0.5532648", "0.5531955", "0.5510645", "0.5509375", "0.5496256", "0.5492804", "0.54630226", "0.54606843", "0.54562676", "0.5450115", "0.54484034", "0.5443966", "0.5436078", "0.54355186", "0.5425166", "0.5424992", "0.5399299", "0.53940743", "0.5382567", "0.5373703", "0.5350149", "0.53486395", "0.5337894", "0.5336361", "0.53176016", "0.53109443", "0.5299434", "0.52956414", "0.5278186", "0.5268641", "0.52676773", "0.5264173", "0.52622396", "0.5260002", "0.52594954", "0.5230875", "0.522951", "0.52215266", "0.52157015", "0.52041626", "0.5187353", "0.51869833", "0.5172347", "0.5172063", "0.5161769", "0.5149303", "0.514846", "0.5145746", "0.5145746", "0.5145746", "0.5145746", "0.5145746", "0.5145746", "0.5145746", "0.5145746", "0.5145746", "0.5145746", "0.5145746", "0.5145746", "0.5145746", "0.5144565", "0.51437366", "0.5139719", "0.51373935" ]
0.54045135
52
whether bst contains key
animateContains(key) { const [node, animations] = this.animateGet(key); // reuse the animateGet method while fixing the display values animations[0] = new Animation("display", `Contains ${key}?`, ""); const containsMsg = node === null ? "False" : "True"; animations[animations.length - 1] = new Animation( "display", containsMsg, "" ); return [node, animations]; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "contains(key) {\n let current = this.head;\n while(current.object != key) {\n current = current.next;\n if(current == null)\n return false;\n }\n return true;\n }", "contains(key)\n\t{\n\t\tkey = this.toString(key);\n\t\treturn super.has(key);\n\t}", "has(key) {\n return this.keys.indexOf(key) > -1;\n }", "has(key: K): boolean {\n return this.tree.find([key, null]) != null;\n }", "async has(key) {}", "hasKey(key) {\n return this.id2Value[key.id] != null;\n }", "has(k) {\n return k in this.kvStore;\n }", "has (key) {\n return this.keys.has(key)\n }", "contains(key) {\n key = binding_key_1.BindingKey.validate(key);\n return this.registry.has(key);\n }", "function sc_hashtableContains(ht, key) {\n var hash = sc_hash(key);\n if (hash in ht)\n\treturn true;\n else\n\treturn false;\n}", "has(key) {\n const idx = asItemIndex(key);\n return typeof idx === 'number' && idx < this.items.length;\n }", "has(key)\n\t{\n\t\tkey = this.toString(key);\n\t\treturn super.has(key);\n\t}", "has(key) {\n const idx = asItemIndex(key);\n return typeof idx === 'number' && idx < this.items.length;\n }", "has(key) {\n\t\treturn key in this.collection;\n\t}", "hasKey(key) {\n return this.store.hasOwnProperty(key);\n }", "hasKey(key) {\n return this.store.hasOwnProperty(key);\n }", "hasKey(key) {\n return this.store.hasOwnProperty(key);\n }", "hasKey(key) {\n return this.store.hasOwnProperty(key);\n }", "hasKey(key) {\n return this.store.hasOwnProperty(key);\n }", "hasKey(key) {\n return this.store.hasOwnProperty(key);\n }", "contains(data) {\n return this.findBFS(data) ? true : false;\n }", "has(key) {\n return this._has(this._translateKey(key));\n }", "has(key) {\n return isCollection(this.contents) ? this.contents.has(key) : false;\n }", "has(key) {\n return identity.isCollection(this.contents) ? this.contents.has(key) : false;\n }", "exists(key) {\n let found = true;\n let current = this._root;\n\n key.split(\".\").forEach((name) => {\n if(current && found) {\n if(current.hasOwnProperty(name)) {\n current = current[name];\n } else {\n found = false;\n }\n }\n });\n\n return(found);\n }", "hasKey(name) {\n if (name in this.values) {\n return true;\n }\n for (let i in this.subspacesById) {\n if (this.subspacesById[i].hasKey(name)) {\n return true;\n }\n }\n return false;\n }", "contains(KEY)\n {\n // Local variable dictionary\n let keyFound = false; // Flag if found the key in dictionary\n\n // Find the key\n if (arguments.length > 1)\n {\n throw new Error(\"Too many arguments\");\n }\n else if (arguments.length < 1)\n {\n throw new Error(\"Too few arguments\");\n }\n else if (!(KEY instanceof Hashable))\n {\n throw new Error(\"Invalid type\");\n }\n else\n {\n // Local variable dictionary\n let hashIndex = KEY.hashVal() % this.#table.getLength();\n\n // Find if the key exists in the table and get the value\n let listIndex = this.#table.peekIndex(hashIndex);\n for (let counter = 0; counter < listIndex.getLength() && keyFound === false; counter++)\n {\n // Get the hash entry\n let hashEntry = listIndex.peekIndex(counter);\n\n // Check if it is the same key\n if (hashEntry.key.key === KEY.key)\n {\n keyFound = true;\n }\n }\n }\n\n // Return flag if the key found\n return keyFound;\n }", "containsKey(key) {\n return this.getKeys().includes(key);\n }", "isBound(key) {\n if (this.contains(key))\n return true;\n if (this._parent) {\n return this._parent.isBound(key);\n }\n return false;\n }", "function dist_index_esm_contains(obj,key){return Object.prototype.hasOwnProperty.call(obj,key);}", "static hasHead(key) {\n return Object.keys(this.heads).includes(key);\n }", "function has(key) /*: boolean*/ {\n\t var val = this.node && this.node[key];\n\t if (val && Array.isArray(val)) {\n\t return !!val.length;\n\t } else {\n\t return !!val;\n\t }\n\t}", "function has(key) /*: boolean*/ {\n\t var val = this.node && this.node[key];\n\t if (val && Array.isArray(val)) {\n\t return !!val.length;\n\t } else {\n\t return !!val;\n\t }\n\t}", "has(key) {\n return this._.has(key);\n }", "function contains(arr, key, val) {\n for (var i = 0; i < arr.length; i++) {\n if(arr[i][key] === val) return true;\n }\n return false;\n }", "function has(key) {\n\t var val = this.node && this.node[key];\n\t if (val && Array.isArray(val)) {\n\t return !!val.length;\n\t } else {\n\t return !!val;\n\t }\n\t}", "contains(obj)\r\n {\r\n var list, k = size;\r\n for (var i = 0; i < k; i++)\r\n {\r\n list = this.#table[i];\r\n var l = list.length; \r\n \r\n for (var j = 0; j < l; j++)\r\n if (list[j].data === obj) return true;\r\n }\r\n return false;\r\n }", "function hasKey(n,t){var o=n;return t.slice(0,-1).forEach(function(n){o=o[n]||{}}),t[t.length-1]in o}", "contains(data) {\n return this.find(data) !== -1 ? true : false\n }", "function has(key) {\n\t var val = this.node[key];\n\t if (val && Array.isArray(val)) {\n\t return !!val.length;\n\t } else {\n\t return !!val;\n\t }\n\t}", "function has(key) {\n\t var val = this.node[key];\n\t if (val && Array.isArray(val)) {\n\t return !!val.length;\n\t } else {\n\t return !!val;\n\t }\n\t}", "function has(object, key) {\n let newArray =Object.keys(object);\n for (let i = 0; i < newArray.length; i++) {\n if(newArray[i]===key) {\n return true;\n } \n \n }\n return false;\n}", "has(k) {\n return Object.keys(this.cache).indexOf(k) > -1;\n }", "function mutationQueuesContainKey(txn, docKey) {\n var found = false;\n return mutationQueuesStore(txn).iterateSerial(function (userId) {\n return mutationQueueContainsKey(txn, userId, docKey).next(function (containsKey) {\n if (containsKey) {\n found = true;\n }\n\n return PersistencePromise.resolve(!containsKey);\n });\n }).next(function () {\n return found;\n });\n }", "contains(key) {\r\n return this.getAnimated(key) !== null;\r\n }", "function has(key) {\n var val = this.node[key];\n if (val && Array.isArray(val)) {\n return !!val.length;\n } else {\n return !!val;\n }\n}", "function BOT_matchKey(ref,key) {\r\n\tif(BOT_isArray(ref)) return (BOT_member(ref, key))\r\n\telse if(ref == key) return true\r\n\telse return false\r\n}", "has(obj, key){\n if ( obj.hasOwnProperty(key) ) {\n return true;\n } else return false;\n }", "contains(value) {\n var currentNode = this.head;\n while(currentNode !== null) {\n if(value === currentNode.data) {\n return true;\n }\n currentNode = currentNode.next;\n }\n return false;\n }", "hasItem(key: string) {\n return this.getItem(key) !== null;\n }", "hasItem(key: string) {\n return this.getItem(key) !== null;\n }", "function mutationQueuesContainKey(txn, docKey) {\r\n var found = false;\r\n return mutationQueuesStore(txn)\r\n .iterateSerial(function (userId) {\r\n return mutationQueueContainsKey(txn, userId, docKey).next(function (containsKey) {\r\n if (containsKey) {\r\n found = true;\r\n }\r\n return PersistencePromise.resolve(!containsKey);\r\n });\r\n })\r\n .next(function () { return found; });\r\n}", "function mutationQueuesContainKey(txn, docKey) {\r\n var found = false;\r\n return mutationQueuesStore(txn)\r\n .iterateSerial(function (userId) {\r\n return mutationQueueContainsKey(txn, userId, docKey).next(function (containsKey) {\r\n if (containsKey) {\r\n found = true;\r\n }\r\n return PersistencePromise.resolve(!containsKey);\r\n });\r\n })\r\n .next(function () { return found; });\r\n}", "function mutationQueuesContainKey(txn, docKey) {\r\n var found = false;\r\n return mutationQueuesStore(txn)\r\n .iterateSerial(function (userId) {\r\n return mutationQueueContainsKey(txn, userId, docKey).next(function (containsKey) {\r\n if (containsKey) {\r\n found = true;\r\n }\r\n return PersistencePromise.resolve(!containsKey);\r\n });\r\n })\r\n .next(function () { return found; });\r\n}", "function contains(obj, key) {\n return Object.prototype.hasOwnProperty.call(obj, key);\n}", "function contains(obj, key) {\n return Object.prototype.hasOwnProperty.call(obj, key);\n}", "function contains(obj, key) {\n return Object.prototype.hasOwnProperty.call(obj, key);\n}", "function contains(obj, key) {\n return Object.prototype.hasOwnProperty.call(obj, key);\n}", "function contains(obj, key) {\n return Object.prototype.hasOwnProperty.call(obj, key);\n}", "has(object, key){\n \n // To access the current value at specified key\n const hasValue = object['key'];\n \n if(hasValue != undefined ){\n return true;\n } else {\n return false;\n }\n }", "function mutationQueuesContainKey(txn, docKey) {\n var found = false;\n return mutationQueuesStore(txn)\n .iterateSerial(function (userId) {\n return mutationQueueContainsKey(txn, userId, docKey).next(function (containsKey) {\n if (containsKey) {\n found = true;\n }\n return PersistencePromise.resolve(!containsKey);\n });\n })\n .next(function () { return found; });\n}", "function mutationQueuesContainKey(txn, docKey) {\n var found = false;\n return mutationQueuesStore(txn).iterateSerial(function (userId) {\n return mutationQueueContainsKey(txn, userId, docKey).next(function (containsKey) {\n if (containsKey) {\n found = true;\n }\n\n return PersistencePromise.resolve(!containsKey);\n });\n }).next(function () {\n return found;\n });\n}", "function IsInHash(object, key) {\n\treturn key in object;\n}", "has (key, strict = true) {\n if (!strict) {\n return [...this.keys()].some((_key) => {\n return isEqual(key, _key);\n });\n }\n return Map.prototype.has.call(this, key);\n }", "has(myObject, myKey){\r\n let hasValue = myObject.myKey;\r\n //store the key, value pairs of the object.\r\n if (hasValue != 'undefined'){\r\n \t\t// return true if the key is undefined\r\n return true;\r\n }\r\n for (let i = 0; i < myObject.length; i++){\r\n\t\t\t// check if the key is within the object\r\n // return the boolean status accordingly.\r\n if (myObject[0] === myKey){\r\n return true;\r\n }\r\n else {\r\n return false;\r\n }\r\n } // for loop for objects\r\n }", "async has (key) {\n let result = await this.client.get(this.namedKey(key));\n return !!result;\n }", "function contains$2(obj, key) {\n return Object.prototype.hasOwnProperty.call(obj, key);\n}", "contains(entity) {\n const id = this.id(entity);\n return this.has(id) && this.get(id) === entity;\n }", "contain(data) {\n if (this.dataStore.indexOf(data) > -1) {\n return true;\n } else {\n return false;\n }\n }", "has(key) {\n return this.map[key] !== undefined;\n }", "function eventExistsInTimeline(key) {\n for (var i = 0; i < $rootScope.sortedEventList.length; i++) {\n if ($rootScope.sortedEventList[i].$id && $rootScope.sortedEventList[i].$id == key) {\n return true;\n }\n }\n return false;\n }", "has(token) {\n return this.map.has(token);\n }", "has(key) {\n return this.items[key]\n && this.items[key].created > (Date.now() / 1000) - this.timeToLive;\n }", "__key_in_object(object, key) {\n if (Object.prototype.hasOwnProperty.call(object, key)) {\n return true\n } else {\n return false\n }\n }", "function keyExists(t,e){if(!e||e.constructor!==Array&&e.constructor!==Object)return!1;for(var i=0;i<e.length;i++)if(e[i]===t)return!0;return t in e}", "function _has(obj, key) {\n\t return Object.prototype.hasOwnProperty.call(obj, key);\n\t }", "hasIn(path) {\n const [key, ...rest] = path;\n if (rest.length === 0)\n return this.has(key);\n const node = this.get(key, true);\n return identity.isCollection(node) ? node.hasIn(rest) : false;\n }", "has(key) {\n const value = this._map.get(key);\n const result = value && value.getTime() > Date.now();\n log.map(\"Key '%s' is present in the map? -> %s\", key, result);\n return result;\n }", "function contains(data) {\n if (this.dataStore.indexOf(data) > -1) {\n return true;\n } else {\n return false;\n }\n}", "static has(key) {\r\n return Object.get(Config.data, key, '__not_exists_') !== '__not_exists_';\r\n }", "hasNode(hash) {\n return hash in this.nodes;\n }", "function has(obj, key) {\n return key in obj\n}", "has(obj, key) {\n return obj.hasOwnProperty(key);\n }", "function BSTContains(val){\n if (this.root == null){\n return false;\n }\n var walker = this.root;\n while (walker != null){\n if (walker.val == val){\n return true;\n }\n else if (walker.val < val){\n walker = walker.right;\n }\n else if (walker.val > val){\n walker = walker.left;\n }\n }\n return false;\n }", "contains(element){\n let current = this.head;\n while(current !== null){\n if(current.data === element) return true; // equals ?\n current = current.next;\n }\n return false;\n }", "function hasCertainKey(arr, key) {\n\treturn arr.every(function(obj) {\n\t\treturn obj[key];\n\t})\n}", "has(key) {\n if (this.#outgoing !== null && this.#outgoing.has(key)) {\n let [, , isSetValue] = this.#outgoing.get(key);\n return isSetValue;\n }\n const values = this.#ensureParsed();\n return !!values[key];\n }", "function boat_has_this_load(loads, load_id) {\n flag = false;\n loads.forEach((load) => {\n if (load.key == load_id) {\n flag = true;\n }\n });\n return flag;\n}", "containsItem(itemID){\n return this.itemStacks.some(itemStack => itemStack.itemID == itemID);\n }", "hasIn(path) {\n const [key, ...rest] = path;\n if (rest.length === 0)\n return this.has(key);\n const node = this.get(key, true);\n return isCollection(node) ? node.hasIn(rest) : false;\n }", "contains(target) {\n let node = this.head\n while(node){\n if(node.value === target) return true\n node = node.next\n }\n return false\n }", "static hasSegment(key) {\n return Object.keys(this.segments).includes(key);\n }", "has(id) {\n return id in this[NODES];\n }", "contains(target) {\n let currNode = this.head;\n\n while (currNode) {\n if (currNode.value === target) {\n return true;\n }\n currNode = currNode.next;\n }\n return false;\n }", "contains(target) {\n let current = this.head;\n while (current) {\n if (current.value === target) {\n return true;\n }\n current = current.next;\n }\n return false;\n }", "contains(target) {\n if(this.length === 0 ) return false;\n let node = this.head\n for(let i = 0; i < this.length; i++ ){\n if(node.value === target){\n return true;\n }\n node = node.next\n }\n return false\n }", "function isBST(bst) {\n if(bst.left) {\n if(bst.left.key > bst.key) {\n return false;\n }\n if(!isbst(bst.left)) {\n return false;\n }\n }\n if(bst.right) {\n if(bst.right.key < bst.key) {\n return false;\n }\n if(!isbst(bst.right)) {\n return false;\n }\n }\n return true;\n }", "contains(value){\n let current = this.root;\n\n while(current){\n if(value === current.value){\n return true;\n }else if(value < current.value){\n current = current.left;\n }else{\n current = current.right;\n }\n }\n return false;\n }", "function isAvailalbe(data, data_index, data_key, statement){\n\t\tif(data && data[data_index] && data[data_index][data_key] === statement){\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}", "function transitionKeysContain(keys, key) {\n return !!(0,_Utilities__WEBPACK_IMPORTED_MODULE_0__.find)(keys, function (transitionKey) {\n return transitionKeysAreEqual(transitionKey, key);\n });\n}", "contains(value) {\n let currentNode = this.root;\n while (currentNode) {\n if(value === currentNode.value) {\n return true\n }\n if (value < currentNode.value) {\n currentNode = currentNode.left;\n } else {\n currentNode = currentNode.right;\n }\n }\n return false;\n }" ]
[ "0.74577385", "0.7159847", "0.7082258", "0.7018241", "0.69806147", "0.6955544", "0.6885939", "0.6791973", "0.6772025", "0.67040795", "0.6695513", "0.66438067", "0.66404474", "0.6628923", "0.6625589", "0.6625589", "0.6625589", "0.6625589", "0.6625589", "0.6600251", "0.65985644", "0.6548939", "0.6523227", "0.65052813", "0.65052575", "0.6485476", "0.64852166", "0.6474253", "0.64720476", "0.64565104", "0.6442245", "0.6410071", "0.6410071", "0.6391506", "0.6351333", "0.6329268", "0.63276005", "0.6326071", "0.6312978", "0.62839645", "0.62839645", "0.6283531", "0.6277547", "0.62572414", "0.6256378", "0.6254786", "0.6232633", "0.6231049", "0.6223703", "0.620189", "0.620189", "0.6200181", "0.6200181", "0.6200181", "0.61855775", "0.61855775", "0.61855775", "0.61855775", "0.61855775", "0.6171442", "0.61701125", "0.6158757", "0.6099091", "0.6071718", "0.60681146", "0.6056129", "0.6051917", "0.60505885", "0.6041962", "0.603337", "0.6019724", "0.5982853", "0.59807545", "0.59644306", "0.59589857", "0.59533334", "0.5952054", "0.5951674", "0.5943187", "0.5937403", "0.59360343", "0.592903", "0.59207374", "0.5913975", "0.59120864", "0.590721", "0.58969504", "0.5894653", "0.58931977", "0.58886015", "0.58811843", "0.5868539", "0.5867879", "0.58636487", "0.5857977", "0.58563834", "0.5854944", "0.5848336", "0.5835632", "0.58332723", "0.58318627" ]
0.0
-1
retrieve value associated with key from bst
animateGet(key) { const animations = []; animations.push(new Animation("display", `Getting ${key}`, "'")); const node = this.animateGetHelper(this.root, key, animations); // highlight last node in red if not found if (node === null) { animations[animations.length - 1].setClass("search-failed-node"); animations.push(new Animation("display", "Not Found", "'")); } // highlight last node in green if found else if (compareTo(key, node.key) === 0) { animations[animations.length - 1].setClass("found-node"); animations.push(new Animation("display", node.value, "'")); } return [node, animations]; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "get(key) {\n const address = this._hash(key);\n if(this.data[address]){\n for (let i = 0; i < this.data[address].length; i++) {\n let currenctBucket = this.data[address][i];\n if (currenctBucket) {\n if (currenctBucket[0] === key) {\n return currenctBucket[1];\n }\n }\n }\n }\n return undefined;\n }", "get(key: K): ?V {\n var val = this.tree.find([key, null]);\n return val ? val[1] : null;\n }", "getValue( key ) {\n return this.get( key );\n }", "function getDataValue(state, key) {\n\t var data = getDataObject(state);\n\t return data[key];\n\t}", "function getDataValue(state, key) {\n\t var data = getDataObject(state);\n\t return data[key];\n\t}", "function getDataValue(state, key) {\n\t var data = getDataObject(state);\n\t return data[key];\n\t}", "search(key) {\r\n const hash = this.calculateHash(key);\r\n if(this.values.hasOwnProperty(hash) && this.values[hash].hasOwnProperty(key)) {\r\n return this.values[hash][key];\r\n } else {\r\n return null;\r\n }\r\n }", "function get_(key){\n\t\tfor(var i = 0; i < keyValueMap.length; i++){\n\t\t\tif(keyValueMap[i].k == key){\n\t\t\t\treturn keyValueMap[i].v;\n\t\t\t}\n\t\t}\n\t}", "get(key){\n\n const index = this.hash(key);\n const dataBucket = this.buckets[index];\n if(dataBucket === undefined){\n return null;\n } else {\n let currentBucket = dataBucket.head;\n while((currentBucket.key !== key) && (currentBucket.next)){\n currentBucket = currentBucket.next;\n }\n return currentBucket.value;\n }\n\n }", "get(key){\n /* WITHOUT SEPARATE CHAINING COLLISION HANDLING...\n return this.table[this.hashFunction(key)];\n */\n \n // SEPARATE CHAINING WAY OF DOING IT:\n var postion = this.hashFunction(key);\n if (this.table[position] !== undefined){\n // iterate thru the LL to find the key\n // we know it's a LL, which has getHead() method\n var current = this.table[position].getHead();\n while(current.next){\n // check for the key on the element\n if (current.element.key === key){\n return current.element.value;\n }\n current = current.next;\n }\n // check in case it's the 1st or last element....\n if (current.element.key === key){\n return current.element.value;\n }\n }\n // key doesn't exist, nothing to get...\n return undefined;\n }", "get(key) {\n let index = this.getIndex(key);\n let data = this.data[index].value;\n if (!data.value) {\n return null;\n }\n return data.value;\n }", "findValue( srcContact, [table, key], cb){\n\n if (srcContact) this._welcomeIfNewNode(srcContact);\n\n this._store.get(table.toString('hex'), key.toString('hex'), (err, out) => {\n //found the data\n if (out) cb(null, [1, out] )\n else cb( null, [0, this._kademliaNode.routingTable.getClosestToKey(key) ] )\n })\n\n }", "function get_value(state_id, object){\n\t\tvar value = 0;\n\t\tobject.forEach(function(key_value){\n\t\t\t\n\t\t\tif(key_value.key == state_id){\n\t\t\t\tvalue = key_value.value;\n\t\t\t};\n\t\t\n\t\t});\n\t\t\n\t\t\n\t\treturn value;\n\t}", "retrieve(key) {\n const index = this._hash(key, this._tableSize);\n if (this._storage[index]) {\n let iterator = this._storage[index].values();\n let item = iterator.next();\n\n while (!item.done) {\n let pair = item.value;\n if (pair.isHead(key)) {\n return pair.getTail();\n }\n item = iterator.next();\n }\n }\n return null;\n }", "get(key) {\n if (this.hashMap.get(key) !== undefined) {\n let node = this.hashMap.get(key);\n let storage = node.storage;\n let val = storage.val;\n this.doublyLinkedList.moveToHead(node);\n return val;\n } else {\n return -1;\n }\n }", "get(key) {\n\t\tif (!key) {\n\t\t\tthrow new Error('key is not passed to get in hashtable');\n\t\t\treturn undefined;\n\t\t}\n\t\tconst hashKey = this._hash(key);\n\t\tconst bucket = this.data[hashKey];\n\t\t// if bucket is there go and loop over each values in that bucket\n\t\tif (bucket) {\n\t\t\t// loop over each array in this bucket and check the value against key\n\t\t\t// if both are equal then return the value on that index\n\t\t\tfor (let i = 0; i < bucket.length; i++) {\n\t\t\t\tif (bucket[i][0] === key) {\n\t\t\t\t\treturn bucket[i][1];\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn undefined;\n\t}", "retrieve(key) {\n const index = getIndexBelowMax(key.toString(), this.limit);\n const bucket = this.storage.get(index);\n if (bucket !== undefined) {\n let current = bucket.head;\n while (current) {\n if (current.value[0] === key) {\n return current.value[1];\n }\n current = current.next;\n }\n }\n }", "retrieve(key) {\n \n }", "function get(root, key, cb) {\n cb = cb || noop\n this.root = decode(root)\n key = decode(key)\n this.get(key, function(err, value) {\n if (err) return cb(err)\n cb(null, encode(value))\n }.bind(this))\n}", "get(key) {\n let index = this.hash(key);\n if (this.keyMap[index]) {\n for (let i = 0; i < this.keyMap[index].length; i++) {\n if (this.keyMap[index][i][0] === key) {\n return this.keyMap[index][i][1];\n }\n }\n }\n return undefined;\n }", "retrieve(key) {\n const index = getIndexBelowMax(key.toString(), this.limit);\n const bucket = this.storage.get(index);\n if (Array.isArray(bucket)) {\n for (let i = 0; i < bucket.length; i++) {\n const objKey = bucket[i][0];\n if (objKey === key) {\n return bucket[i][1];\n }\n }\n }\n }", "get (key, options) {\n return find(this, key, options, (node, parent, matched) => {\n if (!matched) {\n return undefined\n } else if (node.edges) {\n return node.values // Match was on internal value\n } else {\n return node._search(key, options) // Binary search the values list\n }\n })\n }", "searchBucket(bucket, key) {\n if (typeof key !== 'string') key = key.toString();\n let current = bucket.head;\n while (current) {\n if (Object.keys(current.value)[0] === key) {\n return Object.values(current.value)[0];\n } else {\n current = current.next;\n }\n }\n return null;\n }", "getProbe(key){\n var position = this.hashFunction(key);\n // if key exists...\n if (this.table[position] !== undefined){\n // check whether the value we're looking for is the the one at the specified position...\n if (this.table[position].key === key){\n // if so, return the value...\n return this.table[position].value;\n } else {\n // otherwise need to check the next idx...\n var idx = ++position;\n while(this.table[idx] === undefined || this.table[idx].key !== key){\n // break out once we find the position that contains the element and the element's key matches the key we're searching for...\n idx++;\n }\n if (this.table[idx].key === key){\n // verify the item is the one we want...\n return this.table[idx].value;\n }\n }\n }\n return undefined;\n }", "findNodeByKey (key) {\n return Tree.findEntry2 (key, this.rootEntry);\n }", "get(key) {\n let node = this.root;\n let i = 0;\n let sameletters = 0;\n while (node && i < key.length) {\n node = node.getNode(key[i]);\n sameletters = 0;\n // need to go one letter at a time\n while (node && key.charAt(i) && node.label.charAt(sameletters) == key.charAt(i)) {\n i++;\n sameletters++;\n }\n }\n return node ? node.value.get(key.substring(i - sameletters)) : undefined;\n }", "getValueFromKey(key) {\r\n if (!(key in this.cache)) return null;\r\n this.updateMostRecent(this.cache[key]);\r\n return this.cache[key].value;\r\n }", "function get_value(key, tree)\n{\n\tlet paths = key.split('.');\n\n\tfor (var i = 0; i < paths.length; i++)\n\t{\n\t\tvar path = paths[i];\n\n\t\t// treat arrays a little differently\n\t\tif (path.indexOf('[') >= 0 && path.indexOf(']') >= 0)\n\t\t{\n\t\t\tvar index = str_utils.between(path, '[', ']');\n\t\t\tvar ary_path = str_utils.replace_last('[' + index + ']', '', path);\n\n\t\t\tif (typeof tree[ary_path] === 'undefined')\n\t\t\t{\n\t\t\t\tthrow \"Invalid path: \" + key;\n\t\t\t}\n\n\t\t\ttree = tree[ary_path];\n\t\t\tpath = index;\n\t\t}\n\n\t\t// we didn't get a valid tree path\n\t\t// so we need to bail now\n\t\tif (typeof tree[path] === 'undefined')\n\t\t{\n\t\t\tthrow 'Invalid path: ' + key;\n\t\t}\n\n\t\ttree = tree[path];\n\n\t}\t\n\n\treturn tree;\n}", "function find(key) {\r\nreturn this.datastore[key];\r\n}", "findValueByKey(array, key) {\n\n for (let i = 0; i < array.length; i++) {\n\n if (array[i][key]) {\n\n return array[i][key];\n }\n }\n return null;\n }", "function get(key) {\n return data[key];\n }", "get(key) {\n const item = this.getItem(key);\n if (item) {\n return item.value;\n }\n return undefined;\n }", "get (key) {\n let hashed = hash(key);\n if(this.buckets[hash % this.buckets.length].key == key)\n return this.buckets[hash % this.buckets.length].value;\n return null;\n }", "find(key) {\n // If the item is found at the root then return that value\n if (this.key == key) {\n return this.value;\n } else if (key < this.key && this.left) {\n return this.left.find(key);\n } else if (key > this.key && this.right) {\n return this.right.find(key);\n } else {\n throw new Error('Key Error');\n }\n }", "function sc_hashtableGet(ht, key) {\n var hash = sc_hash(key);\n if (hash in ht)\n\treturn ht[hash].val;\n else\n\treturn false;\n}", "function retrieve(key) {\r var storage = getStorage();\r var value = null;\r if (key != null && storage != null) {\r value = storage[key]; \r if (value == \"null\") {\r value = null; \r }\r }\r return value;\r}", "function getValue(key, callback) {\n\n\tlog('getting key: ' + key);\n\n\tvar pair = {\n\t\tkey: key,\n\t\tvalue: undefined\n\t};\n\n\tpost('/key-value-store/get.php', JSON.stringify(pair), callback);\n\n}", "get(key) {\n return this.has(key)\n ? this.items[key].value\n : null;\n }", "getValueFromKey(key) {\n if (!(key in this.cache)) return null;\n this.updateMostRecent(this.cache[key]);\n return this.cache[key].value;\n }", "function get(key) {\n return db.get(key);\n}", "get(key) {\n let index = this._hash(key);\n if (this.keyMap[index]) {\n for (let i = 0; i < this.keyMap[index].length; i++) {\n if (this.keyMap[index][i][0] === key) {\n return this.keyMap[index][i][1];\n }\n }\n }\n return undefined;\n }", "function keyValueArrayGet(keyValueArray, key) {\n var index = keyValueArrayIndexOf(keyValueArray, key);\n\n if (index >= 0) {\n // if we found it retrieve it.\n return keyValueArray[index | 1];\n }\n\n return undefined;\n }", "get(key) {\n let index = this._hash(key);\n if (this.keyMap[index]) {\n for (let i = 0; i < this.keyMap[index].length; i++) {\n if (this.keyMap[index][i][0] === key) {\n return this.keyMap[index][i];\n }\n }\n return undefined;\n }\n }", "lookup(k) {\n return this.cache[k].value;\n }", "retrieve(k) {\n var index = getIndexBelowMaxForKey(k, this._limit);\n var indexBucket = this._storage.get(index);\n var result;\n for (var i = 0; i < indexBucket.length; i ++) {\n if (indexBucket[i][0] === k) {\n result = indexBucket[i][1];\n }\n }\n return result;\n }", "function find(key) {\n\treturn this.dataStore[key];\n}", "get(key) {\n let currentState;\n if (this.currentTransactionIndex > -1) {\n currentState = this.applyTransactions();\n } else {\n currentState = this.db;\n }\n\n if (debug) {\n console.log('db: ', currentState, '\\n');\n }\n\n if (currentState.hasOwnProperty(key)) {\n return currentState[key];\n }\n\n return 'NULL';\n }", "find (key) {\n key = toNumber(input);\n let node = this.root;\n while (node != null) {\n if (key < node.key) {\n node = node.left;\n } else if (key > node.key) {\n node = node.right;\n } else {\n return node.value;\n }\n }\n return null;\n }", "function keyValueArrayGet(keyValueArray, key) {\n var index = keyValueArrayIndexOf(keyValueArray, key);\n\n if (index >= 0) {\n // if we found it retrieve it.\n return keyValueArray[index | 1];\n }\n\n return undefined;\n }", "function keyValueArrayGet(keyValueArray, key) {\n var index = keyValueArrayIndexOf(keyValueArray, key);\n\n if (index >= 0) {\n // if we found it retrieve it.\n return keyValueArray[index | 1];\n }\n\n return undefined;\n }", "function getItem(key, callback) {\n switch (dbBackend) {\n // Find the value for this key directly from IndexedDB and pass the\n // value to a callback function.\n case DB_TYPE_INDEXEDDB:\n indexedTransaction('readonly', function getItemBody(store) {\n var request = store.get(key);\n\n request.onsuccess = function getItemOnSuccess() {\n callback(request.result);\n };\n\n request.onerror = _errorHandler(request);\n });\n break;\n // If we're using localStorage, we have to load the value from\n // localStorage, parse the JSON, and then send that value to the\n // callback function.\n case DB_TYPE_LOCALSTORAGE:\n var result = localStorage.getItem(key);\n\n // If a result was found, parse it from serialized JSON into a\n // JS object. If result isn't truthy, the key is likely\n // undefined and we'll pass it straight to the callback.\n if (result) {\n result = JSON.parse(result);\n }\n\n callback(result);\n break;\n }\n }", "retrieve (key) {\n if (_state[key])\n return _state[key];\n return false;\n }", "function getLevelDBData(key){\n db.get(key, function(err, value) {\n if (err) return 'Not found!';\n return value;\n })\n}", "find(key)\r\n {\r\n var list = this.#table[int(this.#hash(key) & this.#divisor)];\r\n var k = list.length, entry;\r\n for (var i = 0; i < k; i++)\r\n {\r\n entry = list[i];\r\n if (entry.key === key)\r\n return entry.data;\r\n }\r\n return null;\r\n }", "function get(x, key) {\n while (x != null && x != undefined) {\n var cmp = key.localeCompare(x.key);\n if (cmp < 0) x = x.left;\n else if (cmp > 0) x = x.right;\n else return x.value;\n }\n return null;\n }", "function getEntryValue(json,key){\n\tvar entry = json[ENTRY];\n\tif(entry != undefined){\n\t\tfor(var i = 0; i < entry.length; i++){\n\t\t\tif(entry[i][KEY] == key){\n\t\t\t\treturn entry[i][VALUE];\n\t\t\t}\n\t\t}\n\t}\n\telse{\n\t\treturn undefined;\n\t}\n}", "function getValue (obj, key) {\n return obj[key]\n}", "function keyValueArrayGet(keyValueArray, key) {\n const index = keyValueArrayIndexOf(keyValueArray, key);\n if (index >= 0) {\n // if we found it retrieve it.\n return keyValueArray[index | 1];\n }\n return undefined;\n}", "function keyValueArrayGet(keyValueArray, key) {\n const index = keyValueArrayIndexOf(keyValueArray, key);\n if (index >= 0) {\n // if we found it retrieve it.\n return keyValueArray[index | 1];\n }\n return undefined;\n}", "function keyValueArrayGet(keyValueArray, key) {\n const index = keyValueArrayIndexOf(keyValueArray, key);\n if (index >= 0) {\n // if we found it retrieve it.\n return keyValueArray[index | 1];\n }\n return undefined;\n}", "function keyValueArrayGet(keyValueArray, key) {\n const index = keyValueArrayIndexOf(keyValueArray, key);\n if (index >= 0) {\n // if we found it retrieve it.\n return keyValueArray[index | 1];\n }\n return undefined;\n}", "function keyValueArrayGet(keyValueArray, key) {\n const index = keyValueArrayIndexOf(keyValueArray, key);\n if (index >= 0) {\n // if we found it retrieve it.\n return keyValueArray[index | 1];\n }\n return undefined;\n}", "function keyValueArrayGet(keyValueArray, key) {\n const index = keyValueArrayIndexOf(keyValueArray, key);\n if (index >= 0) {\n // if we found it retrieve it.\n return keyValueArray[index | 1];\n }\n return undefined;\n}", "function keyValueArrayGet(keyValueArray, key) {\n const index = keyValueArrayIndexOf(keyValueArray, key);\n if (index >= 0) {\n // if we found it retrieve it.\n return keyValueArray[index | 1];\n }\n return undefined;\n}", "function BOT_get(topic,key,tag) {\r\n\tvar ta = BOT_getTopicAttribute(topic, key);\r\n\tif(ta != undefined) return BOT_getTopicAttributeTagValue(ta,tag)\r\n\telse return;\r\n}", "function getByKey (state, torrentKey) {\n if (!torrentKey) return undefined\n return state.saved.torrents.find((x) =>\n x.torrentKey === torrentKey || x.infoHash === torrentKey)\n}", "get(key)\n {\n return this.map.get(key);\n }", "get(key) {\n return this.frame.get(to_key(key));\n }", "getValueByComponentId(componentId) {\n const tuple = this.hashMap.get(componentId.toString());\n if (!tuple) return null;\n return tuple[1];\n }", "function getValue(object, key) {\n return object[key];\n}", "get(k) {\n return this.root.get(k);\n }", "getValue(index) {\n let node = this.findNode(index);\n let data = node ? node.value : undefined;\n return data;\n }", "function findKthLargestValueInBst(tree, k) {\n let treeInfo = new TreeInfo(0, -1)\n reverseInOrderTraverse(tree, k, treeInfo)\n return treeInfo.currVisitedNodeValue\n }", "_findInBucket( bucket, neddle ) {\n return bucket.filter( ([key, value]) => key === neddle )[0] || undefined;\n }", "get(k) {\n return this.kvStore[k];\n }", "function grabKey(obj, key) {\n return obj[key];\n}", "async getItem(tagoRunURL, key) {\n const result = await this.doRequest({\n path: `/run/${tagoRunURL}/sdb/${key}`,\n method: \"GET\",\n });\n return result;\n }", "item(key)\n\t{\n\t\tkey = this.toString(key);\n\t\tif (!super.has(key))\n\t\t{\n\t\t\t/*if (isBrowser()) throw new Runtime.Exceptions.KeyNotFound(key);*/\n\t\t\tvar _KeyNotFound = use(\"Runtime.Exceptions.KeyNotFound\");\n\t\t\tthrow new _KeyNotFound(key);\n\t\t}\n\t\tvar val = super.get(key);\n\t\tif (val === null || val == undefined) return null;\n\t\treturn val;\n\t}", "getStorageItemValue(item_key, key) {\n if (localStorage.getItem(item_key)) {\n var item_value = JSON.parse(localStorage.getItem(item_key));\n var item_index = item_value.findIndex((obj => obj[0] === key));\n return (item_index >= 0) ? item_value[item_index][1] : null;\n }\n else {\n return null;\n }\n }", "function search(nameKey){\n for (var i=0; i < lookup.length; i++) {\n if (lookup[i].key === nameKey) {\n return lookup[i].value;\n }\n }\n}", "get(target, key) {\n if (key in target) {\n return target[key];\n }\n /**\n * If the key is not in the object\n * then access it on the original node object.\n */\n return target.node[key];\n }", "function getValue(key, array){\n\tfor (i in array) {\n\t\tif (array[key]) {\n\t\t\treturn array[key];\n\t\t}\n\t}\n\treturn false;\n}", "function keyValueArrayGet(keyValueArray, key) {\n var index = keyValueArrayIndexOf(keyValueArray, key);\n\n if (index >= 0) {\n // if we found it retrieve it.\n return keyValueArray[index | 1];\n }\n\n return undefined;\n}", "readKeyValue(key) {\n const value = this._data[key];\n if (!value) return value;\n\n // if under mutation and key is model, always return the latest record value\n if (this._store.mutationId) {\n const { type, Type } = this.getKeyDefinition(key);\n if (type === 'model') {\n return Type.findById(value.getId()) || null;\n }\n }\n\n return value;\n }", "get(){return this[key]}", "find(key) {\n // if Item is found at the root, then return that value\n if (this.key == key) {\n return this.value;\n }\n // if item is less than root, go left, if left child exists, then recursively check its left and/or right child\n else if (key < this.key && this.left) {\n return this.left.find(key);\n }\n // same, but right sided\n else if (key > this.key && this.right) {\n return this.right.find(key);\n }\n // Item not found\n else {\n throw new Error(\"Key Error\");\n }\n }", "function getOnTable(key) {\n switch (typeof key) {\n case 'object':\n case 'function': {\n if (null === key) { return myValues.prim_null; }\n var index = getOnKey(key);\n if (void 0 === index) { return void 0; }\n return myValues[index];\n }\n case 'string': { return myValues['str_' + key]; }\n default: { return myValues['prim_' + key]; }\n }\n }", "get(key, keepPair) {\n const pair = findPair(this.items, key);\n return !keepPair && isPair(pair)\n ? isScalar(pair.key)\n ? pair.key.value\n : pair.key\n : pair;\n }", "get() {\n return this[key];\n }", "get() {\n return this[key];\n }", "get() {\n return this[key];\n }", "get(key) {\n const hashCode = this._hash(key);\n if (this.map[hashCode] === undefined) {\n return null;\n }\n\n for (let i = 0; i < this.map[hashCode].length; i += 1) {\n if (this.map[hashCode][i][0] === key) {\n return this.map[hashCode][i][1];\n }\n }\n\n throw new Error(\"hash table contains entry not set by own `set` method\");\n }", "function getMapKey(value) {\n\t return value;\n\t}", "function getMapKey(value) {\n\t return value;\n\t}", "function getMapKey(value) {\n\t return value;\n\t}", "function getMapKey(value) {\n\t return value;\n\t}", "get(key) {\n return this.data[key];\n }", "getData(key) { return this.data[key]; }", "async function getBookObj(isbn){\n if(!isValidIsbn13(isbn)){\n throw \"User gave an invalid ISBN13.\";\n }\n let db = firebase.database();\n let ref = db.ref(\"books\");\n\n \n let result = await ref.orderByChild(\"isbn\").equalTo(isbn).once(\"value\")\n .then (snap => {\n let obj = snap.val()\n console.log(obj)\n console.log(Object.keys(obj)[0])\n console.log(obj[Object.keys(obj)[0]])\n return snap.val();\n })\n .catch(error => {\n console.warn(\"ISBN not in database!\")\n })\n return result;\n \n}", "function key_value(key) {\n return Evaluator.key_value(key);\n}", "function get_(key) {\n return B (function(obj) { return key in obj ? Just (obj[key]) : Nothing; })\n (toObject);\n }" ]
[ "0.69082135", "0.66037124", "0.6554713", "0.6547571", "0.6547571", "0.6547571", "0.6524139", "0.6487748", "0.6482123", "0.64602643", "0.6368417", "0.63241535", "0.62833166", "0.6265976", "0.6261236", "0.6259042", "0.62365997", "0.6220131", "0.6198753", "0.61806655", "0.60993105", "0.6095039", "0.6092602", "0.6081338", "0.60733867", "0.60663205", "0.6064358", "0.6053568", "0.6037013", "0.6034648", "0.6026996", "0.60175085", "0.60093826", "0.6008808", "0.5987691", "0.5985675", "0.5982124", "0.59651434", "0.59638655", "0.5922125", "0.5922029", "0.5898245", "0.5878243", "0.58775204", "0.5877263", "0.5871415", "0.58673555", "0.5850062", "0.5849981", "0.5849981", "0.5840435", "0.58392215", "0.5834021", "0.5822428", "0.58124685", "0.5801624", "0.57984", "0.5768416", "0.5768416", "0.5768416", "0.5768416", "0.5768416", "0.5768416", "0.5768416", "0.57665277", "0.57635796", "0.57592124", "0.57543683", "0.57532233", "0.5747196", "0.5739595", "0.5738303", "0.5736085", "0.5735353", "0.5726026", "0.5725708", "0.5722189", "0.57117957", "0.5707634", "0.56993675", "0.56961817", "0.5687185", "0.5683751", "0.5667127", "0.56513405", "0.5636023", "0.5630993", "0.5629094", "0.5628331", "0.5628331", "0.5628331", "0.5618936", "0.5618921", "0.5618921", "0.5618921", "0.5618921", "0.5613029", "0.5611389", "0.56090325", "0.56014574", "0.559856" ]
0.0
-1
delete minimum node animate
animateDeleteMin() { const animations = []; animations.push(new Animation("display", "Deleting Min", "")); this.root = this.animateDeleteMinHelper(this.root, animations); this.positionReset(); // reset x,y positions of nodes animations[animations.length - 1].setClass("found-node"); animations.push(new Animation("display", "Deleted Min", "")); return animations; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "deleteMin() {\r\n this.root = this.animateDeleteMinHelper(this.root);\r\n }", "animateDeleteMax() {\r\n const animations = [];\r\n animations.push(new Animation(\"display\", \"Deleting Max\", \"\"));\r\n\r\n this.root = this.animateDeleteMaxHelper(this.root, animations);\r\n this.positionReset(); // reset x,y positions of nodes\r\n\r\n animations[animations.length - 1].setClass(\"found-node\");\r\n\r\n animations.push(new Animation(\"display\", \"Deleted Max\", \"\"));\r\n\r\n return animations;\r\n }", "function deleteNode( node ) {\n\t\n\tLog(\"Deleting Node \" + node.id);\n\t\n\telements_in_canvas[node.id] = null;\n\tnodes_in_canvas_by_id[node.id] = null;\n\tnodes_in_canvas.splice( nodes_in_canvas.indexOf( node ), 1 );\n\t\n\tif (node.animationParent) {\n\t node.animationParent.animationChildren[node.id] = null;\n\t}\n\t\n\tnode.deleteNode();\n\t\n}", "removeNode(g, n) { }", "removeNode(g, n) { }", "async function deleteStackNode() {\n let pos = stack.size - 1;\n d3.select(\"#g\" + pos)\n .transition()\n .ease(d3.easeExp)\n .duration(500)\n\n .attr(\"transform\", \"translate(0,0)\")\n .style(\"opacity\", 0);\n await timeout(510);\n d3.select(\"#g\" + pos).remove();\n data_nodes.pop();\n}", "function deleteMin(node) {\n if (node.left == null) return node.right;\n node.left = deleteMin(node.left);\n node.size = size(node.left) + size(node.right) + 1;\n return node;\n}", "function GoneNode(id) {\n $('.grid').isotope( 'remove', $(\"#node-\" + id)).isotope('layout')\n delete nodes_by_id[id] // Don't change indices\n delete nodes[name]\n delete charts[id]\n setNodes()\n}", "function checkAndDeleteSecondNode(player, node){\n if(nodeToDelete != null && node.key != 'null'){\n var key = min(nodeToDelete.right);\n if(node.key == key){\n\n if (nodeToDelete.right.left.key == 'null') { // when nodeToDelete's right child IS min (move min and its right subtree up)\n\n // DISABLE KEYBOARD\n this.input.keyboard.enabled = false;\n\n // hide links:\n if (nodeToDelete.parent != null) {\n this.add.tween({\n targets: [nodeToDelete.link],\n ease: 'Sine.easeOut',\n duration: 1000,\n alpha: '-=1'\n });\n }\n\n this.add.tween({\n targets: [nodeToDelete.left.link, nodeToDelete.right.link, node.left.link],\n ease: 'Sine.easeOut',\n duration: 1000,\n alpha: '-=1'\n });\n\n // nodes and their components:\n this.add.tween({\n targets: [nodeToDelete.nodeGraphics, nodeToDelete.curtain, nodeToDelete.keyString, node.left.nullGraphics, node.left.keyString],\n delay: 1000,\n ease: 'Sine.easeOut',\n duration: 1000,\n alpha: '-=1'\n });\n\n // destroy left child(null) of 15 and update some stuff\n this.time.addEvent({\n delay: 2100,\n callback: function(nodeToDelete,node) {\n node.left.destroyNode(); // destroy null left child of 15\n node.left = null;\n node.parent = nodeToDelete.parent; // set 15s parent as what 10 had (null) || set 25s parent to 15\n node.dpth = nodeToDelete.dpth;\n },\n args: [nodeToDelete,node]\n });\n\n // abs(10 x - 15 x) + node x\n this.time.addEvent({\n delay: 2500,\n callback: function(nodeToDelete,node,scene) {\n var distanceX = Math.abs(nodeToDelete.posX-node.posX);\n // Version 2\n updateBranch(node,distanceX);\n },\n args: [nodeToDelete,node,this]\n });\n\n // Version 2\n this.time.addEvent({\n delay: 3000,\n callback: function(nodeToDelete,node,scene) {\n var distanceX = Math.abs(nodeToDelete.posX-node.posX);\n\n if (nodeToDelete == tree.root) { // if deleted node is root\n tree.root = node;\n node.left = nodeToDelete.left; // move 10's left branch to 15\n node.left.parent = node; // change left branch's parent to 15\n } else if (nodeToDelete == nodeToDelete.parent.right){ // if deleted node is right child\n node.left = nodeToDelete.left; // set 25s left to 16 (move 20's left branch to 25)\n node.left.parent = node; // set 16s parent to 25 (change left branch's parent to 25)\n node.parent.right = node; // set 15's right child to 25\n } else if (nodeToDelete == nodeToDelete.parent.left) { // if deleted node is left child\n node.left = nodeToDelete.left;\n node.left.parent = node;\n node.parent.left = node; \n }\n node.distanceFromParent = nodeToDelete.distanceFromParent;\n tree.updateNodeDepths(tree.root);\n // nodeToDelete.destroyNode();\n\n tree.traverseAndCheckCollisions(scene);\n tree.traverseAndCheckCrossings(scene);\n\n scene.add.tween({\n targets: player,\n x: node.posX, // if 15 is on left branch then we should do +\n y: node.posY - BUFFER, // 10 is Buffer\n ease: 'Power2',\n duration: 1500,\n });\n\n actuallyMoveBranch(node,distanceX,scene);\n\n // TODO: ROTATE node.right.link and after it is rotated then redraw to extend:\n // node.right.link.setAlpha(0);\n // move node link, rotate it and extend it\n if (node.right.link != null) {\n\n var N = node.right.distanceFromParent;\n \n var O = null;\n if (node.right.distanceFromParent < 0) {\n O = (node.right.link.x - node.right.link.width) - node.right.link.x;\n } else {\n O = (node.right.link.x + node.right.link.width) - node.right.link.x;\n }\n \n var oldAngle = calcAngle(tree.z,O);\n var newAngle = calcAngle(tree.z,N);\n var difference = oldAngle - newAngle;\n \n scene.add.tween({\n targets: node.right.link,\n x: node.right.posX, \n y: node.right.posY,\n ease: 'Power2',\n duration: 1500\n });\n \n if (difference != 0) {\n // ROTATION TWEEN:\n scene.add.tween({\n targets: node.right.link,\n angle: -difference,\n ease: 'Sine.easeInOut',\n duration: 1500,\n onComplete: drawLink,\n onCompleteParams: [node.right,scene]\n });\n \n function drawLink(tween,targets,node,scene) {\n node.drawLinkToParent(scene);\n }\n }\n }\n // appearLinks(node,scene);\n },\n args: [nodeToDelete,node,this]\n });\n\n // need to appear movedNodes's link to parent and left link\n\n this.time.addEvent({\n delay: 4500,\n callback: function(node,scene) {\n node.drawLinkToParent(scene);\n node.link.setAlpha(0);\n node.left.drawLinkToParent(scene);\n node.left.link.setAlpha(0);\n scene.add.tween({\n targets: [node.link, node.left.link],\n ease: 'Sine.easeIn',\n duration: 1000,\n alpha: '+=1'\n });\n \n },\n args: [node,this]\n });\n // end of Version 2\n\n this.time.addEvent({\n delay: 5800,\n callback: function(node,scene) {\n nodeToDelete.destroyNode();\n nodeToDelete = null;\n tree.updateNodeDepths(node);\n // Version 2\n // A way to move the branch together with already expanded branch:\n // in moveBranch only update the posX - line 643\n // then check for collisions - line \n // then actually move the branch nodes (change x to updated posX) - line\n // redraw\n tree.traverseAndCheckCollisions(scene);\n tree.traverseAndCheckCrossings(scene);\n tree.redraw(scene);\n },\n args: [node,this]\n });\n\n this.time.addEvent({\n delay: 7500,\n callback: function(scene) {\n taskSucceededActions(scene);\n displayTask(scene);\n // ENABLE KEYBOARD\n scene.input.keyboard.enabled = true;\n },\n args: [this]\n });\n \n \n } else if (nodeToDelete.right.left.key != 'null') { // when nodeToDelete's right child's left exists (it means there will be a min somewhere on the left from right child)\n\n var nodeToUseForAppear = node.parent;\n\n // DISABLE KEYBOARD\n this.input.keyboard.enabled = false;\n\n // hide links:\n if (nodeToDelete.parent != null) {\n this.add.tween({\n targets: [nodeToDelete.link],\n ease: 'Sine.easeOut',\n duration: 1000,\n alpha: '-=1'\n });\n }\n\n this.add.tween({\n targets: [nodeToDelete.left.link, nodeToDelete.right.link, node.left.link, node.right.link, node.link],\n ease: 'Sine.easeOut',\n duration: 1000,\n alpha: '-=1'\n });\n\n // when min doesn't have children on the right\n if (node.right.key == 'null') {\n\n // hide nodes and their components:\n this.add.tween({\n targets: [nodeToDelete.nodeGraphics, nodeToDelete.curtain, nodeToDelete.keyString, node.left.nullGraphics, node.left.keyString, node.right.nullGraphics, node.right.keyString],\n delay: 1000,\n ease: 'Sine.easeOut',\n duration: 1000,\n alpha: '-=1'\n });\n \n // create null for 20 and destroy 16's both null children and update some stuff\n this.time.addEvent({\n delay: 2100,\n callback: function(nodeToDelete,node,scene) {\n // make null for 20\n var childL = new NodeBST(scene, singleTon.deleteMinColor, node.parent.posX-tree.w, node.parent.posY+tree.z, 'null',node.parent.dpth+1,node.parent);\n childL.distanceFromParent = -tree.w;\n node.parent.left = childL;\n childL.nullGraphics.setAlpha(0);\n childL.keyString.setAlpha(0);\n childL.link.setAlpha(0);\n\n tree.checkCollisions(childL);\n\n // teleporting + curtains\n childL.setPhysicsNode(cursors,player,scene);\n\n // physics\n scene.physics.add.overlap(player, childL, deleteNode, backspaceIsPressed, scene);\n scene.physics.add.overlap(player, childL, checkAndDeleteSecondNode, mIsPressed, scene);\n scene.physics.add.collider(player, childL);\n \n node.left.destroyNode(); // destroy null left child of 16\n node.right.destroyNode(); // destroy null right child of 16\n node.left = null;\n node.right = null;\n node.parent = nodeToDelete.parent; // set 16s parent as what 15 had (null)\n node.dpth = nodeToDelete.dpth;\n },\n args: [nodeToDelete,node,this]\n });\n\n // move 16 to the place of 15\n this.time.addEvent({\n delay: 2500,\n callback: function(nodeToDelete,node,scene) {\n \n // player moves up\n scene.add.tween({\n targets: player,\n x: nodeToDelete.x,\n y: nodeToDelete.y - BUFFER,\n ease: 'Power2',\n duration: 1500,\n });\n \n // 16 shape and curtain moves up\n scene.add.tween({\n targets: [node, node.nodeGraphics, node.curtain],\n x: nodeToDelete.x,\n y: nodeToDelete.y, \n ease: 'Power2',\n duration: 1500,\n });\n \n var distanceX = Math.abs(node.keyString.x-node.posX);\n \n // 16s keystring moves up\n scene.add.tween({\n targets: node.keyString,\n x: nodeToDelete.x - distanceX,\n y: nodeToDelete.keyString.y, // - (tree.z*(node.dpth-nodeToDelete.dpth))\n ease: 'Power2',\n duration: 1500,\n });\n\n // draw 16s link to parent, update physics bodies\n scene.time.addEvent({\n delay: 1500,\n callback: function(node,scene) {\n node.drawLinkToParent(scene);\n node.link.setAlpha(0);\n node.body.updateFromGameObject();\n node.curtain.body.updateFromGameObject();\n },\n args: [node,scene]\n });\n\n // update 16s x and y\n node.posX = nodeToDelete.posX;\n node.posY = nodeToDelete.posY;\n\n },\n args: [nodeToDelete,node,this]\n });\n\n this.time.addEvent({\n delay: 4500,\n callback: function(nodeToUseForAppear,nodeToDelete,node,scene) {\n if (nodeToDelete == tree.root) { // if deleted node is root\n tree.root = node;\n node.left = nodeToDelete.left;\n node.left.parent = node;\n node.right = nodeToDelete.right;\n node.right.parent = node;\n } else if (nodeToDelete == nodeToDelete.parent.right){ // if deleted node is right child\n node.left = nodeToDelete.left;\n node.left.parent = node;\n node.right = nodeToDelete.right;\n node.right.parent = node;\n node.parent.right = node;\n } else if (nodeToDelete == nodeToDelete.parent.left) { // if deleted node is left child\n node.left = nodeToDelete.left;\n node.left.parent = node;\n node.right = nodeToDelete.right;\n node.right.parent = node;\n node.parent.left = node; \n }\n\n // put/appear null on the left of 20\n scene.add.tween({\n targets: [nodeToUseForAppear.left.nullGraphics, nodeToUseForAppear.left.nodeGraphics, nodeToUseForAppear.left.keyString],\n ease: 'Sine.easeIn',\n duration: 1000,\n alpha: '+=1'\n });\n\n node.distanceFromParent = nodeToDelete.distanceFromParent;\n \n if (node.parent != null) {\n scene.add.tween({\n targets: [node.link],\n delay: 1000,\n ease: 'Sine.easeOut',\n duration: 1000,\n alpha: '+=1'\n });\n }\n\n scene.add.tween({\n targets: [node.left.link, node.right.link, nodeToUseForAppear.left.link], //node.right.left.link\n delay: 1000,\n ease: 'Sine.easeOut',\n duration: 1000,\n alpha: '+=1'\n });\n\n tree.updateNodeDepths(tree.root);\n nodeToDelete.destroyNode();\n },\n args: [nodeToUseForAppear,nodeToDelete,node,this]\n });\n\n this.time.addEvent({\n delay: 8000,\n callback: function(node,scene) {\n nodeToDelete = null;\n tree.updateNodeDepths(node);\n tree.traverseAndCheckCollisions(scene);\n tree.traverseAndCheckCrossings(scene);\n tree.redraw(scene); \n },\n args: [node,this]\n });\n\n } else if (node.right.key != 'null') { // when min has children on the right (need to move the right branch up)\n \n // hide nodes and their components:\n this.add.tween({\n targets: [nodeToDelete, nodeToDelete.nodeGraphics, nodeToDelete.curtain, nodeToDelete.keyString, node.left, node.left.nullGraphics, node.left.keyString],\n delay: 1000,\n ease: 'Sine.easeOut',\n duration: 1000,\n alpha: '-=1'\n });\n\n this.time.addEvent({\n delay: 2100,\n callback: function(nodeToDelete,node,scene) {\n node.left.destroyNode(); // node is min. we destroy its left child because it wont be needed anymore/it will be replaced\n node.left = null;\n node.parent = nodeToDelete.parent;\n node.dpth = nodeToDelete.dpth;\n },\n args: [nodeToDelete,node,this]\n });\n\n this.time.addEvent({\n delay: 2500,\n callback: function(nodeToDelete,node,scene) {\n \n // player moves up\n scene.add.tween({\n targets: player,\n x: nodeToDelete.x,\n y: nodeToDelete.y - BUFFER,\n ease: 'Power2',\n duration: 1500,\n });\n \n // 11 shape and curtain moves up\n scene.add.tween({\n targets: [node, node.nodeGraphics, node.curtain],\n x: nodeToDelete.x,\n y: nodeToDelete.y, \n ease: 'Power2',\n duration: 1500,\n });\n \n var distanceX = Math.abs(node.keyString.x-node.posX);\n \n // 11s keystring moves up\n scene.add.tween({\n targets: node.keyString,\n x: nodeToDelete.x - distanceX,\n y: nodeToDelete.keyString.y, // - (tree.z*(node.dpth-nodeToDelete.dpth))\n ease: 'Power2',\n duration: 1500,\n });\n\n // draw 11s link to parent, update physics bodies\n scene.time.addEvent({\n delay: 1500,\n callback: function(node,scene) {\n // node.drawLinkToParent(scene);\n // node.link.setAlpha(0);\n node.body.updateFromGameObject();\n node.curtain.body.updateFromGameObject();\n },\n args: [node,scene]\n });\n\n },\n args: [nodeToDelete,node,this]\n });\n\n this.time.addEvent({\n delay: 4500,\n callback: function(nodeToUseForAppear,nodeToDelete,node,scene) {\n\n var distanceX = Math.abs(node.posX-node.right.posX);\n \n updateBranch(node.right,distanceX); //v2\n\n // update 11s x and y - just to be sure it doesn't get updated before moveBranch \n node.posX = nodeToDelete.posX;\n node.posY = nodeToDelete.posY;\n\n // draw 11s links - have to have it here after we update 11s posX and posY\n node.drawLinkToParent(scene);\n node.link.setAlpha(0);\n \n // update 12s distance from parent\n node.right.distanceFromParent = node.distanceFromParent; // <-- 11s.distancefromparent // nodeToUseForAppear.left.distanceFromParent; <-- 13s.left\n nodeToUseForAppear.left = node.right; // here nodeToUseForAppear is the parent of node(min)\n node.right.parent = nodeToUseForAppear;\n\n if (nodeToDelete == tree.root) { // if deleted node is root\n tree.root = node;\n node.left = nodeToDelete.left;\n node.left.parent = node;\n node.right = nodeToDelete.right;\n node.right.parent = node;\n } else if (nodeToDelete == nodeToDelete.parent.right){ // if deleted node is right child\n node.left = nodeToDelete.left;\n node.left.parent = node;\n node.right = nodeToDelete.right;\n node.right.parent = node;\n node.parent.right = node;\n } else if (nodeToDelete == nodeToDelete.parent.left) { // if deleted node is left child\n node.left = nodeToDelete.left;\n node.left.parent = node;\n node.right = nodeToDelete.right;\n node.right.parent = node;\n node.parent.left = node; \n }\n\n // update distancefromparent for 11\n node.distanceFromParent = nodeToDelete.distanceFromParent;\n\n\n // tree.updateNodeDepths(node.right);\n tree.updateNodeDepths(tree.root);\n\n tree.traverseAndCheckCollisions(scene); //v2\n tree.traverseAndCheckCrossings(scene); //v2\n\n actuallyMoveBranch(nodeToUseForAppear.left,distanceX,scene); //v2\n\n // appearLinks(node.right, scene);\n\n node.drawLinkToParent(scene);\n node.link.setAlpha(0);\n nodeToUseForAppear.left.drawLinkToParent(scene);\n nodeToUseForAppear.left.link.setAlpha(0);\n \n if (node.parent != null) {\n scene.add.tween({\n targets: [node.link],\n delay: 1500,\n ease: 'Sine.easeOut',\n duration: 1000,\n alpha: '+=1'\n });\n }\n\n scene.add.tween({\n targets: [node.left.link, node.right.link, nodeToUseForAppear.left.link], //node.right.left.link\n delay: 1500,\n ease: 'Sine.easeOut',\n duration: 1000,\n alpha: '+=1'\n });\n\n // tree.updateNodeDepths(tree.root);\n nodeToDelete.destroyNode();\n },\n args: [nodeToUseForAppear,nodeToDelete,node,this]\n });\n\n this.time.addEvent({\n delay: 7000,\n callback: function(nodeToUseForAppear,node,scene) {\n nodeToDelete = null;\n tree.updateNodeDepths(node);\n tree.traverseAndCheckCollisions(scene);\n tree.traverseAndCheckCrossings(scene);\n tree.redraw(scene); \n },\n args: [nodeToUseForAppear,node,this]\n });\n\n } //end of else if\n\n this.time.addEvent({\n delay: 8000,\n callback: function(scene) {\n taskSucceededActions(scene);\n displayTask(scene);\n // ENABLE KEYBOARD\n scene.input.keyboard.enabled = true;\n },\n args: [this]\n });\n\n\n } //end of else if\n\n } else {\n panel.redFeedback();\n player.setPosition(nodeToDelete.x,nodeToDelete.y-BUFFER);\n tree.closeCurtains()\n }\n }\n }", "removeMin() {\r\n\t\tthis.remove(this.heap[0]);\r\n\t}", "function animateRemoveNode(node) {\n return new Promise(function(resolve) {\n node.style.animation = 'circle ' + (removeNodeSpeed/1000) +'s linear';\n setTimeout(() => {\n node.style.animation = null;\n resolve();\n }, removeNodeSpeed);\n });\n}", "removeNode(node) {\n this.nodes.splice(this.nodes.indexOf(node), 1);\n this.svgsManager.nodeManager.update();\n }", "anchoredNodeRemoved(node) {}", "function node_delete(_nodeindex){\r\n\tvar currentnode = nodes[_nodeindex];\r\n\tvar temp = delete_relatededges(currentnode, edges, edges_tangents);\r\n\tedges = temp.edges;\r\n\tedges_tangents = temp.edges_tangents;\r\n\tif(matchnodeindex(nodes,currentnode.id)>= 0 & matchnodeindex(nodes,currentnode.id)< nodes.length){\r\n\t\tswitch (currentnode.type){\r\n\t\t\tcase \"ellipse\": \r\n\t\t\t\tnumElli--;\r\n\t\t\t\tnumNode--;\t\t\t\r\n\t\t\t\tbreak;\r\n\t\t\tcase \"rect\":\r\n\t\t\t\tnumRec--;\r\n\t\t\t\tnumNode--;\t\t\t\t\r\n\t\t\t\tbreak;\r\n\r\n\t\t\tcase \"triangle\":\r\n\t\t\t\tnumTri--;\r\n\t\t\t\tnumNode--;\r\n\t\t\t\tbreak;\r\n\r\n\t\t\tdefault:;\r\n\t\t}//end of switch (_type) \r\n\t\tnodes.splice(_nodeindex,1);\r\n\t}\r\n}", "remove() {\n this.node.remove()\n }", "destroy() {\n nodes.splice(nodes.indexOf(el), 1);\n }", "function removeNode(){\n\tfadeOut();\n\tif (state === true) {\n\t\tmakeRequest();\n\t}\n}", "function outNode(){\n\t\ttooltipsvg\n\t\t.style(\"opacity\", 0)\n\t\t.attr(\"width\",0)\n\t\t.attr(\"height\",0)\n\t\t.selectAll(\"*\").remove();;\n\t}", "function deleteStart() {\n var child = starter.lastElementChild;\n starter.removeChild(child);\n}", "function deleteNode(player, node) {\n if (nodeToDelete == null && tasks.length != 0) {\n // (node.key != 'null') \n if (node.key != 'null' && (tasks[0] == node.key || (tasks[0] == 'Min' && node.key == min(tree.root)) || (tasks[0] == 'Max' && node.key == max(tree.root))) && nodeToDelete == null) {\n if (node.left.key =='null' && node.right.key =='null') { // both children are null \n\n // DISABLE KEYBOARD\n this.input.keyboard.enabled = false;\n\n if (node.parent != null) {\n player.setPosition(node.parent.posX,node.parent.posY-BUFFER);\n }\n\n // node.left, node.right, node\n // hide links and nodes\n this.add.tween({\n targets: [node.left.link, node.right.link, node.left.nullGraphics, node.right.nullGraphics, node.nodeGraphics, node.keyString, node.left.keyString,node.right.keyString],\n ease: 'Sine.easeOut',\n duration: 1000,\n alpha: '-=1'\n });\n\n this.time.addEvent({\n delay: 1000,\n callback: function(node) {\n node.setKey('null');\n node.setNullGraphics();\n node.nullGraphics.setAlpha(0);\n node.left.destroyNode();\n node.right.destroyNode();\n node.setChildren(); // set children as null\n },\n args: [node]\n });\n\n this.add.tween({\n targets: [node.nullGraphics, node.keyString],\n ease: 'Sine.easeIn',\n delay: 2000,\n duration: 1000,\n alpha: '+=1',\n // onComplete: taskSucceededActions(this),\n // onCompleteParams: [this]\n });\n\n this.time.addEvent({\n delay: 4000,\n callback: function(scene) {\n // ENABLE KEYBOARD\n taskSucceededActions(scene)\n scene.input.keyboard.enabled = true;\n // displayTask();\n },\n args: [this]\n });\n\n } else if (node.right.key == 'null' || node.left.key == 'null') { // one child is null\n\n // DISABLE KEYBOARD\n this.input.keyboard.enabled = false;\n\n if (node.right.key == 'null') { // right child is null\n\n player.setPosition(node.left.x,node.left.y-BUFFER);\n\n // hide links\n this.add.tween({\n targets: [node.left.link, node.right.link, node.link],\n ease: 'Sine.easeOut',\n duration: 1000,\n alpha: '-=1'\n });\n\n // hide right null of deleted node and the deleted node\n this.add.tween({\n targets: [node.right.nullGraphics, node.nodeGraphics, node.keyString, node.right.keyString],\n ease: 'Sine.easeOut',\n duration: 1000,\n alpha: '-=1'\n });\n\n // branch moves to the right\n this.time.addEvent({\n delay: 1000,\n callback: function(node,scene) {\n\n if (node.parent == null) {\n node.left.parent = null;\n tree.root = node.left;\n tree.root.dpth = 0;\n } else if (node.parent.left == node) {\n node.parent.left = node.left;\n node.left.parent = node.parent;\n } else if (node.parent.right == node) {\n node.parent.right = node.left;\n node.left.parent = node.parent;\n }\n \n var distanceX = node.left.posX-node.posX;\n // moveBranch(node.left,distanceX,scene); //v1\n updateBranch(node.left,distanceX); //v2\n\n // TO PREVENT COLLAPSING:\n node.left.distanceFromParent = node.distanceFromParent;\n\n tree.updateNodeDepths(node.left); // starting from 9 (the node that changes deleted node)\n\n tree.traverseAndCheckCollisions(scene); //v2\n tree.traverseAndCheckCrossings(scene); //v2\n\n // player moves up\n scene.add.tween({\n targets: player,\n x: node.left.posX,\n y: node.left.posY - BUFFER,\n ease: 'Power2',\n duration: 1500,\n });\n\n actuallyMoveBranch(node.left,distanceX,scene); //v2\n\n // // destroy 15.right\n // node.right.destroyNode();\n // // destroy 15\n // node.destroyNode();\n },\n args: [node,this]\n });\n\n // appear link that changed\n this.time.addEvent({\n delay: 2500,\n callback: function(scene,node) {\n\n node.left.drawLinkToParent(scene);\n node.left.link.setAlpha(0);\n scene.add.tween({\n targets: node.left.link,\n ease: 'Sine.easeIn',\n duration: 1000,\n alpha: '+=1'\n });\n\n },\n args: [this,node]\n });\n\n // move player to root, update tasks, enable keyboard\n this.time.addEvent({\n delay: 3000,\n callback: function(scene) {\n tree.traverseAndCheckCollisions(scene);\n tree.traverseAndCheckCrossings(scene);\n // tree.traverseAndCheckCrossings(scene);\n\n tree.redraw(scene);\n\n // appearLinksOneChild(node.left, scene);\n // destroy 15.right\n node.right.destroyNode();\n // destroy 15\n node.destroyNode();\n\n },\n args: [this]\n });\n\n } else { // left child is null\n\n player.setPosition(node.right.x,node.right.y-BUFFER);\n\n // hide links\n this.add.tween({\n targets: [node.left.link, node.right.link, node.link],\n ease: 'Sine.easeOut',\n duration: 1000,\n alpha: '-=1'\n });\n\n // hide left null of deleted node and the deleted node\n this.add.tween({\n targets: [node.left.nullGraphics, node.nodeGraphics, node.keyString, node.left.keyString],\n ease: 'Sine.easeOut',\n duration: 1000,\n alpha: '-=1'\n });\n\n // branch moves to the left up\n this.time.addEvent({\n delay: 1000,\n callback: function(node,scene) {\n\n if (node.parent == null) {\n node.right.parent = null;\n tree.root = node.right;\n tree.root.dpth = 0;\n } else if (node.parent.left == node) {\n node.parent.left = node.right;\n node.right.parent = node.parent;\n } else if (node.parent.right == node) {\n node.parent.right = node.right;\n node.right.parent = node.parent;\n }\n\n // TODO:\n // not here:\n // 2.the collisions are checked only once? the crossings are not checked?\n\n var distanceX = node.right.posX-node.posX;\n // moveBranch(node.right,distanceX,scene); //v1\n updateBranch(node.right,distanceX); //v2\n\n // TO PREVENT COLLAPSING:\n node.right.distanceFromParent = node.distanceFromParent;\n\n tree.updateNodeDepths(node.right); // starting from 33 (the node that changes deletd node)\n\n tree.traverseAndCheckCollisions(scene); //v2\n tree.traverseAndCheckCrossings(scene); //v2\n\n // player moves up\n scene.add.tween({\n targets: player,\n x: node.right.posX,\n y: node.right.posY - BUFFER,\n ease: 'Power2',\n duration: 1500,\n });\n actuallyMoveBranch(node.right,distanceX,scene); //v2\n\n // appearLinks(node.right, scene);\n\n // // destroy 24.left\n // node.left.destroyNode();\n // // destroy 24\n // node.destroyNode();\n },\n args: [node,this]\n });\n\n // appear link that changed\n this.time.addEvent({\n delay: 2500,\n callback: function(scene,node) {\n\n node.right.drawLinkToParent(scene);\n node.right.link.setAlpha(0);\n scene.add.tween({\n targets: node.right.link,\n ease: 'Sine.easeIn',\n duration: 1000,\n alpha: '+=1'\n });\n\n },\n args: [this,node]\n });\n\n // move player to root, update tasks, enable keyboard\n this.time.addEvent({\n delay: 3500,\n callback: function(scene) {\n tree.traverseAndCheckCollisions(scene);\n tree.traverseAndCheckCrossings(scene);\n // tree.traverseAndCheckCrossings(scene);\n \n tree.redraw(scene);\n \n // appearLinksOneChild(node.right, scene);\n // destroy 24.left\n node.left.destroyNode();\n // destroy 24\n node.destroyNode();\n \n },\n args: [this]\n });\n } //end of if else\n \n\n this.time.addEvent({\n delay: 6000,\n callback: function(scene) {\n taskSucceededActions(scene);\n // ENABLE KEYBOARD\n scene.input.keyboard.enabled = true;\n },\n args: [this]\n });\n } else { // both children are NOT null\n // setting a value of nodeToDelete to use it after user clicks Enter\n nodeToDelete = node;\n nodeToDelete.nodeGraphics.setTint(0xf3a6ff);\n if(nodeToDelete.key == 631) {\n if (expert.progressCounter <= 2) {\n talkNodes.shift();\n }\n expert.progressCounter = 3;\n expert.talk('deleteTwoChildren',3,'nosymbol');\n }\n }\n } else {\n panel.redFeedback();\n player.setPosition(tree.root.x,tree.root.y-BUFFER);\n tree.closeCurtains()\n\n\n }\n }\n }", "remove() {\n this.parent.removeTween(this);\n }", "animateDelete(key) {\r\n const animations = [];\r\n animations.push(new Animation(\"display\", `Deleting ${key}`));\r\n\r\n this.root = this.animateDeleteHelper(this.root, key, animations);\r\n this.positionReset(); // reset x,y positions of nodes\r\n\r\n // highlight last node in green if found\r\n if (compareTo(animations[animations.length - 1].getItem(), key) === 0) {\r\n animations[animations.length - 1].setClass(\"found-node\");\r\n animations.push(new Animation(\"display\", `Deleted ${key}`));\r\n return [key, animations];\r\n } // highlight last node in red if not found\r\n else {\r\n animations[animations.length - 1].setClass(\"search-failed-node\");\r\n animations.push(new Animation(\"display\", \"Not Found\"));\r\n\r\n return [null, animations];\r\n }\r\n }", "function deleteNode(node) {\n\n // delete link, tubes and cables\n spliceLinksForNode(node);\n\n // delete node\n nodes.splice(nodes.indexOf(node), 1);\n\n correctID();\n\n updateMatrix();\n\n // close the modal box\n closeModal();\n\n // redraw\n restart();\n}", "function _deleteNode() {\n const id = diagram.selection.toArray()[0].key;\n const node = diagram.findNodeForKey(id);\n diagram.startTransaction();\n diagram.remove(node);\n diagram.commitTransaction(\"deleted node\");\n diagramEvent()\n}", "handleDelete() {\n API.deleteNode(this.props.node).then(() => {\n this.props.node.remove();\n this.props.engine.repaintCanvas();\n }).catch(err => console.log(err));\n }", "function delFrom_cum() {\n if (cumRows > 1 && transitioning == false) {\n\n // delete the row\n cumRows--;\n var cumRowsObj = document.getElementById(\"cumRows\");\n cumRowsObj.lastChild.className = \"cumRow toHide\";\n\n // perform transition\n transitioning = true;\n setTimeout(function() { delRow(cumRowsObj); }, 500);\n\n }\n}", "clear () {\n this.control.disable();\n while (this.nodes.length) this.nodes[this.nodes.length-1].remove();\n this.control.enable();\n }", "resetTree() {\n this.root.nodes.forEach((node) => { var _a; return (_a = node.currentAnimation) === null || _a === void 0 ? void 0 : _a.stop(); });\n this.root.nodes.forEach(clearMeasurements);\n this.root.sharedNodes.clear();\n }", "function delRow(row) {\n row.removeChild(row.lastChild);\n transitioning = false;\n recalc();\n}", "function delete_circle() {\r\n\t$('#drag_resize').css({\"display\":\"none\"});\r\n}", "function deleteLastPosition() {\r\n\t//delete the trace of the block in the matrix\r\n\tmatrix[lastY][lastX] = 0;\r\n\tvar parent = document.getElementsByClassName('coll-' + lastX)[lastY - 1];\r\n\tparent.removeChild(parent.children[0]);\r\n}", "function deleteMin(h) { \n if (h.left == null || h.left == undefined)\n return null;\n\n if (!isRed(h.left) && !isRed(h.left.left))\n h = moveRedLeft(h);\n\n h.left = deleteMin(h.left);\n return balance(h);\n }", "removeNode(node) {\n if (nodesCount > 0) { nodesCount -= 1; }\n if (node.id < nodesCount && nodesCount > 0) {\n // we do not really delete anything from the buffer.\n // Instead we swap deleted node with the \"last\" node in the\n // buffer and decrease marker of the \"last\" node. Gives nice O(1)\n // performance, but make code slightly harder than it could be:\n webglUtils.copyArrayPart(nodes, node.id * ATTRIBUTES_PER_PRIMITIVE, nodesCount * ATTRIBUTES_PER_PRIMITIVE, ATTRIBUTES_PER_PRIMITIVE);\n }\n }", "remove() {\n if (!this.value) {\n this.value = this.min || 0;\n }\n const step = this.ctrl_key ? 100 : this.shift_key ? 10 : this.step || 1;\n this.value -= step;\n if (this.value < this.min) {\n this.value = this.min || 0;\n }\n this.setValue(this.value);\n }", "function removeNodeOnto(index){\n if(index>=0 && index<node_dataOnto.length){\n removeAllEdgesOnto(index);\n for(var i = 0;i<node_dataOnto.length;i++){\n if(i>index){\n node_dataOnto[i].index = i-1;\n }\n } \n node_dataOnto.splice(index,1);\n refreshGraphOnto(node_dataOnto,link_dataOnto);\n }\n}", "function deleteAndRaiseFN() {\n let sel = $('#' + $('.selected').attr('id'));\n let pos = sel.offset();\n let subTree = sel.detach();\n $('#' + sel.attr('line-target')).remove();\n subTree.appendTo('body');\n sel.css({\n 'top' : pos.top,\n 'left' : pos.left\n });\n calc_all_lines('#' + sel.attr('id'));\n }", "remove () {\r\n\t\tvar svg = d3.select(this.element);\r\n\t\tsvg.selectAll('*').remove();\r\n\t}", "destroy() {\n this.node.parentNode.removeChild(this.node);\n }", "remove(index){\n// check the param\n\nconst leader = this.traverseToIndex(index-1);\nconst unwamtedNode = leader.next;\nleader.next = unwamtedNode.next;\nthis.length--;\n\n\n}", "undoPos()\n {\n this.dot.undoPos();\n }", "function deleteNode() {\n try {\n _deleteNode();\n createToast(\"Node deleted.\", \"warning\");\n } catch (e) {\n console.log(e);\n }\n}", "removeLineSegmant(){\n this.linePath.splice(this.linePath.length-1, 1);\n this.circlesInLinePath.splice(this.circlesInLinePath.length-1, 1);\n this.lineGraphics.clear();\n var lineToDelete = this.animLinePath.splice(this.animLinePath.length-1, 1);\n\n lineToDelete[0].destroy();\n }", "function nodeDragEnd(d) {\n if (!d3.event.active) simulation.alphaTarget(0);\n d.fx = null;\n d.fy = null;\n}", "function deletenode(e) {\n jsPlumb.remove(e.parentNode.parentNode.parentNode.parentNode);\n}", "remove () {\n this.node.parentNode.removeChild(this.node)\n this.stylesheet.parentNode.removeChild(this.stylesheet)\n }", "function graphRemove() {\r\n svg.selectAll(\"*\").remove();\r\n d3nodes = [];\r\n d3links = [];\r\n}", "removeAnchoredNode(node) {\n\t\tfor (var i = 0; i < this.anchoredNodes.length; i++) {\n\t\t\tif (node === this.anchoredNodes[i].node) {\n\t\t\t\tthis.anchoredNodes.splice(i,1);\n this.scene.remove(node)\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t}", "function animateRemoval() {\n return $animateCss(element, {addClass: '_md-leave'}).start();\n }", "function animateRemoval() {\n return $animateCss(element, {addClass: '_md-leave'}).start();\n }", "function animateRemoval() {\n return $animateCss(element, {addClass: '_md-leave'}).start();\n }", "function deleteFN() {\n let sel = $('.selected');\n $('#' + sel.attr('line-target')).remove();\n sel.find('.node').each(function() {\n // Remove the linking lines.\n let attr = $(this).attr('line-target');\n if (typeof attr !== typeof undefined && attr !== false) {\n $('#' + attr).remove();\n }\n });\n sel.remove();\n targets = ['body'];\n }", "function removeNodeClick() {\n if (buttonChecked == button_options.REMOVENODE) {\n buttonChecked = button_options.NONE;\n }\n else {\n buttonChecked = button_options.REMOVENODE;\n }\n consoleAdd(\"Button Selected: \" + buttonChecked);\n}", "function unFreeze(node){\n node.fixed = false;\n for( var i = 0; i < node.get('transitions').length; i++ ) {\n var childNode = idMap[node.get('transitions')[i].target];\n unFreeze(childNode);\n }\n }", "function removeDistantNodes(){\n\t\t\tvar preload = grid.preload,\n\t\t\t\ttrashBin = put(\"div\");\n\t\t\twhile (preload.previous){\n\t\t\t\tpreload = preload.previous;\n\t\t\t}\n\t\t\twhile (preload){\n\t\t\t\t// This code will not remove blocks of rows that are not adjacent to a preload node,\n\t\t\t\t// however currently the only situation this happens is when they are between two loading nodes.\n\t\t\t\t// In this case they will be removed on the first scroll after one of the loading nodes' queries\n\t\t\t\t// has been resolved.\n\t\t\t\tremovePreloadDistantNodes(preload, \"previousSibling\", trashBin);\n\t\t\t\tremovePreloadDistantNodes(preload, \"nextSibling\", trashBin);\n\t\t\t\tpreload = preload.next;\n\t\t\t}\n\t\t\tsetTimeout(function(){\n\t\t\t\t// we can defer the destruction until later\n\t\t\t\tput(trashBin, \"!\");\n\t\t\t},1);\n\t\t}", "function animateRemoval() {\n return $animateCss(element, {addClass: 'md-leave'}).start();\n }", "function animateRemoval() {\n return $animateCss(element, {addClass: 'md-leave'}).start();\n }", "function animateRemoval() {\n return $animateCss(element, {addClass: 'md-leave'}).start();\n }", "function animateRemoval() {\n return $animateCss(element, {addClass: 'md-leave'}).start();\n }", "function animateRemoval() {\n return $animateCss(element, {addClass: 'md-leave'}).start();\n }", "function animateRemoval() {\n return $animateCss(element, {addClass: 'md-leave'}).start();\n }", "delete() {\n this.eachElem((node) => {\n if (node.parentNode) {\n node.parentNode.removeChild(node);\n }\n });\n }", "delete() {\n this.eachElem((node) => {\n if (node.parentNode) {\n node.parentNode.removeChild(node);\n }\n });\n }", "deleteFirstNode() {\n if (!this.head) {\n return;\n }\n this.head = this.head.next;\n }", "remove(index){\n const leader = this.traverseToIndex(index-1)\n const unwantedNode = leader.next;\n leader.next = unwantedNode.next;\n this.length --;\n }", "wipeAllPathData() {\n for (let i = 0; i < this.nodes.length; i++) {\n let node = this.nodes[i]\n node.setShortestPath(node)\n node.distance = Number.MAX_SAFE_INTEGER\n }\n\n }", "function cleanLine(line) {\n var delay = 0;\n for (var k = 0; k < numBlocksX; k++) {\n // Make a small animation to send the removed blocks flying to the top\n var tween = game.add.tween(sceneSprites[k][line]);\n tween.to({ y: 0 }, 500, null, false, delay);\n tween.onComplete.add(destroy, this);\n tween.start();\n sceneSprites[k][line] = null;\n scene[k][line] = 0;\n delay += 50; // For each block, start the tween 50ms later so they move wave-like\n }\n}", "function remove_start_point(x, y) {\n\tsvg.select('#'+'p'+x+'black'+y).remove();\n}", "function unmarkMin(globals, params, q) {\n animToQueue(q, '#' + globals.cardArray[params].num,\n {top:'0px'}, \"unmin\", globals, params);\n}", "function deleteToHere (index) {\n // set construction points to animating\n svg.select('.construction-notes').selectAll('rect')\n .attr('animating', 'yes')\n .attr('selected', 'false')\n // disable choice mouse events\n svg.select('.choice-notes').selectAll('rect')\n .on('mousedown', null)\n .on('touchstart', null)\n .on('mouseup', null)\n .on('touchend', null)\n // pop until\n d3.range(cf.length() - 1 - index).forEach(function () {\n cf.pop()\n })\n redraw(svg)\n }", "function removeExtraCircles(){\n buildingBinding = objectContainer.selectAll(\".circleNode\");\n var loopCounter = 0;\n buildingBinding.each(function(d) {\n if(loopCounter >= startingNumOfCircles){\n var node = d3.select(this);\n node.remove();\n }\n loopCounter = loopCounter + 1;\n });\n}", "remove () {\n var p= this.parent;\n this._remove();\n p.update(true);\n }", "delete(node) {\n mona_dish_1.DQ.byId(node.id.value, true).delete();\n }", "_transitionExitNodes (source, nodes, transitionSpeed) {\n let nodeExit = nodes.exit()\n .transition()\n .duration(transitionSpeed)\n .attr(\"transform\", (d) => {\n return \"translate(\" + source.y + \",\" + source.x + \")\";\n })\n .remove();\n\n nodeExit.select(\"circle\")\n .attr(\"r\", 0);\n\n nodeExit.select(\"text\")\n .style(\"fill-opacity\", 0);\n }", "start() {\n setTimeout(() => {\n if (this.node && this.node.destroy()) {\n console.log('destroy complete');\n }\n }, 5000);\n }", "_removeChild(id, to, animate) {\n const self = this;\n const node = self.findById(id);\n if (!node) {\n return;\n }\n Util.each(node.get('children'), child => {\n self._removeChild(child.getModel().id, to, animate);\n });\n if (animate) {\n const model = node.getModel();\n node.set('to', to);\n node.set('origin', { x: model.x, y: model.y });\n self.get('removeList').push(node);\n } else {\n self.removeItem(node);\n }\n }", "remove() {\n this.x = -1000\n this.y = -1000\n }", "function _decreaseKey(minimum, node, key) {\n // set node key\n node.key = key; // get parent node\n\n var parent = node.parent;\n\n if (parent && smaller(node.key, parent.key)) {\n // remove node from parent\n _cut(minimum, node, parent); // remove all nodes from parent to the root parent\n\n\n _cascadingCut(minimum, parent);\n } // update minimum node if needed\n\n\n if (smaller(node.key, minimum.key)) {\n minimum = node;\n } // return minimum\n\n\n return minimum;\n }", "function _decreaseKey(minimum, node, key) {\n // set node key\n node.key = key; // get parent node\n\n var parent = node.parent;\n\n if (parent && smaller(node.key, parent.key)) {\n // remove node from parent\n _cut(minimum, node, parent); // remove all nodes from parent to the root parent\n\n\n _cascadingCut(minimum, parent);\n } // update minimum node if needed\n\n\n if (smaller(node.key, minimum.key)) {\n minimum = node;\n } // return minimum\n\n\n return minimum;\n }", "function clear() {\n lastPos = null;\n delta = 0;\n\n // $('.cine').css('-webkit-transition','.5s');\n // $('.cine').css('-webkit-transform','skewY(0deg)');\n // $('.cine pre').css('-webkit-transform','skewY(0deg)');\n // $('.cine span').css('-webkit-transform','skewY(0deg)');\n //\n // timer = setTimeout(function(){\n // $('.cine').css('-webkit-transition','0s');\n // console.log(\"!@#\");\n // }, 500);\n }", "function magnify(node) {\n if (parent = node.parent) {\n var parent,\n x = parent.x,\n k = .8;\n parent.children.forEach(function(sibling) {\n x += reposition(sibling, x, sibling === node\n ? parent.dx * k / node.value\n : parent.dx * (1 - k) / (parent.value - node.value));\n });\n } else {\n reposition(node, 0, node.dx / node.value);\n }\n \n path.transition()\n .duration(750)\n .attrTween(\"d\", arcTween);\n }", "removeChild (child) {\n this.scene.remove(child.root)\n }", "function clearNode(node) {\n setTextContent(node, \"\");\n}", "function clearNode(node) {\n setTextContent(node, \"\");\n}", "function clearNode(node) {\n setTextContent(node, \"\");\n}", "function clearNode(node) {\n setTextContent(node, \"\");\n}", "function clearNode(node) {\n setTextContent(node, \"\");\n}", "function clearNode(node) {\n setTextContent(node, \"\");\n}", "function deleteNode(node){\n\tnode.parentNode.removeChild(node);\n}", "unstyleNode() {\n var modules = this.getModules();\n modules.push(this.fAudioInput);\n modules.push(this.fAudioOutput);\n for (var i = 0; i < modules.length; i++) {\n if (modules[i].moduleView.fInputNode) {\n modules[i].moduleView.fInputNode.style.border = \"none\";\n modules[i].moduleView.fInputNode.style.left = \"-16px\";\n modules[i].moduleView.fInputNode.style.marginTop = \"-18px\";\n }\n if (modules[i].moduleView.fOutputNode) {\n modules[i].moduleView.fOutputNode.style.border = \"none\";\n modules[i].moduleView.fOutputNode.style.right = \"-16px\";\n modules[i].moduleView.fOutputNode.style.marginTop = \"-18px\";\n }\n }\n ModuleClass.isNodesModuleUnstyle = true;\n }", "function animateRemoval() {\n animationRunner = $animateCss(element, {addClass: 'md-leave'});\n return animationRunner.start();\n }", "removeChild(node) {\n const that = this;\n\n if (!that.isCompleted) {\n const args = Array.prototype.slice.call(arguments, 2);\n return HTMLElement.prototype.insertBefore.apply(that, args.concat(Array.prototype.slice.call(arguments)));\n }\n\n if (!node) {\n that.error(that.localize('invalidNode', { elementType: that.nodeName.toLowerCase(), method: 'removeChild', node: 'node' }));\n return\n }\n\n that.$.content.removeChild(node);\n that._applyPosition();\n }", "function growCircle() {\n\t//Avant de changer la taille de la bulle sélectionnée, on réinitialise la taille de toutes les autres\n\td3.selectAll(\"circle\").transition()\n\t\t.duration(500)\n\t\t.attr(\"r\", function(d) {return d.r});\n\t//On réaffiche les autres bulles et leur texte\n\td3.selectAll(\"circle\").transition()\n\t\t.style(\"opacity\", 1)\n\t\t//On replace toutes les autres bulles à leur emplacement original\n\t\t.attr(\"transform\", function(d) {\n\t\t\treturn \"translate (\" + 0 + \",\" + 0 + \")\";\n\t})\n\td3.selectAll(\".node\").selectAll(\"text\").transition()\n\t.style(\"opacity\", 1);\n\t//Si la bulle est déjà grossie, on la réinitialise\n\tif(d3.select(this).attr(\"increased\") == \"true\") {\n\t\t//Avant de changer la taille de la bulle sélectionnée, on réinitialise la taille de toutes les autres\n\t\td3.selectAll(\"circle\").transition()\n\t\t\t.duration(500)\n\t\t\t.attr(\"r\", function(d) {return d.r});\n\t\t//Animation de réduction et de replacement\n\t\td3.select(this).transition()\n\t\t\t.duration(500)\n\t\t\t.attr(\"r\", function(d) {return d.r})\n\t\t\t.attr(\"increased\",\"false\")\n\t\t\t.attr(\"transform\", function(d) {\n\t\t\treturn \"translate (\" + 0 + \",\" + 0 + \")\";\n\t\t});\n\t\t//Suppression du contenu de la bulle\n\t\tdeDisplay();\n\t}\n\t//Sinon, on la grossit\n\telse {\n\t\t//On réduit toutes les autres bulles\n\t\td3.selectAll(\"circle\").transition()\n\t\t\t.duration(200)\n\t\t\t.attr(\"r\", 0);\n\t\t\n\t\t//On rend tous les textes des bulles transparents\n\t\td3.selectAll(\".node\").selectAll(\"text\").transition()\n\t\t\t.style(\"opacity\", 0);\n\t\t\n\t\t//Animation de grossissement\n\t\td3.select(this).transition()\n\t\t\t.duration(500)\n\t\t\t.attr(\"r\", 30 + \"%\")\n\t\t\t//Mouvement vers la position d'affichage\n\t\t\t.attr(\"transform\", function(d) {\n\t\t\t\treturn \"translate (\" + (0 - d.x + 200) + \",\" + (0 - d.y + 200) + \")\";\n\t\t\t})\n\t\t\t.style(\"opacity\",1) //Au cas où on aurait cliqué sur une bulle rendue transparente, on la rend de nouveau opaque\n\t\t\t\n\t\td3.select(this).attr(\"increased\", \"true\")\n\t\t\n\t\t//Affichage des éléments\n\t\tvar ugo_id = d3.select(this).attr(\"ugo_id\")\n\t\tdisplay(ugo_id);\n\t}\n}", "function clearNode(node) {\n node.isLeaf = false;\n node.frequency = 0;\n for(var i = 0; i < 26; i++){\n node.children[i] = null;\n }\n}", "async function removeFigureDOM(index) {\n await animateNode(listNodes[index]);\n await animateArrow(listArrows[index]);\n \n list.removeChild(listNodes[index]);\n list.removeChild(listArrows[index]);\n listNodes.splice(index, 1);\n listArrows.splice(index, 1);\n}", "function deleteNode(e, object) {\n swal({\n title: \"確定要刪除?\",\n type: \"warning\",\n showCancelButton: true,\n cancelButtonText: \"取消\",\n confirmButtonClass: \"btn-danger\",\n confirmButtonText: \"確定\",\n closeOnConfirm: true\n },\n\n function (isConfirm) {\n if (isConfirm) {\n var currentObjectKey = object.part.data.key;\n var currentObjectCategory = object.part.data.category\n\n if (currentObjectCategory === \"CareMale\" || currentObjectCategory === \"CareFemale\" || currentObjectCategory === \"FreehandDrawing\" || currentObjectCategory === \"CommentBox\") {\n mainDiagram.commandHandler.deleteSelection();\n commentBoxKey = -1;\n return\n }\n\n var newNode;\n //delete parentTree's Node\n var previousNode = searchParentTreeNodePreviousNode(globalLogicData.parentTree, currentObjectKey)\n if (previousNode != null) {\n previousNode.left = null;\n previousNode.right = null;\n reRender(previousNode.id);\n return;\n }\n\n // delete node on childrenList\n var currentNodeArrayData = searchNodeCurrentArray(globalLogicData.childrenList, currentObjectKey);\n var NodeCurrentIndex = currentNodeArrayData.index;\n var NodeCurrentchildrenList = currentNodeArrayData.childrenList;\n if (NodeCurrentchildrenList[NodeCurrentIndex].parentTree) {\n var mainNodePosition = NodeCurrentchildrenList[NodeCurrentIndex].parentTree.linkNode\n // check weather the node that want to be deleted is child or partner, if it is not partner delete the node, else delete the partner\n if ((mainNodePosition === \"left\" && NodeCurrentchildrenList[NodeCurrentIndex].parentTree.left.id === currentObjectKey) ||\n (mainNodePosition === \"right\" && NodeCurrentchildrenList[NodeCurrentIndex].parentTree.right.id === currentObjectKey)) {\n\n NodeCurrentchildrenList.splice(NodeCurrentIndex, 1);\n reRender(currentObjectKey);\n return;\n } else if (mainNodePosition === \"left\") {\n newNode = NodeCurrentchildrenList[NodeCurrentIndex].parentTree.left;\n } else if (mainNodePosition === \"right\") {\n newNode = NodeCurrentchildrenList[NodeCurrentIndex].parentTree.right;\n }\n\n NodeCurrentchildrenList.splice(NodeCurrentIndex, 1);\n NodeCurrentchildrenList.splice(NodeCurrentIndex, 0, newNode);\n reRender(currentObjectKey);\n return;\n } else {\n NodeCurrentchildrenList.splice(NodeCurrentIndex, 1);\n reRender(currentObjectKey);\n return;\n }\n } else {\n return false;\n }\n }\n );\n}", "function __removeNodeFromCurrentQueue(_level,_node){\n currentAnimation[_level] = $.grep(currentAnimation[_level], function(obj){\n return obj['id'] !== _node['id'];\n });\n finishedAnimationQueue[_level].push(_node);\n }", "clear() {\n if (this.score >= 50) {\n this.score -= 50;\n this.update_score();\n let sprite = app.stage.getChildAt(0);\n this.meteors.forEach(element => app.stage.removeChild(element));\n this.meteors.clear;\n }\n }", "function clearCurrentNode(node)\n {\n while(node.firstChild)\n {\n node.removeChild(node.firstChild);\n }\n}", "function decreaseMin () {\n newMin = getMinimum()-10;\n min = newMin;\n return min;\n }", "destroyBetween(start, end) {\n if (start == end)\n return;\n for (let i = start; i < end; i++)\n this.top.children[i].destroy();\n this.top.children.splice(start, end - start);\n this.changed = true;\n }" ]
[ "0.8219588", "0.6764469", "0.6589784", "0.65468085", "0.65468085", "0.6514791", "0.6413174", "0.6265333", "0.6247256", "0.6247038", "0.61816996", "0.61467886", "0.6139714", "0.61021894", "0.6100401", "0.6087959", "0.60735303", "0.6065149", "0.6044144", "0.60392064", "0.59934336", "0.59658986", "0.59627634", "0.5959835", "0.5920941", "0.59143794", "0.58601946", "0.58558494", "0.5847551", "0.58449", "0.5837271", "0.58333296", "0.5832185", "0.5815542", "0.5788977", "0.5773734", "0.57631767", "0.5749958", "0.57464117", "0.57118773", "0.57115954", "0.57059354", "0.5700587", "0.5691636", "0.5643763", "0.56299454", "0.5609462", "0.56052405", "0.55965483", "0.55965483", "0.55910206", "0.55885816", "0.5584395", "0.55795074", "0.5573839", "0.5573839", "0.5573839", "0.5573839", "0.5573839", "0.5573839", "0.55534685", "0.55534685", "0.5551304", "0.5540706", "0.55316716", "0.5511985", "0.5510854", "0.550132", "0.5500544", "0.54958695", "0.54935783", "0.54882747", "0.5485453", "0.5484796", "0.54817384", "0.54771143", "0.54751253", "0.54751253", "0.54679006", "0.54647", "0.5456172", "0.5447975", "0.5447975", "0.5447975", "0.5447975", "0.5447975", "0.5447975", "0.54475456", "0.54464334", "0.5445689", "0.5444603", "0.544314", "0.543763", "0.5428837", "0.5426807", "0.54250616", "0.54247504", "0.5416445", "0.5410458", "0.54016846" ]
0.7807901
1
delete maximum node animate
animateDeleteMax() { const animations = []; animations.push(new Animation("display", "Deleting Max", "")); this.root = this.animateDeleteMaxHelper(this.root, animations); this.positionReset(); // reset x,y positions of nodes animations[animations.length - 1].setClass("found-node"); animations.push(new Animation("display", "Deleted Max", "")); return animations; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "deleteMin() {\r\n this.root = this.animateDeleteMinHelper(this.root);\r\n }", "animateDeleteMin() {\r\n const animations = [];\r\n animations.push(new Animation(\"display\", \"Deleting Min\", \"\"));\r\n\r\n this.root = this.animateDeleteMinHelper(this.root, animations);\r\n this.positionReset(); // reset x,y positions of nodes\r\n\r\n animations[animations.length - 1].setClass(\"found-node\");\r\n\r\n animations.push(new Animation(\"display\", \"Deleted Min\", \"\"));\r\n\r\n return animations;\r\n }", "async function deleteStackNode() {\n let pos = stack.size - 1;\n d3.select(\"#g\" + pos)\n .transition()\n .ease(d3.easeExp)\n .duration(500)\n\n .attr(\"transform\", \"translate(0,0)\")\n .style(\"opacity\", 0);\n await timeout(510);\n d3.select(\"#g\" + pos).remove();\n data_nodes.pop();\n}", "function deleteNode( node ) {\n\t\n\tLog(\"Deleting Node \" + node.id);\n\t\n\telements_in_canvas[node.id] = null;\n\tnodes_in_canvas_by_id[node.id] = null;\n\tnodes_in_canvas.splice( nodes_in_canvas.indexOf( node ), 1 );\n\t\n\tif (node.animationParent) {\n\t node.animationParent.animationChildren[node.id] = null;\n\t}\n\t\n\tnode.deleteNode();\n\t\n}", "function node_delete(_nodeindex){\r\n\tvar currentnode = nodes[_nodeindex];\r\n\tvar temp = delete_relatededges(currentnode, edges, edges_tangents);\r\n\tedges = temp.edges;\r\n\tedges_tangents = temp.edges_tangents;\r\n\tif(matchnodeindex(nodes,currentnode.id)>= 0 & matchnodeindex(nodes,currentnode.id)< nodes.length){\r\n\t\tswitch (currentnode.type){\r\n\t\t\tcase \"ellipse\": \r\n\t\t\t\tnumElli--;\r\n\t\t\t\tnumNode--;\t\t\t\r\n\t\t\t\tbreak;\r\n\t\t\tcase \"rect\":\r\n\t\t\t\tnumRec--;\r\n\t\t\t\tnumNode--;\t\t\t\t\r\n\t\t\t\tbreak;\r\n\r\n\t\t\tcase \"triangle\":\r\n\t\t\t\tnumTri--;\r\n\t\t\t\tnumNode--;\r\n\t\t\t\tbreak;\r\n\r\n\t\t\tdefault:;\r\n\t\t}//end of switch (_type) \r\n\t\tnodes.splice(_nodeindex,1);\r\n\t}\r\n}", "removeNode(g, n) { }", "removeNode(g, n) { }", "function deleteLastPosition() {\r\n\t//delete the trace of the block in the matrix\r\n\tmatrix[lastY][lastX] = 0;\r\n\tvar parent = document.getElementsByClassName('coll-' + lastX)[lastY - 1];\r\n\tparent.removeChild(parent.children[0]);\r\n}", "destroy() {\n nodes.splice(nodes.indexOf(el), 1);\n }", "function GoneNode(id) {\n $('.grid').isotope( 'remove', $(\"#node-\" + id)).isotope('layout')\n delete nodes_by_id[id] // Don't change indices\n delete nodes[name]\n delete charts[id]\n setNodes()\n}", "function delFrom_cum() {\n if (cumRows > 1 && transitioning == false) {\n\n // delete the row\n cumRows--;\n var cumRowsObj = document.getElementById(\"cumRows\");\n cumRowsObj.lastChild.className = \"cumRow toHide\";\n\n // perform transition\n transitioning = true;\n setTimeout(function() { delRow(cumRowsObj); }, 500);\n\n }\n}", "anchoredNodeRemoved(node) {}", "remove(index){\n// check the param\n\nconst leader = this.traverseToIndex(index-1);\nconst unwamtedNode = leader.next;\nleader.next = unwamtedNode.next;\nthis.length--;\n\n\n}", "function checkAndDeleteSecondNode(player, node){\n if(nodeToDelete != null && node.key != 'null'){\n var key = min(nodeToDelete.right);\n if(node.key == key){\n\n if (nodeToDelete.right.left.key == 'null') { // when nodeToDelete's right child IS min (move min and its right subtree up)\n\n // DISABLE KEYBOARD\n this.input.keyboard.enabled = false;\n\n // hide links:\n if (nodeToDelete.parent != null) {\n this.add.tween({\n targets: [nodeToDelete.link],\n ease: 'Sine.easeOut',\n duration: 1000,\n alpha: '-=1'\n });\n }\n\n this.add.tween({\n targets: [nodeToDelete.left.link, nodeToDelete.right.link, node.left.link],\n ease: 'Sine.easeOut',\n duration: 1000,\n alpha: '-=1'\n });\n\n // nodes and their components:\n this.add.tween({\n targets: [nodeToDelete.nodeGraphics, nodeToDelete.curtain, nodeToDelete.keyString, node.left.nullGraphics, node.left.keyString],\n delay: 1000,\n ease: 'Sine.easeOut',\n duration: 1000,\n alpha: '-=1'\n });\n\n // destroy left child(null) of 15 and update some stuff\n this.time.addEvent({\n delay: 2100,\n callback: function(nodeToDelete,node) {\n node.left.destroyNode(); // destroy null left child of 15\n node.left = null;\n node.parent = nodeToDelete.parent; // set 15s parent as what 10 had (null) || set 25s parent to 15\n node.dpth = nodeToDelete.dpth;\n },\n args: [nodeToDelete,node]\n });\n\n // abs(10 x - 15 x) + node x\n this.time.addEvent({\n delay: 2500,\n callback: function(nodeToDelete,node,scene) {\n var distanceX = Math.abs(nodeToDelete.posX-node.posX);\n // Version 2\n updateBranch(node,distanceX);\n },\n args: [nodeToDelete,node,this]\n });\n\n // Version 2\n this.time.addEvent({\n delay: 3000,\n callback: function(nodeToDelete,node,scene) {\n var distanceX = Math.abs(nodeToDelete.posX-node.posX);\n\n if (nodeToDelete == tree.root) { // if deleted node is root\n tree.root = node;\n node.left = nodeToDelete.left; // move 10's left branch to 15\n node.left.parent = node; // change left branch's parent to 15\n } else if (nodeToDelete == nodeToDelete.parent.right){ // if deleted node is right child\n node.left = nodeToDelete.left; // set 25s left to 16 (move 20's left branch to 25)\n node.left.parent = node; // set 16s parent to 25 (change left branch's parent to 25)\n node.parent.right = node; // set 15's right child to 25\n } else if (nodeToDelete == nodeToDelete.parent.left) { // if deleted node is left child\n node.left = nodeToDelete.left;\n node.left.parent = node;\n node.parent.left = node; \n }\n node.distanceFromParent = nodeToDelete.distanceFromParent;\n tree.updateNodeDepths(tree.root);\n // nodeToDelete.destroyNode();\n\n tree.traverseAndCheckCollisions(scene);\n tree.traverseAndCheckCrossings(scene);\n\n scene.add.tween({\n targets: player,\n x: node.posX, // if 15 is on left branch then we should do +\n y: node.posY - BUFFER, // 10 is Buffer\n ease: 'Power2',\n duration: 1500,\n });\n\n actuallyMoveBranch(node,distanceX,scene);\n\n // TODO: ROTATE node.right.link and after it is rotated then redraw to extend:\n // node.right.link.setAlpha(0);\n // move node link, rotate it and extend it\n if (node.right.link != null) {\n\n var N = node.right.distanceFromParent;\n \n var O = null;\n if (node.right.distanceFromParent < 0) {\n O = (node.right.link.x - node.right.link.width) - node.right.link.x;\n } else {\n O = (node.right.link.x + node.right.link.width) - node.right.link.x;\n }\n \n var oldAngle = calcAngle(tree.z,O);\n var newAngle = calcAngle(tree.z,N);\n var difference = oldAngle - newAngle;\n \n scene.add.tween({\n targets: node.right.link,\n x: node.right.posX, \n y: node.right.posY,\n ease: 'Power2',\n duration: 1500\n });\n \n if (difference != 0) {\n // ROTATION TWEEN:\n scene.add.tween({\n targets: node.right.link,\n angle: -difference,\n ease: 'Sine.easeInOut',\n duration: 1500,\n onComplete: drawLink,\n onCompleteParams: [node.right,scene]\n });\n \n function drawLink(tween,targets,node,scene) {\n node.drawLinkToParent(scene);\n }\n }\n }\n // appearLinks(node,scene);\n },\n args: [nodeToDelete,node,this]\n });\n\n // need to appear movedNodes's link to parent and left link\n\n this.time.addEvent({\n delay: 4500,\n callback: function(node,scene) {\n node.drawLinkToParent(scene);\n node.link.setAlpha(0);\n node.left.drawLinkToParent(scene);\n node.left.link.setAlpha(0);\n scene.add.tween({\n targets: [node.link, node.left.link],\n ease: 'Sine.easeIn',\n duration: 1000,\n alpha: '+=1'\n });\n \n },\n args: [node,this]\n });\n // end of Version 2\n\n this.time.addEvent({\n delay: 5800,\n callback: function(node,scene) {\n nodeToDelete.destroyNode();\n nodeToDelete = null;\n tree.updateNodeDepths(node);\n // Version 2\n // A way to move the branch together with already expanded branch:\n // in moveBranch only update the posX - line 643\n // then check for collisions - line \n // then actually move the branch nodes (change x to updated posX) - line\n // redraw\n tree.traverseAndCheckCollisions(scene);\n tree.traverseAndCheckCrossings(scene);\n tree.redraw(scene);\n },\n args: [node,this]\n });\n\n this.time.addEvent({\n delay: 7500,\n callback: function(scene) {\n taskSucceededActions(scene);\n displayTask(scene);\n // ENABLE KEYBOARD\n scene.input.keyboard.enabled = true;\n },\n args: [this]\n });\n \n \n } else if (nodeToDelete.right.left.key != 'null') { // when nodeToDelete's right child's left exists (it means there will be a min somewhere on the left from right child)\n\n var nodeToUseForAppear = node.parent;\n\n // DISABLE KEYBOARD\n this.input.keyboard.enabled = false;\n\n // hide links:\n if (nodeToDelete.parent != null) {\n this.add.tween({\n targets: [nodeToDelete.link],\n ease: 'Sine.easeOut',\n duration: 1000,\n alpha: '-=1'\n });\n }\n\n this.add.tween({\n targets: [nodeToDelete.left.link, nodeToDelete.right.link, node.left.link, node.right.link, node.link],\n ease: 'Sine.easeOut',\n duration: 1000,\n alpha: '-=1'\n });\n\n // when min doesn't have children on the right\n if (node.right.key == 'null') {\n\n // hide nodes and their components:\n this.add.tween({\n targets: [nodeToDelete.nodeGraphics, nodeToDelete.curtain, nodeToDelete.keyString, node.left.nullGraphics, node.left.keyString, node.right.nullGraphics, node.right.keyString],\n delay: 1000,\n ease: 'Sine.easeOut',\n duration: 1000,\n alpha: '-=1'\n });\n \n // create null for 20 and destroy 16's both null children and update some stuff\n this.time.addEvent({\n delay: 2100,\n callback: function(nodeToDelete,node,scene) {\n // make null for 20\n var childL = new NodeBST(scene, singleTon.deleteMinColor, node.parent.posX-tree.w, node.parent.posY+tree.z, 'null',node.parent.dpth+1,node.parent);\n childL.distanceFromParent = -tree.w;\n node.parent.left = childL;\n childL.nullGraphics.setAlpha(0);\n childL.keyString.setAlpha(0);\n childL.link.setAlpha(0);\n\n tree.checkCollisions(childL);\n\n // teleporting + curtains\n childL.setPhysicsNode(cursors,player,scene);\n\n // physics\n scene.physics.add.overlap(player, childL, deleteNode, backspaceIsPressed, scene);\n scene.physics.add.overlap(player, childL, checkAndDeleteSecondNode, mIsPressed, scene);\n scene.physics.add.collider(player, childL);\n \n node.left.destroyNode(); // destroy null left child of 16\n node.right.destroyNode(); // destroy null right child of 16\n node.left = null;\n node.right = null;\n node.parent = nodeToDelete.parent; // set 16s parent as what 15 had (null)\n node.dpth = nodeToDelete.dpth;\n },\n args: [nodeToDelete,node,this]\n });\n\n // move 16 to the place of 15\n this.time.addEvent({\n delay: 2500,\n callback: function(nodeToDelete,node,scene) {\n \n // player moves up\n scene.add.tween({\n targets: player,\n x: nodeToDelete.x,\n y: nodeToDelete.y - BUFFER,\n ease: 'Power2',\n duration: 1500,\n });\n \n // 16 shape and curtain moves up\n scene.add.tween({\n targets: [node, node.nodeGraphics, node.curtain],\n x: nodeToDelete.x,\n y: nodeToDelete.y, \n ease: 'Power2',\n duration: 1500,\n });\n \n var distanceX = Math.abs(node.keyString.x-node.posX);\n \n // 16s keystring moves up\n scene.add.tween({\n targets: node.keyString,\n x: nodeToDelete.x - distanceX,\n y: nodeToDelete.keyString.y, // - (tree.z*(node.dpth-nodeToDelete.dpth))\n ease: 'Power2',\n duration: 1500,\n });\n\n // draw 16s link to parent, update physics bodies\n scene.time.addEvent({\n delay: 1500,\n callback: function(node,scene) {\n node.drawLinkToParent(scene);\n node.link.setAlpha(0);\n node.body.updateFromGameObject();\n node.curtain.body.updateFromGameObject();\n },\n args: [node,scene]\n });\n\n // update 16s x and y\n node.posX = nodeToDelete.posX;\n node.posY = nodeToDelete.posY;\n\n },\n args: [nodeToDelete,node,this]\n });\n\n this.time.addEvent({\n delay: 4500,\n callback: function(nodeToUseForAppear,nodeToDelete,node,scene) {\n if (nodeToDelete == tree.root) { // if deleted node is root\n tree.root = node;\n node.left = nodeToDelete.left;\n node.left.parent = node;\n node.right = nodeToDelete.right;\n node.right.parent = node;\n } else if (nodeToDelete == nodeToDelete.parent.right){ // if deleted node is right child\n node.left = nodeToDelete.left;\n node.left.parent = node;\n node.right = nodeToDelete.right;\n node.right.parent = node;\n node.parent.right = node;\n } else if (nodeToDelete == nodeToDelete.parent.left) { // if deleted node is left child\n node.left = nodeToDelete.left;\n node.left.parent = node;\n node.right = nodeToDelete.right;\n node.right.parent = node;\n node.parent.left = node; \n }\n\n // put/appear null on the left of 20\n scene.add.tween({\n targets: [nodeToUseForAppear.left.nullGraphics, nodeToUseForAppear.left.nodeGraphics, nodeToUseForAppear.left.keyString],\n ease: 'Sine.easeIn',\n duration: 1000,\n alpha: '+=1'\n });\n\n node.distanceFromParent = nodeToDelete.distanceFromParent;\n \n if (node.parent != null) {\n scene.add.tween({\n targets: [node.link],\n delay: 1000,\n ease: 'Sine.easeOut',\n duration: 1000,\n alpha: '+=1'\n });\n }\n\n scene.add.tween({\n targets: [node.left.link, node.right.link, nodeToUseForAppear.left.link], //node.right.left.link\n delay: 1000,\n ease: 'Sine.easeOut',\n duration: 1000,\n alpha: '+=1'\n });\n\n tree.updateNodeDepths(tree.root);\n nodeToDelete.destroyNode();\n },\n args: [nodeToUseForAppear,nodeToDelete,node,this]\n });\n\n this.time.addEvent({\n delay: 8000,\n callback: function(node,scene) {\n nodeToDelete = null;\n tree.updateNodeDepths(node);\n tree.traverseAndCheckCollisions(scene);\n tree.traverseAndCheckCrossings(scene);\n tree.redraw(scene); \n },\n args: [node,this]\n });\n\n } else if (node.right.key != 'null') { // when min has children on the right (need to move the right branch up)\n \n // hide nodes and their components:\n this.add.tween({\n targets: [nodeToDelete, nodeToDelete.nodeGraphics, nodeToDelete.curtain, nodeToDelete.keyString, node.left, node.left.nullGraphics, node.left.keyString],\n delay: 1000,\n ease: 'Sine.easeOut',\n duration: 1000,\n alpha: '-=1'\n });\n\n this.time.addEvent({\n delay: 2100,\n callback: function(nodeToDelete,node,scene) {\n node.left.destroyNode(); // node is min. we destroy its left child because it wont be needed anymore/it will be replaced\n node.left = null;\n node.parent = nodeToDelete.parent;\n node.dpth = nodeToDelete.dpth;\n },\n args: [nodeToDelete,node,this]\n });\n\n this.time.addEvent({\n delay: 2500,\n callback: function(nodeToDelete,node,scene) {\n \n // player moves up\n scene.add.tween({\n targets: player,\n x: nodeToDelete.x,\n y: nodeToDelete.y - BUFFER,\n ease: 'Power2',\n duration: 1500,\n });\n \n // 11 shape and curtain moves up\n scene.add.tween({\n targets: [node, node.nodeGraphics, node.curtain],\n x: nodeToDelete.x,\n y: nodeToDelete.y, \n ease: 'Power2',\n duration: 1500,\n });\n \n var distanceX = Math.abs(node.keyString.x-node.posX);\n \n // 11s keystring moves up\n scene.add.tween({\n targets: node.keyString,\n x: nodeToDelete.x - distanceX,\n y: nodeToDelete.keyString.y, // - (tree.z*(node.dpth-nodeToDelete.dpth))\n ease: 'Power2',\n duration: 1500,\n });\n\n // draw 11s link to parent, update physics bodies\n scene.time.addEvent({\n delay: 1500,\n callback: function(node,scene) {\n // node.drawLinkToParent(scene);\n // node.link.setAlpha(0);\n node.body.updateFromGameObject();\n node.curtain.body.updateFromGameObject();\n },\n args: [node,scene]\n });\n\n },\n args: [nodeToDelete,node,this]\n });\n\n this.time.addEvent({\n delay: 4500,\n callback: function(nodeToUseForAppear,nodeToDelete,node,scene) {\n\n var distanceX = Math.abs(node.posX-node.right.posX);\n \n updateBranch(node.right,distanceX); //v2\n\n // update 11s x and y - just to be sure it doesn't get updated before moveBranch \n node.posX = nodeToDelete.posX;\n node.posY = nodeToDelete.posY;\n\n // draw 11s links - have to have it here after we update 11s posX and posY\n node.drawLinkToParent(scene);\n node.link.setAlpha(0);\n \n // update 12s distance from parent\n node.right.distanceFromParent = node.distanceFromParent; // <-- 11s.distancefromparent // nodeToUseForAppear.left.distanceFromParent; <-- 13s.left\n nodeToUseForAppear.left = node.right; // here nodeToUseForAppear is the parent of node(min)\n node.right.parent = nodeToUseForAppear;\n\n if (nodeToDelete == tree.root) { // if deleted node is root\n tree.root = node;\n node.left = nodeToDelete.left;\n node.left.parent = node;\n node.right = nodeToDelete.right;\n node.right.parent = node;\n } else if (nodeToDelete == nodeToDelete.parent.right){ // if deleted node is right child\n node.left = nodeToDelete.left;\n node.left.parent = node;\n node.right = nodeToDelete.right;\n node.right.parent = node;\n node.parent.right = node;\n } else if (nodeToDelete == nodeToDelete.parent.left) { // if deleted node is left child\n node.left = nodeToDelete.left;\n node.left.parent = node;\n node.right = nodeToDelete.right;\n node.right.parent = node;\n node.parent.left = node; \n }\n\n // update distancefromparent for 11\n node.distanceFromParent = nodeToDelete.distanceFromParent;\n\n\n // tree.updateNodeDepths(node.right);\n tree.updateNodeDepths(tree.root);\n\n tree.traverseAndCheckCollisions(scene); //v2\n tree.traverseAndCheckCrossings(scene); //v2\n\n actuallyMoveBranch(nodeToUseForAppear.left,distanceX,scene); //v2\n\n // appearLinks(node.right, scene);\n\n node.drawLinkToParent(scene);\n node.link.setAlpha(0);\n nodeToUseForAppear.left.drawLinkToParent(scene);\n nodeToUseForAppear.left.link.setAlpha(0);\n \n if (node.parent != null) {\n scene.add.tween({\n targets: [node.link],\n delay: 1500,\n ease: 'Sine.easeOut',\n duration: 1000,\n alpha: '+=1'\n });\n }\n\n scene.add.tween({\n targets: [node.left.link, node.right.link, nodeToUseForAppear.left.link], //node.right.left.link\n delay: 1500,\n ease: 'Sine.easeOut',\n duration: 1000,\n alpha: '+=1'\n });\n\n // tree.updateNodeDepths(tree.root);\n nodeToDelete.destroyNode();\n },\n args: [nodeToUseForAppear,nodeToDelete,node,this]\n });\n\n this.time.addEvent({\n delay: 7000,\n callback: function(nodeToUseForAppear,node,scene) {\n nodeToDelete = null;\n tree.updateNodeDepths(node);\n tree.traverseAndCheckCollisions(scene);\n tree.traverseAndCheckCrossings(scene);\n tree.redraw(scene); \n },\n args: [nodeToUseForAppear,node,this]\n });\n\n } //end of else if\n\n this.time.addEvent({\n delay: 8000,\n callback: function(scene) {\n taskSucceededActions(scene);\n displayTask(scene);\n // ENABLE KEYBOARD\n scene.input.keyboard.enabled = true;\n },\n args: [this]\n });\n\n\n } //end of else if\n\n } else {\n panel.redFeedback();\n player.setPosition(nodeToDelete.x,nodeToDelete.y-BUFFER);\n tree.closeCurtains()\n }\n }\n }", "clear () {\n this.control.disable();\n while (this.nodes.length) this.nodes[this.nodes.length-1].remove();\n this.control.enable();\n }", "remove() {\n this.node.remove()\n }", "function animateRemoveNode(node) {\n return new Promise(function(resolve) {\n node.style.animation = 'circle ' + (removeNodeSpeed/1000) +'s linear';\n setTimeout(() => {\n node.style.animation = null;\n resolve();\n }, removeNodeSpeed);\n });\n}", "remove() {\n this.parent.removeTween(this);\n }", "handleDelete() {\n API.deleteNode(this.props.node).then(() => {\n this.props.node.remove();\n this.props.engine.repaintCanvas();\n }).catch(err => console.log(err));\n }", "animateDelete(key) {\r\n const animations = [];\r\n animations.push(new Animation(\"display\", `Deleting ${key}`));\r\n\r\n this.root = this.animateDeleteHelper(this.root, key, animations);\r\n this.positionReset(); // reset x,y positions of nodes\r\n\r\n // highlight last node in green if found\r\n if (compareTo(animations[animations.length - 1].getItem(), key) === 0) {\r\n animations[animations.length - 1].setClass(\"found-node\");\r\n animations.push(new Animation(\"display\", `Deleted ${key}`));\r\n return [key, animations];\r\n } // highlight last node in red if not found\r\n else {\r\n animations[animations.length - 1].setClass(\"search-failed-node\");\r\n animations.push(new Animation(\"display\", \"Not Found\"));\r\n\r\n return [null, animations];\r\n }\r\n }", "function deleteNode(player, node) {\n if (nodeToDelete == null && tasks.length != 0) {\n // (node.key != 'null') \n if (node.key != 'null' && (tasks[0] == node.key || (tasks[0] == 'Min' && node.key == min(tree.root)) || (tasks[0] == 'Max' && node.key == max(tree.root))) && nodeToDelete == null) {\n if (node.left.key =='null' && node.right.key =='null') { // both children are null \n\n // DISABLE KEYBOARD\n this.input.keyboard.enabled = false;\n\n if (node.parent != null) {\n player.setPosition(node.parent.posX,node.parent.posY-BUFFER);\n }\n\n // node.left, node.right, node\n // hide links and nodes\n this.add.tween({\n targets: [node.left.link, node.right.link, node.left.nullGraphics, node.right.nullGraphics, node.nodeGraphics, node.keyString, node.left.keyString,node.right.keyString],\n ease: 'Sine.easeOut',\n duration: 1000,\n alpha: '-=1'\n });\n\n this.time.addEvent({\n delay: 1000,\n callback: function(node) {\n node.setKey('null');\n node.setNullGraphics();\n node.nullGraphics.setAlpha(0);\n node.left.destroyNode();\n node.right.destroyNode();\n node.setChildren(); // set children as null\n },\n args: [node]\n });\n\n this.add.tween({\n targets: [node.nullGraphics, node.keyString],\n ease: 'Sine.easeIn',\n delay: 2000,\n duration: 1000,\n alpha: '+=1',\n // onComplete: taskSucceededActions(this),\n // onCompleteParams: [this]\n });\n\n this.time.addEvent({\n delay: 4000,\n callback: function(scene) {\n // ENABLE KEYBOARD\n taskSucceededActions(scene)\n scene.input.keyboard.enabled = true;\n // displayTask();\n },\n args: [this]\n });\n\n } else if (node.right.key == 'null' || node.left.key == 'null') { // one child is null\n\n // DISABLE KEYBOARD\n this.input.keyboard.enabled = false;\n\n if (node.right.key == 'null') { // right child is null\n\n player.setPosition(node.left.x,node.left.y-BUFFER);\n\n // hide links\n this.add.tween({\n targets: [node.left.link, node.right.link, node.link],\n ease: 'Sine.easeOut',\n duration: 1000,\n alpha: '-=1'\n });\n\n // hide right null of deleted node and the deleted node\n this.add.tween({\n targets: [node.right.nullGraphics, node.nodeGraphics, node.keyString, node.right.keyString],\n ease: 'Sine.easeOut',\n duration: 1000,\n alpha: '-=1'\n });\n\n // branch moves to the right\n this.time.addEvent({\n delay: 1000,\n callback: function(node,scene) {\n\n if (node.parent == null) {\n node.left.parent = null;\n tree.root = node.left;\n tree.root.dpth = 0;\n } else if (node.parent.left == node) {\n node.parent.left = node.left;\n node.left.parent = node.parent;\n } else if (node.parent.right == node) {\n node.parent.right = node.left;\n node.left.parent = node.parent;\n }\n \n var distanceX = node.left.posX-node.posX;\n // moveBranch(node.left,distanceX,scene); //v1\n updateBranch(node.left,distanceX); //v2\n\n // TO PREVENT COLLAPSING:\n node.left.distanceFromParent = node.distanceFromParent;\n\n tree.updateNodeDepths(node.left); // starting from 9 (the node that changes deleted node)\n\n tree.traverseAndCheckCollisions(scene); //v2\n tree.traverseAndCheckCrossings(scene); //v2\n\n // player moves up\n scene.add.tween({\n targets: player,\n x: node.left.posX,\n y: node.left.posY - BUFFER,\n ease: 'Power2',\n duration: 1500,\n });\n\n actuallyMoveBranch(node.left,distanceX,scene); //v2\n\n // // destroy 15.right\n // node.right.destroyNode();\n // // destroy 15\n // node.destroyNode();\n },\n args: [node,this]\n });\n\n // appear link that changed\n this.time.addEvent({\n delay: 2500,\n callback: function(scene,node) {\n\n node.left.drawLinkToParent(scene);\n node.left.link.setAlpha(0);\n scene.add.tween({\n targets: node.left.link,\n ease: 'Sine.easeIn',\n duration: 1000,\n alpha: '+=1'\n });\n\n },\n args: [this,node]\n });\n\n // move player to root, update tasks, enable keyboard\n this.time.addEvent({\n delay: 3000,\n callback: function(scene) {\n tree.traverseAndCheckCollisions(scene);\n tree.traverseAndCheckCrossings(scene);\n // tree.traverseAndCheckCrossings(scene);\n\n tree.redraw(scene);\n\n // appearLinksOneChild(node.left, scene);\n // destroy 15.right\n node.right.destroyNode();\n // destroy 15\n node.destroyNode();\n\n },\n args: [this]\n });\n\n } else { // left child is null\n\n player.setPosition(node.right.x,node.right.y-BUFFER);\n\n // hide links\n this.add.tween({\n targets: [node.left.link, node.right.link, node.link],\n ease: 'Sine.easeOut',\n duration: 1000,\n alpha: '-=1'\n });\n\n // hide left null of deleted node and the deleted node\n this.add.tween({\n targets: [node.left.nullGraphics, node.nodeGraphics, node.keyString, node.left.keyString],\n ease: 'Sine.easeOut',\n duration: 1000,\n alpha: '-=1'\n });\n\n // branch moves to the left up\n this.time.addEvent({\n delay: 1000,\n callback: function(node,scene) {\n\n if (node.parent == null) {\n node.right.parent = null;\n tree.root = node.right;\n tree.root.dpth = 0;\n } else if (node.parent.left == node) {\n node.parent.left = node.right;\n node.right.parent = node.parent;\n } else if (node.parent.right == node) {\n node.parent.right = node.right;\n node.right.parent = node.parent;\n }\n\n // TODO:\n // not here:\n // 2.the collisions are checked only once? the crossings are not checked?\n\n var distanceX = node.right.posX-node.posX;\n // moveBranch(node.right,distanceX,scene); //v1\n updateBranch(node.right,distanceX); //v2\n\n // TO PREVENT COLLAPSING:\n node.right.distanceFromParent = node.distanceFromParent;\n\n tree.updateNodeDepths(node.right); // starting from 33 (the node that changes deletd node)\n\n tree.traverseAndCheckCollisions(scene); //v2\n tree.traverseAndCheckCrossings(scene); //v2\n\n // player moves up\n scene.add.tween({\n targets: player,\n x: node.right.posX,\n y: node.right.posY - BUFFER,\n ease: 'Power2',\n duration: 1500,\n });\n actuallyMoveBranch(node.right,distanceX,scene); //v2\n\n // appearLinks(node.right, scene);\n\n // // destroy 24.left\n // node.left.destroyNode();\n // // destroy 24\n // node.destroyNode();\n },\n args: [node,this]\n });\n\n // appear link that changed\n this.time.addEvent({\n delay: 2500,\n callback: function(scene,node) {\n\n node.right.drawLinkToParent(scene);\n node.right.link.setAlpha(0);\n scene.add.tween({\n targets: node.right.link,\n ease: 'Sine.easeIn',\n duration: 1000,\n alpha: '+=1'\n });\n\n },\n args: [this,node]\n });\n\n // move player to root, update tasks, enable keyboard\n this.time.addEvent({\n delay: 3500,\n callback: function(scene) {\n tree.traverseAndCheckCollisions(scene);\n tree.traverseAndCheckCrossings(scene);\n // tree.traverseAndCheckCrossings(scene);\n \n tree.redraw(scene);\n \n // appearLinksOneChild(node.right, scene);\n // destroy 24.left\n node.left.destroyNode();\n // destroy 24\n node.destroyNode();\n \n },\n args: [this]\n });\n } //end of if else\n \n\n this.time.addEvent({\n delay: 6000,\n callback: function(scene) {\n taskSucceededActions(scene);\n // ENABLE KEYBOARD\n scene.input.keyboard.enabled = true;\n },\n args: [this]\n });\n } else { // both children are NOT null\n // setting a value of nodeToDelete to use it after user clicks Enter\n nodeToDelete = node;\n nodeToDelete.nodeGraphics.setTint(0xf3a6ff);\n if(nodeToDelete.key == 631) {\n if (expert.progressCounter <= 2) {\n talkNodes.shift();\n }\n expert.progressCounter = 3;\n expert.talk('deleteTwoChildren',3,'nosymbol');\n }\n }\n } else {\n panel.redFeedback();\n player.setPosition(tree.root.x,tree.root.y-BUFFER);\n tree.closeCurtains()\n\n\n }\n }\n }", "destroy() {\n this.node.parentNode.removeChild(this.node);\n }", "removeNode(node) {\n this.nodes.splice(this.nodes.indexOf(node), 1);\n this.svgsManager.nodeManager.update();\n }", "function deleteNode(node) {\n\n // delete link, tubes and cables\n spliceLinksForNode(node);\n\n // delete node\n nodes.splice(nodes.indexOf(node), 1);\n\n correctID();\n\n updateMatrix();\n\n // close the modal box\n closeModal();\n\n // redraw\n restart();\n}", "removeNode(node) {\n if (nodesCount > 0) { nodesCount -= 1; }\n if (node.id < nodesCount && nodesCount > 0) {\n // we do not really delete anything from the buffer.\n // Instead we swap deleted node with the \"last\" node in the\n // buffer and decrease marker of the \"last\" node. Gives nice O(1)\n // performance, but make code slightly harder than it could be:\n webglUtils.copyArrayPart(nodes, node.id * ATTRIBUTES_PER_PRIMITIVE, nodesCount * ATTRIBUTES_PER_PRIMITIVE, ATTRIBUTES_PER_PRIMITIVE);\n }\n }", "function removeNode(){\n\tfadeOut();\n\tif (state === true) {\n\t\tmakeRequest();\n\t}\n}", "removeMax() {\r\n\t\tthis.remove(this.heap[0]);\r\n\t}", "function removeNodeOnto(index){\n if(index>=0 && index<node_dataOnto.length){\n removeAllEdgesOnto(index);\n for(var i = 0;i<node_dataOnto.length;i++){\n if(i>index){\n node_dataOnto[i].index = i-1;\n }\n } \n node_dataOnto.splice(index,1);\n refreshGraphOnto(node_dataOnto,link_dataOnto);\n }\n}", "function outNode(){\n\t\ttooltipsvg\n\t\t.style(\"opacity\", 0)\n\t\t.attr(\"width\",0)\n\t\t.attr(\"height\",0)\n\t\t.selectAll(\"*\").remove();;\n\t}", "_removeChild(id, to, animate) {\n const self = this;\n const node = self.findById(id);\n if (!node) {\n return;\n }\n Util.each(node.get('children'), child => {\n self._removeChild(child.getModel().id, to, animate);\n });\n if (animate) {\n const model = node.getModel();\n node.set('to', to);\n node.set('origin', { x: model.x, y: model.y });\n self.get('removeList').push(node);\n } else {\n self.removeItem(node);\n }\n }", "remove(index){\n const leader = this.traverseToIndex(index-1)\n const unwantedNode = leader.next;\n leader.next = unwantedNode.next;\n this.length --;\n }", "resetTree() {\n this.root.nodes.forEach((node) => { var _a; return (_a = node.currentAnimation) === null || _a === void 0 ? void 0 : _a.stop(); });\n this.root.nodes.forEach(clearMeasurements);\n this.root.sharedNodes.clear();\n }", "clear() {\n if (this.score >= 50) {\n this.score -= 50;\n this.update_score();\n let sprite = app.stage.getChildAt(0);\n this.meteors.forEach(element => app.stage.removeChild(element));\n this.meteors.clear;\n }\n }", "function deletenode(e) {\n jsPlumb.remove(e.parentNode.parentNode.parentNode.parentNode);\n}", "function _deleteNode() {\n const id = diagram.selection.toArray()[0].key;\n const node = diagram.findNodeForKey(id);\n diagram.startTransaction();\n diagram.remove(node);\n diagram.commitTransaction(\"deleted node\");\n diagramEvent()\n}", "remove_child(node) {\n delete this.children[node.get_token_string()];\n this.notify_fragment_dirty();\n }", "function nodeMouseOut(d, i) {\n // Reset link styles\n link\n .style(\"opacity\", 1)\n .style(\"stroke\", \"#999\");\n // Reset node styles\n node\n .style(\"opacity\", 1)\n .style(\"stroke\", \"#fff\");\n // Reset text styles\n text\n .style(\"visibility\", \"hidden\")\n .style(\"font-weight\", \"normal\");\n }", "delete() {\n this.eachElem((node) => {\n if (node.parentNode) {\n node.parentNode.removeChild(node);\n }\n });\n }", "delete() {\n this.eachElem((node) => {\n if (node.parentNode) {\n node.parentNode.removeChild(node);\n }\n });\n }", "removeChild (child) {\n this.scene.remove(child.root)\n }", "function delRow(row) {\n row.removeChild(row.lastChild);\n transitioning = false;\n recalc();\n}", "function nodeDragEnd(d) {\n if (!d3.event.active) simulation.alphaTarget(0);\n d.fx = null;\n d.fy = null;\n}", "function deleteToHere (index) {\n // set construction points to animating\n svg.select('.construction-notes').selectAll('rect')\n .attr('animating', 'yes')\n .attr('selected', 'false')\n // disable choice mouse events\n svg.select('.choice-notes').selectAll('rect')\n .on('mousedown', null)\n .on('touchstart', null)\n .on('mouseup', null)\n .on('touchend', null)\n // pop until\n d3.range(cf.length() - 1 - index).forEach(function () {\n cf.pop()\n })\n redraw(svg)\n }", "destroyRest() {\n this.destroyBetween(this.index, this.top.children.length);\n }", "function deleteNode() {\n try {\n _deleteNode();\n createToast(\"Node deleted.\", \"warning\");\n } catch (e) {\n console.log(e);\n }\n}", "_remove() {\n\t\tthis.parent._removeChildren( this.index );\n\t}", "decreaseItem(decrease = this.options.decrease) {\n this.setIndexesByDirection(false)\n Array.from(this.expander.children).forEach((ctx, i) => {\n if (i > (this.options.show - 1) && i > this.lastIndex && i <= (this.lastIndex + decrease)) {\n new Animate(ctx, i, this.lastIndex, {\n delay: this.options.animationDuration, align: 'end', reverse: true, event: function () {\n ctx.classList.add('hidden')\n }\n }).animate()\n }\n })\n }", "function timeo() {\n var myobj = document.getElementById(\"Table\")\n while (myobj.lastChild) {\n triggernum = true;\n myobj.removeChild(myobj.lastChild);\n }\n }", "async function removeFigureDOM(index) {\n await animateNode(listNodes[index]);\n await animateArrow(listArrows[index]);\n \n list.removeChild(listNodes[index]);\n list.removeChild(listArrows[index]);\n listNodes.splice(index, 1);\n listArrows.splice(index, 1);\n}", "function clearNode(node) {\n node.isLeaf = false;\n node.frequency = 0;\n for(var i = 0; i < 26; i++){\n node.children[i] = null;\n }\n}", "function removeCells(percent){\n while (list.length>percent*n*n){\n var index = list[list.length-1];\n svg.selectAll(\".cell\"+index).remove();\n list.splice(list.length-1, 1);\n // console.log(\"list.length\"+list.length);\n }\n}", "function deleteFN() {\n let sel = $('.selected');\n $('#' + sel.attr('line-target')).remove();\n sel.find('.node').each(function() {\n // Remove the linking lines.\n let attr = $(this).attr('line-target');\n if (typeof attr !== typeof undefined && attr !== false) {\n $('#' + attr).remove();\n }\n });\n sel.remove();\n targets = ['body'];\n }", "function deleteAndRaiseFN() {\n let sel = $('#' + $('.selected').attr('id'));\n let pos = sel.offset();\n let subTree = sel.detach();\n $('#' + sel.attr('line-target')).remove();\n subTree.appendTo('body');\n sel.css({\n 'top' : pos.top,\n 'left' : pos.left\n });\n calc_all_lines('#' + sel.attr('id'));\n }", "function graphRemove() {\r\n svg.selectAll(\"*\").remove();\r\n d3nodes = [];\r\n d3links = [];\r\n}", "function nexttimeMonthDelete(){\n\tvar element = document.getElementById(\"nexttime_month\");\n\tvar length = element.length;\n\tnexttime.month = 0;\n\t\n\tfor(var i = 0; i < length - 1; i++){\n\t\telement.removeChild(element.lastChild);\n\t}\n\t\n\tnexttimeDayDelete();\n}", "function clearScene (){\r\n for( var i = scene.children.length - 1; i >= 0; i--) {\r\n scene.remove(scene.children[i]);\r\n }\r\n }", "delete(node) {\n mona_dish_1.DQ.byId(node.id.value, true).delete();\n }", "function animateRemoval() {\n return $animateCss(element, {addClass: '_md-leave'}).start();\n }", "function destroyRenderNode(morph) {}", "function animate() {\n let animation = document.getElementById('movies-num');\n animation.style.animation = 'none';\n animation.offsetHeight;\n animation.style.animation = null;\n}", "destroyBetween(start, end) {\n if (start == end)\n return;\n for (let i = start; i < end; i++)\n this.top.children[i].destroy();\n this.top.children.splice(start, end - start);\n this.changed = true;\n }", "removeLife() {\r\n // increment here, to facilitate generating the\r\n // heartListOl.children index below\r\n this.missed = this.missed + 1;\r\n if (this.missed > maxMisses) {\r\n this.gameOver(false);\r\n } else {\r\n const li = heartListOl.children[heartListOl.children.length-this.missed];\r\n li.children[0].src=\"images/lostHeart.png\";\r\n }\r\n }", "_transitionExitNodes (source, nodes, transitionSpeed) {\n let nodeExit = nodes.exit()\n .transition()\n .duration(transitionSpeed)\n .attr(\"transform\", (d) => {\n return \"translate(\" + source.y + \",\" + source.x + \")\";\n })\n .remove();\n\n nodeExit.select(\"circle\")\n .attr(\"r\", 0);\n\n nodeExit.select(\"text\")\n .style(\"fill-opacity\", 0);\n }", "clearFromeScene()\r\n {\r\n for (var i=0;i<this.segMeshes.length;i++)\r\n {\r\n scene.remove(this.segMeshes[i]);\r\n }\r\n //alert(this.leafMeshes.length + \" \" +this.segMeshes.length);\r\n for (var i=0;i<this.leafMeshes.length;i++)\r\n {\r\n //alert(\"hm\");\r\n scene.remove(this.leafMeshes[i]);\r\n }\r\n }", "function destroyBlock(){\r\n document.getElementById(\"last-selected\").remove();\r\n}", "MoveInactive(nodelist) {\n //console.log('initial', this.nodes);\n if (nodelist.length > 0 && nodelist!=null) {\n //move nodes to timeout circle position *** max//\n for (let d of nodelist) {\n //console.log('refreshmove',this.processSeconds(d.timestamp));\n const nodeIndex = this.nodes.findIndex(node => node.id == d.id);\n if (nodeIndex >= 0 && this.nodes[nodeIndex] !== undefined) {\n if (this.act_counts[this.nodes[nodeIndex].act] > 0) {\n this.act_counts[this.nodes[nodeIndex].act] -= 1;\n }\n this.nodes[nodeIndex].act = 2\n d.act = 2\n this.act_counts[this.nodes[nodeIndex].act] += 1;\n this.nodes[nodeIndex] = {\n ...d,\n age: new Date()\n };\n this.force.resume();\n this.act_counts[this.nodes[nodeIndex].act] -= 1;\n this.fastSliceArray(this.nodes, nodeIndex);\n }\n }\n }\n }", "removeAnchoredNode(node) {\n\t\tfor (var i = 0; i < this.anchoredNodes.length; i++) {\n\t\t\tif (node === this.anchoredNodes[i].node) {\n\t\t\t\tthis.anchoredNodes.splice(i,1);\n this.scene.remove(node)\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t}", "function removeExtraCircles(){\n buildingBinding = objectContainer.selectAll(\".circleNode\");\n var loopCounter = 0;\n buildingBinding.each(function(d) {\n if(loopCounter >= startingNumOfCircles){\n var node = d3.select(this);\n node.remove();\n }\n loopCounter = loopCounter + 1;\n });\n}", "function animateRemoval() {\n return $animateCss(element, {addClass: '_md-leave'}).start();\n }", "function animateRemoval() {\n return $animateCss(element, {addClass: '_md-leave'}).start();\n }", "remove () {\r\n\t\tvar svg = d3.select(this.element);\r\n\t\tsvg.selectAll('*').remove();\r\n\t}", "function delnode(val,i){\r\n\r\n while(val!=mainarr[i][0]&&i<totnods){\r\n highlight[next++]=mainarr[i][0];\r\n if(mainarr[i][0]==undefined){\r\n break;\r\n }\r\n else if(val<mainarr[i][0]){\r\n i=2*i+1;\r\n }\r\n else if(val>mainarr[i][0]){\r\n i=2*i+2;\r\n }\r\n if(i>totnods){\r\n limitflag=true;\r\n break;\r\n }\r\n }\r\n //node present\r\n if(!limitflag&&mainarr[i][0]==val){\r\n console.log('node is present');\r\n highlight[next++]=mainarr[i][0];\r\n var lc=2*i+1,rc=2*i+2;\r\n //no child\r\n \r\n if(lc>=totnods||(mainarr[lc][0]==undefined&&mainarr[rc][0]==undefined)){\r\n console.log('no child');\r\n highlight[next++]=mainarr[i][0];\r\n mainarr[i][0]=undefined;\r\n mainarr[i][1]=undefined;\r\n mainarr[i][2]=undefined;\r\n msgflag=4;\r\n }\r\n else if(mainarr[lc][0]!=undefined){\r\n console.log('left child');\r\n }\r\n else{\r\n console.log('right child');\r\n }\r\n\r\n count_nodes--;\r\n }\r\n //node absent\r\n else{\r\n msgflag=6;\r\n }\r\n}", "function delete_circle() {\r\n\t$('#drag_resize').css({\"display\":\"none\"});\r\n}", "function __removeNodeFromCurrentQueue(_level,_node){\n currentAnimation[_level] = $.grep(currentAnimation[_level], function(obj){\n return obj['id'] !== _node['id'];\n });\n finishedAnimationQueue[_level].push(_node);\n }", "exitElements(){\n this.itemg.exit()\n .transition(this.transition)\n .style(\"opacity\", 0)\n .remove();\n }", "_reset(goal) {\r\n this.node.reset(!this.idle, goal);\r\n each(this._children, observer => {\r\n if (isAnimationValue(observer)) {\r\n observer._reset(goal);\r\n }\r\n });\r\n }", "start() {\n setTimeout(() => {\n if (this.node && this.node.destroy()) {\n console.log('destroy complete');\n }\n }, 5000);\n }", "function unFreeze(node){\n node.fixed = false;\n for( var i = 0; i < node.get('transitions').length; i++ ) {\n var childNode = idMap[node.get('transitions')[i].target];\n unFreeze(childNode);\n }\n }", "function animateRemoval() {\n return $animateCss(element, {addClass: 'md-leave'}).start();\n }", "function animateRemoval() {\n return $animateCss(element, {addClass: 'md-leave'}).start();\n }", "function animateRemoval() {\n return $animateCss(element, {addClass: 'md-leave'}).start();\n }", "function animateRemoval() {\n return $animateCss(element, {addClass: 'md-leave'}).start();\n }", "function animateRemoval() {\n return $animateCss(element, {addClass: 'md-leave'}).start();\n }", "function animateRemoval() {\n return $animateCss(element, {addClass: 'md-leave'}).start();\n }", "function clearScene() {\n for (var i = scene.children.length - 1; i >= 0; --i) {\n var obj = scene.children[i];\n scene.remove(obj);\n }\n}", "clear() {\n if (this.current.lastChild) {\n console.log(this.current.lastChild)\n this.current.removeChild(this.current.lastChild)\n }\n return\n }", "function remover(myNode){\r\n\r\n while(myNode.hasChildNodes())\r\n {\r\n myNode.removeChild(myNode.lastChild);\r\n }\r\n }", "function remove() {\n var index = Math.floor(Math.random() * values.length);\n console.log(\"DEL \" + values[index]);\n tree.remove(values[index]);\n values.splice(index, 1);\n}", "function deleteMax(h) { \n if (isRed(h.left))\n h = rotateRight(h);\n\n if (h.right == null || h.right == undefined)\n return null;\n\n if (!isRed(h.right) && !isRed(h.right.left))\n h = moveRedRight(h);\n\n h.right = deleteMax(h.right);\n\n return balance(h);\n }", "function moveSlot(parent) {\n for (var i = 0; i < 10; i++) {\n var rand = Math.floor(Math.random() * imgUrl.length);\n parent.prepend('<div class=\"logo\" data-img=\"' + imgUrl[rand] + '\"><img src=\"' + imgUrl[rand] + '\"></div>');\n }\n parent.addClass('animate');\n setTimeout(function () {\n parent.children('.logo:gt(2)').remove();\n parent.removeClass('animate');\n },1500)\n}", "removeSize() {\n this.size = 0;\n }", "removeSelf() {\n this.DOM.wrap.remove();\n\n /*\n this.getChildren.forEach((child) => {\n child.offline();\n });*/\n }", "remove() {\n console.log('Deleting Ghosts...');\n clearInterval(this.trailInterval);\n _.each(this.clones, (clone) => {\n this.parent.remove(clone);\n clone = null;\n });\n }", "deleteAt(index){\n if(index > this.count - 1){\n return;\n }\n if(index === 0){\n this.head = this.head.next;\n } else{\n let tempIndex = 0;\n let node = this.head;\n while(tempIndex < index -1){\n node = node.next;\n tempIndex += 1;\n }\n node.next = node.next.next;\n this.count -= 1;\n }\n }", "function deleteElement(elementID){\n var currentDuration = 0;\n for (var i = 0; i < diagram.length; i++) {\n var cur = diagram[i];\n if (cur._id == elementID) {\n currentDuration = cur.end_time - cur.start_time;\n for (var j = i; j < diagram.length; j++) {\n var node = diagram[j];\n diagram[j].start_time = diagram[j].start_time - currentDuration;\n diagram[j].end_time = diagram[j].end_time - currentDuration;\n $(\"#time_\"+diagram[j]._id).text(diagram[j].start_time);\n }\n totalTime = totalTime - currentDuration;\n diagram.splice(i, 1);\n break;\n }\n }\n $(\"#\"+elementID).remove();\n $(\"#timeline_\"+elementID).remove();\n}", "function deleteNeume(){\n currentSyllable.neumes.splice(currentNeumeIndex, 1);\n \n currentNeumeIndex = 0;\n \n document.getElementById(\"input\").innerHTML = neumeDataChangeForm();\n document.getElementById(\"meiOutput\").value = createMEIOutput();\n createSVGOutput();\n}", "function undoLast() {\n var x = document.getElementById(\"movieList\");\n if(x.hasChildNodes()){\n x.removeChild(x.lastChild);\n }\n}", "remove () {\n this.node.parentNode.removeChild(this.node)\n this.stylesheet.parentNode.removeChild(this.stylesheet)\n }", "removeAllChildren() {\n for (let i = 0; i < this.children.length; ++i) {\n this.children[i].destroy();\n }\n this.children.length = 0;\n }", "undoPos()\n {\n this.dot.undoPos();\n }" ]
[ "0.7379584", "0.72975993", "0.6662128", "0.65339935", "0.6525566", "0.651626", "0.651626", "0.63917893", "0.6388692", "0.62053037", "0.61227125", "0.6117489", "0.6116594", "0.60836446", "0.6061511", "0.6052558", "0.6017127", "0.6011314", "0.59932804", "0.5989712", "0.5985415", "0.59809136", "0.5958224", "0.5949225", "0.5947244", "0.5934425", "0.5917318", "0.5909829", "0.5884384", "0.5840098", "0.5816933", "0.5799791", "0.5797867", "0.5789068", "0.57182354", "0.570979", "0.5705162", "0.5701452", "0.5701452", "0.57011366", "0.5700712", "0.569667", "0.56630164", "0.56505406", "0.564861", "0.5647195", "0.5645234", "0.5644388", "0.5639934", "0.5630945", "0.56156003", "0.5608547", "0.5605853", "0.5605294", "0.5597473", "0.55971575", "0.5590058", "0.5582772", "0.5582599", "0.5567723", "0.55657744", "0.55655396", "0.5559251", "0.5558746", "0.55500436", "0.5542683", "0.55405456", "0.5537441", "0.5535009", "0.5535009", "0.55334854", "0.55283797", "0.55259496", "0.55185854", "0.5513655", "0.551008", "0.54976505", "0.5491701", "0.5490497", "0.5490497", "0.5490497", "0.5490497", "0.5490497", "0.5490497", "0.548528", "0.548237", "0.5480085", "0.5476667", "0.5472004", "0.54643774", "0.54573464", "0.54536766", "0.5443701", "0.5441444", "0.54332316", "0.5432547", "0.5431202", "0.5429397", "0.541407", "0.5414029" ]
0.7588953
0
delete a specific key from bst
animateDelete(key) { const animations = []; animations.push(new Animation("display", `Deleting ${key}`)); this.root = this.animateDeleteHelper(this.root, key, animations); this.positionReset(); // reset x,y positions of nodes // highlight last node in green if found if (compareTo(animations[animations.length - 1].getItem(), key) === 0) { animations[animations.length - 1].setClass("found-node"); animations.push(new Animation("display", `Deleted ${key}`)); return [key, animations]; } // highlight last node in red if not found else { animations[animations.length - 1].setClass("search-failed-node"); animations.push(new Animation("display", "Not Found")); return [null, animations]; } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "async delete(key) {}", "delete(key: K) {\n this.tree.remove([key, null]);\n }", "delete(key){\n const address = this._hash(key);\n if(this.data[address]){\n for (let i = 0; i < this.data[address].length; i++) {\n let currenctBucket = this.data[address][i];\n if (currenctBucket) {\n if (currenctBucket[0] === key) {\n this.data[address].splice(i,1);\n return;\n }\n }\n }\n }\n return undefined;\n }", "delete(key) {\n\t\tthis.update( state => {\n\t\t\t\tthis.removeChildAt(key);\n\n\t\t\t\treturn { name: `delete(${key})`, nextState: omit(state, key) };\n\t\t\t});\n\t}", "function remove(key) {\r\ndelete this.datastore[key];\r\n}", "function deleteKey(key)\n {\n this.root = this.deleteRec(this.root, key);\n }", "removekey(value) {\n\n this.root = this.remove(this.root, value)\n\n }", "function del(key) {\n return db.delete(key);\n}", "async del(key) {\n if (this.isCheckpoint) {\n // delete the value in the current cache\n this.checkpoints[this.checkpoints.length - 1].keyValueMap.set(key.toString('binary'), null);\n }\n else {\n // delete the value on disk\n await this._leveldb.del(key, db_1.ENCODING_OPTS);\n }\n }", "function del(root, key, cb) {\n cb = cb || noop\n this.root = decode(root)\n key = decode(key)\n this.del(key, function() {\n cb(null, encode(this.root))\n }.bind(this))\n}", "del(key, overrideDb) {\n let currentState;\n if (overrideDb) {\n currentState = overrideDb;\n delete currentState[key];\n } else {\n currentState = this.db;\n\n if (this.currentTransactionIndex > -1) {\n this.transactions[this.currentTransactionIndex].push(`DELETE ${key}`);\n } else {\n delete currentState[key];\n }\n }\n \n if (debug) {\n console.log('db: ', currentState);\n console.log('transactions: ', this.transactions, '\\n');\n }\n }", "async del (key) {\n return await this.safeDelete([this.namedKey(key)]);\n }", "static deleteKeyFromDB(dbElementName, key) {\r\n\t\treturn DBHelper.openDB('restaurant-review-DB').then(db => {\r\n\t\t\tconst tx = db.transaction(dbElementName, 'readwrite');\r\n\t\t\ttx.objectStore(dbElementName).delete(key);\r\n\t\t\treturn tx.complete;\r\n\t\t});\r\n\t}", "delete(key) {\n this.map[key] = undefined;\n if (this.store) this.store.removeItem(key);\n }", "remove(key) {\n delete this.store[key];\n }", "function remove(key) {\n\tdelete this.dataStore[key];\n}", "erase(key) {\n this.eraseNode(treeFind(this.root, key));\n }", "remove(key) {\n delete this.store[key];\n }", "remove(key) {\n delete this.store[key];\n }", "remove(key) {\n delete this.store[key];\n }", "remove(key) {\n delete this.store[key];\n }", "remove(key) {\n delete this.store[key];\n }", "remove(key) {\n const h = this.hash(key);\n\n let found = this.structure[h];\n if (found) {\n if (Array.isArray(found)) {\n for (let i = 0; i < found.length; i++) {\n if (found[i]['key'] === key) {\n found = found[i]['key'];\n this.structure[h].splice(i, 1);\n break;\n }\n }\n } else {\n this.structure.splice(h, 1);\n }\n this.size -= 1;\n return found;\n }\n\n return undefined;\n }", "remove(key) {\n let index = hash(key, this.storageLimit);\n\n if (this.storage[index].length === 1 && this.storage[index][0][0] === key) {\n delete this.storage[index];\n } else {\n for (let i = 0; i < this.storage[index]; i++) {\n if (this.storage[index][i][0] === key) {\n delete this.storage[index][i];\n break;\n }\n }\n }\n }", "removeNode(key) {\n const { nodes } = this;\n if (nodes.all[key]) {\n debug(\"Remove %s from the pool\", key);\n delete nodes.all[key];\n }\n delete nodes.master[key];\n delete nodes.slave[key];\n }", "remove(key) {\r\n const hash = this.calculateHash(key);\r\n if(this.values.hasOwnProperty(hash) && this.values[hash].hasOwnProperty(key)) {\r\n delete this.values[hash][key];\r\n this.numberOfValues--;\r\n }\r\n }", "function remove(key) {\n delete this.dataStore[key];\n }", "delete(k) {\n return delete this.kvStore[k]\n }", "async removeItem(tagoRunURL, key) {\n const result = await this.doRequest({\n path: `/run/${tagoRunURL}/sdb/${key}`,\n method: \"DELETE\",\n });\n return result;\n }", "function remove({ key, obj }) {\n\n // REMOVE THE KEY\n delete obj[key]\n\n return obj;\n}", "remove(key) {\n const index = getIndexBelowMax(key.toString(), this.limit);\n const bucket = this.storage.get(index);\n if (Array.isArray(bucket)) {\n for (let i = 0; i < bucket.length; i++) {\n const objKey = bucket[i][0];\n if (objKey === key) {\n bucket.splice(i, 1);\n }\n }\n }\n }", "delete(key) {\n const index = this._findSlot(key)\n const slot = this._hashTable[index]\n if(slot === undefined){\n throw new Error('Key Error')\n }\n slot.DELETED = true\n this.length--\n this._deleted++\n }", "remove(key) { \n debug('remove', key);\n return this._doDelete(this._singleResourceURI(key));\n }", "function destructivelyDeleteFromDriverByKey(obj, key) {\n delete obj[key];\n return obj;\n }", "deleteOne(storename, key) {\n this.cache.then((db) => {\n db.transaction(storename, \"readwrite\").objectStore(storename).delete(key);\n });\n }", "function deleteFromObjectByKey(object, key){\n var newobj = Object.assign({},object)\n return delete newobj[key]\n}", "function deleteIndexedDB(objectStore, key) {\r\n let openDB = openIndexedDB();\r\n\r\n openDB.onsuccess = function() {\r\n let db = getStoreIndexedDB(openDB, objectStore);\r\n let deleteRequest = db.store.delete(key);\r\n\r\n deleteRequest.onsuccess = function() {\r\n console.log(\"IndexedDB delete() request onSuccess\")\r\n }\r\n \r\n }\r\n\r\n}", "function deleteFromDriverByKey(obj,key) {\n const newObj = Object.assign({},obj);\n // console.log(newObj);\n delete newObj[key];\n return newObj;\n}", "remove(bucket, key) {\n return this.store.del(`${bucket}${DELIM}${key}`);\n }", "function destructivelyDeleteFromDriverByKey(driver,key){\n delete driver[key]\n return driver\n}", "function remove(key) { return local.remove(key); }", "function deleteFromDriverByKey(driver,key) {\n const new_driver = { ...driver }\n delete new_driver[key]\n return new_driver\n}", "function removeItem(key, callback) {\n switch (dbBackend) {\n case DB_TYPE_INDEXEDDB:\n indexedTransaction('readwrite', function removeItemBody(store) {\n var request = store.delete(key);\n if (callback) {\n request.onsuccess = function removeItemOnSuccess() {\n callback();\n };\n }\n request.onerror = _errorHandler(request);\n });\n break;\n case DB_TYPE_LOCALSTORAGE:\n localStorage.removeItem(key);\n callback();\n break;\n }\n }", "delete(key) {\n const index = this._findSlot(key)\n const slot = this._hashTable[index]\n if (slot === undefined) {\n throw new Error('Key error')\n }\n slot.DELETED = true\n this.length--\n this._deleted++\n }", "function destructivelyDeleteFromDriverByKey(obj, key) {\n delete obj[key];\n return obj;\n}", "function deleteFromObjectByKey(object, key){\n //you can use a around word for this part recipes\n recipes = Object.assign({}, object)\n delete recipes[key]\n return recipes\n}", "delete(key){\n this.props.delete(key);\n }", "delete(key) {\n if (this.enabled) {\n this.store.removeItem(key);\n }\n }", "deleteSubKey() {\n if (Array.isArray(this.getSubKey()) && this.getSubKey().length > 0) {\n delete this[this._subKey];\n }\n }", "function deleteItem(key) {\n return Promise.resolve(key)\n .then(function(key) {\n return map.delete(key)\n })\n }", "remove(key)\r\n {\r\n var list = this.#table[int(this.#hash(key) & this.#divisor)];\r\n var k = list.length;\r\n for (var i = 0; i < k; i++)\r\n {\r\n var entry = list[i];\r\n if (entry.key === key)\r\n {\r\n list.splice(i, 1);\r\n return entry.data;\r\n }\r\n }\r\n return null;\r\n }", "deleteCurrentEditEntry(key) {\n let newUserData = this.state.userData;\n delete newUserData[key];\n firebase.database().ref('userData/' + this.props.user.uid + '/userJournalEntries').set(newUserData);\n }", "function deleteFromDriverByKey(driver, key, value){\n const newObj = {...driver}\n delete newObj[key]\n\n return newObj\n}", "rem(key, member, cb){\n let set = this.setsMap.get(key),\n deleted = 0;\n\n if(set && set.delete(member)){\n deleted = 1;\n if(set.size === 0){\n this.setsMap.delete(key);\n }\n }\n\n cb && cb(null, deleted);\n }", "delete(key) {\n return this.client.del(key);\n }", "delete(key){\n this.props.delete(key);\n\n }", "delete(key, value, id = null, index = null, dbName = null) {\n const url = this.getApiUrl(dbName);\n\n if (index != null) {\n throw \"'delete' does not support 'index' parameter\";\n }\n\n if (value == null && id != null) {\n value = {\n id: id\n };\n }\n\n const urlParam = new URL(url + key);\n // urlParam.search = new URLSearchParams({\n // id: id,\n // index: index\n // });\n\n console.log(\">>> DB '\" + url + \"' DELETE for key=\" + key); // #DEBUG\n\n let retry = 0;\n const request = () => {\n return fetch(urlParam, {\n method: 'DELETE',\n headers: this.prepareHeaders(),\n body: this.prepareBody(value)\n }).then(response => {\n return this.validateResponse(response);\n }).catch(err => {\n if (retry < HostStorageService.MAX_RETRIES) {\n retry++;\n this.onRetry(retry);\n\n request(); // recursion for re-tries\n } else {\n this.validateResponse(err);\n }\n });\n };\n\n return request();\n }", "static remove(key) {\n PStore.remove(key);\n }", "function remove(key) {\n context.removeItem(key);\n}", "delete(key) {\n this.storageMechanism.removeItem(key);\n }", "async del (key) {\n if (!this.opened)\n throw new Error(\"still not opened\")\n return new Promise((resolve, reject) => {\n this.db.query(`DELETE FROM ${this.options.table} ` +\n `WHERE ${this.options.colKey} = ?;`,\n [ key ],\n (err) => {\n if (err) reject(err)\n else resolve()\n }\n )\n })\n }", "async function delBkmk (a_id, a_BN) {\n let len = a_BN.length;\n // Fecord a multiple operation if more than one item in the array\n if (len > 1) {\n\tawait recordHistoryMulti((options.trashEnabled ? \"remove_tt\" : \"remove\"), a_id);\n }\n\n let BN;\n for (let i=0 ; i<len ; i++) {\n\tBN = a_BN[i];\n//trace(\"Remove BN id: \"+BN.id);\n\t// If BSP2 trash enabled, move the bookmark item to trash instead (except when already in trash, where we really delete it)\n\tlet bnId = BN.id;\n\tif (options.trashEnabled && !BN.inBSP2Trash) { // Move at end of trash\n\t await browser.bookmarks.move(\n\t\tbnId,\n\t\t{parentId: bsp2TrashFldrBNId\n\t\t}\n\t );\n\t}\n\telse { // Really delete the bookmark item\n\t await browser.bookmarks.removeTree(bnId);\n\t}\n }\n}", "function removeKey(obj, key) {\n //copy the original object into a new one and use it to remove a key \n let obj2 = {...obj};\n delete obj2[key];\n //console.log({...obj2});\n return obj2;\n}", "remove(key) {\n\n // getIndexBelowMax(this.storage[key]);\n }", "function deleteFromDriverByKey(obj, key) {\n const newDriver = Object.assign({}, driver);\n\n delete newDriver[key];\n return newDriver;\n\n}", "delete(key) {\n return assertCollection(this.contents) ? this.contents.delete(key) : false;\n }", "del(key) {\n this._update(key, new ethereumjs_account_1.default(), false, true);\n }", "function deleteValue(key, obj, type = 1) {\n obj[key] -= type\n }", "delete(storeName, key) {\n return from(new Promise((resolve, reject) => {\n openDatabase(this.indexedDB, this.dbConfig.name, this.dbConfig.version)\n .then((db) => {\n validateBeforeTransaction(db, storeName, reject);\n const transaction = createTransaction(db, optionsGenerator(DBMode.readwrite, storeName, reject, resolve));\n const objectStore = transaction.objectStore(storeName);\n objectStore.delete(key);\n transaction.oncomplete = () => {\n this.getAll(storeName)\n .pipe(take(1))\n .subscribe((newValues) => {\n resolve(newValues);\n });\n };\n })\n .catch((reason) => reject(reason));\n }));\n }", "removeChildAt(key) {\n\t\tconst mapping = this.nextMapping();\n\t\tconst child = mapping[key];\n\n\t\tif (child) {\n\t\t\tthis.removeChild(child);\n\t\t}\n\t}", "deleteRepair($key) {\n this.repairList.remove($key);\n }", "function deleteFromDriverByKey(driver, key){\n const newObj = Object.assign({}, driver);\n delete newObj[key];\n return newObj;\n }", "function cb_removeKeys(event) {\n const db = event.target.result;\n db.onerror = event => {\n output(\"Database error (\" + event.target.errorCode + \") \" + event.target.error);\n };\n var keys = [];\n const store = db.transaction([\"keys\"], \"readwrite\").objectStore(\"keys\");\n store.onerror = event => {\n output('Error opening store');\n }\n store.onsuccess = findKeys();\n store.delete(user_email);\n}", "remove(key) {\n this._remove(this._translateKey(key));\n }", "delete (key, options, filter) {\n // If no prefix match, then return\n const n = options.match(key, this.skip)\n if (n !== this.skip.length) {\n return undefined\n }\n\n // If this is a terminal node, binary search for the key\n if (!this.edges) {\n this._sortValues(options)\n const needle = options.setKey({}, key) // Create a dummy value for searching\n const idx = bounds.eq(this.values, needle, options.comparator)\n if (idx >= 0) {\n const [ keep, removed ] = this._delete(this.values[idx], filter)\n if (keep === undefined) {\n this.values.splice(idx, 1)\n }\n return removed\n }\n return undefined\n }\n\n // Check if the internal value matches this key\n if (n === key.length) {\n const [ keep, removed ] = this._delete(this.values, filter)\n this.values = keep\n return removed\n }\n\n // Traverse the jump table\n const x = key.charAt(this.skip.length)\n const child = this.edges[x]\n if (child) {\n // Call delete recursively\n const ret = child.delete(key, options, filter)\n if (ret !== undefined) {\n this._compact(x, child) // Compact if we actually removed something\n }\n return ret\n }\n return undefined\n }", "function delete_boat(boat_id) {\r\n const b_key = datastore.key( ['BOAT', parseInt(boat_id, 10)] ); // Create key for ds entity deletion\r\n return datastore.delete(b_key); // Delete entity and return to calling function\r\n}", "function del(key, customStore = defaultGetStore()) {\n return customStore('readwrite', (store) => {\n store.delete(key);\n return promisifyRequest(store.transaction);\n });\n }", "static DeleteKey() {}", "function deleteTodo(key) {\n //Retrieve the index of the todo entry in the collection\n const index = todoItems.findIndex((item) => item.id === Number(key));\n //set delete attribute to true for the todo entry\n const todo = {\n deleted: true,\n ...todoItems[index],\n };\n todoItems = todoItems.filter((item) => item.id !== Number(key));\n //Trigger page update by (invoking) calling the renderTodo function\n renderTodo(todo);\n}", "removeItem(key) {\n return this.store.delete(key);\n }", "function deleteFromDriverByKey(driver, key){\n const newDriver = Object.assign({}, driver);\n\n delete newDriver[key];\n\n return newDriver;\n}", "deleteItem(key) {\n const filteredItem = this.state.items.filter(item => item.key!==key);\n this.setState({\n items: filteredItem\n })\n }", "function deleteFromDriverByKey(driver, key) {\n let newDriver = Object.assign({}, driver)\n delete newDriver[key]\n return newDriver\n}", "function del(target, key) {\n if (Array.isArray(target) && isValidArrayIndex(key)) {\n target.splice(key, 1);\n return;\n }\n\n var ob = target.__ob__;\n\n if (target._isGengine || ob && ob.gmCount) {\n return;\n }\n\n if (!hasOwn(target, key)) {\n return;\n }\n\n delete target[key];\n\n if (!ob) {\n return;\n }\n\n ob.dep.notify();\n}", "deleteItem(key) {\n const filteredItems = this.state.items.filter(item => item.key!==key);\n this.setState({\n items:filteredItems\n })\n }", "function destructivelyDeleteFromObjectByKey(object, key){\n delete object[key];// modifies the original object\n return object;//returns object without the delete key/value pair\n}", "function deleteRecord(db, table, key) {\n var $def = $.Deferred();\n var transaction = db.transaction([table], 'readwrite');\n var req = transaction.objectStore(table).delete(key);\n req.onerror = function(e) {\n $def.reject('delete record failed');\n };\n transaction.oncomplete = function(event) {\n $def.resolve(key);\n };\n return $def;\n }", "function deleteBoat(boatId){\n if(typeof boatId === 'undefined'){\n const query = datastore.createQuery('boat')\n\n return datastore.runQuery(query)\n .then((results) => {\n const entities = results[0];\n\t\t\t\tvar allBoatKeys = [];\n\t\t\t\t/*for(var i = 0; i < entities.length; i++){\n\t\t\t\t\tallBoatKeys.push(entities[i][datastore.KEY])\n\t\t\t\t}*/\n\t\t\t\tentities.map((entity) => {\n\t\t\t\t\tallBoatKeys.push(entity[datastore.KEY]);\n\t\t\t\t});\n\n\t\t\t\tdatastore.delete(allBoatKeys)\n\t\t\t\t\t.then(() => {\n\t\t\t\t\t\tconsole.log('deleteBoat (All boats) complete');\n\t\t\t\t\t});\n });\n }else{\n const query = datastore.createQuery('boat')\n .filter('__key__', '=', boatId);\n\n return datastore.runQuery(query)\n .then((result) => {\n const entities = result[0];\n const entity = entities[0];\n var key = entity[datastore.KEY];\n\t\t\t\t\n\t\t\t\tdatastore.delete(key)\n\t\t\t\t\t.then(() => {\n\t\t\t\t\t\tconsole.log('deleteBoat (one boat) complete');\n\t\t\t\t\t});\n });\n }\n}", "remove ( key ) {\n\t\tlet _this = this;\n\t\ttry{\t\n\t\t\tvar st=this._gt();\n\t\t\tlet oBody = this._generateCacheObj (key,-1,'','');\t\t\n\t\t\tconsole.dir(this._requestOptions(HTTP_HEADER[HTTP_METHOD_RM],HTTP_HEADER[HTTP_METHOD_POST],oBody));\n \t\tlet req = http.request( this._requestOptions(HTTP_HEADER[HTTP_METHOD_RM],HTTP_HEADER[HTTP_METHOD_POST],oBody), function( res ) {\n\t\t\t\tvar buffer = \"\";\n \t\t\t\tres.on( EVT[EVT_HTTP_DATA], function( data ) \t{ buffer = buffer + data; });\n\t\t\t\tres.on( EVT[EVT_HTTP_END], \tfunction( data ) \t{ \n\t\t\t\t\tlet bO = JSON.parse(buffer);\n\t\t\t\t\t//console.dir(bO);\n\t\t\t\t\t_this._st('get',st,_this._gt());\n\t\t\t\t\tswitch (bO.errorCode){\n\t\t\t\t\t\tcase 1 :\n\t\t\t\t\t\t\t_this.emit(EVT[EVT_TTCACHE_RM],bO); \n\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase 0 :\n\t\t\t\t\t\t\t_this.emit(EVT[EVT_TTCACHE_RM],bO); \n\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\t_this.emit(EVT[EVT_HTTP_ERR],'undefined switch@error'); \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\treq.on( EVT[EVT_HTTP_ERR],\tfunction( e) \t\t{ _this.emit(EVT[EVT_TTCACHE_ERR],e) });\n\t\t\t});\t\n\t\t\treq.write(oBody);\n\t\t\treq.end();\t\n\t\t} catch (err ){\n\t\t\tthrow err\n\t\t}\n\t}", "delete(key) {\n log.map(\"Deleting key '%s' from the map\", key);\n return this._map.delete(key);\n }", "function destructivelyDeleteFromDriverByKey (driver, key) {\n delete driver[key];\n return driver;\n }", "function deleteTodo(key) {\n //Retrieve the index of the todo entry in the collection. \n const index = todoItems.findIndex((item) => item.id === Number(key));\n //Set delete attribute to true for todo entry\n const todo = {\n deleted: true,\n ...todoItems[index],\n\n };\n todoItems = todoItems.filter((item) => item.id !== Number(key));\n // console.table(todoItems)\n //trigger page update by invoking renderTodo function.\n renderTodo(todo);\n}", "function destructivelyDeleteFromObjectByKey(object, key) {\n delete object[key];\n return object\n}", "del(transaction, bucket, keys) {\n contract(arguments).params(\"object\", \"string\", \"string|array\").end();\n\n keys = Array.isArray(keys) ? keys : [keys];\n\n keys = keys.map((key) => this.bucketKey(bucket, key));\n\n transaction.del(keys);\n }", "static remove(history, key) {\n return new Promise((resolve, reject) => {\n this.getAll(history).then((data) => {\n if (data !== null) {\n delete data[key];\n\n this._post(history, data)\n .then(function (result) {\n // return full object within the callback\n resolve(data);\n })\n .catch(function () {\n reject(false);\n });\n }\n resolve(data);\n });\n });\n }", "function removeFromIndex(obj) {\n\t\t\tvar objKey, item, keys, j, key, indexItem;\n\t\t\t// Find the item to delete\n\t\t\tobjKey = obj.bob.index.call(obj).uid;\n\t\t\titem = items[objKey];\n\t\t\tkeys = item.keys;\n\t\t\t// Iterate through all the keys and remove the item from each of them\n\t\t\tfor (j = 0; j < keys.length; j = j + 1) {\n\t\t\t\tkey = keys[j];\n\t\t\t\tindexItem = index[key];\n\t\t\t\tif (indexItem) {\n\t\t\t\t\tdelete indexItem[objKey];\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn obj;\n\t\t}", "delete(key, options) {\n const serializeOptions = {\n expires: DELETED_EXPIRATION\n };\n if (options == null ? void 0 : options.domain) {\n serializeOptions.domain = options.domain;\n }\n if (options == null ? void 0 : options.path) {\n serializeOptions.path = options.path;\n }\n this.#ensureOutgoingMap().set(key, [\n DELETED_VALUE,\n serialize(key, DELETED_VALUE, serializeOptions),\n false\n ]);\n }", "[mutationTypes.UPDATE_BANKERS](state, key) {\n\t\t// 没有可以全部删除\n\t\tif (!key) {\n\t\t\tstate.bankerMap = {};\n\t\t\treturn;\n\t\t}\n\t\tconst bankerMap = state.bankerMap;\n\t\tif (bankerMap[key]) {\n\t\t\tVue.delete(bankerMap, key);\n\t\t} else {\n\t\t\tVue.set(bankerMap, key, 1);\n\t\t}\n\t}", "function destructivelyDeleteFromObjectByKey(object, key) {\n delete object[key];\n return object;\n}", "delete(node) {\n mona_dish_1.DQ.byId(node.id.value, true).delete();\n }", "function destructivelyDeleteFromObjectByKey(object, key) {\n delete object[key]\n return object\n}" ]
[ "0.7587212", "0.7576173", "0.7471219", "0.7264688", "0.7240824", "0.70758283", "0.6920737", "0.6865355", "0.684363", "0.68303055", "0.6800355", "0.67972964", "0.6765296", "0.67506516", "0.67473835", "0.67216694", "0.6717055", "0.66764915", "0.66764915", "0.66764915", "0.66764915", "0.66764915", "0.66758585", "0.66688496", "0.66610247", "0.66287595", "0.6628537", "0.6603373", "0.65992504", "0.65759784", "0.6572023", "0.65298843", "0.64793587", "0.6460994", "0.6424774", "0.64137506", "0.64050734", "0.64037365", "0.63684326", "0.63526994", "0.6344987", "0.6343071", "0.6327608", "0.6324788", "0.6322858", "0.6318462", "0.6306483", "0.6274478", "0.6272447", "0.62523687", "0.6249603", "0.62483835", "0.6235129", "0.6234405", "0.621886", "0.62170714", "0.6215442", "0.621165", "0.6206694", "0.61823434", "0.6178305", "0.61781013", "0.6171747", "0.6170112", "0.6164391", "0.6163271", "0.61585873", "0.615146", "0.61477137", "0.61462206", "0.61433977", "0.61314666", "0.61086994", "0.61074466", "0.61005116", "0.6093628", "0.6089315", "0.60792184", "0.607818", "0.60658145", "0.60638446", "0.6061871", "0.60588676", "0.60554457", "0.6052417", "0.6050728", "0.60488665", "0.6048737", "0.6047062", "0.60451114", "0.6040495", "0.60346836", "0.60334724", "0.6033256", "0.60286564", "0.6022918", "0.60223716", "0.6022062", "0.6017848", "0.6011953", "0.60080755" ]
0.0
-1
return key in bst with given rank
animateSelect(rank) { let animations = []; animations.push(new Animation("display", `Select ${rank}`, "")); const node = this.animateSelectHelper(this.root, rank, animations); // highlight last node in red if not found if (node === null) { animations[animations.length - 1].setClass("search-failed-node"); animations.push(new Animation("display", "Not Found", "")); } // highlight last node in green if found else animations[animations.length - 1].setClass("found-node"); animations.push(new Animation("display", node.value, "")); return [node, animations]; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function findKthLargestValueInBst(tree, k) {\n let treeInfo = new TreeInfo(0, -1)\n reverseInOrderTraverse(tree, k, treeInfo)\n return treeInfo.currVisitedNodeValue\n }", "find (key) {\n key = toNumber(input);\n let node = this.root;\n while (node != null) {\n if (key < node.key) {\n node = node.left;\n } else if (key > node.key) {\n node = node.right;\n } else {\n return node.value;\n }\n }\n return null;\n }", "function findKthLargestValueInBst(tree, k) {\n let results = [];\n\n dfs(tree);\n\n return results[results.length - k];\n\n function dfs(node) {\n if (!node) {\n return;\n }\n\n if (node.left) {\n dfs(node.left);\n }\n\n results.push(node.value);\n\n if (node.right) {\n dfs(node.right);\n }\n }\n}", "function findRank(pos){\n\tfor (var i = 0; i < 32; i++){\n\t\tif (sortedTeams[i] == pos){\n\t\t\treturn i;\n\t\t}\n\t}\n}", "searchBucket(bucket, key) {\n if (typeof key !== 'string') key = key.toString();\n let current = bucket.head;\n while (current) {\n if (Object.keys(current.value)[0] === key) {\n return Object.values(current.value)[0];\n } else {\n current = current.next;\n }\n }\n return null;\n }", "function findKthLargestValueInBst(tree, k) {\n const treeInfo = new TreeInfo(0, -1);\n reverseInOrderTraverse(tree, k, treeInfo);\n return treeInfo.latestVisitedNodeValue;\n}", "_findInBucket( bucket, neddle ) {\n return bucket.filter( ([key, value]) => key === neddle )[0] || undefined;\n }", "retrieve(k) {\n var index = getIndexBelowMaxForKey(k, this._limit);\n var indexBucket = this._storage.get(index);\n var result;\n for (var i = 0; i < indexBucket.length; i ++) {\n if (indexBucket[i][0] === k) {\n result = indexBucket[i][1];\n }\n }\n return result;\n }", "rank(i) { return this.#rank[i]; }", "mrhof_rank_via_nbr(nbr) {\n const min_hoprankinc = this.node.config.RPL_MIN_HOPRANKINC;\n const path_cost = this.mrhof_nbr_path_cost(nbr);\n\n /* Rank lower-bound: nbr rank + min_hoprankinc */\n return Math.max(Math.min(nbr.rank + min_hoprankinc, RPL_INFINITE_RANK), path_cost);\n }", "findNodeByKey (key) {\n return Tree.findEntry2 (key, this.rootEntry);\n }", "get(nk){\n for(let [k, v] of this.kmap){\n if(equal(k, nk)) return v;\n }\n return new Nil;\n }", "retrieve(key) {\n const index = getIndexBelowMax(key.toString(), this.limit);\n const bucket = this.storage.get(index);\n if (bucket !== undefined) {\n let current = bucket.head;\n while (current) {\n if (current.value[0] === key) {\n return current.value[1];\n }\n current = current.next;\n }\n }\n }", "search(key, root=this.root){\n if(root.data == key){\n return root\n }\n if(root.data < key){\n return this.search(key, root.nodeR);\n }else{\n return this.search(key, root.nodeL)\n }\n }", "function getRank(team, rankingIndex) {\n // We might be pointing to a ranking which doesn't exist.\n // Duplicate the ranking to keep a flat line at the graph's edges.\n rankingIndex = Math.min(Math.max(rankingIndex, 0), numberOfRankings - 1);\n // Find the rank at the given rankings.\n const rank = team.ranks[rankingIndex];\n return rank && rank > topNRanks ? null : rank;\n }", "function getRankedBBR(stat) {\n\tconst copy = dataBBR.map(d => {\n\t\tconst minutes = +d.G * +d.MP;\n\t\tconst threshold = MIN_MP_SPECIAL[d.Season] || MIN_MP_DEFAULT;\n\t\tconst statValue = minutes >= threshold ? +d[stat] : -9999;\n\t\treturn {\n\t\t\tbbrID: d.bbrID,\n\t\t\tSeason: d.Season,\n\t\t\t[[`${stat}_value`]]: statValue\n\t\t};\n\t});\n\n\tconst nested = d3\n\t\t.nest()\n\t\t.key(d => d.Season)\n\t\t.sortValues((a, b) => d3.descending(a[`${stat}_value`], b[`${stat}_value`]))\n\t\t.entries(copy);\n\n\t// add rank as col\n\tconst ranked = nested.map(season => {\n\t\tconst justValues = season.values.map(v => v[`${stat}_value`]);\n\t\t// season.values.forEach((d, i) => (d[`${stat}_rank`] = i));\n\t\treturn season.values.map(d => {\n\t\t\tconst rank = justValues.indexOf(d[`${stat}_value`]);\n\t\t\t// console.log(d[`${stat}_value`], rank);\n\t\t\t// if (d.bbrID === 'abdulka01') console.log(d);\n\t\t\treturn {\n\t\t\t\t...d,\n\t\t\t\t[[`${stat}_rank`]]: rank\n\t\t\t};\n\t\t});\n\t});\n\n\treturn [].concat(...ranked);\n}", "get(key){\n\n const index = this.hash(key);\n const dataBucket = this.buckets[index];\n if(dataBucket === undefined){\n return null;\n } else {\n let currentBucket = dataBucket.head;\n while((currentBucket.key !== key) && (currentBucket.next)){\n currentBucket = currentBucket.next;\n }\n return currentBucket.value;\n }\n\n }", "function getRank(score) {\n let rank;\n // Iterate through the gameLevels array until we find the item whose score is\n // greater than the current score. Then we return the name gameLevels item\n // that just preceeds the item with the greater score.\n gameLevels.some((level, idx, arr) => {\n if (level[1] > score) {\n rank = arr[idx - 1][0];\n return true;\n } else return false;\n });\n // If our score is above the Genius level, return the name in the last element.\n // I could just return 'Genius', but maybe they'll change the word someday, eg\n // to 'Super Brain'.\n gameRank = rank ? rank : gameLevels.slice(-1)[0][0];\n return gameRank;\n}", "function main6(){\n let starshipUSSEnterprise = new BinarySearchTree();\n starshipUSSEnterprise.insert(10,'Captain Picard');\n starshipUSSEnterprise.insert(7,'Commander Riker');\n starshipUSSEnterprise.insert(11,'Commander Data');\n starshipUSSEnterprise.insert(12,'Lt. Cmdr. Crusher');\n starshipUSSEnterprise.insert(13,'Lieutenant Selar');\n starshipUSSEnterprise.insert(8,'Lt. Cmdr. LaForge ');\n starshipUSSEnterprise.insert(6,'Lt. Cmdr. Worf ');\n starshipUSSEnterprise.insert(5,'Lieutenant security-officer');\n console.log('Ranking Order: ',bfs(starshipUSSEnterprise));\n}", "get(key) {\n const address = this._hash(key);\n if(this.data[address]){\n for (let i = 0; i < this.data[address].length; i++) {\n let currenctBucket = this.data[address][i];\n if (currenctBucket) {\n if (currenctBucket[0] === key) {\n return currenctBucket[1];\n }\n }\n }\n }\n return undefined;\n }", "function findKthBiggest(root, k) {}", "static fetchGamesByRank(rank, callback) {\n DBHelper.fetchGames((error, games) => {\n if(error) {\n callback(error, null);\n }\n else {\n const game = games.find(r => r.Rank == rank);\n if(game) {\n callback(null, game);\n }\n else {\n callback(`Game does not exist`, null);\n }\n }\n })\n }", "getKey(value, index) {\n return index;\n }", "function findKth(head, k) {\n\tvar i = 0;\n\tvar kth = head;\n\n\twhile(head.next) {\n\t\ti++;\n\t\tif ( i >= k ) {\n\t\t\t// Only progress kth node\n\t\t\t// after moving k nodes forward\n\t\t\tkth = kth.next;\n\t\t}\n\t\thead = head.next;\n\t}\n\n\treturn kth.data;\n}", "function compareRanks( rank1, rank2 ) {\r\n\treturn ( Ranks[ rank1].index - Ranks[ rank2 ].index );\r\n}", "function getRank() {\n\tvar s = document.querySelectorAll(\"input[name= 'suit']:checked\")[0].getAttribute('value'); \n\tvar r = document.querySelectorAll(\"input[name= 'rank']:checked\")[0].getAttribute('value');\n\treturn cards[s][r];\t\n}", "findNode( srcContact, [key], cb ){\n\n const err = Validation.checkIdentity(key);\n if (err) return cb(err);\n\n if (srcContact) this._welcomeIfNewNode(srcContact);\n\n cb( null, [0, this._kademliaNode.routingTable.getClosestToKey(key) ] );\n }", "function map(b, g, r) {\n var i;\n var j;\n var dist;\n var a;\n var bestd;\n var p;\n var best;\n\n // Biggest possible distance is 256 * 3\n bestd = 1000;\n best = -1;\n i = netindex[g]; // index on g\n j = i - 1; // start at netindex[g] and work outwards\n\n while (i < netsize || j >= 0) {\n if (i < netsize) {\n p = network[i];\n\n dist = p[1] - g; // inx key\n\n if (dist >= bestd) {\n i = netsize; // stop iter\n } else {\n i++;\n\n if (dist < 0) {\n dist = -dist;\n }\n\n a = p[0] - b;\n\n if (a < 0) {\n a = -a;\n }\n\n dist += a;\n\n if (dist < bestd) {\n a = p[2] - r;\n\n if (a < 0) {\n a = -a;\n }\n\n dist += a;\n\n if (dist < bestd) {\n bestd = dist;\n best = p[3];\n }\n }\n }\n }\n\n if (j >= 0) {\n p = network[j];\n\n dist = g - p[1]; // inx key - reverse dif\n\n if (dist >= bestd) {\n j = -1; // stop iter\n } else {\n j--;\n if (dist < 0) {\n dist = -dist;\n }\n a = p[0] - b;\n if (a < 0) {\n a = -a;\n }\n dist += a;\n\n if (dist < bestd) {\n a = p[2] - r;\n if (a < 0) {\n a = -a;\n }\n dist += a;\n if (dist < bestd) {\n bestd = dist;\n best = p[3];\n }\n }\n }\n }\n }\n\n return best;\n }", "function find_kth_element_BST(rootNode, k) {\n\n if (!rootNode) {\n return;\n }\n const stack = [];\n\n stack.push(rootNode);\n\n while(stack.length) {\n const node = stack[stack.length - 1];\n if (node.left) {\n stack.push(node.left);\n continue;\n }\n\n if (k == 0) return node;\n stack.pop();\n k--;\n\n if (node.right) {\n stack.push(node.right);\n }\n }\n return null;\n}", "function getScoreToRank(){\n\tvar scoreBucket = {};\n\n\tObject.keys(io.sockets.connected).forEach(function(socketID){\n\t\tvar player = io.sockets.connected[socketID].player;\n\t\tif(player){\n\t\t\tvar score = player.kills;\n\t\t\tif(!scoreBucket[score]){\n\t\t\t\tscoreBucket[score] = 0;\n\t\t\t}\n\t\t\tscoreBucket[score]++;\n\t\t}\n\t});\n\n\tvar scores = Object.keys(scoreBucket);\n\tscores.sort(scoreCompareFunction);\n\n\tvar rank = 1;\n\tvar scoreToRank = {};\n\tfor(var i = 0; i < scores.length; i++){\n\t\tvar s = scores[i];\n\t\tscoreToRank[s] = rank;\n\t\trank += scoreBucket[s];\n\t}\n\n\tscoreToRank.leaderScore = scores[0];\n\tscoreToRank.leaderID = -1;\n\tif(scores[0]){\n\t\tObject.keys(io.sockets.connected).forEach(function(socketID){\n\t\t\tvar player = io.sockets.connected[socketID].player;\n\t\t\tif(player && player.kills == scores[0])\n\t\t\t\tscoreToRank.leaderID = player.id;\n\t\t});\n\t}\n\treturn scoreToRank;\n}", "function keyIndexByKey (key) {\n return keys.findIndex(element => {return element.key === key});\n}", "function searchInTheTree(root, key) {\n let res;\n while(root && root.data) {\n if(root.data === key) {\n res = root;\n break;\n }\n else if (key > root.data) root = root.right;\n else root = root.left;\n }\n return res;\n}", "find(key) {\n let current = this.root;\n while (current != null) {\n if (current.element.key == key) {\n return current.element\n }\n else if (key > current.element.key) {\n current = current.right\n }\n else {\n current = current.left\n }\n }\n return null\n }", "function getRankBonus(result) {\n // set a bonus factor for Matches and Hits in the upper rankings (of Original Dataset)\n let bonus\n if (result <= topRank) {\n bonus = topBonus\n } else if (result <= mediumRank) {\n bonus = mediumBonus\n } else {\n bonus = 1\n }\n return bonus\n}", "function outputByRank(tree, rankOrder=[]) {\n const queue = new Queue();\n const person = tree; // tree is the first node\n queue.enqueue(person);\n while (queue.length) {\n const person = queue.dequeue();\n rankOrder.push(person.value);\n // console.log(person.value)\n if (person.left) {\n queue.enqueue(person.left);\n }\n\n if (person.right) {\n queue.enqueue(person.right);\n }\n }\n\n return rankOrder;\n}", "function getNextKeyWith( keys, fullSid, ndx ) {\n\n\t\t\tfor ( ; ndx < keys.length; ndx ++ ) {\n\n\t\t\t\tvar key = keys[ ndx ];\n\n\t\t\t\tif ( key.hasTarget( fullSid ) ) {\n\n\t\t\t\t\treturn key;\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\treturn null;\n\n\t\t}", "get(key){\n /* WITHOUT SEPARATE CHAINING COLLISION HANDLING...\n return this.table[this.hashFunction(key)];\n */\n \n // SEPARATE CHAINING WAY OF DOING IT:\n var postion = this.hashFunction(key);\n if (this.table[position] !== undefined){\n // iterate thru the LL to find the key\n // we know it's a LL, which has getHead() method\n var current = this.table[position].getHead();\n while(current.next){\n // check for the key on the element\n if (current.element.key === key){\n return current.element.value;\n }\n current = current.next;\n }\n // check in case it's the 1st or last element....\n if (current.element.key === key){\n return current.element.value;\n }\n }\n // key doesn't exist, nothing to get...\n return undefined;\n }", "function get_node_key(node_label, map_id)\n{\n\treturn \"n_\" + node_label + \"_\" + map_id;\n}", "_binarySearchUpperIndexByKey(arr, x, makeKey) {\n if (!arr.length) return null;\n if (makeKey) {\n arr = arr.map(makeKey);\n x = makeKey(x);\n }\n let start = 0;\n let end = arr.length - 1;\n let mid;\n\n if (arr[end] < x) return null;\n\n while (start < end) {\n mid = Math.floor((start + end) / 2);\n if (arr[mid] < x) start = mid + 1;\n else end = mid;\n }\n\n return start;\n }", "function getNextKeyWith ( keys, fullSid, ndx ) {\n\n\t\tfor ( ; ndx < keys.length; ndx ++ ) {\n\n\t\t\tvar key = keys[ ndx ];\n\n\t\t\tif ( key.hasTarget( fullSid ) ) {\n\n\t\t\t\treturn key;\n\n\t\t\t}\n\n\t\t}\n\n\t\treturn null;\n\n\t}", "function bid(u) {\n return base[outer.find(u)];\n}", "function key(n, callback) {\n\t var self = this;\n\n\t var promise = new Promise(function (resolve, reject) {\n\t self.ready().then(function () {\n\t var dbInfo = self._dbInfo;\n\t dbInfo.db.transaction(function (t) {\n\t t.executeSql('SELECT key FROM ' + dbInfo.storeName + ' WHERE id = ? LIMIT 1', [n + 1], function (t, results) {\n\t var result = results.rows.length ? results.rows.item(0).key : null;\n\t resolve(result);\n\t }, function (t, error) {\n\t reject(error);\n\t });\n\t });\n\t })['catch'](reject);\n\t });\n\n\t executeCallback(promise, callback);\n\t return promise;\n\t }", "function key(n, callback) {\n\t var self = this;\n\n\t var promise = new Promise(function (resolve, reject) {\n\t self.ready().then(function () {\n\t var dbInfo = self._dbInfo;\n\t dbInfo.db.transaction(function (t) {\n\t t.executeSql('SELECT key FROM ' + dbInfo.storeName + ' WHERE id = ? LIMIT 1', [n + 1], function (t, results) {\n\t var result = results.rows.length ? results.rows.item(0).key : null;\n\t resolve(result);\n\t }, function (t, error) {\n\t reject(error);\n\t });\n\t });\n\t })['catch'](reject);\n\t });\n\n\t executeCallback(promise, callback);\n\t return promise;\n\t }", "function key(n, callback) {\n\t var self = this;\n\n\t var promise = new Promise(function (resolve, reject) {\n\t self.ready().then(function () {\n\t var dbInfo = self._dbInfo;\n\t dbInfo.db.transaction(function (t) {\n\t t.executeSql('SELECT key FROM ' + dbInfo.storeName + ' WHERE id = ? LIMIT 1', [n + 1], function (t, results) {\n\t var result = results.rows.length ? results.rows.item(0).key : null;\n\t resolve(result);\n\t }, function (t, error) {\n\t reject(error);\n\t });\n\t });\n\t })['catch'](reject);\n\t });\n\n\t executeCallback(promise, callback);\n\t return promise;\n\t }", "kth_node_iterative(k) {\r\n if (!this.head) return null;\r\n\r\n let count = 1;\r\n let current = this.head;\r\n\r\n while (count < k && current.next) {\r\n current = current.next;\r\n count++;\r\n }\r\n\r\n if (count === k) return current;\r\n\r\n else return undefined;\r\n }", "static nodeKey(layer, nodeIndex) {\n return layer.name + '_ib-' + nodeIndex.toString();\n }", "function binarySearch(arr, key, insertIndex) {\n var len = arr.length;\n var sp = -1;\n var m;\n var retVal = -1;\n\n while (len - sp > 1) {\n var index = m = len + sp >> 1;\n if (arr[index] < key) {\n sp = m;\n } else {\n len = m;\n }\n }\n \n if (arr[len] == key || insertIndex ) {\n retVal = len; \n }\n return retVal;\n}", "getTileRank() {\n return parseInt(this.props.id.replace(/\\D/g, ''), 10); // Get integer out of ID\n }", "function sortByRank(a, b) {\n return a.rank < b.rank ? 1 : -1;\n}", "function binarySearch(ar, el, compare_fn) {\n var m = 0;\n var n = ar.length - 1;\n while (m <= n) {\n var k = (n + m) >> 1;\n var cmp = compare_fn(el, ar[k]);\n if (cmp > 0) {\n m = k + 1;\n } else if(cmp < 0) {\n n = k - 1;\n } else {\n return k;\n }\n }\n return -m - 1;\n}", "findValue( srcContact, [table, key], cb){\n\n if (srcContact) this._welcomeIfNewNode(srcContact);\n\n this._store.get(table.toString('hex'), key.toString('hex'), (err, out) => {\n //found the data\n if (out) cb(null, [1, out] )\n else cb( null, [0, this._kademliaNode.routingTable.getClosestToKey(key) ] )\n })\n\n }", "retrieve(key) {\n const index = getIndexBelowMax(key.toString(), this.limit);\n const bucket = this.storage.get(index);\n if (Array.isArray(bucket)) {\n for (let i = 0; i < bucket.length; i++) {\n const objKey = bucket[i][0];\n if (objKey === key) {\n return bucket[i][1];\n }\n }\n }\n }", "function top(k) {\n throw \"Not implemented yet\";\n }", "kthToLastRecursive(k) {\n let index = 0;\n let result = null;\n\n const findNode = (node) => {\n if (node === null) {\n return 0;\n }\n index += findNode(node.next) + 1;\n\n if (index === k) {\n result = node;\n }\n return index;\n };\n // returns length\n findNode(this.head);\n // returns kth element\n return result;\n }", "function kthLastElement(head, k) {\n\tif(!head) {\n\t\treturn { node: null, index: 0 };\n\t}\n\n\tvar result\t= kthLastElement(head.next, k),\n\t\tindex\t= result.index;\n\n\tindex++;\n\tresult.index = index;\n\n\tif(index == k) {\n\t\treturn { node: head, index: index };\n\t} else {\n\t\treturn result;\n\t}\n}", "select(k) {\n // FIXME\n // public Key select(int k) {\n // if (k < 0 || k >= size()) {\n // throw new IllegalArgumentException(\"argument to select() is invalid: \" + k);\n // }\n // Node x = select(root, k);\n // return x.key;\n // }\n }", "function key(n, callback) {\n var self = this;\n\n var promise = new Promise(function(resolve, reject) {\n self.ready().then(function() {\n var dbInfo = self._dbInfo;\n dbInfo.db.transaction(function(t) {\n t.executeSql('SELECT key FROM ' + dbInfo.storeName +\n ' WHERE id = ? LIMIT 1', [n + 1],\n function(t, results) {\n var result = results.rows.length ?\n results.rows.item(0).key : null;\n resolve(result);\n }, function(t, error) {\n reject(error);\n });\n });\n })[\"catch\"](reject);\n });\n\n executeCallback(promise, callback);\n return promise;\n }", "get (key) {\n let hashed = hash(key);\n if(this.buckets[hash % this.buckets.length].key == key)\n return this.buckets[hash % this.buckets.length].value;\n return null;\n }", "function selectRank(size, bias) {\n bias = bias || 1.5\n if (bias <= 1) return Math.floor(size * Math.random())\n var rand = (bias - Math.sqrt(bias * bias - 4 * (bias - 1) * Math.random())) / 2 / (bias - 1)\n return Math.floor(size * rand)\n}", "function linearSearch(arr, value) {\n for (let key in arr) {\n if (arr[key] === value) return key;\n }\n return -1;\n}", "function top(k) {\n\t var top = select(all(), 0, groups.length, k);\n\t return heap.sort(top, 0, top.length);\n\t }", "function getRank(position) {\n switch (position) {\n case 0:\n return \"Grand Master\";\n break;\n case 1:\n return \"Master\";\n break;\n case 2:\n return \"Knight\";\n break;\n case 3:\n return \"Apprentice\";\n break;\n case 4:\n return \"Padawan\";\n break;\n default:\n return \"Youngling\";\n }\n }", "function minKey(key,mstSet) \n{ \n // Initialize min value \n let min = Number.MAX_VALUE, min_index; \n for (let v = 0; v < V; v++) \n if (mstSet[v] == false && key[v] < min) \n min = key[v], min_index = v; \n \n return min_index; \n}", "function binarySearch(array, key) {\n var low = 0;\n var high = array.length - 1;\n var mid;\n var element;\n\n while(low <= high) {\n mid = Math.floor((low + high) / 2, 10);\n element = array[mid];\n if (element < key) {\n high = mid - 1;\n }else if (element > key){\n high = mid - 1;\n }else{\n return mid;\n }\n }\n return - 1;\n}", "function binarySearch(array, key) {\n var low = 0;\n var high = array.length - 1;\n var mid;\n var element;\n \n while (low <= high) {\n mid = Math.floor((low + high) / 2, 10);\n element = array[mid];\n if (element < key) {\n low = mid + 1;\n } else if (element > key) {\n high = mid - 1;\n } else {\n return mid;\n }\n }\n return -1;\n}", "function BN_getIndex (BN, parentBN = undefined, bnList = curBNList) {\r\n if (parentBN == undefined) {\r\n\tlet parentId;\r\n\tif ((parentId = BN.parentId) == undefined) {\r\n\t return(-1);\r\n\t}\r\n\tif ((parentBN = bnList[parentId]) == undefined) {\r\n\t return(-1);\r\n\t}\r\n }\r\n return(parentBN.children.indexOf(BN));\r\n}", "function keyIndexById (id) {\n return keys.findIndex(element => {return element.id === id});\n}", "find(key)\r\n {\r\n var list = this.#table[int(this.#hash(key) & this.#divisor)];\r\n var k = list.length, entry;\r\n for (var i = 0; i < k; i++)\r\n {\r\n entry = list[i];\r\n if (entry.key === key)\r\n return entry.data;\r\n }\r\n return null;\r\n }", "function positionFor(list, key) {\n for(var i = 0, len = list.length; i < len; i++) {\n if( list[i]._key === key ) {\n return i;\n }\n }\n return -1;\n}", "function nextRight(first, k) {\n\n // Base Case\n if (first == null)\n return null;\n\n // Create an empty queue for level\n // order traversal. A queue to\n // store node addresses\n let qn = [];\n\n // Another queue to store node levels\n let ql = [];\n\n // Initialize level as 0\n let level = 0;\n\n // Enqueue Root and its level\n qn.push(first);\n ql.push(level);\n\n // A standard BFS loop\n while (qn.length > 0) {\n\n // dequeue an node from qn and its level from ql\n let node = qn[0];\n level = ql[0];\n qn.shift();\n ql.shift();\n\n // If the dequeued node has the given key k\n if (node.data == k) {\n\n // If there are no more items in queue\n // or given node is the rightmost node\n // of its level, then return NULL\n if (ql.length == 0 || ql[0] != level)\n return null;\n\n // Otherwise return next node\n // from queue of nodes\n return qn[0];\n }\n\n // Standard BFS steps: enqueue\n // children of this node\n if (node.left != null) {\n qn.push(node.left);\n ql.push(level + 1);\n }\n if (node.right != null) {\n qn.push(node.right);\n ql.push(level + 1);\n }\n }\n\n // We reach here if given key\n // x doesn't exist in tree\n return null;\n}", "key(index) {\n return this._key(index) || this._keyPlus(index)\n }", "ll_kth_from_end(k) {\n if (Number.isInteger(k) && k > -1) {\n let current = this.head;\n let valueArr = [];\n let index = -1;\n\n // find the last node, which will have a next value of null\n while (current.next) {\n valueArr.push(current.value);\n current = current.next;\n index++;\n }\n if (current.next === null) {\n valueArr.push(current.value);\n index++;\n }\n\n let finalIndex = (index - k);\n if (Number.isInteger(finalIndex) && finalIndex > -1) {\n return valueArr[finalIndex];\n }\n return false;\n }\n }", "function findResultKeyById(resultId){\n\tvar results = getSortedResults();\n\tvar key = '';\n\tfor(i in results){\n\t\tif(results[i].id === resultId){\n\t\t\tkey = i;\n\t\t\tbreak;\n\t\t}\n\t}\n\t\n\treturn key;\n}", "search (val) {\n let i = 0;\n while (this.bst[i]) {\n if (this.bst[i] === val) break;\n if (this.bst[i] < val) i = 2 * i + 2;\n else i = 2 * i + 1;\n }\n return !this.bst[i] ? -1 : i;\n }", "function binarySearch(arr, k) {\n //assumption that arr is ordered & comprised of numbers\n // k is desired number\n // returns index of k or -1 if there is no match\n\n var low = 0;\n var high = arr.length-1;\n var mid = Math.floor((high + low)/2);\n\n while(low !== mid ){\n if(arr[mid] === k){\n console.log('FOUND!', mid);\n return mid;\n } else if (arr[mid] > k) {\n high = mid;\n mid = Math.floor((high + low)/2);\n } else if (arr[mid] < k) {\n low = mid;\n mid = Math.floor((high + low)/2);\n }\n }\n console.log('NOT FOUND! ', -1);\n return -1;\n}", "function getNextKey() {\n var key = nodeIdCounter;\n while (myDiagram.model.findNodeDataForKey(key) !== null) {\n key = nodeIdCounter--;\n }\n return key;\n }", "get(key) {\n if (this.hashMap.get(key) !== undefined) {\n let node = this.hashMap.get(key);\n let storage = node.storage;\n let val = storage.val;\n this.doublyLinkedList.moveToHead(node);\n return val;\n } else {\n return -1;\n }\n }", "function findKey(obj, predicate, context) {\n predicate = cb(predicate, context);\n var _keys = keys(obj), key;\n for (var i = 0, length = _keys.length; i < length; i++) {\n key = _keys[i];\n if (predicate(obj[key], key, obj)) return key;\n }\n }", "function findKey(obj, predicate, context) {\n predicate = cb(predicate, context);\n var _keys = keys(obj), key;\n for (var i = 0, length = _keys.length; i < length; i++) {\n key = _keys[i];\n if (predicate(obj[key], key, obj)) return key;\n }\n }", "function findKey(obj, predicate, context) {\n predicate = cb(predicate, context);\n var _keys = keys(obj), key;\n for (var i = 0, length = _keys.length; i < length; i++) {\n key = _keys[i];\n if (predicate(obj[key], key, obj)) return key;\n }\n }", "function findKey(obj, predicate, context) {\n predicate = cb(predicate, context);\n var _keys = keys(obj), key;\n for (var i = 0, length = _keys.length; i < length; i++) {\n key = _keys[i];\n if (predicate(obj[key], key, obj)) return key;\n }\n }", "function findKey(obj, predicate, context) {\n predicate = cb(predicate, context);\n var _keys = keys(obj), key;\n for (var i = 0, length = _keys.length; i < length; i++) {\n key = _keys[i];\n if (predicate(obj[key], key, obj)) return key;\n }\n }", "function findKey(obj, predicate, context) {\n predicate = cb(predicate, context);\n var _keys = keys(obj), key;\n for (var i = 0, length = _keys.length; i < length; i++) {\n key = _keys[i];\n if (predicate(obj[key], key, obj)) return key;\n }\n }", "function findKey(obj, predicate, context) {\n predicate = cb(predicate, context);\n var _keys = keys(obj), key;\n for (var i = 0, length = _keys.length; i < length; i++) {\n key = _keys[i];\n if (predicate(obj[key], key, obj)) return key;\n }\n }", "function findKey(obj, predicate, context) {\n predicate = cb(predicate, context);\n var _keys = keys(obj), key;\n for (var i = 0, length = _keys.length; i < length; i++) {\n key = _keys[i];\n if (predicate(obj[key], key, obj)) return key;\n }\n }", "function findKey(obj, predicate, context) {\n predicate = cb(predicate, context);\n var _keys = keys(obj), key;\n for (var i = 0, length = _keys.length; i < length; i++) {\n key = _keys[i];\n if (predicate(obj[key], key, obj)) return key;\n }\n }", "getKey() {\n return container[idx]\n }", "function selectScnd (chain, key) {\n var len = chain.tableLen.scnd[key] || 1\n var idx = Math.floor(Math.random() * len)\n\n var t = 0\n for (var token in chain.scnd[key]) {\n t += chain.scnd[key][token]\n if (idx < t) {\n return token\n }\n }\n return '~'\n}", "function bst({ root, key }) {\n if(!root) {\n root = { key };\n }\n else if (key < root.key) {\n root.left = bst({ root: root.left, key });\n }\n else {\n root.right = bst({ root: root.right, key });\n }\n return root;\n}", "getScore() {\r\n\t\tconst keys = Object.keys(this.score);\r\n\t\tlet scored = 0;\r\n\t\tfor (let i = 0; i < keys.length; i++) {\r\n\t\t\tlet key = keys[i];\r\n\t\t\tlet userAnswer = this.score[key];\r\n\t\t\tlet itr = this.head;\r\n\t\t\tlet j = 0;\r\n\t\t\twhile (j < i) {\r\n\t\t\t\titr = itr.next;\r\n\t\t\t\tj++;\r\n\t\t\t}\r\n\t\t\tif (itr.val[key][userAnswer]) {\r\n\t\t\t\tscored++;\r\n\t\t\t};\r\n\t\t}\r\n\t\treturn scored;\r\n\t}", "function findTarget(root, k) {\n let nodesArray = createArrayFromRoot(root); // return array of all elements O(n) time and space\n\n // create hash from the array O(n) time and space\n let nodesHash = {};\n nodesArray.forEach( node => {\n if(!nodesHash[node.value]) {\n nodesHash[node.value] = 1;\n } else {\n nodesHash[node.value]++;\n }\n });\n\n // loop through nodesArray and look up the target value - current value in hash O(n) time O(1) space\n for(let i = 0; i < nodesArray.length; i++) {\n let valueToFind = k - nodesArray[i].value;\n\n if(k !== nodesArray[i].value && nodesHash[valueToFind] >= 1) {\n return true;\n } else if(nodesHash[valueToFind] >= 2) {\n return true;\n }\n }\n\n return false;\n\n}", "set rank(rank) {\n\t\tthis._rank = rank;\n\t}", "function top(k) {\n var top = select(all(), 0, groups.length, k);\n return heap.sort(top, 0, top.length);\n }", "function getPgRank2(){\n return pgRank2;\n}", "function rank(list) {\n\treturn Object.keys(list).sort(function(a,b) { return list[b] - list[a] })\n}", "function findKey(key,currentNode){\n if (currentNode.hasOwnProperty(key)) {\n return currentNode;\n } else {\n var node = null\n for(var index in currentNode.blocks){\n \n node = currentNode.blocks[index];\n \n if(node.hasOwnProperty(key)){\n return node;\n }\n findNode(key, node);\n }\n return node\n\n }\n}", "function key(kind, key) {\n \n}", "getKeyword(state) {\n return state.bestBooks\n }", "find(key) {\n // If the item is found at the root then return that value\n if (this.key == key) {\n return this.value;\n } else if (key < this.key && this.left) {\n return this.left.find(key);\n } else if (key > this.key && this.right) {\n return this.right.find(key);\n } else {\n throw new Error('Key Error');\n }\n }", "function getIndexByKey(array, key, value, isReverse) {\n for (let i = 0, l = array.length; i < l; i++) {\n const idx = isReverse ? ((l - 1) - i) : i;\n if (array[idx][key] === value) {\n return idx;\n }\n }\n return -1;\n }", "function key$1(n, callback) {\n var self = this;\n var promise = new Promise$1(function (resolve, reject) {\n self.ready().then(function () {\n var dbInfo = self._dbInfo;\n dbInfo.db.transaction(function (t) {\n tryExecuteSql(t, dbInfo, 'SELECT key FROM ' + dbInfo.storeName + ' WHERE id = ? LIMIT 1', [n + 1], function (t, results) {\n var result = results.rows.length ? results.rows.item(0).key : null;\n resolve(result);\n }, function (t, error) {\n reject(error);\n });\n });\n })[\"catch\"](reject);\n });\n executeCallback(promise, callback);\n return promise;\n }" ]
[ "0.5895939", "0.5836745", "0.5822547", "0.57418513", "0.5739508", "0.571266", "0.5675706", "0.5673694", "0.5623479", "0.56151193", "0.5561554", "0.5492664", "0.54798895", "0.541149", "0.5401308", "0.5395234", "0.5390893", "0.538417", "0.53783524", "0.5372408", "0.5369971", "0.5356195", "0.53252053", "0.52944213", "0.5279321", "0.5274535", "0.5273071", "0.5272441", "0.52656496", "0.5244662", "0.52397895", "0.52391285", "0.5210294", "0.52065474", "0.520407", "0.519412", "0.51864237", "0.5183581", "0.5180727", "0.5170165", "0.516463", "0.51448137", "0.51448137", "0.51448137", "0.51427275", "0.5136539", "0.51316804", "0.51154304", "0.51094615", "0.5107603", "0.51041406", "0.5101963", "0.50946146", "0.5087859", "0.5081514", "0.5078004", "0.5075401", "0.50737035", "0.5058598", "0.5058298", "0.5057874", "0.5049459", "0.50444824", "0.50267726", "0.502425", "0.5023157", "0.50209564", "0.5017888", "0.5013044", "0.50033134", "0.5001565", "0.50008774", "0.4997385", "0.49840146", "0.4978654", "0.4978154", "0.49771217", "0.4971618", "0.4971618", "0.4971618", "0.4971618", "0.4971618", "0.4971618", "0.4971618", "0.4971618", "0.4971618", "0.49666384", "0.49555913", "0.49552348", "0.49544406", "0.49522313", "0.49399328", "0.49378583", "0.49360248", "0.49312547", "0.49294457", "0.4927625", "0.4921078", "0.49200457", "0.49137467", "0.4903022" ]
0.0
-1
return number of keys in subtree < key
animateRank(key) { let animations = []; animations.push(new Animation("display", `Rank of ${key}`, "")); const rank = this.animateRankHelper(this.root, key, animations); if (animations[animations.length - 1].getItem() === key) animations[animations.length - 1].setClass("found-node"); else animations[animations.length - 1].setClass("search-failed-node"); animations.push(new Animation("display", rank, "")); return [rank, animations]; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "getNumberOfKeys () {\n let res\n\n if (!Object.prototype.hasOwnProperty.call(this, 'key')) return 0\n\n res = 1\n if (this.left) res += this.left.getNumberOfKeys()\n if (this.right) res += this.right.getNumberOfKeys()\n\n return res\n }", "get_child_count(){\n return Object.keys(this.children).length;\n }", "numGreater(lowerBound) {\n let count = 0;\n if ([this.root][0] === null) return 0;\n const totalValues = [this.root];\n while (totalValues.length) {\n let current = totalValues.pop();\n if (current.val > lowerBound) {\n count = count + 1;\n }\n if (current.children) {\n for (let child of current.children) {\n totalValues.push(child);\n }\n }\n } return count;\n }", "numGreater(lowerBound) {\n let count = 0;\n if (this.root === null){\n return count;\n }\n const stack = [this.root];\n while (stack.length){\n const currentNode = stack.pop();\n if (currentNode.val > lowerBound){\n count++;\n }\n for (let child of currentNode.children){\n stack.push(child);\n }\n }\n return count;\n }", "numGreater(lowerBound) {\n // if no root then we return 0\n if(!this.root) return 0;\n // set a variable for greater count, if there is onl;y one node (the root) and it is greater then the lower bound then we only have 1 val greater than the argument , otherwise we start at 0\n let greaterCount = this.root.val > lowerBound ? 1: 0;\n // create a help function that we can use to count child nodes \n function greaterCountHelper(node){\n // loop through the children\n for(let child of node.children){\n // if the value is greater than the lower bound lets add one to the count\n if(child.val > lowerBound) greaterCount++;\n if(child.children.length > 0){\n greaterCountHelper(child)\n }\n }\n }\n greaterCountHelper(this.root);\n return greaterCount;\n }", "get numberOfChildren() {\n return Object.keys(this.children).length;\n }", "getKeyCount() {\n return this.keys.length;\n }", "function getPathLength(orbits, key) {\n return getPath(orbits, key).length;\n}", "get numberOfChildren() {\n return Object.keys(this.children).length;\n }", "get numberOfChildren() {\n return Object.keys(this.children).length;\n }", "get numberOfChildren() {\n return Object.keys(this.children).length;\n }", "get numberOfChildren() {\n return Object.keys(this.children).length;\n }", "get numberOfChildren() {\n return Object.keys(this.children).length;\n }", "function treeQuantity(root, target){\r\n if (!root) {\r\n return 0;\r\n }\r\n let count = 0;\r\n if(root.val === target){\r\n count++;\r\n }\r\n\r\n return count + treeQuantity(root.left, target) + treeQuantity(root.right, target)\r\n}", "countEvens() {\n let count = 0;\n if (this.root === null){\n return count;\n }\n const queue = [this.root];\n while (queue.length){\n const currentNode = queue.shift();\n if (currentNode.val%2==0){\n count+=1;\n }\n for (let child of currentNode.children){\n queue.push(child);\n }\n }\n return count;\n }", "function countLeaves (node) {\n let count = 0\n node.forEach(n => { count += countLeaves(n) })\n return count || 1\n }", "size() {\n let _size = node => node === null ? 0 : 1 + _size(node.left) + _size(node.right)\n return _size(this.root)\n }", "function countChildren(rev,uid){\n var count = 0;\n for(cid in rev[uid]){\n if(!rev.hasOwnProperty(cid)){// leaf\n count += 1;\n }\n else{// not leaf\n count += 1 + countChildren(rev,cid);\n }\n }\n return count;\n}", "function greaterCountHelper(node){\n // loop through the children\n for(let child of node.children){\n // if the value is greater than the lower bound lets add one to the count\n if(child.val > lowerBound) greaterCount++;\n if(child.children.length > 0){\n greaterCountHelper(child)\n }\n }\n }", "function countNestedKeys(obj) {\n\n return map(obj, function (value, key) {\n return Object.keys(value).length\n })\n}", "_getKeyLength( key ){\n\t\treturn key.length;\n\t}", "function heightoftree(tree) {\n if (tree.left && tree.right)\n return Math.max(heightoftree(tree.left), heightoftree(tree.right)) + 1;\n if (tree.left) return heightoftree(tree.left) + 1;\n if (tree.right) return heightoftree(tree.right) + 1;\n return 1;\n}", "nodeSize(node) {\n let size = 1;\n if (!node.children) {\n return size;\n }\n let children = this.getChild(node.children);\n do {\n size++;\n children = children.children\n ? this.getChild(children.children)\n : undefined;\n } while (children);\n return size;\n }", "countEvens() {\n let count = 0;\n if ([this.root][0] === null) return 0;\n const totalValues = [this.root];\n while (totalValues.length) {\n let current = totalValues.pop();\n if (current.val % 2 === 0) {\n count = count + 1;\n }\n if (current.children) {\n for (let child of current.children) {\n totalValues.push(child);\n }\n }\n } return count;\n\n }", "function tree(t) {\n if (!t) {\n return 0;\n }\n return tree(t.left) + t.key + tree(t.right);\n}", "get length () {\n let length = 0;\n let n = this._start;\n while (n !== null) {\n if (!n._deleted && n._countable) {\n length += n._length;\n }\n n = n._right;\n }\n return length\n }", "function BSTHeight(tree) {\n if (!tree.key) return 0;\n \n let left = 0, right = 0;\n\n if (!tree.left && !tree.right) {\n return 1;\n }\n \n if (tree.left) {\n left = BSTHeight(tree.left);\n }\n\n if (tree.right) {\n right = BSTHeight(tree.right);\n }\n\n return Math.max(left, right) + 1;\n}", "function countFilesInTree(tree) {\n var treeItems = tree.get_json('#', { \"flat\" : true });\n var count = 0;\n var nodesList = [];\n for(var i = 0; i < treeItems.length; i++) {\n if (treeItems[i].type == 'file') {\n if ($.inArray(treeItems[i].data.node, nodesList) < 0) {\n nodesList.push(treeItems[i].data.node);\n count++;\n }\n }\n }\n $('.search-form .files-count span').html(count);\n}", "size(node) {\n if (node === undefined) {\n return 0;\n }\n if (Text.isText(node)) {\n return 1;\n }\n if (node.children !== undefined && node.children.length > 0) {\n let count = 0;\n node.children.forEach((child) => {\n count += this.size(child);\n });\n return count;\n }\n return 0;\n }", "_getKeyLength(key) {\n return key.length;\n }", "function treeQuantity(root, target){\r\n if (!root) return 0;\r\n let count = 0;\r\n let stack = [root];\r\n\r\n while(stack.length) {\r\n let currentNode = stack.pop();\r\n if(currentNode.val === target) {\r\n count++\r\n };\r\n if(currentNode.left) stack.push(currentNode.left);\r\n if(currentNode.right) stack.push(currentNode.right);\r\n };\r\n\r\n return count;\r\n\r\n}", "length() {\n let count = 0;\n\n this.traverse(function (node) {\n count++;\n console.log('current count is ' + count);\n });\n\n return count;\n }", "function count(node) {\n if (node === null) return 0\n const leftHeight = edgeHeight(node, 'left')\n const rightHeight = edgeHeight(node, 'right')\n if (leftHeight === rightHeight) {\n return Math.pow(2, leftHeight) - 1\n }\n return 1 + count(node.left) + count(node.right)\n}", "calculateHeightH(node) {\n if (node.key === \"null\") return 0\n else {\n var left = this.calculateHeightH(node.left);\n var right = this.calculateHeightH(node.right);\n this.treedpth = Math.max(left, right) + 1;\n } \n }", "childCount() {\n\t\tif (!this.state()) { return 0 }\n\n\t\tif (this[_size] === undefined) {\n\t\t\tthis[_size] = Object.keys(this.state()).length;\n\t\t}\n\n\t\treturn this[_size];\n\t}", "function possibility ( node ) {\n const keys = Object.keys(node);\n let count = 0;\n for (let i = 0; i < keys.length; i++) {\n let val = node[keys[i]];\n if (val !== null && typeof val === 'object') {\n count += possibility( val );\n } else {\n count += 1;\n }\n }\n return count;\n}", "function numOfTrees(map) {\n var _iteratorNormalCompletion2 = true;\n var _didIteratorError2 = false;\n var _iteratorError2 = undefined;\n\n try {\n for (var _iterator2 = map[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {\n var _step2$value = _slicedToArray(_step2.value, 2),\n key = _step2$value[0],\n value = _step2$value[1];\n\n if (value.numOfTrees > 1000) {\n console.log(value.name + ' has ' + value.numOfTrees + ' trees.');\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}", "size() {\n return this.root ? this.root.size() : 0;\n }", "checkNodeOrdering () {\n if (!Object.prototype.hasOwnProperty.call(this, 'key')) return\n\n if (this.left) {\n this.left.checkAllNodesFullfillCondition(k => {\n if (this.compareKeys(k, this.key) >= 0) throw new Error(`Tree with root ${this.key} is not a binary search tree`)\n })\n this.left.checkNodeOrdering()\n }\n\n if (this.right) {\n this.right.checkAllNodesFullfillCondition(k => {\n if (this.compareKeys(k, this.key) <= 0) throw new Error(`Tree with root ${this.key} is not a binary search tree`)\n })\n this.right.checkNodeOrdering()\n }\n }", "function sumByCount(d) {\n return d.children ? 0 : 1;\n}", "size() {\n let output = 0;\n this.traverse((currentNode) => {\n output++;\n });\n return output;\n }", "function count(node) {\n var sum = 0,\n children = node.children,\n i = children && children.length;\n if (!i) sum = 1;\n else while (--i >= 0) sum += children[i].value;\n node.value = sum;\n}", "length() {\n return this.forEachNode( (currentNode, i) => {\n return i;\n });\n }", "get totalNumberOfDescendants() {\n let n = 0;\n const counter = (vampire) => {\n for (let offspring of vampire.offsprings) {\n n ++;\n counter(offspring);\n }\n };\n\n counter(this);\n return n;\n }", "getLeftCount() {\n return _.size(_.filter(this.todos, {\n isComplete: false\n }));\n }", "function popindex(node, key) {\n let j = 0;\n for(i=0;i<node.allchils.length;i++){\n if (key == node.allchils[i]){\n msg = 'Se encontro el elemento ' +key ;\n j=i;\n break;\n }\n }\n return j;\n}", "function getLength(){\r\n return keyTable.length;\r\n }", "function smaller(tree,n,m,depth){var _n2=n*2;var _m2=m*2;return tree[_n2]/*.Freq*/<tree[_m2]/*.Freq*/||tree[_n2]/*.Freq*/===tree[_m2]/*.Freq*/&&depth[n]<=depth[m];}", "not_intersect_left_subtree(search_node) {\n const comparable_less_than = this.item.key.constructor.comparable_less_than; // static method\n let high = this.left.max.high !== undefined ? this.left.max.high : this.left.max;\n return comparable_less_than(high, search_node.item.key.low);\n }", "countEvens() {\n return (this.root ? this.root.evensCounter() : 0);\n }", "get nodeCount() {\n let count = 0\n for (let x in this.app.state.aspects) {\n let nodes = cloneDeep(this.app.state.aspects[x].nodes)\n nodes.reverse()\n let countNulls = false\n\n for (let z in nodes) {\n if (nodes[z] != null) // on the first non-null subnode we find, start counting\n countNulls = true\n if (nodes[z] != null || countNulls) {\n count++\n }\n }\n }\n\n // add core nodes\n for (let node in this.app.state.coreNodes) {\n count += (this.app.state.coreNodes[node]) ? 1 : 0\n }\n\n return count\n }", "function Treecount(right, down) {\n let counter = 0; //counts tress\n let counter2 = 1; //counts items in file\n let sledPosition = 0;\n \n\n for ( let i = 0; i < dataList.length; i=i+down) {\n if (sledPosition>30) sledPosition = sledPosition-31;\n if (dataList[i][sledPosition]== \"#\") counter++;\n console.log(dataList[i], dataList[i][sledPosition], sledPosition, counter, counter2); \n sledPosition = sledPosition+right; \n counter2++ \n }\n return counter;\n}", "getMaxKey () {\n return this.getMaxKeyDescendant().key\n }", "size() {\n let count = 0;\n let node = this.head;\n while (node) {\n count++;\n node = node.both.next;\n }\n return count;\n }", "function count(){\r\n\r\n\tvar n=0;\r\n\tObject.keys(this.datastore).forEach((key)=>\r\n\t{\r\n\t\t++n;\r\n\t});\r\n\treturn n;\r\n}", "function compare(key){\n if(elementsAroundMines.has(key)){\n var i=elementsAroundMines.get(key);\n console.log(i);\n elementsAroundMines.set(key,i+1);\n }\n else{\n elementsAroundMines.set(key,1);\n }\n }", "getMaxKeyDescendant () {\n if (this.right) return this.right.getMaxKeyDescendant()\n else return this\n }", "function GetSize() : int\n\t{\n\t\tvar n = 0;\n\t\tfor( var i = 0; i < key2down.length; i++ )\n\t\t{\n\t\t\tif( key2down[i] )\n\t\t\t\tn++;\n\t\t}\n\t\treturn n;\n\t}", "function bstHeight(bst, left = 0, right = 0) {\n if (bst.key === null) {\n return 0;\n }\n\n if (!bst.left && !bst.right) {\n return 1;\n }\n if (bst.left) {\n left = 1 + bstHeight(bst.left, left, right);\n }\n if (bst.right) {\n right = 1 + bstHeight(bst.right, left, right);\n }\n return left > right ? left : right;\n}", "function count2(node) {\n if (node === null) return 0\n return 1 + count(node.left) + count(node.right)\n}", "function searchInTheTree(root, key) {\n let res;\n while(root && root.data) {\n if(root.data === key) {\n res = root;\n break;\n }\n else if (key > root.data) root = root.right;\n else root = root.left;\n }\n return res;\n}", "function keyCount(obj) {\n return Object.keys(obj).length;\n }", "function keyCount(obj) {\n return Object.keys(obj).length;\n }", "function getKeyLength(obj) {\n return Object.keys(obj).length;\n }", "findAndElevate(key) {\n const found = treeFind(this.root, key);\n if (found !== NIL) {\n found.priority *= 2;\n this._heapFixUp(found);\n }\n return found;\n }", "function computeTreeDepth(tree) {\n let depth = 0\n let p = tree\n let q = [p]\n while (q.length > 0) {\n let qq = []\n for (const x of q) {\n if (x.children) {\n for (const y of x.children) {\n qq.push(y)\n }\n }\n }\n if (qq.length > 0) depth += 1\n q = qq\n }\n\n return depth\n}", "get size() {\n // Return the triple count if if was cached\n var size = this._size;\n if (size !== null)\n return size;\n\n // Calculate the number of triples by counting to the deepest level\n size = 0;\n var graphs = this._graphs, subjects, subject;\n for (var graphKey in graphs)\n for (var subjectKey in (subjects = graphs[graphKey].subjects))\n for (var predicateKey in (subject = subjects[subjectKey]))\n size += Object.keys(subject[predicateKey]).length;\n return this._size = size;\n }", "get size() {\n // Return the quad count if if was cached\n var size = this._size;\n if (size !== null) return size; // Calculate the number of quads by counting to the deepest level\n\n size = 0;\n var graphs = this._graphs,\n subjects,\n subject;\n\n for (var graphKey in graphs) for (var subjectKey in subjects = graphs[graphKey].subjects) for (var predicateKey in subject = subjects[subjectKey]) size += Object.keys(subject[predicateKey]).length;\n\n return this._size = size;\n }", "not_intersect_right_subtree(search_node) {\n const comparable_less_than = this.item.key.constructor.comparable_less_than; // static method\n let low = this.right.max.low !== undefined ? this.right.max.low : this.right.item.key.low;\n return comparable_less_than(search_node.item.key.high, low);\n }", "function getKeyLength(obj) {\r\n return Object.keys(obj).length;\r\n }", "function tagCountInNode(node)\n {\n var sum = 0;\n\n if(node.nodeType == 1)\n {\n sum ++;\n }\n\n var allChildrenNodes = node.childNodes;\n for(var i = 0; i < allChildrenNodes.length; i++)\n {\n sum += tagCountInNode(allChildrenNodes[i]);\n }\n\n return sum;\n}", "get size() {\n // Return the triple count if if was cached.\n var size = this._size;\n if (size !== null)\n return size;\n\n // Calculate the number of triples by counting to the deepest level.\n var contexts = this._contexts, subjects, subject;\n for (var contextKey in contexts)\n for (var subjectKey in (subjects = contexts[contextKey].subjects))\n for (var predicateKey in (subject = subjects[subjectKey]))\n size += Object.keys(subject[predicateKey]).length;\n return this._size = size;\n }", "get size() {\n // Return the quad count if if was cached\n let size = this._size;\n if (size !== null) return size;\n\n // Calculate the number of quads by counting to the deepest level\n size = 0;\n const graphs = this._graphs;\n let subjects, subject;\n for (const graphKey in graphs) for (const subjectKey in subjects = graphs[graphKey].subjects) for (const predicateKey in subject = subjects[subjectKey]) size += Object.keys(subject[predicateKey]).length;\n return this._size = size;\n }", "numProperties() {\n let count = 0;\n if (this.hasChildren) {\n for (const it = this.children; it.hasNext(); it.next()) {\n const child = it.item();\n switch (child.snapshotType) {\n case 3 /* Internal */:\n switch (child.indexOrName) {\n case \"elements\": {\n // Contains numerical properties, including those of\n // arrays and objects.\n const elements = child.to;\n // Only count if no children.\n if (!elements.hasChildren) {\n count += Math.floor(elements.size / 8);\n }\n break;\n }\n case \"table\": {\n // Contains Map and Set object entries.\n const table = child.to;\n if (table.hasChildren) {\n count += table.childrenLength;\n }\n break;\n }\n case \"properties\": {\n // Contains expando properties on DOM nodes,\n // properties storing numbers on objects,\n // etc.\n const props = child.to;\n if (props.hasChildren) {\n count += props.childrenLength;\n }\n break;\n }\n }\n break;\n case 4 /* Hidden */:\n case 5 /* Shortcut */:\n case 6 /* Weak */:\n break;\n default:\n count++;\n break;\n }\n }\n }\n return count;\n }", "function numPaths(node, targetSum) {\n var result = 0;\n\n function recurse(node, hash, runningSum) {\n if (!node) {\n return 0;\n }\n runningSum += node.val;\n\n if (hash[runningSum]) {\n hash[runningSum] += 1;\n } else {\n hash[runningSum] = 1;\n }\n\n if (hash[runningSum - targetSum]) {\n result += 1;\n }\n\n if (node.left) {\n recurse(node.left, hash, runningSum);\n }\n if (node.right) {\n recurse(node.right, Object.assign({}, hash), runningSum);\n }\n }\n\n recurse(node, {}, 0)\n return result;\n}", "function height(tree) {\n if (!tree.value) {\n return \"not found\"\n\n }\n hLeft = [],\n hRigth = []\n\n\n function hRigthfnc() {\n if (tree.right) {\n height(tree.right),\n hRigth++\n }\n\n if (hRigth > hLeft) {\n return hRigth - 1\n }\n }\n\n\n function hLeftfnc() {\n if (tree.left) {\n height(tree.left),\n hLeft++\n }\n\n if (hLeft > hRigth) {\n return hLeft - 1\n }\n }\n return \" melhor percorrimento pela direita: \" + hRigthfnc() + \" melhor percorrimento pela esquerda: \" + hLeftfnc()\n // if (hRigthfnc() > hLeftfnc()) {\n // return hRigthfnc() + \" Rota pela direita\"\n // }\n // else {\n // return hLeftfnc() + \" Rota pela Esquerda\"\n // }\n}", "get size() {\n // Return the triple count if if was cached.\n var size = this._size;\n if (size !== null)\n return size;\n\n // Calculate the number of triples by counting to the deepest level.\n var graphs = this._graphs, subjects, subject;\n for (var graphKey in graphs)\n for (var subjectKey in (subjects = graphs[graphKey].subjects))\n for (var predicateKey in (subject = subjects[subjectKey]))\n size += Object.keys(subject[predicateKey]).length;\n return this._size = size;\n }", "get size() {\n // Return the triple count if if was cached.\n var size = this._size;\n if (size !== null)\n return size;\n\n // Calculate the number of triples by counting to the deepest level.\n var graphs = this._graphs, subjects, subject;\n for (var graphKey in graphs)\n for (var subjectKey in (subjects = graphs[graphKey].subjects))\n for (var predicateKey in (subject = subjects[subjectKey]))\n size += Object.keys(subject[predicateKey]).length;\n return this._size = size;\n }", "get numChildren() {\n return this._childPaths.length;\n }", "get length(): number {\n // Provide a mechanism for a class to set length on push for O(1) lookup\n if (this.__length) {\n return this.__length;\n }\n\n return this._length(this.root);\n }", "numGreater(lowerBound) {\n return (this.root ? this.root.numsAboveCounter(lowerBound) : 0);\n }", "function countKeys(obj) {\n return Object.keys(obj).length;\n}", "keyReached(key) {\n return coords_key[key].map(n => n <= this.path.length);\n }", "function getHierarchylevelnameCounts(hvl) { \n\tfor (var i = 0; i < hierarchylevelnameCounts.length; i++) { \n\t\tif (hvl == hierarchylevelnameCounts[i].hvl)\n\t\t\treturn hierarchylevelnameCounts[i].count;\n\t}\n\treturn 0;\n}", "async function getNewKey(){\n let db = firebase.database();\n let ref = db.ref(\"books\");\n let result = await ref.once(\"value\")\n .then ( snap => {\n return newKey = snap.numChildren();\n })\n .catch( error => {\n console.log(error);\n })\n return result;\n}", "maxNode(node) {\n if (node) {\n while (node && node.right !== null) {\n node = node.right;\n }\n return node.key;\n }\n }", "numberOfListeners(){\n return Object.keys(this.keyListeners).length;\n }", "function getIndex(node) {\n var childs = node.parentNode.childNodes;\n var count = 0;\n for (var i = 0; i < childs.length; i++) {\n if (node === childs[i]) break;\n if (childs[i].toString() !== '[object Text]') count++;\n }\n return count;\n}", "function heightOf(tree, count=0){\n if (!tree){\n return count;\n } else {\n count++;\n }\n return Math.max(\n heightOf(tree.left, count),\n heightOf(tree.right, count)\n );\n}", "countBST(n) {\n // find nth catalan number \n let count = this.catalan(n);\n\n // return nth catalan number \n return count;\n}", "#minchild(x) {\n\t\tthis.downsteps++;\n\t\tlet minc = this.left(x);\n\t\tif (minc > this.m) return 0;\n\t\tfor (let y = minc + 1; y <= this.right(x) && y <= this.m; y++) {\n\t\t\tthis.downsteps++;\n\t\t\tif (this.#key[this.#item[y]] < this.#key[this.#item[minc]])\n\t\t\t\tminc = y;\n\t\t}\n\t\treturn minc;\n\t}", "get nodeSize() {\n return this.isLeaf ? 1 : 2 + this.content.size;\n }", "subtreeWeight () {\n const localWeight = this.template && this.template.weight;\n\n return this.components.reduce(\n (sum, component) => sum + component.subtreeWeight(),\n localWeight\n );\n }", "countEvens() {\n // if there is no root then we just return 0\n if(!this.root) return 0;\n // if the initial root is the only node and it is even then we set the count to 1 , otherwise we start at 0\n let evenCount = this.root.val % 2 === 0 ? 1: 0;\n // create a helper function and accept a node as an argument\n function countEvensHelper(node){\n // loop through the children of the node we pass in \n for(let child of node.children){\n // check the value of the child and if it is even add to the even count\n if(child.val % 2 ===0) evenCount ++;\n // check if that child has children and then recurse through the child node with the even counter if it has children\n if(child.children.length > 0){\n countEvensHelper(child)\n }\n }\n }\n // call the helper function on our root node \n countEvensHelper(this.root);\n // return the count of the even numbers in the tree \n return evenCount;\n }", "function max_key_length(data) {\r\n \tvar max = 0;\r\n for(var i = 0; i < data.length; i++) {\r\n if (data[i].key.length > max) {\r\n max = data[i].key.length;\r\n }\r\n }\r\n return max\r\n }", "size(){\n // Object.keys returns an array of all the properties of a given obj...\n return Object.keys(this.items).length;\n\n \n // OR, iterate thru object and increase counter for each (this does the same thing as Object.keys does under the hood)\n // var count = 0;\n // for (var key in this.items){\n // if (this.items.hasOwnProperty(key)){\n // count++;\n // }\n // }\n // return count;\n \n }", "function thirdLargestKey(tree) {\n if (!tree.right) {\n return findThirdLargestKey(tree.key);\n }\n return thirdLargestKey(tree.right);\n}", "function findHeightTwo(tree) {\n if (tree === null) {\n return -1;\n }\n let parent = tree.parent;\n let left = findHeightTwo(tree.left);\n let right = findHeightTwo(tree.right);\n\n if (left > right) {\n return left + 1;\n } else {\n return right + 1;\n }\n}", "get size() {\n let size = 0;\n for (let i = 0; i < this.children.length; i++)\n size += this.children[i].size;\n return size;\n }", "function levelWidth(root) {\n let counterArray = [0];\n let traverseArray = [root, 's'];\n\n while (traverseArray.length > 1) {\n let element = traverseArray.shift();\n if (element === 's') {\n counterArray.push(0);\n traverseArray.push(element);\n } else {\n traverseArray.push(...element.children);\n counterArray[counterArray.length - 1]++;\n }\n }\n\n return counterArray;\n\n}", "get entries() {\n return this.keys.length;\n }" ]
[ "0.7712641", "0.66334707", "0.6452036", "0.63177204", "0.6238651", "0.60802096", "0.60652745", "0.5975413", "0.5970096", "0.5970096", "0.5970096", "0.5970096", "0.5970096", "0.5940673", "0.59302676", "0.59011996", "0.588781", "0.5886737", "0.5863305", "0.58179635", "0.5798335", "0.57645816", "0.57157385", "0.57117665", "0.5709042", "0.56988263", "0.56958854", "0.5686211", "0.5680005", "0.56739604", "0.56587887", "0.56383747", "0.5631774", "0.562995", "0.5621378", "0.5620038", "0.5579882", "0.55474263", "0.5539537", "0.55259365", "0.55197185", "0.5516779", "0.5500423", "0.5495413", "0.548882", "0.5450968", "0.5446901", "0.54337597", "0.5428494", "0.5408611", "0.53925437", "0.53890234", "0.5361097", "0.5354346", "0.5346353", "0.5340518", "0.5334294", "0.5324097", "0.5314542", "0.5310236", "0.53094006", "0.52977824", "0.52977824", "0.5293924", "0.5288602", "0.52843666", "0.5276267", "0.52550685", "0.52538633", "0.52533954", "0.5251103", "0.52480847", "0.52303153", "0.5229778", "0.5227579", "0.5209396", "0.52054435", "0.52054435", "0.5192024", "0.5185961", "0.517273", "0.5170666", "0.5169859", "0.51697415", "0.51654625", "0.51606745", "0.51595974", "0.5157596", "0.5151312", "0.5136991", "0.51330715", "0.51311666", "0.5127676", "0.5116718", "0.51160836", "0.5114823", "0.51147753", "0.5113612", "0.51118106", "0.51005894", "0.50844747" ]
0.0
-1
inorder traversal of nodes
animateInorderNodes() { let queue = []; let animations = []; animations.push(new Animation("display", "Traversing Inorder", "")); this.animateInorderNodesHelper(this.root, queue, animations); animations.push(new Animation("display", "Finished Travering", "")); return [queue, animations]; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function inOrderTraversal(node) {}", "inorderTraversal() {\n\n }", "inorderTraversal(node = this.root) {\n if (node === null)\n return;\n\n this.inorderTraversal(node.left);\n console.log(node.data);\n this.inorderTraversal(node.right);\n }", "inorder(node) {\n if (node !== null) {\n this.inorder(node.left);\n console.log(node.data);\n this.inorder(node.right);\n }\n }", "inorder(node) {\n if (node !== null) {\n this.inorder(node.left);\n console.log(node.data);\n this.inorder(node.right);\n }\n }", "inorder(node) {\n if (node !== null) {\n this.inorder(node.left);\n console.log(node.data);\n this.inorder(node.right);\n }\n }", "inorder(node) {\n if (node !== null) {\n this.inorder(node.left);\n console.log(node.data);\n this.inorder(node.right);\n }\n }", "inorder(node) {\n if (node !== null) {\n this.inorder(node.left);\n console.log(node.data);\n this.inorder(node.right);\n }\n }", "inorder(node){\n if(node !== null){\n this.inorder(node.left);\n console.log(node.data);\n this.inorder(node.right);\n }\n }", "_inorder(node) {\n if (node !== null && node !== undefined) {\n this._inorder(node.getLeftChild());\n this.currElem = node.getElement();\n this._inorder(node.getRightChild());\n }\n }", "inOrder(node) {\n if (node != null) {\n this.inOrder(node.left);\n console.log(node.data);\n this.inOrder(node.right);\n }\n }", "function preOrderTraversal(node) {}", "inOrderTraversal(node, callback) {\n if (node !== null) {\n this.inOrderTraversal(node.left, callback);\n callback(node.key); // append via callback\n this.inOrderTraversal(node.right, callback);\n }\n }", "inorder() {\n this.inorder(this._root);\n }", "function inOrderTraversal(node) {\n if (node !== null) {\n inOrderTraversal(node.left);\n console.log(node.val);\n inOrderTraversal(node.right);\n }\n}", "function inorder(node){\n if(!_.isNull(node.left)) inorder(node.left)\n trav.push({\"key\": node.key, \"value\": node.value, \"children\": [_.get(node, \"left.value\", \"null\"), _.get(node, \"right.value\", \"null\")]})\n if(!_.isNull(node.right)) inorder(node.right)\n}", "inorderTraverse() {\n let data = [];\n function traverse(node) {\n if(node.left != null) {\n traverse(node.left);\n }\n data.push(node.data);\n if(node.left != null) {\n traverse(node.left);\n }\n }\n traverse(this.root);\n return data;\n }", "inOrder(node) {\n if (node !== null) {\n this.inOrder(node.left);\n console.log(node.show());\n this.inOrder(node.right);\n }\n }", "inorder() {\n const resultArray = [];\n return this.inorderHelper(this.root, resultArray);\n }", "function inOrder(node) {\n if(node) {\n output.push(node.val);\n inOrder(node.left);\n inOrder(node.right);\n }\n else {\n output.push(null);\n }\n\n }", "inOrderTraversal(node, traversal = []) {\n if (node === null) {\n return traversal;\n } else {\n this.inOrderTraversal(node.left, traversal);\n traversal.push(node.value);\n this.inOrderTraversal(node.right, traversal);\n }\n return traversal;\n }", "inorderTraversal(currentNode) {\n let arr = []\n if (currentNode) {\n arr = this.inorderTraversal(currentNodec.left)\n arr.push(currentNode.value)\n arr = arr.push(this.inorderTraversal(currentNode.right));\n }\n return res\n\n }", "static *inorder(node) {\n if (node === null) {\n return\n }\n if ( !(node instanceof BinaryTreeNode) ) {\n throw Error(`The node must be a BinaryTreeNode instance!`)\n }\n yield *this.inorder(node.left)\n yield node.data\n yield *this.inorder(node.right)\n }", "function inOrder(node) {\n if (node == undefined) return [];\n return inOrder(node.left).concat(node.data).concat(inOrder(node.right));\n}", "inorder(root) {\n if (root != null) {\n inorder(root.left);\n console.log('Node : ' + root.data + ' , ');\n if (root.parent == null) console.log('Parent : NULL');\n else console.log('Parent : ' + root.parent.data);\n inorder(root.right);\n }\n }", "inOrderTraversal(visitorFn) {\n if (this.leftChild) {\n this.leftChild.inOrderTraversal(visitorFn)\n }\n\n visitorFn(this)\n\n if (this.rightChild) {\n this.rightChild.inOrderTraversal(visitorFn)\n }\n }", "function inOrder(node) {\n if(node) {\n // traverse the left subtree\n if(node.left !== null) {\n inOrder(node.left);\n }\n // call the process method on this node\n process.call(this, node);\n // traverse the right subtree\n if(node.right !== null) {\n inOrder(node.right);\n }\n }\n }", "function inOrder(node) {\n if(node) {\n // traverse the left subtree\n if(node.left !== null) {\n inOrder(node.left);\n }\n // call the process method on this node\n process.call(this, node);\n // traverse the right subtree\n if(node.right !== null) {\n inOrder(node.right);\n }\n }\n }", "function in_order(root, nodes) {\n if (root && root.left) {\n in_order(root.left, nodes);\n }\n nodes.push(root.data);\n if (root && root.right) {\n in_order(root.right, nodes)\n }\n return nodes;\n}", "inorderNodes() {\r\n let queue = [];\r\n\r\n this.inorderNodesHelper(this.root, queue);\r\n\r\n return queue;\r\n }", "function preOrderTraversal(node){\n console.log(node.key)\n \n if(node.left) {\n preOrderTraversal(node.left);\n }\n if(node.right){\n preOrderTraversal(node.right);\n }\n }", "function inOrderTraverse(tree) {\n let arr = [];\n inOrderTraverseHelper(tree, arr);\n return arr;\n}", "inOrder() {\n const results = [];\n const _traversal = (node) => {\n if (node.left) _traversal(node.left);\n results.push(node.value);\n if (node.right) _traversal(node.right);\n };\n _traversal(this.root);\n return results;\n }", "function traversePreOrder(node) {\n console.log(node.value);\n if (node.left) {\n traversePreOrder(node.left);\n }\n if (node.right) {\n traversePreOrder(node.right);\n }\n}", "inOrderTraversal() {\n let visited = [];\n\n function inOrder(node) {\n if (node !== null) {\n if (node.left !== null) inOrder(node.left);\n visited.push(node.value);\n if (node.right !== null) inOrder(node.right);\n }\n }\n\n inOrder(this.root);\n return visited;\n }", "inorder() {\n let values = [];\n if (this.root) this.root.inorder(values);\n return values;\n }", "function postOrderTraversal(node) {}", "function inOrder(currentNode) {\n if(currentNode.left) {\n inOrder(currentNode.left);\n }\n method.call(this, currentNode);\n if(currentNode.right) {\n inOrder(currentNode.right);\n }\n }", "inorderTraversal(root) {\r\n const path = []\r\n const rootChildren = root.children\r\n if(rootChildren.length === 0)\r\n path.push(root.val)\r\n else {\r\n let preStack = new Stack();\r\n preStack.push(root)\r\n while(preStack.size!==0) {\r\n const currentNode = preStack.pop()\r\n const currentChildren = currentNode.children\r\n if(currentChildren.length > 0 && !currentNode.visited) {\r\n for (let i=currentChildren.length-1; i>=1; i--) {\r\n preStack.push(currentChildren[i])\r\n }\r\n currentNode.visited = true\r\n preStack.push(currentNode)\r\n preStack.push(currentChildren[0])\r\n } else {\r\n currentNode.visited = false\r\n path.push(currentNode.val)\r\n } \r\n }\r\n }\r\n return path\r\n }", "function inOrderBinaryTreeTraversal(tree){\n const results = [];\n function _go(node){\n if (node.left) (_go(node.left));\n results.push(node.value);\n if (node.right) (_go(node.right));\n }\n if(tree.root){\n _go(tree.root);\n }\n return results;\n}", "inOrder(root=this.root,result=[]){\n if(root == null){\n return;\n }\n this.printOrder(root.nodeL, result);\n result.push(root.data);\n this.printOrder(root.nodeR, result);\n return result;\n }", "function traverseInOrder(node, list) {\n debugger;\n if (node.left) {\n traverseInOrder(node.left, list);\n }\n list.push(node.value);\n if (node.right) {\n traverseInOrder(node.right, list);\n }\n return list;\n}", "function inOrder(node, arr) {\n if (!arr) var arr = [];\n if (!node) return;\n inOrder(node.left, arr);\n arr.push(node.data);\n inOrder(node.right, arr);\n return arr\n}", "function inOrder(t) {\n if (t.left) {\n inOrder(t.left)\n }\n console.log(t.key)\n if (t.right) {\n inOrder(t.right)\n }\n}", "inOrder() {\n const result = [];\n\n // The recursive function\n function _inOrder(node) {\n if (node) {\n _inOrder(node.left);\n result.push(node.value);\n _inOrder(node.right);\n }\n }\n\n if (this.root) _inOrder(this.root);\n\n return result;\n }", "inOrder() {\n const arr = [];\n\n const inOrder = (node) => {\n\n if (node.left) {\n inOrder(node.left);\n }\n\n arr.push(node.value);\n\n if (node.right) {\n inOrder(node.right);\n }\n };\n\n let current = this.root;\n inOrder(current);\n\n return arr;\n }", "function preOrderTraversal(node) {\n if (node !== null) {\n console.log(node.val);\n preOrderTraversal(node.left);\n preOrderTraversal(node.right);\n }\n}", "function inorderTraversal(root) {\n const result = [];\n\n function traverse(node) {\n if (!node) return;\n traverse(node.left);\n result.push(node.val);\n traverse(node.right);\n }\n\n traverse(root);\n return result;\n}", "function inOrderTraverse(tree, array) {\n // Write your code here.\n\tif (tree !== null){\n\t\tinOrderTraverse(tree.left, array);\n\t\tarray.push(tree.value);\n\t\tinOrderTraverse(tree.right, array);\n\t}\n\n\treturn array;\n}", "function inOrder(tree) {\n if (!tree.value) {\n return \"not found\"\n\n }\n tree.left && inOrder(tree.left)\n console.log(tree.value)\n\n tree.right && inOrder(tree.right)\n\n\n}", "traverse(method) {\n inOrder(this.root);\n // Helper method for traversing the nodes in order\n function inOrder(currentNode) {\n if(currentNode.left) {\n inOrder(currentNode.left);\n }\n method.call(this, currentNode);\n if(currentNode.right) {\n inOrder(currentNode.right);\n }\n }\n }", "function inOrder_iterative(tree, index) {\n \n var stack = [];\n \n while (stack.length > 0 || !isUndefined(tree[index])) {\n if (!isUndefined(tree[index])) {\n stack.push(index);\n index = left(index);\n } else {\n index = stack.pop();\n console.log(tree[index]);\n index = right(index);\n }\n }\n}", "traverse(node, process_node = this.node_out) {\n if (!node) return;\n this.traverse(node.left, process_node);\n process_node(node); // in-order !!!\n this.traverse(node.right, process_node);\n return this;\n }", "preOrder(node) {\n if (node != null) {\n console.log(node.data);\n this.preOrder(node.left);\n this.preOrder(node.right);\n }\n }", "function inOrder_recursive(tree, index) {\n \n if (isUndefined(tree[index])) {\n return;\n }\n \n inOrder_recursive(tree, left(index));\n console.log(tree[index]);\n inOrder_recursive(tree, right(index));\n}", "preorder(node){\n if(node !== null) {\n console.log(node.data);\n this.preorder(node.left);\n this.preorder(node.right);\n }\n }", "inOrder() {\n const results = [];\n const _traverse = (node) => {\n if (node.left) _traverse(node.left);\n results.push(node.value);\n if (node.right) _traverse(node.right);\n };\n\n _traverse(this.root);\n return results;\n }", "inOrder() {\n let results = [];\n\n let _walk = node => {\n if (node.left) _walk(node.left);\n results.push(node.value);\n if (node.right) _walk(node.right);\n };\n _walk(this.root);\n\n return results;\n }", "function inOrder(root){\n if (!root){\n return;\n }\n if (root){\n inOrder(root.left);\n console.log(root.value);\n inOrder(root.right);\n }\n}", "DFSInOrdert() {\r\n\t\treturn this.traverseInOrder(this.root, []);\r\n\t}", "preOrderSearch(node) {\n if (node === null) {\n return;\n }\n\n console.log(node.data);\n\n this.preOrderSearch(node.leftChild);\n this.preOrderSearch(node.rightChild);\n }", "preorder(node) {\n if (node !== null) {\n console.log(node.data);\n this.preorder(node.left);\n this.preorder(node.right);\n }\n }", "preorder(node) {\n if (node != null) {\n console.log(node.data);\n this.preorder(node.left);\n this.preorder(node.right);\n }\n }", "preOrderTraversal(node, traversal = []) {\n if (node === null) {\n return traversal;\n } else {\n traversal.push(node.value);\n this.preOrderTraversal(node.left, traversal);\n this.preOrderTraversal(node.right, traversal);\n }\n return traversal;\n }", "*nodes(root) {\n var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n var {\n pass,\n reverse = false\n } = options;\n var {\n from = [],\n to\n } = options;\n var visited = new Set();\n var p = [];\n var n = root;\n\n while (true) {\n if (to && (reverse ? Path.isBefore(p, to) : Path.isAfter(p, to))) {\n break;\n }\n\n if (!visited.has(n)) {\n yield [n, p];\n } // If we're allowed to go downward and we haven't decsended yet, do.\n\n\n if (!visited.has(n) && !Text.isText(n) && n.children.length !== 0 && (pass == null || pass([n, p]) === false)) {\n visited.add(n);\n var nextIndex = reverse ? n.children.length - 1 : 0;\n\n if (Path.isAncestor(p, from)) {\n nextIndex = from[p.length];\n }\n\n p = p.concat(nextIndex);\n n = Node.get(root, p);\n continue;\n } // If we're at the root and we can't go down, we're done.\n\n\n if (p.length === 0) {\n break;\n } // If we're going forward...\n\n\n if (!reverse) {\n var newPath = Path.next(p);\n\n if (Node.has(root, newPath)) {\n p = newPath;\n n = Node.get(root, p);\n continue;\n }\n } // If we're going backward...\n\n\n if (reverse && p[p.length - 1] !== 0) {\n var _newPath = Path.previous(p);\n\n p = _newPath;\n n = Node.get(root, p);\n continue;\n } // Otherwise we're going upward...\n\n\n p = Path.parent(p);\n n = Node.get(root, p);\n visited.add(n);\n }\n }", "inOrder() {\n let root = this.root;\n let arr = [];\n\n if (root.left) {\n arr.push(...root.left.inOrder());\n }\n\n arr.push(root.value);\n\n if (root.right) {\n arr.push(...root.right.inOrder());\n }\n return arr;\n }", "*nodes(root) {\n var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n var {\n pass,\n reverse = false\n } = options;\n var {\n from = [],\n to\n } = options;\n var visited = new Set();\n var p = [];\n var n = root;\n\n while (true) {\n if (to && (reverse ? Path.isBefore(p, to) : Path.isAfter(p, to))) {\n break;\n }\n\n if (!visited.has(n)) {\n yield [n, p];\n } // If we're allowed to go downward and we haven't descended yet, do.\n\n\n if (!visited.has(n) && !Text.isText(n) && n.children.length !== 0 && (pass == null || pass([n, p]) === false)) {\n visited.add(n);\n var nextIndex = reverse ? n.children.length - 1 : 0;\n\n if (Path.isAncestor(p, from)) {\n nextIndex = from[p.length];\n }\n\n p = p.concat(nextIndex);\n n = Node.get(root, p);\n continue;\n } // If we're at the root and we can't go down, we're done.\n\n\n if (p.length === 0) {\n break;\n } // If we're going forward...\n\n\n if (!reverse) {\n var newPath = Path.next(p);\n\n if (Node.has(root, newPath)) {\n p = newPath;\n n = Node.get(root, p);\n continue;\n }\n } // If we're going backward...\n\n\n if (reverse && p[p.length - 1] !== 0) {\n var _newPath = Path.previous(p);\n\n p = _newPath;\n n = Node.get(root, p);\n continue;\n } // Otherwise we're going upward...\n\n\n p = Path.parent(p);\n n = Node.get(root, p);\n visited.add(n);\n }\n }", "preorder(node) {\n if (node !== null) {\n console.log(node.data);\n this.preorder(node.left);\n this.preorder(node.right);\n }\n }", "preorder(node)\n {\n if(node != null)\n {\n console.log(node.data);\n this.preorder(node.left);\n this.preorder(node.right);\n }\n }", "function inOrderDFS(root) {\n if (root === null) return;\n // print here -> pre order\n if (root.left) {\n preOrderDFS(root.left);\n }\n // print here -> in order\n console.log(root.value);\n if (root.right) {\n preOrderDFS(root.right);\n }\n // print here -> post order\n}", "function inOrderTraverse(tree, array) {\n\tvar current = tree;\n\tfunction traverse(node) {\n\t\tnode.left && traverse(node.left);\n\t\tarray.push(node.value);\n\t\tnode.right && traverse(node.right);\n\t}\n\ttraverse(tree);\n\treturn array;\n}", "levelOrderSearch(node) {\n if (node === null) {\n return;\n }\n\n let discoveredNodes = [];\n discoveredNodes.push(node);\n\n while(discoveredNodes.length > 0) {\n let currentNode = discoveredNodes[0];\n console.log(currentNode.data);\n\n if (currentNode.leftChild !== null) {\n discoveredNodes.push(currentNode.leftChild);\n }\n if (currentNode.rightChild !== null) {\n discoveredNodes.push(currentNode.rightChild);\n }\n\n discoveredNodes.shift();\n }\n }", "preTraverseSceneGraph(rootNode, func) {\n func(rootNode);\n if (!this.gameObjects.has(rootNode)) return; //might have been deleted during execution\n\n let nodeQueue = new Set(this.childrenOf(rootNode)); //shallow copy\n for (let child of nodeQueue) {\n this.preTraverseSceneGraph(child, func);\n }\n }", "traverse(fn) { \n var curr = this.head; \n //var str = \"\"; \n while (curr) { \n //str += curr.element + \" \"; \n \n fn (curr.element, curr.next.element);\n\n curr = curr.next; \n } \n }", "function inOrder(root, process) {\n if (root.leftChild !== null) {\n inOrder(root.leftChild, process);\n }\n\n process.call(this, root.value);\n\n if (root.rightChild !== null) {\n inOrder(root.rightChild, process);\n }\n}", "preOrder() {\n const results = [];\n const _traversal = (node) => {\n results.push(node.value);\n if (node.left) _traversal(node.left);\n if (node.right) _traversal(node.right);\n };\n _traversal(this.root);\n return results;\n }", "function traverse(root) {}", "function inOrderArrayIter(root) {\n\tlet path = [];\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// 1) initialize empty stack, and current node to root\n\tlet stack = [];\n\tlet node = root;\n\n\twhile (stack.length || node) {\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// 2) loop while stack NOT empty OR node exists\n\n\t\tif (node) {\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// 3) if current node exists, push node to stack, update node to left node\n\t\t\tstack.push(node);\n\t\t\tnode = node.left;\n\n\t\t} else {\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// 4) if current node does NOT exist\n\n\t\t\tnode = stack.pop();\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// 5) update node\"visit\" node/pop last node in stack\n\t\t\tpath.push(node.val);\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// 6) push node val to path\n\t\t\tnode = node.right;\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// 7) update node to right node\n\t\t}\n\t}\n\n\treturn path;\n}", "*nodesAscending(){\n let i = 0;\n let node = this.root && this.root.getLeftmostChild();\n while(node){\n yield node;\n node = node.getSuccessor();\n }\n }", "function postOrderTraversal(node) {\n if (node !== null) {\n postOrderTraversal(node.left);\n postOrderTraversal(node.right);\n console.log(node.val);\n }\n}", "function inOrderHelper(root) {\n if(root === null) return\n\n inOrderHelper(root.left)\n\n count--\n\n if(count === 0) {\n response.push(root.value)\n return\n }\n\n inOrderHelper(root.right)\n }", "_preorder(node) {\n if (node !== null && node !== undefined) {\n this.currElem = node.getElement();\n this._preorder(node.getLeftChild());\n this._preorder(node.getRightChild());\n }\n }", "dfsInOrder(){\n let result = []\n\n const traverse = node => {\n //if left node exists, go left again//\n if(node.left) traverse(node.left)\n //capture root node value//\n result.push(node.value)\n //if right node exists, go right again//\n if(node.right) traverse(node.right)\n }\n\n traverse(this.root)\n console.log(`DFS In Order: ${result}`)\n }", "preOrderTraversal() {\n \n let visited = [];\n\n if (this.root === null) {\n return visited;\n }\n\n function preOrder(node) {\n if (node === null) {\n return;\n }\n\n visited.push(node.value);\n preOrder(node.left);\n preOrder(node.right);\n }\n\n preOrder(this.root);\n return visited;\n }", "function fnTraversal(root, node, preorder, postorder) {\n\t\tnode.childnodes.forEach((child, i) => { //iterate over next deep level\n\t\t\tpreorder(root, node, child, i) && fnTraversal(root, child, preorder, postorder); //preorder = cut/poda\n\t\t\tpostorder(root, node, child, i);\n\t\t});\n\t\treturn self;\n\t}", "function preOrder(root) {\n console.log(root.data) \n root.left && preOrder(root.left) \n root.right && preOrder(root.right) \n }", "dfsInOrder() {\n let visitedNodes = [];\n let currentNode = this.root;\n\n function traverse(node){\n \n node.left && traverse(node.left)\n visitedNodes.push(node.val);\n node.right && traverse(node.right);\n }\n \n traverse(currentNode);\n return visitedNodes;\n }", "dfsPreOrder() {\n let result = [];\n function traverse(node, arr) {\n arr.push(node);\n if (node.left) traverse(node.left);\n if (node.right) traverse(node.right);\n }\n traverse(this.root, result);\n return result;\n }", "function levelOrderTraversal(node) {\n let queue = [];\n let res = [];\n\n if (node) queue.push(node);\n\n while (queue.length) {\n node = queue.shift();\n\n res.push(node.val);\n\n if (node.left) queue.push(node.left);\n if (node.right) queue.push(node.right);\n }\n\n return res;\n}", "function xWalkTreeRev( oNode, fnVisit, skip, data )\r\n{\r\n var r=null;\r\n if(oNode){if(oNode.nodeType==1&&oNode!=skip){r=fnVisit(oNode,data);if(r)return r;}\r\n for(var c=oNode.lastChild;c;c=c.previousSibling){if(c!=skip)r=xWalkTreeRev(c,fnVisit,skip,data);if(r)return r;}}\r\n return r;\r\n}", "dfsInOrder() {\n let result = [];\n\n function traverse(node, arr) {\n if (node.left) traverse(node.left);\n arr.push(node);\n if (node.right) traverse(node.right);\n }\n traverse(this.root, result);\n return result;\n }", "preOrder(node) {\n if (node != null) {\n document.write(node.key + \" \");\n this.preOrder(node.left);\n this.preOrder(node.right);\n }\n }", "DFSInOrder() {\n let data = []\n function traverse(node) {\n if (node.left) traverse(node.left)\n data.push(node.value)\n if (node.right) traverse(node.right)\n }\n traverse(this.root)\n return data\n }", "preOrder() { //DLR\n let results = [];\n\n let _walk = node => {\n results.push(node.value); //executing code\n if(node.left) _walk(node.left); //go left - if node,left is null, we are at a leaf - traversing\n if(node.right) _walk(node.right); // go right - if node.right=null then we are at a leaf - traversing\n };\n console.log(_walk(this.root));\n _walk(this.root); // for whiteboard use ll.root instead of this.root, unless using a class constructor\n return results;\n }", "DFSInOrder() {\n var data = [],\n current = this.root\n\n function traverse(node) {\n if (node.left) traverse(node.left)\n data.push(node.value)\n if (node.right) traverse(node.right)\n \n }\n traverse(current)\n return data\n }", "function xWalkTree2( oNode, fnVisit, skip, data )\r\n{\r\n var r=null;\r\n if(oNode){if(oNode.nodeType==1&&oNode!=skip){r=fnVisit(oNode,data);if(r)return r;}\r\n for(var c=oNode.firstChild;c;c=c.nextSibling){if(c!=skip)r =xWalkTree2(c,fnVisit,skip,data);if(r)return r;}}\r\n return r;\r\n}", "dfsInorder() {\n let result = [];\n const traverse = node => {\n if (node.left) {\n traverse(node.left);\n }\n result.push(node.data);\n if (node.right) {\n traverse(node.right)\n }\n }\n traverse(this.root)\n\n return result;\n }", "bfsInOrder() {\r\n\r\n\t\tif(this.isEmpty()){\r\n\t\t\treturn []\r\n\t\t}\r\n\r\n\t\telse{\r\n\t\t\tvar result = [];\r\n\r\n\t\t\tvar traverse = node => {\r\n\t\r\n\t\t\t\tif (node.left !== null)\r\n\t\t\t\t\ttraverse(node.left);\r\n\t\r\n\t\t\t\tresult.push(node.value);\r\n\t\r\n\t\t\t\tif (node.right !== null)\r\n\t\t\t\t\ttraverse(node.right);\r\n\t\t\t}\r\n\t\r\n\t\t\ttraverse(this.root);\r\n\t\t\treturn result;\r\n\t\t}\r\n\t}", "inOrder(root = this.root, values = []) {\n if (!root) {\n return null;\n }\n if (root.left) {\n this.inOrder(root.left, values);\n }\n\n values.push(root.data);\n\n if (root.right) {\n this.inOrder(root.right, values);\n }\n return values;\n }", "function preOrder(node) {\n if (node == undefined) return [];\n return [node.data].concat(preOrder(node.left)).concat(preOrder(node.right));\n}", "dfsPreOrder() {\n let visitedNodes = [];\n let currentNode = this.root;\n\n function traverse(node){\n visitedNodes.push(node.val);\n node.left && traverse(node.left)\n node.right && traverse(node.right);\n }\n \n traverse(currentNode);\n return visitedNodes;\n }" ]
[ "0.8586327", "0.80949754", "0.78377247", "0.78191906", "0.78191906", "0.7784994", "0.7784994", "0.7784994", "0.7769381", "0.7545223", "0.74973994", "0.7490266", "0.7421076", "0.73980016", "0.7306658", "0.72934455", "0.72826487", "0.7265739", "0.72056234", "0.7176716", "0.7061097", "0.7046876", "0.70393145", "0.70218277", "0.70203805", "0.6998537", "0.696094", "0.696094", "0.6922681", "0.6893698", "0.68645865", "0.67907345", "0.6756864", "0.6743377", "0.6714066", "0.6700872", "0.6669368", "0.66533506", "0.6644839", "0.66327906", "0.6603852", "0.6564797", "0.65523076", "0.654072", "0.65339786", "0.6532404", "0.6497586", "0.6453754", "0.64520186", "0.64409256", "0.6387689", "0.63864684", "0.6384282", "0.6383414", "0.6340791", "0.63406", "0.62862456", "0.62496203", "0.6240982", "0.6236617", "0.62307674", "0.62293464", "0.619983", "0.6191537", "0.6184882", "0.617529", "0.6172259", "0.61694133", "0.61544704", "0.6111803", "0.60837924", "0.6061115", "0.6049689", "0.60467845", "0.604458", "0.60179245", "0.5982799", "0.59739065", "0.5965129", "0.59570587", "0.59532356", "0.5942424", "0.5941571", "0.59218323", "0.59169656", "0.59148794", "0.5894449", "0.5869738", "0.586121", "0.58532804", "0.5850877", "0.58249867", "0.58234257", "0.5822105", "0.5813701", "0.5807099", "0.57724124", "0.5759053", "0.57526004", "0.575114", "0.5750435" ]
0.0
-1
preorder traversal of nodes
animatePreorderNodes() { let queue = []; let animations = []; animations.push(new Animation("display", "Traversing Preorder", "")); this.aniamtePreorderNodesHelper(this.root, queue, animations); animations.push(new Animation("display", "Finished Traversing", "")); return [queue, animations]; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function preOrderTraversal(node) {}", "_preorder(node) {\n if (node !== null && node !== undefined) {\n this.currElem = node.getElement();\n this._preorder(node.getLeftChild());\n this._preorder(node.getRightChild());\n }\n }", "preorder(node) {\n if (node != null) {\n console.log(node.data);\n this.preorder(node.left);\n this.preorder(node.right);\n }\n }", "preorder(node) {\n if (node !== null) {\n console.log(node.data);\n this.preorder(node.left);\n this.preorder(node.right);\n }\n }", "function preOrderTraversal(node){\n console.log(node.key)\n \n if(node.left) {\n preOrderTraversal(node.left);\n }\n if(node.right){\n preOrderTraversal(node.right);\n }\n }", "preorder(node) {\n if (node !== null) {\n console.log(node.data);\n this.preorder(node.left);\n this.preorder(node.right);\n }\n }", "preorder(node){\n if(node !== null) {\n console.log(node.data);\n this.preorder(node.left);\n this.preorder(node.right);\n }\n }", "preorder(node)\n {\n if(node != null)\n {\n console.log(node.data);\n this.preorder(node.left);\n this.preorder(node.right);\n }\n }", "preOrder(node) {\n if (node != null) {\n console.log(node.data);\n this.preOrder(node.left);\n this.preOrder(node.right);\n }\n }", "function traversePreOrder(node) {\n console.log(node.value);\n if (node.left) {\n traversePreOrder(node.left);\n }\n if (node.right) {\n traversePreOrder(node.right);\n }\n}", "function preOrderTraversal(node) {\n if (node !== null) {\n console.log(node.val);\n preOrderTraversal(node.left);\n preOrderTraversal(node.right);\n }\n}", "function preorder(node){\n trav.push({\"key\": node.key, \"value\": node.value, \"children\": [_.get(node, \"left.value\", \"null\"), _.get(node, \"right.value\", \"null\")]})\n if(!_.isNull(node.left)) preorder(node.left)\n if(!_.isNull(node.right)) preorder(node.right)\n}", "function inOrderTraversal(node) {}", "preorder() {\n this.preorder(this._root);\n }", "preOrder(root=this.root,result=[]){\n if(root == null){\n return;\n }\n result.push(root.data);\n this.preOrder(root.nodeL, result);\n this.preOrder(root.nodeR, result);\n return result;\n }", "preOrder() {\n const results = [];\n const _traversal = (node) => {\n results.push(node.value);\n if (node.left) _traversal(node.left);\n if (node.right) _traversal(node.right);\n };\n _traversal(this.root);\n return results;\n }", "function pre_order(root, nodes) {\n nodes.push(root.data);\n if (root && root.left) {\n pre_order(root.left, nodes)\n }\n if (root && root.right) {\n pre_order(root.right, nodes)\n }\n return nodes;\n}", "preOrderTraversal(node, traversal = []) {\n if (node === null) {\n return traversal;\n } else {\n traversal.push(node.value);\n this.preOrderTraversal(node.left, traversal);\n this.preOrderTraversal(node.right, traversal);\n }\n return traversal;\n }", "preOrder(node) {\n if (node != null) {\n document.write(node.key + \" \");\n this.preOrder(node.left);\n this.preOrder(node.right);\n }\n }", "preOrderTraversal() {\n \n let visited = [];\n\n if (this.root === null) {\n return visited;\n }\n\n function preOrder(node) {\n if (node === null) {\n return;\n }\n\n visited.push(node.value);\n preOrder(node.left);\n preOrder(node.right);\n }\n\n preOrder(this.root);\n return visited;\n }", "function preorder(root){\r\n if (!root) return;\r\n\r\n console.log(root.val);\r\n preorder(root.left);\r\n preorder(root.right);\r\n // F, B, A, D, C, E, G, I, H\r\n}", "preorder() {\n const resultArray = [];\n return this.preorderHelper(this.root, resultArray);\n }", "preOrderTraversal(visitorFn) {\n visitorFn(this)\n\n if (this.leftChild) {\n this.leftChild.preOrderTraversal(visitorFn)\n }\n if (this.rightChild) {\n this.rightChild.preOrderTraversal(visitorFn)\n }\n }", "dfsPreOrder() {\n let result = [];\n function traverse(node, arr) {\n arr.push(node);\n if (node.left) traverse(node.left);\n if (node.right) traverse(node.right);\n }\n traverse(this.root, result);\n return result;\n }", "static *preorder(node) {\n if (node === null) {\n return\n }\n if ( !(node instanceof BinaryTreeNode) ) {\n throw Error(`The node must be a BinaryTreeNode instance!`)\n }\n yield node.data\n yield *this.preorder(node.left)\n yield *this.preorder(node.right)\n }", "function preOrder(node) {\n if (node == undefined) return [];\n return [node.data].concat(preOrder(node.left)).concat(preOrder(node.right));\n}", "function preOrder(root) {\n console.log(root.data) \n root.left && preOrder(root.left) \n root.right && preOrder(root.right) \n }", "preOrderSearch(node) {\n if (node === null) {\n return;\n }\n\n console.log(node.data);\n\n this.preOrderSearch(node.leftChild);\n this.preOrderSearch(node.rightChild);\n }", "preOrder() {\n const results = [];\n const _traverse = (node) => {\n results.push(node.value);\n if (node.left) _traverse(node.left);\n if (node.right) _traverse(node.right);\n }\n\n _traverse(this.root);\n return results;\n }", "traversePreOrder(node = this.root, arr = []) {\n if (!node) return arr;\n\n arr.push(node.val);\n this.traversePreOrder(node.left, arr);\n this.traversePreOrder(node.right, arr);\n return arr;\n }", "preOrder() {\n const result = [];\n\n // The recursive function\n function _preOrder(node) {\n if (node) {\n result.push(node.value);\n _preOrder(node.left);\n _preOrder(node.right);\n }\n }\n\n if (this.root) _preOrder(this.root);\n\n return result;\n }", "function preorder(g, root, f) {\n var visited = new Set();\n if (g.isDirected()) {\n throw new Error(\"This function only works for undirected graphs\");\n }\n function dfs(u, prev) {\n if (visited.has(u)) {\n throw new Error(\"The input graph is not a tree: \" + g);\n }\n visited.add(u);\n f(u);\n g.neighbors(u).forEach(function(v) {\n if (v !== prev) dfs(v, u);\n });\n }\n dfs(root);\n}", "dfsPreOrder() {\r\n let result = []\r\n\r\n const traverse = node => {\r\n result.push(node.data)\r\n if (node.left) traverse(node.left)\r\n if (node.right) traverse(node.right)\r\n }\r\n\r\n traverse(this.root)\r\n return result\r\n }", "function preOrder(node)\n\t{\n\t\tif (node == null)\n\t\t\treturn;\n\t\tdocument.write(node.data + \" \");\n\t\tpreOrder(node.left);\n\t\tpreOrder(node.right);\n\t}", "function preOrder(node, arr) {\n if (!arr) var arr = [];\n if (!node) return;\n arr.push(node.data);\n preOrder(node.left, arr);\n preOrder(node.right, arr);\n return arr;\n}", "dfsPreOrder(){\n let result = []\n\n const traverse = node => {\n //capture root node value//\n result.push(node.value)\n //if left node exists, go left again//\n if(node.left) traverse(node.left)\n //if right node exists, go right again//\n if(node.right) traverse(node.right)\n }\n\n traverse(this.root)\n console.log(`DFS Pre Order: ${result}`)\n }", "function preOrder(root){\n if (!root){\n return;\n }\n if (root){\n console.log(root.value);\n preOrder(root.left);\n preOrder(root.right);\n };\n}", "dfsPreOrder() {\n let result = [];\n\n const traverse = node => {\n result.push(node.data);\n if (node.left) {\n traverse(node.left)\n }\n if (node.right) {\n traverse(node.right)\n }\n }\n traverse(this.root);\n\n return result;\n }", "preOrder(root) {\n if (root != null) {\n console.log(root.data + ' ');\n if (root.parent == null) console.log('Parent : NULL');\n else console.log('Parent : ' + root.parent.data);\n this.preOrder(root.left);\n this.preOrder(root.right);\n }\n }", "dfsPreOrder() {\n let result = []\n const traverse = (node) => {\n // capture root node value\n result.push(node.value);\n // if left exists, go left again\n if (node.left) {\n traverse(node.left);\n } \n // if right child exists, go right again\n if (node.right) { \n traverse(node.right);\n }\n }\n traverse(this.root);\n return result;\n }", "function preOrder(tree) {\n //break case; if tree is null\n if (!tree) {\n return;\n }\n\n console.log(tree.key);\n\n if (tree.left){\n preOrder(tree.left);\n }\n\n if (tree.right){\n preOrder(tree.right);\n }\n\n}", "function preorderTraversal(A) {\n\tvar stack = [];\n\tvar preOrder = [];\n\tif (!A) {\n\t\treturn preOrder;\n\t}\n\n\tvar current = A;\n\twhile (current || stack.length) {\n\t\tif (current) {\n\t\t\tpreOrder.push(current.data);\n\t\t\tif (current.right) {\n\t\t\t\tstack.push(current.right);\n\t\t\t}\n\t\t\tcurrent = current.left;\n\t\t} else {\n\t\t\tcurrent = stack.pop();\n\t\t\tpreOrder.push(current.data);\n\t\t\tcurrent = current.left;\n\t\t}\n\t}\n\n\treturn preOrder;\n}", "preOrder() {\n const arr = [];\n const preOrder = (node) => {\n arr.push(node.value);\n\n if (node.left) {\n preOrder(node.left);\n }\n\n if (node.right) {\n preOrder(node.right);\n }\n };\n\n let current = this.root;\n preOrder(current);\n\n return arr;\n }", "preOrder() {\n let results = [];\n\n let _walk = node => {\n results.push(node.value); //root\n if (node.left) _walk(node.left);\n if (node.right) _walk(node.right);\n };\n _walk(this.root);\n\n return results;\n }", "function preorder(btree){\n let curr_node = btree.root;\n let s = [];\n if(curr_node){\n s.push(curr_node);\n }\n let result = [];\n while(s.length > 0){\n curr_node = s.pop();\n result.push(curr_node.value);\n if(curr_node.right){\n s.push(curr_node.right);\n }\n if(curr_node.left){\n s.push(curr_node.left);\n }\n }\n return result;\n}", "function preOrder_recursive(tree, index) {\n \n if (isUndefined(tree[index])) {\n return;\n }\n \n console.log(tree[index]);\n preOrder_recursive(tree, left(index));\n preOrder_recursive(tree, right(index));\n}", "preOrder() {\n console.log(this.data) \n this.left && preOrder(this.left) \n this.right && preOrder(this.right)\n }", "function postOrderTraversal(node) {}", "inorderTraversal() {\n\n }", "preOrderTraverseWithStack() {\n var stack = [this]\n var result = []\n while (stack.length != 0) {\n var tail = stack.pop()\n if (tail.rightChild !== null)\n stack.push(tail.rightChild)\n if (tail.leftChild !== null)\n stack.push(tail.leftChild)\n result.push(tail)\n }\n return result\n }", "function preorder(node, index, parent) {\n var children = node.children\n var childIndex = -1\n var position = 0\n\n if (is(node, index, parent)) {\n return null\n }\n\n if (children && children.length) {\n // Move all living children to the beginning of the children array.\n while (++childIndex < children.length) {\n if (preorder(children[childIndex], childIndex, node)) {\n children[position++] = children[childIndex]\n }\n }\n\n // Cascade delete.\n if (cascade && !position) {\n return null\n }\n\n // Drop other nodes.\n children.length = position\n }\n\n return node\n }", "dfsPreOrder() {\n let visitedNodes = [];\n let currentNode = this.root;\n\n function traverse(node){\n visitedNodes.push(node.val);\n node.left && traverse(node.left)\n node.right && traverse(node.right);\n }\n \n traverse(currentNode);\n return visitedNodes;\n }", "dfsPreOrder(current = this.root, visitedNodes=[]) {\n if(this.root === null) return [];\n visitedNodes.push(current.val);\n if (current.left) this.dfsPreOrder(current.left, visitedNodes);\n if (current.right) this.dfsPreOrder(current.right, visitedNodes);\n\n return visitedNodes;\n }", "dfs_pre_order() {\n const visited = [];\n const helper = (node) => {\n visited.push(node.value);\n if (node.left) helper(node.left);\n if (node.right) helper(node.right);\n }\n helper(this.root);\n return visited;\n }", "preTraverseSceneGraph(rootNode, func) {\n func(rootNode);\n if (!this.gameObjects.has(rootNode)) return; //might have been deleted during execution\n\n let nodeQueue = new Set(this.childrenOf(rootNode)); //shallow copy\n for (let child of nodeQueue) {\n this.preTraverseSceneGraph(child, func);\n }\n }", "preOrder(){\n let results = [];\n\n let _walk = node => {\n results.push(node.value); // root\n if(node.left) _walk(node.left); // left\n if(node.right) _walk(node.right); // right \n };\n\n _walk(this.root);\n\n return results;\n }", "function preOrder_iterative(tree, index) {\n \n var stack = [];\n \n while (stack.length > 0 || !isUndefined(tree[index])) {\n if (!isUndefined(tree[index])) {\n console.log(tree[index]);\n \n var rightNode = right(index);\n \n if (!isUndefined(tree[rightNode])) {\n stack.push(rightNode);\n }\n \n index = left(index);\n } else {\n index = stack.pop();\n }\n }\n}", "preorderTraversal(root) {\r\n const path = []\r\n if(root.children.length === 0)\r\n path.push(root.val)\r\n else {\r\n let preStack = new Stack();\r\n preStack.push(root)\r\n while(preStack.size!==0) {\r\n const currentNode = preStack.pop()\r\n path.push(currentNode.val)\r\n const currentChildren = currentNode.children\r\n //Children are looped from right to left so that they enter stack accordingly, and is popped out left to right\r\n for (let i=currentChildren.length-1; i>=0; i--) {\r\n preStack.push(currentChildren[i])\r\n }\r\n }\r\n }\r\n return path\r\n }", "function preOrder(node,data){\r\n\tif(node.test==null){\r\n\t\t//updateNode(j,<x,y>)\r\n\t\tnode.data.push(dataSet.length-1);\r\n\t\treturn node;\r\n\t}\r\n\tif(vectorSigmoid(data,node.test[0]) > node.test[1])\r\n\t\treturn preOrder(node.right,data);\r\n\telse\r\n\t\treturn preOrder(node.left,data);\r\n\r\n}", "function preOrderDFS(root) {\n if (root === null) return;\n // print here -> pre order\n console.log(root.value);\n if (root.left) {\n preOrderDFS(root.left);\n }\n // print here -> in order\n if (root.right) {\n preOrderDFS(root.right);\n }\n // print here -> post order\n}", "function preOrderTraverse(tree, array) {\n // Write your code here.\n\tif (tree !== null){\n\t\tarray.push(tree.value);\n\t\tpreOrderTraverse(tree.left, array);\n\t\tpreOrderTraverse(tree.right, array);\n\t}\n\n\treturn array;\n}", "dfsPreOrder() {\n const visitedNodes = [];\n const nodeStack = [this.root];\n\n while(nodeStack.length){\n const currentNode = nodeStack.pop();\n const {left, right} = currentNode;\n visitedNodes.push(currentNode.val); //Root or next node\n\n if(right) nodeStack.push(right);// right first so it gets popped after left\n if(left) nodeStack.push(left);// left last - it will get popped first\n }\n\n return visitedNodes;\n }", "preOrder() {\n let root = this.root;\n let arr = [];\n arr.push(root.value);\n\n if (root.left) {\n arr.push(...root.left.preOrder());\n }\n\n if (root.right) {\n arr.push(...root.right.preOrder());\n }\n return arr;\n }", "preOrder() { //DLR\n let results = [];\n\n let _walk = node => {\n results.push(node.value); //executing code\n if(node.left) _walk(node.left); //go left - if node,left is null, we are at a leaf - traversing\n if(node.right) _walk(node.right); // go right - if node.right=null then we are at a leaf - traversing\n };\n console.log(_walk(this.root));\n _walk(this.root); // for whiteboard use ll.root instead of this.root, unless using a class constructor\n return results;\n }", "dfs_preOrder(){ // ***** Noice! Using Helper Method Recursion\n if(!this.root) return null;\n \n let data = [];\n let cur = this.root;\n\n const traverse = (node) => {\n data.push(node.value);\n if(node.left) traverse(node.left);\n if(node.right) traverse(node.right);\n }\n traverse(cur);\n\n return data;\n }", "function preOrderTraversalUsingRecursion(node, cb) {\n if(node == null) {\n return;\n }\n\n cb ? cb(node) : console.log(node.value);\n preOrderTraversalUsingRecursion(node.left, cb);\n preOrderTraversalUsingRecursion(node.right, cb);\n\n}", "function eachBefore(root, callback) {\n\t var nodes = [root];\n\t var node;\n\t\n\t while (node = nodes.pop()) {\n\t // jshint ignore:line\n\t callback(node);\n\t\n\t if (node.isExpand) {\n\t var children = node.children;\n\t\n\t if (children.length) {\n\t for (var i = children.length - 1; i >= 0; i--) {\n\t nodes.push(children[i]);\n\t }\n\t }\n\t }\n\t }\n\t }", "function fnTraversal(root, node, preorder, postorder) {\n\t\tnode.childnodes.forEach((child, i) => { //iterate over next deep level\n\t\t\tpreorder(root, node, child, i) && fnTraversal(root, child, preorder, postorder); //preorder = cut/poda\n\t\t\tpostorder(root, node, child, i);\n\t\t});\n\t\treturn self;\n\t}", "traverseBefore(fn, skipSelf = false) {\n const me = this;\n\n if (me.isLoaded) {\n me.children.forEach((child) => child.traverse(fn));\n }\n if (!skipSelf) {\n fn.call(me, me);\n }\n }", "prepend(value) {\n let node = new Node(value);\n node.next = this.root;\n\n this.root.prev = node;\n this.root = node;\n }", "traverseBefore(fn, skipSelf = false) {\n const {\n children\n } = this; // Simply testing whether there is non-zero children length\n // is 10x faster than using this.isLoaded\n\n for (let i = 0, l = children && children.length; i < l; i++) {\n children[i].traverse(fn);\n }\n\n if (!skipSelf) {\n fn.call(this, this);\n }\n }", "*nodesAscending(){\n let i = 0;\n let node = this.root && this.root.getLeftmostChild();\n while(node){\n yield node;\n node = node.getSuccessor();\n }\n }", "dfsPreOrder() {\n const result = [];\n\n // traverse tree\n const traverseTree = node => {\n // root value\n result.push(node.value);\n\n // if left child exists, go left again\n if (node.left) traverseTree(node.left);\n\n // if right child exists, go right again\n if (node.right) traverseTree(node.right);\n };\n traverseTree(this.root);\n\n return result;\n }", "function preOrderTraverse(tree, array) {\n if (tree !== null) {\n // start by appending to the array the value \n array.push(tree.value)\n preOrderTraverse(tree.left, array)\n preOrderTraverse(tree.right, array)\n }\n return array\n}", "preOrder(root = this.root, values = []) {\n if (!root) {\n return null;\n }\n // Add root value\n if (root) {\n values.push(root.data);\n }\n if (root.left) {\n this.preOrder(root.left, values);\n }\n if (root.right) {\n this.preOrder(root.right, values);\n }\n return values;\n }", "prepend(data) {\n console.log(\"prepend\", data);\n const node = new Node(data);\n if (this.head === null) {\n return (this.head = null);\n }\n node.next = this.head;\n this.head = node;\n }", "inorderTraversal(node = this.root) {\n if (node === null)\n return;\n\n this.inorderTraversal(node.left);\n console.log(node.data);\n this.inorderTraversal(node.right);\n }", "function eachBefore(root, callback) {\n var nodes = [root];\n var node;\n\n while (node = nodes.pop()) {\n // jshint ignore:line\n callback(node);\n\n if (node.isExpand) {\n var children = node.children;\n\n if (children.length) {\n for (var i = children.length - 1; i >= 0; i--) {\n nodes.push(children[i]);\n }\n }\n }\n }\n}", "function getPreOrderIterable(rootNode) {\r\n\r\n if (!(rootNode instanceof Node)) {\r\n throw new TypeError('Parameter rootNode must be of Node type')\r\n }\r\n\r\n // to generate an iterator, a stack data structure will be created\r\n // the nodes will be pushed to this stack as if they were traversed in pre order\r\n\r\n // initially add the root node to the top of stack\r\n let nodeStack = [rootNode]\r\n\r\n return {\r\n [Symbol.iterator]: () => {\r\n return {\r\n next: () => {\r\n // process the \"current parent\"\r\n let nextNode = nodeStack.pop()\r\n\r\n // check if there are children to be processed next\r\n if (nextNode && !nextNode.isLeaf()) {\r\n let childrenReversed = [...nextNode.children].reverse()\r\n nodeStack.push(...childrenReversed)\r\n }\r\n\r\n if (nextNode) {\r\n return {value: nextNode, done: false}\r\n }\r\n else {\r\n return {done: true}\r\n }\r\n }\r\n }\r\n }\r\n }\r\n }", "function prewalk(treeNode, iterator, childGetter) {\n var counter = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : { i: 0 };\n var depth = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : 0;\n\n var i = counter.i++;\n iterator(treeNode, i, depth);\n (childGetter(treeNode, i, depth) || []).forEach(function (ea) {\n return prewalk(ea, iterator, childGetter, counter, depth + 1);\n });\n}", "inOrderTraversal(node, callback) {\n if (node !== null) {\n this.inOrderTraversal(node.left, callback);\n callback(node.key); // append via callback\n this.inOrderTraversal(node.right, callback);\n }\n }", "prepend(value) {\n let node = new ListNode(value);\n node.next = this.root; \n this.root = node;\n this.length++;\n }", "getPredecessor(){\n if(this.left) return this.left.getRightmostChild();\n let node = this;\n while(node){\n if(node.parent && node === node.parent.right) return node.parent;\n node = node.parent;\n }\n }", "inorder(node) {\n if (node !== null) {\n this.inorder(node.left);\n console.log(node.data);\n this.inorder(node.right);\n }\n }", "inorder(node) {\n if (node !== null) {\n this.inorder(node.left);\n console.log(node.data);\n this.inorder(node.right);\n }\n }", "inorder(node){\n if(node !== null){\n this.inorder(node.left);\n console.log(node.data);\n this.inorder(node.right);\n }\n }", "function inorder(node){\n if(!_.isNull(node.left)) inorder(node.left)\n trav.push({\"key\": node.key, \"value\": node.value, \"children\": [_.get(node, \"left.value\", \"null\"), _.get(node, \"right.value\", \"null\")]})\n if(!_.isNull(node.right)) inorder(node.right)\n}", "function solution_1 (preorder) {\n const root = new TreeNode(preorder[0]);\n function insert (root, val) {\n if (val <= root.val) {\n if (root.left) {\n insert(root.left, val);\n } else {\n root.left = new TreeNode(val);\n }\n } else {\n if (root.right) {\n insert(root.right, val);\n } else {\n root.right = new TreeNode(val);\n }\n }\n }\n for (let i = 1; i < preorder.length; ++i) {\n insert(root, preorder[i]);\n }\n return root;\n}", "function preOrder(t) {\n if (!t) {\n return [];\n }\n else {\n const left = preOrder(t.left);\n const right = preOrder(t.right);\n return [t.value, ...left, ...right]\n }\n}", "function bstFromPreorder(preorder) {\n if (preorder.length == 0) return null;\n const ans = new TreeNode(preorder[0]);\n let stack = [[ans, Infinity]], length = preorder.length;\n for (let i = 1; i < length; i++) {\n const node = new TreeNode(preorder[i]);\n while ((stack[stack.length - 1][0].left && stack[stack.length - 1][0].right) || stack[stack.length - 1][1] < preorder[i]) {\n stack.pop();\n }\n if (preorder[i] < stack[stack.length - 1][0].val) {\n stack[stack.length - 1][0].left = node;\n stack.push([node, stack[stack.length - 1][0].val])\n } else {\n stack[stack.length - 1][0].right = node;\n stack.push([node, stack[stack.length - 1][1]]);\n }\n } \n return ans;\n}", "inorder(node) {\n if (node !== null) {\n this.inorder(node.left);\n console.log(node.data);\n this.inorder(node.right);\n }\n }", "inorder(node) {\n if (node !== null) {\n this.inorder(node.left);\n console.log(node.data);\n this.inorder(node.right);\n }\n }", "inorder(node) {\n if (node !== null) {\n this.inorder(node.left);\n console.log(node.data);\n this.inorder(node.right);\n }\n }", "createPreOrder(arr, node = this.root) {\n if (arr.length > 0) {\n let val = arr.shift();\n if (!val) return null;\n\n if (!node) {\n node = new BinaryTreeNode(val);\n } else node.val = val;\n\n node.left = this.createPreOrder(arr, node.left);\n node.right = this.createPreOrder(arr, node.right);\n }\n return node;\n }", "inorder() {\n this.inorder(this._root);\n }", "prepend(value){\nconst newNode = new Node(value);\n//// {\n// value:value,\n// next:null\n// }\nnewNode.next = this.head;\nthis.head = newNode;\nthis.length++;\n\n\n}", "function inOrderTraversal(node) {\n if (node !== null) {\n inOrderTraversal(node.left);\n console.log(node.val);\n inOrderTraversal(node.right);\n }\n}", "function preOrderTraverse(root) {\n if (!root) return;\n // visit and copy current node\n var mappedNode = {};\n var val = root['$'];\n mappedNode.id = val.id;\n mappedNode.name = val.feature || val.id;\n mappedNode.value = val.value || -1;\n // recurse on children\n mappedNode.children = [];\n \n var children = root.Node;\n var responses = root.Response;\n if (children) {\n if (children[0]) mappedNode.children.push(preOrderTraverse(children[0]));\n if (children[1]) mappedNode.children.push(preOrderTraverse(children[1]));\n }\n if (responses) {\n if (responses[0]) {\n mappedNode.children.push({\n id: responses[0].$.id,\n name: responses[0].$.value,\n value: responses[0].$.value,\n children:[]\n });\n }\n if (responses[1]) {\n mappedNode.children.push({\n id: responses[1].$.id,\n name: responses[1].$.value,\n value: responses[1].$.value,\n children:[]\n });\n }\n }\n\n return mappedNode;\n }", "prepend(data) {\n const newNode = new Node(data);\n newNode.next = this.head;\n this.head = newNode;\n }", "unshift(data) {\n const node = new Node(data);\n if (this.head) {\n node.next = this.head;\n }\n this.head = node;\n }", "inOrderTraversal(visitorFn) {\n if (this.leftChild) {\n this.leftChild.inOrderTraversal(visitorFn)\n }\n\n visitorFn(this)\n\n if (this.rightChild) {\n this.rightChild.inOrderTraversal(visitorFn)\n }\n }" ]
[ "0.88136935", "0.81697696", "0.81652904", "0.8152653", "0.812996", "0.8125248", "0.80743426", "0.80690646", "0.8026129", "0.7895955", "0.77762496", "0.7703113", "0.7663644", "0.75896186", "0.7567731", "0.7550127", "0.7522614", "0.7482504", "0.74700505", "0.74630684", "0.74617827", "0.7451562", "0.743479", "0.7386904", "0.7365205", "0.7363684", "0.7345636", "0.7309474", "0.7213639", "0.7181316", "0.71774614", "0.715998", "0.71452206", "0.7126917", "0.7107954", "0.709175", "0.7073611", "0.7072512", "0.70530355", "0.70461303", "0.70262146", "0.7000896", "0.69984037", "0.69948786", "0.6984717", "0.6975068", "0.69730693", "0.69460356", "0.6943215", "0.69355476", "0.6930141", "0.6924572", "0.6870454", "0.6867167", "0.68633926", "0.6861617", "0.6841587", "0.68044305", "0.68000054", "0.6799061", "0.67925376", "0.6781459", "0.67077404", "0.6692081", "0.6659666", "0.6653965", "0.6602879", "0.65628785", "0.6560732", "0.65463555", "0.65339273", "0.6499613", "0.6491274", "0.6479145", "0.64724225", "0.6456095", "0.64516747", "0.6386604", "0.6365583", "0.624822", "0.6218739", "0.6199233", "0.6184147", "0.617504", "0.617504", "0.61388326", "0.6136605", "0.6124593", "0.6115665", "0.6113629", "0.6111635", "0.6111635", "0.6111635", "0.6109216", "0.610355", "0.60961765", "0.60779196", "0.60724527", "0.6053845", "0.6047936", "0.6038518" ]
0.0
-1
postorder traversal of nodes
animatePostorderNodes() { let queue = []; let animations = []; animations.push(new Animation("display", "Traversing Postorder", "")); this.animatePostorderNodesHelper(this.root, queue, animations); animations.push(new Animation("display", "Finished Traversing", "")); return [queue, animations]; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function postOrderTraversal(node) {}", "postorder(node) {\n if (node != null) {\n this.postorder(node.left);\n this.postorder(node.right);\n console.log(node.data);\n }\n }", "postorder(node) {\n if (node !== null) {\n this.postorder(node.left);\n this.postorder(node.right);\n console.log(node.data);\n }\n }", "postorder(node){\n if(node !== null) {\n this.postorder(node.left);\n this.postorder(node.right);\n console.log(node.data);\n }\n }", "_postorder(node) {\n if (node !== null && node !== undefined) {\n this._postorder(node.getLeftChild());\n this._postorder(node.getRightChild());\n this.currElem = node.getElement();\n }\n }", "function postOrderTraversal(node) {\n if (node !== null) {\n postOrderTraversal(node.left);\n postOrderTraversal(node.right);\n console.log(node.val);\n }\n}", "postOrder(node) {\n if (node != null) {\n this.postOrder(node.left);\n this.postOrder(node.right);\n console.log(node.data);\n }\n }", "function postOrder(node) {\n if (node == undefined) return [];\n return postOrder(node.left).concat(postOrder(node.right)).concat([node.data]);\n}", "postOrder() {\n const results = [];\n const _traversal = (node) => {\n if (node.left) _traversal(node.left);\n if (node.right) _traversal(node.right);\n results.push(node.value);\n };\n _traversal(this.root);\n return results;\n }", "postOrderTraversal() {\n\n let visited = [];\n\n function postOrder(node) {\n if (node !== null) {\n if (node.left !== null) postOrder(node.left);\n if (node.right !== null) postOrder(node.right);\n visited.push(node.value);\n }\n }\n\n postOrder(this.root);\n return visited;\n }", "function postorder(node){\n if(!_.isNull(node.left)) postorder(node.left)\n if(!_.isNull(node.right)) postorder(node.right)\n trav.push({\"key\": node.key, \"value\": node.value, \"children\": [_.get(node, \"left.value\", \"null\"), _.get(node, \"right.value\", \"null\")]})\n}", "postOrder(node) {\n if (node !== null) {\n this.postOrder(node.left);\n this.postOrder(node.right);\n console.log(node.show());\n }\n }", "function postorderTraversal(node) {\n let stack = [];\n let res = [];\n\n if (node) stack.push(node);\n\n while (stack.length) {\n node = stack.pop();\n\n res.unshift(node.val);\n\n if (node.left) stack.push(node.left);\n if (node.right) stack.push(node.right);\n }\n\n return res;\n}", "postOrder() {\n const results = [];\n const _traverse = (node) => {\n if (node.left) _traverse(node.left);\n if (node.right) _traverse(node.right);\n results.push(node.value);\n };\n\n _traverse(this.root);\n return results;\n }", "dfsPostOrder() {\n let result = [];\n\n function traverse(node, arr) {\n if (node.left) traverse(node.left);\n if (node.right) traverse(node.right);\n arr.push(node);\n }\n traverse(this.root, result);\n return result;\n }", "postOrderTraversal(visitorFn) {\n if (this.leftChild) {\n this.leftChild.postOrderTraversal(visitorFn)\n }\n if (this.rightChild) {\n this.rightChild.postOrderTraversal(visitorFn)\n }\n visitorFn(this)\n }", "function inOrderTraversal(node) {}", "function preOrderTraversal(node) {}", "dfsPostOrder() {\n const visitedNodes = [];\n const nodeStack = [this.root];\n\n while(nodeStack.length){\n const currentNode = nodeStack.pop();\n const {left, right} = currentNode;\n\n visitedNodes.push(currentNode.val);\n if(right) {\n nodeStack.push(right);\n }else{\n visitedNodes.push(currentNode.val);\n }// right first so it gets popped after left\n if(left){\n nodeStack.push(left);\n }else{\n visitedNodes.push(currentNode.val);\n }\n //add current node\n //then right, then left to visited\n }\n\n return visitedNodes;\n }", "function postOrder_iterative(tree, index) {\n \n var stack = [];\n var lastNodeVisited = null;\n \n var node = tree[index];\n \n while (stack.length > 0 || !isUndefined(node)) {\n if (!isUndefined(node)) {\n \n stack.push(index);\n index = left(index);\n node = tree[index];\n\n } else {\n var peekNode = peek(stack);\n var peekNodeRight = right(peekNode);\n \n if (!isUndefined(tree[peekNodeRight]) && lastNodeVisited != peekNodeRight) {\n index = peekNodeRight;\n node = tree[index];\n } else {\n console.log(tree[peekNode]);\n lastNodeVisited = stack.pop();\n delete node;\n }\n }\n }\n}", "dfsPostOrder(){\n let result = []\n\n const traverse = node => {\n //if left node exists, go left again//\n if(node.left) traverse(node.left)\n //if right node exists, go right again//\n if(node.right) traverse(node.right)\n //capture root node value//\n result.push(node.value)\n }\n\n traverse(this.root)\n console.log(`DFS Post Order: ${result}`)\n }", "postOrder(root=this.root,result=[]){\n if(root == null){\n return;\n }\n this.postOrder(root.nodeL, result);\n this.postOrder(root.nodeR, result);\n result.push(root.data);\n return result;\n }", "postorderTraversal(root) {\r\n const path = []\r\n const rootChildren = root.children\r\n if(rootChildren.length === 0)\r\n path.push(root.val)\r\n else {\r\n let preStack = new Stack();\r\n preStack.push(root)\r\n while(preStack.size!==0) {\r\n const currentNode = preStack.pop()\r\n const currentChildren = currentNode.children\r\n if(currentChildren.length > 0 && !currentNode.visited) {\r\n //An addl visited flag is being used to identify that it already has been recorded\r\n currentNode.visited = true\r\n preStack.push(currentNode)\r\n //Children are looped from right to left so that they enter stack accordingly, and is popped out left to right\r\n for (let i=currentChildren.length-1; i>=0; i--) {\r\n preStack.push(currentChildren[i])\r\n }\r\n } else {\r\n //Visited flag is reset\r\n currentNode.visited = false\r\n path.push(currentNode.val)\r\n } \r\n }\r\n }\r\n return path\r\n }", "function postOrder(tree) {\n\tif(!tree){\n\t\treturn\n\t}\n\tpostOrder(tree.left)\n\tpostOrder(tree.right)\n\tconsole.log(tree.val)\n\n}", "dfs_post_order() {\n const visited = [];\n const helper = (node) => {\n if (node.left) helper(node.left);\n if (node.right) helper(node.right);\n visited.push(node.value);\n }\n helper(this.root);\n return visited;\n }", "postOrder() {\n const result = [];\n\n // The recursive function\n function _preOrder(node) {\n if (node) {\n _preOrder(node.left);\n _preOrder(node.right);\n result.push(node.value);\n }\n }\n\n if (this.root) _preOrder(this.root);\n\n return result;\n }", "dfsPostOrder() {\n let visitedNodes = [];\n let currentNode = this.root;\n\n function traverse(node){\n \n node.left && traverse(node.left)\n \n node.right && traverse(node.right);\n\n visitedNodes.push(node.val);\n }\n \n traverse(currentNode);\n return visitedNodes;\n }", "function postOrderDFS(root) {\n if (root === null) return;\n // print here -> pre order\n if (root.left) {\n preOrderDFS(root.left);\n }\n // print here -> in order\n if (root.right) {\n preOrderDFS(root.right);\n }\n // print here -> post order\n console.log(root.value);\n}", "function postOrderWalk( node, cb ) {\n\n // traverse children\n if( typeof node == 'object' ) {\n if( 'op1' in node){ postOrderWalk( node.op1, cb ); }\n if( 'op2' in node){ postOrderWalk( node.op2, cb ); }\n }\n\n // execute callback\n cb( node );\n\n }", "dfsPostOrder() {\n let result = []\n const traverse = (node) => {\n // if left exists, go left again\n if (node.left) {\n traverse(node.left);\n } \n // if right child exists, go right again\n if (node.right) { \n traverse(node.right);\n }\n // capture root node value\n result.push(node.value);\n }\n traverse(this.root);\n return result;\n }", "function postOrder(node, arr) {\n if (!arr) var arr = [];\n if (!node) return;\n postOrder(node.left, arr);\n postOrder(node.right, arr);\n arr.push(node.data);\n return arr\n}", "postOrder() {\n const arr = [];\n\n const postOrder = (node) => {\n if (node.left) {\n postOrder(node.left);\n }\n\n if (node.right) {\n postOrder(node.right);\n }\n arr.push(node.value);\n };\n\n let current = this.root;\n postOrder(current);\n\n return arr;\n }", "dfs_postOrder(){\n if(!this.root) return null;\n \n let data = [];\n let cur = this.root;\n\n const traverse = (node) =>{\n if(node.left) traverse(node.left);\n if(node.right) traverse(node.right);\n data.push(node.value);\n }\n traverse(cur);\n\n return data;\n }", "dfsPostOrder(current = this.root, visitedNodes=[]) {\n if(this.root === null) return [];\n if (current.left) this.dfsPostOrder(current.left, visitedNodes);\n if (current.right) this.dfsPostOrder(current.right, visitedNodes);\n visitedNodes.push(current.val);\n\n return visitedNodes;\n\n }", "dfsPostOrder() {\r\n let result = []\r\n\r\n const traverse = node => {\r\n if (node.left) traverse(node.left)\r\n if (node.right) traverse(node.right)\r\n result.push(node.data)\r\n }\r\n\r\n traverse(this.root)\r\n return result\r\n }", "postorder() {\n this.postorder(this._root);\n }", "postorder() {\n const resultArray = [];\n return this.postorderHelper(this.root, resultArray);\n }", "function postOrderTraverse(tree, array) {\n // Write your code here.\n\tif(tree !== null){\n\t\tpostOrderTraverse(tree.left, array);\n\t\tpostOrderTraverse(tree.right, array);\n\t\tarray.push(tree.value);\n\t}\n\n\treturn array;\n}", "*nodes(root) {\n var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n var {\n pass,\n reverse = false\n } = options;\n var {\n from = [],\n to\n } = options;\n var visited = new Set();\n var p = [];\n var n = root;\n\n while (true) {\n if (to && (reverse ? Path.isBefore(p, to) : Path.isAfter(p, to))) {\n break;\n }\n\n if (!visited.has(n)) {\n yield [n, p];\n } // If we're allowed to go downward and we haven't decsended yet, do.\n\n\n if (!visited.has(n) && !Text.isText(n) && n.children.length !== 0 && (pass == null || pass([n, p]) === false)) {\n visited.add(n);\n var nextIndex = reverse ? n.children.length - 1 : 0;\n\n if (Path.isAncestor(p, from)) {\n nextIndex = from[p.length];\n }\n\n p = p.concat(nextIndex);\n n = Node.get(root, p);\n continue;\n } // If we're at the root and we can't go down, we're done.\n\n\n if (p.length === 0) {\n break;\n } // If we're going forward...\n\n\n if (!reverse) {\n var newPath = Path.next(p);\n\n if (Node.has(root, newPath)) {\n p = newPath;\n n = Node.get(root, p);\n continue;\n }\n } // If we're going backward...\n\n\n if (reverse && p[p.length - 1] !== 0) {\n var _newPath = Path.previous(p);\n\n p = _newPath;\n n = Node.get(root, p);\n continue;\n } // Otherwise we're going upward...\n\n\n p = Path.parent(p);\n n = Node.get(root, p);\n visited.add(n);\n }\n }", "dfsPostOrder() {\n let result = [];\n const traverse = node => {\n if (node.left) {\n traverse(node.left)\n }\n if (node.right) {\n traverse(node.right)\n }\n result.push(node.data);\n }\n\n\n traverse(this.root)\n return result;\n }", "function postOrder_recursive(tree, index) {\n \n if (isUndefined(tree[index])) {\n return;\n }\n \n postOrder_recursive(tree, left(index));\n postOrder_recursive(tree, right(index));\n \n console.log(tree[index]);\n}", "function postOrder(root){\n if(!root){\n return;\n }\n if (root){\n postOrder(root.left);\n postOrder(root.right);\n console.log(root.value);\n };\n}", "function postOrderTraverse(tree, array) {\n if (tree !== null) {\n postOrderTraverse(tree.left, array)\n postOrderTraverse(tree.right, array)\n array.push(tree.value)\n }\n return array\n}", "postOrder() {\n let root = this.root;\n let arr = [];\n\n if (root.left) {\n arr.push(...root.left.postOrder());\n }\n\n if (root.right) {\n arr.push(...root.right.postOrder());\n }\n\n arr.push(root.value);\n return arr;\n }", "*nodes(root) {\n var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n var {\n pass,\n reverse = false\n } = options;\n var {\n from = [],\n to\n } = options;\n var visited = new Set();\n var p = [];\n var n = root;\n\n while (true) {\n if (to && (reverse ? Path.isBefore(p, to) : Path.isAfter(p, to))) {\n break;\n }\n\n if (!visited.has(n)) {\n yield [n, p];\n } // If we're allowed to go downward and we haven't descended yet, do.\n\n\n if (!visited.has(n) && !Text.isText(n) && n.children.length !== 0 && (pass == null || pass([n, p]) === false)) {\n visited.add(n);\n var nextIndex = reverse ? n.children.length - 1 : 0;\n\n if (Path.isAncestor(p, from)) {\n nextIndex = from[p.length];\n }\n\n p = p.concat(nextIndex);\n n = Node.get(root, p);\n continue;\n } // If we're at the root and we can't go down, we're done.\n\n\n if (p.length === 0) {\n break;\n } // If we're going forward...\n\n\n if (!reverse) {\n var newPath = Path.next(p);\n\n if (Node.has(root, newPath)) {\n p = newPath;\n n = Node.get(root, p);\n continue;\n }\n } // If we're going backward...\n\n\n if (reverse && p[p.length - 1] !== 0) {\n var _newPath = Path.previous(p);\n\n p = _newPath;\n n = Node.get(root, p);\n continue;\n } // Otherwise we're going upward...\n\n\n p = Path.parent(p);\n n = Node.get(root, p);\n visited.add(n);\n }\n }", "function fnTraversal(root, node, preorder, postorder) {\n\t\tnode.childnodes.forEach((child, i) => { //iterate over next deep level\n\t\t\tpreorder(root, node, child, i) && fnTraversal(root, child, preorder, postorder); //preorder = cut/poda\n\t\t\tpostorder(root, node, child, i);\n\t\t});\n\t\treturn self;\n\t}", "function postorder(g, root, f) {\n var visited = new Set();\n if (g.isDirected()) {\n throw new Error(\"This function only works for undirected graphs\");\n }\n function dfs(u, prev) {\n if (visited.has(u)) {\n throw new Error(\"The input graph is not a tree: \" + g);\n }\n visited.add(u);\n g.neighbors(u).forEach(function(v) {\n if (v !== prev) dfs(v, u);\n });\n f(u);\n }\n dfs(root);\n}", "postOrder(root = this.root, values = []) {\n if (root.left) {\n values.push(...this.inOrder(root.left));\n }\n if (root.right) {\n values.push(...this.inOrder(root.right));\n }\n values.push(root.data);\n return values;\n }", "function traversePreOrder(node) {\n console.log(node.value);\n if (node.left) {\n traversePreOrder(node.left);\n }\n if (node.right) {\n traversePreOrder(node.right);\n }\n}", "preorder(node){\n if(node !== null) {\n console.log(node.data);\n this.preorder(node.left);\n this.preorder(node.right);\n }\n }", "DFSPostOrder() {\n const accum = [];\n function traverse(node) {\n if (node.left) traverse(node.left);\n if (node.right) traverse(node.right);\n accum.push(node.value);\n }\n traverse(this.root);\n return accum;\n }", "dfsPostOrder() {\n const result = [];\n\n // traverse tree\n const traverseTree = node => {\n // if left child exists, go left again\n if (node.left) traverseTree(node.left);\n\n // if right child exists, go right again\n if (node.right) traverseTree(node.right);\n\n // root value\n result.push(node.value);\n };\n traverseTree(this.root);\n\n return result;\n }", "function xWalkTreeRev( oNode, fnVisit, skip, data )\r\n{\r\n var r=null;\r\n if(oNode){if(oNode.nodeType==1&&oNode!=skip){r=fnVisit(oNode,data);if(r)return r;}\r\n for(var c=oNode.lastChild;c;c=c.previousSibling){if(c!=skip)r=xWalkTreeRev(c,fnVisit,skip,data);if(r)return r;}}\r\n return r;\r\n}", "inorderTraversal() {\n\n }", "function postOrderSingle (root) {\n \n}", "DFSPreOrder(){\n var data = [],\n current = this.root\n \n function traverse(node) {\n data.push(node.value)\n if (node.left) traverse(node.left)\n if (node.right) traverse(node.right)\n }\n traverse(current)\n return data\n }", "DFSPostOrder() {\n let data = []\n function traverse(node) {\n if (node.left) traverse(node.left)\n if (node.right) traverse(node.right)\n data.push(node.value)\n }\n traverse(this.root)\n return data\n }", "preorder(node) {\n if (node !== null) {\n console.log(node.data);\n this.preorder(node.left);\n this.preorder(node.right);\n }\n }", "dfsPreOrder() {\n const visitedNodes = [];\n const nodeStack = [this.root];\n\n while(nodeStack.length){\n const currentNode = nodeStack.pop();\n const {left, right} = currentNode;\n visitedNodes.push(currentNode.val); //Root or next node\n\n if(right) nodeStack.push(right);// right first so it gets popped after left\n if(left) nodeStack.push(left);// left last - it will get popped first\n }\n\n return visitedNodes;\n }", "DFSPostOrder() {\n var data = [],\n current = this.root\n\n function traverse(node) {\n if (node.left) traverse(node.left)\n if (node.right) traverse(node.right)\n data.push(node.value)\n }\n traverse(current)\n return data\n }", "DFSPostOrder() {\n if (!this.root) return [];\n const visited = [];\n const visitNodeDFSPostOrder = (node) => {\n if (node.left) visitNodeDFSPostOrder(node.left);\n if (node.right) visitNodeDFSPostOrder(node.right);\n visited.push(node.value);\n }\n visitNodeDFSPostOrder(this.root);\n return visited;\n }", "preorder(node) {\n if (node != null) {\n console.log(node.data);\n this.preorder(node.left);\n this.preorder(node.right);\n }\n }", "DFSPreOrder() {\n let data = [];\n traverse = (node) => {\n data.push(node);\n if (node.left) traverse(node.left);\n if (node.right) traverse(node.right);\n }\n traverse(this.root)\n return data\n }", "function preOrderTraversal(node) {\n if (node !== null) {\n console.log(node.val);\n preOrderTraversal(node.left);\n preOrderTraversal(node.right);\n }\n}", "preorder(node) {\n if (node !== null) {\n console.log(node.data);\n this.preorder(node.left);\n this.preorder(node.right);\n }\n }", "function preOrderTraversal(node){\n console.log(node.key)\n \n if(node.left) {\n preOrderTraversal(node.left);\n }\n if(node.right){\n preOrderTraversal(node.right);\n }\n }", "dfsPreOrder() {\n let result = []\n const traverse = (node) => {\n // capture root node value\n result.push(node.value);\n // if left exists, go left again\n if (node.left) {\n traverse(node.left);\n } \n // if right child exists, go right again\n if (node.right) { \n traverse(node.right);\n }\n }\n traverse(this.root);\n return result;\n }", "DFSPostOrder() {\n let data = [];\n let current = this.root;\n\n function traverse(node) {\n if (node.left) traverse(node.left)\n if (node.right) traverse(node.right)\n data.push(node.value)\n }\n\n traverse(current);\n console.log(data);\n return data;\n }", "preOrder(node) {\n if (node != null) {\n console.log(node.data);\n this.preOrder(node.left);\n this.preOrder(node.right);\n }\n }", "DFSPostOrder() {\n let data = [];\n\n let traverse = (node) => {\n if (node.left) traverse(node.left);\n if (node.right) traverse(node.right);\n data.push(node.value)\n }\n\n traverse(this.root)\n return data;\n }", "preorder(node)\n {\n if(node != null)\n {\n console.log(node.data);\n this.preorder(node.left);\n this.preorder(node.right);\n }\n }", "dfsPreOrder() {\n let result = [];\n function traverse(node, arr) {\n arr.push(node);\n if (node.left) traverse(node.left);\n if (node.right) traverse(node.right);\n }\n traverse(this.root, result);\n return result;\n }", "function postDepth(fun, ary) {\n return visit(partial(postDepth, fun), fun, ary);\n}", "addToBack(nodes){ // does not return anything\n var runner=this.head\n while(runner){\n if(runner.next==null){\n runner.next=nodes;\n }\n else runner=runner.next;\n }\n }", "function postOrder(t) {\n if (!t) {\n return [];\n }\n else {\n const left = postOrder(t.left);\n const right = postOrder(t.right);\n return [...left, ...right, t.value];\n }\n}", "dfsPreOrder() {\r\n let result = []\r\n\r\n const traverse = node => {\r\n result.push(node.data)\r\n if (node.left) traverse(node.left)\r\n if (node.right) traverse(node.right)\r\n }\r\n\r\n traverse(this.root)\r\n return result\r\n }", "DFSPreOrder() {\n let data = []\n function traverse(node) {\n data.push(node.value)\n if (node.left) traverse(node.left)\n if (node.right) traverse(node.right)\n }\n traverse(this.root)\n return data\n }", "dfsPreOrder(){\n let result = []\n\n const traverse = node => {\n //capture root node value//\n result.push(node.value)\n //if left node exists, go left again//\n if(node.left) traverse(node.left)\n //if right node exists, go right again//\n if(node.right) traverse(node.right)\n }\n\n traverse(this.root)\n console.log(`DFS Pre Order: ${result}`)\n }", "DFSPreOrder() {\n let data = [];\n let current = this.root;\n\n const traverse = (node) => {\n data.push(node.value);\n if (node.left) traverse(node.left);\n if (node.right) traverse(node.right);\n }\n\n traverse(current)\n return data;\n }", "DFSPreOrder() {\n const accum = [];\n function traverse(node) {\n accum.push(node.value);\n if (node.left) traverse(node.left);\n if (node.right) traverse(node.right);\n }\n traverse(this.root);\n return accum;\n }", "preOrder() { //DLR\n let results = [];\n\n let _walk = node => {\n results.push(node.value); //executing code\n if(node.left) _walk(node.left); //go left - if node,left is null, we are at a leaf - traversing\n if(node.right) _walk(node.right); // go right - if node.right=null then we are at a leaf - traversing\n };\n console.log(_walk(this.root));\n _walk(this.root); // for whiteboard use ll.root instead of this.root, unless using a class constructor\n return results;\n }", "traverse(node, process_node = this.node_out) {\n if (!node) return;\n this.traverse(node.left, process_node);\n process_node(node); // in-order !!!\n this.traverse(node.right, process_node);\n return this;\n }", "dfsPreOrder() {\n let visitedNodes = [];\n let currentNode = this.root;\n\n function traverse(node){\n visitedNodes.push(node.val);\n node.left && traverse(node.left)\n node.right && traverse(node.right);\n }\n \n traverse(currentNode);\n return visitedNodes;\n }", "*nodesDescending(){\n let node = this.root && this.root.getRightmostChild();\n while(node){\n yield node;\n node = node.getPredecessor();\n }\n }", "DFSPreOrder() {\n let data = [];\n let current = this.root;\n\n function traverse(node) {\n data.push(node.value);\n if (node.left) traverse(node.left);\n if (node.right) traverse(node.right);\n }\n traverse(current)\n console.log(data)\n return data;\n }", "preOrder() {\n const results = [];\n const _traversal = (node) => {\n results.push(node.value);\n if (node.left) _traversal(node.left);\n if (node.right) _traversal(node.right);\n };\n _traversal(this.root);\n return results;\n }", "function inOrderTraversal(node) {\n if (node !== null) {\n inOrderTraversal(node.left);\n console.log(node.val);\n inOrderTraversal(node.right);\n }\n}", "inorder(node){\n if(node !== null){\n this.inorder(node.left);\n console.log(node.data);\n this.inorder(node.right);\n }\n }", "function traverse(root) {}", "inorderTraversal(node = this.root) {\n if (node === null)\n return;\n\n this.inorderTraversal(node.left);\n console.log(node.data);\n this.inorderTraversal(node.right);\n }", "function inorder(node){\n if(!_.isNull(node.left)) inorder(node.left)\n trav.push({\"key\": node.key, \"value\": node.value, \"children\": [_.get(node, \"left.value\", \"null\"), _.get(node, \"right.value\", \"null\")]})\n if(!_.isNull(node.right)) inorder(node.right)\n}", "breathFirstTraversalHelper(root) {\n // Vinicio - This is a pseudocode help for your homework\n // const queue = ....; --> BFT\n // const stack = ...; --> DFT\n // while the queue is not empty\n // dequeue one element\n // enqueue all its children into queue\n // print/visit the node you just dequeued\n }", "dfsPreOrder() {\n let result = [];\n\n const traverse = node => {\n result.push(node.data);\n if (node.left) {\n traverse(node.left)\n }\n if (node.right) {\n traverse(node.right)\n }\n }\n traverse(this.root);\n\n return result;\n }", "function preOrder(root) {\n console.log(root.data) \n root.left && preOrder(root.left) \n root.right && preOrder(root.right) \n }", "inorder(node) {\n if (node !== null) {\n this.inorder(node.left);\n console.log(node.data);\n this.inorder(node.right);\n }\n }", "inorder(node) {\n if (node !== null) {\n this.inorder(node.left);\n console.log(node.data);\n this.inorder(node.right);\n }\n }", "function preOrder_iterative(tree, index) {\n \n var stack = [];\n \n while (stack.length > 0 || !isUndefined(tree[index])) {\n if (!isUndefined(tree[index])) {\n console.log(tree[index]);\n \n var rightNode = right(index);\n \n if (!isUndefined(tree[rightNode])) {\n stack.push(rightNode);\n }\n \n index = left(index);\n } else {\n index = stack.pop();\n }\n }\n}", "function preorder(node){\n trav.push({\"key\": node.key, \"value\": node.value, \"children\": [_.get(node, \"left.value\", \"null\"), _.get(node, \"right.value\", \"null\")]})\n if(!_.isNull(node.left)) preorder(node.left)\n if(!_.isNull(node.right)) preorder(node.right)\n}", "dfsInOrder() {\n let result = [];\n\n function traverse(node, arr) {\n if (node.left) traverse(node.left);\n arr.push(node);\n if (node.right) traverse(node.right);\n }\n traverse(this.root, result);\n return result;\n }", "function walk(nodes) {\n for(var i = 0;i < nodes.length;i++) {\n\n // can't rely on crawl item depth property\n nodes[i].depth = depth; \n\n printer.item(nodes[i]);\n\n if(nodes[i].nodes && nodes[i].nodes.length) {\n\n if(typeof printer.enter === 'function') {\n printer.enter(nodes[i]);\n }\n\n walk(nodes[i].nodes, ++depth); \n\n if(typeof printer.exit === 'function') {\n printer.exit(nodes[i]);\n }\n }\n } \n depth--;\n }", "function preorder(root){\r\n if (!root) return;\r\n\r\n console.log(root.val);\r\n preorder(root.left);\r\n preorder(root.right);\r\n // F, B, A, D, C, E, G, I, H\r\n}" ]
[ "0.8691974", "0.79807144", "0.7973612", "0.7918904", "0.77977616", "0.7781324", "0.7632293", "0.7402599", "0.7381848", "0.7354399", "0.7346977", "0.7333587", "0.7315197", "0.71389705", "0.71344286", "0.7118694", "0.71151143", "0.7083866", "0.7041777", "0.701417", "0.69705826", "0.6960763", "0.6959966", "0.69326085", "0.69175214", "0.69072556", "0.689673", "0.6878804", "0.6850404", "0.68488294", "0.6825652", "0.68057024", "0.6803371", "0.67965776", "0.6762563", "0.67269295", "0.6715831", "0.6696609", "0.66834027", "0.66646624", "0.66604763", "0.6655699", "0.6632849", "0.66322535", "0.662981", "0.66175604", "0.6601821", "0.6448328", "0.62512493", "0.6219926", "0.6215965", "0.6215641", "0.61749244", "0.61485064", "0.6147512", "0.6121286", "0.6107278", "0.60949725", "0.609374", "0.60896593", "0.60734785", "0.60645604", "0.6064405", "0.6048885", "0.6036018", "0.60333437", "0.6027056", "0.60134965", "0.59927803", "0.5980838", "0.5969729", "0.596948", "0.59369826", "0.59329045", "0.59173936", "0.5893586", "0.5889537", "0.5889359", "0.5860173", "0.5859506", "0.5857697", "0.584986", "0.5810692", "0.58070487", "0.58020526", "0.5796191", "0.5788234", "0.57868505", "0.57566935", "0.5756261", "0.57529354", "0.57447237", "0.5729572", "0.57229096", "0.5722527", "0.5722527", "0.57185584", "0.57113993", "0.5710266", "0.57043815", "0.56969446" ]
0.0
-1
level order traversal of nodes
animateLevelorderNodes() { let queue = []; let nodeQueue = []; let animations = []; animations.push(new Animation("display", "Traversing Levelorder", "")); nodeQueue.push(this.root); while (nodeQueue.length !== 0) { const node = nodeQueue.shift(); if (node === null) continue; queue.push(node); // insert animations if (this.root && !node.isEqual(this.root)) animations.push(new Animation("line", node.key, "line-highlighted")); animations.push(new Animation("node", node.key, "found-node")); nodeQueue.push(node.left); nodeQueue.push(node.right); } animations.push(new Animation("display", "Finished Traversing", "")); return [queue, animations]; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "levelOrderSearch(node) {\n if (node === null) {\n return;\n }\n\n let discoveredNodes = [];\n discoveredNodes.push(node);\n\n while(discoveredNodes.length > 0) {\n let currentNode = discoveredNodes[0];\n console.log(currentNode.data);\n\n if (currentNode.leftChild !== null) {\n discoveredNodes.push(currentNode.leftChild);\n }\n if (currentNode.rightChild !== null) {\n discoveredNodes.push(currentNode.rightChild);\n }\n\n discoveredNodes.shift();\n }\n }", "function levelOrderTraversal(node) {\n let queue = [];\n let res = [];\n\n if (node) queue.push(node);\n\n while (queue.length) {\n node = queue.shift();\n\n res.push(node.val);\n\n if (node.left) queue.push(node.left);\n if (node.right) queue.push(node.right);\n }\n\n return res;\n}", "print_level_order() {\n console.log(\"Level order traversal using 'next' pointer: \");\n let nextLevelRoot = this;\n while (nextLevelRoot !== null) {\n let current = nextLevelRoot;\n nextLevelRoot = null;\n while (current != null) {\n console.log(`${current.val} `);\n if(current.next) {\n console.log(`next ${current.next.val}`)\n }\n if (nextLevelRoot === null) {\n if (current.left !== null) {\n nextLevelRoot = current.left;\n } else if (current.right !== null) {\n nextLevelRoot = current.right;\n }\n }\n current = current.next;\n }\n console.log();\n }\n }", "function inOrderTraversal(node) {}", "levelOrder() {\n let result = [];\n let Q = []; \n if (this.root != null) {\n Q.push(this.root);\n while(Q.length > 0) {\n let node = Q.shift();\n result.push(node.data);\n if (node.left != null) {\n Q.push(node.left);\n };\n if (node.right != null) {\n Q.push(node.right);\n };\n };\n return result;\n } else {\n return null;\n };\n }", "levelOrderTraversal() {\n\n if (!this.root || this.root === null) {\n return [];\n } \n\n let queue = new Queue();\n let visited = [];\n\n queue.enqueue(this.root);\n\n while (!queue.isEmpty()) {\n\n let topNode = queue.dequeue();\n\n visited.push(topNode.value);\n\n if (topNode.left !== null) {\n queue.enqueue(topNode.left);\n }\n\n if (topNode.right !== null) {\n queue.enqueue(topNode.right);\n }\n }\n\n return visited;\n }", "print_level_order() {\n console.log(\"Level order traversal using 'next' pointer: \");\n let nextLevelRoot = this;\n while (nextLevelRoot !== null) {\n let current = nextLevelRoot;\n nextLevelRoot = null;\n while (current != null) {\n process.stdout.write(`${current.val} `);\n if (nextLevelRoot === null) {\n if (current.left !== null) {\n nextLevelRoot = current.left;\n } else if (current.right !== null) {\n nextLevelRoot = current.right;\n }\n }\n current = current.next;\n }\n console.log();\n }\n }", "function levelOrder(node) {\n if (!node) return [];\n let queue = [[node, 0]];\n let values = [];\n\n while (queue.length > 0) {\n parseNode(queue.shift(), queue, values);\n }\n\n return values;\n}", "function traverse(root) {}", "*levels(root, path) {\n var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};\n\n for (var p of Path.levels(path, options)) {\n var n = Node.get(root, p);\n yield [n, p];\n }\n }", "*levels(root, path) {\n var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};\n\n for (var p of Path.levels(path, options)) {\n var n = Node.get(root, p);\n yield [n, p];\n }\n }", "function traversePreOrder(node) {\n console.log(node.value);\n if (node.left) {\n traversePreOrder(node.left);\n }\n if (node.right) {\n traversePreOrder(node.right);\n }\n}", "function inOrderTraversal(node) {\n if (node !== null) {\n inOrderTraversal(node.left);\n console.log(node.val);\n inOrderTraversal(node.right);\n }\n}", "levelTraversal () {\n let elements = [];\n let agenda = [this];\n while(agenda.length > 0) {\n let curElem = agenda.shift();\n if(curElem.height == 0) continue;\n elements.push(curElem);\n agenda.push(curElem.left);\n agenda.push(curElem.right);\n }\n return elements;\n }", "function printLevelOrder(root)\n{\n // Base Case\n if (root == null) return;\n \n // Create an empty queue for level order tarversal\n var q = [];\n \n // Enqueue Root and initialize height\n q.push(root);\n \n while (q.length)\n {\n // Print front of queue and remove it from queue\n var node = q.shift();\n console.log(node.data);\n \n \n /* Enqueue left child */\n if (node.left != null)\n q.push(node.left);\n \n /*Enqueue right child */\n if (node.right != null)\n q.push(node.right);\n }\n}", "function preOrderTraversal(node) {}", "function _printTreeLevelNodesWithNext(root) {\n let levelStart = root;\n while (levelStart) {\n const levelValues = [];\n let current = levelStart;\n levelStart = null;\n while (current) {\n levelValues.push(current.val);\n if (!levelStart) {\n levelStart = current.left || current.right;\n }\n current = current.next;\n }\n console.log(levelValues);\n }\n}", "function nodesAtLevels() {\n let x = createVector(WIDTH / 2, HEIGHT);\n let y = createVector(WIDTH / 2, HEIGHT - LENGTH);\n let root = new Branch(x, y, BRANCH_ANGLE, LENGTH_FACTOR);\n\n let byLevel = [];\n byLevel.push([root]);\n\n for (let i = 1; i < LEVELS; i++) {\n let prev = byLevel[i - 1];\n let curr = [];\n prev.forEach(b => {\n let t = b.branch();\n curr = curr.concat(t);\n })\n byLevel.push(curr);\n }\n return byLevel;\n}", "function walk(nodes) {\n for(var i = 0;i < nodes.length;i++) {\n\n // can't rely on crawl item depth property\n nodes[i].depth = depth; \n\n printer.item(nodes[i]);\n\n if(nodes[i].nodes && nodes[i].nodes.length) {\n\n if(typeof printer.enter === 'function') {\n printer.enter(nodes[i]);\n }\n\n walk(nodes[i].nodes, ++depth); \n\n if(typeof printer.exit === 'function') {\n printer.exit(nodes[i]);\n }\n }\n } \n depth--;\n }", "dfsPreOrder() {\n let result = []\n const traverse = (node) => {\n // capture root node value\n result.push(node.value);\n // if left exists, go left again\n if (node.left) {\n traverse(node.left);\n } \n // if right child exists, go right again\n if (node.right) { \n traverse(node.right);\n }\n }\n traverse(this.root);\n return result;\n }", "function preOrderTraversal(node){\n console.log(node.key)\n \n if(node.left) {\n preOrderTraversal(node.left);\n }\n if(node.right){\n preOrderTraversal(node.right);\n }\n }", "function traverse(node, func) {\n\tfunc(node);//1\n\tfor (var key in node) { //2\n\t\tif (node.hasOwnProperty(key)) { //3\n\t\t\tvar child = node[key];\n\t\t\tif (typeof child === 'object' && child !== null) { //4\n\n\t\t\t\tif (Array.isArray(child)) {\n\t\t\t\t\tchild.forEach(function (node) { //5\n\t\t\t\t\t\ttraverse(node, func);\n\t\t\t\t\t});\n\t\t\t\t} else {\n\t\t\t\t\ttraverse(child, func); //6\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}", "function traverse(nodes) {\n for (var i = 0, l = nodes.length; i < l; i++) {\n var node = nodes[i];\n if (node.isSelected()) {\n result.push(node);\n }\n else {\n // if not selected, then if it's a group, and the group\n // has children, continue to search for selections\n if (node.group && node.children) {\n traverse(node.children);\n }\n }\n }\n }", "function traverse(nodes) {\n for (var i = 0, l = nodes.length; i < l; i++) {\n var node = nodes[i];\n if (node.isSelected()) {\n result.push(node);\n }\n else {\n // if not selected, then if it's a group, and the group\n // has children, continue to search for selections\n if (node.group && node.children) {\n traverse(node.children);\n }\n }\n }\n }", "function traverse(nodes) {\n for (var i = 0, l = nodes.length; i < l; i++) {\n var node = nodes[i];\n if (node.isSelected()) {\n result.push(node);\n }\n else {\n // if not selected, then if it's a group, and the group\n // has children, continue to search for selections\n if (node.group && node.children) {\n traverse(node.children);\n }\n }\n }\n }", "function traverse(nodes) {\n for (var i = 0, l = nodes.length; i < l; i++) {\n var node = nodes[i];\n if (node.isSelected()) {\n result.push(node);\n }\n else {\n // if not selected, then if it's a group, and the group\n // has children, continue to search for selections\n if (node.group && node.children) {\n traverse(node.children);\n }\n }\n }\n }", "function traverse(nodes) {\n for (var i = 0, l = nodes.length; i < l; i++) {\n var node = nodes[i];\n if (node.isSelected()) {\n result.push(node);\n }\n else {\n // if not selected, then if it's a group, and the group\n // has children, continue to search for selections\n if (node.group && node.children) {\n traverse(node.children);\n }\n }\n }\n }", "preOrder() { //DLR\n let results = [];\n\n let _walk = node => {\n results.push(node.value); //executing code\n if(node.left) _walk(node.left); //go left - if node,left is null, we are at a leaf - traversing\n if(node.right) _walk(node.right); // go right - if node.right=null then we are at a leaf - traversing\n };\n console.log(_walk(this.root));\n _walk(this.root); // for whiteboard use ll.root instead of this.root, unless using a class constructor\n return results;\n }", "function inOrderTraverse(tree) {\n let arr = [];\n inOrderTraverseHelper(tree, arr);\n return arr;\n}", "inOrder(node) {\n if (node != null) {\n this.inOrder(node.left);\n console.log(node.data);\n this.inOrder(node.right);\n }\n }", "inorderTraverse() {\n let data = [];\n function traverse(node) {\n if(node.left != null) {\n traverse(node.left);\n }\n data.push(node.data);\n if(node.left != null) {\n traverse(node.left);\n }\n }\n traverse(this.root);\n return data;\n }", "function walkTree(root, path) {\n let node = root\n path.forEach(function(d) {\n // handle traversing an array, need to parse index into an int\n if (Array.isArray(node)) {\n const ix = parseInt(d, 10)\n if (Number.isNaN(ix)) {\n console.log(`Array index '${d}' in '${path}' is not an int`)\n return undefined\n } else if (ix < 0 || ix >= node.length) {\n console.log(`Array index '${d}' in '${path}' > ${node.length}`)\n return undefined\n }\n node = node[ix]\n } else if (typeof node === 'object') {\n if (!(d in node)) Vue.$set(node, d, {}) // allow new subtrees to be created\n node = node[d]\n } else {\n console.log(`Level '${d}' of '${path}'' is not traversable: ${typeof node[d]}`)\n return undefined\n }\n })\n return node\n}", "inOrder() {\n let results = [];\n\n let _walk = node => {\n if (node.left) _walk(node.left);\n results.push(node.value);\n if (node.right) _walk(node.right);\n };\n _walk(this.root);\n\n return results;\n }", "traverse(method) {\n inOrder(this.root);\n // Helper method for traversing the nodes in order\n function inOrder(currentNode) {\n if(currentNode.left) {\n inOrder(currentNode.left);\n }\n method.call(this, currentNode);\n if(currentNode.right) {\n inOrder(currentNode.right);\n }\n }\n }", "inorderTraversal(node = this.root) {\n if (node === null)\n return;\n\n this.inorderTraversal(node.left);\n console.log(node.data);\n this.inorderTraversal(node.right);\n }", "inorder(node){\n if(node !== null){\n this.inorder(node.left);\n console.log(node.data);\n this.inorder(node.right);\n }\n }", "inOrder() {\n const results = [];\n const _traversal = (node) => {\n if (node.left) _traversal(node.left);\n results.push(node.value);\n if (node.right) _traversal(node.right);\n };\n _traversal(this.root);\n return results;\n }", "dfsInOrder(){\n let result = []\n\n const traverse = node => {\n //if left node exists, go left again//\n if(node.left) traverse(node.left)\n //capture root node value//\n result.push(node.value)\n //if right node exists, go right again//\n if(node.right) traverse(node.right)\n }\n\n traverse(this.root)\n console.log(`DFS In Order: ${result}`)\n }", "function traverseTree(treeNode) {\n function loop(node, result) {\n if (node.url) {\n result.push(node);\n } else if (node.children) {\n for (var i = 0; i < node.children.length; i++) {\n var item = node.children[i];\n loop(item, result);\n }\n }\n return result;\n }\n\n return loop(treeNode, []);\n}", "function traverse(root, currLvl) {\n if (root === null) { return []; }\n else {\n \n //if the currLvl is done processing all the nodes for that lvl, start a new array for that lvl\n if (currLvl >= result.length) {\n result[currLvl] = [];\n }\n\n result[currLvl].push(root.val); //push the current value into the currLvl \n //if the current Node has a children left and right, move in the next lvl\n traverse(root.left, currLvl + 1);\n traverse(root.right, currLvl + 1);\n }\n }", "function preOrderTraversal(node) {\n if (node !== null) {\n console.log(node.val);\n preOrderTraversal(node.left);\n preOrderTraversal(node.right);\n }\n}", "function bfs(node) {\n let q = [];\n let level = 0;\n q.push(node);\n\n while (q.length > 0) {\n let cur = q.shift();\n console.log(cur.data);\n if (cur.left !== null || cur.right !== null) {\n level++;\n if (cur.left !== null) {\n q.push(cur.left);\n }\n if (cur.right !== null) {\n q.push(cur.right);\n }\n }\n }\n\n console.log(level);\n}", "traverse(fn) {\n fn(this)\n\n const children = this._children\n for (let i = 0, l = children.length; i < l; i++) {\n children[i].traverse(fn)\n }\n }", "function postOrderTraversal(node) {}", "dfsPreOrder(){\n let result = []\n\n const traverse = node => {\n //capture root node value//\n result.push(node.value)\n //if left node exists, go left again//\n if(node.left) traverse(node.left)\n //if right node exists, go right again//\n if(node.right) traverse(node.right)\n }\n\n traverse(this.root)\n console.log(`DFS Pre Order: ${result}`)\n }", "inorder(node) {\n if (node !== null) {\n this.inorder(node.left);\n console.log(node.data);\n this.inorder(node.right);\n }\n }", "inorder(node) {\n if (node !== null) {\n this.inorder(node.left);\n console.log(node.data);\n this.inorder(node.right);\n }\n }", "*nodes(root) {\n var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n var {\n pass,\n reverse = false\n } = options;\n var {\n from = [],\n to\n } = options;\n var visited = new Set();\n var p = [];\n var n = root;\n\n while (true) {\n if (to && (reverse ? Path.isBefore(p, to) : Path.isAfter(p, to))) {\n break;\n }\n\n if (!visited.has(n)) {\n yield [n, p];\n } // If we're allowed to go downward and we haven't descended yet, do.\n\n\n if (!visited.has(n) && !Text.isText(n) && n.children.length !== 0 && (pass == null || pass([n, p]) === false)) {\n visited.add(n);\n var nextIndex = reverse ? n.children.length - 1 : 0;\n\n if (Path.isAncestor(p, from)) {\n nextIndex = from[p.length];\n }\n\n p = p.concat(nextIndex);\n n = Node.get(root, p);\n continue;\n } // If we're at the root and we can't go down, we're done.\n\n\n if (p.length === 0) {\n break;\n } // If we're going forward...\n\n\n if (!reverse) {\n var newPath = Path.next(p);\n\n if (Node.has(root, newPath)) {\n p = newPath;\n n = Node.get(root, p);\n continue;\n }\n } // If we're going backward...\n\n\n if (reverse && p[p.length - 1] !== 0) {\n var _newPath = Path.previous(p);\n\n p = _newPath;\n n = Node.get(root, p);\n continue;\n } // Otherwise we're going upward...\n\n\n p = Path.parent(p);\n n = Node.get(root, p);\n visited.add(n);\n }\n }", "function inOrderTraverse(tree, array) {\n // Write your code here.\n\tif (tree !== null){\n\t\tinOrderTraverse(tree.left, array);\n\t\tarray.push(tree.value);\n\t\tinOrderTraverse(tree.right, array);\n\t}\n\n\treturn array;\n}", "function traverse(indent, node) {\n log.add(Array(indent++).join(\"--\") + node.name);\n\n for (let i = 0, len = node.children.length; i < len; i++) {\n traverse(indent, node.getChild(i));\n }\n}", "function fnTraversal(root, node, preorder, postorder) {\n\t\tnode.childnodes.forEach((child, i) => { //iterate over next deep level\n\t\t\tpreorder(root, node, child, i) && fnTraversal(root, child, preorder, postorder); //preorder = cut/poda\n\t\t\tpostorder(root, node, child, i);\n\t\t});\n\t\treturn self;\n\t}", "*nodes(root) {\n var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n var {\n pass,\n reverse = false\n } = options;\n var {\n from = [],\n to\n } = options;\n var visited = new Set();\n var p = [];\n var n = root;\n\n while (true) {\n if (to && (reverse ? Path.isBefore(p, to) : Path.isAfter(p, to))) {\n break;\n }\n\n if (!visited.has(n)) {\n yield [n, p];\n } // If we're allowed to go downward and we haven't decsended yet, do.\n\n\n if (!visited.has(n) && !Text.isText(n) && n.children.length !== 0 && (pass == null || pass([n, p]) === false)) {\n visited.add(n);\n var nextIndex = reverse ? n.children.length - 1 : 0;\n\n if (Path.isAncestor(p, from)) {\n nextIndex = from[p.length];\n }\n\n p = p.concat(nextIndex);\n n = Node.get(root, p);\n continue;\n } // If we're at the root and we can't go down, we're done.\n\n\n if (p.length === 0) {\n break;\n } // If we're going forward...\n\n\n if (!reverse) {\n var newPath = Path.next(p);\n\n if (Node.has(root, newPath)) {\n p = newPath;\n n = Node.get(root, p);\n continue;\n }\n } // If we're going backward...\n\n\n if (reverse && p[p.length - 1] !== 0) {\n var _newPath = Path.previous(p);\n\n p = _newPath;\n n = Node.get(root, p);\n continue;\n } // Otherwise we're going upward...\n\n\n p = Path.parent(p);\n n = Node.get(root, p);\n visited.add(n);\n }\n }", "DFSInOrdert() {\r\n\t\treturn this.traverseInOrder(this.root, []);\r\n\t}", "function inOrder(tree) {\n if (!tree.value) {\n return \"not found\"\n\n }\n tree.left && inOrder(tree.left)\n console.log(tree.value)\n\n tree.right && inOrder(tree.right)\n\n\n}", "depthFirstForEach(cb) {\n // const traversePreOrder = (node) => {\n // cb(node.value); // Call the Callback on the First item and every item after that!\n // if (node.left) { // If there is a left node, then go left!\n // traversePreOrder(node.left); // Recursive call until there is no more left nodes!\n // }\n // if (node.right) { // If there is a right node, then go right!\n // traversePreOrder(node.right); // Recursive call until there is no more right nodes!\n // }\n // };\n // traversePreOrder(this); // Execute traversePreOrder on the tree!\n cb(this.value);\n if (this.left !== null) this.left.depthFirstForEach(cb);\n if (this.right !== null) this.right.depthFirstForEach(cb);\n }", "preOrder() {\n const results = [];\n const _traversal = (node) => {\n results.push(node.value);\n if (node.left) _traversal(node.left);\n if (node.right) _traversal(node.right);\n };\n _traversal(this.root);\n return results;\n }", "function walk(node) {\n console.log(node.nodeName);\n for (var i = 0; i < node.childNodes.length; i++) {\n walk(node.childNodes[i]);\n }\n}", "function walk_list(ul, level)\n {\n var result = [];\n ul.children('li').each(function(i,e){\n var state, li = $(e), sublist = li.children('ul');\n var node = {\n id: dom2id(li),\n classes: String(li.attr('class')).split(' '),\n virtual: li.hasClass('virtual'),\n level: level,\n html: li.children().first().get(0).outerHTML,\n text: li.children().first().text(),\n children: walk_list(sublist, level+1)\n }\n\n if (sublist.length) {\n node.childlistclass = sublist.attr('class');\n }\n if (node.children.length) {\n if (node.collapsed === undefined)\n node.collapsed = sublist.css('display') == 'none';\n\n // apply saved state\n state = get_state(node.id, node.collapsed);\n if (state !== undefined) {\n node.collapsed = state;\n sublist[(state?'hide':'show')]();\n }\n\n if (!li.children('div.treetoggle').length)\n $('<div class=\"treetoggle '+(node.collapsed ? 'collapsed' : 'expanded') + '\">&nbsp;</div>').appendTo(li);\n\n li.attr('aria-expanded', node.collapsed ? 'false' : 'true');\n }\n if (li.hasClass('selected')) {\n li.attr('aria-selected', 'true');\n selection = node.id;\n }\n\n li.data('id', node.id);\n\n // declare list item as treeitem\n li.attr('role', 'treeitem').attr('aria-level', node.level+1);\n\n // allow virtual nodes to receive focus\n if (node.virtual) {\n li.children('a:first').attr('tabindex', '0');\n }\n\n result.push(node);\n indexbyid[node.id] = node;\n });\n\n ul.attr('role', level == 0 ? 'tree' : 'group');\n\n return result;\n }", "dfsPreOrder() {\n let result = [];\n function traverse(node, arr) {\n arr.push(node);\n if (node.left) traverse(node.left);\n if (node.right) traverse(node.right);\n }\n traverse(this.root, result);\n return result;\n }", "_traverse(n, state, f) {\n var content = \"\";\n\n if (TreeTransformer.isNode(n)) {\n // If we were called on a node object, then we handle it\n // this way.\n var node = n; // safe cast; we just tested\n // Put the node on the stack before recursing on its children\n\n state._containers.push(node);\n\n state._ancestors.push(node); // Record the node's text content if it has any.\n // Usually this is for nodes with a type property of \"text\",\n // but other nodes types like \"math\" may also have content.\n\n\n if (typeof node.content === \"string\") {\n content = node.content;\n } // Recurse on the node. If there was content above, then there\n // probably won't be any children to recurse on, but we check\n // anyway.\n //\n // If we wanted to make the traversal completely specific to the\n // actual Perseus parse trees that we'll be dealing with we could\n // put a switch statement here to dispatch on the node type\n // property with specific recursion steps for each known type of\n // node.\n\n\n var keys = Object.keys(node);\n keys.forEach(key => {\n // Never recurse on the type property\n if (key === \"type\") {\n return;\n } // Ignore properties that are null or primitive and only\n // recurse on objects and arrays. Note that we don't do a\n // isNode() check here. That is done in the recursive call to\n // _traverse(). Note that the recursive call on each child\n // returns the text content of the child and we add that\n // content to the content for this node. Also note that we\n // push the name of the property we're recursing over onto a\n // TraversalState stack.\n\n\n var value = node[key];\n\n if (value && typeof value === \"object\") {\n state._indexes.push(key);\n\n content += this._traverse(value, state, f);\n\n state._indexes.pop();\n }\n }); // Restore the stacks after recursing on the children\n\n state._currentNode = state._ancestors.pop();\n\n state._containers.pop(); // And finally call the traversal callback for this node. Note\n // that this is post-order traversal. We call the callback on the\n // way back up the tree, not on the way down. That way we already\n // know all the content contained within the node.\n\n\n f(node, state, content);\n } else if (Array.isArray(n)) {\n // If we were called on an array instead of a node, then\n // this is the code we use to recurse.\n var nodes = n; // Push the array onto the stack. This will allow the\n // TraversalState object to locate siblings of this node.\n\n state._containers.push(nodes); // Now loop through this array and recurse on each element in it.\n // Before recursing on an element, we push its array index on a\n // TraversalState stack so that the TraversalState sibling methods\n // can work. Note that TraversalState methods can alter the length\n // of the array, and change the index of the current node, so we\n // are careful here to test the array length on each iteration and\n // to reset the index when we pop the stack. Also note that we\n // concatentate the text content of the children.\n\n\n var index = 0;\n\n while (index < nodes.length) {\n state._indexes.push(index);\n\n content += this._traverse(nodes[index], state, f); // Casting to convince Flow that this is a number\n\n index = state._indexes.pop() + 1;\n } // Pop the array off the stack. Note, however, that we do not call\n // the traversal callback on the array. That function is only\n // called for nodes, not arrays of nodes.\n\n\n state._containers.pop();\n } // The _traverse() method always returns the text content of\n // this node and its children. This is the one piece of state that\n // is not tracked in the TraversalState object.\n\n\n return content;\n }", "inOrder() {\n const arr = [];\n\n const inOrder = (node) => {\n\n if (node.left) {\n inOrder(node.left);\n }\n\n arr.push(node.value);\n\n if (node.right) {\n inOrder(node.right);\n }\n };\n\n let current = this.root;\n inOrder(current);\n\n return arr;\n }", "assignLevel(node, level) {\n\t\tnode.level = level;\n\t\tfor(var i in node.children){\n\t\t\tthis.assignLevel(node.children[i], level+1);\n\t\t}\n\t}", "function traverse(node) {\n // push the value of the node to the variable that stores the values\n result.push(node.value);\n // if the node has a left property, call the helper function with the left property on the node\n if (node.left) traverse(node.left);\n // if the node has a right property, call the helper function with the right property on the node\n if (node.right) traverse(node.right);\n }", "function reverse_level_order_traversal(root) {\n const queue = [];\n queue.push(root);\n const stack = [];\n let currentLevelNodes = [];\n let totalNodesAtCurrentLevel = 1;\n let totalNodesAtNextLevel = 0;\n while (queue.length) {\n const current = queue.shift();\n currentLevelNodes.push(current.data);\n totalNodesAtCurrentLevel--;\n if (current.left) {\n queue.push(current.left);\n totalNodesAtNextLevel++;\n }\n if (current.right) {\n queue.push(current.right);\n totalNodesAtNextLevel++;\n }\n if (totalNodesAtCurrentLevel === 0) {\n totalNodesAtCurrentLevel = totalNodesAtNextLevel;\n totalNodesAtNextLevel = 0;\n stack.push(currentLevelNodes);\n currentLevelNodes = [];\n }\n }\n\n while (stack.length) {\n process.stdout.write(`${stack.pop().join(' ')} `);\n }\n console.log('\\n');\n}", "preOrder(){\n let results = [];\n\n let _walk = node => {\n results.push(node.value); // root\n if(node.left) _walk(node.left); // left\n if(node.right) _walk(node.right); // right \n };\n\n _walk(this.root);\n\n return results;\n }", "dfsInOrder() {\n let result = [];\n const traverse = (node) => {\n // if left exists, go left again\n if (node.left) {\n traverse(node.left);\n } \n // capture root node value\n result.push(node.value);\n // if right child exists, go right again\n if (node.right) { \n traverse(node.right);\n }\n }\n traverse(this.root);\n return result;\n }", "function traverse(node) {\n // if the node has a left property, call the helper function with the left property on the node\n if (node.left) traverse(node.left);\n // if the node has a right property, call the helper function with the right property on the node\n if (node.right) traverse(node.right);\n // push the value of the node to the variable that stores the values\n result.push(node.value);\n }", "function inorder(node){\n if(!_.isNull(node.left)) inorder(node.left)\n trav.push({\"key\": node.key, \"value\": node.value, \"children\": [_.get(node, \"left.value\", \"null\"), _.get(node, \"right.value\", \"null\")]})\n if(!_.isNull(node.right)) inorder(node.right)\n}", "function postOrderTraversal(node) {\n if (node !== null) {\n postOrderTraversal(node.left);\n postOrderTraversal(node.right);\n console.log(node.val);\n }\n}", "inorder(node) {\n if (node !== null) {\n this.inorder(node.left);\n console.log(node.data);\n this.inorder(node.right);\n }\n }", "inorder(node) {\n if (node !== null) {\n this.inorder(node.left);\n console.log(node.data);\n this.inorder(node.right);\n }\n }", "inorder(node) {\n if (node !== null) {\n this.inorder(node.left);\n console.log(node.data);\n this.inorder(node.right);\n }\n }", "DFSPostOrder() {\n let data = [];\n let current = this.root;\n\n function traverse(node) {\n if (node.left) traverse(node.left)\n if (node.right) traverse(node.right)\n data.push(node.value)\n }\n\n traverse(current);\n console.log(data);\n return data;\n }", "function traverseNodes(node) {\n if (node.value) {\n cb(node.value);\n }\n if (node.left) {\n traverseNodes(node.left);\n }\n if (node.right) {\n traverseNodes(node.right);\n }\n }", "inOrderTraversal(node, callback) {\n if (node !== null) {\n this.inOrderTraversal(node.left, callback);\n callback(node.key); // append via callback\n this.inOrderTraversal(node.right, callback);\n }\n }", "function inOrder(root){\n if (!root){\n return;\n }\n if (root){\n inOrder(root.left);\n console.log(root.value);\n inOrder(root.right);\n }\n}", "DFSPreOrder(){\n var data = [],\n current = this.root\n \n function traverse(node) {\n data.push(node.value)\n if (node.left) traverse(node.left)\n if (node.right) traverse(node.right)\n }\n traverse(current)\n return data\n }", "DFSPreOrder() {\n let data = [];\n let current = this.root;\n\n function traverse(node) {\n data.push(node.value);\n if (node.left) traverse(node.left);\n if (node.right) traverse(node.right);\n }\n traverse(current)\n console.log(data)\n return data;\n }", "function perLevel (root){\n var result = [];\n var queue = [];\n queue.push(root);\n queue.push(null);\n var i = 0;\n while (i< queue.length){\n var curr = queue[i];\n if(curr === null){\n if(i<queue.length-1){\n queue.push(null);\n }\n console.log(result);\n result = [];\n i++;\n continue;\n }\n if(curr.left !== null){\n var left = curr.left;\n queue.push(left);\n }\n if(curr.right !== null){\n var right = curr.right;\n queue.push(right);\n }\n result.push(curr.value);\n i++;\n }\n return result;\n}", "function walkTree(order, level, index, node, callback, customData = null) {\n\tif (no(customData)) {\n\t\tcustomData = {};\n\t}\n\tlet data = {\n\t\tlevel: level,\n\t\tindex: index,\n\t\tnode: node,\n\t\thasChildren: node.children.length > 0,\n\t\tmessage: \"\",\n\t};\n\tif (order.toLowerCase() == \"preorder\") {\n\t\tcallback(data, customData);\n\t}\n\t/*\n\tlet s = \"\";\n\tnode.children.forEach(kid => s = `${s} ${kid.meaningfulName}`);\n\tconsole.log(`DEBUG walkTree ${node.apiData.name}:${s}`);\n\t*/\n\tfor (let i = 0; i < node.children.length; i++) {\n\t\tlet child = node.children[i];\n\t\twalkTree(order, level + 1, i + 1, child, callback, customData);\n\t}\n\tif (order.toLowerCase() == \"postorder\") {\n\t\tcallback(data, customData);\n\t}\n}", "inOrder() {\n const results = [];\n const _traverse = (node) => {\n if (node.left) _traverse(node.left);\n results.push(node.value);\n if (node.right) _traverse(node.right);\n };\n\n _traverse(this.root);\n return results;\n }", "inOrderTraversal() {\n let visited = [];\n\n function inOrder(node) {\n if (node !== null) {\n if (node.left !== null) inOrder(node.left);\n visited.push(node.value);\n if (node.right !== null) inOrder(node.right);\n }\n }\n\n inOrder(this.root);\n return visited;\n }", "function in_order(root, nodes) {\n if (root && root.left) {\n in_order(root.left, nodes);\n }\n nodes.push(root.data);\n if (root && root.right) {\n in_order(root.right, nodes)\n }\n return nodes;\n}", "preOrder() {\n let results = [];\n\n let _walk = node => {\n results.push(node.value); //root\n if (node.left) _walk(node.left);\n if (node.right) _walk(node.right);\n };\n _walk(this.root);\n\n return results;\n }", "preTraverseSceneGraph(rootNode, func) {\n func(rootNode);\n if (!this.gameObjects.has(rootNode)) return; //might have been deleted during execution\n\n let nodeQueue = new Set(this.childrenOf(rootNode)); //shallow copy\n for (let child of nodeQueue) {\n this.preTraverseSceneGraph(child, func);\n }\n }", "dfsPreOrder() {\r\n let result = []\r\n\r\n const traverse = node => {\r\n result.push(node.data)\r\n if (node.left) traverse(node.left)\r\n if (node.right) traverse(node.right)\r\n }\r\n\r\n traverse(this.root)\r\n return result\r\n }", "depthFirstForEach(cb) {\n cb(this.value);\n if (this.left) this.left.depthFirstForEach(cb);\n if (this.right) this.right.depthFirstForEach(cb);\n }", "dfsPostOrder() {\n let result = []\n const traverse = (node) => {\n // if left exists, go left again\n if (node.left) {\n traverse(node.left);\n } \n // if right child exists, go right again\n if (node.right) { \n traverse(node.right);\n }\n // capture root node value\n result.push(node.value);\n }\n traverse(this.root);\n return result;\n }", "_traverse(callback) {\n function exec(node) {\n callback(node);\n node.children && node.children.forEach(exec);\n }\n exec(this.root);\n }", "function traverse(node) {\n //If the node has a left property, call the helper function with the left property on the node\n if (node.left) traverse(node.left);\n //Push the value of the node to the variable that stores the values\n visited.push(node.val);\n //If the node has a right property, call the helper function with the left property on the node\n if (node.right) traverse(node.right);\n }", "dfsInOrder() {\n let result = [];\n\n function traverse(node, arr) {\n if (node.left) traverse(node.left);\n arr.push(node);\n if (node.right) traverse(node.right);\n }\n traverse(this.root, result);\n return result;\n }", "depthFirstTraversal(fn) {\n fn(this.value);\n\n if (this.left) {\n this.left.depthFirstTraversal(fn);\n }\n\n if (this.right) {\n this.right.depthFirstTraversal(fn);\n }\n }", "inorder(root) {\n if (root != null) {\n inorder(root.left);\n console.log('Node : ' + root.data + ' , ');\n if (root.parent == null) console.log('Parent : NULL');\n else console.log('Parent : ' + root.parent.data);\n inorder(root.right);\n }\n }", "dfsPostOrder(){\n let result = []\n\n const traverse = node => {\n //if left node exists, go left again//\n if(node.left) traverse(node.left)\n //if right node exists, go right again//\n if(node.right) traverse(node.right)\n //capture root node value//\n result.push(node.value)\n }\n\n traverse(this.root)\n console.log(`DFS Post Order: ${result}`)\n }", "dfsPreOrder() {\n let visitedNodes = [];\n let currentNode = this.root;\n\n function traverse(node){\n visitedNodes.push(node.val);\n node.left && traverse(node.left)\n node.right && traverse(node.right);\n }\n \n traverse(currentNode);\n return visitedNodes;\n }", "traversal () {\n var elements = [];\n if(this.height == 0) return elements;\n elements.push(...this.left.traversal());\n elements.push(this);\n elements.push(...this.right.traversal());\n\n return elements;\n }", "BFSRecursive(levelNodes) {\n\n if (levelNodes.length) {\n\n var data = levelNodes.map(node => node.data);\n\n console.log(data.join(' '));\n\n var newLevelNodes = [];\n\n levelNodes.forEach(function (node) {\n if (node.left != null) newLevelNodes.push(node.left);\n if (node.right != null) newLevelNodes.push(node.right);\n });\n\n this.BFSRecursive(newLevelNodes);\n\n }\n\n }", "dfsInOrder() {\n let visitedNodes = [];\n let currentNode = this.root;\n\n function traverse(node){\n \n node.left && traverse(node.left)\n visitedNodes.push(node.val);\n node.right && traverse(node.right);\n }\n \n traverse(currentNode);\n return visitedNodes;\n }", "function step2(map) {\n\tconst root = { name: '/', nodes: [] };\n\treturn (function next(map, parent, level) {\n\t\tObject.keys(map).forEach(key => {\n\t\t\tlet val = map[key];\n\t\t\tlet node = { name: key };\n\t\t\tif (typeof val === 'object') {\n\t\t\t\tnode.nodes = [];\n\t\t\t\tnode.open = level < 1;\n\t\t\t\tnext(val, node, level + 1);\n\t\t\t} else {\n\t\t\t\tnode.src = val;\n\t\t\t}\n\t\t\tparent.nodes.push(node);\n\t\t});\n\t\treturn parent;\n\t})(map, root, 0);\n}", "function preOrder(root) {\n console.log(root.data) \n root.left && preOrder(root.left) \n root.right && preOrder(root.right) \n }" ]
[ "0.7738875", "0.73244894", "0.7306826", "0.73028904", "0.72906595", "0.72680694", "0.70416194", "0.6918859", "0.6873484", "0.68360394", "0.68360394", "0.68203324", "0.6736197", "0.6723117", "0.6712994", "0.6697749", "0.6534343", "0.65244234", "0.6521104", "0.6489053", "0.64833784", "0.64688987", "0.646548", "0.646548", "0.646548", "0.646548", "0.646548", "0.6463622", "0.64554906", "0.6454772", "0.6418795", "0.6410066", "0.6395189", "0.637411", "0.6372865", "0.6364683", "0.6361502", "0.6355525", "0.63552076", "0.63472444", "0.6311735", "0.6303345", "0.62833357", "0.62826264", "0.6277867", "0.62767565", "0.62767565", "0.6275594", "0.62754655", "0.62725925", "0.62668437", "0.62582034", "0.6247854", "0.6242859", "0.6238425", "0.623569", "0.62306815", "0.6220227", "0.62095976", "0.6208002", "0.6204401", "0.6203659", "0.62013173", "0.62011904", "0.61946535", "0.6188217", "0.61860704", "0.61843157", "0.61823386", "0.61760825", "0.61760825", "0.61760825", "0.617576", "0.6175675", "0.6174896", "0.61639374", "0.6159581", "0.6154902", "0.615287", "0.6147681", "0.61345136", "0.6134194", "0.61151755", "0.61133975", "0.6111843", "0.6103386", "0.6102498", "0.60971284", "0.6093416", "0.6091493", "0.6085523", "0.6079038", "0.60778964", "0.60766095", "0.6075068", "0.60674393", "0.60579604", "0.6056561", "0.60444254", "0.60433465" ]
0.6354307
39
makes a request for JSON, getting back an array of contributors and passes this data to cb, an anonymous callback function that is given
function getRepoContributors(repoOwner, repoName, cb) { var requestURL = 'https://'+ GITHUB_USER + ':' + GITHUB_TOKEN + '@api.github.com/repos/' + repoOwner + '/' + repoName + '/contributors'; console.log(requestURL); var options = { url: requestURL, headers: { 'User-Agent': 'GitHub Avatar Downloader - Student Project' } }; request.get(options, function(err, response) { if (err) { throw err } if (response.statusCode === 200) {; cb(response); } }); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function xhrCallbackContributors(data) {\n //console.log('data from server', data);\n contributors = JSON.parse(data);\n console.log('parsed contributor data:', contributors);\n \n showContributorsInList(contributors);\n}", "fetchContributors() {\n return Util.fetchJSON(this.data.contributors_url);\n }", "function getRepoContributors(repoOwner, repoName, cb) {\n\n var options = {\n url: \"https://api.github.com/repos/\" + repoOwner + \"/\" + repoName + \"/contributors\",\n headers: {\n 'User-Agent': 'request',\n 'Authorization' : 'token ' + token.GITHUB_TOKEN\n }\n };\n // parses the body into a readable JSON format\n request(options, function(err, res, body) {\n var data = JSON.parse(body);\n console.log(typeof(data));\n cb(err, data);\n });\n}", "function getRepoContributors(repoOwner, repoName, cb) {\n var options = {\n url: 'https://'+ GITHUB_USER + ':' + GITHUB_TOKEN + '@api.github.com/repos/' + repoOwner + '/' + repoName + '/contributors',\n headers:{\n 'User-Agent':'request'\n }\n };\n //when you request if the response is good, callback the data in JSON format\n request(options,function(error, response, body){\n if (!error && response.statusCode == 200){\n cb(JSON.parse(body));\n }\n });\n\n}", "async fetchContributors() {\n const response = await fetch(this.repository.contributors_url);\n return response.json();\n }", "function getRepoContributors(repoOwner, repoName, cb) {\n var options = {\n url: \"https://api.github.com/repos/\" + repoOwner + \"/\" + repoName + \"/contributors\",\n headers: {\n 'User-Agent': 'request',\n 'myToken' : 'process.env.KEY'\n }\n };\n\n //converts the requests body and converts to an actual javascript object/array.\n request(options, function(err, res, body) {\n let requested = JSON.parse(body);\n cb(err, requested);\n });\n\n}", "function getRepoContributors(repoOwner, repoName, cb) {\n var options = {\n url: 'https://api.github.com/repos/' + repoOwner + '/' + repoName + '/contributors',\n headers: {\n 'User-Agent': 'request',\n 'Authorization': 'token ' + github.password\n }\n };\n request(options, function(err, res, body) {\n //Get repo contributors and parse JSON string to object\n var result = JSON.parse(body);\n //Pass result into callback function\n cb(err, result);\n });\n}", "function getRepoContributors(repoOwner, repoName, cb) {\n var options = {\n url: \"https://api.github.com/repos/\" + repoOwner + \"/\" + repoName + \"/contributors\",\n headers: {\n 'User-Agent': 'request',\n 'Authorization': process.env.GITHUB_TOKENsec\n }\n };\n request.get(options, function(err, response, body) {\n var contributers = JSON.parse (body);\n console.log(contributers);\n cb(err, contributers)\n });\n}", "function getRepoContributors(repoOwner, repoName, cb) {\n\n var options = {\n url: \"https://api.github.com/repos/\" + repoOwner + \"/\" + repoName + \"/contributors\",\n headers: {\n 'User-Agent': 'request' \n }\n };\n\n request(options, function(err, res, body) {\n cb(err, body);\n });\n\n}", "function getRepoContributors(repoOwner, repoName, cb) {\n\n// if statement to check if user have the required arguments on node\n if(repoOwner && repoName) {\n\n var options = {\n url: \"https://api.github.com/repos/\" + repoOwner + \"/\" + repoName + \"/contributors\",\n headers: {\n 'User-Agent': 'request',\n Authorization: 'token ' + getKey.GITHUB_TOKEN\n }\n };\n request(options, function(err, res, body) {\n cb(err, body);\n });\n\n } else {\n console.log(\"Error: Please add your repoOwner and repoName to node.\");\n }\n\n}", "function getRepoContributors(repoOwner, repoName, cb) {\n// Added logic to enforce command-line arguments. If the two arguments are not passed, then the program fails. Otherwise, it proceeds normally.\n if (!owner || !name) {\n console.log(\"USER ERROR. Please enter two arguments. The first should be the GitHub username of the repo owner, and the second should be the repo name. Please note, the repo must be public.\" + \"\\n\" + \"\\n\");\n }\n else {\n// We need to define our URL in this format, in order to pass 'User-Agent' in the headers.\n var options = {\n url: 'https://' + GITHUB_USER + ':' + GITHUB_TOKEN + '@api.github.com/repos/' + repoOwner + '/' + repoName + '/contributors',\n headers: {\n 'User-Agent': 'GitHub Avatar Downloader - Student Project'\n }\n };\n\n// This is a very simple request that either throws an error or parses the body of the response from our URL. It passes the err and the response to the callback function.\n request(options, function(err, response, body) {\n if (err) throw err;\n cb(err, JSON.parse(response.body));\n });\n }\n}", "function getRepoContributors(repoOwner, repoName, cb) {\n var requestURL = 'https://'+ GITHUB_USER + ':' + GITHUB_TOKEN + '@api.github.com/repos/' + repoOwner + '/' + repoName + '/contributors';\n var requestOptions = {\n url: requestURL,\n headers: {\n 'User-Agent' : 'VidushanK'\n }\n };\n// request options and parse the body and output the avatar_url and invoke DownloadImageByURL function to create the images\n request.get(requestOptions,function(err, result, body){\n\n if (!err && result.statusCode === 200) {\n var parsedData = JSON.parse(body);\n parsedData.forEach(function (releaseObject) {\n var dir = \"./avatars/\"\n var loginFileName = dir + releaseObject.login + \".jpg\";\n console.log(releaseObject.avatar_url);\n downloadImageByURL(releaseObject.avatar_url, loginFileName);\n });\n }\n });\n\n}", "function getRepoContributors(repoOwner, repoName, cb) {\n var options = {\n url: \"https://api.github.com/repos/\" + repoOwner + \"/\" + repoName + \"/contributors\",\n headers: {\n 'User-Agent': 'request',\n 'Authorization': 'token ' + secret.GITHUB_TOKEN\n }\n };\n request(options, function(err, res, body) {\n cb(err, JSON.parse(body));\n });\n}", "function getRepoContributors (repoOwner, repoName, cb) {\n const options = {\n url: `https://api.github.com/repos/${repoOwner}/${repoName}/contributors`,\n headers: {\n 'User-Agent': 'request',\n 'Authorization': token.GITHUB_TOKEN\n }\n };\n\n request(options, function(err, res, body) {\n cb(err, body);\n });\n}", "function getRepoContributors(repoOwner, repoName, cb) {\n var options = {\n url: \"https://api.github.com/repos/\" + repoOwner + \"/\" + repoName + \"/contributors\",\n headers: {\n 'User-Agent': 'request',\n 'Authorization' : env.GITHUB_TOKEN\n }\n };\n\n request(options, function(err, res, body) {\n var body = JSON.parse(body);\n // if the repo or owner doesn't exist, let them know\n if (body.message === \"Not Found\") {\n console.log(\"Download failed: this repo doesn't exist.\");\n return;\n }\n /******************************************************* \n * callback: takes the error, and JSON body as arguments.\n * Loops through each collaborator's info and download's \n * their image\n *******************************************************/\n cb(err, body);\n });\n }", "function getRepoContributors(repositoryOwner, repositoryName, cb) {\n let options = {\n // gets the url, the access tokens, and the headers\n url: \"https://api.github.com/repos/\" + repositoryOwner + \"/\" + repositoryName + \"/contributors\",\n qs: {\n \"access_token\": ENV.GITHUB_TOKEN\n },\n headers: {\n 'User-Agent': 'request',\n }\n }\n\n function pullURL(error, response){\n let followersArray = []; \n if (response.statusCode !== 200){\n console.log(`Bad request error ${response.statusCode}: The provided owner/repo does not exist.`);\n } else if (error){\n throw \"Error: There was an issue with the information provided.\"; \n } else if (!repoOwner || !repoName){\n // handles error: inadequate number of arguments\n throw \"Error: Missing the name of either the repository owner, the repository name, or both.\"\n } else if (process.argv.length > 4){\n // handles error: excessive number of arguments\n throw \"Error: Cannot process the additional parameters.\"\n } else {\n let list = JSON.parse(response.body);\n list.forEach(function(contributor, index){\n cb(contributor.url, followersArray, list, index)\n })\n }\n }\n request(options, pullURL);\n}", "function getRepoContributors(repoOwner, repoName, cb) {\n var options = {\n url:\n 'https://api.github.com/repos/' +\n repoOwner +\n '/' +\n repoName +\n '/contributors',\n headers: {\n 'User-Agent': 'request',\n Authorization: 'token ' + token.GITHUB_TOKEN,\n },\n };\n\n // If the user does not specify both arguments,\n // the program should not attempt a request.\n // It should instead terminate with an error message letting the user know about the problem.\n if (commandOne === undefined || commandTwo === undefined) {\n console.log('There is an error!');\n return false;\n }\n\n request(options, function(err, res, body) {\n var data = JSON.parse(body);\n data.forEach(function(element) {\n cb(err, body);\n });\n });\n}", "function getRepoContributors(repoOwner, repoName, cb) {\n var GITHUB_USER = process.env.GITHUB_USER;\n var GITHUB_TOKEN = process.env.GITHUB_ACCESS_TOKEN;\n var requestURL = 'https://'+ GITHUB_USER + ':' + GITHUB_TOKEN + '@api.github.com/repos/' + repoOwner + '/' + repoName + '/contributors';\n // User-Agent required in request headers, otherwise we get 403 status code\n var requestOptions = {\n headers: {\n 'User-Agent': 'GitHub Avatar Downloader Exercise'\n }\n }\n // Use request to make an HTTP GET request to the generated URL\n request(requestURL, requestOptions, function(err, response, body) {\n if (err) {\n throw err;\n }\n // data will be an array where each element is a contributor's metadata\n const data = JSON.parse(body);\n data.forEach(function(user) {\n console.log(\"Avatar URL for \" + user.login + \": \" + user.avatar_url);\n downloadImageByURL(user.avatar_url, './avatars/' + user.login + '.png');\n });\n });\n}", "function getRepoContributors(repoOwner, repoName, callback) {\n\n // Ensures user input includes required arguments.\n // ### TODO: Create checks for incorrect owners and names, not just missing ones.\n if (!repoOwner || !repoName) {\n return console.log(`\\nExpected arguments: <Name of Repository Owner> <Name of Repository>\\nPlease try again.\\n`);\n }\n\n // Inserts user input into the API.\n // For reliable use, add your own token to ./secrets.js {GITHUB_TOKEN: \"token <string>\"}\n const options = {\n url: \"https://api.github.com/repos/\" + repoOwner + \"/\" + repoName + \"/contributors\",\n headers: {\n \"User-Agent\": \"request\",\n \"Authorization\": secrets.GITHUB_TOKEN\n }\n };\n\n request(options, function (err, result, body) {\n const downloadedInfo = JSON.parse(body);\n callback(err, downloadedInfo);\n });\n}", "function contributorsInfo(data) {\r\n const rightContainer = document.getElementById('rightContainer');\r\n rightContainer.innerHTML = '';\r\n return fetchJSON(data)\r\n .then(data => {\r\n const contrUrl = data.contributors_url;\r\n\r\n fetchJSON(contrUrl)\r\n .then(contrUrl => {\r\n const ul = createAndAppend('ul', rightContainer, {\r\n id: 'ulRightContr'\r\n });\r\n\r\n for (const contrs of contrUrl) {\r\n\r\n const li = createAndAppend('li', ul);\r\n\r\n createAndAppend('img', li, {\r\n src: contrs.avatar_url,\r\n alt: \"user's image\"\r\n });\r\n\r\n createAndAppend('div', li, {\r\n\r\n html: \"<a href=\" + contrs.html_url + ' target=\"_blank\" >' + contrs.login + \"</a>\"\r\n });\r\n\r\n createAndAppend('div', li, {\r\n html: contrs.contributions\r\n\r\n });\r\n };\r\n })\r\n })\r\n\r\n .catch(error => {\r\n console.log(error.message);\r\n });\r\n\r\n}", "function getRepoContributors(repoOwner, repoName, cb) {\n\n var options = {\n url: \"https://api.github.com/repos/\" + repoOwner + \"/\" + repoName + \"/contributors\",\n headers: {\n 'User-Agent': 'request',\n 'Authorization': 'token ' + authToken\n }\n };\n\n // Checks if owner/repo exists\n request(options, function(err, res, body) {\n if (res.statusCode !== 404) {\n cb(err, JSON.parse(body));\n } else {\n console.log(\"Please provide an actual owner/repo!\");\n }\n });\n}", "function getRepoContributors(repoOwner, repoName, cb) {\n var requestURL = 'https://'+ username + ':' + token + '@api.github.com/repos/' + repoOwner + '/' + repoName + '/contributors';\n console\n // checks for synchronous errors\n switch(true) {\n case (!fs.existsSync(\"./.env\")):\n console.log(\"Please create ./.env file with credentials\");\n return;\n case (!username || !token ): \n console.log(\"Missing username or Token in .env file\");\n return;\n case (process.argv.length < 4 || process.argv.length < 4): \n console.log(\"Please enter the right number of arguemnts (2): <repo-owner> <repo-name>\");\n return;\n case (!fs.existsSync(path)):\n fs.mkdirSync(path);\n console.log(\"/avatars/ not found so it was created\");\n }\n request.get(requestURL, options, cb) \n .on('error', function (err) { \n throw err;\n }) \n}", "function getRepoContributors(repoOwner, repoName, cb) {\n let requestURL = 'https://'+ GITHUB_USER + ':' + GITHUB_TOKEN + '@api.github.com/repos/' + repoOwner + '/' + repoName + '/contributors';\n options.url = requestURL;\n request(options, (err, response, body) => {\n if (err) {\n return cb(err);\n }\n if (body !== null) {\n let content = JSON.parse(body);\n if (content.message === \"Not Found\") {\n console.log(\"This repo does not exist\");\n return;\n }\n else {\n return cb(null, content);\n }\n }\n });\n}", "getData(cb){\n\t\tlet promArray = [];\n\t\tthis.allUserNames.map((userName)=>{\n\t\t\tpromArray.push(fetch(`https://api.github.com/users/${userName}`).then(res=>res.json()))\n\t\t})\n\n\t\tPromise.all(promArray)\n\t\t\t.then(data => {\n\t\t \t\t// do something with the data\n\t\t \t\t cb(data);\n\t\t\t})\n\n\t}", "function getContributions(author, permlink) {\r\n var url = `https://utopian.rocks/api/posts?author=`+author;\r\n var m_body = '';\r\n https.get(url, function(res) {\r\n res.on('data', function(chunk) {\r\n m_body += String(chunk);\r\n });\r\n res.on('end', function() {\r\n try {\r\n const response = JSON.parse(m_body);\r\n console.log(\"Total Contributions \", response.length);\r\n if (response.length > 0) {\r\n var contributionsObj = {\r\n \"total\": response.length,\r\n \"approved\": 0,\r\n \"staff_picked\": 0,\r\n \"total_payout\": 0.0\r\n };\r\n \r\n var first_contribution_date = timeConverter(response[0].created.$date);\r\n \r\n contributionsObj['category'] = {};\r\n contributionsObj['approved'] = response.filter(function (el) { return el.voted_on == true;});\r\n contributionsObj['staff_picked'] = response.filter(function (el) { return el.staff_picked == true;});\r\n\r\n contributionsObj['category']['analysis'] = response.filter(function (el) { return el.category === 'analysis' && el.voted_on === true;});\r\n contributionsObj['category']['blog'] = response.filter(function (el) { return el.category === 'blog' && el.voted_on === true;});\r\n contributionsObj['category']['bughunting'] = response.filter(function (el) { return el.category === 'bug-hunting' && el.voted_on === true;});\r\n contributionsObj['category']['copywriting'] = response.filter(function (el) { return el.category === 'copywriting' && el.voted_on === true;});\r\n contributionsObj['category']['development'] = response.filter(function (el) { return el.category === 'development' && el.voted_on === true;});\r\n contributionsObj['category']['documentation'] = response.filter(function (el) { return el.category === 'documentation' && el.voted_on === true;});\r\n contributionsObj['category']['graphics'] = response.filter(function (el) { return el.category === 'graphics' && el.voted_on === true;});\r\n contributionsObj['category']['suggestions'] = response.filter(function (el) { return el.category === 'suggestions' && el.voted_on === true;});\r\n contributionsObj['category']['taskrequests'] = response.filter(function (el) { return el.category === 'task-requests' && el.voted_on === true;});\r\n contributionsObj['category']['tutorials'] = response.filter(function (el) { return el.category === 'tutorials' && el.voted_on === true;});\r\n contributionsObj['category']['videotutorials'] = response.filter(function (el) { return el.category === 'video-tutorials' && el.voted_on === true;});\r\n contributionsObj['category']['translations'] = response.filter(function (el) { return el.category === 'translations' && el.voted_on === true;});\r\n contributionsObj['category']['iamutopian'] = response.filter(function (el) { return el.category === 'iamutopian' && el.voted_on === true;}); \r\n contributionsObj['category']['task'] = response.filter(function (el) { return el.category.startsWith(\"task\") && el.voted_on === true;});\r\n contributionsObj['category']['ideas'] = response.filter(function (el) { return el.category === 'ideas' && el.voted_on === true;});\r\n contributionsObj['category']['visibility'] = response.filter(function (el) { return el.category === 'visibility' && el.voted_on === true;});\r\n\r\n response.forEach(function(contribution) {\r\n if(contribution.voted_on === true){\r\n contributionsObj.total_payout = contributionsObj.total_payout + contribution.total_payout;\r\n }\r\n });\r\n\r\n for(var key in contributionsObj.category) {\r\n const value = contributionsObj.category[key];\r\n if(value.length == 0){\r\n delete contributionsObj.category[key];\r\n }\r\n }\r\n\r\n commentOnAuthorPost(contributionsObj, first_contribution_date, author, permlink);\r\n }\r\n } catch (e) {\r\n console.log('Err' + e);\r\n }\r\n });\r\n }).on('error', function(e) {\r\n req.abort();\r\n console.log(\"Got an error: \", e);\r\n });\r\n}", "function listContributors(error, response, body){\n // Check for asynchronous errors\n switch(true) {\n case (response.statusCode == 404):\n console.log (\"Repo or user not found\")\n return;\n case (response.statusCode == 401):\n console.log (\"Bad Credentials\")\n return;\n }\n var contributors = JSON.parse(body);\n\n // create array of which resolves when a contributor's stars have been counted\n const allPromises = contributors.map(function(person, contributorIndex) {\n var myPromise = new Promise(function(resolve, reject){\n var url = 'https://' + username + ':' + token + '@api.github.com/users/' + person.login + \"/starred\"\n listStarred(url, person.login, function(){\n resolve();\n });\n })\n return myPromise;\n });\n // When all star counting promises have returned, return..\n // encompassing promise, and count stars to find the most popular repo\n Promise.all(allPromises).then(function(){\n var sorted = Object.keys(repoCount).sort(function(a, b){\n return repoCount[b].count - repoCount[a].count;\n }).slice(0, 6);\n sorted.forEach(function(repo){\n console.log(`[${repoCount[repo].count} stars] ${repoCount[repo].name} / ${repoCount[repo].owner}`);\n });\n\n })\n}", "function getContributors() {\n Object.keys(markers).forEach(function(key) {\n //Loops through the object. snippet from https://stackoverflow.com/questions/684672/how-do-i-loop-through-or-enumerate-a-javascript-object\n if (contributors[markers[key].udacityForumUserName] == null) {\n // checks if undefined or null. code snippet from https://stackoverflow.com/questions/2647867/how-to-determine-if-variable-is-undefined-or-null\n contributors[markers[key].udacityForumUserName] = [key];\n } else {\n contributors[markers[key].udacityForumUserName].push(key);\n }\n });\n}", "getCommits(username) {\r\n // Create a request variable and assign a new XMLHttpRequest object to it.\r\n var request = new XMLHttpRequest();\r\n request.open('GET', 'https://api.github.com/repos/' + username + \"/\" + this.selectedProject + \"/commits?since=\" + this.dateSince + \"T00:00:00Z&until=\" + this.dateUntil + \"T23:59:59Z\", true);\r\n request.setRequestHeader(\"Authorization\", \"token \" + config.token);\r\n listCommits = [];\r\n request.onload = function () {\r\n if (request.status >= 200) {\r\n var dataCommits = JSON.parse(this.response);\r\n console.log(JSON.parse(this.response))\r\n dataCommits.forEach(aCommit => {\r\n listCommits.push(\r\n { \r\n \"author\": aCommit.commit.author.name,\r\n \"date\": aCommit.commit.author.date,\r\n \"message\": aCommit.commit.message\r\n }\r\n );\r\n })\r\n } else {\r\n console.log(error);\r\n }\r\n }\r\n // Send request\r\n console.log(\"commit:\", listCommits)\r\n request.send();\r\n \r\n this.isDisplay = true;\r\n }", "function getAllMentors(callback) {\n // jQuery AJAX call for JSON\n $.getJSON( '/users/getAllMentors', function( data ) {\n callback(data);\n }); \n}", "function getUsers(params, callback) {\n var github = GithubSession.connect(params.accessToken);\n var respondWith = formatJsend.respondWith(callback);\n\n github.repos.getCollaborators({\n user: params.userName,\n repo: params.urlName\n }, function(err, collaborators) {\n if (err) { return respondWith(err); }\n\n collaborators = collaborators.map(translator.toBpUser);\n respondWith({ users: collaborators });\n });\n}", "function getAllMentorslist(callback) {\n // jQuery AJAX call for JSON\n $.getJSON( '/users/getAllMentorslist', function( data ) {\n callback(data);\n }); \n}", "function requestUsers() {\r\n var request = new XMLHttpRequest();\r\n request.open('GET', urlBase + 'users.json', true);\r\n request.onreadystatechange = requestUsersCallback;\r\n request.send();\r\n }", "function makeTheCall(userName){\n\n fetch(gitHubURL + userName +\"/repos\")\n .then(response => response.json())\n .then(responseJson => listOnlyName(responseJson)); \n}", "function smallDataFetch(search){\n return fetch('https://api.github.com/repos/'+search+'/stats/contributors')\n .then(data=>data.json())\n .then(data=>{\n let betterData = []\n for(i=0; i<data.length; i++){\n betterData.push({'total':data[i].total,'user':data[i].author.login})\n }\n return betterData\n })\n}", "function mockFetchContributors (contributors) {\n return (opts, cb) => process.nextTick(() => cb(null, contributors || fakeContributors()))\n}", "function loadUsers() {\n // This takes the the GET method and the API's location.\n xhr.open(\"GET\", \"https://api.github.com/users\", true);\n\n xhr.onload = function () {\n if (this.status === 200) {\n // Here we are parsing JSON data to plain text\n let githubUsers = JSON.parse(this.responseText);\n // Here i used template strings for simplicity\n // output is empty so that you can simply add it later on.\n let output = '';\n // loop through githubUsers variable because there are many of them\n for(let i in githubUsers){\n output +=\n `<div class = \"user\">\n <img src= ${githubUsers[i].avatar_url} width=70px height= 70px>\n <ul>\n <li>ID: ${githubUsers[i].id}</li>\n <li>Name: ${githubUsers[i].login}</li>\n </ul>\n </div>`\n }\n users.innerHTML = output;\n }\n };\n// This will give you an output if there is an error\n xhr.onerror = function () {\n alert(\"Sorry but there is an error\");\n };\n// This function helps to send the request.\n xhr.send();\n}", "function getComments(artifact, project_id, callback) {\n // jQuery AJAX call for JSON\n $.getJSON( '/projects/getComments/' + project_id + '/' + artifact, function( data ) {\n // Stick our user data array into a userlist variable in the global object\n callback(data);\n });\n}", "function getArtifacts(project_id,callback) {\n // jQuery AJAX call for JSON\n $.getJSON( '/projects/getArtifacts/'+ project_id, function( data ) {\n // Stick our user data array into a userlist variable in the global object\n console.log(data);\n callback(data);\n });\n}", "function getAuthors() {\n $.get(\"/api/authors\", renderAuthorList);\n }", "function getLeagues(leagueNames, cb) {\n http.request(new Options(), null , processLeagues);\n\n var body = \"\";\n\n function processLeagues(res) {\n res.on(\"data\", function(chunk) {\n body += chunk;\n });\n\n res.on(\"end\", function(chunk) {\n cb(null, JSON.parse(body))\n });\n }\n\n}", "function getMenteeByusername(username,callback) {\n // jQuery AJAX call for JSON\n $.getJSON( '/users/getMenteeByusername/'+ username, function( data ) {\n callback(data);\n });\n}", "function gatherResearchPapers(callback){\r\n $.getJSON(GITHUB_RESEARCH, function(data){\r\n \r\n research = data.filter(function(item){\r\n if (item.name != \"readme.json\"){\r\n return item;\r\n }\r\n });\r\n $.getJSON(GITHUB_RESEARCH_INFO, function(data){\r\n research_description = data;\r\n return callback();\r\n })\r\n });\r\n}", "function getRepoContributors(username, repo, options){\n commits = getCommitsInRange(username, repo, options); \n let result = [];\n let lookup = {};\n for (let i=0; i<commits.length; i++){\n let item = commits[i][\"commit\"][\"author\"][\"name\"];\n let name = item;\n if(!(name in lookup)){\n lookup[name] = 1;\n result.push(name);\n }\n }\n return(result);\n}", "function getMentors(type, callback) {\n // jQuery AJAX call for JSON\n $.getJSON( '/users/getMentors/' + type, function( data ) {\n callback(data);\n });\n}", "function getExternal() {\n fetch('https://api.github.com/users')\n .then(function (response) {\n return response.json();\n })\n .then(function (data) {\n console.log(data);\n let op = '';\n data.forEach(function (user) {\n op+= `<li>${user.login}</li>`\n });\n document.getElementById('output').innerHTML = op;\n })\n .catch(function (err) {\n console.log(err);\n });\n}", "async function getPeople(){\n const { data } = await axios.get('https://gist.githubusercontent.com/robherley/5112d73f5c69a632ef3ae9b7b3073f78/raw/24a7e1453e65a26a8aa12cd0fb266ed9679816aa/people.json');\n return data;\n }", "async function getPeople(){\n const { data } = await axios.get('https://gist.githubusercontent.com/robherley/5112d73f5c69a632ef3ae9b7b3073f78/raw/24a7e1453e65a26a8aa12cd0fb266ed9679816aa/people.json');\n return data;\n }", "function getJSON(url, callback) {\n let request = new XMLHttpRequest();\n request.open('GET', url, true);\n\n request.onload = function() {\n if (this.status >= 200 && this.status < 400) {\n callback(JSON.parse(this.response));\n } else {\n conosle.log(\"GitHub Cards Update error: \" + this.response);\n }\n };\n\n request.onerror = function() {\n console.log(\"GitHub Cards could not connect to Github!\");\n };\n\n request.send()\n }", "function fetchUsers() {\n return fetch('https://api.github.com/users')\n .then(response => response.json());\n}", "function getExternal() {\n fetch(\"https://api.github.com/users\")\n .then(function (res) {\n return res.json();\n })\n .then(function (data) {\n console.log(data);\n let output = \"\";\n data.forEach(function (user) {\n output += `<li>${user.login}</li>`;\n });\n document.getElementById(\"output\").innerHTML = output;\n })\n .catch(function (err) {\n console.log(err);\n });\n}", "async function fetchUsersAsync() {\n const response = await fetch('https://api.github.com/users');\n\n const json = await response.json();\n\n console.log(json);\n}", "function getExternal(){\n fetch('https://api.github.com/users')\n .then(res => res.json())\n .then(data =>{\n\n console.log(data);\n let output = '';\n data.forEach(function(user){\n\n output += `<li>${user.login}</li>`\n });\n document.getElementById('output').innerHTML = output;\n \n\n })\n .catch(err => console.log(err));\n\n}", "function xhrCallback(data) {\n //console.log('data from server', data);\n repositories = JSON.parse(data);\n console.log('parsed repo data:', repositories);\n\n showRepositoriesInSelect(repositories);\n}", "function userRequest() {\n $.getJSON('/users/userlist', function (data) {\n\n // For each item in our JSON, do something like render some HTML to the DOM\n $.each(data, function () {\n // mock up some html\n });\n });\n}", "function getExternal() {\n fetch('https://api.github.com/users')\n .then(function(res){\n return res.json();\n })\n .then(function(data) {\n console.log(data);\n let output = '';\n data.forEach(function(user) {\n output += `<li>${user.login}</li>`;\n });\n document.getElementById('output').innerHTML = output;\n })\n .catch(function(err){\n console.log(err);\n });\n}", "function getJiveUsers(res, userSyncingConditions, utcDate, previousDate, callback) {\n\n var headers = {\n 'Authorization': 'Bearer ' + jive1.access_token,\n 'Content-Type': 'application/json'\n };\n\n var options = {\n url: jiveLoginUrl + '/api/core/v3/people?filter=updated(' + previousDate + ',' + utcDate + ')&fields=jive,addresses,id,emails,followerCount,followed,displayName,mentionName,followingCount,name,phoneNumbers,updated,location',\n method: 'GET',\n headers: headers\n };\n\n console.log(options);\n request(options, function (err, response, data) {\n console.log(err);\n if (!err && response.statusCode == 200) {\n // console.log(data);\n data = JSON.parse(data);\n if (data.list.length) {\n\n var k = 0;\n\n function getAnalyticsData(k) {\n\n if (k < data.list.length) {\n getAnalyticsValues(data.list[k].emails[0].value, data.list[k], function (cb) {\n k++;\n getAnalyticsData(k);\n });\n }\n else {\n userSyncingConditions.data = data.list;\n\n // res.send(userSyncingConditions);\n\n callback(null, userSyncingConditions);\n }\n }\n\n getAnalyticsData(0);\n\n }\n else {\n res.send(\"no users updated in last week\");\n }\n\n }\n else {\n res.send(\"some error occured\");\n }\n\n });\n\n\n}", "function getExternal(){\n fetch('https://api.github.com/users')\n .then(res => res.json())\n .then(data => {\n console.log(data);\n let output = '';\n data.forEach(function(user){\n output += `<li>${user.login}</li>`;\n });\n document.getElementById('output').innerHTML = output;\n })\n .catch(err => console.log(err));\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 }", "function getAssignedMentees(user_id,callback) {\n // jQuery AJAX call for JSON\n //get the data from the users collection\n $.getJSON( '/users/getAssignedMentees/'+ user_id, function( data ) {\n callback(data);\n });\n}", "function getJsonGit(){\n fetch('https://api.github.com/users')\n .then(resp => resp.json())\n .then(data => {\n console.log(data);\n\n const dataDisplay = data.map(item => {\n return `<li>${item.login} <img src='${item.avatar_url}' width='200px' height='200-x' > </li>`\n });\n\n output.innerHTML = `<ul>${dataDisplay.join('')}</ul>`;\n });\n}", "fetchPopularUsers(url, popularUsersAreReady) {\n let popularUsers = []; // saved results\n\n /*\n * Fetches a page on the github API\n */\n function fetchPage(pageURL) {\n console.log(`Fetching${pageURL}`);\n\n // Please note I don't use hostRequest for this GET request because\n // its not in the same scope\n request\n .get(pageURL)\n .auth(credentials.username, credentials.token)\n .set('Accept', 'application/vnd.github.v3+json')\n .end((err, res) => {\n popularUsers = popularUsers.concat(res.body.items);\n if (res.links.next) {\n fetchPage(res.links.next);\n } else {\n popularUsersAreReady(popularUsers);\n }\n });\n }\n fetchPage(url);\n }", "function listOfUsers() {\n request.get('https://slack.com/api/users.list?token='+\n process.env.Apptoken+'&pretty=1',function (err,requ,response)\n {\n var data= JSON.parse(response);\n usersLists=data.members;\n });//end of get users.list function\n}", "function getAPI(){\n fetch('https://api.github.com/users')\n .then(function (respnse) {\n return respnse.json();\n }).then(function (data) {\n console.log(data);\n let output ='';\n data.forEach(function(user){\n output+=`<li>${user.login}</li>`;\n })\n document.getElementById('output').innerHTML = output;\n }).catch(function(err){\n console.log(err);\n });\n}", "function user_tree(callback) {\n familysearch.get('/platform/tree/current-person', {\n followRedirect: true\n }, function(error, response){\n if(error) {\n handleError(error);\n }\n else {\n callback(response.data.persons[0]);\n console.log(response.data.persons[0]);\n }\n });\n}", "async function handle_contributions(response) {\n contributions = await response.json();\n render_contributions();\n}", "async getAllPeople() {\n const responseData = await fetch(\"https://ghibliapi.herokuapp.com/people\");\n\n const response = await responseData.json();\n\n return response;\n }", "function getProfile(username) {\n\n var request = http.get(\"http://teamtreehouse.com/\" + username + \".json\", function(response) {\n\n console.log(\"STATUS: \" + response.statusCode);\n response.setEncoding('utf8');\n\n var body = \"\";\n\n response.on('data', function(jsonBody) {\n body += jsonBody;\n });\n\n response.on('end', function() {\n\n if (response.statusCode == 200) {\n\n try {\n profile = JSON.parse(body);\n name = profile.name;\n profileName = profile.profile_name;\n profileUrl = profile.profile_url;\n gravatarUrl = profile.gravatar_url;\n gravatarHash = profile.gravatar_hash;\n badges = profile.badges;\n points = profile.points;\n \n for (i = 0; i < badges.length; i++) {\n console.log(badges[i].name); \n }\n \n } catch (error) {\n // Parse Error\n printError(error);\n }\n\n setProfile();\n return profile;\n\n } else {\n printError({ message: \"There was an error, status code error is \" \n + http.STATUS_CODES[response.statusCode]}); \n }\n });\n });\n\n // Connection Error\n request.on('error', printError);\n \n}", "function getUserData(octokit, repoOwner, repoName) {\n return __awaiter(this, void 0, void 0, function* () {\n const {data: collaborators} = yield octokit.repos.listCollaborators({\n owner: repoOwner,\n repo: repoName,\n });\n const {data: contributors} = yield octokit.repos.listContributors({\n owner: repoOwner,\n repo: repoName\n });\n var collaboratorsSet = new Set();\n for (var i = 0; i < collaborators.length; i ++){\n collaboratorsSet.add(collaborators[i].login);\n }\n var contributorsSet = new Set();\n for (var i = 0; i < contributors.length; i ++){\n contributorsSet.add(contributors[i].login);\n }\n return {\n collaborators: collaboratorsSet,\n contributors: contributorsSet\n }\n });\n}", "function authorCallback (x){\n\n x.forEach(function(object){\n $('#authorDropDownAnchor').append(\"<option value='\"+object.author+\"'>\"+object.author+ \"</option>\");\n });\n }", "function getUsers() {\n let xhttp = new XMLHttpRequest();\n xhttp.onreadystatechange = function () {\n if (xhttp.readyState === 4 && xhttp.status === 200) {\n \n let arrayUsers = JSON.parse(xhttp.responseText);\n let select = document.getElementById(\"cboUsers\"); \n for (let i in arrayUsers) {\n let option = document.createElement(\"option\");\n select.options.add(option, 0);\n select.options[0].value = arrayUsers[i].id;\n select.options[0].innerText = arrayUsers[i].name;\n }\n }\n };\n xhttp.open(\"GET\", \"../data/cohorts/lim-2018-03-pre-core-pw/users.json\", true);\n xhttp.send();\n }", "function GetAuthor(data) {\r\n return fetch('http://localhost:4000/authors/'+data)\r\n .then(response =>\r\n response.json())\r\n}", "function getUsers(){\r\n fetch('data.json')\r\n .then((res) => res.json())\r\n .then((data)=>{\r\n data.forEach((color) => {\r\n \r\n items.push(color); \r\n });\r\n\r\n })\r\n }", "function getJSON(){\n var request = new XMLHttpRequest();\n request.open('GET', \"https://scratch.mit.edu/studios/5142661/\");\n request.responseType = 'json';\n request.send();\n request.onload = function() {\n var project = request.response;\n args.unshift(project);\n return project;\n }\n}", "function getList(){\n\t\t// call ajax\n\t\tlet url = 'https://final-project-sekyunoh.herokuapp.com/get-user';\n\t\tfetch(url)\n\t\t.then(checkStatus)\n\t\t.then(function(responseText) {\n\t\t\tlet res = JSON.parse(responseText);\n\t\t\tlet people = res['people'];\n\t\t\tdisplayList(people);\n\t\t})\n\t\t.catch(function(error) {\n\t\t\t// show error\n\t\t\tdisplayError(error + ' while getting list');\n\t\t});\n\t}", "function getAllUsers(callback) {\n requester.get('user', '', 'kinvey')\n .then(callback)\n}", "function get_organisations() {\n\t\n\tconsole.log(\"Getting organisations...\");\n\t\n\tvar headers = new Headers();\n headers.append(\"Authorization\", \"Bearer \" + userAccountData.jwt);\n headers.append(\"Content-Type\", \"application/json\");\n\t//console.log(accountObj.deviceTemplates);\n\tfetch(xi_bp_url+'organizations?accountId=' + userAccountData.accountId, {\n\t\tmethod: \"GET\",\n headers: headers,\n cache: \"no-store\"\n\t})\n\t.then(function(response) { return response.json(); })\n .then(function(data) {\n \tconsole.log(\"Getting the organisations: done\");\n\n \tuserAccountData.organizations = data.organizations.results;\n console.log(userAccountData.organizations);\n }.bind(this)).catch(() => {\n alert(\"Couldn't fetch the organisations\");\n });\n}", "function loadFamilyMembers() {\n fetch('json/family.json')\n .then(function(response) {\n return response.json();\n })\n .then(function(json) {\n console.log(\"Family Members: \");\n console.log(json);\n family = json;\n appendFamily(json, \"family\");\n });\n}", "function getTheJson(apiUrl, cb){\r\n ajaxFunctions.ready(\r\n ajaxFunctions.ajaxRequest(reqMethod, apiUrl, true, function(data){\r\n cb(data);\r\n })\r\n ); \r\n }", "function getAllTeachers(callback, params){\n all_teachers = [];\n var xmlHttpF = new XMLHttpRequest();\n xmlHttpF.onreadystatechange = function () {\n if (xmlHttpF.responseText && xmlHttpF.status == 200 && xmlHttpF.readyState == 4) {\n var obj = jQuery.parseJSON(xmlHttpF.responseText);\n var portfolioCurrent;\n $.each(obj, function () { \n if(this['accountType'] == \"Teacher\"){ \n all_teachers.push(this)\n }\n });\n callback(params, all_teachers)\n return all_teachers;\n }\n };\n xmlHttpF.open(\"GET\", \"https://mydesigncompany.herokuapp.com/users/\", true);\n xmlHttpF.send(null);\n}", "function GetCommentsFromFamily() {\n fetch('https://gentle-ridge-58844.herokuapp.com/family', {\n method: 'get',\n headers: {'content-type': 'application/json'},\n })\n .then(data => data.json())\n .then(res => CreateComment(res.forEach(obj => CreateComment(obj))))\n .catch(console.log);\n}", "function getUserInfo(name) {\n console.log();\n const url = `https://api.github.com/users/${name}/repos`;\n //fetch api GET calls github api\n fetch(url)\n .then( response => {\n //check for errors before returning response.json \n if (response.ok) {\n return response.json() ;\n }\n //send eror status text to .catch\n throw new Error(response.statusText) ;\n })\n //do something \n .then(responseJson => displayResults(responseJson))\n .catch( err => {$( '#js-error-message' ).text(`something went wrong: ${err.message}`);\n });\n}", "function getArtifactLink(artifact, project_id, callback) {\n // jQuery AJAX call for JSON\n $.getJSON( '/projects/getArtifactLink/' + project_id + '/' + artifact, function( data ) {\n // Stick our user data array into a userlist variable in the global object\n callback(data);\n });\n}", "function getClientsVolunteers() {\n var rowsToAdd = [];\n $.get(\"/api/clients\", function(data) {\n for (var i = 0; i < data.length; i++) {\n rowsToAdd.push(createUserRow(data[i]));\n }\n });\n $.get(\"/api/volunteers\", function(data) {\n for (var i = 0; i < data.length; i++) {\n rowsToAdd.push(createUserRow(data[i]));\n }\n });\n renderCommunityList(rowsToAdd);\n nameInput.val(\"\");\n }", "function getUsers(json) { return json.map(function (obj){ return obj.user; } ); }", "function getUsers(){\n fetch('users.json')\n .then((res) => res.json())\n .then((data) => {\n let output = `<h2 class=\"bb-4\">Users</h2>`;\n data.forEach((user) => {\n output += `\n <ul class=\"list-group mb-3\">\n <li class=\"list-group-item\">Id: ${user.id}</li>\n <li class=\"list-group-item\">Name: ${user.name}</li>\n <li class=\"list-group-item\">Email: ${user.email}</li>\n </ul>\n `;\n });\n document.getElementById('output').innerHTML = output;\n \n })\n .catch((err) => console.log(err));\n}", "function getContributions(callback){\n db.collection(\"pollination\").find().toArray(callback);\n }", "function getCollaboratorsByProject(){\n\tvar urlGitHubCollaborators = \"https://api.github.com/repos/\" + projectOwner + \"/\" + projectName + \"/collaborators?\" + githubCredentials;\n\tvar collaborators = new Array();\n\t$.ajax({\n \t\turl: urlGitHubCollaborators,\n \t\tasync: false,\n \t\tsuccess: function(data){\n \t\t\t// Makes an array of urls\n \t\t\t$.each(data, function(index) {\t\n\t\t\t\tcollaborators.push(this.url + \"?\" + githubCredentials);\n\t\t\t\tif(restriction == true && index == 9)\n\t\t\t\t\treturn false;\n\t\t\t});\n\t\t},\n\t\terror: function (jqXHR, textStatus, errorThrown){\n\t\t\tconsole.log(\"Error: GitHub getCollaboratorsByProject\");\n\t\t\tthrow new GitHubException(jqXHR.status, textStatus, \"GetCollaboratorsByProject\");\n\t\t}\t\t\t\n\t});\n\treturn collaborators;\n}", "function userOrganisations(opts) {\n var url = ApiUrl + 'user/orgs' +\n '?access_token=' + opts.access_token;\n var moreHeaders = {};\n var orgs = {};\n\n cache.get(url, function(err, store) {\n if (!err && Object.keys(store).length !== 0) {\n console.log('Orgs from cache: ' + url);\n orgs = store[url].orgs;\n moreHeaders = {'If-None-Match': store[url].etag};\n }\n });\n\n return new Promise(function (resolve, reject) {\n prequest({\n url: url,\n headers: _.defaults({'User-Agent': opts.nickname}, moreHeaders),\n arrayResponse: true\n }).spread(function (response, data) {\n if (response.statusCode === 304) {\n return resolve(orgs);\n }\n data.push({login: opts.nickname}); // Add user into list of orgs\n orgs = githubOrganisations(data);\n cache.set(url, {orgs: orgs, etag: response.headers.etag});\n resolve(orgs);\n }).catch(function (err) {\n err.message = 'Cannot access ' + url;\n reject(err);\n });\n });\n}", "list(owner, callback) {\n\t\tthis.userlib.get(owner, (err, doc) => {\n\t\t\tif (err) {\n\t\t\t\tcallback(false, err);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (doc) {\n\t\t\t\tcallback(true, doc.repos);\n\t\t\t} else {\n\t\t\t\tcallback(false, \"user_not_found\");\n\t\t\t}\n\t\t});\n\t}", "function getAuthorListJSON(author, eventCallback) {\r\n\r\n\tvar book_details={};\r\n\tvar rank_count = 1;\r\n\tauthorencode = author.replace(' ','+');\r\n\r\n\trequest.get({\r\n\t\turl: \"https://www.googleapis.com/books/v1/volumes?q=\" + authorencode +\"&orderBy=relevance&key=APIKEY\"\r\n\t\t}, function(err, response, body) {\r\n\r\n\t\t\tvar list_of_books = [];\r\n\t\t\tvar list_of_titles = [];\r\n\r\n\t\t\tif (body){\r\n\t\t\t\ttry{\r\n\t\t\t\t\tbody = JSON.parse(body);\r\n\t\t\t\t}catch(e){\r\n\t\t\t\t\tvar list_of_books = [];\r\n\t\t\t\t\teventCallback(list_of_books);\r\n\t\t\t\t\treturn;\r\n\t\t\t\t}\r\n\t\t\t}\t\r\n\r\n\t\t\tif (body.totalItems === 0){\r\n\t\t\t\tstringify(list_of_books);\r\n\t\t\t\teventCallback(list_of_books);\r\n\t\t\t}\r\n\r\n\r\n\t\t\tfor (var i = 0,length = body.items.length; i < length; i++ ) {\r\n\r\n\t\t\t\tvar book_details={};\r\n\r\n\t\t\t\tvar title = body.items[i].volumeInfo.title;\r\n\t\t\t\tbook_details.title = title;\r\n\t\t\t\tbook_details.titleupper = title.toUpperCase();\r\n\t\t\t\tconsole.log(book_details.title);\r\n\t\t\t\t\r\n\t\t\t\tif (list_of_titles.indexOf(body.items[i].volumeInfo.title)> 0) { \t\t\t\t\r\n\t\t\t\t\tcontinue; \r\n\t\t\t\t}\r\n\r\n\t\t\t\tif (typeof body.items[i].volumeInfo.authors=== 'undefined') { \t\t\t\t\r\n\t\t\t\t\tcontinue; \r\n\t\t\t\t}\r\n\r\n\t\t\t\tlist_of_titles[i] = body.items[i].volumeInfo.title;\r\n\r\n\t\t\t\tvar author_string = \"\"; \r\n\t\t\t\tvar author_array = body.items[i].volumeInfo.authors;\r\n\t\t\t\tvar author_array_upper = [];\r\n\r\n\t\t\t\tfor (var a = 0, alength = author_array.length; a < alength; a++){\r\n\t\t\t\t\tauthor_array_upper[a] = author_array[a].toUpperCase();\r\n\t\t\t\t}\r\n\r\n\t\t\t\tif (author_array_upper.indexOf(author.toUpperCase())< 0) { \r\n\t\t\t\t\t//console.log(\"Excluded: \" + book_details.title);\t\t\t\t\t\r\n\t\t\t\t\tcontinue; \r\n\t\t\t\t}\r\n\r\n\t\t\t\tfor (var k = 0, klength = author_array.length; k < klength; k++){\r\n\t\t\t\t\tauthor_string = author_string + author_array[k] + \" and \" ;\r\n\t\t\t\t}\r\n\r\n\t\t\t\tauthor_string = author_string.slice(0, -5);\r\n\t\t\t\tbook_details.author = author_string;\t\t\t\t\r\n\t\t\t\tbook_details.contributor = \"by \" + author_string;\r\n\r\n\r\n\t\t\t\tbook_details.author = author_string;\t\t\t\t\r\n\t\t\t\tbook_details.contributor = \"by \" + author_string;\r\n\t\t\t\t\r\n\t\t\t\tbook_details.rank = rank_count;\r\n\t\t\t\trank_count++;\r\n\r\n\t\t\t\tvar isbns_string = \"\";\r\n\t\t\t\tvar isbns_array = body.items[i].volumeInfo.industryIdentifiers;\r\n\r\n\t\t\t\tfor (var j = 0, jlength = isbns_array.length; j < jlength; j++){\r\n\t\t\t\t\tif (isbns_array[j].type === 'ISBN_10'){\r\n\t\t\t\t\t\tbook_details.primary_isbn10 = isbns_array[j].identifier;\r\n\t\t\t\t\t\tisbns_string = isbns_string + isbns_array[j].identifier + ',';\r\n\t\t\t\t\t}else{\r\n\t\t\t\t\t\tbook_details.primary_isbn13 = isbns_array[j].identifier;\r\n\t\t\t\t\t\tisbns_string = isbns_string + isbns_array[j].identifier + ',';\r\n\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t}\r\n\t\t\t\tisbns_string = isbns_string.slice(0, -1);\r\n\r\n\t\t\t\tbook_details.isbns_string = isbns_string;\r\n\r\n\t\t\t\tbook_details.contributor_alt = \"\";\r\n\r\n\t\t\t\tif (typeof body.items[i].volumeInfo.publishedDate !== 'undefined') { \r\n\t\t\t\t\t//published_date = body.items[i].volumeInfo.publishedDate;\r\n\t\t\t\t\tvar published_date = new Date(body.items[i].volumeInfo.publishedDate);\r\n\t\t\t\t\tvar date_string = monthNames[published_date.getMonth()] + \" \" + published_date.getFullYear();\r\n\t\t\t\t\tbook_details.contributor_alt = \"published in \" + date_string;\r\n\t\t\t\t}\r\n\t\t\t\r\n\r\n\t\t\t\tvar description = \". No description available.\";\r\n\t\t\t\t\r\n\t\t\t\tif (typeof(body.items[i].searchInfo) !=='undefined'){\r\n\t\t\t\t\tif (typeof(body.items[i].searchInfo.textSnippet) !=='undefined'){\r\n\t\t\t\t\t\tdescription = \". Here's a brief description of the book, \" + body.items[i].searchInfo.textSnippet;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\r\n\t\t\t\tbook_details.description = book_details.title + description;\r\n\t\t\t\t\r\n\r\n\t\t\t\tlist_of_books[i] = book_details;\r\n\t\t\t}\r\n\r\n\t\t\tlist_of_books = list_of_books.filter(function(n){ return n != undefined }); \r\n\t\t\tstringify(list_of_books);\r\n\t\t\t//console.log(list_of_books);\r\n\r\n\t\t\teventCallback(list_of_books);\r\n\t\t}).on('err', function (e) {\r\n console.log(\"Got error: \", e);\r\n });\r\n\r\n}", "function make_request (url, callback) {\n var reqOpts = {\n hostname: 'api.github.com',\n path: url,\n headers: {'User-Agent': 'GitHub StarCounter'},\n //auth: opts.auth || undefined\n }\n https.request(reqOpts, function (res) {\n var body = ''\n res\n .on('data', function (buf) {\n body += buf.toString()\n })\n .on('end', function () {\n //fetch_repos(user, JSON.parse(body), callback);\n callback(JSON.parse(body));\n })\n }).end()\n}", "function getUsers () {\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': 'getUsers',\n\t\t}, complete: function (data) {\n\t\t\tconsole.log(\"RESPONSE JSON FOR getUsers() = \",data.responseJSON);\n\t\t\tif (data.responseJSON) {\n\t\t\t\tusers = data.responseJSON;\n\t\t\t\tconsole.log(\"USERS = \",users);\n\t\t\t\tcreateDropdown(data.responseJSON);\n\t\t\t\tgetTasks();\n\t\t\t}\n\t\t}\n\t\t\n\t});\t\n}", "function getContributerUrl( err, data ){\n\n data.forEach(function(element){\n downloadImageByURL(element.avatar_url, `avatars/${element.login}.jpg`);\n })\n}", "function getStudents(callback) {\n // jQuery AJAX call for JSON\n $.getJSON( '/users/getStudents', function( data ) {\n callback(data);\n });\n}", "getData(cb) {\n fetch(userUrl + this.props.getUserId(), {\n method: 'GET',\n headers: { 'x-access-token': this.props.getToken() },\n })\n .then(res => res.json())\n .then((data) => {\n this.props.updateMealList(data.mealsObjs);\n }).done(() => {\n if (cb) { cb(); }\n });\n }", "function webScrape(username){\n\n return new Promise(resolve => {\n let data = []\n request('https://github.com/' + username, function (error, response, html) {\n if (!error && response.statusCode == 200) {\n var $ = cheerio.load(html);\n //Grabs information on user's contributions from their github page\n $('div.js-calendar-graph > svg > g > g > rect').each(function(i, element){\n const contributions = $(this).attr('data-count');\n const dataDate = $(this).attr('data-date');\n let object = {\n contribution: contributions,\n dataDate: dataDate\n };\n data.push(object)\n })\n resolve(data)\n }\n })\n })\n}", "function getRepositories(theUrl, callback) {\n var xmlHttp = new XMLHttpRequest();\n xmlHttp.onreadystatechange = function () {\n if (xmlHttp.readyState == 4 && xmlHttp.status == 200)\n callback(xmlHttp.responseText);\n }\n xmlHttp.open(\"GET\", theUrl, true); // true for asynchronous \n xmlHttp.send(null);\n}", "function findAllUsers(callback) {\n \treturn fetch(this.url)\n .then(function(response) {\n return response.json();\n });\n }", "function getAllUnassignedMentees(callback) {\n // jQuery AJAX call for JSON\n $.getJSON( '/users/getAllUnassignedMentees', function( data ) {\n callback(data);\n }); \n}", "getUserData(username) {\n $.ajax({\n url: `https://api.github.com/users/${username}`,\n dataType: 'jsonp',\n success: this.createUserCard.bind(this)\n })\n }" ]
[ "0.7660997", "0.73393077", "0.719259", "0.70867324", "0.708333", "0.70817816", "0.7047408", "0.7006869", "0.68267876", "0.6731167", "0.67047584", "0.6612997", "0.6612835", "0.65748113", "0.6507493", "0.6444939", "0.640652", "0.638246", "0.6349789", "0.63270503", "0.6324915", "0.6296204", "0.6254266", "0.6229763", "0.6193208", "0.6168528", "0.60324687", "0.60297215", "0.5962352", "0.5955492", "0.5915608", "0.58907616", "0.58800405", "0.581553", "0.57748353", "0.57295763", "0.5682574", "0.567803", "0.5673863", "0.5648414", "0.56371516", "0.5603941", "0.56008345", "0.55990696", "0.55943274", "0.5576012", "0.5576012", "0.55694795", "0.5563658", "0.5546463", "0.5537686", "0.5534588", "0.55326265", "0.5529178", "0.5520887", "0.5491087", "0.548112", "0.547784", "0.54157174", "0.53978914", "0.539188", "0.5391074", "0.5384639", "0.537494", "0.53610206", "0.53482074", "0.53479534", "0.534081", "0.5336734", "0.5333819", "0.5325838", "0.5311715", "0.5305447", "0.5303301", "0.52953726", "0.52945256", "0.5288281", "0.5271189", "0.5257502", "0.5257399", "0.5255033", "0.5252859", "0.5240367", "0.52334225", "0.5232572", "0.5230903", "0.52250034", "0.5216646", "0.5210716", "0.52073383", "0.520687", "0.5200427", "0.51969737", "0.51816434", "0.5179377", "0.51778364", "0.5172505", "0.5172423", "0.51722103", "0.51718956" ]
0.6761881
9
fetches desired url and write the images url to a new file path
function downloadImageByURL (url ,filePath) { var content = request.get(url) content.pipe(fs.createWriteStream(filePath)); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function downloadImage(url) {}", "function updateURL(imageNum,imageNum2,contributor1,contributor2,issued1,issued2,title1,title2,troveUrl1,troveUrl2){\n url1 = loadedImages[imageNum];\n url2 = loadedImages[imageNum2];\n Image_Path_1 = url1;\n Image_Path_2 = url2;\n contributor11 = contributor1;\n contributor22 = contributor2;\n issued11 = issued1;\n issued22 = issued2;\n title11 = title1;\n title22 = title2;\n troveUrl11 = troveUrl1;\n troveUrl22 = troveUrl2;\n console.log(\"prnt\");\n // console.log(\"first\",contributor11);\n // console.log(\"second\",contributor22);\n // console.log(Image_Path_1);\n // console.log(Image_Path_2);\n\n if (Image_Path_1 === undefined){\n Image_Path_1 = \"default.jpg\";\n }\n if (Image_Path_2 === undefined){\n Image_Path_2 = \"default.jpg\";\n }\n }", "function downloadImagebyURL(url, contributor) {\n request.get(url).pipe(fs.createWriteStream(`./avatar/${contributor}.jpeg`));\n }", "function ParsedURL(parsedInput){\n parsedInput.forEach(function (item) {\n filePath = \"avatars/\" + item.login + \".png\";\n url = item.avatar_url;\n downloadImageByURL(url, filePath);\n })\n\n// this function extracts the filepath and url of the js objects gained from the get request\n// particularly the filepath needs to have a .jpg appended on the end of it or it won't\n// a picture\n}", "function downloadImageByURL(url, filePath) {\n request.get(url)\n .on('error', function (err) {\n throw err;\n })\n .on('response', function (response) {\n console.log('Response Status Code: ', response.statusCode);\n })\n // Save the avatar images by piping the response stream to a directory\n .pipe(fs.createWriteStream(filePath));\n}", "async function download_picture( url, compno, classid, mysql ) {\n\n\t// Check when it was last checked\n\tconst lastUpdated = (await mysql.query( escape`SELECT updated FROM images WHERE class=${classid} AND compno=${compno} AND unix_timestamp()-updated < 86400` ))[0];\n\n\tif( lastUpdated ) {\n\t\tconsole.log( `not updating ${compno} picture` );\n\t\treturn;\n\t}\n\t\n\tconsole.log( `downloading picture for ${classid}:${compno}` );\n fetch( url, { \"headers\": { \"Referer\":\"https://\"+config.NEXT_PUBLIC_SITEURL+\"/\" }} )\n .then( (res) => {\n\t\t\tif( res.status != 200 ) {\n\t\t\t\tconsole.log( ` ${classid}:${compno}: FAI website returns ${res.status}: ${res.statusText}` );\n\t\t\t\tif( res.status == '404' ) {\n\t\t\t\t\treturn undefined;\n\t\t\t\t}\n\t\t\t\tthrow `FAI website returns ${res.status}: ${res.statusText}`;\n\t\t\t}\n\t\t\t\n\t\t\telse {\n\t\t\t\treturn res.buffer()\n\t\t\t}})\n .then( data => {\n\t\t\tif( data ) {\n\t\t\t\tmysql.query( escape`INSERT INTO images (class,compno,image,updated) VALUES ( ${classid}, ${compno}, ${data}, unix_timestamp() )\n ON DUPLICATE KEY UPDATE image=values(image), updated=values(updated)` );\n\t\t\t\tmysql.query( escape`UPDATE pilots SET image = 'Y' WHERE class=${classid} AND compno=${compno}` );\n\t\t\t}\n });\n}", "function downloadImageByURL(url, filePath) {\n request.get(url)\n .on('error', function (err) {\n throw err; \n })\n .pipe(fs.createWriteStream(filePath));\n }", "function downloadImageByURL( url, filePath ){\n request.get( url )\n //Downloader function that runs for every image we want to download.\n .on( 'error', function(err) {\n console.log( 'Error while downloading Image:', err )\n return; //if error occurs, log and end function\n })\n .on( 'end', function() {\n console.log( 'Image downloaded' ) //logs each time an image is successfully downloaded\n })\n .pipe( fs.createWriteStream( filePath ) ); //stores image file in specified folder\n}", "function downloadImageByURL(url, filePath) {\n request.get(url) \n .on('error', function (err) { \n if (err) {\n console.log('error!'); \n } \n })\n // .on('response', function (response) { \n // })\n .pipe(fs.createWriteStream(filePath)); \n}", "function downloadImageByURL(url, filePath) {\n\n request.get(url)\n .on('err', (err) => {\n throw err\n })\n .on('response', (res) => {\n if (res.statusCode !== 200) {\n console.log(`Response Code: ${res.statusCode}`)\n return\n }\n }).pipe(fs.createWriteStream(filePath))\n\n\n}", "async getRedditPic(url) {\n let downloadedImg = document.createElement('img')\n downloadedImg.src = url\n return console.log(downloadedImg)\n }", "function downloadImageByURL(url, path) {\n request.get(url)\n .on('error', function (err) {\n throw err; \n })\n .on('response', function (response) {\n // console.log('Response Status Code: ', response.statusCode);\n // console.log(\" downloading image...\");\n })\n .on('end', function (response) {\n // console.log('download complete!', response)\n })\n if (fs.existsSync('./avatars')) {\n request.get(url).pipe(fs.createWriteStream(`./avatars/${path}.jpg`));\n } else {\n fs.mkdirSync('avatars');\n request.get(url).pipe(fs.createWriteStream(`./avatars/${path}.jpg`));\n }\n}", "function downloadImageByURL(url, filePath) {\n\n request.get(url)\n // .on('error', function (err) {\n // })\n\n .on('response', function (response) {\n console.log(\"Downloading...\", response.statusMessage);\n })\n\n .pipe(fs.createWriteStream(\"./avatars/\" + filePath + \".jpg\")); //filepath where avatar downloads\n\n}", "function downloadImageByURL(url, filePath) {\n request(url).pipe(fs.createWriteStream(\"./avatars/\" + filePath + '.jpg'));\n}", "function downloadImageByURL(url, filepath) {\n request.get(url)\n .on('error', (err) => {\n throw (err);\n })\n .pipe(fs.createWriteStream(filepath)\n .on('finish', () => {\n console.log(\"Image downloaded\");\n })\n .on('error', (err) => {\n throw (err);\n })\n );\n}", "function downloadImageByURL(url, filePath) {\n request.get(url).pipe(fs.createWriteStream(filePath));\n}", "function downloadImageByURL(url, filePath) {\n request.get(url)\n .on('error',function(err){\n throw err;\n })\n .pipe(fs.createWriteStream(filePath));\n}", "function downloadNextImage()\n{\n // stop downloading if requested\n if (!isDownloading)\n {\n return;\n }\n // get a set ID if no valid one is known\n if (!currentDownloadSet || \n !setData.hasOwnProperty(currentDownloadSet) || \n setData[currentDownloadSet].photoList.length == 0)\n {\n currentDownloadSet = null;\n for (var setId in setData)\n {\n if (setData[setId].photoList.length > 0)\n {\n currentDownloadSet = setId;\n break;\n }\n }\n if (!currentDownloadSet)\n {\n // no more sets to download\n stopDownloading();\n return;\n }\n }\n if (setData[currentDownloadSet].photoList.length == 0)\n {\n log(\"No more photos to download for set \" + currentDownloadSet);\n currentDownloadSet = null;\n downloadNextImage();\n return;\n }\n var photoToDownload = setData[currentDownloadSet].photoList.shift();\n\n // create the filename\n var origExt = /[a-zA-Z0-9]+$/.exec(photoToDownload.bigUrl)[0];\n\n var targetFile = setData[currentDownloadSet].saveDirectory.clone();\n targetFile.append(photoToDownload.name+\".\"+origExt);\n photoToDownload.file = targetFile;\n if (targetFile.exists())\n {\n log(\"The image already exists. Skip downloading. \" + targetFile.path);\n photoToDownload.progressBar.setAttribute(\"max\", 1);\n photoToDownload.progressBar.setAttribute(\"value\", 1);\n downloadedPhotos[photoToDownload.id] = photoToDownload;\n downloadNextImage();\n return;\n }\n log(\"Downloading \" + targetFile.path);\n\n // create the file\n targetFile.create(targetFile.NORMAL_FILE_TYPE, 0644);\n // start the download\n var fileDownloader = Components.classes[\"@mozilla.org/embedding/browser/nsWebBrowserPersist;1\"].createInstance(Components.interfaces.nsIWebBrowserPersist); \n // set listener\n fileDownloader.progressListener = {\n onProgressChange: function(aWebProgress, aRequest, aCurSelfProgress, aMaxSelfProgress, aCurTotalProgress, aMaxTotalProgress)\n {\n if (photoToDownload.hasOwnProperty(\"progressBar\"))\n {\n photoToDownload.progressBar.setAttribute(\"max\", aMaxSelfProgress);\n photoToDownload.progressBar.setAttribute(\"value\", aCurSelfProgress);\n }\n },\n onStateChange: function(aWebProgress, aRequest, aStateFlags, aStatus)\n {\n if (aStateFlags & Components.interfaces.nsIWebProgressListener.STATE_STOP)\n {\n // This fires when the load finishes\n downloadedPhotos[photoToDownload.id] = photoToDownload;\n downloadNextImage();\n }\n }\n }\n\n //save file to target \n var imageUri = Components.classes[\"@mozilla.org/network/io-service;1\"].getService(Components.interfaces.nsIIOService).newURI(photoToDownload.bigUrl, null, null);\n fileDownloader.saveURI(imageUri,null,null,null,null,targetFile); \n}", "function downloadImageByURL(url, filePath) {\n // Check that the write directory exists\n var dirname = path.dirname(filePath);\n if (!fs.existsSync(dirname)) {\n fs.mkdirSync(dirname);\n }\n // Request the file and pipe to stream\n request(url).pipe(fs.createWriteStream(filePath)\n .on('end', function () {\n console.log(`Finished writing to ${filePath}`);\n }))\n}", "function downloadImageByURL(url, filePath) {\n request.get(url)\n// We will throw an error and log it if we experience an issue.\n .on('error', function (err) {\n throw err;\n })\n// Let's tell the user as each image finishes downloading to our local file system.\n .on('end', function() {\n console.log('Image download complete.');\n })\n// This downloads the image to the file path we specify.\n .pipe(fs.createWriteStream(filePath));\n\n}", "function downloadImageByURL(url, filePath) {\n request.get(url)\n .on('error', function (err) {\n throw err;\n })\n .on('response', function (response) {\n console.log('Response Status Code: ', response.statusCode);\n })\n .pipe(fs.createWriteStream(filePath));\n}", "async function downloadImages()\n{\n if ( !await fileExists( `${advTitle}/images` ) ) {\n await fs.mkdir( `${advTitle}/images` );\n }\n\n let imgPath = `${advTitle}/images`;\n for ( let image of myImages ) {\n if ( !await fileExists( `${imgPath}/${image.img}` ) ) {\n console.log( ` download: image ${image.base}` );\n if ( image.url.match( /^http/ ) ) {\n\tawait downloadFile( image.url, `${imgPath}/${image.base}` );\n\tawait convertWebp( `${imgPath}/${image.base}`, `${imgPath}/${image.img}` );\n } else {\n\t// simply copy\n\tlet fname = findFullPath( image.url );\n\tawait fs.copyFile( fname, `${imgPath}/${image.base}` );\n\tawait convertWebp( `${imgPath}/${image.base}`, `${imgPath}/${image.img}` );\n }\n }\n }\n}", "function downloadImageByURL(url, filePath) {\n\n request.get(url)\n .on('error', function (err) {\n throw err;\n })\n .on('response', function (response) {\n console.log('Response Status Code: ', response.statusCode);\n })\n .pipe(fs.createWriteStream(filePath));\n\n}", "function saveImageToDisk(url, localPath) {\n const file = fs.createWriteStream(localPath);\n https.get(url, (response) => {\n response.pipe(file);\n });\n}", "function setSrc(url){\r\n\r\n if (typeof(Storage) !== \"undefined\") {\r\n window.localStorage.setItem(\"img_url\",url[0]);\r\n window.localStorage.setItem(\"img_url_living\",url[1]);\r\n window.localStorage.setItem(\"img_url_dining\",url[2]);\r\n window.localStorage.setItem(\"img_url_living_2\",url[3]);\r\n }\r\n\r\n}", "static pasteImageURL(image_url) {\n let filename = image_url.split(\"/\").pop().split(\"?\")[0];\n let ext = path.extname(filename);\n let imagePath = this.genTargetImagePath(ext);\n if (!imagePath)\n return;\n let silence = this.getConfig().silence;\n if (silence) {\n Paster.downloadFile(image_url, imagePath);\n }\n else {\n let options = {\n prompt: \"You can change the filename. The existing file will be overwritten!\",\n value: imagePath,\n placeHolder: \"(e.g:../test/myimg.png?100,60)\",\n valueSelection: [\n imagePath.length - path.basename(imagePath).length,\n imagePath.length - ext.length,\n ],\n };\n vscode.window.showInputBox(options).then((inputVal) => {\n Paster.downloadFile(image_url, inputVal);\n });\n }\n }", "function loadImage(){\n $(\".image-box\").attr(\"src\", displayedImg.download_url);\n}", "function getUrlPic(picture) { return \"url(\"+host+picture+\")\"; }", "function getUrlPic(picture) { return \"url(\"+host+picture+\")\"; }", "async function saveImageToDisk(url, filename) {\n await fetch(url)\n .then((res) => {\n const dest = fs.createWriteStream(filename)\n res.body.pipe(dest)\n })\n .catch((err) => {\n console.log(err)\n })\n}", "function downloadImageByURL(url, filePath) {\n request.get(url)\n .on('error', function(err) {\n throw err;\n })\n .on('response', function(response) {\n console.log('Downloading image:', url);\n })\n .pipe(fs.createWriteStream(filePath))\n .on('finish', function(finish){\n console.log('Download complete for image:', url);\n });\n}", "function fetchURL(qno){\r\n// i ll write the logic behind fetchin the image from folders...for now i am hardcoding url of images\r\n// 1) modify pending_images tabel to add bundle_id\r\n// 2) select top 10 pending_images which are not evaluated and correspond to this bundle_id (pending_images)\r\n// 3) select see image table to see if evaluation_done = 0 then only fetch url from (image) table\r\n// 4) evaluation complete hote hi pending_images se remove plus insert into completed table \r\n//var imageurls= [\"1pi12cs002/t112CS4011a2016.jpg\",\"1pi12cs003/t112CS4011a2016.jpg\",\"1pi12cs004/t112CS4011a2016.jpg\",\"1pi12cs005/t112CS4011a2016.jpg\",\"1pi12cs008/t112CS4011a2016.jpg\"];\r\n\t/*var xhr = new XMLHttpRequest();\r\n\txhr.onreadystatechange = getURL;\r\n\txhr.open(\"GET\",\"http://localhost/REAP/dataFetchingFiles/getImageURL.php?bundle_id=\"+bundle_id+\"&qno=\"+qno,true);\r\n\txhr.send(); \r\n\tvar imageurls= [\"1pi12cs003/t112CS4011a2016.jpg\",\"1pi12cs004/t112CS4011a2016.jpg\",\"1pi12cs005/t112CS4011a2016.jpg\",\"1pi12cs008/t112CS4011a2016.jpg\"];\r\n\tvar imageIds = [10004,10005,10006,10007,10008];\r\n\tvar imageDetails ={\"imageurls\":imageurls,\"imageids\":imageIds};\r\n\tif(questionNumber != \"1a\") \r\n \t\treturn null; \r\n\treturn imageDetails;*/\r\n\r\n}", "function retrieveImageUrl(memoizeRef, filename){\n /*\n var storageRef = firebase.storage().ref();\n var spaceRef = storageRef.child('images/photo_1.png');\n var path = spaceRef.fullPath;\n var gsReference = storage.refFromURL('gs://test.appspot.com')\n */\n memoizeRef.child(filename).getDownloadURL().then(function(url) {\n var test = url;\n console.log(test)\n var imageLoaded = document.createElement(\"img\");\n imageLoaded.src = test;\n imageLoaded.className = \"w3-image w3-padding-large w3-hover-opacity\";\n document.getElementById(\"chatDisplay\").prepend(imageLoaded);\n\n imageLoaded.setAttribute(\"onclick\", \"onClick(this)\");\n }).catch(function(error) {\n\n });\n}", "function downloadImageByURL(url, filePath) {\n request.get(url)\n .on('error', function (err) {\n throw err;\n })\n .pipe(fs.createWriteStream(filePath));\n}", "async function download(url) {\n return Jimp.read(url)\n .then(image => {\n const width = image.bitmap.width;\n const height = image.bitmap.height;\n const format = image.getExtension();\n const uniqueName = uid();\n const smallFileName = uniqueName + '.png';\n const fileName = uniqueName + '.' + format;\n\n return image\n // Save original\n .writeAsync(`${outputFolder}/original/${fileName}`)\n .then(() => image\n // Do stuff with the image.\n .resize(120, Jimp.AUTO)\n // Save small image\n .writeAsync(`${outputFolder}/small/${smallFileName}`)\n )\n .then(() => {\n return {\n url,\n fileName,\n smallFileName,\n width,\n height,\n format\n }\n })\n }\n )\n .catch(err => {\n console.log('ERROR', err)\n })\n}", "function set_image_src(image_ref, image_element) {\n image_ref.getDownloadURL()\n .then( function(url) {\n image_element.src = url;\n })\n .catch( function (error) {\n console.log(error.message);\n })\n}", "function download_image(search_res_data, res){\n //Variable to hold the image name.\n let imag_name = search_res_data.artists.items[0].name;\n imag_name = imag_name.replace(/\\s+/g, '');\n\n //Variable to hold the image path.\n const img_path = './artists/' + imag_name + '.jpg';\n\n //Variable to hold the url to the image.\n const img_url = search_res_data.artists.items[0].images[0].url;\n\n //The html data to show the user.\n let webpage = `<h1 style=\"text-align:center;\">Name: ${search_res_data.artists.items[0].name}</h1><p style=\"text-align:center;\">Genres: ${search_res_data.artists.items[0].genres.join()}</p><img src = \"./artists/${imag_name}.jpg\"/>`;\n\n //Check to see if image is downloaded already.\n if(fs.existsSync(img_path)){\n res.end(webpage);\n }\n\n //If image doesn't exist, then download the image required for the artist.\n else {\n let img_req = https.get(img_url, image_res => {\n let new_img = fs.createWriteStream(img_path, {'encoding': null});\n image_res.pipe(new_img);\n new_img.on('finish', function () {\n console.log('Download Finised');\n res.end(webpage);\n });\n });\n\n img_req.on('error', (e) => {\n console.error(e);\n });\n\n img_req.end();\n }\n}", "function getUrlPic(picture) { return \"url(\"+picture+\")\"; }", "function linksUrlToImg (categorie, url) {\n\tconst imgs = document.getElementsByClassName(categorie);\n\tgetUrlImages(url).then(function (map){\n\t\tvar i = 0;\n\t\tfor (let img of imgs) {\n\t\t\t// link url image to img[index]\n\t\t\tvar urlImg = Array.from(map.values())[i];\n\t\t\timg.src = urlImg;\n\t\t\t// link id to img[index]\n\t\t\tvar idImg = Array.from(map.keys())[i];\n\t\t\timg.id = idImg;\n\t\t\ti ++;\n\t\t}\n});\n}", "function obtainExternalPhotos() {\n const random = Math.floor(Math.random() * (paths.length));\n const pathImage = path.join(__dirname, \"../images/\" + paths[random])\n return pathImage;\n}", "function downloadImageByURL(url, filePath) {\n request.get(url)\n .on('error', function (err) {\n throw err;\n })\n .on('response', function (response) {\n console.log('Response Status Code: ', response.statusCode);\n })\n .on('end', function() {\n console.log(\"Download complete\");\n })\n\n .pipe(fs.createWriteStream(filePath));\n}", "function fetchImgs() {\n const imgUrl = \"https://dog.ceo/api/breeds/image/random/4\";\n fetch(imgUrl)\n .then(resp => resp.json())\n .then(results => insertImgs(results)) \n}", "function getImage(url, path) {\n var requestConfig = {\n url: url,\n method: 'GET',\n headers: {\n 'User-Agent': 'request'\n },\n json: true,\n }\n var stream = request(requestConfig, function(err, response, body) {\n if (err) {\n throw err;\n };\n });\n // Pipes the request to a stream and writes to the given path.\n stream.pipe(fs.createWriteStream(path));\n}", "function getPic() {\n fetch(baseUrl)\n .then(function (response) {\n if (!response.ok) {\n console.log(response);\n return new Error(response);\n }\n console.log(\"Response:\", response);\n\n console.log(\"Meep:\", response.url);\n\n //GRAB PHOTOGRAPHER\n\n var deepest = new URL(response.url).pathname.split('/')\n var id = deepest[2]\n console.log(\"Deepest:\", id);\n var idUrl = 'https://picsum.photos/id/0/info';\n var rep = idUrl.replace(\"0\", id);\n console.log(\"Replaced:\", rep);\n var grayscaleUrl = 'https://picsum.photos/id/0/450/350.jpg?grayscale';\n var repGrayscale = grayscaleUrl.replace(\"0\", id);\n console.log(\"repGrayscale:\", repGrayscale);\n var blurURL = 'https://picsum.photos/id/0/450/350.jpg?blur';\n var repBlur = blurURL.replace(\"0\", id);\n console.log(\"repBlur:\", repBlur);\n\n document.getElementById(\"photographer\").innerHTML = \"\"\n const section = document.querySelector('#photographer');\n fetch(rep)\n .then(function (result) {\n console.log(\"photographer:\", result)\n return result.json()\n })\n .then(function (json) {\n console.log(\"photographer:\", json.author);\n displayResults(json.author);\n })\n\n //GRAYSCALE FETCH\n\n document.getElementById('button2').addEventListener(\"click\", function () {\n fetch(repGrayscale)\n .then(function (response2) {\n if (!response2.ok) {\n console.log(response2);\n return new Error(response2);\n }\n console.log(\"Response2:\", response2);\n\n console.log(\"Meep2:\", response2.url);\n return response2.blob();\n })\n\n .then(function (photoBlob) {\n console.log(\"My Blob2:\", photoBlob)\n var objectURL = URL.createObjectURL(photoBlob);\n console.log(\"Object URL2:\", objectURL);\n randomImage.src = objectURL;\n\n console.log(\"randomImage2.src:\", randomImage.src);\n\n\n })\n })\n\n //BLUR FETCH\n document.getElementById('button3').addEventListener(\"click\", function () {\n fetch(repBlur)\n .then(function (response2) {\n if (!response2.ok) {\n console.log(response2);\n return new Error(response2);\n }\n console.log(\"Response2:\", response2);\n\n console.log(\"Meep2:\", response2.url);\n return response2.blob();\n })\n\n .then(function (photoBlob) {\n console.log(\"My Blob3:\", photoBlob)\n var objectURL = URL.createObjectURL(photoBlob);\n console.log(\"Object URL3:\", objectURL);\n randomImage.src = objectURL;\n\n console.log(\"randomImage3.src:\", randomImage.src);\n\n })\n })\n\n //END GRAYSCALE FETCH, BACK TO GRAB PHOTOGRAPHER\n\n\n function displayResults(json) {\n let photographer = json;\n let heading = document.createElement('h1');\n section.appendChild(heading);\n heading.textContent = photographer;\n }\n\n //END GRAB PHOTOGRAPHER \n\n return response.blob();\n })\n\n .then(function (photoBlob) {\n console.log(\"My Blob:\", photoBlob)\n var objectURL = URL.createObjectURL(photoBlob);\n console.log(\"Object URL:\", objectURL);\n randomImage.src = objectURL;\n\n console.log(\"randomImage.src:\", randomImage.src);\n\n })\n\n .catch(function (err) {\n console.log(err);\n })\n}", "function readURLUp(input) {\n if (input.files && input.files[0]) {\n var reader = new FileReader();\n \n reader.onload = function (e) {\n //id <img scr=\"#\"\n $('#imagePreviewUpdate1').attr('src', e.target.result);\n }\n \n reader.readAsDataURL(input.files[0]);\n }\n }", "function addImageToScreen(myURL) {\n\n}", "function readURL(input) {\n\t if (input.files && input.files[0]) {\n\t var reader = new FileReader();\n\n\t reader.onload = function (e) {\n\t jQuery('#banner-image-edit').attr('src', e.target.result);\n\t }\n\n\t reader.readAsDataURL(input.files[0]);\n\t }\n\t}", "function downloadImageByURL(url, filePath) {\n request(url)\n\n //if url is invalid, throws the error.\n .on('error', function(err) {\n throw err;\n })\n\n //if response is valid, console logs download status.\n .on('response', function(response) {\n console.log(\"downloading images....\");\n console.log(response.statusCode, response.statusMessage, response.headers['content-type'])\n\n })\n\n //on finish, console logs completed message.\n .on('end', function(respose) {\n console.log(\"download complete\");\n })\n\n //pipes the result to filePath and saves it if it already exists\n // or creates the file if it doesn't exist.\n .pipe(fs.createWriteStream(filePath));\n}", "function populateURLS() {\n urls.push('https://s3.amazonaws.com/limbforge/' + this.specs.design + \"/Ebe_forearm_\" + this.specs.hand + \"/forearm_\" + this.specs.hand + \"_C4-\" + this.specs.c4 + \"_L1-\" + this.specs.l1+ '.stl');\n // add on terminal device adaptor\n if (this.specs.design == \"EbeArm\"){\n urls.push('https://s3.amazonaws.com/limbforgestls/EbeArm/EbeArm_wrist_unit+v1.stl');\n }\n }", "function setImgFilepath(){\n Item.imgEl1.src = Item.objStore[Item.prevNum[0]].filepath;\n Item.imgEl1.alt = Item.objStore[Item.prevNum[0]].name;\n Item.imgEl2.src = Item.objStore[Item.prevNum[1]].filepath;\n Item.imgEl2.alt = Item.objStore[Item.prevNum[1]].name;\n Item.imgEl3.src = Item.objStore[Item.prevNum[2]].filepath;\n Item.imgEl3.alt = Item.objStore[Item.prevNum[2]].name;\n}", "function readURL(input,x) \n{\n let imagehold=x;\n if (input.files && input.files[0]) \n {\n let reader = new FileReader();\n\n reader.onload = function (e) \n {\n $('#'+imagehold).attr('src', e.target.result);\n };\n\n reader.readAsDataURL(input.files[0]);\n }\n }", "function getImage() {\n fetch(\"https://unsplash.it/900/600\").then(response => {\n // Fetching the Unsplash link\n imageDiv.innerHTML = `<img src=\"${response.url}\">`; // Embedding the photo url inside the div\n imageLink = `${response.url}`; // Setting the url as a variable so it can be stored\n });\n}", "function readURL(input) {\n\n if (input.files && input.files[0]) {\n var reader = new FileReader();\n\n reader.onload = function (e) {\n $('#img1').attr('src', e.target.result);\n }\n\n reader.readAsDataURL(input.files[0]);\n }\n }", "function genImageURL(imageDatasArr){\n\tfor (var i = 0; i < imageDatasArr.length; i++) {\n\t\tvar singleImageData = imageDatasArr[i];\n\t\tsingleImageData.imageURL = require('../images/'+singleImageData.fileName);\n\n\t\timageDatasArr[i] = singleImageData;\n\t}\n\treturn imageDatasArr;\n}", "load_from_url() {\n this.download_btn.prop(\"disabled\", 1);\n\n const url = this.url_input.val();\n\n let xhr = new XMLHttpRequest();\n\n console.info(\"Loading remote image from\", url)\n\n xhr.open(\"GET\", url, true);\n xhr.responseType = \"blob\";\n\n xhr.onload = (e) => {\n this.fname = e.target.responseURL.replace(/\\\\/g,'/').replace(/.*\\//, '').split('.')[0];\n\n let file_reader = new FileReader();\n file_reader.onload = (e) => { this.load_image(e, this); };\n file_reader.readAsArrayBuffer(e.target.response);\n };\n\n xhr.send();\n }", "function RenderUrlsToFile (urls, callbackPerUrl, callbackFinal) {\n var getFilename, next, page, retrieve;\n var urlIndex = 0;\n var webpage = require(\"webpage\");\n getFilename = function() {\n return imagesDir + urlIndex + \".png\";\n };\n next = function(status, url, file) {\n page.close();\n callbackPerUrl(status, url, file);\n return retrieve();\n };\n retrieve = function() {\n if (urls.length > 0) {\n urlIndex++;\n var url = urls.shift();\n page = webpage.create();\n page.loadImages = true;\n page.webSecurityEnabled = false;\n page.javascriptCanOpenWindows = false;\n page.javascriptCanCloseWindows = false;\n page.paperSize = paperSize;\n page.viewportSize = viewportSize;\n page.settings.userAgent = userAgent;\n page.customHeaders = customHeaders;\n page.onResourceRequested = onResourceRequested;\n return page.open(url, function(status) {\n var file = getFilename();\n if (status === \"success\") {\n return window.setTimeout((function() {\n page.render(file);\n return next(status, url, file);\n }), timeout);\n } else {\n return next(status, url, file);\n }\n });\n } else {\n return callbackFinal();\n }\n };\n return retrieve();\n}", "function download(id) {\n var afterresp = request.post(uri + id).on('response', function () {\n if (afterresp.response.statusCode == 200) {\n console.log('Downloaded Image: ' + id + '');\n var filename = './out/imageRepo/' + id + '.png';\n afterresp.pipe(fs.createWriteStream(filename));\n }\n else {\n console.log('Bad image: ' + id + '');\n }\n if (current != last) {\n current++;\n download(current);\n }\n else {\n console.log('Done!');\n }\n });\n}", "function downloadImageByURL(url, filePath) {\n request.get(url)\n .on('error', function (err) {\n throw err; \n })\n\n .on('response', function (response) {\n console.log('Response Status Message: ' + response.statusMessage +\n ' of Content Type: ' + response.headers['content-type']);\n })\n\n .pipe(fs.createWriteStream(filePath));\n}", "downloadPNGs()\n {\n\t\t\n var directory = this.dir;\n\t\t\n\t\t//Get HTML from URL provided\n https.get(this.url, function(response)\n {\n parseResponse(response);\n })\n\n var parseResponse = function(response)\n {\n\t\t\t//Concatenate site HTML\n var data = \"\";\n response.on('data', function(chunk)\n {\n data += chunk;\n });\n var count = 0;\n var imgPaths = [];\n response.on('end', function(chunk)\n {\n\t\t\t\t//Initialize HTMLParser\n var parsedData = new htmlparser.Parser(\n {\n onattribute: function(name, value)\n {\n\t\t\t\t\t\t//Check src tags to check if the source image is a .png file\n if (name === \"src\" && value.substr(value.length - 3) === \"png\")\n {\n imgPaths.push(value);\n count++;\n }\n },\n onend: function()\n {\n console.log('Downloading...');\n }\n },\n {\n decodeEntities: true\n });\n parsedData.write(data);\n parsedData.end();\n\n var file;\n var fileName;\n var download;\n\n\t\t\t\t//Create function to download image\n\t\t\t\tdownload = function(uri, filename, callback)\n {\n request(uri).pipe(fs.createWriteStream(filename)).on('close', callback);\n };\n\t\t\t\t\n\t\t\t\t//Loop to download all images in url to local directory\n for (var i = 0; i < imgPaths.length ; i++)\n {\n\t\t\t\t\t//Split to get the last part of the image path(fileName)\n fileName = imgPaths[i].split('/');\n file = fs.createWriteStream(directory + \"/\" + fileName[fileName.length - 1]);\n\t\t\t\t\t\n download(imgPaths[i], directory + \"/\" + fileName[fileName.length - 1], function(){});\n }\n\t\t\t\t//Display amount of images as well as the directory downloaded to\n\t\t\t\tconsole.log( count + ' png images saved to : ' + directory);\n });\n }\n }", "function readURL(input) {\n if (input.files && input.files[0]) {\n var reader = new FileReader();\n reader.onload = function (e) {\n $('#img').attr('src', e.target.result);\n }\n reader.readAsDataURL(input.files[0]);\n }\n }", "function findImageURL() {\n for (var _i = 0, _a = triviaData.includes.Asset; _i < _a.length; _i++) {\n var asset = _a[_i];\n if (currentQuestion.fields.image.sys.id == asset.sys.id) {\n return \"https:\" + asset.fields.file.url;\n }\n }\n return;\n}", "function setFile(url){\n\tfile = url;\n}", "function setimgsrc() {\n document.getElementById(\"mainimg\").src = \"http://\" + window.location.hostname + \":3001/?action=stream\";\n }", "function getLogoUrl2(url){\n\t$(\"#addLogoModal\").modal(\"hide\");\n\n\t$(\"#edit_ .froala-element p\").append( '<img src=\"'+window.location.origin+url+'\" />' );\n\n}", "function readURL(input) {\n if (input.files && input.files[0]) {\n var reader = new FileReader();\n reader.onload = function (e) {\n // Use the input element's name attrbute to select and\n // update the image element with matching id\n $('#' + input.name).attr('src', reader.result); //e.target.result\n }\n reader.readAsDataURL(input.files[0]);\n }\n }", "function scrapeimg(name,element){\n var globalurl;\n var scraperes = [];\n element.forEach(function(img){\n scraperes.push($(document).find(img));\n });\n var search=name.split(\"-\")[0].split(\"&\")[0].trim().split(\",\")[0].trim().split(\"ft.\")[0].trim().split(\"vs\")[0].trim().split(\"Ft.\")[0].trim().split(\"feat.\")[0].trim().split(\"Feat.\")[0].trim().split(' ').join('-');\n search = deUmlaut(search);\n var url = encodeURIComponent('https://genius.com/artists/' + search);\n ////console.log(search);\n ////console.log(url);\n ////////console.log(name);\n ////////console.log(search);\n ////////console.log(url);\n fetch(`https://api.allorigins.win/get?url=${url}`)\n .then(response => {\n if (response.ok) return response.json()\n throw new Error('Network response was not ok.')\n })\n .then(function(data){\n //var res = data.find();\n var base64;\n var quick = data.contents;\n ////////console.log(quick);\n var index = quick.search(\"user_avatar\");\n var quick = quick.substring(index,quick.lenght);\n index = quick.search(\"url\\\\('\");\n quick = quick.substring(index+5,quick.lenght);\n var imgurl = quick.split(\"'\")[0];\n //imgurl='https://api.allorigins.win/get?url=${url' + imgurl + '}';\n ////////console.log(imgurl);\n globalurl = imgurl;\n /*\n try{\n toDataURL(\n imgurl,\n function(dataUrl) {\n base64 = dataUrl;\n scraperes.forEach(image => {\n if(dataUrl){\n image.attr(\"src\",dataUrl);\n //console.log(\"base64\");\n }\n else{\n image.attr(\"src\",imgurl);\n //console.log(\"img source\");\n }\n\n }); \n });\n }\n catch(e){\n //console.log(\"getting dominant color failed\");\n }\n */\n scraperes.forEach( image => image.attr(\"src\",imgurl) ); \n //////console.log(scraperes);\n\n ////console.log(imgurl);\n //scraperes.each(function() {\n // $(this).prop(\"src\",imgurl))\n // $(this).children('.time').after($('.inner'));\n //});\n //$(scraperes).prop(\"src\",imgurl);\n });\n $(element[0])\n .on('load', function() { \n\n })\n .on('error', function(){\n setTimeout(function(){\n $(this).prop(\"src\",\"https://cdn.discordapp.com/attachments/331151226756530176/725817255484719124/AURFavicon.webp\");\n },5000);\n });\n}", "function readURL(input, id) {\n if (input.files && input.files[0]) {\n var reader = new FileReader();\n \n reader.onload = function(e) {\n $(id).attr('src', e.target.result).css({'width': CAPTURE_IMG_WIDTH, 'height': CAPTURE_IMG_HEIGHT});\n }\n \n reader.readAsDataURL(input.files[0]);\n }\n}", "function addPathToImage() {\n $(ctrl.imageTags).each(function (index) {\n if (ctrl.imageTags[index].hasAttribute('id')) {\n var imageSrc = ctrl.imageTags[index].getAttribute('id');\n $(ctrl.imageTags[index]).attr('src', oDataPath + \"/Asset('\" + imageSrc + \"')/$value\");\n }\n });\n }", "function updateImg() {\n const $url = $('#newPinUrl');\n // If URL field is empty, don't do anything\n if ($url.val() === '') return;\n // Otherwise, continue with validation\n let thisUrl = $url.val().trim().replace(/['\"]/g, '');\n // Prepend URL with protocol, if necessary\n if (!thisUrl.toLowerCase().startsWith('http')) thisUrl = `https://${thisUrl}`;\n $url.val(thisUrl);\n // If URL is new and appears valid, update the image\n if (thisUrl !== lastUrl) {\n $('#newPinImg').attr('src', thisUrl);\n lastUrl = thisUrl;\n }\n}", "function updateImage(url) {\n //Select the image from the htnl\n var image = document.getElementById('myImage');\n\n //Set to default img\n if (url === null | typeof url === \"undefined\") {\n url = defaultLargeBoxArt;\n }\n\n //Update the image in the html\n image.src = url;\n}", "function readURL(input){\n if(input.files && input.files[0]){\n var reader = new FileReader();\n reader.onload = function(e){\n $('#showimages').attr('src', e.target.result);\n }\n reader.readAsDataURL(input.files[0]);\n }\n}", "function setSpeakerImage(img, id) {\n let url = location.origin + \"/api/speakers/\" + id + \"/image\";\n fetch(url)\n .then(function (response) {\n if (response.ok) {\n return response.blob();\n }\n })\n .then(function (blob) {\n const objUrl = URL.createObjectURL(blob);\n img.src = objUrl;\n })\n .catch(function (err) {\n console.log(err);\n });\n}", "function downPic(url){\n var urls = [];\n var path = 'D:/work_nodejs/mynode/spider/kenan/';\n\n request(url, function (err, res, body) {\n if (!err && res.statusCode == 200) {\n var html = iconv.decode(body, 'utf-8');\n //console.log(html);\n var $ = cheerio.load(html, {decodeEntities: false});\n var tableContent = $('#div_mobi');\n //console.log(tableContent.html());\n\n tableContent.find('tr td a').each(function(){\n var url_download_page = $(this).attr('href');\n //console.log( url_download_page );\n\n request(url_download_page, function (err,res,body) { //打开下载页\n if (!err && res.statusCode == 200) {\n var html_down_load_page = iconv.decode(body,'utf-8');\n //console.log(html_down_load_page);\n var $ = cheerio.load(html_down_load_page, {decodeEntities: false});\n var _this = $('#vol_downimg').find('a')[0];\n var url_down = $(_this).attr('href');\n var file_name = $(_this).html().replace(/10250-[0-9]{4}-/,'');\n console.log(url_down);\n saveFile(url_down,path+file_name);\n console.log(file_name+' is over.');\n }\n });\n });\n\n \n \n\n }else{\n console.log('open the url is error');\n }\n });\n \n console.log(111111111);\n console.log(urls);\n}", "function readURL(input) {\n\t if (input.files && input.files[0]) {\n\t var reader = new FileReader();\n\n\t reader.onload = function (e) {\n\t $('#image-preview').attr('src', e.target.result);\n\t storeTheImage();\n\t }\n\t reader.readAsDataURL(input.files[0]);\n\t }\n\t}", "function readURL(input) {\n if (input.files && input.files[0]) {\n var reader = new FileReader();\n \n reader.onload = function (e) {\n //id <img scr=\"#\"\n $('#imagePreview').attr('src', e.target.result);\n }\n \n reader.readAsDataURL(input.files[0]);\n }\n }", "async function getNewImage() {\n let randomNumber = Math.floor(Math.random() * 10);\n return fetch(unsplashURL)\n .then((response) => response.json())\n .then((data) => {\n let allImages = data.results[randomNumber];\n return allImages.urls.regular;\n });\n}", "function downloadImage(_url, _fn)\n{\n //console.log(_url);\n var request = https.get(_url, function(response) {\n if (response.statusCode === 200) {\n var file = fs.createWriteStream(\"./\"+searchTerm+\"/\"+_fn);\n response.pipe(file);\n }\n // Add timeout.\n request.setTimeout(12000, function () {\n request.abort();\n });\n });\n}", "function createURL(data) {\n for (let i = 0; i < data.photos.photo.length; i++) {\n imageArray.push(\"https://farm\" + data.photos.photo[i].farm + \".staticflickr.com/\" + data.photos.photo[i].server + \"/\" + data.photos.photo[i].id + \"_\" + data.photos.photo[i].secret + \".jpg\")\n }\n displayImages(imageArray)\n return imageArray\n}", "function downloadFileToLocation(uri, filePath, fileName,num, cb){\n\tvar saveDir = '/home/hbthegreat/teamsite/assets/images' + filePath;\n\tvar fullFilePath = saveDir+ '/'+fileName;\n\n\tvar http = require('http');\n\tvar fs = require('fs');\n\tvar mkdirp = require('mkdirp');\n\n\tmkdirp.sync(saveDir, function(err) {\n\t\tconsole.log('directory not created');\n\t\tconsole.log(err);\n\t});\n\n\tvar file = fs.createWriteStream(fullFilePath);\n\tvar request = http.get(uri, function(response) {\n\t\tresponse.pipe(file);\n\t\tfile.on('finish', function() {\n\t \tfile.close(cb(num)); // close() is async, call cb after close completes.\n\t\t});\n\t}).on('error', function(err) { // Handle errors\n\t\t\tfs.unlink(fullFilePath); // Delete the file async. (But we don't check the result)\n\t\t\tif (cb) cb(err.message);\n\t});\n}", "async function storePhotos(url) {\n fetch(url)\n .then((response) => response.json())\n .then((data) => {\n for (let i = 0; i <= 4; i++) {\n //individual url to pic\n let pic = data.results[i].urls.regular;\n\n //add pics to list\n let li = document.createElement(\"li\");\n\n //event listener once you select an image to view\n list.appendChild(li).addEventListener(\"click\", () => {\n text.classList.add(\"hidden\");\n photos.classList.remove(\"hidden\");\n photos.src = pic;\n });\n li.classList.add(\"list-pic\");\n li.style.backgroundImage = `url(${pic})`;\n }\n })\n .catch(() => {\n photos.classList.add(\"hidden\");\n text.classList.remove(\"hidden\");\n text.innerHTML =\n \"Could not find any photos with that, try somthing else.\";\n setTimeout(() => {\n text.innerHTML =\n \"Search for a photo and select one to get a better view.\";\n }, 6180);\n });\n }", "function getLogoUrl3(url,eID){\n\t$(\"#addLogoModal\").modal(\"hide\");\n\t$(eID+\" .froala-element p\").append( '<img src=\"'+window.location.origin+url+'\" />' );\n\n\n}", "function setUrl(src, str) {\n\t\t\t\tvar a = src.split(\"/\");\n\t\t\t\ta[a.length - 2] = str;\n\t\t\t\treturn a.join('/');\n\t\t\t}", "function saveItAsImage()\n {\n let image = $cvs.get(0).toDataURL(\"image/png\").replace(\"image/png\", \"image/octet-stream\");\n //locally save\n window.location.href=image;\n }", "function prepareUrl(imgObject) {\n return 'https://farm8.staticflickr.com/' + imgObject.server + '/'+ imgObject.id + '_' + imgObject.secret + '.jpg';\n}", "getImageUrls(imageUrl){\n // http://www.pickledbraingames.com/temp/images/0258b0_tn.jpg\n\n const fileRegEx = /^(http:\\/\\/www.pickledbraingames.com\\/temp\\/images\\/)(.*)_(lg|md|sm|tn).jpg$/;\n let matches = fileRegEx.exec(imageUrl);\n\n if(matches !== null){\n return({\n id: Math.floor(Math.random() * 10000), // This is a temporary id used to index the images for deletion ect. It is not saved to the database\n url_zoom: `${matches[1]}${matches[2]}_lg.jpg`,\n url_standard: `${matches[1]}${matches[2]}_md.jpg`,\n url_thumbnail: `${matches[1]}${matches[2]}_sm.jpg`,\n url_tiny: `${matches[1]}${matches[2]}_tn.jpg`,\n });\n }\n else{\n throw new Error('Photo filename does not match: ' + imageUrl);\n }\n }", "function readURL(input) {\n\n if (input.files && input.files[0]) {\n\n var reader = new FileReader();\n\n reader.onload = function (e) {\n $('#imgUser').attr('src', e.target.result);\n }\n\n reader.readAsDataURL(input.files[0]);\n }\n\n }", "function getImageUrl () {\n var query3 = {\n APIKey: 'pq4nxcZNwNc8dLc43cK72X27H2Vnt9Q2'\n }\n $.getJSON(quizState.returnedRawImageEndpoint, query3, function(returnedText) {\n quizState.quizImage = returnedText.Response.ImageSizeDetails.ImageSizeXLarge.Url;\n //testing\n questionObject[quizState.questionNumberArray[incr]].push(quizState.quizImage);\n getAlbumNameFromApi();\n });\n}", "function readURL(input, img) {\n if (input.files && input.files[0]) {\n var reader = new FileReader();\n\n reader.onload = function (e) {\n img.attr('src', e.target.result);\n }\n reader.readAsDataURL(input.files[0]);\n }\n }", "function readURL2(input) {\n if (input.files && input.files[0]) {\n var reader = new FileReader();\n \n reader.onload = function(e) {\n $('#fatherimg').attr('src', e.target.result);\n }\n \n reader.readAsDataURL(input.files[0]);\n }\n }", "function readURL(input) {\n if (input.files && input.files[0]) {\n var reader = new FileReader();\n \n reader.onload = function(e) {\n $('#studentimg').attr('src', e.target.result);\n }\n \n reader.readAsDataURL(input.files[0]);\n }\n }", "function retrievePictures(coords) {\n console.log(\"Lat: \" + coords.latitude)\n console.log(\"Lon: \" + coords.longitude)\n imageArray = []\n const url = \"https://shrouded-mountain-15003.herokuapp.com/https://flickr.com/services/rest/?api_key=d3bfc1adf01a36079d0c6711030a97e8&format=json&nojsoncallback=1&method=flickr.photos.search&safe_search=1&per_page=5&lat=\" + coords.latitude + \"&lon=\" + coords.longitude + \"&text=outdoors\"\n\n fetch(url)\n\n .then(function(responseObject) {\n return responseObject.json()\n })\n .then(function(data) {\n createURL(data)\n return data\n })\n}", "function downloadImages(id) {\n\tvar afterresp = request.post(uri_img + id).on('response', function () {\n\t\tif (afterresp.response.statusCode == 200) {\n\t\t\tvar got = item_count+1;\n\t\t\tconsole.log('Downloaded Image (' + got + '/'+ imageList.length + '): ' + id);\n\t\t\tvar filename = dir_images + '/' + id + '.png';\n\t\t\tafterresp.pipe(fs.createWriteStream(filename));\n\t\t}\n\t\telse {\n\t\t\tconsole.log('Bad image: ' + id + '');\n\t\t}\n\t\titem_count++;\n\t\tif (item_count < imageList.length) {\n\t\t\tdownloadImages(imageList[item_count]);\n\t\t}\n\t\telse {\n\t\t\tconsole.log('FINISHED!!!');\n\t\t}\n\t});\n}", "function saveURLToCurrentFolder(fileUrl) {\n\n // Get current spreadsheet Id\n const ssid = SpreadsheetApp.getActiveSpreadsheet().getId();\n\n // Look in the same folder the sheet exists in. For example, if this template is in\n // My Drive, it will return all of the files in My Drive.\n const ssparents = DriveApp.getFileById(ssid).getParents();\n\n // Loop through all the files and add the values to the spreadsheet.\n const folder = ssparents.next();\n\n // Get URL Blob Content\n var fileContent = UrlFetchApp.fetch(fileUrl).getBlob();\n\n // Save File there\n folder.createFile(fileContent);\n}", "function imgcache_set_file(url, file)\n{\n\tvar c = get_create_image_cache_by_url(url);\n\tc.file = file;\n\tset_image_in_cache(c);\n\twrite_image_cache();\n}", "function updateurl(val){\n seticonurl(val);\n }", "async updateImage(url) {\n const avatar = url;\n\n if (!avatar) {\n swal({ text: 'Hace falta el avatar' })\n }\n\n const consulta = await fetch(`${this.url}/user/avatar`, {\n method: 'POST',\n body: JSON.stringify({ avatar: avatar }),\n headers: {\n 'Content-Type': 'application/json',\n 'x-access-token': sessionStorage.getItem('__token')\n }\n });\n const res = await consulta.json();\n return res\n }", "function imagePlacer(url) {\n modalImageEl.src = `${url}`;\n}", "function updateURLs(res, type, id) {\n\t$('.' + id + '-atlas').attr('url', 'res/lineImages/' + type + '/' + id + '/' + id + '_' + res + '.png');\n}", "function fetchImg(){\n fetch(imgUrl)\n .then(resp => resp.json())\n .then(json => json.message.forEach(element => \n addImgToDom(element)\n ));\n}", "getUrl() {\n if (this.state != remote_file) {\n return undefined;\n }\n let [ssName, storageService] = getStorageService();\n return storageService.getUrl(this._obj.location);\n }" ]
[ "0.6802452", "0.63121134", "0.63020307", "0.62854433", "0.6244627", "0.6198315", "0.61598814", "0.6134651", "0.61144173", "0.6109636", "0.6097733", "0.60919195", "0.6091496", "0.6091364", "0.60882545", "0.60596526", "0.6031612", "0.6019611", "0.600994", "0.5981598", "0.59799993", "0.59792894", "0.5977352", "0.59765077", "0.59687775", "0.5965622", "0.5952598", "0.59440166", "0.59440166", "0.59188265", "0.58798486", "0.5865251", "0.5855016", "0.5850098", "0.5830558", "0.5820813", "0.58168525", "0.58136797", "0.58087957", "0.5798364", "0.57913506", "0.57905346", "0.5780384", "0.5779503", "0.57777035", "0.5773412", "0.5755963", "0.5754446", "0.5745695", "0.57229686", "0.5704183", "0.5693051", "0.56903756", "0.5675438", "0.56713206", "0.56668496", "0.5665643", "0.56655043", "0.56645447", "0.5663392", "0.5660835", "0.56523716", "0.56470346", "0.56469434", "0.5643135", "0.5641168", "0.56314224", "0.5627864", "0.5614979", "0.5610083", "0.5599489", "0.5585978", "0.5585354", "0.5579863", "0.55731267", "0.5567641", "0.555822", "0.5556398", "0.5554424", "0.55470264", "0.55468297", "0.5546096", "0.55438167", "0.55372405", "0.5534637", "0.5534386", "0.5523038", "0.55148613", "0.55147773", "0.5511792", "0.5509106", "0.55065465", "0.5503845", "0.5494134", "0.5492568", "0.5484186", "0.5484035", "0.54811823", "0.5481083", "0.5478759" ]
0.62411606
5
! Single baseline \class Line
function Line(lineId, startx, y, finishx){ this.id = lineId; this.startx = startx; this.y = y; this.finishx = finishx; this.selected = false; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function Line() {}", "function Line() {}", "function Line() {}", "function Line() {}", "function Line() {}", "function Line(){}", "function RendererTextLine() {\n\n /*\n * The width of the line in pixels.\n * @property width\n * @type number\n * @protected\n */\n this.width = 0;\n\n /*\n * The height of the line in pixels.\n * @property width\n * @type number\n * @protected\n */\n this.height = 0;\n\n /*\n * The descent of the line in pixels.\n * @property descent\n * @type number\n * @protected\n */\n this.descent = 0;\n\n /*\n * The content of the line as token objects.\n * @property content\n * @type Object[]\n * @protected\n */\n this.content = [];\n }", "function LineBasicPass() {\n _super.call(this);\n }", "static line(spec) {\n return new LineDecoration(spec);\n }", "function Line(p1,p2){\t\n\tthis.p1 = p1;\n\tthis.p2 = p2;\t\n}", "function Baseline(lines) {\n this.lines = lines;\n this.visible = false;\n this.clickMargin = 0.4; //in percent of the image height\n}", "function lineObj(x, y, x_diff, y_diff, width) {\n this.type = \"line\";\n this.x = x;\n this.y = y;\n this.x_diff = x_diff;\n this.y_diff = y_diff;\n this.width = width;\n}", "function mxLine(bounds, stroke, strokewidth)\r\n{\r\n\tthis.bounds = bounds;\r\n\tthis.stroke = stroke;\r\n\tthis.strokewidth = (strokewidth != null) ? strokewidth : 1;\r\n}", "function Line(p1,p2){\n\tthis.p1 = p1;\n\tthis.p2 = p2;\n\t\n\tthis.render = function(){\n\t\tdrawLine(p1, p2);\n\t}\n}", "function line() {\n var inlineHtml =\n '<hr style=\"height:5px; width:100%; border-width:0; color:red; background-color:#fff\">'\n\n return inlineHtml\n }", "function LineStyle() {\n\tthis.thickness=1.5;\n\tthis.endCap = 'round';\n\tthis.setThickness = function(thickness) {\n\t\tthis.thickness = thickness;\n\t\treturn this;\n\t};\n\tthis.setEndCap = function(endCap) {\n\t\tthis.endCap = endCap;\n\t\treturn this;\n\t};\n}", "function Line(text, styles) {\n this.styles = styles || [text, null];\n this.text = text;\n this.height = 1;\n this.marked = this.gutterMarker = this.className = this.bgClassName = this.handlers = null;\n this.stateAfter = this.parent = this.hidden = null;\n }", "function Line(text, styles) {\n this.styles = styles || [text, null];\n this.text = text;\n this.height = 1;\n this.marked = this.gutterMarker = this.className = this.bgClassName = this.handlers = null;\n this.stateAfter = this.parent = this.hidden = null;\n }", "function Line(text, styles) {\n this.styles = styles || [text, null];\n this.text = text;\n this.height = 1;\n this.marked = this.gutterMarker = this.className = this.bgClassName = this.handlers = null;\n this.stateAfter = this.parent = this.hidden = null;\n }", "function PatchLine() { }", "drawAppropriateLine() {\n const { width, color } = this._getLineStyle();\n this.graphics.lineStyle(width, color);\n\n if (this.lineType === EConnectionLineType.SOLID\n || this.lineType === EConnectionLineType.NODATA) {\n\n if (this.drawLineType === EConnectionDrawLineType.STRAIGHT){\n this.drawLine(this.pointA, this.pointB);\n } else {\n this.drawBezier(this.pointA, this.controlPointA, this.controlPointB, this.pointB);\n } \n\n } else {\n this.drawDottedLine();\n }\n\n if (this._selectable) {\n this._setHitArea();\n }\n }", "function LineDraw(ctor) {\n this._ctor = ctor || LineGroup;\n this.group = new graphic.Group();\n}", "function LineDraw(ctor) {\n this._ctor = ctor || LineGroup;\n this.group = new graphic.Group();\n}", "function LineDraw(ctor) {\n this._ctor = ctor || LineGroup;\n this.group = new graphic.Group();\n}", "function LineDraw(ctor) {\n this._ctor = ctor || LineGroup;\n this.group = new graphic.Group();\n}", "function Line(text, styles) {\n this.styles = styles || [text, null];\n this.stateAfter = null;\n this.text = text;\n this.marked = this.gutterMarker = this.className = null;\n }", "function Line(text, styles) {\n this.styles = styles || [text, null];\n this.stateAfter = null;\n this.text = text;\n this.marked = this.gutterMarker = this.className = null;\n }", "function Line(text, styles) {\n this.styles = styles || [text, null];\n this.stateAfter = null;\n this.text = text;\n this.marked = this.gutterMarker = this.className = null;\n }", "function Line() {\n _classCallCheck(this, Line);\n\n /** @type {Array} */\n this.elements = [];\n /** @type {HTMLElement} */\n this.$rendered = null;\n /** @type {Number} */\n this.width = null;\n /** @type {Number} */\n this.left = null;\n /** @type {Number} */\n this.x1 = null;\n /** @type {Number} */\n this.x2 = null;\n /** @type {Number} */\n this.y1 = null;\n /** @type {Number} */\n this.y2 = null;\n /** @type {Number} */\n this.left = null;\n /** @type {Number} */\n this.top = null;\n }", "drawLine() {\n ctx.moveTo(this.u0, this.v0);\n ctx.lineTo(this.u1, this.v1);\n ctx.stroke();\n }", "function drawLine() {\n var i = term.width;\n while(i--) {\n term.blue(\"-\");\n }\n term.blue(\"\\n\");\n}", "function line_basic_draw(cxt, movex, movey, linex, liney, lineWidth, color) {\n cxt.beginPath();\n cxt.lineWidth = lineWidth;\n cxt.strokeStyle = color;\n cxt.moveTo(movex, movey);\n cxt.lineTo(linex, liney);\n cxt.closePath();\n cxt.stroke();\n}", "function Line(){\n\tthis.circles = [];\n\tthis.color = (r,g,b);\n}", "getLine() { return this.line; }", "function Line(x1, y1, x2, y2) {\r\n\tthis.fillColour = getFillColour();\r\n\tthis.update(x1, y1, x2, y2);\r\n\tthis.isSelected = false; // initially false\r\n\tthis.outlineWidth = defaultOutlineWidth;\r\n\tthis.outlineColour = getOutlineColour();\r\n\r\n\tthis.draw = function() {\r\n\t\tcontext.beginPath();\r\n\t\tcontext.lineWidth = this.lineWidth;\r\n\t\tcontext.moveTo(this.x1, this.y1);\r\n\t\tcontext.lineTo(this.x2, this.y2);\r\n\t\tcontext.strokeStyle = this.outlineColour;\r\n\t\tif (this.isSelected) {\r\n\t\t\tcontext.lineWidth = this.outlineWidth + 3;\r\n\t\t} else {\r\n\t\t\tcontext.lineWidth = this.outlineWidth;\r\n\t\t}\r\n\t\tcontext.stroke();\r\n\t};\r\n}", "line(x0, y0, x1, y1, opts = {}) {\n const line = Line(Vec2(x0, y0), Vec2(x1, y1), opts)\n this.add(line)\n return line\n }", "function strline(begin_l,begin_t,end_l,end_t){ \n ctx.beginPath();\n ctx.moveTo(begin_l,begin_t);\n ctx.lineTo(end_l,end_t);\n ctx.strokeStyle=\"#7f7e7e\";\n ctx.stroke();\n }", "function Line (position) {\n\tthis.position = position; \n}", "function createLine() {\n\t\tlet element = document.createElement('span')\n\t\telement.className = 'line'\n\t\treturn element\n\t}", "line(x1, y1, x2, y2) {\n this.ctx.beginPath();\n this.ctx.moveTo(x1, y1);\n this.ctx.lineTo(x2, y2);\n this.ctx.stroke();\n }", "function Line(x, y, endX, endY, lineWidth, strokeStyle) {\n if (x === void 0) { x = 0; }\n if (y === void 0) { y = 0; }\n if (endX === void 0) { endX = 0; }\n if (endY === void 0) { endY = 0; }\n if (lineWidth === void 0) { lineWidth = 0; }\n if (strokeStyle === void 0) { strokeStyle = color_6.default.white; }\n var _this = _super.call(this, x, y, null, strokeStyle) || this;\n _this._endPosition = new vector2d_5.default(0, 0);\n _this._vertices = [];\n /**\n * Reacts to changes in position.\n */\n _this.positionOnChanged = function (sender) {\n _this.update();\n };\n _this.closePath = false;\n _this.fill = false;\n _this.lineWidth = lineWidth;\n _this._endPosition.x = endX;\n _this._endPosition.y = endY;\n _this._endPosition.onChanged.subscribe(_this.positionOnChanged);\n _this.update();\n return _this;\n }", "function Line(x1,y1,x2,y2){\n\tthis.x1 = x1;\n\tthis.y1 = y1;\n\tthis.x2 = x2;\n\tthis.y2 = y2;\n\tthis.vertical = x1==x2;\n\tif(!this.vertical){\n\t\tthis.m = (y2-y1)/(x2-x1);\n\t\tthis.n = y2 - this.m*x2;\n\t}else{\n\t\tthis.m = Number.POSITIVE_INFINITY;\n\t\tthis.n = undefined;\n\t}\n}", "function LineSegment(x1, y1, x2, y2) {\n this.x1 = x1;\n this.y1 = y1;\n this.x2 = x2;\n this.y2 = y2;\n}", "function Line(point1, point2, color) {\n this.point1 = point1;\n this.point2 = point2;\n this.color = color;\n }", "function Line(startx, starty, endx, endy, stroke){\n\tctx.beginPath();\n\tctx.moveTo(startx, starty);\n\tctx.lineTo(endx, endy);\n\tctx.strokeStyle = \"rgba(255,255,255,\" + stroke + \")\"\n\tctx.lineWidth = .5;\n\tctx.stroke();\n}", "drawLines() {\n stroke(this.lineColor);\n line(this.startLine, this.top, this.startLine, this.bottom); // start line\n line(this.endLine, this.top, this.endLine, this.bottom); // end line\n }", "function Line(x1, y1, x2, y2, settings){\r\n\t\tICollider.apply(this, [settings]);\r\n\t\tthis.p1 = new Vec(x1, y1), this.p2 = new Vec(x2, y2);\r\n\t\t\r\n\t\tthis.filled = 0; //-1 for left, 1 for right\r\n\t\tthis.capped = true;\r\n\t}", "line(...args) {\n let thickness = args[args.length-1];\n if (typeof thickness != \"number\") {\n thickness = 1;\n }\n let p1 = args[1];\n if (typeof p1 != \"object\") {\n p1 = [0, 0];\n }\n let p0 = args[0];\n if (typeof p0 != \"object\") {\n p0 = [0, 0];\n }\n ctx.lineWidth = thickness/ctxtransform[0];\n ctx.beginPath();\n ctx.moveTo(p0[0], p0[1]);\n ctx.lineTo(p1[0], p1[1]);\n ctx.stroke();\n\t}", "function Line(text, markedSpans, estimateHeight) {\n this.text = text\n attachMarkedSpans(this, markedSpans)\n this.height = estimateHeight ? estimateHeight(this) : 1\n}", "function drawLines() {\n}", "function drawLines() {\n}", "function drawLine(P0, P1, line, color, stage) {\r\n line.graphics.setStrokeStyle(2).beginStroke(color);\r\n line.graphics.moveTo(P0.x, P0.y);\r\n line.graphics.lineTo(P1.x, P1.y).endStroke();\r\n stage.update();\r\n}", "biggerLine() {\n this.ctx.lineWidth++\n }", "function visualLine(line) {\n\t\t var merged;\n\t\t while (merged = collapsedSpanAtStart(line))\n\t\t { line = merged.find(-1, true).line; }\n\t\t return line\n\t\t }", "function CalculationStepLine(options) {\n // TODO: CLEAN ALL OF THIS CODE\n // TODO: GET RID OF CONSTANT COLUMN POSITIONS\n\n const leftColumnPosition = 100;\n const middleColumnPosition = 100;\n\n let barHeight,\n color,\n domain,\n fontFamily,\n fontSize,\n labelText,\n line,\n scale,\n where;\n\n line = this;\n\n init(options);\n\n return line;\n\n /* INTIIALIZE */\n function init(options) {\n\n _required(options);\n _defaults(options);\n\n scale = defineScale();\n\n line.group = addGroup();\n line.columns = addColumns();\n\n line.label = addLabel()\n .update(labelText);\n\n line.bar = addBar();\n\n }\n\n /* PRIVATE METHODS */\n function _defaults(options) {\n\n barHeight = options.barHeight ? options.barHeight : 10;\n color = options.color ? options.color : \"black\";\n fontSize = options.fontSize ? options.fontSize : \"15pt\";\n fontFamily = options.fontFamily ? options.fontFamily : \"\";\n labelText = options.label ? options.label +\" =\" : \"=\";\n domain = options.domain ? options.domain : [0,1];\n line.lineHeight = options.lineHeight ? options.lineHeight : 25;\n\n }\n\n function _required(options) {\n\n where = options.where;\n\n }\n\n function addBar() {\n let bar;\n\n bar = new CalculationStepLinearIndicator({\n \"where\":line.columns.middle,\n \"color\":color,\n \"scale\":scale,\n \"fontSize\":fontSize,\n \"fontFamily\":fontFamily,\n \"height\":barHeight\n });\n\n return bar;\n }\n\n function addColumns() {\n let groupObject;\n\n groupObject = {};\n\n groupObject.left = explorableGroup({\n \"where\":line.group,\n }).attr(\"transform\",\"translate(\"+leftColumnPosition+\",0)\");\n\n\n groupObject.middle = explorableGroup({\n \"where\":line.group,\n }).attr(\"transform\",\"translate(\"+middleColumnPosition+\",0)\");\n\n\n return groupObject;\n }\n\n function addGroup() {\n let group;\n\n group = explorableGroup({\n \"where\":where\n })\n .attr(\"transform\",\"translate(0,50)\");\n\n return group;\n }\n\n\n function addLabel() {\n let label;\n\n // TODO: DOES COLUMNS REALLY NEED TO BE PUBLIC?\n label = new ExplorableHintedText({\n \"where\":line.columns.left,\n \"textAnchor\":\"end\",\n \"foregroundColor\":color,\n \"fontFamily\":fontFamily,\n \"fontWeight\":\"normal\",\n \"fontSize\":fontSize\n })\n .move({\n \"x\":-5,\n \"y\":0\n });\n\n return label;\n }\n\n\n function defineScale() {\n let scale;\n\n //TODO: DONT HARD CODE DOMAIN AND RANGE\n scale = d3.scaleLinear()\n .domain(domain)\n .range([0,100]);\n\n return scale;\n }\n\n}", "function CalculationStepLine(options) {\n // TODO: CLEAN ALL OF THIS CODE\n // TODO: GET RID OF CONSTANT COLUMN POSITIONS\n\n const leftColumnPosition = 100;\n const middleColumnPosition = 100;\n\n let barHeight,\n color,\n domain,\n fontFamily,\n fontSize,\n labelText,\n line,\n scale,\n where;\n\n line = this;\n\n init(options);\n\n return line;\n\n /* INTIIALIZE */\n function init(options) {\n\n _required(options);\n _defaults(options);\n\n scale = defineScale();\n\n line.group = addGroup();\n line.columns = addColumns();\n\n line.label = addLabel()\n .update(labelText);\n\n line.bar = addBar();\n\n }\n\n /* PRIVATE METHODS */\n function _defaults(options) {\n\n barHeight = options.barHeight ? options.barHeight : 10;\n color = options.color ? options.color : \"black\";\n fontSize = options.fontSize ? options.fontSize : \"15pt\";\n fontFamily = options.fontFamily ? options.fontFamily : \"\";\n labelText = options.label ? options.label +\" =\" : \"=\";\n domain = options.domain ? options.domain : [0,1];\n line.lineHeight = options.lineHeight ? options.lineHeight : 25;\n\n }\n\n function _required(options) {\n\n where = options.where;\n\n }\n\n function addBar() {\n let bar;\n\n bar = new CalculationStepLinearIndicator({\n \"where\":line.columns.middle,\n \"color\":color,\n \"scale\":scale,\n \"fontSize\":fontSize,\n \"fontFamily\":fontFamily,\n \"height\":barHeight\n });\n\n return bar;\n }\n\n function addColumns() {\n let groupObject;\n\n groupObject = {};\n\n groupObject.left = explorableGroup({\n \"where\":line.group,\n }).attr(\"transform\",\"translate(\"+leftColumnPosition+\",0)\");\n\n\n groupObject.middle = explorableGroup({\n \"where\":line.group,\n }).attr(\"transform\",\"translate(\"+middleColumnPosition+\",0)\");\n\n\n return groupObject;\n }\n\n function addGroup() {\n let group;\n\n group = explorableGroup({\n \"where\":where\n })\n .attr(\"transform\",\"translate(0,50)\");\n\n return group;\n }\n\n\n function addLabel() {\n let label;\n\n // TODO: DOES COLUMNS REALLY NEED TO BE PUBLIC?\n label = new ExplorableHintedText({\n \"where\":line.columns.left,\n \"textAnchor\":\"end\",\n \"foregroundColor\":color,\n \"fontFamily\":fontFamily,\n \"fontWeight\":\"normal\",\n \"fontSize\":fontSize\n })\n .move({\n \"x\":-5,\n \"y\":0\n });\n\n return label;\n }\n\n\n function defineScale() {\n let scale;\n\n //TODO: DONT HARD CODE DOMAIN AND RANGE\n scale = d3.scaleLinear()\n .domain(domain)\n .range([0,100]);\n\n return scale;\n }\n\n}", "setLine(line) { this.line = line; return this; }", "function drawLine(v1, v2) {\n push();\n strokeWeight(rez * 0.2);\n stroke(255, randomG, randomB);\n line(v1.x, v1.y, v2.x, v2.y);\n pop();\n}", "function Line(start, end, time, loops){\n\tvar that = Gibberish.Line(start, end, G.time(time), loops);\n\t\n\treturn that;\n}", "function Br(e,t,a,n){a<e.line?e.line+=n:t<e.line&&(e.line=t,e.ch=0)}", "function visualLine(line) {\n\t\t var merged;\n\t\t while (merged = collapsedSpanAtStart(line))\n\t\t line = merged.find(-1, true).line;\n\t\t return line;\n\t\t }", "get horizontalLineStroke() {\r\n return brushToString(this.i.pb);\r\n }", "function line(x, y, width, height) {\n this.width = width;\n this.height = height;\n this.x = x;\n this.y = y;\n //ctx.fillStyle = pat;\n\t\tvar grd = ctx.createLinearGradient(10,90,400,0);\n\t\tgrd.addColorStop(0,\"#df1540\");\n\t\tgrd.addColorStop(1,\"#f9a940\");\n\t\tctx.fillStyle = grd;\n ctx.fillRect(this.x, this.y, this.width, this.height);\n}", "display() {\n line(this.start.x, this.start.y, this.end.x, this.end.y);\n }", "function line (x1, y1, x2, y2) {\n newPath(); // Neuer Grafikpfad (Standardwerte)\n ctx.moveTo(x1,y1); // Anfangspunkt\n ctx.lineTo(x2,y2); // Weiter zum Endpunkt\n ctx.stroke(); // Linie zeichnen\n }", "get lineBegin() {\n\t\treturn this.state.lineBegin;\n\t}", "function draw_first_line(){\n points.push(start);\n points.push(end);\n}", "_addLine(line) {\n //line.initProgram(this.webgl);\n line._vbuffer = this.webgl.createBuffer();\n this.webgl.bindBuffer(this.webgl.ARRAY_BUFFER, line._vbuffer);\n this.webgl.bufferData(this.webgl.ARRAY_BUFFER, line.xy, this.webgl.STREAM_DRAW);\n this.webgl.bindBuffer(this.webgl.ARRAY_BUFFER, line._vbuffer);\n line._coord = this.webgl.getAttribLocation(this.progThinLine, \"coordinates\");\n this.webgl.vertexAttribPointer(line._coord, 2, this.webgl.FLOAT, false, 0, 0);\n this.webgl.enableVertexAttribArray(line._coord);\n }", "drawLine(canvas, dependency, points, assignmentData = null) {\n const { client } = this,\n metaId = this.getMetaId(assignmentData);\n\n // Reuse existing element if possible\n let line = dependency.instanceMeta(metaId).lineElement;\n\n if (!line) {\n line = dependency.instanceMeta(metaId).lineElement = document.createElementNS(\n 'http://www.w3.org/2000/svg',\n 'polyline'\n );\n line.setAttribute('depId', dependency.id);\n if (assignmentData) {\n line.setAttribute('fromId', assignmentData.from.id);\n line.setAttribute('toId', assignmentData.to.id);\n }\n canvas.appendChild(line);\n }\n\n // TODO: Use DomHelper.syncClassList\n\n // className is SVGAnimatedString for svg elements, reading attribute instead\n line.classList.length && line.classList.remove.apply(line.classList, line.getAttribute('class').split(' '));\n\n line.classList.add(this.baseCls);\n\n if (dependency.cls) {\n line.classList.add(dependency.cls);\n }\n if (dependency.bidirectional) {\n line.classList.add('b-sch-bidirectional-line');\n }\n if (dependency.highlighted) {\n line.classList.add(...dependency.highlighted.split(' '));\n }\n if (BrowserHelper.isIE11) {\n const ddr = dependency.getDateRange(true),\n viewStart = client.startDate;\n\n if (ddr.start < viewStart) {\n line.classList.add('b-no-start-marker');\n }\n if (ddr.end < viewStart) {\n line.classList.add('b-no-end-marker');\n }\n }\n\n line.setAttribute(\n 'points',\n !points\n ? ''\n : points\n .map((p, i) => (i !== points.length - 1 ? `${p.x1},${p.y1}` : `${p.x1},${p.y1} ${p.x2},${p.y2}`))\n .join(' ')\n );\n\n DomDataStore.set(line, {\n dependency\n });\n }", "updateLastLine(line) { // this is used when drawing with the pen\r\n if (line.length < 2) return;\r\n var point1 = line.points[line.points.length - 1];\r\n var point2 = line.points[line.points.length - 2];\r\n point1 = this.worldPointToChunkScreenPoint(point1);\r\n point2 = this.worldPointToChunkScreenPoint(point2);\r\n this.ctx.beginPath();\r\n this.ctx.lineWidth = Main.Camera.getRelativeWidth(line.width);\r\n this.ctx.strokeStyle = line.style;\r\n this.ctx.lineTo(point1.x, point1.y);\r\n this.ctx.lineTo(point2.x, point2.y);\r\n this.ctx.stroke();\r\n }", "initLine(line) {\n line.text = this.add.sprite(320, 336, `line-B-${line.id}`);\n this.anims.create({\n key: `line-B-${line.id}-sheet`,\n frames: this.anims.generateFrameNumbers(`line-B-${line.id}`, {\n start: 0,\n end: line.numFrames\n }),\n frameRate: 5,\n repeat: 0\n });\n line.text.play(`line-B-${line.id}-sheet`);\n line.text.visible = line.toggle;\n }", "function drawALine(ctx, line) { \n //check whether drawing dashed lines\n if (line.type == \"dashed\"){\n ctx.setLineDash([dashLineWidth, dashSpaceWidth]);\n }\n else{\n ctx.setLineDash([]);\n }\n \n ctx.beginPath();\n ctx.moveTo(findTrueXCoord(line.x1), findTrueYCoord(line.y1));\n ctx.lineWidth = lineWidth;\n ctx.lineTo(findTrueXCoord(line.x2), findTrueYCoord(line.y2));\n if (line.color == \"correct\"){\n ctx.strokeStyle = lineCorrectColor;\n }\n else if (line.color == \"incorrect\"){\n ctx.strokeStyle = lineIncorrectColor;\n }\n else {\n ctx.strokeStyle = lineColor;\n }\n ctx.stroke();\n}", "function custom_line(specs) {\n // Store relevant variables\n var delta_x = specs.Point_b.x - specs.Point_a.x;\n var delta_y = specs.Point_b.y - specs.Point_a.y;\n var increment_x = delta_x / specs.nsegments;\n var increment_y = delta_y / specs.nsegments;\n\n // Calculate the points\n var points = [];\n points.push(specs.Point_a);\n for (var i = 1; i < specs.nsegments; i++) {\n this_point = [\n specs.Point_a.x +\n increment_x * i +\n randFBtwn(-specs.wobble, specs.wobble),\n specs.Point_a.y +\n increment_y * i +\n randFBtwn(-specs.wobble, specs.wobble),\n ];\n points.push(this_point);\n }\n points.push(specs.Point_b);\n\n // Create path\n var myPath = new Path({\n segments: points,\n });\n\n // Style path\n myPath.strokeWidth = specs.stroke_width;\n myPath.strokeColor = specs.stroke_color;\n myPath.strokeCap = specs.stroke_cap;\n myPath.smooth();\n\n // myPath.parent = specs.parent;\n}", "function visualLine(line) {\n var merged;\n while (merged = collapsedSpanAtStart(line))\n { line = merged.find(-1, true).line; }\n return line\n }", "function visualLine(line) {\n var merged;\n while (merged = collapsedSpanAtStart(line))\n { line = merged.find(-1, true).line; }\n return line\n }", "function visualLine(line) {\n var merged;\n while (merged = collapsedSpanAtStart(line))\n { line = merged.find(-1, true).line; }\n return line\n }", "function visualLine(line) {\n var merged;\n while (merged = collapsedSpanAtStart(line))\n { line = merged.find(-1, true).line; }\n return line\n }", "function visualLine(line) {\n var merged;\n while (merged = collapsedSpanAtStart(line))\n { line = merged.find(-1, true).line; }\n return line\n }", "function visualLine(line) {\n var merged;\n while (merged = collapsedSpanAtStart(line))\n { line = merged.find(-1, true).line; }\n return line\n }", "function visualLine(line) {\n var merged;\n while (merged = collapsedSpanAtStart(line))\n { line = merged.find(-1, true).line; }\n return line\n }", "function visualLine(line) {\n var merged;\n while (merged = collapsedSpanAtStart(line))\n { line = merged.find(-1, true).line; }\n return line\n }", "function visualLine(line) {\n var merged;\n while (merged = collapsedSpanAtStart(line))\n { line = merged.find(-1, true).line; }\n return line\n }", "function visualLine(line) {\n var merged;\n while (merged = collapsedSpanAtStart(line))\n { line = merged.find(-1, true).line; }\n return line\n }", "function visualLine(line) {\n var merged;\n while (merged = collapsedSpanAtStart(line))\n { line = merged.find(-1, true).line; }\n return line\n }", "function visualLine(line) {\n var merged;\n while (merged = collapsedSpanAtStart(line))\n { line = merged.find(-1, true).line; }\n return line\n }", "function visualLine(line) {\n var merged;\n while (merged = collapsedSpanAtStart(line))\n { line = merged.find(-1, true).line; }\n return line\n }", "function visualLine(line) {\n var merged;\n while (merged = collapsedSpanAtStart(line))\n { line = merged.find(-1, true).line; }\n return line\n }", "function visualLine(line) {\n var merged;\n while (merged = collapsedSpanAtStart(line))\n { line = merged.find(-1, true).line; }\n return line\n }", "function visualLine(line) {\n var merged;\n while (merged = collapsedSpanAtStart(line))\n { line = merged.find(-1, true).line; }\n return line\n }", "function visualLine(line) {\n var merged;\n while (merged = collapsedSpanAtStart(line))\n { line = merged.find(-1, true).line; }\n return line\n }", "function visualLine(line) {\r\n var merged;\r\n while (merged = collapsedSpanAtStart(line))\r\n { line = merged.find(-1, true).line; }\r\n return line\r\n}", "function line(ctx, x1, y1, x2, y2) {\n ctx.beginPath();\n ctx.moveTo(x1, y1);\n ctx.lineTo(x2, y2);\n ctx.stroke();\n }", "function visualLine(line) {\n\t var merged;\n\t while (merged = collapsedSpanAtStart(line))\n\t line = merged.find(-1, true).line;\n\t return line;\n\t }", "function visualLine(line) {\n\t var merged;\n\t while (merged = collapsedSpanAtStart(line))\n\t line = merged.find(-1, true).line;\n\t return line;\n\t }", "function visualLine(line) {\n\t var merged;\n\t while (merged = collapsedSpanAtStart(line))\n\t line = merged.find(-1, true).line;\n\t return line;\n\t }", "function visualLine(line) {\r\n var merged;\r\n while (merged = collapsedSpanAtStart(line))\r\n line = merged.find(-1, true).line;\r\n return line;\r\n }", "drawLineSegment(line, circle){\n // this.lineGraphics.lineStyle(10, 0xfdfd96, 0.7);\n // this.lineGraphics.strokeLineShape(line);\n // this.lineGraphics.fillStyle(0xfdfd96, 0.7);\n // this.lineGraphics.fillCircleShape(circle);\n\n\n }", "function drawLine(P1, P2) {\n var line = doc.pathItems.add()\n line.stroked = true;\n line.strokeColor = hexToRGB(\"#00FFFF\");\n line.strokeWidth = 0.5;\n line.setEntirePath([P1, P2]);\n}", "getYForLine(line) {\n const options = this.options;\n const spacing = options.spacing_between_lines_px;\n const headroom = options.space_above_staff_ln;\n\n const y = this.y + (line * spacing) + (headroom * spacing);\n\n return y;\n }", "function line(sx, sy, tx, ty) {\n return 'M' + sx + ',' + sy +\n 'L' + tx + ',' + ty;\n}" ]
[ "0.7952938", "0.7952938", "0.7952938", "0.7952938", "0.7952938", "0.78384835", "0.6997238", "0.6926064", "0.68488264", "0.6817992", "0.668045", "0.666385", "0.65811104", "0.65633917", "0.6556548", "0.6538027", "0.652666", "0.652666", "0.652666", "0.6501308", "0.64601517", "0.645706", "0.645706", "0.645706", "0.645706", "0.6444326", "0.6444326", "0.6444326", "0.64207846", "0.6400528", "0.63765407", "0.6362634", "0.63555354", "0.6334314", "0.63283765", "0.6320504", "0.62972814", "0.62932056", "0.6275498", "0.62641466", "0.62511337", "0.6250868", "0.62100613", "0.62072766", "0.6199618", "0.61934596", "0.61830944", "0.6151968", "0.6150397", "0.6145582", "0.6145582", "0.6131031", "0.6127634", "0.61258686", "0.6121994", "0.6121994", "0.61205375", "0.6114173", "0.61133647", "0.61062527", "0.6099918", "0.6094003", "0.6087729", "0.60828286", "0.6079075", "0.607631", "0.60652447", "0.6060927", "0.60596806", "0.6055026", "0.6054618", "0.6046462", "0.60294527", "0.6007334", "0.6007334", "0.6007334", "0.6007334", "0.6007334", "0.6007334", "0.6007334", "0.6007334", "0.6007334", "0.6007334", "0.6007334", "0.6007334", "0.6007334", "0.6007334", "0.6007334", "0.6007334", "0.6007334", "0.60070693", "0.60049057", "0.5996951", "0.5996951", "0.5996951", "0.5996773", "0.59795964", "0.5966243", "0.5959979", "0.5958689" ]
0.6192433
46
! Container of all baselines \class Baseline
function Baseline(lines) { this.lines = lines; this.visible = false; this.clickMargin = 0.4; //in percent of the image height }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "constructor() { \n \n LineItem.initialize(this);\n }", "function LinesSequence(parent) {\n this.parent = parent;\n}", "function addBaselines(sketch, layer, fragments) {\n\n // First we make a new group to contain our baseline layers\n var container = layer.container.newGroup({\"name\" : \"Baselines\"})\n\n // The we process each fragment in turn\n processFragments(sketch, container, fragments, function(sketch, group, fragment, index) {\n\n // We make a rectangle that's just 0.5 pixels high, positioned to match\n // the location of the baseline\n var rect = layer.localRectToParentRect(fragment.rect)\n rect.y += rect.height - fragment.baselineOffset\n rect.height = 0.5\n\n // We make a new shape layer with this rectangle.\n group.newShape({\"frame\": rect, fills: [\"#ff000090\"], borders: []})\n })\n}", "function Line(){}", "function Line() {}", "function Line() {}", "function Line() {}", "function Line() {}", "function Line() {}", "function BaseRenderer() {\n }", "function LineAllOf() {\n _classCallCheck(this, LineAllOf);\n\n LineAllOf.initialize(this);\n }", "function inherited() { }", "function LineBasicPass() {\n _super.call(this);\n }", "function inherit(){}", "function LineDraw(ctor) {\n this._ctor = ctor || LineGroup;\n this.group = new graphic.Group();\n}", "function LineDraw(ctor) {\n this._ctor = ctor || LineGroup;\n this.group = new graphic.Group();\n}", "function LineDraw(ctor) {\n this._ctor = ctor || LineGroup;\n this.group = new graphic.Group();\n}", "function LineDraw(ctor) {\n this._ctor = ctor || LineGroup;\n this.group = new graphic.Group();\n}", "function BaseElement() {\n }", "function LineItem() {\n this.name = '';\n //this.sku = '';\n this.quantity = '';\n this.price = new Amount();\n }", "prepareLines() {\n let attributes = this.props.attributes;\n let actions = this.props.actions;\n const models = this.props.models;\n const className = this.props.className;\n let lines = [];\n\n if(models !== undefined) {\n for (let i in models) {\n let model = models[i];\n let line = (\n <div key={\"line-\" + model.id}\n className={\"grid-container \" + (className !== undefined ? className : \"\") + \" grid-container-line\"}\n style={{opacity: model.is_delete === 1 ? 0.4 : 1}}\n >\n {this.lineItems(attributes, model)}\n <div className={\"grid-item action-buttons\"}>\n {this.actionButtons(actions, model)}\n </div>\n\n </div>\n );\n\n lines.push(line);\n }\n }\n\n return lines;\n\n }", "function BaseEditor() { }", "function BaseEditor() { }", "function finishBaseline( baseline ) {\n //setPolyrect( baseline, self.cfg.polyrectHeight, self.cfg.polyrectOffset );\n setPolystripe( baseline, self.cfg.polyrectHeight, self.cfg.polyrectOffset );\n\n sortOnDrop( $(baseline).parent()[0] );\n\n $(baseline)\n .parent()\n .addClass('editable')\n .each( function () {\n this.setEditing = function () {\n var event = { target: this };\n self.util.setEditing( event, 'points', { points_selector: '> polyline', restrict: false } );\n };\n } );\n window.setTimeout( function () {\n if ( typeof $(baseline).parent()[0].setEditing !== 'undefined' )\n $(baseline).parent()[0].setEditing();\n self.util.selectElem(baseline,true);\n }, 50 );\n\n self.util.registerChange('added baseline '+$(baseline).parent().attr('id'));\n\n for ( var n=0; n<self.cfg.onFinishBaseline.length; n++ )\n self.cfg.onFinishBaseline[n](baseline);\n }", "function Base() {}", "function Base() {\n }", "function SegmentBase() {\n}", "function BaseClass() {}", "function BaseClass() {}", "function BaseRenderable(x, y, fillStyle, strokeStyle) {\n this._position = new vector2d_1.default(0, 0);\n /**\n * Used as CanvasRenderingContext2D.lineCap.\n */\n this.lineCap = 'butt';\n /**\n * Used as CanvasRenderingContext2D.lineJoin.\n */\n this.lineJoin = 'miter';\n /**\n * Used as CanvasRenderingContext2D.miterLimit.\n */\n this.miterLimit = 10;\n /**\n * Used as CanvasRenderingContext2D.miterLimit.\n */\n this.lineDash = [];\n /**\n * Used as CanvasRenderingContext2D.setLineDash(lineDash). Example: [2, 16]\n */\n this.lineDashOffset = 0;\n /**\n * Color used as the CanvasRenderingContext2D.fillStyle if fill is set to true.\n */\n this.fillStyle = color_1.default.black;\n /**\n * Color used as the CanvasRenderingContext2D.strokeStyle if stroke is set to true.\n */\n this.strokeStyle = color_1.default.white;\n /**\n * Used as CanvasRenderingContext2D.lineWidth.\n */\n this.lineWidth = 1;\n /**\n * Whether or not the CanvasRenderingContext2D.fill() method should be called on endRender().\n */\n this.fill = true;\n /**\n * Whether or not the CanvasRenderingContext2D.stroke() method should be called on endRender().\n */\n this.stroke = true;\n /**\n * Whether or not CanvasRenderingContext2D.closePath() method should be called on endRender().\n */\n this.closePath = true;\n /**\n * Defines how an object reacts to the change of the position property.\n * @param sender The position that initiated the event.\n */\n this.positionOnChanged = function (sender) { };\n this._position.x = x;\n this._position.y = y;\n this.fillStyle = fillStyle;\n this.strokeStyle = strokeStyle;\n this._position.onChanged.subscribe(this.positionOnChanged);\n }", "function BaseLayouter() { }", "function PlaceholderLine(props) {\n var className = props.className,\n length = props.length;\n var classes = Object(clsx__WEBPACK_IMPORTED_MODULE_1__[\"default\"])('line', length, className);\n var rest = Object(_lib__WEBPACK_IMPORTED_MODULE_4__[\"getUnhandledProps\"])(PlaceholderLine, props);\n var ElementType = Object(_lib__WEBPACK_IMPORTED_MODULE_4__[\"getElementType\"])(PlaceholderLine, props);\n return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement(ElementType, Object(_babel_runtime_helpers_esm_extends__WEBPACK_IMPORTED_MODULE_0__[\"default\"])({}, rest, {\n className: classes\n }));\n}", "init() {\n // If any lines use a text attribute set innerText on the elements before\n // calculating the height of the container.\n const attr = `${this.pfx}-text`\n this.container.querySelectorAll(`[${attr}]`).forEach(function(textLine) {\n textLine.textContent = textLine.getAttribute(attr)\n })\n\n // Appends dynamically loaded lines to existing line elements.\n this.lines = [...this.container.querySelectorAll(`[${this.pfx}]`)].concat(\n this.lineData\n )\n\n /**\n * Calculates width and height of Termynal container.\n * If container is empty and lines are dynamically loaded, defaults to browser `auto` or CSS.\n */\n\n const containerStyle = getComputedStyle(this.container)\n this.container.style.width =\n containerStyle.width !== \"0px\" ? containerStyle.width : undefined\n this.container.style.minHeight =\n containerStyle.height !== \"0px\" ? containerStyle.height : undefined\n\n this.container.setAttribute(\"data-termynal\", \"\")\n this.container.innerHTML = \"\"\n this.start()\n }", "function SuperclassBare() {}", "function SuperclassBare() {}", "createNew() {\n // Creation and expiration times\n this.time = (new Date).getTime();\n this.interval = 10000; // + Math.random() * 2000;\n\n // Split into lines\n super.createNew();\n\n // Vertical (Y) position, offeset for drawing taking into account\n // the number of lines, the size and the space between lines\n this.Y = this.Yoriginal - ((this.line.length * this.offesetAmount - this.offesetAmount) / 2);\n }", "function HealthBarBase(fillStyle, strokeStyle, lineWidth, parent) {\n var _this = _super.call(this, fillStyle, strokeStyle, lineWidth, parent) || this;\n _this.rectangle.stroke = false;\n return _this;\n }", "renderBase() {\r\n return h(\"div\", { class: \"outer-container\" },\r\n (this.isClosable ?\r\n h(\"div\", { class: \"close-btn\" },\r\n h(\"yoo-icon\", { class: \"yo-close\" }))\r\n : null),\r\n this.renderIconBasedOnSource(),\r\n h(\"div\", { class: \"top-container\" },\r\n (this.heading ? h(\"div\", { class: \"heading-container\" }, this.heading)\r\n : null),\r\n (this.subheading ? h(\"div\", { class: \"subheading-container\" }, this.subheading)\r\n : null)));\r\n }", "function Base() {\n}", "function RendererTextLine() {\n\n /*\n * The width of the line in pixels.\n * @property width\n * @type number\n * @protected\n */\n this.width = 0;\n\n /*\n * The height of the line in pixels.\n * @property width\n * @type number\n * @protected\n */\n this.height = 0;\n\n /*\n * The descent of the line in pixels.\n * @property descent\n * @type number\n * @protected\n */\n this.descent = 0;\n\n /*\n * The content of the line as token objects.\n * @property content\n * @type Object[]\n * @protected\n */\n this.content = [];\n }", "function PlaceholderLine(props) {\n var className = props.className,\n length = props.length;\n var classes = classnames__WEBPACK_IMPORTED_MODULE_1___default()('line', length, className);\n var rest = Object(_lib__WEBPACK_IMPORTED_MODULE_4__[\"getUnhandledProps\"])(PlaceholderLine, props);\n var ElementType = Object(_lib__WEBPACK_IMPORTED_MODULE_4__[\"getElementType\"])(PlaceholderLine, props);\n return react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement(ElementType, _babel_runtime_helpers_extends__WEBPACK_IMPORTED_MODULE_0___default()({}, rest, {\n className: classes\n }));\n}", "function PlaceholderLine(props) {\n var className = props.className,\n length = props.length;\n var classes = classnames__WEBPACK_IMPORTED_MODULE_1___default()('line', length, className);\n var rest = Object(_lib__WEBPACK_IMPORTED_MODULE_4__[\"getUnhandledProps\"])(PlaceholderLine, props);\n var ElementType = Object(_lib__WEBPACK_IMPORTED_MODULE_4__[\"getElementType\"])(PlaceholderLine, props);\n return react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement(ElementType, _babel_runtime_helpers_extends__WEBPACK_IMPORTED_MODULE_0___default()({}, rest, {\n className: classes\n }));\n}", "function ContentChildDecorator() { }", "function ContentChildDecorator() { }", "function BaseLayouter() {}", "function BaseLayouter() {}", "function BaseLayouter() {}", "function AbstractRenderer() {\n this.points = [];\n this.drawing = false;\n this.parameters = new scope.RenderingParameters();\n }", "createBases (dataObj) {\n const dataBase = dataObj.dataBase; // getter\n const s = new PIXI.projection.Spine2d(dataBase.spineData); //new PIXI.spine.Spine(sd);\n const [d,n] = s.hackAttachmentGroups(\"_n\",null,null); // (nameSuffix, group)\n //PIXI.projection.Spine2d.call(this,dataBase.spineData);\n /*if(dataObj.dataValues.p.skinName){\n s.skeleton.setSkinByName(dataObj.dataValues.p.skinName);//FIXME: player have no skin for now\n };\n s.state.setAnimation(0, dataObj.dataValues.p.defaultAnimation , true); // default animation 'idle' TODO: add more in getDataValues_spine\n s.skeleton.setSlotsToSetupPose();*/\n this.Sprites = {s,d,n};\n \n }", "function Base() {\n\tthis.name = \"Base\"; // 3. {}.name = \"Base\";\n}", "function find_lines() {\n // reset line indices for reuse\n special_lines.green = [];\n special_lines.red = [];\n\n d3.selectAll('line')\n .each(function(d, i) {\n // find each line that has class of \"green\" or \"red\"\n // these classes were added during rendering in \"slopey.js\"\n if (d3.select(this).classed(\"green\")) {\n var clas = d3.select(this).attr(\"class\").split(\"-\");\n // take last element in array of class string to identify\n // the line number\n special_lines.green.push(clas[clas.length-1]);\n } else if(d3.select(this).classed(\"red\")) {\n var clas = d3.select(this).attr(\"class\").split(\"-\");\n special_lines.red.push(clas[clas.length-1]);\n }\n })\n }", "function Drawing(){\n\n\tthis.header={\n\t\t$INSBASE:{x:0,y:0,z:0},\n\t\t$EXTMIN:{x:0,y:0,z:0},\n\t\t$EXTMAX:{x:10,y:10,z:0}\n\t};\n\tthis.tables={\n\t\tlinetype:{\n\t\t\tContinuous:{\n name: \"Continuous\",\n description: \"Solid line\",\n patternLength: 0\n },\n HIDDEN2: {\n name: \"HIDDEN2\",\n description: \"Hidden (.5x) _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _\",\n pattern:[0.125, -0.0625],\n patternLength: 0.1875\n }\n\t\t},\n\t\tlayer:{\n\t\t\thandle: \"2\",\n\t\t\townerHandle: \"0\",\n\t\t\tlayers: {\n\t\t\t\t\"0\":{Name:\"0\", Visible:true, color:16711680},\n\t\t\t\t\"A-WALL\":{Name:\"0\", Visible:true, color:16711680}\n\t\t\t}\t\t\n\t\t}\n\t};\n\tthis.blocks={};\n\tthis.entities=[\n\t\tline.create(this)\n\t\t//new line.Line(this)\n\t];\t\n}", "static line(spec) {\n return new LineDecoration(spec);\n }", "function Border(descr) {\n\n // Common inherited setup logic from Entity\n this.setup(descr);\n\n}", "function Base(data) {\n this.dateStart = null;\n this.dateEnd = null;\n this.lastEntry = Date.now();\n}", "function _createBaseStyles() {\n _baseVisualization = $(\"<style />\", {\n id: \"alice-base-visualization\",\n type: \"text/css\",\n html: _visualizationBaseCSS\n });\n _baseVisualization.appendTo(\"head\");\n _baseStylesCreated = true;\n }", "function newTodoLine(container, todoType) {\n let draggable = createDraggable();\n let item = createItem(draggable, todoType);\n let icon = gen(\"div\");\n icon.classList.add(\"icon\"); // icon div\n let circl = createCircle(item, draggable, container);\n let ipt = createInput(draggable);\n let divider = gen(\"div\");\n divider.classList.add(\"is-divider\"); //divider\n icon.appendChild(circl);\n item.appendChild(icon);\n item.appendChild(ipt);\n draggable.appendChild(item);\n draggable.appendChild(divider);\n let elems = [ipt, item, circl, draggable];\n return elems;\n }", "function ContentChildDecorator(){}", "static get baseStyles() {\n return [\n ...super.baseStyles,\n ...RichTextStyles,\n css`\n :host {\n border: var(--rich-text-editor-border-width, 1px) solid\n var(--rich-text-editor-border-color, #ddd);\n background-color: var(--rich-text-editor-bg, #ffffff);\n }\n #morebutton::part(button) {\n border-radius: var(\n --rich-text-editor-button-disabled-border-radius,\n 0px\n );\n }\n `,\n ];\n }", "addLineDeco(deco) {\n let attrs = deco.spec.attributes, cls = deco.spec.class;\n if (attrs)\n this.attrs = combineAttrs(attrs, this.attrs || {});\n if (cls)\n this.attrs = combineAttrs({ class: cls }, this.attrs || {});\n }", "function initializeOutline() {\r\n}", "function ContentChildDecorator() {}", "function ContentChildDecorator() {}", "function ContentChildDecorator() {}", "function CVBaseElement() {\n }", "constructor() {\n super();\n this.draw();\n }", "constructor() {\n super();\n\n // Bind to make 'this' work in callbacks.\n this.getBodyRows = this.getBodyRows.bind(this);\n }", "constructor() {\n super();\n\n // Bind to make 'this' work in callbacks.\n this.getBodyRows = this.getBodyRows.bind(this);\n }", "function LineStyle() {\n\tthis.thickness=1.5;\n\tthis.endCap = 'round';\n\tthis.setThickness = function(thickness) {\n\t\tthis.thickness = thickness;\n\t\treturn this;\n\t};\n\tthis.setEndCap = function(endCap) {\n\t\tthis.endCap = endCap;\n\t\treturn this;\n\t};\n}", "function computeArrowheadVerticesFromBaseAndPoint(base, point, lineWidth) {\n var WING=2,\n width = ((lineWidth/2) + WING) || WING, //protect against undefined lineWidth\n vertices = [],\n axisV = point.subtract(base).unit(),\n orthV = new GSP.GeometricPoint(-axisV.y, axisV.x);\n vertices.push(base.add(orthV.multiply(width)));\n vertices.push(point);\n vertices.push(base.add(orthV.multiply(-width)));\n return vertices;\n }", "function Derived() {} // private", "get _allsplines() {\r\n return new AllSplineIter(this);\r\n }", "render() {\n const list = this._item ? [this._item.object] : [];\n this._decoration = this._editor.deltaDecorations(this._decoration, list);\n }", "function editModeBaselineCreate() {\n self.mode.off();\n var args = arguments;\n self.mode.current = function () { return editModeBaselineCreate.apply(this,args); };\n\n self.util.selectFiltered('.TextLine')\n .addClass('editable')\n .each( function () {\n this.setEditing = function ( ) {\n var event = { target: this };\n self.util.setEditing( event, 'points', { points_selector: '> polyline', restrict: false } );\n };\n } );\n\n self.util.setDrawPoly( createNewBaseline, isValidBaseline, finishBaseline, removeElem, self.cfg.baselineMaxPoints );\n\n //self.util.prevEditing();\n\n return false;\n }", "function SimpleLine(scene, startpoint, endpoint) {\n\n // general\n this.id = Nickel.UTILITY.assign_id();\n this.type = 'SimpleLine';\n this.scene = scene;\n this.canvas = scene.canvas;\n this.context = this.canvas.getContext(\"2d\");\n\n // style\n this.stroke_width = 1;\n this.stroke_dash_length = 0;\n this.stroke_gap_length = 0;\n this.stroke_color = null;\n\n // pos\n this.x = startpoint[0];\n this.y = startpoint[1];\n this.xend = endpoint[0];\n this.yend = endpoint[1];\n\n // dir\n this.dx = this.xend - this.x;\n this.dy = this.yend - this.y;\n\n // other\n this.dead = false;\n this.visibility = true;\n\n this.update = function() {\n //-- Called every frame.\n //-- Updates changing parameters.\n //--\n\n // skip if marked for deletion\n if (this.dead == true) {\n return;\n }\n\n // user custom update\n this.update_more();\n\n // render graphics\n this.draw();\n }\n\n this.draw = function() {\n //-- Called every frame. Processes graphics\n //-- based on current parameters.\n //--\n\n // skip if marked for invisibility\n if (this.visibility == false || this.dead == true) {\n return;\n }\n\n // skip if no stroke color\n if (!this.stroke_color) {\n return;\n }\n\n // draw\n var ctx = this.context;\n ctx.save();\n\n // stroke properties\n ctx.lineWidth = this.stroke_width;\n ctx.setLineDash([this.stroke_dash_length, this.stroke_gap_length]);\n ctx.strokeStyle = this.stroke_color;\n\n // draw line\n ctx.beginPath();\n ctx.moveTo(this.x, this.y);\n ctx.lineTo(this.xend, this.yend);\n ctx.stroke();\n\n ctx.restore();\n }\n\n this.destroy = function() {\n //-- Marks current instance for deletion\n //--\n\n this.dead = true;\n this.visibility = false;\n }\n\n this.hide = function() {\n //-- Marks current instance's visibility to hidden\n //--\n\n this.visibility = false;\n }\n\n this.show = function() {\n //-- Marks current instance's visibility to shown\n //--\n\n this.visibility = true;\n }\n\n this.is_visible = function() {\n //-- Returns if self is visible\n //--\n\n return this.visibility;\n }\n\n this.update_more = function() {\n //-- Called in update. Meant to be over-ridden.\n //--\n\n }\n\n this.get_pos = function() {\n //-- returns the start position\n //--\n\n return [this.x, this.y];\n }\n\n this.get_end = function() {\n //-- returns the end position\n //--\n\n return [this.xend, this.yend];\n }\n\n this.get_dir = function() {\n //-- returns the direction vector from start\n //--\n\n return [this.dx, this.dy];\n }\n\n this.get_rot = function() {\n //-- Returns angle (in radians) from start to end\n //--\n\n return Nickel.UTILITY.atan2(-this.dy, this.dx) * 180 / Math.PI;\n }\n\n this.get_center = function() {\n //-- Returns midpoint of linesegment\n //--\n\n return [this.x + this.dx/2, this.y + this.dy/2];\n //return [this.x+(this.xend-this.x)/2, this.y+(this.yend-this.y)/2];\n }\n\n this.set_pos = function(startpoint) {\n //-- Sets the start point, ultimately changing the\n //-- direction vector\n //--\n\n this.x = startpoint[0];\n this.y = startpoint[1];\n this.dx = this.xend - this.x;\n this.dy = this.yend - this.y;\n }\n\n this.set_end = function(endpoint) {\n //-- Sets the end point, ultimately changing the\n //-- direction vector\n //--\n\n this.xend = endpoint[0];\n this.yend = endpoint[1];\n this.dx = this.xend - this.x;\n this.dy = this.yend - this.y;\n }\n\n this.set_dir = function(dir) {\n //-- Sets the direction vector from start,\n //-- ultimately changing the end point\n //--\n\n this.dx = dir[0];\n this.dy = dir[1];\n this.xend = this.x + dir[0];\n this.yend = this.y + dir[1];\n }\n\n this.set_center = function(new_center) {\n //-- Centers midpoint onto a position (expensive)\n //--\n\n var center = this.get_center();\n var difx = new_center[0] - center[0];\n var dify = new_center[1] - center[1];\n\n this.shift_pos(difx, dify);\n }\n\n this.shift_pos = function(shiftx, shifty) {\n //-- Shifts endpoints\n //--\n\n this.x += shiftx;\n this.y += shifty;\n this.xend += shiftx;\n this.yend += shifty;\n\n this.dx = this.xend - this.x;\n this.dy = this.yend - this.y;\n }\n\n this.scale_around = function(scale, point) {\n //-- Scales self's endpoints around a point\n //--\n\n this.scale_around(scale, scale, point);\n }\n\n this.scale_around2 = function(scalex, scaley, point) {\n //-- Scales self's endpoints around a point\n //--\n\n this.x = scalex * (this.x - point[0]) + point[0];\n this.y = scaley * (this.y - point[1]) + point[1];\n this.xend = scalex * (this.xend - point[0]) + point[0];\n this.yend = scaley * (this.yend - point[1]) + point[1];\n }\n\n this.rotate_around = function(degrees, point) {\n //-- Applies a rotation transformation to both endpoints\n //--\n\n var radians = degrees*Math.PI/180*-1;\n var tmpx, tmpy;\n\n tmpx = this.x - point[0];\n tmpy = this.y - point[1];\n this.x = tmpx * Math.cos(radians) - tmpy * Math.sin(radians) + point[0];\n this.y = tmpx * Math.sin(radians) + tmpy * Math.cos(radians) + point[1];\n\n tmpx = this.xend - point[0];\n tmpy = this.yend - point[1];\n this.xend = tmpx * Math.cos(radians) - tmpy * Math.sin(radians) + point[0];\n this.yend = tmpx * Math.sin(radians) + tmpy * Math.cos(radians) + point[1];\n\n this.dx = this.xend - this.x;\n this.dy = this.yend - this.y;\n }\n\n //\n // proxy functions:\n //\n\n this.offset_position = function(offx, offy) {\n //-- shift_pos proxy\n //--\n\n this.shift_pos(offx, offy);\n }\n\n this.offset_turn = function(angle, point) {\n //-- rotate_around proxy\n //--\n\n this.rotate_around(angle, point);\n }\n\n this.offset_scale = function(scale, point) {\n //-- scale_around proxy\n //--\n\n this.scale_around(scale, point);\n }\n}//end SimpleLine", "function ContentChildrenDecorator() { }", "function ContentChildrenDecorator() { }", "function BaseClass() {\n this.initialize();\n }", "renderLineItemsComponent(){\n return(\n <LineItemsComponent\n lineItems={this.state.lineItems}\n data={this.state.data}\n onLineItemDescriptionChange={this.handleLineItemDescriptionChange}\n onLineItemAmountChange={this.handleLineItemAmountChange}\n onAddInvoiceButtonClick={this.handleInvoiceButtonClick}\n />\n );\n }", "function Line() {\n _classCallCheck(this, Line);\n\n /** @type {Array} */\n this.elements = [];\n /** @type {HTMLElement} */\n this.$rendered = null;\n /** @type {Number} */\n this.width = null;\n /** @type {Number} */\n this.left = null;\n /** @type {Number} */\n this.x1 = null;\n /** @type {Number} */\n this.x2 = null;\n /** @type {Number} */\n this.y1 = null;\n /** @type {Number} */\n this.y2 = null;\n /** @type {Number} */\n this.left = null;\n /** @type {Number} */\n this.top = null;\n }", "function Spriteset_Base() {\n this.initialize.apply(this, arguments);\n}", "function CssBaseline(props) {\n /* eslint-disable no-unused-vars */\n var _props$children = props.children,\n children = _props$children === void 0 ? null : _props$children,\n classes = props.classes;\n /* eslint-enable no-unused-vars */\n\n return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_1__[\"createElement\"](react__WEBPACK_IMPORTED_MODULE_1__[\"Fragment\"], null, children);\n}", "function CssBaseline(props) {\n /* eslint-disable no-unused-vars */\n var _props$children = props.children,\n children = _props$children === void 0 ? null : _props$children,\n classes = props.classes;\n /* eslint-enable no-unused-vars */\n\n return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_1__[\"createElement\"](react__WEBPACK_IMPORTED_MODULE_1__[\"Fragment\"], null, children);\n}", "function CssBaseline(props) {\n /* eslint-disable no-unused-vars */\n var _props$children = props.children,\n children = _props$children === void 0 ? null : _props$children,\n classes = props.classes;\n /* eslint-enable no-unused-vars */\n\n return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_1__[\"createElement\"](react__WEBPACK_IMPORTED_MODULE_1__[\"Fragment\"], null, children);\n}", "function OutputLine(parent) {\n var _character_count = 0;\n // use indent_count as a marker for lines that have preserved indentation\n var _indent_count = -1;\n\n var _items = [];\n var _empty = true;\n\n this.set_indent = function(level) {\n _character_count = parent.baseIndentLength + level * parent.indent_length;\n _indent_count = level;\n };\n\n this.get_character_count = function() {\n return _character_count;\n };\n\n this.is_empty = function() {\n return _empty;\n };\n\n this.last = function() {\n if (!this._empty) {\n return _items[_items.length - 1];\n } else {\n return null;\n }\n };\n\n this.push = function(input) {\n _items.push(input);\n _character_count += input.length;\n _empty = false;\n };\n\n this.pop = function() {\n var item = null;\n if (!_empty) {\n item = _items.pop();\n _character_count -= item.length;\n _empty = _items.length === 0;\n }\n return item;\n };\n\n this.remove_indent = function() {\n if (_indent_count > 0) {\n _indent_count -= 1;\n _character_count -= parent.indent_length;\n }\n };\n\n this.trim = function() {\n while (this.last() === ' ') {\n _items.pop();\n _character_count -= 1;\n }\n _empty = _items.length === 0;\n };\n\n this.toString = function() {\n var result = '';\n if (!this._empty) {\n if (_indent_count >= 0) {\n result = parent.indent_cache[_indent_count];\n }\n result += _items.join('');\n }\n return result;\n };\n}", "function OutputLine(parent) {\n var _character_count = 0;\n // use indent_count as a marker for lines that have preserved indentation\n var _indent_count = -1;\n\n var _items = [];\n var _empty = true;\n\n this.set_indent = function(level) {\n _character_count = parent.baseIndentLength + level * parent.indent_length;\n _indent_count = level;\n };\n\n this.get_character_count = function() {\n return _character_count;\n };\n\n this.is_empty = function() {\n return _empty;\n };\n\n this.last = function() {\n if (!this._empty) {\n return _items[_items.length - 1];\n } else {\n return null;\n }\n };\n\n this.push = function(input) {\n _items.push(input);\n _character_count += input.length;\n _empty = false;\n };\n\n this.pop = function() {\n var item = null;\n if (!_empty) {\n item = _items.pop();\n _character_count -= item.length;\n _empty = _items.length === 0;\n }\n return item;\n };\n\n this.remove_indent = function() {\n if (_indent_count > 0) {\n _indent_count -= 1;\n _character_count -= parent.indent_length;\n }\n };\n\n this.trim = function() {\n while (this.last() === ' ') {\n _items.pop();\n _character_count -= 1;\n }\n _empty = _items.length === 0;\n };\n\n this.toString = function() {\n var result = '';\n if (!this._empty) {\n if (_indent_count >= 0) {\n result = parent.indent_cache[_indent_count];\n }\n result += _items.join('');\n }\n return result;\n };\n}", "function BaseLevel()\n\t{\n\t\tthis.gameObjectsArray = [];\n\t\tthis.gameObjects = {};\n\t}", "constructor(){\n //Call constructor in your parent class LightningElement\n super();\n console.log('childLwcDay10 constructor');\n }", "render() {\n return (\n <div className=\"px-3\">\n <hr />\n Visualization method{this.createVisualizationSelector()}\n <hr />\n </div>\n );\n }", "function Base() {\n this.init.apply(this, arguments);\n}", "render() {\n this.getColorsFromCSS();\n this.drawLines();\n }", "constructor() { \n \n InlineObject18.initialize(this);\n }", "constructor(tipo, value, linea) {\n super(linea);\n this.tipo = tipo;\n this.value = value;\n }", "draw() {\n if (!this.lines[1]) { return; }\n let left = this.endpoints[0].x;\n let right = this.endpoints[1].x + this.endpoints[1].boxWidth;\n\n let lOffset = -this.endpoints[0].boxWidth / 2;\n let rOffset = this.endpoints[1].boxWidth / 2;\n\n if (this.endpoints[0].row === this.endpoints[1].row) {\n // draw left side of the brace and align text\n let center = (-left + right) / 2;\n this.x = center + lOffset;\n this.svgText.x(center + lOffset);\n this.lines[0].plot('M' + lOffset + ',33c0,-10,' + [center,0,center,-8]);\n this.lines[1].plot('M' + rOffset + ',33c0,-10,' + [-center,0,-center,-8]);\n }\n else {\n // draw right side of brace extending to end of row and align text\n let center = (-left + this.endpoints[0].row.rw) / 2 + 10;\n this.x = center + lOffset;\n this.svgText.x(center + lOffset);\n\n this.lines[0].plot('M' + lOffset\n + ',33c0,-10,' + [center,0,center,-8]\n + 'c0,10,' + [center,0,center,8]\n );\n this.lines[1].plot('M' + rOffset\n + ',33c0,-10,' + [-right + 8, 0, -right + 8, -8]\n + 'c0,10,' + [-right + 8, 0, -right + 8, 8]\n );\n }\n\n // propagate draw command to parent links\n this.links.forEach(l => l.draw(this));\n }", "function CssBaseline(props) {\n /* eslint-disable no-unused-vars */\n var _props$children = props.children,\n children = _props$children === void 0 ? null : _props$children;\n props.classes;\n /* eslint-enable no-unused-vars */\n\n return /*#__PURE__*/react.exports.createElement(react.exports.Fragment, null, children);\n}", "function Core() {\n this.options = {};\n this.ruler = new ruler();\n for (var i = 0; i < _rules.length; i++) {\n this.ruler.push(_rules[i][0], _rules[i][1]);\n }\n }", "function OogaahTutorialContent4() {\n\tOogaahTutorialContent.apply(this, null); // construct the base class\n}", "function CssBaseline(props) {\n /* eslint-disable no-unused-vars */\n var _props$children = props.children,\n children = _props$children === void 0 ? null : _props$children,\n classes = props.classes;\n /* eslint-enable no-unused-vars */\n\n return /*#__PURE__*/react[\"createElement\"](react[\"Fragment\"], null, children);\n}", "constructor(length, width, height) {\n\n super(length, width)\n //super calls parent class's constructor(the rectangle constructor to establish length and width properties)--need this if adding PROPERTIES\n this.height = height\n\n }", "function SVGBaseElement() {\n }" ]
[ "0.61401486", "0.59537953", "0.5813507", "0.57587916", "0.5717775", "0.5717775", "0.5717775", "0.5717775", "0.5717775", "0.56673896", "0.56312335", "0.5539384", "0.5498428", "0.54636276", "0.54307616", "0.54307616", "0.54307616", "0.54307616", "0.5376955", "0.5366981", "0.5345071", "0.53425974", "0.53425974", "0.533057", "0.52597934", "0.52541375", "0.5244839", "0.5207217", "0.5207217", "0.5196317", "0.51830256", "0.517998", "0.5172717", "0.517115", "0.517115", "0.51576203", "0.51555777", "0.51509833", "0.51472837", "0.5120978", "0.5111489", "0.5111489", "0.51107925", "0.51107925", "0.5105849", "0.5105849", "0.5105849", "0.5091317", "0.50885975", "0.50835323", "0.5080432", "0.50708926", "0.5070388", "0.5047739", "0.5033986", "0.503316", "0.50299954", "0.502339", "0.5016", "0.49777365", "0.49727425", "0.4967422", "0.4967422", "0.4967422", "0.49655518", "0.49655163", "0.49602586", "0.49602586", "0.49567395", "0.49482936", "0.4941334", "0.49361026", "0.49356642", "0.49227217", "0.49110535", "0.49109298", "0.49109298", "0.4904146", "0.49029806", "0.49006015", "0.48952237", "0.48737925", "0.48737925", "0.48737925", "0.48672962", "0.48672962", "0.48604274", "0.48595732", "0.48594508", "0.48521653", "0.48419574", "0.48418906", "0.48390153", "0.48389223", "0.48323995", "0.48211983", "0.4820122", "0.48171753", "0.48154953", "0.48132455" ]
0.72711754
0
! Rectangle of a BoundingBox \class Rectangle
function Rectangle(rect, idCC, idLine){ this.rect = rect; this.idCC = idCC; this.idLine = idLine; this.visible = true; this.selected = false; this.labeled = false; this.hover = false; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function BoundingBoxRect() { }", "function Rectangle(left,top,right,bottom){this.left=left;this.top=top;this.right=right;this.bottom=bottom;}", "function BoundingBox(x, y, width, height) { \n this.width = width;\n this.height = height;\n\n this.left = x;\n this.top = y;\n this.right = this.left + width;\n this.bottom = this.top + height;\n}", "function BoundingBox(rects) {\n this.rects = rects;\n}", "function BoundingBox(topX, topY, totalWidth, totalHeight) {\n this.x = topX;\n this.y = topY;\n this.width = totalWidth;\n this.height = totalHeight;\n}", "function Rectangle(width, height) {\n this.width = width;\n this.height = height;\n}", "function Rectangle(width, height) {\n this.width = width;\n this.height = height;\n}", "function Rectangle(left, top, right, bottom) {\n\tthis.init(new Point((left || 0), (top || 0)), \n\t\t\t\tnew Point((right || 0), (bottom || 0)));\n}", "function Rectangle(height, width) {\n this.height = height;\n this.width = width;\n this.calcArea = function() {\n return this.height * this.width;\n };\n this.height = height;\n this.width = width;\n this.calcPerimeter = function() {\n return 2 * (this.height +this.width);\n };\n\n}", "getBounds(){\n let rect = new Rectangle()\n\t\trect.setRect(this.x, this.y, this.size, this.size)\n\t\treturn rect\n }", "getBounds(){\n let rect = new Rectangle()\n\t\trect.setRect(this.x, this.y, this.size, this.size)\n\t\treturn rect\n }", "static fromBoundingRect(rect) {\n let b = new Bound(new Pt_1.Pt(rect.left || 0, rect.top || 0), new Pt_1.Pt(rect.right || 0, rect.bottom || 0));\n if (rect.width && rect.height)\n b.size = new Pt_1.Pt(rect.width, rect.height);\n return b;\n }", "function Rectangle(width, height) {\n this.width = width;\n this.height = height;\n}", "function Rectangle() {\n _classCallCheck(this, Rectangle);\n\n this.left = -Infinity;\n this.right = Infinity;\n this.bottom = -Infinity;\n this.top = Infinity;\n }", "function Rectangle(w, h){\n this.w = w;\n this.h = h;\n }", "function Rectangle(x, y) {\r\n this.x = x;\r\n this.y = y;\r\n }", "function getRectangle(x, y, width, height) {\n return {\n minX: x,\n maxX: x + width,\n minY: y,\n maxY: y + height\n };\n }", "getBounds() {\n return new Rectangle(new Point(this.x, this.y), new Vector(0, 0));\n }", "function Rectangle(a, b) {\r\n this.length=a\r\n this.width=b\r\n this. perimeter=2*(a+b)\r\n this.area=a*b\r\n \r\n}", "function Rectangle(a, b) {\n this.length = a;\n this.width = b;\n this.area = a * b;\n this.perimeter = 2 * (a + b);\n }", "function Rectangle(a, b) {\n this.length = a;\n this.width = b;\n this.perimeter = 2 * (a + b);\n this.area = a * b;\n}", "get boundingBox() {\n }", "function Rectangle(a, b) {\n this.length = a;\n this.width = b; \n this.perimeter = 2 * (a + b);\n this.area = a * b;\n}", "function boundingBox(x,y,xextent,yextent)\n{\n \n this.x1=x;\n this.y1=y;\n this.x2=x+xextent;\n this.y2=y+yextent;\n this.toString=function(){ return 'boundingBox(('+this.x1+','+this.y1+'),('+this.x2+','+this.y2+'))'; }\n}", "function Rectangle(a, b) {\n return {\n length: a,\n width: b,\n perimeter: 2 * (a + b),\n area : a * b\n }\n}", "getBoundingBox() {\n return new BoundingBox(this.x, this.y, this.width, this.height)\n }", "function BoundingBox() {\n this.x1 = Number.NaN;\n this.y1 = Number.NaN;\n this.x2 = Number.NaN;\n this.y2 = Number.NaN;\n }", "function Rectangle(x,y,width,height){\n\tthis.x=(x==null)?0:x;\n\tthis.y=(y==null)?0:y;\n\tthis.width=(width==null)?0:width;\n\tthis.height=(height==null)?this.width:height;\n\n\t//funcion interseccion dentro de la funcion tipo objeto Rectangulo\n\tthis.intersects=function(rect){\n\t\tif(rect!=null){\n\t\t\treturn(\tthis.x<rect.x+rect.width&&\n\t\t\t\t\tthis.x+this.width>rect.x&&\n\t\t\t\t\tthis.y<rect.y+rect.height&&\n\t\t\t\t\tthis.y+this.height>rect.y);\n\t\t\t//si la condicion se cumple hay una interseccion(retorna true) entonces devuelve true \n\t\t\t\n\t\t\t\n\n\t\t}\n\t}\n\t//esta funcion acepta 4 variables, si se omite alguna se volvera 0 de manera automatica\n\t//para evitar errores excepto en el caso de la height, si se omite este valor se toma por defecto\n\t//el tamaño de el width.\n\n}", "function BoundingBox(x, y, width, height) {\n this.x = x - CAMERA.x;\n this.y = y - CAMERA.y;\n this.width = width;\n this.height = height;\n\n this.left = x;\n this.top = y;\n this.right = this.left + width;\n this.bottom = this.top + height;\n}", "function BoundingBox() {\r\n\t this.x1 = Number.NaN;\r\n\t this.y1 = Number.NaN;\r\n\t this.x2 = Number.NaN;\r\n\t this.y2 = Number.NaN;\r\n\t}", "function Rectangle(height, width) {\n this.height = height;\n this.width = width;\n this.calcArea = function() {\n return this.height * this.width;\n };\n // put our perimeter function here!\n this.calcPerimeter = function(){\n return this.height*2+this.width*2;\n }\n}", "function Rectangle (width,height) {\n this.width = width\n this.height = height\n Quadrilateral.call (this,width,height,width,height)\n}", "function Rectangle(side1, side2, color) {\n Shape.call(this, 4, color, 6);\n this.side1 = side1;\n this.side2 = side2;\n}", "function lbCreateRect2(x, y, width, height) {\n this.x = x;\n this.y = y;\n this.width = width;\n this.height = height;\n}", "function Rectangle(a, b) {\n var o = {\n length: a,\n width: b,\n perimeter: 2 * (a + b),\n area : a * b\n }\n return o;\n}", "function BoundingBox() {\n this.x1 = Number.NaN;\n this.y1 = Number.NaN;\n this.x2 = Number.NaN;\n this.y2 = Number.NaN;\n}", "function BoundingBox() {\n this.x1 = Number.NaN;\n this.y1 = Number.NaN;\n this.x2 = Number.NaN;\n this.y2 = Number.NaN;\n}", "function Bounds()\n{\n /**\n * @member {number}\n * @default 0\n */\n this.minX = Infinity;\n\n /**\n * @member {number}\n * @default 0\n */\n this.minY = Infinity;\n\n /**\n * @member {number}\n * @default 0\n */\n this.maxX = -Infinity;\n\n /**\n * @member {number}\n * @default 0\n */\n this.maxY = -Infinity;\n\n this.rect = null;\n}", "async boundingBox() {\n throw new Error('Not implemented');\n }", "async boundingBox() {\n throw new Error('Not implemented');\n }", "function Rectangle(side1, side2) {\n this.side1 = side1;\n this.side2 = side2;\n}", "function Rectangle(options) {\n options = options || {};\n this.size = options.size || [0,0];\n Body.call(this, options);\n }", "function Rectangle(options) {\n options = options || {};\n this.size = options.size || [0,0];\n Body.call(this, options);\n }", "function Rectangle() {\r\n var _this = _super.call(this) || this;\r\n _this.className = \"Rectangle\";\r\n _this.element = _this.paper.add(\"rect\");\r\n //this.pixelPerfect = false;\r\n _this.applyTheme();\r\n return _this;\r\n }", "function Rectangle() {\n var _this = _super.call(this) || this;\n _this.className = \"Rectangle\";\n _this.element = _this.paper.add(\"rect\");\n //this.pixelPerfect = false;\n _this.applyTheme();\n return _this;\n }", "function Rectangle(length, width) {\n this.length = length;\n this.width = width\n}", "function Rectangle(){\r\n this.x = 0;\r\n this.y = 0;\r\n this.width = 0;\r\n this.height = 0;\r\n this.type = \"rectangle\";\r\n \r\n var argLen = arguments.length;\r\n switch(argLen){\r\n case 1: this._create1(arguments[0]);break;\r\n case 2: this._create2(arguments[0],arguments[1]);break;\r\n case 4: this._create4(arguments[0],arguments[1],arguments[2],arguments[3]);break;\r\n }\r\n \r\n this.getX = function(){ return this.x;};\r\n this.getY = function(){ return this.y;};\r\n this.getWidth = function(){ return this.width;};\r\n this.getHeight = function(){ return this.height;};\r\n}", "getRectangle() {\n return __awaiter(this, void 0, void 0, function* () {\n const location = yield this.location();\n const size = yield this.size();\n const rect = { x: location.x, y: location.y, width: size.y, height: size.x };\n return rect;\n });\n }", "function BoundingBox() {\n this.halfExtent = new Vector3();\n}", "function Rectangle(length, width) {\n this.length = length;\n this.width = width;\n}", "function Rect(point, width, height) {\n this.point = point;\n this.width = width; \n this.height = height;\n}", "static createRectangle(x, y, width, height) {\n return new Rectangle(x, y, width, height)\n }", "function drawRectangle() {\n clearGeometry();\n drawingTools.setShape('rectangle');\n drawingTools.draw();\n}", "function Rectangle(sideLengthOne, sideLengthTwo, color) { // TODO: THIS IS JUST A PLACE HOLDER, PLEASE CHANGE.\n\tShape.call(this, 4, color);\n\tthis.sideLengthOne = sideLengthOne;\n\tthis.sideLengthTwo = sideLengthTwo;\n}", "function CreateRectangle() {\n var bounds = new google.maps.LatLngBounds(\n new google.maps.LatLng(0, 0),\n new google.maps.LatLng(1, 1));\n rectangle = new google.maps.Rectangle({\n bounds : bounds,\n fillOpacity : 0.2,\n strokeOpacity : 0.8,\n draggable : true,\n editable : true\n });\n google.maps.event.addListener(rectangle, 'mousedown', function() {rectangleIsDragged = true;});\n google.maps.event.addListener(rectangle, 'mouseup', function() {rectangleIsDragged = false;});\n if ($(\"#results-panel\").length > 0)\n google.maps.event.addListener(rectangle, 'bounds_changed', aggregateQuery);\n}", "function getArea(rectangle) {\n return rectangle.width * rectangle.height;\n}", "getBoundingBox() {\n return this.box;\n }", "rectifyBBox (bbox) {\n // horizontal top\n if (bbox[0].y != bbox[1].y) {\n let ymin = Math.min(bbox[0].y, bbox[1].y)\n bbox[0].y = ymin\n bbox[1].y = ymin\n }\n\n // horizontal bottom\n if (bbox[3].y != bbox[2].y) {\n let ymax = Math.max(bbox[3].y, bbox[2].y)\n bbox[3].y = ymax\n bbox[2].y = ymax\n }\n\n // vertical right\n if (bbox[1].x != bbox[2].x) {\n let xmax = Math.max(bbox[1].x, bbox[2].x)\n bbox[1].x = xmax\n bbox[2].x = xmax\n }\n\n // vertical left\n if (bbox[0].x != bbox[3].x) {\n let xmin = Math.min(bbox[0].x, bbox[3].x)\n bbox[0].x = xmin\n bbox[3].x = xmin\n }\n\n return bbox\n }", "function Rect (x1, y1, x2, y2) {\n \n \n this.left = x1;\n this.right = x2;\n this.top = y1;\n this.bottom = y2;\n}", "function Rectangle(length, width, color) {\n // TODO: THIS IS JUST A PLACE HOLDER, PLEASE CHANGE.\n Shape.call(this, 4, color);\n this.length = length;\n this.width = width;\n}", "function make_rect(tl, br) {\n return { \n \"x\" : tl.x,\n \"y\" : tl.y,\n \"width\" : br.x - tl.x,\n \"height\" : br.y - tl.y,\n };\n}", "function hb_rect(self,value) {\n switch (value) {\n case 0: return self.pos[0] - self.width/2;\n case 1: return self.pos[1] - self.height;\n case 2: return self.pos[0] + self.width/2;\n case 3: return self.pos[1];\n }\n }", "function boundArea(x, y, w, h){\n\tthis.x = x;\n\tthis.y = y;\n\tthis.w = w;\n\tthis.h = h;\n}", "function Rectangle(x, y, width, height) {\r\n this.x = (x == null) ? 0 : x;\r\n this.y = (y == null) ? 0 : y;\r\n this.width = (width == null) ? 0 : width;\r\n this.height = (height == null) ? this.width : height;\r\n this.intersects = function (rect) {\r\n if (rect == null) {\r\n window.console.warn('Missing parameters on function intersects');\r\n } else {\r\n return (this.x < rect.x + rect.width &&\r\n this.x + this.width > rect.x &&\r\n this.y < rect.y + rect.height &&\r\n this.y + this.height > rect.y);\r\n }\r\n};\r\n\r\n\r\nthis.fill = function (ctx) {\r\n if (ctx == null) {\r\n window.console.warn('Missing parameters on function fill');\r\n } else {\r\n ctx.fillRect(this.x, this.y, this.width, this.height);\r\n }\r\n};\r\n}", "get boundingBox() {\n return this._boundingBox;\n }", "async boundingBox() {\n const result = await this._getBoxModel();\n if (!result)\n return null;\n const quad = result.model.border;\n const x = Math.min(quad[0], quad[2], quad[4], quad[6]);\n const y = Math.min(quad[1], quad[3], quad[5], quad[7]);\n const width = Math.max(quad[0], quad[2], quad[4], quad[6]) - x;\n const height = Math.max(quad[1], quad[3], quad[5], quad[7]) - y;\n return { x, y, width, height };\n }", "async boundingBox() {\n const result = await this._getBoxModel();\n if (!result)\n return null;\n const quad = result.model.border;\n const x = Math.min(quad[0], quad[2], quad[4], quad[6]);\n const y = Math.min(quad[1], quad[3], quad[5], quad[7]);\n const width = Math.max(quad[0], quad[2], quad[4], quad[6]) - x;\n const height = Math.max(quad[1], quad[3], quad[5], quad[7]) - y;\n return { x, y, width, height };\n }", "async boundingBox() {\n const result = await this._getBoxModel();\n if (!result)\n return null;\n const quad = result.model.border;\n const x = Math.min(quad[0], quad[2], quad[4], quad[6]);\n const y = Math.min(quad[1], quad[3], quad[5], quad[7]);\n const width = Math.max(quad[0], quad[2], quad[4], quad[6]) - x;\n const height = Math.max(quad[1], quad[3], quad[5], quad[7]) - y;\n return { x, y, width, height };\n }", "boundary(x, y, width, height) {\n\t\tvar poly = this.add.rectangle(x, y, width, height, COLOR.OUTER);\n\t\treturn this.matter.add.gameObject(poly, {\n\t\t\tisStatic: true,\n\t\t\tshape: {\n\t\t\t\ttype: 'rectangle',\n\t\t\t\tx: x,\n\t\t\t\ty: y,\n\t\t\t\twidth: width,\n\t\t\t\theight: height,\n\t\t\t\tflagInternal: false\n\t\t\t},\n\t\t\trender: {\n\t\t\t\tfillStyle: COLOR.OUTER,\n\t\t\t\tlineColor: COLOR.OUTER\n\t\t\t}\n\t\t},\n\t\t);\n\n\n\t\t// return this.matter.add.rectangle(x, y, width, height, {\n\t\t// \t//engine.bodies.rectangle(x, y, width, height, {\n\t\t// \t//Matter.Bodies.rectangle(x, y, width, height, {\n\t\t// \tisStatic: true,\n\t\t// \trender: {\n\t\t// \t\tfillStyle: COLOR.OUTER,\n\t\t// \t\tfillColor: COLOR.OUTER\n\t\t// \t}\n\t\t// });\n\t}", "function Rectangle(length, width) {\n\tthis.length = length;\n\tthis.width = width;\n}", "function __Rect(x, y, width, height) {\n this.x1 = x || 0;\n this.y1 = y || 0;\n this.width = width || 0;\n this.height = height || 0;\n this.x2 = this.x1 + this.width;\n this.y2 = this.y1 + this.height;\n\n return this;\n }", "function Rectangle(_ref) {\n var x = _ref.x,\n y = _ref.y,\n width = _ref.width,\n height = _ref.height,\n children = _ref.children,\n props = _objectWithoutProperties(_ref, [\"x\", \"y\", \"width\", \"height\", \"children\"]);\n\n var command = useCallback(function (p) {\n handleCommonProps(props, p);\n p.rect.apply(p, _toConsumableArray(handleValueOrFunction(p, x, y, width, height)));\n }, [props, x, y, width, height]);\n return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(Command, {\n command: command\n }), children);\n}", "getWorldBounds() {\n const left = this.screenToWorldCoordinates(Vector.Zero).x;\n const top = this.screenToWorldCoordinates(Vector.Zero).y;\n const right = left + this.drawWidth;\n const bottom = top + this.drawHeight;\n return new BoundingBox(left, top, right, bottom);\n }", "function addBoundingBox(bbox) {\n if (rectangle === undefined) {\n rectangle = L.rectangle(bbox, {color: 'blue', weight: 1}).addTo(map);\n } else {\n rectangle.setBounds(bbox);\n }\n}", "get boundingBox() {\n throw this._notImplemented(\"get boundingBox\");\n }", "function Rect() {\n\tthis.left = 0;\n\tthis.right = 0;\n\tthis.top = 0;\n\tthis.bottom = 0;\n\tthis.toString = rectToString;\n}", "function OldRectangles(width, height) {\n this.width = width;\n this.height = height;\n}", "function rectangle(width, height, x, y) {\n if (!_utils_Type__WEBPACK_IMPORTED_MODULE_1__[\"isNumber\"](x)) {\n x = 0;\n }\n if (!_utils_Type__WEBPACK_IMPORTED_MODULE_1__[\"isNumber\"](y)) {\n y = 0;\n }\n return moveTo({ x: x, y: y }) + lineTo({ x: x + width, y: y }) + lineTo({ x: x + width, y: y + height }) + lineTo({ x: x, y: y + height }) + closePath();\n}", "function rectangle(height, width, x, y) {\n var rect = [x, y, 0,\n x + width, y, 0,\n x + width, y + height, 0,\n x, y + height, 0\n ];\n return rect;\n}", "createTheoriticalBoundingBox(x, y) {\n var temp = new BoundingBox(x, y, this.width, this.height)\n temp.entity = this.entity;\n return temp;\n }", "boundingRect(width, height) {\n if (arguments.length === 0) {\n return [this.opts.boundingWidth, this.opts.boundingHeight];\n }\n\n if (arguments.length >= 1 && isDefined(width)) {\n const minWidth = this.option('margin.left') + this.option('margin.right');\n if (width < minWidth) { width = minWidth; }\n this.opts.boundingWidth = width;\n }\n\n if (arguments.length === 2 && isDefined(height)) {\n const minHeight = this.option('margin.top') + this.option('margin.bottom');\n if (height < minHeight) { height = minHeight; }\n this.opts.boundingHeight = height;\n }\n\n this._boundsUpdate();\n this.update();\n\n return this;\n }", "function Rect(){\n\t\tvar input = argFormatter(arguments, {\n\t\t\tname: \"Rect\",\n\t\t\tdefinition: [\n\t\t\t\t{name: \"x\", type: \"number\"},\n\t\t\t\t{name: \"y\", type: \"number\"},\n\t\t\t\t{name: \"width\", type: \"number\"},\n\t\t\t\t{name: \"height\", type: \"number\"},\n\t\t\t\t{name: \"cornerRadius\", type: \"number\", optional: true, default: 0}\n\t\t\t]\n\t\t}, true), args = input.arguments;\n\n\t\tTransformable.call(this, args.x, args.y, args.width, args.height);\n\n\t\tthis.set(\"cornerRadius\", args.cornerRadius);\n\t}", "function rect(location, corner) {\n return new Rectangle(location.x, location.y, corner.x - location.x, corner.y - location.y);\n}", "function Rect(p1, p2) {\n this.p1 = p1;\n this.p2 = p2;\n}", "function drawRectangle() {\n}", "function BoundingBox(leftOrOptions, top, right, bottom) {\n if (leftOrOptions === void 0) { leftOrOptions = 0; }\n if (top === void 0) { top = 0; }\n if (right === void 0) { right = 0; }\n if (bottom === void 0) { bottom = 0; }\n if (typeof leftOrOptions === 'object') {\n this.left = leftOrOptions.left;\n this.top = leftOrOptions.top;\n this.right = leftOrOptions.right;\n this.bottom = leftOrOptions.bottom;\n }\n else if (typeof leftOrOptions === 'number') {\n this.left = leftOrOptions;\n this.top = top;\n this.right = right;\n this.bottom = bottom;\n }\n }", "function rectangleArea(width, height) {\n\tvar area = width * height;\n\treturn 'width: ' + width + ' height: ' + height + ' Rectangle\\'s area is: ' + area;\n}", "setRectangle() {\n this.gene = makeRectangle(this.size, this.size - 10);\n }", "function Rectangles(sideA, sideB){\n this.sideA = sideA\n this.sideB = sideB\n}", "bbox() {\n let maxX = -Infinity\n let maxY = -Infinity\n let minX = Infinity\n let minY = Infinity\n this.forEach(function (el) {\n maxX = Math.max(el[0], maxX)\n maxY = Math.max(el[1], maxY)\n minX = Math.min(el[0], minX)\n minY = Math.min(el[1], minY)\n })\n return new Box(minX, minY, maxX - minX, maxY - minY)\n }", "function CreateRectangle(x, y, width, height, option, rate) {\n return Matter.Bodies.rectangle(x * rate, y * rate, width * rate, height * rate, option);\n}", "function Rect(x, y, w, h) {\n this.x = x; this.y = y;\n this.w = w; this.h = h;\n}", "bbox() {\n let width = this.box.attr(\"width\");\n let height = this.box.attr(\"height\");\n let x = this.box.attr(\"x\");\n let y = this.box.attr(\"y\");\n let cy = y + height / 2;\n let cx = x + width / 2;\n\n return {\n width: width,\n height: height,\n x: x,\n y: y,\n cx: cx,\n cy: cy\n };\n }", "function Rect( xmin , ymin , xmax , ymax ) {\n\tvar src = xmin ;\n\n\tthis.xmin = 0 ;\n\tthis.xmax = 0 ;\n\tthis.ymin = 0 ;\n\tthis.ymax = 0 ;\n\tthis.width = 0 ;\n\tthis.height = 0 ;\n\tthis.isNull = true ;\n\n\tif ( src && ( typeof src === 'object' || typeof src === 'function' ) ) {\n\t\tif ( src instanceof termkit.Terminal ) {\n\t\t\tthis.set( {\n\t\t\t\txmin: 1 ,\n\t\t\t\tymin: 1 ,\n\t\t\t\txmax: src.width ,\n\t\t\t\tymax: src.height\n\t\t\t} ) ;\n\t\t}\n\t\telse if ( src instanceof termkit.ScreenBuffer ) {\n\t\t\tthis.set( {\n\t\t\t\txmin: 0 ,\n\t\t\t\tymin: 0 ,\n\t\t\t\txmax: src.width - 1 ,\n\t\t\t\tymax: src.height - 1\n\t\t\t} ) ;\n\t\t}\n\t\telse if ( src instanceof termkit.TextBuffer ) {\n\t\t\tthis.set( {\n\t\t\t\txmin: 0 ,\n\t\t\t\tymin: 0 ,\n\t\t\t\txmax: src.width - 1 ,\n\t\t\t\tymax: src.height - 1\n\t\t\t} ) ;\n\t\t}\n\t\telse if ( src instanceof Rect ) {\n\t\t\tthis.set( src ) ;\n\t\t}\n\t\telse if ( src.xmin !== undefined || src.ymin !== undefined || src.xmax !== undefined || src.ymax !== undefined ) {\n\t\t\tthis.set( {\n\t\t\t\txmin: src.xmin !== undefined ? src.xmin : 0 ,\n\t\t\t\tymin: src.ymin !== undefined ? src.ymin : 0 ,\n\t\t\t\txmax: src.xmax !== undefined ? src.xmax : 1 ,\n\t\t\t\tymax: src.ymax !== undefined ? src.ymax : 1\n\t\t\t} ) ;\n\t\t}\n\t\telse if ( src.x !== undefined || src.y !== undefined || src.width !== undefined || src.height !== undefined ) {\n\t\t\tthis.set( {\n\t\t\t\txmin: src.x !== undefined ? src.x : 0 ,\n\t\t\t\tymin: src.y !== undefined ? src.y : 0 ,\n\t\t\t\txmax: src.width !== undefined ? src.x + src.width - 1 : 1 ,\n\t\t\t\tymax: src.height !== undefined ? src.y + src.height - 1 : 1\n\t\t\t} ) ;\n\t\t}\n\t}\n\telse {\n\t\tthis.set( {\n\t\t\txmin: xmin !== undefined ? xmin : 0 ,\n\t\t\tymin: ymin !== undefined ? ymin : 0 ,\n\t\t\txmax: xmax !== undefined ? xmax : 1 ,\n\t\t\tymax: ymax !== undefined ? ymax : 1\n\t\t} ) ;\n\t}\n}", "function normalizeRect(rect) {\n\t return BoundingRect.create(rect);\n\t}", "get rect():Object {\n\t\treturn this._rect = this._rect || new XY.Rect(this.origin.x, this.origin.y, this._width, this._height);\n\t}", "function getRectangleArea(width, height) {\r\n\r\n let RectangleArea = width * height;\r\n\r\n return (width * height);\r\n}", "function BoundingBox(sprite) {\n\n\n // --\n // ------- PROPERTIES ----------------------------------------\n // --\n\n\n // general\n this.id = Nickel.UTILITY.assign_id();\n this.type = 'BoundingBox';\n\n // pos\n this.left = 0;\n this.right = 0;\n this.top = 0;\n this.bottom = 0;\n\n // size\n this.w = 0;\n this.h = 0;\n\n // parent\n this.target = sprite;\n\n // indicates if we have already bounded around the sprite\n this.updated = false;\n\n\n // --\n // ------- METHODS -------------------------------------------\n // --\n\n\n this.update = function() {\n //-- Main update function\n //--\n\n // indicate that we must bound self when needed\n this.updated = false;\n }\n\n this.bound = function(force_bound=false) {\n //-- Bounds self around a target sprite\n //--\n\n // ignore if this function if we already updated\n if (this.updated && !force_bound) return;\n\n // indicate that we have bounded self\n this.updated = true;\n\n // corners of sprite\n var tl = this.target.get_topleft();\n var tr = this.target.get_topright();\n var bl = this.target.get_bottomleft();\n var br = this.target.get_bottomright();\n\n // top left of bbox\n var AXnew = Math.min(tl[0], tr[0], bl[0], br[0]);\n var AYnew = Math.min(tl[1], tr[1], bl[1], br[1]);\n\n // dimensions of bbox\n var Wnew = Math.max(tl[0], tr[0], bl[0], br[0]) - AXnew;\n var Hnew = Math.max(tl[1], tr[1], bl[1], br[1]) - AYnew;\n\n // apply\n this.left = AXnew;\n this.right = AXnew + Wnew;\n this.top = AYnew;\n this.bottom = AYnew + Hnew;\n this.w = Wnew;\n this.h = Hnew;\n }\n\n this.get_cx = function() {\n //-- Returns the center x pos of the bbox\n //--\n\n return this.left + this.w / 2;\n }\n\n this.get_cy = function() {\n //-- Returns the center y pos of the bbox\n //--\n\n return this.top + this.h / 2;\n }\n\n this.get_center = function() {\n //-- Returns the center pos of the bbox\n //--\n\n return [this.get_cx(),this.get_cy()];\n }\n\n}//end BoundingBox", "bbox() {\n var maxX = -Infinity;\n var maxY = -Infinity;\n var minX = Infinity;\n var minY = Infinity;\n this.forEach(function (el) {\n maxX = Math.max(el[0], maxX);\n maxY = Math.max(el[1], maxY);\n minX = Math.min(el[0], minX);\n minY = Math.min(el[1], minY);\n });\n return {\n x: minX,\n y: minY,\n width: maxX - minX,\n height: maxY - minY\n };\n }", "function Rect(x, y, w, h) {\n this.x = x;\n this.y = y;\n this.width = w;\n this.height = h;\n}" ]
[ "0.8464728", "0.7720044", "0.76760346", "0.76466966", "0.7542002", "0.75321186", "0.75321186", "0.7531904", "0.75220364", "0.75114924", "0.75114924", "0.7498288", "0.74518615", "0.7394226", "0.73913777", "0.73857254", "0.7366572", "0.7364287", "0.7357801", "0.7348406", "0.734775", "0.73400927", "0.7337631", "0.7294348", "0.7278063", "0.7258727", "0.72457117", "0.7183261", "0.7166148", "0.71314776", "0.71197397", "0.7112803", "0.7091182", "0.70908695", "0.7088894", "0.7086048", "0.7086048", "0.7052979", "0.70434546", "0.70434546", "0.70347595", "0.70337373", "0.70337373", "0.70093924", "0.6998612", "0.6981371", "0.69799846", "0.6974568", "0.69600797", "0.6949177", "0.69430757", "0.694102", "0.69298786", "0.6926493", "0.69055134", "0.69021416", "0.68951505", "0.68943936", "0.6878944", "0.6875407", "0.68530786", "0.6834165", "0.6820131", "0.6817224", "0.6797127", "0.679655", "0.679655", "0.679655", "0.6782387", "0.6756865", "0.6754677", "0.6718385", "0.67165613", "0.6714713", "0.67081475", "0.6707289", "0.6704962", "0.6691556", "0.66821295", "0.66747564", "0.6672305", "0.6666086", "0.6655207", "0.66530645", "0.6652915", "0.66448337", "0.66364694", "0.6636183", "0.66351134", "0.66323286", "0.6631385", "0.6621219", "0.66109645", "0.6595733", "0.65923464", "0.6591659", "0.6573595", "0.65721935", "0.6570767", "0.6545408" ]
0.70361125
40
! Container of all BoundingBox \class BoundingBox
function BoundingBox(rects) { this.rects = rects; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function BoundingBoxRect() { }", "GetBoundingBoxes()\n\t{\n\t\treturn Object.values(this.collection).map(function(component)\n\t\t{\n\t\t\treturn {\n\t\t\t\tcomponent: component,\n\t\t\t\tBB: component._getBoundingBox()\n\t\t\t};\n\t\t});\n\t}", "function BoundingBox() {\n this.x1 = Number.NaN;\n this.y1 = Number.NaN;\n this.x2 = Number.NaN;\n this.y2 = Number.NaN;\n }", "function BoundingBox(topX, topY, totalWidth, totalHeight) {\n this.x = topX;\n this.y = topY;\n this.width = totalWidth;\n this.height = totalHeight;\n}", "getBoundingBox() {\n return new BoundingBox(this.x, this.y, this.width, this.height)\n }", "function BoundingBox(x, y, width, height) { \n this.width = width;\n this.height = height;\n\n this.left = x;\n this.top = y;\n this.right = this.left + width;\n this.bottom = this.top + height;\n}", "function BoundingBox() {\r\n\t this.x1 = Number.NaN;\r\n\t this.y1 = Number.NaN;\r\n\t this.x2 = Number.NaN;\r\n\t this.y2 = Number.NaN;\r\n\t}", "get boundingBox() {\n }", "function BoundingBox() {\n this.x1 = Number.NaN;\n this.y1 = Number.NaN;\n this.x2 = Number.NaN;\n this.y2 = Number.NaN;\n}", "function BoundingBox() {\n this.x1 = Number.NaN;\n this.y1 = Number.NaN;\n this.x2 = Number.NaN;\n this.y2 = Number.NaN;\n}", "function boundingBox() {\n for (let node of nodes) {\n // If the positions exceed the box, set them to the boundary position.\n var yearX = xSmallScale.bandwidth() * ((node.year - minYear) / 4 + 0.6) // xSmallScale.bandwidth() * ((node.year - minYear) / 4 + 0.1)\n node.x = Math.max(Math.min(node.x, yearX + xSmallScale.bandwidth() / 2.5 - medalRadius), yearX - xSmallScale.bandwidth() / 2.5 + medalRadius);\n node.y = Math.max(Math.min(innerHeight - medalRadius, node.y), 0 + medalRadius);\n }\n }", "function BoundingBox() {\n this.halfExtent = new Vector3();\n}", "getBoundingBox() {\n return this.box;\n }", "async boundingBox() {\n throw new Error('Not implemented');\n }", "async boundingBox() {\n throw new Error('Not implemented');\n }", "function BoundingBox(x, y, width, height) {\n this.x = x - CAMERA.x;\n this.y = y - CAMERA.y;\n this.width = width;\n this.height = height;\n\n this.left = x;\n this.top = y;\n this.right = this.left + width;\n this.bottom = this.top + height;\n}", "get boundingBox() {\n return this._boundingBox;\n }", "function BoundingBox(sprite) {\n\n\n // --\n // ------- PROPERTIES ----------------------------------------\n // --\n\n\n // general\n this.id = Nickel.UTILITY.assign_id();\n this.type = 'BoundingBox';\n\n // pos\n this.left = 0;\n this.right = 0;\n this.top = 0;\n this.bottom = 0;\n\n // size\n this.w = 0;\n this.h = 0;\n\n // parent\n this.target = sprite;\n\n // indicates if we have already bounded around the sprite\n this.updated = false;\n\n\n // --\n // ------- METHODS -------------------------------------------\n // --\n\n\n this.update = function() {\n //-- Main update function\n //--\n\n // indicate that we must bound self when needed\n this.updated = false;\n }\n\n this.bound = function(force_bound=false) {\n //-- Bounds self around a target sprite\n //--\n\n // ignore if this function if we already updated\n if (this.updated && !force_bound) return;\n\n // indicate that we have bounded self\n this.updated = true;\n\n // corners of sprite\n var tl = this.target.get_topleft();\n var tr = this.target.get_topright();\n var bl = this.target.get_bottomleft();\n var br = this.target.get_bottomright();\n\n // top left of bbox\n var AXnew = Math.min(tl[0], tr[0], bl[0], br[0]);\n var AYnew = Math.min(tl[1], tr[1], bl[1], br[1]);\n\n // dimensions of bbox\n var Wnew = Math.max(tl[0], tr[0], bl[0], br[0]) - AXnew;\n var Hnew = Math.max(tl[1], tr[1], bl[1], br[1]) - AYnew;\n\n // apply\n this.left = AXnew;\n this.right = AXnew + Wnew;\n this.top = AYnew;\n this.bottom = AYnew + Hnew;\n this.w = Wnew;\n this.h = Hnew;\n }\n\n this.get_cx = function() {\n //-- Returns the center x pos of the bbox\n //--\n\n return this.left + this.w / 2;\n }\n\n this.get_cy = function() {\n //-- Returns the center y pos of the bbox\n //--\n\n return this.top + this.h / 2;\n }\n\n this.get_center = function() {\n //-- Returns the center pos of the bbox\n //--\n\n return [this.get_cx(),this.get_cy()];\n }\n\n}//end BoundingBox", "function boundingBox(x,y,xextent,yextent)\n{\n \n this.x1=x;\n this.y1=y;\n this.x2=x+xextent;\n this.y2=y+yextent;\n this.toString=function(){ return 'boundingBox(('+this.x1+','+this.y1+'),('+this.x2+','+this.y2+'))'; }\n}", "bbox() {\n let maxX = -Infinity\n let maxY = -Infinity\n let minX = Infinity\n let minY = Infinity\n this.forEach(function (el) {\n maxX = Math.max(el[0], maxX)\n maxY = Math.max(el[1], maxY)\n minX = Math.min(el[0], minX)\n minY = Math.min(el[1], minY)\n })\n return new Box(minX, minY, maxX - minX, maxY - minY)\n }", "function BoundingBox() {\n var bounds = map.getBounds().getSouthWest().lng + \",\" + map.getBounds().getSouthWest().lat + \",\" + map.getBounds().getNorthEast().lng + \",\" + map.getBounds().getNorthEast().lat;\n return bounds;\n}", "function make_bounding_box(boudingBox){\n i = boundingBox.vertices\n thick = 100\n length = 2 * Math.abs(i[1].x - i[0].x)\n return [{\n dimensions: { h: thick, w: length}, // most likely assume in mm (1mm = 3.779528px)\n coordinates: { x: i[1].x, y: i[1].y-thick/2}, // in px also may be undefined (when initializing)\n rotation: 0, // in degrees\n pinned: true,\n nodes: [{x: 0, y: 20, color: 4}]\n },\n {\n dimensions: { h: thick, w: length}, // most likely assume in mm (1mm = 3.779528px)\n coordinates: { x: i[2].x+thick/2, y: i[2].y}, // in px also may be undefined (when initializing)\n rotation: 90, // in degrees\n pinned: true,\n nodes: [{x: 0, y: 20, color: 4}]\n },\n {\n dimensions: { h: thick, w: length}, // most likely assume in mm (1mm = 3.779528px)\n coordinates: { x: i[3].x, y: i[3].y+thick/2}, // in px also may be undefined (when initializing)\n rotation: 180, // in degrees\n pinned: true,\n nodes: [{x: 0, y: 20, color: 4}]\n },\n {\n dimensions: { h: thick, w: length}, // most likely assume in mm (1mm = 3.779528px)\n coordinates: { x: i[0].x-thick/2, y: i[0].y}, // in px also may be undefined (when initializing)\n rotation: 270, // in degrees\n pinned: true,\n nodes: [{x: 0, y: 20, color: 4}]\n }]\n}", "get boundingBox() {\n throw this._notImplemented(\"get boundingBox\");\n }", "getBoundingBox() {\n\t\t\t\tvar w = this.animation.getWidth() * abs(this._getScaleX());\n\t\t\t\tvar h = this.animation.getHeight() * abs(this._getScaleY());\n\n\t\t\t\t//if the bounding box is 1x1 the image is not loaded\n\t\t\t\t//potential issue with actual 1x1 images\n\t\t\t\tif (w === 1 && h === 1) {\n\t\t\t\t\t//not loaded yet\n\t\t\t\t\treturn new AABB(this.position, this.p.createVector(w, h));\n\t\t\t\t} else {\n\t\t\t\t\treturn new AABB(this.position, this.p.createVector(w, h));\n\t\t\t\t}\n\t\t\t}", "get boundingBox() { return GeoJsonUtils.getBoundingBox(this.item); }", "function boundingBox( jqNode, jqGraph, box ) {\n var v = jqNode.offset();\n var graphOffset = jqGraph.offset();\n var top = v.top - graphOffset.top;\n var left = v.left - graphOffset.left;\n box = box || {};\n box.top = top;\n box.left = left;\n box.right = left + jqNode.width();\n box.bottom = top + jqNode.height();\n return box;\n }", "async boundingBox() {\n const result = await this._getBoxModel();\n if (!result)\n return null;\n const quad = result.model.border;\n const x = Math.min(quad[0], quad[2], quad[4], quad[6]);\n const y = Math.min(quad[1], quad[3], quad[5], quad[7]);\n const width = Math.max(quad[0], quad[2], quad[4], quad[6]) - x;\n const height = Math.max(quad[1], quad[3], quad[5], quad[7]) - y;\n return { x, y, width, height };\n }", "async boundingBox() {\n const result = await this._getBoxModel();\n if (!result)\n return null;\n const quad = result.model.border;\n const x = Math.min(quad[0], quad[2], quad[4], quad[6]);\n const y = Math.min(quad[1], quad[3], quad[5], quad[7]);\n const width = Math.max(quad[0], quad[2], quad[4], quad[6]) - x;\n const height = Math.max(quad[1], quad[3], quad[5], quad[7]) - y;\n return { x, y, width, height };\n }", "async boundingBox() {\n const result = await this._getBoxModel();\n if (!result)\n return null;\n const quad = result.model.border;\n const x = Math.min(quad[0], quad[2], quad[4], quad[6]);\n const y = Math.min(quad[1], quad[3], quad[5], quad[7]);\n const width = Math.max(quad[0], quad[2], quad[4], quad[6]) - x;\n const height = Math.max(quad[1], quad[3], quad[5], quad[7]) - y;\n return { x, y, width, height };\n }", "bbox() {\n let width = this.box.attr(\"width\");\n let height = this.box.attr(\"height\");\n let x = this.box.attr(\"x\");\n let y = this.box.attr(\"y\");\n let cy = y + height / 2;\n let cx = x + width / 2;\n\n return {\n width: width,\n height: height,\n x: x,\n y: y,\n cx: cx,\n cy: cy\n };\n }", "_estimateBoundingBox()\n\t{\n\t\t// take the alignment into account:\n\t\tthis._boundingBox = new PIXI.Rectangle(\n\t\t\tthis._pos[0] - this._size[0] / 2.0,\n\t\t\tthis._pos[1] - this._size[1] / 2.0,\n\t\t\tthis._size[0],\n\t\t\tthis._size[1],\n\t\t);\n\t}", "bbox() {\n var maxX = -Infinity;\n var maxY = -Infinity;\n var minX = Infinity;\n var minY = Infinity;\n this.forEach(function (el) {\n maxX = Math.max(el[0], maxX);\n maxY = Math.max(el[1], maxY);\n minX = Math.min(el[0], minX);\n minY = Math.min(el[1], minY);\n });\n return {\n x: minX,\n y: minY,\n width: maxX - minX,\n height: maxY - minY\n };\n }", "_estimateBoundingBox()\n\t{\n\t\tconst size = this._getDisplaySize();\n\t\tif (typeof size !== \"undefined\")\n\t\t{\n\t\t\tthis._boundingBox = new PIXI.Rectangle(\n\t\t\t\tthis._pos[0] - size[0] / 2,\n\t\t\t\tthis._pos[1] - size[1] / 2,\n\t\t\t\tsize[0],\n\t\t\t\tsize[1],\n\t\t\t);\n\t\t}\n\n\t\t// TODO take the orientation into account\n\t}", "function BoundingBox(leftOrOptions, top, right, bottom) {\n if (leftOrOptions === void 0) { leftOrOptions = 0; }\n if (top === void 0) { top = 0; }\n if (right === void 0) { right = 0; }\n if (bottom === void 0) { bottom = 0; }\n if (typeof leftOrOptions === 'object') {\n this.left = leftOrOptions.left;\n this.top = leftOrOptions.top;\n this.right = leftOrOptions.right;\n this.bottom = leftOrOptions.bottom;\n }\n else if (typeof leftOrOptions === 'number') {\n this.left = leftOrOptions;\n this.top = top;\n this.right = right;\n this.bottom = bottom;\n }\n }", "function Bounds()\n{\n /**\n * @member {number}\n * @default 0\n */\n this.minX = Infinity;\n\n /**\n * @member {number}\n * @default 0\n */\n this.minY = Infinity;\n\n /**\n * @member {number}\n * @default 0\n */\n this.maxX = -Infinity;\n\n /**\n * @member {number}\n * @default 0\n */\n this.maxY = -Infinity;\n\n this.rect = null;\n}", "function azureCVObjsToCogniBoundingBox(azureCVObjects, width, height){\n for(let aObj of azureCVObjects){\n let bl = { 'x': aObj['rectangle']['x'],\n 'y': (aObj['rectangle']['y']+aObj['rectangle']['h'] > height)? aObj['rectangle']['y']+aObj['rectangle']['h']:height\n };\n let br = { 'x': (aObj['rectangle']['x']+aObj['rectangle']['w'] < width)? aObj['rectangle']['x']+aObj['rectangle']['w']:width,\n 'y': (aObj['rectangle']['y']+aObj['rectangle']['h'] > height)? aObj['rectangle']['y']+aObj['rectangle']['h']:height\n };\n let tl = { 'x': aObj['rectangle']['x'],\n 'y': aObj['rectangle']['y'],\n };\n let tr = { 'x': (aObj['rectangle']['x']+aObj['rectangle']['w']<width)? aObj['rectangle']['x']+aObj['rectangle']['w']:width,\n 'y': aObj['rectangle']['y'],\n };\n aObj['boundingBox'] = {\n 'bl': bl, 'br': br, 'tr': tr, 'tl': tl,\n 'height': +(bl['y']-tl['y']).toFixed(1), 'width': +(br['x']-bl['x']).toFixed(1)\n };\n }\n}", "function getBoundingBox () {\n let boundingBox = map.getBounds()\n xmin = parseFloat(boundingBox._sw.lng)\n ymin = parseFloat(boundingBox._sw.lat)\n xmax = parseFloat(boundingBox._ne.lng)\n ymax = parseFloat(boundingBox._ne.lat)\n\n //console.log(`${xmin}, ${ymin}, ${xmax}, ${ymax}`)\n}", "getWorldBounds() {\n const left = this.screenToWorldCoordinates(Vector.Zero).x;\n const top = this.screenToWorldCoordinates(Vector.Zero).y;\n const right = left + this.drawWidth;\n const bottom = top + this.drawHeight;\n return new BoundingBox(left, top, right, bottom);\n }", "createTheoriticalBoundingBox(x, y) {\n var temp = new BoundingBox(x, y, this.width, this.height)\n temp.entity = this.entity;\n return temp;\n }", "getBounds(bounds) {\n if (this.objects !== undefined) {\n for (let i = 0; i < this.objects.length; i++) {\n this.objects[i].getBounds(bounds);\n }\n }\n }", "getBoundingBox() {\n if (this.root instanceof SVGGraphicsElement) {\n return this.root.getBBox();\n }\n else {\n return null;\n }\n }", "function getBounds(bounds){\n\t var bbox = [];\n\t\n\t bbox.push(parseFloat(bounds.attrib[\"minlon\"]));\n\t bbox.push(parseFloat(bounds.attrib[\"minlat\"]));\n\t bbox.push(parseFloat(bounds.attrib[\"maxlon\"]));\n\t bbox.push(parseFloat(bounds.attrib[\"maxlat\"]));\n\t\n\t return bbox;\n\t}", "getBounds() {}", "getBoundingBox()\r\n\t{\r\n\t\tif ( this.vpos.length == 0 ) return null;\r\n\t\tvar min = [...this.vpos[0]];\r\n\t\tvar max = [...this.vpos[0]];\r\n\t\tfor ( var i=1; i<this.vpos.length; ++i ) \r\n\t\t{\r\n\t\t\tfor ( var j=0; j<3; ++j ) \r\n\t\t\t{\r\n\t\t\t\tif ( min[j] > this.vpos[i][j] ) min[j] = this.vpos[i][j];\r\n\t\t\t\tif ( max[j] < this.vpos[i][j] ) max[j] = this.vpos[i][j];\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn { min: min, max: max };\r\n\t}", "function getBoundingBox() {\n if (!bounds) return; // client does not want to restrict movement\n\n if (typeof bounds === 'boolean') {\n // for boolean type we use parent container bounds\n var ownerRect = owner.getBoundingClientRect();\n var sceneWidth = ownerRect.width;\n var sceneHeight = ownerRect.height;\n\n return {\n left: sceneWidth * boundsPadding,\n top: sceneHeight * boundsPadding,\n right: sceneWidth * (1 - boundsPadding),\n bottom: sceneHeight * (1 - boundsPadding)\n };\n }\n\n return bounds;\n }", "geWorldBoundingBox (fragIds, fragList) {\n\n var fragbBox = new THREE.Box3()\n var nodebBox = new THREE.Box3()\n\n fragIds.forEach((fragId) => {\n\n fragList.getWorldBounds(fragId, fragbBox)\n nodebBox.union(fragbBox)\n })\n\n return nodebBox\n }", "function drawBoxes(boxes) {\n progressMessage.setProgressMessage(\"draw bounding boxes\");\n boxpolys = new Array(boxes.length);\n for (var i = 0; i < boxes.length; i++) {\n boxpolys[i] = new google.maps.Rectangle({\n bounds: boxes[i],\n fillOpacity: 0,\n strokeOpacity: 1.0,\n strokeColor: '#000000',\n strokeWeight: 1,\n map: map\n });\n }\n}", "computeBoundingBox () {\n let vertices = this.vertices;\n let min_x, max_x;\n let min_y, max_y;\n let min_z, max_z;\n let N = vertices.length / 3;\n\n min_x = max_x = vertices[0];\n min_y = max_y = vertices[0+1];\n min_z = max_z = vertices[0+2];\n\n for (let i = 0; i < N; i++) {\n if (vertices[i] < min_x)\n min_x = vertices[i];\n if (vertices[i] > max_x)\n max_x = vertices[i];\n if (vertices[i+1] < min_y)\n min_y = vertices[i+1];\n if (vertices[i+1] > max_y)\n max_y = vertices[i+1];\n if (vertices[i+2] < min_z)\n min_z = vertices[i+2];\n if (vertices[i+2] > max_z)\n max_z = vertices[i+2];\n }\n\n let size = vec3.clone([max_x-min_x, max_y-min_y, max_z-min_z]);\n let center = vec3.clone([(min_x+max_x)/2,\n (min_y+max_y)/2,\n (min_z+max_z)/2]);\n let min = vec3.clone([min_x, min_y, min_z]);\n let max = vec3.clone([max_x, max_y, max_z]);\n\n this._vecMin = min;\n this._vecMax = max;\n }", "function setBoundingBox() {\r\n that.x1P = board.widthP - 1;\r\n that.y1P = board.heightP - 1;\r\n that.x2P = that.y2P = 0;\r\n for (var i in that.pieces) {\r\n piece = that.pieces[i];\r\n that.x1P = Math.min(that.x1P, piece.xP);\r\n that.x2P = Math.max(that.x2P, piece.xP + piece.widthP - 1);\r\n that.y1P = Math.min(that.y1P, piece.yP);\r\n that.y2P = Math.max(that.y2P, piece.yP + piece.heightP - 1);\r\n }\r\n that.xP = that.x1P;\r\n that.yP = that.y1P;\r\n that.widthP = that.x2P - that.x1P + 1;\r\n that.heightP = that.y2P - that.y1P + 1;\r\n }", "function bboxOGC(args, params) {\n return '' + \n '<ogc:BBOX>' + \n ogcHelpers.propName(args.property) + \n gmlHelpers.envelope(args, params) +\n '</ogc:BBOX>';\n } // bboxOGC", "calculateBounds() {\n this._bounds.clear();\n this._calculateBounds();\n for (var i = 0; i < this.children.length; i++) {\n var child = this.children[i];\n if (!child.visible || !child.renderable) {\n continue;\n }\n child.calculateBounds();\n // TODO: filter+mask, need to mask both somehow\n if (child._mask) {\n child._mask.calculateBounds();\n this._bounds.addBoundsMask(child._bounds, child._mask._bounds);\n }\n else if (child.filterArea) {\n this._bounds.addBoundsArea(child._bounds, child.filterArea);\n }\n else {\n this._bounds.addBounds(child._bounds);\n }\n }\n this._lastBoundsID = this._boundsID;\n }", "get bounds() {}", "function AABBBox(max,min){\n\t\n\tthis.max = max ? max : $V([-10000.0,-10000.0,-10000.0]);\n\tthis.min = min ? min : $V([10000.0,10000.0,10000.0]);\n\t\n}", "getBounds(){\n let rect = new Rectangle()\n\t\trect.setRect(this.x, this.y, this.size, this.size)\n\t\treturn rect\n }", "getBounds(){\n let rect = new Rectangle()\n\t\trect.setRect(this.x, this.y, this.size, this.size)\n\t\treturn rect\n }", "function gCloudVObjsToCogniBoundingBox(gCloudObjects, width, height){\n for(let gCloudObj of gCloudObjects){\n let vertices;\n let normalized = false;\n\n if(gCloudObj['boundingPoly']['vertices'].length > 0) // we can't know for sure that vertices will be filled (in case we check and use normalizedVertices)\n vertices = gCloudObj['boundingPoly']['vertices'];\n\n else if(gCloudObj['boundingPoly']['normalizedVertices'].length > 0) {\n vertices = gCloudObj['boundingPoly']['normalizedVertices'];\n normalized = true;\n }\n\n let x1 = vertices[0]['x']; // min x\n let x2 = vertices[0]['x']; // max x\n let y1 = vertices[0]['y']; // min y\n let y2 = vertices[0]['y']; // max y\n\n // remind that\n // - x goes from 0 -> N (left -> right)\n // - y goes from 0 -> N (top -> bottom)\n for(let point of vertices){\n x1 = Math.min(x1, point['x']);\n x2 = Math.max(x2, point['x']);\n y1 = Math.max(y1, point['y']);\n y2 = Math.min(y2, point['y']);\n }\n\n let bl = { 'x': (normalized)? +(x1 * width).toFixed(1):x1,\n 'y': (normalized)? +(y1 * height).toFixed(1):y1\n };\n let br = { 'x': (normalized)? +(x2 * width).toFixed(1):x2,\n 'y': (normalized)? +(y1 * height).toFixed(1):x1\n };\n let tl = { 'x': (normalized)? +(x1 * width).toFixed(1):x1,\n 'y': (normalized)? +(y2 * height).toFixed(1):y2\n };\n let tr = { 'x': (normalized)? +(x2 * width).toFixed(1):x2,\n 'y': (normalized)? +(y2 * height).toFixed(1):y2\n };\n\n gCloudObj['boundingBox'] = {\n 'bl': bl, 'br': br, 'tr': tr, 'tl': tl,\n 'height': +(bl['y']-tl['y']).toFixed(1), 'width': +(br['x']-bl['x']).toFixed(1)\n };\n }\n}", "function addBoundingBox(bbox) {\n if (rectangle === undefined) {\n rectangle = L.rectangle(bbox, {color: 'blue', weight: 1}).addTo(map);\n } else {\n rectangle.setBounds(bbox);\n }\n}", "function getBoundingBox(selectables) {\n const box = {\n top: Infinity,\n left: Infinity,\n bottom: -Infinity,\n right: -Infinity,\n width: 0,\n height: 0,\n };\n selectables.forEach(s => {\n box.top = Math.min(box.top, s.metrics.clientRect.top);\n box.left = Math.min(box.left, s.metrics.clientRect.left);\n box.bottom = Math.max(box.bottom, s.metrics.clientRect.bottom);\n box.right = Math.max(box.right, s.metrics.clientRect.right);\n });\n return Object.assign({}, box, { width: box.right - box.left, height: box.bottom - box.top });\n }", "function getBox(o) {\n return {\n xMin: o.position.x,\n xMax: o.position.x + o.width,\n yMin: o.position.y,\n yMax: o.position.y + o.height\n };\n }", "function getBox(o) {\n return {\n xMin: o.position.x,\n xMax: o.position.x + o.width,\n yMin: o.position.y,\n yMax: o.position.y + o.height\n };\n }", "updateBoundingBox() {\n this.sceneObject.updateMatrixWorld();\n let box = this.sceneObject.geometry.boundingBox.clone();\n box.applyMatrix4(this.sceneObject.matrixWorld);\n this.boundingBox = box;\n }", "function getPathBoundingBoxes(p) {\n var segs = p.pathSegList, currentBox, seg, boxes = [], mmin = Math.min, mmax = Math.max;\n\n for (var i = 0, len = segs.numberOfItems; i < len; i++) {\n seg = segs.getItem(i);\n switch (seg.pathSegType) {\n case 1: // Z\n boxes.push({\n x : currentBox.x1,\n y : currentBox.y1,\n width : currentBox.x2 - currentBox.x1,\n height : currentBox.y2 - currentBox.y1\n });\n break;\n\n case 2: // M\n currentBox = {\n x1 : seg.x,\n x2 : seg.x,\n y1 : seg.y,\n y2 : seg.y\n };\n break;\n\n case 4: // L\n currentBox.x1 = mmin(seg.x, currentBox.x1);\n currentBox.x2 = mmax(seg.x, currentBox.x2);\n currentBox.y1 = mmin(seg.y, currentBox.y1);\n currentBox.y2 = mmax(seg.y, currentBox.y2);\n break;\n\n default:\n }\n }\n\n return boxes;\n }", "function calculateBoundingBox() {\n return {\n top: -((strokeWidth + 1) / 2) + sourceRectYEntry,\n left: -(targetRect.left - (sourceRect.left + sourceRect.width)),\n width:\n (strokeWidth + 1) / 2 +\n (targetRect.left + targetRect.width / 2) -\n (sourceRect.left + sourceRect.width),\n height: (strokeWidth + 1) / 2 + Math.abs(sourceRectYEntry),\n };\n }", "function getClippingBBox(bounds) {\n return [[bounds.xmin, bounds.ymin],\n [bounds.xmin, bounds.ymax],\n [bounds.xmax, bounds.ymax],\n [bounds.xmax, bounds.ymin]];\n }", "get bounds() { return this._bounds; }", "function toBoundingBox(original) {\n return [\n { x: original[0], y: original[1] },\n { x: original[2], y: original[3] },\n { x: original[4], y: original[5] },\n { x: original[6], y: original[7] }\n ];\n}", "getBounds() {\n return new Rectangle(new Point(this.x, this.y), new Vector(0, 0));\n }", "function findBoundingBox(json) {\n var bbox = [ null, null, null, null ];\n\n for (var key in json.objects) {\n var curBbox = json.objects[key].bbox;\n if (bbox[0] === null || curBbox[0] < bbox[0]) bbox[0] = curBbox[0];\n if (bbox[1] === null || curBbox[1] < bbox[1]) bbox[1] = curBbox[1];\n if (bbox[2] === null || curBbox[2] > bbox[2]) bbox[2] = curBbox[2];\n if (bbox[3] === null || curBbox[3] > bbox[3]) bbox[3] = curBbox[3];\n }\n\n return bbox;\n}", "function GeometryContainer(container) {\n\n /**\n * Container name\n */\n this.name = container[\"name\"];\n \n /**\n * Container ID - used only for dynamic containers\n * static containers always -1\n */\n this.id = parseInt(container[\"container_id\"]);\n \n /**\n * GeometryObjects in container\n */\n this.objects = [];\n\n /**\n * Indicates whether this container is part of game field\n */\n this.gameField = parseInt(container[\"prvek\"]);\n \n /**\n * Indicates whether this is polygon container\n * Polygons have lightmaps\n */\n this.isItPoly = false;\n this.polyID = -1;\n if(container[\"type\"] == \"geometry_container_poly\"){\n this.isItPoly = true;\n this.polyID = container[\"poly_id\"];\n }\n\n /* Pruchod objektu v kontejneru a vytvareni odpovidajicich objektu a jejich naplneni */\n /* Objekty jsou v poli identifikovany cislem, ktere urcuje poradi, ve kterem byli nacteny */\n\n /**\n * Loading of all models inside container and\n * creating new GeometryObject objects with those models.\n * Objects are indexed by their order.\n */\n var containerObjectCounter = 0;\n for (containerObject in container[\"geometry_objects\"]) {\n // Adding new GeometryObject\n this.objects[containerObjectCounter] = new GeometryObject(container[\"geometry_objects\"][containerObject], this.isItPoly);\n containerObjectCounter++;\n }\n\n /* Size and center attributes\n */\n this.center = [];\n this.size = [];\n this.min = [];\n this.max = [];\n \n this.sizeCalc = function() { \n var min = [ MAX_NUMBER, MAX_NUMBER, MAX_NUMBER ];\n var max = [-MAX_NUMBER,-MAX_NUMBER,-MAX_NUMBER ];\n \n for (i in this.objects) { \n min[0] = getMin(min[0], this.objects[i].min[0]);\n min[1] = getMin(min[1], this.objects[i].min[1]);\n min[2] = getMin(min[2], this.objects[i].min[2]);\n \n max[0] = getMax(max[0], this.objects[i].max[0]);\n max[1] = getMax(max[1], this.objects[i].max[1]);\n max[2] = getMax(max[2], this.objects[i].max[2]);\n }\n \n this.min = min;\n this.max = max;\n \n this.center[0] = getCenter(min[0], max[0]);\n this.center[1] = getCenter(min[1], max[1]);\n this.center[2] = getCenter(min[2], max[2]);\n \n this.size[0] = max[0] - min[0];\n this.size[1] = max[1] - min[1];\n this.size[2] = max[2] - min[2];\n }\n \n this.sizeCalc();\n}", "function getRects(){\n const ids = props.players.map( player => (`${player.name}-stat`).replace(\" \", \"-\").toLowerCase() );\n ids.push(\"tree-container\");\n return boundingRects(ids);\n }", "boxQuery(searchBox) {\n // initialize return points\n let foundPoints = [];\n\n // return empty array if no intersect\n if (!this.boundary.boxIntersect(searchBox)) {\n return foundPoints;\n\n // else if there are no children, search this box\n } else if (this.childTrees.length == 0) {\n for (let point of this.childPoints) {\n if (searchBox.containsPoint(point)) {\n foundPoints.push(point);\n }\n }\n // else, there ARE children, push the query\n } else { \n // loop over all childBoxes\n for (let childTree of this.childTrees) {\n // find child points\n let childPoints = childTree.boxQuery(searchBox);\n\n // concatenate childPoints onto foundPoints\n foundPoints = foundPoints.concat(childPoints);\n }\n }\n\n // return all foundPoints\n return foundPoints;\n }", "getLogicalBox() {\n let rv = {};\n if (!this.updatedMetrics) {\n this._calculateBlockIndex();\n }\n const adjBox = (box) => {\n const nbox = svgHelpers.smoBox(box);\n nbox.y = nbox.y - nbox.height;\n return nbox;\n };\n this.blocks.forEach((block) => {\n if (!rv.x) {\n rv = svgHelpers.smoBox(adjBox(block));\n } else {\n rv = svgHelpers.unionRect(rv, adjBox(block));\n }\n });\n return rv;\n }", "rectifyBBox (bbox) {\n // horizontal top\n if (bbox[0].y != bbox[1].y) {\n let ymin = Math.min(bbox[0].y, bbox[1].y)\n bbox[0].y = ymin\n bbox[1].y = ymin\n }\n\n // horizontal bottom\n if (bbox[3].y != bbox[2].y) {\n let ymax = Math.max(bbox[3].y, bbox[2].y)\n bbox[3].y = ymax\n bbox[2].y = ymax\n }\n\n // vertical right\n if (bbox[1].x != bbox[2].x) {\n let xmax = Math.max(bbox[1].x, bbox[2].x)\n bbox[1].x = xmax\n bbox[2].x = xmax\n }\n\n // vertical left\n if (bbox[0].x != bbox[3].x) {\n let xmin = Math.min(bbox[0].x, bbox[3].x)\n bbox[0].x = xmin\n bbox[3].x = xmin\n }\n\n return bbox\n }", "function AstroBoundingBox(astroMap, layer, boundingBoxSettings) {\n // map to draw bounding boxes on\n this.astroMap = astroMap;\n\n // layer to draw bboxes on\n this.layer = layer;\n\n // index into stored vectors array for vector currently being modified.\n // Is -1 if currently modified vector isn't saved, or if we aren't modifying\n // anything\n this.savedIndex = -1;\n\n // form id defaults\n this.formIdWKT = 'astroBBWKT';\n this.formIdDatelineWKT = 'astroBBDatelineWKT';\n this.formIdTopLeftLon = 'astroBBTopLeftLon';\n this.formIdTopLeftLat = 'astroBBTopLeftLat';\n this.formIdBotRightLon = 'astroBBBotRightLon';\n this.formIdBotRightLat = 'astroBBBotRightLat';\n this.formIdCenterpoint = 'astroBBCenterPoint';\n this.formIdCenterLon = 'astroBBCenterLon';\n this.formIdCenterLat = 'astroBBCenterLat';\n this.formIdLength = 'astroBBLength';\n\n this.centerPoint = null; //for editing center point\n\n // event callbacks\n this.boundingBoxRemoveTrigger = function() {};\n\n\n // this function is called when an AJAX feature search (using the nomen service) is\n // complete. The function is passed an object containing the results. If an error\n // occurred with the AJAX request, null is returned. If no features were returned\n // (ie. no hits) the object will not be null. The results array will simply be\n // empty.\n this.boundingBoxFeatureSearchResultHandler = function() {};\n\n // set options\n if (boundingBoxSettings) {\n if (boundingBoxSettings.formIdWKT) {\n this.formIdWKT = boundingBoxSettings.formIdWKT;\n }\n if (boundingBoxSettings.formIdDatelineWKT) {\n this.formIdDatelineWKT = boundingBoxSettings.formIdDatelineWKT;\n }\n if (boundingBoxSettings.formIdTopLeftLon) {\n this.formIdTopLeftLon = boundingBoxSettings.formIdTopLeftLon;\n }\n if (boundingBoxSettings.formIdTopLeftLat) {\n this.formIdTopLeftLat = boundingBoxSettings.formIdTopLeftLat;\n }\n if (boundingBoxSettings.formIdBotRightLon) {\n this.formIdBotRightLon = boundingBoxSettings.formIdBotRightLon;\n }\n if (boundingBoxSettings.formIdBotRightLat) {\n this.formIdBotRightLat = boundingBoxSettings.formIdBotRightLat;\n }\n if (boundingBoxSettings.boundingBoxRemoveTrigger) {\n this.boundingBoxRemoveTrigger = boundingBoxSettings.boundingBoxRemoveTrigger;\n }\n if (boundingBoxSettings.boundingBoxFeatureSearchResultHandler) {\n this.boundingBoxFeatureSearchResultHandler = boundingBoxSettings.boundingBoxFeatureSearchResultHandler;\n }\n }\n\n // if form elements don't exist, create hidden fields so that\n // there aren't any errors when the code below tries to add text to\n // those fields\n/*\n if (document.getElementById(this.formIdWKT) == null) {\n var dummy = document.createElement(\"input\");\n dummy.setAttribute(\"type\", \"hidden\");\n dummy.setAttribute(\"id\", this.formIdWKT);\n document.body.appendChild(dummy);\n }\n if (document.getElementById(this.formIdDatelineWKT) == null) {\n var dummy = document.createElement(\"input\");\n dummy.setAttribute(\"type\", \"hidden\");\n dummy.setAttribute(\"id\", this.formIdDatelineWKT);\n document.body.appendChild(dummy);\n }\n if (document.getElementById(this.formIdTopLeftLon) == null) {\n var dummy = document.createElement(\"input\");\n dummy.setAttribute(\"type\", \"hidden\");\n dummy.setAttribute(\"id\", this.formIdTopLeftLon);\n document.body.appendChild(dummy);\n }\n if (document.getElementById(this.formIdTopLeftLat) == null) {\n var dummy = document.createElement(\"input\");\n dummy.setAttribute(\"type\", \"hidden\");\n dummy.setAttribute(\"id\", this.formIdTopLeftLat);\n document.body.appendChild(dummy);\n }\n if (document.getElementById(this.formIdBotRightLon) == null) {\n var dummy = document.createElement(\"input\");\n dummy.setAttribute(\"type\", \"hidden\");\n dummy.setAttribute(\"id\", this.formIdBotRightLon);\n document.body.appendChild(dummy);\n }\n if (document.getElementById(this.formIdBotRightLat) == null) {\n var dummy = document.createElement(\"input\");\n dummy.setAttribute(\"type\", \"hidden\");\n dummy.setAttribute(\"id\", this.formIdBotRightLat);\n document.body.appendChild(dummy);\n }\n*/\n}", "function convertBoundingBoxToBox(_a) {\n var top = _a.top, left = _a.left, right = _a.right, bottom = _a.bottom;\n return {\n x: { min: left, max: right },\n y: { min: top, max: bottom },\n };\n}", "function drawBoundingBox(ctx, object) {\n ctx.fillStyle = 'rgba(255, 0, 0, 0.1)'\n ctx.fillRect(\n object.lowX(),\n object.lowY(),\n object.highX() - object.lowX(),\n object.highY() - object.lowY()\n );\n}", "carregaBoundaries() {\n\n //Modifica o tamanho do estagio baseado no tamanho do elemento div do bird\n this.maxBoundsWidth = this.getEstagio().clientWidth - this.getBird().getTamanhoWidth();\n this.maxBoundsHeight = this.getEstagio().clientHeight - this.getBird().getTamanhoHeight();\n\n // console.log(\"Max width da arena: \" + this.maxBoundsWidth);\n // console.log(\"Max height da arena: \" + this.maxBoundsHeight);\n\n //Verifico se o passaro esta dentro as boundaries(caso o usuario de resize)\n this.estaForaDasBounds()\n }", "_resetBoundingBoxStyles() {\n extendStyles(this._boundingBox.style, {\n top: '0',\n left: '0',\n right: '0',\n bottom: '0',\n height: '',\n width: '',\n alignItems: '',\n justifyContent: '',\n });\n }", "function BoundingDimensions(width, height) {\n this.width = width;\n this.height = height;\n}", "function BoundingDimensions(width, height) {\n this.width = width;\n this.height = height;\n}", "function BoundingDimensions(width, height) {\n this.width = width;\n this.height = height;\n}", "_setBoundingBoxStyles(origin, position) {\n const boundingBoxRect = this._calculateBoundingBoxRect(origin, position);\n // It's weird if the overlay *grows* while scrolling, so we take the last size into account\n // when applying a new size.\n if (!this._isInitialRender && !this._growAfterOpen) {\n boundingBoxRect.height = Math.min(boundingBoxRect.height, this._lastBoundingBoxSize.height);\n boundingBoxRect.width = Math.min(boundingBoxRect.width, this._lastBoundingBoxSize.width);\n }\n const styles = {};\n if (this._hasExactPosition()) {\n styles.top = styles.left = '0';\n styles.bottom = styles.right = styles.maxHeight = styles.maxWidth = '';\n styles.width = styles.height = '100%';\n }\n else {\n const maxHeight = this._overlayRef.getConfig().maxHeight;\n const maxWidth = this._overlayRef.getConfig().maxWidth;\n styles.height = Object(_angular_cdk_coercion__WEBPACK_IMPORTED_MODULE_5__[\"coerceCssPixelValue\"])(boundingBoxRect.height);\n styles.top = Object(_angular_cdk_coercion__WEBPACK_IMPORTED_MODULE_5__[\"coerceCssPixelValue\"])(boundingBoxRect.top);\n styles.bottom = Object(_angular_cdk_coercion__WEBPACK_IMPORTED_MODULE_5__[\"coerceCssPixelValue\"])(boundingBoxRect.bottom);\n styles.width = Object(_angular_cdk_coercion__WEBPACK_IMPORTED_MODULE_5__[\"coerceCssPixelValue\"])(boundingBoxRect.width);\n styles.left = Object(_angular_cdk_coercion__WEBPACK_IMPORTED_MODULE_5__[\"coerceCssPixelValue\"])(boundingBoxRect.left);\n styles.right = Object(_angular_cdk_coercion__WEBPACK_IMPORTED_MODULE_5__[\"coerceCssPixelValue\"])(boundingBoxRect.right);\n // Push the pane content towards the proper direction.\n if (position.overlayX === 'center') {\n styles.alignItems = 'center';\n }\n else {\n styles.alignItems = position.overlayX === 'end' ? 'flex-end' : 'flex-start';\n }\n if (position.overlayY === 'center') {\n styles.justifyContent = 'center';\n }\n else {\n styles.justifyContent = position.overlayY === 'bottom' ? 'flex-end' : 'flex-start';\n }\n if (maxHeight) {\n styles.maxHeight = Object(_angular_cdk_coercion__WEBPACK_IMPORTED_MODULE_5__[\"coerceCssPixelValue\"])(maxHeight);\n }\n if (maxWidth) {\n styles.maxWidth = Object(_angular_cdk_coercion__WEBPACK_IMPORTED_MODULE_5__[\"coerceCssPixelValue\"])(maxWidth);\n }\n }\n this._lastBoundingBoxSize = boundingBoxRect;\n extendStyles(this._boundingBox.style, styles);\n }", "function getBoundariesFor(obj) {\r\n\t\treturn {\r\n\t\t\ttop: obj.center.y - (obj.size.height / 2.5),\r\n\t\t\tbottom: obj.center.y + (obj.size.height / 2.5),\r\n\t\t\tleft: obj.center.x - (obj.size.width / 2.5),\r\n\t\t\tright: obj.center.x + (obj.size.width / 2.5)\r\n\t\t};\r\n\t}", "function drawBoxes() {\n boxpolys = new Array(boxes.length);\n for (var i = 0; i < boxes.length; i++) {\n boxpolys[i] = new google.maps.Rectangle({\n bounds: boxes[i],\n fillOpacity: 0,\n strokeOpacity: 1.0,\n strokeColor: '#000000',\n strokeWeight: 1,\n map: map\n });\n }\n}", "function getBoundingBoxOfGroup(group) {\n //Just in case, make sure we're provided with at least one object.\n if(group.length > 0) {\n //set all of our locations to the first object for now.\n var leftMostPoint = group[0].offsetLeft;\n var topMostPoint = group[0].offsetTop;\n var rightMostPoint = group[0].offsetLeft + group[0].offsetWidth;\n var bottomMostPoint = group[0].offsetTop + group[0].offsetHeight;\n \n //If there is more than 1 item, go through the rest of the array.\n for(var i = 1; i < group.length; i ++) {\n if(group[i].offsetLeft < leftMostPoint)\n leftMostPoint = group[i].offsetLeft;\n if(group[i].offsetTop < topMostPoint)\n topMostPoint = group[i].offsetTop;\n if(group[i].offsetLeft + group[i].offsetWidth > rightMostPoint)\n rightMostPoint = group[i].offsetLeft + group[i].offsetWidth;\n if(group[i].offsetTop + group[i].offsetHeight > bottomMostPoint)\n bottomMostPoint = group[i].offsetTop + group[i].offsetHeight;\n }\n \n //Create the bounding box.\n var box = new BoundingBox(leftMostPoint, topMostPoint, rightMostPoint - leftMostPoint,\n bottomMostPoint - topMostPoint);\n \n return box;\n }\n \n return null;\n}", "updateBoundingBox() {\n this._aabb.copy(this.origMeshInstances[0].aabb);\n for (let i = 1; i < this.origMeshInstances.length; i++) {\n this._aabb.add(this.origMeshInstances[i].aabb);\n }\n this.meshInstance.aabb = this._aabb;\n this.meshInstance._aabbVer = 0;\n }", "function bounds() {\n return {\n start: conductor.displayStart(),\n end: conductor.displayEnd(),\n domain: conductor.domain().key\n };\n }", "function getIntersectionBBOX()\n{\n var mapBounds = map.getExtent();\n var mapBboxEls = mapBounds.toBBOX().split(',');\n // bbox is the bounding box of the currently-visible layer\n var layerBboxEls = bbox.split(',');\n var newBBOX = Math.max(parseFloat(mapBboxEls[0]), parseFloat(layerBboxEls[0])) + ',';\n newBBOX += Math.max(parseFloat(mapBboxEls[1]), parseFloat(layerBboxEls[1])) + ',';\n newBBOX += Math.min(parseFloat(mapBboxEls[2]), parseFloat(layerBboxEls[2])) + ',';\n newBBOX += Math.min(parseFloat(mapBboxEls[3]), parseFloat(layerBboxEls[3]));\n return newBBOX;\n}", "boundingBox(shape) {\n let r = {x0 : 10, x1 : -10, y0 : 10, y1 : -10};\n\n shape.foreach( function(x, y) {\n if ((x <= r.x0)) r.x0 = x;\n if ((x >= r.x1)) r.x1 = x;\n if ((y <= r.y0)) r.y0 = y;\n if ((y >= r.y1)) r.y1 = y;\n });\n\n return r;\n }", "function getBoundingBox(points) {\n\tvar xmin, xmax, ymin, ymax;\n\txmin = xmax = points[0].x;\n\tymin = ymax = points[0].y;\n\n\tpoints.forEach(point => {\n\t\tif(point.x < xmin) xmin = point.x;\n\t\telse if (point.x > xmax) xmax = point.x;\n\n\t\tif(point.y < ymin) ymin = point.y;\n\t\telse if (point.y > ymax) ymax = point.y;\n\t});\n\n\treturn {xmin: xmin, xmax: xmax, ymin: ymin, ymax: ymax};\n}", "static fromBoundingRect(rect) {\n let b = new Bound(new Pt_1.Pt(rect.left || 0, rect.top || 0), new Pt_1.Pt(rect.right || 0, rect.bottom || 0));\n if (rect.width && rect.height)\n b.size = new Pt_1.Pt(rect.width, rect.height);\n return b;\n }", "function compute_bound(bbox) {\n var offset = 0.01;\n var southWest = new L.LatLng(bbox[0][0] - offset, bbox[0][1] - offset);\n var northEast = new L.LatLng(bbox[2][0] + offset, bbox[2][1] + offset);\n return new L.LatLngBounds(southWest, northEast);\n}", "function moveBallsIntoBounds() {\n var maxX = container.width(),\n maxY = container.height();\n $('b',container).each(function(i,b) {\n var ball = $(b),\n pos = ball.position()\n x = pos.left,\n y = pos.top,\n size = ball.height();\n if (x+size > maxX) ball.css({ left: maxX-size+'px' });;\n if (y+size > maxY) ball.css({ top: maxY-size+'px' });;\n });\n}", "generateBoundingBox(p1, p2) {\n let startTime = Date.now();\n let minX, minY, maxX, maxY;\n \n // Find min/max x values\n if (p1.x < p2.x) {\n minX = p1.x;\n maxX = p2.x;\n } else {\n minX = p2.x;\n maxX = p1.x;\n }\n\n // Find min/max y values\n if (p1.y < p2.y) {\n minY = p1.y;\n maxY = p2.y;\n } else {\n minY = p2.y;\n maxY = p1.y;\n }\n\n // Scale the BB so it's a more uniform square\n // This covers edge cases when the start and end points share an axis\n let slope = Math.abs((p2.y - p1.y) / (p2.x - p1.x));\n if (slope < 1) {\n // Scale Y values\n let deltaY = maxY - minY;\n let scale = deltaY / 5 * Math.abs((p2.x - p1.x) / (p2.y - p1.y));\n maxY += scale;\n minY -= scale;\n } else if (slope > 1) {\n // Scale X values\n let deltaX = maxX - minX;\n let scale = deltaX / 5 * slope;\n maxX += scale;\n minX -= scale;\n }\n\n this.boundingBox.topLeft = [minX, maxY];\n this.boundingBox.topRight = [maxX, maxY];\n this.boundingBox.bottomLeft = [minX, minY];\n this.boundingBox.bottomRight = [maxX, minY];\n\n this.timestamps.createBoundingBox = Date.now() - startTime;\n }", "setBounds() {\n let x = this.position.getX();\n let y = this.position.getY();\n let s = Game.Settings().UnitSize;\n let hs = s / 2;\n\n //generate Individual Bounds\n this.bounds = new Bounds(x - hs, y - hs, x + hs, y + hs);\n }", "function drawBoundingBox(keypoints, ctx) {\n var boundingBox = posenet.getBoundingBox(keypoints);\n ctx.rect(boundingBox.minX, boundingBox.minY, boundingBox.maxX - boundingBox.minX, boundingBox.maxY - boundingBox.minY);\n ctx.strokeStyle = boundingBoxColor;\n ctx.stroke();\n}", "getBoundingBox() {\n if (!this.preFormatted) {\n throw new Vex.RERR('UnformattedNote', \"Can't call getBoundingBox on an unformatted note.\");\n }\n\n const spacing = this.stave.getSpacingBetweenLines();\n const half_spacing = spacing / 2;\n const min_y = this.y - half_spacing;\n\n return new Flow.BoundingBox(this.getAbsoluteX(), min_y, this.width, spacing);\n }", "getModifiedWorldBoundingBox(fragIds, fragList) {\n\n const fragbBox = new THREE.Box3()\n const nodebBox = new THREE.Box3()\n\n fragIds.forEach(function(fragId) {\n\n fragList.getWorldBounds(fragId, fragbBox)\n\n nodebBox.union(fragbBox)\n })\n\n return nodebBox\n }", "function _getBBox(feature) {\n\n //Not valid\n if (!feature.geometry) {\n return false;\n }\n\n //if it's a point, put in an array\n if (feature.geometry.type === \"Point\"){\n return [\n feature.geometry.coordinates,\n feature.geometry.coordinates\n ];\n }\n\n //Don't check inner rings\n var outer = feature.geometry.type === \"Polygon\" ? [feature.geometry.coordinates[0]] : feature.geometry.coordinates.map(function(f){\n return f[0];\n });\n\n //For each point, extend bounds as needed\n var bounds = [[Infinity,Infinity],[-Infinity,-Infinity]];\n\n outer.forEach(function(polygon){\n\n polygon.forEach(function(point){\n\n bounds = [\n [\n Math.min(point[0],bounds[0][0]),\n Math.min(point[1],bounds[0][1])\n ],\n [\n Math.max(point[0],bounds[1][0]),\n Math.max(point[1],bounds[1][1])\n ]\n ];\n\n });\n\n });\n \n return bounds;\n\n\n }", "bbox() {\n parser().path.setAttribute('d', this.toString());\n return parser.nodes.path.getBBox();\n }" ]
[ "0.78263265", "0.7469249", "0.7451684", "0.74225336", "0.73739296", "0.73164916", "0.7308891", "0.7257851", "0.72357893", "0.72357893", "0.7172033", "0.7168233", "0.71567285", "0.7103066", "0.7103066", "0.7077606", "0.7004648", "0.692082", "0.6896966", "0.6867919", "0.68636775", "0.68375885", "0.68318343", "0.6827246", "0.67148584", "0.6642881", "0.6594067", "0.6594067", "0.6594067", "0.6574515", "0.6554108", "0.6549176", "0.6526463", "0.6466018", "0.64249843", "0.6423943", "0.6416246", "0.63906515", "0.6372477", "0.6338338", "0.6297504", "0.6285936", "0.6281741", "0.626455", "0.62498987", "0.6246855", "0.62392116", "0.6210716", "0.62089384", "0.6208458", "0.61882275", "0.6176287", "0.61609215", "0.6155294", "0.6155294", "0.6151178", "0.61504257", "0.6147238", "0.6138879", "0.6137242", "0.6130822", "0.61275285", "0.61207914", "0.610679", "0.6073961", "0.60610044", "0.6055906", "0.60544324", "0.6051992", "0.6048471", "0.6040673", "0.60392076", "0.60130507", "0.60121775", "0.59711695", "0.5969106", "0.5965684", "0.59632033", "0.5953071", "0.5953071", "0.5953071", "0.59528106", "0.5930209", "0.59233654", "0.59215426", "0.5908454", "0.5905773", "0.5905576", "0.5904005", "0.58992714", "0.58711785", "0.5868359", "0.58623827", "0.58616424", "0.58194214", "0.58136404", "0.5800551", "0.5794282", "0.57833004", "0.577722" ]
0.7913982
0
! principal canvas \class Canvas \param canvas canvas element \param image image draw on the canvas \param baseline list of baselines \param boundingBox list of boundingBox
function Canvas(canvas, image, baseline, boundingBox) { var myCanvas = this; this.canvas = canvas; this.width = canvas.width; this.height = canvas.height; this.ctx = canvas.getContext('2d'); this.image = image; this.baseline = baseline; this.boundingBox = boundingBox; this.dragging = false; this.scale = 1.0; this.panX = 0; this.panY = 0; this.selectedCC = []; this.dragoffx = 0; this.dragoffy = 0; this.image.img.onload = function(){ myCanvas.image.w = this.width; myCanvas.image.h = this.height; myCanvas.image.initialx = myCanvas.width/2 - this.width/2; myCanvas.image.initialy = myCanvas.height/2 - this.height/2; myCanvas.image.x = myCanvas.image.initialx; myCanvas.image.y = myCanvas.image.initialy; if(this.width > this.height) myCanvas.scale = myCanvas.width /this.width; else myCanvas.scale = myCanvas.height /this.height; myCanvas.draw(); } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function init(src, boundingBox, baseline) {\n var image = new ProcessingImage(src);\n var imagePreview = new ProcessingImage(src);\n \n\n var listRect = new Array();\n for (var rect in boundingBox) {\n listRect.push(new Rectangle({x:boundingBox[rect].x, y:boundingBox[rect].y, w:boundingBox[rect].width, h: boundingBox[rect].height},boundingBox[rect].idCC, boundingBox[rect].idLine));\n } \n var boundingBox = new BoundingBox(listRect);\n \n var listBaseline = new Array();\n for (var line in baseline) {\n listBaseline.push(new Line(baseline[line].idLine, baseline[line].x_begin,baseline[line].y_baseline,baseline[line].x_end));\n }\n var baseline = new Baseline(listBaseline);\n\n var previewCanvas = new PreviewCanvas(document.getElementById('small_canvas'), imagePreview);\n var normalCanvas = new Canvas(document.getElementById('canvas'), image, baseline, boundingBox);\n\n\n var listCharacter = new ListCharacter();\n var controller = new Controller(normalCanvas, previewCanvas, listCharacter);\n}", "drawCanvas(imgData) {\n\t\t// abstract\n\t}", "function drawImageCanvas() {\n // Emulate background-size: cover\n var width = imageCanvas.width;\n var height = imageCanvas.width / image.naturalWidth * image.naturalHeight;\n \n if (height < imageCanvas.height) {\n width = imageCanvas.height / image.naturalHeight * image.naturalWidth;\n height = imageCanvas.height;\n }\n\n imageCanvasContext.clearRect(0, 0, imageCanvas.width, imageCanvas.height);\n imageCanvasContext.globalCompositeOperation = 'source-over';\n imageCanvasContext.drawImage(image, 0, 0, width, height);\n imageCanvasContext.globalCompositeOperation = 'destination-in';\n imageCanvasContext.drawImage(lineCanvas, 0, 0);\n}", "function mainDraw(canvasObject) {\n\n\t\tvar ctx = canvasObject.ctx;\n\t\tvar backImage = canvasObject.img;\n\n\t\tif (canvasObject.isValid == false) {\n\t\t\tclear(canvasObject);\n\n\t\t// Add stuff you want drawn in the background all the time here\n\t\t/* added by Miguel */\n\t\tif(backImage != 'undefined') {\n\t\t ctx.drawImage(backImage, 0,0, canvasObject.width, canvasObject.height);\n\t\t}\n\n\t\t// draw all boxes\n\t\tvar l = canvasObject.boxes2.length;\n\t\tfor (var i = 0; i < l; i++) {\n\t\t canvasObject.boxes2[i].draw(ctx); // we used to call drawshape, but now each box draws itself\n\t\t}\n\n\t\t// Add stuff you want drawn on top all the time here\n\n\t\tcanvasObject.isValid = true;\n\t\t}\n\t}", "function drawToCanvas(canvas, predictions, img) {\n var context = canvas.getContext('2d');\n \n if (img)\n context.drawImage(img, 0, 0 );\n\n if (predictions.length > 0) {\n const result = predictions[0].landmarks;\n drawKeypoints(context, result, predictions[0].annotations);\n canvas.style.border = \"6px solid lightgreen\";\n }\n}", "drawImageCanvas() {\n // Emulate background-size: cover\n if (this.imageCanvas) {\n var width = this.imageCanvas.width;\n var height = this.imageCanvas.width / this.image.naturalWidth * this.image.naturalHeight;\n \n if (height < this.imageCanvas.height) {\n width = this.imageCanvas.height / this.image.naturalHeight * this.image.naturalWidth;\n height = this.imageCanvas.height;\n }\n \n this.imageCanvasContext.clearRect(0, 0, this.imageCanvas.width, this.imageCanvas.height);\n this.imageCanvasContext.globalCompositeOperation = 'source-over';\n this.imageCanvasContext.drawImage(this.image, 0, 0, width, height);\n this.imageCanvasContext.globalCompositeOperation = 'destination-in';\n this.imageCanvasContext.drawImage(this.lineCanvas, 0, 0);\n }\n }", "function PreviewCanvas(canvas, image)\n{\n this.canvas = canvas;\n this.width = canvas.width;\n this.height = canvas.height;\n this.ctx = canvas.getContext('2d');\n\n this.image = image;\n\n this.visible = false;\n this.scaleX = 1;\n this.scaleY = 1;\n\n this.isBaseline = false;\n\n this.position_up_line = 0;\n this.position_down_line = 0;\n this.position_left_line = 0;\n this.position_right_line = 0;\n this.position_baseline = 0;\n this.idElementSelected = 0;\n var myPreviewCanvas = this; \n\n this.image.img.onload = function(){\n myPreviewCanvas.draw();\n }\n}", "drawCanvas() {\n //TODO find better version of how to structure so that the margin can be programmatically set\n this.ctx.clearRect(0, 0, this.can.width, this.can.height)\n this.invisictx.clearRect(0, 0, this.can.width, this.can.height)\n // remove previous tooltips\n while (this.infoHolder.firstChild) {\n this.infoHolder.removeChild(this.infoHolder.firstChild)\n }\n let red = {\n r: 227, g: 74, b: 51\n }\n let gray = {\n r: 254, g: 232, b: 200\n }\n let blue = {\n r: 67, g: 162, b: 202\n }\n // iterate over the boundary data\n for (let region of this.paneOb.sliceData.features) {\n // this is the object that has features, and properties\n for (let coords of region.geometry.coordinates) {\n this.ctx.lineWidth = 2\n this.ctx.beginPath()\n this.invisictx.beginPath()\n // create simplified variable with points and region name\n let linedata = { points: coords, region: region.properties.regionName }\n\n // begin actual drawing to the canvas\n let first = linedata.points[0]\n let x = this.xinterp.calc(first[0])\n let y = this.yinterp.calc(first[1])\n this.ctx.moveTo(x, y)\n this.invisictx.moveTo(x, y)\n for (let i = 1; i < linedata.points.length; i++) {\n let pt = linedata.points[i]\n let x = this.xinterp.calc(pt[0])\n let y = this.yinterp.calc(pt[1])\n this.ctx.lineTo(x, y)\n this.invisictx.lineTo(x, y)\n }\n this.ctx.closePath()\n this.invisictx.closePath()\n // check if its a roilisted\n if (this.paneOb.rois[linedata.region]) {\n if (this.paneOb.rois[linedata.region]) {\n this.ctx.strokeStyle = \"black\"\n this.ctx.lineWidth = 5\n this.ctx.stroke()\n }\n // add tooltips that are visible\n let regId = linedata.region.replace(/[-_]/g, \"\")\n // if we don't find the element must make the tooltip, make search specific to pane\n if (!this.paneOb.paneDiv.querySelector(`#tooltip${regId}`)) {\n this.tooltipMaker(linedata.region, this.paneOb.rois[linedata.region])\n }\n }\n\n // default stroke gray, update if nec\n this.ctx.strokeStyle = \"gray\"\n this.ctx.stroke()\n // these aren't defined yet\n if (this.regNameToValueMap != undefined) {\n if (this.regNameToValueMap[linedata.region]) {\n let scanData = this.regNameToValueMap[linedata.region].value\n let lerpc\n if (scanData < 0) {\n // use the blue to gray instead of gray to red\n let t = this.colInterpolator.calc(scanData)\n lerpc = LerpCol( t)\n } else {\n let t = this.colInterpolator.calc(scanData)\n lerpc = LerpCol( t)\n }\n this.ctx.fillStyle = lerpc\n this.ctx.fill()\n // query the region to color map\n }\n }\n this.invisictx.fillStyle = `rgb(${this.regToColMap[linedata.region][0]},${this.regToColMap[linedata.region][1]},${this.regToColMap[linedata.region][2]})`\n this.invisictx.fill()\n }\n }\n if (this.scanDatamin != undefined && this.scanDatamax != undefined) {\n // setup a legend in the corner\n let gradient = this.ctx.createLinearGradient(0, 0, 0, this.can.height / 4)\n // color stop for rgb\n if (this.scanDatamin < 0 && this.scanDatamax > 0) {\n gradient.addColorStop(1, `rgb(${blue.r},${blue.g},${blue.b})`)\n gradient.addColorStop(.5, `rgb(${gray.r},${gray.g},${gray.b})`)\n gradient.addColorStop(0, `rgb(${red.r},${red.g},${red.b})`)\n } else if (this.scanDatamax > 0) {\n gradient.addColorStop(1.0, `rgb(255,255,178)`)\n gradient.addColorStop(0.75, `rgb(254,204,92)`)\n gradient.addColorStop(0.5, `rgb(253,141,60)`)\n gradient.addColorStop(0.25, `rgb(240,59,32)`)\n gradient.addColorStop(.0, `rgb(189,0,38)`)\n } else {\n // this is the case of blue only\n console.log(this.scanDatamax, \"max\", this.scanDatamin, \"min\")\n gradient.addColorStop(0, `rgb(${gray.r},${gray.g},${gray.b})`)\n gradient.addColorStop(1, `rgb(${blue.r},${blue.g},${blue.b})`)\n }\n let gradientWidth = 10\n this.ctx.fillStyle = gradient\n let startx = this.can.width - this.margin - gradientWidth\n let endx = this.can.width - this.margin * 2\n this.ctx.fillRect(startx, 0, endx, this.can.height / 4)\n // add numeric values to the gradient\n // measure the text so it sits right next to the gradient\n this.ctx.font = \"15px Arial\"\n let minmeasure = this.ctx.measureText(this.scanDatamin).width\n let maxmeasure = this.ctx.measureText(this.scanDatamax).width\n this.ctx.fillStyle = \"black\"\n // the -5 is a spacer for the text next to the gradient bar\n this.ctx.fillText(this.scanDatamin, startx - minmeasure - 5, this.can.height / 4)\n this.ctx.fillText(this.scanDatamax, startx - maxmeasure - 5, 15)\n }\n }", "function finishBaseline( baseline ) {\n //setPolyrect( baseline, self.cfg.polyrectHeight, self.cfg.polyrectOffset );\n setPolystripe( baseline, self.cfg.polyrectHeight, self.cfg.polyrectOffset );\n\n sortOnDrop( $(baseline).parent()[0] );\n\n $(baseline)\n .parent()\n .addClass('editable')\n .each( function () {\n this.setEditing = function () {\n var event = { target: this };\n self.util.setEditing( event, 'points', { points_selector: '> polyline', restrict: false } );\n };\n } );\n window.setTimeout( function () {\n if ( typeof $(baseline).parent()[0].setEditing !== 'undefined' )\n $(baseline).parent()[0].setEditing();\n self.util.selectElem(baseline,true);\n }, 50 );\n\n self.util.registerChange('added baseline '+$(baseline).parent().attr('id'));\n\n for ( var n=0; n<self.cfg.onFinishBaseline.length; n++ )\n self.cfg.onFinishBaseline[n](baseline);\n }", "function drawCanvas() {\n\tif (imageId != null) {\n\t\tdrawJointJS(imageId);\n\t\timageId = null;\n\t}\n}", "function draw(image, thecanvas) {\n\n var context = thecanvas.getContext('2d');\n\n context.drawImage(image, 0, 0, thecanvas.width, thecanvas.height);\n }", "function CanvasImage(canvas) {\n\n if (canvas.width !== innerWidth || canvas.height !== innerHeight) {\n canvas.width = innerWidth - innerWidth*0.2;\n canvas.height = innerHeight - innerHeight*0.2;\n } else {\n ctx.clearRect(0, 0, canvas.width, canvas.height);\n }\n\n this.canvas = canvas;\n this.context = canvas.getContext(\"2d\");\n this.width = canvas.width;\n this.height = canvas.height;\n this.newImageData = this.context.createImageData(this.width, this.height);\n this.oldImageData = this.context.createImageData(this.width, this.height);\n this.newBuffer = new Uint32Array(this.newImageData.data.buffer);\n this.oldBuffer = new Uint32Array(this.oldImageData.data.buffer);\n }", "function copyImgFromCanvasToCanvas(canvasA, canvasB, topLeft, bottomRight){\n \n var originContext = canvasA.getContext('2d');\n var newContext = canvasB.getContext('2d');\n\n let [sx, sy] = topLeft;\n let [ex, ey] = bottomRight;\n const wx = ex - sx \n const wy = ey - sy \n\n // get img data\n const imgData = originContext.getImageData(sx, sy, wx, wy);\n newContext.putImageData(imgData, sx, sy);\n canvasB.style.border = \"6px solid lightgreen\";\n\n\n}", "function imageDraw(imgData){\r\n\t\r\n\tif(typeof imgData === \"undefined\") {\r\n\t\treturn;\r\n\t}\r\n\tcanvasWidth = imgData.width * zoom/100;\r\n\tcanvasHeight = imgData.height * zoom/100;\r\n\t\r\n\t// new Size of canvas\r\n\tctx.canvas.width = canvasWidth; \r\n\tctx.canvas.height = canvasHeight;\r\n\t\r\n\t// new Position of Canvas\r\n\tvar deltaX = canvasWidth - canvasOldWidth;\r\n\tvar deltaY = canvasHeight - canvasOldHeight;\r\n\tvar canvXString = $('.image_area').children().css('left');\r\n\tvar canvYString = $('.image_area').children().css('top');\r\n\tvar newCanvX = Number( canvXString.substring(0,canvXString.length-2) ) - deltaX/2;\r\n\tvar newCanvY = Number( canvYString.substring(0,canvYString.length-2) ) - deltaY/2;\r\n\t\r\n\t$('.image_area').children().css('left',newCanvX + 'px');\r\n\t$('.image_area').children().css('top',newCanvY + 'px');\r\n\tcanvasOldWidth = canvasWidth;\r\n\tcanvasOldHeight = canvasHeight;\r\n\t\r\n\t// zoom in or out as canvas operation\r\n\tctx.scale(zoom/100, zoom/100);\r\n\tvar newCanvas = $(\"<canvas>\")\r\n\t\t.attr(\"width\", imgData.width)\r\n\t\t.attr(\"height\", imgData.height)[0];\r\n\tnewCanvas.getContext(\"2d\").putImageData(imgData,0,0);\r\n\t\r\n\tctx.drawImage(newCanvas,0,0);\r\n}", "function Scribble( canvasID,image,_width,_height, callback) {\n this._callback = callback;\n this.canvasID = canvasID;\n this._lineWidth=5;\n this.canvas = $(\"#\"+canvasID);\n this.context = this.canvas.get(0).getContext(\"2d\"); \n this.context.clearRect(0,0,this.canvas.width,this.canvas.height);\n this._enabled=true;\n this.context.strokeStyle = \"#000000\";\n this.canvasBorderWidth = parseInt(this.canvas.css('border-left-width'),10); // assuming top and left borders are same width\n this.context.lineWidth = this._lineWidth;\n this.lastMousePoint = {x:0, y:0};\n \n this.canvas[0].width = _width;// this.canvas.parent().innerWidth();\n this.canvas[0].height = _height;//this.canvas.parent().innerHeight();\n if(!image){\n this.context.fillStyle = '#ffffff';\n this.context.clearRect(0,0,_width,_height);\n } else {\n this.context.drawImage(image,0,0);\n }\n this.canvas.bind( TouchUtil.POINTER_DOWN, this.onCanvasMouseDown() );\n}", "setupCanvases() {\n this.mainCanvas = document.getElementById('main-canvas');\n this.strokeCanvas = document.getElementById('stroke-canvas');\n\n this.mainCanvas.width = this.windowWidth;\n this.mainCanvas.height = this.windowHeight;\n\n this.canvas = [];\n\n for (let i = 0; i < this.images.length; i++) {\n // Create temp and draw canvases for each image\n this.canvas[i] = {\n 'temp': document.createElement('canvas'),\n 'draw': document.createElement('canvas')\n };\n\n // Set canvases to width and height of main canvas\n this.canvas[i].temp.width = this.canvas[i].draw.width = this.strokeCanvas.width = this.mainCanvas.width;\n this.canvas[i].temp.height = this.canvas[i].draw.height = this.strokeCanvas.height = this.mainCanvas.height;\n }\n\n // draw the stuff to start\n this.recompositeCanvases();\n\n this.mouseDown = false;\n\n // Bind events\n this.strokeCanvas.addEventListener('mousedown', this.mousedown_handler, false);\n this.strokeCanvas.addEventListener('touchstart', this.mousedown_handler, false);\n\n this.strokeCanvas.addEventListener('mousemove', this.mousemove_handler, false);\n this.strokeCanvas.addEventListener('touchmove', this.mousemove_handler, false);\n\n this.strokeCanvas.addEventListener('mouseup', this.mouseup_handler, false);\n this.strokeCanvas.addEventListener('touchend', this.mouseup_handler, false);\n }", "function drawCanvas(src){\n \n // redraw animation\n var redraw = false;\n if(filechanged)\n redraw = true;\n \n\t// check whether backgroundcanvas needs to be redrawn\n if(filechanged || vischanged){\n $('#backgroundlayer').remove();\n } \n\t\n\t// draw input image as background to canvas\n\timageObj = new Image();\n\timageObj.onload = function(){\n \n // get image dimensions\n var imgW = imageObj.width;\n var imgH = imageObj.height;\n \n // if fit to screen is selected\n if(fitted){\n // get scaled canvas size\n var arr = scaleDimensions(imgW, imgH);\t\n imgW = Math.round(arr[0]);\n imgH = Math.round(arr[1]);\n }\n \n $('#demo').height(imgH + 400);\n \n if($('#backgroundlayer').length == 0){\n // create canvas with correct dimensions\n $('#imageDiv').append('<canvas id=\"backgroundlayer\" width=\"' + imgW + '\" height=\"' + imgH + '\" style=\"border:3px solid #000000; z-index:1\"></canvas>');\n var backgroundlayer = document.getElementById(\"backgroundlayer\");\n var ctx1 = backgroundlayer.getContext(\"2d\");\n ctx1.clearRect(0,0, imgW, imgH);\n \n $('#backgroundlayer').css({position: 'absolute'});\n \n // draw image to canvas\n ctx1.drawImage(imageObj, 0, 0, imgW, imgH);\n } \n \n // configure animation\n prepareAnimation(redraw);\n prepareClick();\n \n // call specific draw functions\n var value = $('#visSelect').val();\n \n // handle different visualizations\n if(value == \"gazeplot\"){\n \n // register color picker for connecting lines\n registerColorpicker($('#lineColorpicker'), $('#lineColor'), '#000000');\n \n var e = $('#slider-range').slider(\"values\", 1);\n drawClick(e);\n \n // draw selected interval\n if(vischanged){\n var s = $('#slider-range').slider(\"values\", 0);\n var e = $('#slider-range').slider(\"values\", 1);\n drawGazeplotAnimation(e, s, e, true);\n }\n // draw complete gazepath\n else{ \n drawGazeplot();\n } \n }\n \n if(value == \"heatmap\"){\n \n // register color picker\n registerColorpicker($('#c1Colorpicker'), $('#c1Color'), '#0000ff');\n registerColorpicker($('#c2Colorpicker'), $('#c2Color'), '#00ff00');\n registerColorpicker($('#c3Colorpicker'), $('#c3Color'), '#ff0000');\n \n // place color pickers\n $('#c1Colorpicker').css('margin-top', '30px').css('margin-left', '10px');\n $('#c2Colorpicker').css('margin-top', '30px').css('margin-left', '73px');\n $('#c3Colorpicker').css('margin-top', '30px').css('margin-left', '136px');\n \n // draw selected interval\n if(vischanged){\n var s = $('#slider-range').slider(\"values\", 0);\n var e = $('#slider-range').slider(\"values\", 1);\n drawHeatmapAnimation(e, s, e, true);\n }\n // draw complete heatmap\n else{ \n drawHeatmap();\n }\n }\t\n \n if(value == \"attentionmap\"){\n\n // register cover color picker\n registerColorpicker($('#attColorpicker'), $('#attColor'), '#000000');\n \n // place color picker\n $('#attColorpicker').css('margin-top', '30px').css('margin-left', '10px');\n \n // draw selected interval\n if(vischanged){\n var s = $('#slider-range').slider(\"values\", 0);\n var e = $('#slider-range').slider(\"values\", 1);\n drawAttentionmapAnimation(e, s, e, true);\n }\n // draw complete gazepath\n else{ \n drawAttentionmap();\n }\n }\n \n if(filechanged || vischanged){\n filechanged = false;\n vischanged = false;\n }\n \n }; \n // set image source\n\timageObj.src = 'data/' + src; \n}", "function updateCanvas(pivot){\n var canv = document.getElementById('canv');\n var ctx = canv.getContext('2d');\n\n ctx.clearRect(0, 0, canv.width, canv.height);\n\n drawLines(pivot);\n\n\n}", "function init2() {\n canvas = document.getElementById('pictureCanvas');\n HEIGHT = canvas.height;\n WIDTH = canvas.width;\n ctx = canvas.getContext('2d');\n ghostcanvas = document.createElement('canvas');\n ghostcanvas.height = HEIGHT;\n ghostcanvas.width = WIDTH;\n gctx = ghostcanvas.getContext('2d');\n \n //fixes a problem where double clicking causes text to get selected on the canvas\n canvas.onselectstart = function () { return false; }\n \n // fixes mouse co-ordinate problems when there's a border or padding\n // see getMouse for more detail\n if (document.defaultView && document.defaultView.getComputedStyle) {\n stylePaddingLeft = parseInt(document.defaultView.getComputedStyle(canvas, null)['paddingLeft'], 10) || 0;\n stylePaddingTop = parseInt(document.defaultView.getComputedStyle(canvas, null)['paddingTop'], 10) || 0;\n styleBorderLeft = parseInt(document.defaultView.getComputedStyle(canvas, null)['borderLeftWidth'], 10) || 0;\n styleBorderTop = parseInt(document.defaultView.getComputedStyle(canvas, null)['borderTopWidth'], 10) || 0;\n }\n \n // make mainDraw() fire every INTERVAL milliseconds\n // setInterval(mainDraw, INTERVAL);\n setInterval(mainDrawImages, INTERVAL);\n \n // set our events. Up and down are for dragging,\n // double click is for making new boxes\n canvas.onmousedown = myDown;\n canvas.onmouseup = myUp;\n canvas.ondblclick = myDblClick;\n canvas.onmousemove = myMove;\n \n // set up the selection handle boxes\n for (var i = 0; i < 5; i ++) {\n var rect = new Box2Image;\n selectionHandles.push(rect);\n }\n \n // add custom initialization here:\n\n // addRectImage(\"images/city.png\");\n // addRectImage(\"images/kohls_sunglasses1.png\");\n // addRectImage(\"images/kohls_sunglasses1.png\");\n addRectImage(\"images/kohls_sunglasses1.png\");\n // addRectImage(\"http://devarapps.seemoreinteractive.com/files/clients/85/products/kohls_sunglasses1.png\");\n\n}", "function draw_image( img ) {\n context.clearRect(0, 0, canvas.width, canvas.height);\n context.drawImage(img, 0, 0, canvas.width, canvas.height);\n }", "function onPhotoDataSuccess(imageData){\n\n myImageMiddle.onload = function() {\n\n $scope.scaleImgX = 1;\n $scope.scaleImgY = 1;\n $scope.ResizeValue = 0;\n\n var im_width = myImageMiddle.width;\n var im_height = myImageMiddle.height;\n var ratio = im_width/800;\n var contWidth = 800;\n var contHeight = im_height/ratio;\n\n var container = $('#customContainer');\n $('#customContainer').css({'width':contWidth,'height':contHeight}) // Originally 800 X 535\n //var contWidth = 800;\n //var contHeight = 800*ratio;\n $scope.contRatio = contWidth/contHeight;\n $('#ratio').html($scope.contRatio);\n\n $('#cont').html(contWidth+ ', '+contHeight);\n\n //$scope.scaleImgX = contWidth/myImageMiddle.width;\n //$scope.scaleImgY = contHeight/myImageMiddle.height;\n\n $scope.draw_w = myImageMiddle.width * $scope.scaleImgX;\n $scope.draw_h = myImageMiddle.height * $scope.scaleImgY;\n //alert(\"\"+$scope.draw_w)\n //alert(\"\"+$scope.draw_h)\n\n context.canvas.width = $scope.draw_w;\n context.canvas.height = $scope.draw_h;\n contextMiddle.canvas.width = $scope.draw_w;\n contextMiddle.canvas.height = $scope.draw_h;\n contextTop.canvas.width = $scope.draw_w;\n contextTop.canvas.height = $scope.draw_h;\n\n contextMiddle.drawImage(myImageMiddle, 0, 0, $scope.draw_w, $scope.draw_h);\n setTimeout(function(){ $scope.readJSON();},500);\n\n\n\n resize(0);\n }\n }", "function draw_on_canvas(canvas, image) {\n // Giving canvas the image dimension\n\n var ctx = canvas.getContext('2d');\n // Drawing\n ctx.drawImage(image, 0 ,0,canvas.width,canvas.height);\n }", "function drawCanvas() {\n if( drawio.loadedIMG != ''){\n drawio.ctx.drawImage(drawio.loadedIMG, 0, 0);\n }\n for( var i = 0; i < drawio.shapes.length; i++) {\n drawio.shapes[i].render();\n }\n if(drawio.selectedElement) {\n drawio.selectedElement.render();\n }\n }", "function initCanvas(onDrawingCallback) {\n let flag = false,\n prevX, prevY, currX, currY = 0;\n let canvasJq = $('#canvas');\n let canvasEle = document.getElementById('canvas');\n let imgEle = document.getElementById('image');\n\n // event on the canvas when the mouse is on it\n canvasJq.on('mousemove mousedown mouseup mouseout', function (e) {\n prevX = currX;\n prevY = currY;\n currX = e.clientX - canvasJq.position().left;\n currY = e.clientY - canvasJq.position().top;\n if (e.type === 'mousedown') {\n flag = true;\n }\n if (e.type === 'mouseup' || e.type === 'mouseout') {\n flag = false;\n }\n // if the flag is up, the movement of the mouse draws on the canvas\n if (e.type === 'mousemove') {\n if (flag) { \n data = { \n canvas: { \n width: canvasEle.width, \n height: canvasEle.height \n }, \n paths: [\n { \n x1: prevX, \n y1: prevY, \n x2: currX, \n y2: currY \n }\n ], \n color: inkColor, \n thickness: thickness \n }\n pushPath(data);\n onDrawingCallback(data);\n }\n }\n });\n\n // Loaded & resize event\n imgEle.addEventListener('load', () => {\n repositionCanvas();\n });\n\n window.addEventListener('resize', () => {\n repositionCanvas();\n });\n\n // If the image has already been loaded.\n if (imgEle.naturalHeight && imgEle.clientWidth > 0) {\n repositionCanvas();\n }\n}", "function mainDraw() {\n if (canvasValid == false) {\n clear(ctx);\n \n // Add stuff you want drawn in the background all the time here\n \n // draw all boxes\n var l = boxes2.length;\n for (var i = 0; i < l; i++) {\n boxes2[i].draw(ctx); // we used to call drawshape, but now each box draws itself\n }\n \n // Add stuff you want drawn on top all the time here\n \n canvasValid = true;\n }\n}", "draw(ctx) {\n const {x, y, w, h, radius, isMatched, scaleX, scaleY, img} = this;\n const grd = ctx.createLinearGradient(x, y, x + w, y + h);\n\n ctx.save();\n ctx.translate(x + 0.5 * w, y + 0.5 * h); // TRANSLATE TO SHAPE CENTER\n ctx.scale(scaleX, scaleY);\n ctx.translate(-(x + 0.5 * w), -(y + 0.5 * h)); // TRANSLATE CENTER BACK TO 0, 0\n ctx.beginPath();\n ctx.moveTo(x, y + radius);\n ctx.lineTo(x, y + h - radius);\n ctx.quadraticCurveTo(x, y + h, x + radius, y + h);\n ctx.lineTo(x + w - radius, y + h);\n ctx.quadraticCurveTo(x + w, y + h, x + w, y + h - radius);\n ctx.lineTo(x + w, y + radius);\n ctx.quadraticCurveTo(x + w, y, x + w - radius, y);\n ctx.lineTo(x + radius, y);\n ctx.quadraticCurveTo(x, y, x, y + radius);\n grd.addColorStop(0, '#800080');\n grd.addColorStop(1, '#660066');\n ctx.fillStyle = grd;\n ctx.strokeStyle = '#D896FF';\n ctx.lineWidth = 10;\n ctx.stroke();\n ctx.fill();\n\n // DRAW IMAGE IF CARD IS MATCHED\n\n ctx.clip();\n if (isMatched && scaleX >= 0 ) {\n\n ctx.drawImage(img, 0, 0, w, h, x, y, w, h);\n }\n ctx.restore()\n }", "function mainDraw() {\n\t\tif (canvasValid == false) {\n\t\tclear(ctx);\n\t\t\n\t\t// Add stuff you want drawn in the background all the time here\n\t\t\n\t\t// draw all boxes\n\t\tvar l = boxes2.length;\n\t\tfor (var i = 0; i < l; i++) {\n\t\t\tboxes2[i].draw(ctx); // we used to call drawshape, but now each box draws itself\n\t\t}\n\t\t\n\t\t// Add stuff you want drawn on top all the time here\n\t\tdocument.querySelector('#iou').innerHTML = computeIoU(boxes2[0], boxes2[1]);\n\t\t\n\t\tcanvasValid = true;\n\t\t}\n\t}", "function drawCaptionsToCanvas() {\r\n if (activeTabIndex === 2) {\r\n addOverlay(base_canvas, \"caption\");\r\n var baseRect = base_canvas.getBoundingClientRect();\r\n var overlayRect = current_overlay_canvas.getBoundingClientRect();\r\n var captionCanvases = [\r\n ...document.querySelectorAll(\".caption-canvas\")\r\n ].forEach(caption => {\r\n var topRect = caption.getBoundingClientRect();\r\n current_overlay_context.drawImage(\r\n caption,\r\n topRect.left - overlayRect.left,\r\n topRect.top - overlayRect.top\r\n );\r\n });\r\n }\r\n }", "drawCanvas(imgData,antiAliasRadius,dirtyArea) {\n\t\tantiAliasRadius=antiAliasRadius||0; // 0px as default\n\n\t\tconst gl=this.gl;\n\t\tconst program=this.canvasProgram;\n\t\tconst w=this.canvas.width;\n\t\tconst h=this.canvas.height;\n\t\t// const iw=imgData.validArea.width;\n\t\t// const ih=imgData.validArea.height;\n\t\t// area to draw\n\t\tconst tA=GLProgram.borderIntersection(dirtyArea||imgData.validArea,this.viewport);\n\n\t\tconst isToDraw=tA.width&&tA.height;\n\t\tconst tmp=this.tmpImageData;\n\t\ttmp.left=0;\n\t\ttmp.top=0;\n\t\t// horizontal blur\n\t\tconst unitRect=GLProgram.getAttributeRect();\n\t\tif(isToDraw) {\n\t\t\t// clear tmp\n\t\t\tthis.vramManager.verify(imgData);\n\t\t\tthis.vramManager.verify(tmp);\n\t\t\tprogram.setTargetTexture(tmp.data); // draw to temp data\n\t\t\tgl.viewport(0,0,w,h);\n\t\t\tgl.clearColor(0,0,0,0);\n\t\t\tgl.clear(gl.COLOR_BUFFER_BIT);\n\n\t\t\t// calculate area to render\n\t\t\t// vertically extend *2 AARad is for the following vertical AARad sampling\n\t\t\tconst tAW=GLProgram.borderIntersection({ // horizontal extend blur area\n\t\t\t\tleft: Math.floor(tA.left-antiAliasRadius),\n\t\t\t\ttop: Math.floor(tA.top-2*antiAliasRadius-1),\n\t\t\t\twidth: Math.ceil(tA.width+2*antiAliasRadius),\n\t\t\t\theight: Math.ceil(tA.height+4*antiAliasRadius+2)\n\t\t\t},this.viewport);\n\n\t\t\t// suppose tmp is at viewport position (left, top are 0)\n\t\t\tprogram.setSourceTexture(\"u_image\",imgData.data);\n\t\t\tprogram.setAttribute(\"a_src_pos\",GLProgram.getAttributeRect(tAW,imgData),2);\n\t\t\tprogram.setAttribute(\"a_src_posv\",GLProgram.getAttributeRect(tAW,imgData.validArea),2);\n\t\t\tprogram.setAttribute(\"a_dst_pos\",unitRect,2);\n\t\t\tprogram.setUniform(\"u_aa_step\",[1/imgData.width,0]); // 1 pixel horizontal\n\t\t\tprogram.setUniform(\"u_aa_stepv\",[1/imgData.validArea.width,0]); // 1 pixel horizontal\n\t\t\tprogram.setUniform(\"u_aa_cnt\",antiAliasRadius);\n\t\t\tgl.viewport(tAW.left,h-tAW.height-tAW.top,tAW.width,tAW.height); // set according to tAW\n\t\t\tgl.blendFunc(this.gl.ONE,this.gl.ZERO); // copy\n\t\t\tprogram.run();\n\t\t}\n\n\t\t// vertical blur\n\t\tprogram.setTargetTexture(null); // draw to canvas\n\t\tif(!dirtyArea){\n\t\t\t// 1. ready to draw the whole valid area (nothing outside)\n\t\t\t// 2. drawing an texture of no width/height\n\t\t\tgl.viewport(0,0,w,h);\n\t\t\tgl.clearColor(0,0,0,0);\n\t\t\tgl.clear(gl.COLOR_BUFFER_BIT);\n\t\t}\n\t\tif(!isToDraw){ // nothing to draw, do not change\n\t\t\treturn;\n\t\t}\n\n\t\t// draw tAWH part to canvas\n\t\tconst tAWH=GLProgram.borderIntersection({ // hori/vert extend blur area\n\t\t\tleft: Math.floor(tA.left-antiAliasRadius),\n\t\t\ttop: Math.floor(tA.top-antiAliasRadius),\n\t\t\twidth: Math.ceil(tA.width+2*antiAliasRadius),\n\t\t\theight: Math.ceil(tA.height+2*antiAliasRadius)\n\t\t},this.viewport);\n\n\t\tconst srcPosRect=GLProgram.getAttributeRect(tAWH,tmp);\n\t\tprogram.setSourceTexture(\"u_image\",tmp.data);\n\t\tprogram.setAttribute(\"a_src_pos\",srcPosRect,2);\n\t\tprogram.setAttribute(\"a_src_posv\",srcPosRect,2);\n\t\tprogram.setAttribute(\"a_dst_pos\",unitRect,2);\n\t\tprogram.setUniform(\"u_aa_step\",[0,1/h]); // 1 pixel vertical, tmp size is (w,h)\n\t\tprogram.setUniform(\"u_aa_stepv\",[0,1/h]); // 1 pixel vertical\n\t\tprogram.setUniform(\"u_aa_cnt\",antiAliasRadius);\n\t\tgl.viewport(tAWH.left,h-tAWH.height-tAWH.top,tAWH.width,tAWH.height); // set according to tAWH\n\t\tgl.blendFunc(this.gl.ONE,this.gl.ZERO); // copy\n\t\tprogram.run();\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 drawImage() {\n clear();\n ctx.save();\n ctx.scale(currentScale, currentScale);\n ctx.rotate(currentAngle * Math.PI / 180);\n ctx.drawImage(image, -image.width / 2, -image.height / 2);\n ctx.restore();\n }", "function VerticalAdjust() {\n\n var maxWidth = 1000;\n var maxHeight = 850;\n\n var minWidth = 450;\n var minHeight = 500;\n\n var origWidth = untouchedImage.width;\n var origHeight = untouchedImage.height;\n\n var windowWidth = $(window).width();\n var windowHeight = $(window).height();\n\n var canvasMaxWidth = (maxWidth > windowWidth) ? windowWidth : maxWidth;\n var canvasMaxHeight = (maxHeight > windowHeight) ? windowHeight : maxHeight;\n\n\n // ---------------------------\n // -- now deal with fitting the image\n // ---------------------------\n var canvasWidth;\n var canvasHeight;\n if (origWidth <= canvasMaxWidth && origHeight <= canvasMaxHeight) {\n\n // the image does not go out of the max canvas, make the canvas\n // be the size of the image.\n canvasWidth = origWidth;\n canvasHeight = origHeight;\n\n } else {\n\n // the image goes out of the max canvas, resize the image and canvas. Both\n // sizes are the same.\n\n\n var ratio;\n // determine restricting dimension\n if ((origWidth / origHeight) > (canvasMaxWidth / canvasMaxHeight)) {\n // width is the restricting dimension\n ratio = canvasMaxWidth / origWidth;\n canvasWidth = ratio * origWidth;\n if (canvasWidth < minWidth) {\n ratio = minWidth / origWidth;\n canvasWidth = ratio * origWidth;\n }\n canvasHeight = ratio * origHeight;\n } else {\n // height is the restricting dimension\n ratio = canvasMaxHeight / origHeight;\n canvasHeight = ratio * origHeight;\n if (canvasHeight < minHeight) {\n ratio = minHeight / origHeight;\n canvasHeight = ratio * origHeight;\n }\n canvasWidth = ratio * origWidth;\n }\n\n }\n\n $('#canvas,#image').css({\n 'width': canvasWidth + 'px',\n 'height': canvasHeight + 'px'\n });\n\n // ---------------------------\n // -- do the vertical align\n // ---------------------------\n $('#canvas').css({\n top: ($(window).height() - canvasHeight) / 2\n });\n\n\n\n}", "function backendOCR(base64Image, imageWidth, imageHeight) {\n ocrReq({image: base64Image})\n .then(lines => {\n lines.lines = lines;\n for (var idx = 0; idx < lines.lines.length; idx++) {\n lines.lines[idx].bbox.x0 = Math.round(lines.lines[idx].bbox.x0 * imageWidth);\n lines.lines[idx].bbox.x1 = Math.round(lines.lines[idx].bbox.x1 * imageWidth);\n lines.lines[idx].bbox.y0 = Math.round(lines.lines[idx].bbox.y0 * imageHeight);\n lines.lines[idx].bbox.y1 = Math.round(lines.lines[idx].bbox.y1 * imageHeight);\n }\n console.log(lines);\n handleOCRResult(lines);\n })\n .catch(error => {\n console.error(error);\n });\n}", "function initCanvas() {\n context = document.getElementById('canvas').getContext('2d');\n context.strokeStyle = 'black';\n context.fillStyle = 'white';\n context.lineJoin = 'round';\n context.lineCap = 'round';\n context.lineWidth = 15;\n\n pcontext = document.getElementById('prediction').getContext('2d');\n pcontext.font = '240px Roboto';\n pcontext.textAlign = 'center';\n pcontext.textBaseline = 'middle';\n\n $('#canvas').mousedown(function (e) {\n if (prediction)\n clearCanvas();\n addPoint(e.pageX - this.offsetLeft, e.pageY - this.offsetTop);\n mouseIsDown = true;\n redraw();\n });\n\n $('#canvas').mousemove(function (e) {\n if (mouseIsDown) {\n addPoint(e.pageX - this.offsetLeft, e.pageY - this.offsetTop);\n redraw();\n }\n });\n\n $('#canvas').mouseup(function (e) {\n mouseIsDown = false;\n });\n\n $('#canvas').mouseleave(function (e) {\n mouseIsDown = false;\n });\n\n clearCanvas();\n}", "function doneDrawing() {\n canImage.context.drawImage(imgArray[imgNumber], 50, 50)\n canImage.changeOpacity(0.3);\n canDraw.overlay(canOverlay);\n canOverlay.changeOpacity(0.5);\n}", "function cropImages ( f, index ){\n //face found\n if( f ){\n //get body\n var body = $('body')[0];\n //create new canvas for cropped Image\n canvasObjects[index] = document.createElement('canvas');\n canvasObjects[index].width = f.width + 20;\n canvasObjects[index].height = f.width + 40;\n\n //get old canvas for cropping\n var i = document.getElementById(\"detectedImage\");\n\n //get old image context\n var ctx = i.getContext(\"2d\");\n\n //get new created canvas context\n var ctx1 = canvasObjects[index].getContext(\"2d\");\n\n //now get to x y and width and height of current Faces\n //margin added in both width and height\n var croppedImage = ctx.getImageData( f.x - 7, f.y - 7, f.width + 20, f.height + 40 );\n\n //draw image with given values to new canvas\n ctx1.putImageData(croppedImage, 0, 0);\n\n //TODO:here we modify the image to server instead of append in body\n sendToSever(canvasObjects[index].toDataURL(\"image/jpeg\"));\n\n //all done just append the canvas to body\n body.appendChild(canvasObjects[index])\n\n\n }\n}", "function draw(){\n\nctx.fillStyle = '#EEEEEE';\n ctx.fillRect(0, 0, theCanvas.width, theCanvas.height);\n //Box\n ctx.strokeStyle = '#000000';\n ctx.strokeRect(1, 1, theCanvas.width-2, theCanvas.height-2);\n\ndrawMountain();\ndrawTargetCannon();\ndrawUserCannon();\nctx.addEventListener(\"click\",drawScreen);\n\n\n}", "recompositeCanvases() {\n const mainctx = this.mainCanvas.getContext('2d');\n\n for (let i = 0; i < this.canvas.length; i++) {\n const tempctx = this.canvas[i].temp.getContext('2d');\n const drawctxNext = this.canvas[i + 1] !== undefined ? this.canvas[i + 1].draw.getContext('2d') : null;\n\n if (drawctxNext !== null) {\n // Clear [i + 1].draw\n this.canvas[i + 1].draw.width = this.canvas[i + 1].draw.width;\n\n // Stamp [i].temp to [i + 1].draw\n drawctxNext.globalCompositeOperation = 'source-over';\n drawctxNext.drawImage(this.canvas[i].temp, 0, 0);\n }\n\n // Stamp [i].draw to [i].temp\n tempctx.globalCompositeOperation = 'source-over';\n tempctx.drawImage(this.canvas[i].draw, 0, 0);\n\n if (drawctxNext !== null) {\n // Stamp [i].draw to [i + 1].draw (destination-in)\n drawctxNext.globalCompositeOperation = 'destination-in';\n drawctxNext.drawImage(this.canvas[i].draw, 0, 0);\n }\n\n // The image\n const img = this.images[i].img;\n\n // Calculate ratio to scale image to canvas\n let widthRatio, heightRatio, ratio = 1;\n\n if (img.width > this.mainCanvas.width || img.height > this.mainCanvas.height) {\n widthRatio = this.mainCanvas.width / img.width;\n heightRatio = this.mainCanvas.height / img.height;\n ratio = Math.min(widthRatio, heightRatio);\n }\n\n // Calculate centered image position\n const centerX = ( this.mainCanvas.width - img.width * ratio ) / 2;\n const centerY = ( this.mainCanvas.height - img.height * ratio ) / 2;\n\n // Stamp image[i] to [i].temp (source-atop)\n tempctx.globalCompositeOperation = 'source-atop';\n tempctx.drawImage(img, 0, 0, img.width, img.height, centerX, centerY, img.width * ratio, img.height * ratio);\n\n // Stamp [i].temp to mainCanvas\n mainctx.drawImage(this.canvas[i].temp, 0, 0);\n }\n\n }", "drawCanvas() {\n\n\t}", "function render_user_interface()\n{\n mycanvas_context.drawImage(m_canvas, 0, 0);\n}", "draw(canvas, rect, viewId, elementId, elementType, widgetTime, stateTime, mode, attributes) {\n\n canvas.imageSmoothingEnabled=true;\n\n if (elementType == \"background\") {\n\n this.drawBackground(canvas, rect, viewId, elementId, widgetTime, stateTime, mode, attributes);\n\n } else if (elementType == \"button\") {\n\n this.drawButton(canvas, rect, viewId, elementId);\n\n } else if (elementType == \"buttonImage\") {\n\n this.drawButtonImage(canvas, rect, viewId, elementId, widgetTime, stateTime, mode, attributes);\n\n } else if (elementType == \"image\") {\n \n this.drawImage(canvas, rect, viewId, elementId, widgetTime, stateTime, mode, attributes);\n \n } else if (elementType == \"imageError\") {\n\n this.drawImageError(canvas, rect, viewId, elementId, widgetTime, stateTime, mode, attributes);\n\n } else if (elementType == \"text\") {\n\n this.drawText(canvas, rect, viewId, elementId, widgetTime, stateTime, mode, attributes);\n\n } else if (elementType == \"faceSearcher\") {\n \n this.drawFaceSearcher(canvas, rect, viewId, elementId, widgetTime, stateTime, mode, attributes);\n \n } else if (elementType == \"video\") {\n\n if (viewId == \"Extractor\") {\n if (this.extractionMode == FPhi.Selphi.Mode.Register)\n this.drawImageWithClippingCircle(canvas, rect, attributes.player, rect.x + rect.width / 2.0, rect.y + rect.height / 2.0, rect.width / 2.0);\n } else {\n this.drawImageWithClippingCircle(canvas, rect, attributes.player, rect.x + rect.width / 2.0, rect.y + rect.height / 2.0, rect.width / 2.0);\n }\n //this.drawImage(canvas,rect,attributes.player);\n\n } else if (elementType == \"camera\") {\n\n var progress = attributes.progress;\n var borderWidth = this.rm.getSetupFloat(\"facephi-widget-conf\", \"\", this.landscape, \"width_progress_bar\");\n var colorProgress = this.rm.getSetupColor(\"facephi-widget-conf\", \"\", this.landscape, \"color_progress_bar\");\n var colorWarning = this.rm.getSetupColor(\"facephi-widget-conf\", \"\", this.landscape, \"color_warning_message\");\n var colorExcellent = this.rm.getSetupColor(\"facephi-widget-conf\", \"\", this.landscape, \"color_quality_excellent\");\n var colorLow = this.rm.getSetupColor(\"facephi-widget-conf\", \"\", this.landscape, \"color_quality_low\");\n\n /*\n canvas.save();\n canvas.translate(this.width, 0);\n canvas.scale(-1, 1);\n\n\n this.cameraWidth = attributes.width;\n this.cameraHeight = attributes.height;\n this.cameraRotation = attributes.cameraRotation;\n this.faceDataRect = attributes.faceDataRect;\n this.faceTracking = attributes.faceTracking;\n\n // draw camera image to visible canvas\n if ((this.faceDataRect != 'undefined') && (this.faceDataRect != null) && (this.faceTracking)) {\n this.faceCenterOffsetTarget = { x: (this.faceDataRect.x + this.faceDataRect.width / 2.0) - this.circleX, y: (this.faceDataRect.y + this.faceDataRect.height / 2.0) - this.circleY }\n }\n this.faceCenterOffset.x += (this.faceCenterOffsetTarget.x - this.faceCenterOffset.x) * 0.1;\n this.faceCenterOffset.y += (this.faceCenterOffsetTarget.y - this.faceCenterOffset.y) * 0.1;\n var tRect = this.scaleRect({ width: this.cameraWidth, height: this.cameraHeight }, { x: 0, y: 0, width: this.width, height: this.height });\n\n // limit camera offset to circle bounds.\n var localCameraX = tRect.x + this.faceCenterOffset.x;\n if (localCameraX >= this.circleX - this.circleRadius) localCameraX = this.circleX - this.circleRadius;\n if (localCameraX + tRect.width <= this.circleX + this.circleRadius) localCameraX = this.circleX + this.circleRadius - tRect.width;\n var localCameraY = tRect.y - this.faceCenterOffset.y;\n if (localCameraY >= this.circleY - this.circleRadius) localCameraY = this.circleY - this.circleRadius;\n if (localCameraY + tRect.height <= this.circleY + this.circleRadius) localCameraY = this.circleY + this.circleRadius - tRect.height;\n\n*/\n canvas.save();\n canvas.beginPath();\n canvas.arc(this.circleX, this.circleY, this.circleRadius, 0, 2 * Math.PI, false);\n canvas.clip();\n //canvas.drawImage(attributes.camera, localCameraX, localCameraY, tRect.width, tRect.height);\n \n if ((attributes.state == \"UCLivenessMoveStabilizing\") || (attributes.state==\"UCLivenessMoveStabilized\") || (attributes.state==\"UCLivenessMoveDetecting\") || (attributes.state==\"UCLivenessMoveProcessing\")) {\n // Capa translucida negra para resaltar las letras\n canvas.fillStyle = \"#00000033\";\n canvas.fillRect(rect.x, rect.y, rect.width, rect.height);\n }\n\n //canvas.drawImage(attributes.camera, tRect.x, tRect.y, tRect.width, tRect.height);\n canvas.restore();\n\n //canvas.drawImage(attributes.camera, 0,0, tRect.width, tRect.height);\n\n var circleColor = colorProgress; // this.rm.getSetupColor(\"facephi-widget-conf\", \"\", \"color_progress_bar\");\n if (mode == \"Warning\")\n circleColor = colorWarning; // this.rm.getSetupColor(\"facephi-widget-conf\", \"\", \"color_warning_message\");\n\n if (progress == 0.0 && mode == \"Warning\") {\n // Arco completo\n canvas.beginPath();\n canvas.strokeStyle = colorLow; // this.rm.getSetupColor(\"facephi-widget-conf\",\"\",\"color_quality_low\");\n canvas.lineWidth = borderWidth; // this.rm.getSetupFloat(\"facephi-widget-conf\", \"\", \"width_progress_bar\");\n canvas.lineCap = \"round\";\n canvas.arc(this.circleX, this.circleY, this.circleRadius - (canvas.lineWidth / 2) + 0.5, -Math.PI / 2, 2 * Math.PI - Math.PI / 2);\n canvas.stroke();\n }\n\n if ((attributes.state == \"UCLivenessMoveStabilizing\") || (attributes.state==\"UCLivenessMoveStabilized\") || (attributes.state==\"UCLivenessMoveDetecting\") || (attributes.state==\"UCLivenessMoveProcessing\")) {\n progress = 1.0;\n if (attributes.liveness_move_last_result) circleColor = colorExcellent; // this.rm.getSetupColor(\"facephi-widget-conf\",\"\",\"color_quality_excellent\");\n else circleColor = colorLow; // this.rm.getSetupColor(\"facephi-widget-conf\",\"\",\"color_quality_low\");\n \n if (attributes.state==\"UCLivenessMoveDetecting\" || attributes.state==\"UCLivenessMoveProcessing\") {\n // Arco completo\n canvas.beginPath();\n canvas.strokeStyle = colorProgress; // this.rm.getSetupColor(\"facephi-widget-conf\",\"\",\"color_progress_bar\");;\n canvas.lineWidth = borderWidth; // this.rm.getSetupFloat(\"facephi-widget-conf\", \"\", \"width_progress_bar\");\n canvas.lineCap = \"round\";\n canvas.arc(this.circleX, this.circleY, this.circleRadius - (canvas.lineWidth / 2) + 0.5, -Math.PI / 2, 2 * Math.PI - Math.PI / 2);\n canvas.stroke(); \n }\n\n } else {\n \n if (progress > 1.0) progress=1.0;\n if (this.extractionMode == FPhi.Selphi.Mode.Authenticate)\n progress = progress*progress*(3.0 - 2.0*progress); //smoothstep\n\n canvas.beginPath();\n canvas.strokeStyle = circleColor;\n canvas.lineWidth = borderWidth; // this.rm.getSetupFloat(\"facephi-widget-conf\", \"\", \"width_progress_bar\");\n canvas.lineCap = \"round\";\n canvas.arc(this.circleX, this.circleY, this.circleRadius - (canvas.lineWidth / 2) + 0.5, -Math.PI / 2, 2 * Math.PI * progress - Math.PI / 2);\n canvas.stroke();\n\n var colorShutter = this.rm.getSetupColor(\"facephi-widget-conf\", \"\", this.landscape, \"color_shutter\");\n this.drawBlind(canvas, this.circleX, this.circleY, this.circleRadius, attributes.eyesYLevel, attributes.blind, colorShutter, attributes.blindText); \n }\n\n\n\n } else if (elementType == \"results\") {\n\n var totalTransitionTime = 1.000 + 1.500 * attributes.progress;\n var progressTime = stateTime / totalTransitionTime;\n if (progressTime > 1.0) {\n progressTime = 1.0;\n }\n\n // Calculamos la interpolacion de la barra de progreso (OutQuad -> InOutQuad)\n progressTime = progressTime * (2.0 - progressTime);\n progressTime = progressTime < 0.5 ? 2 * progressTime * progressTime : -1 + (4 - 2 * progressTime) * progressTime;\n\n canvas.beginPath();\n canvas.fillStyle = this.rm.getSetupColor(viewId, elementId, this.landscape, \"background_color\");\n canvas.arc(this.circleX, this.circleY, this.circleRadius, -Math.PI / 2, 2 * Math.PI - Math.PI / 2);\n canvas.fill();\n\n var scoreColor = this.rm.getSetupColor(\"facephi-widget-conf\", \"\", this.landscape, \"color_quality_excellent\");\n if (attributes.progress <= 0.33)\n scoreColor = this.rm.getSetupColor(\"facephi-widget-conf\", \"\", this.landscape, \"color_quality_low\");\n else if (attributes.progress <= 0.66)\n scoreColor = this.rm.getSetupColor(\"facephi-widget-conf\", \"\", this.landscape, \"color_quality_good\");\n\n canvas.beginPath();\n canvas.strokeStyle = scoreColor;\n canvas.lineWidth = this.rm.getSetupFloat(\"facephi-widget-conf\", \"\", this.landscape, \"width_progress_bar\");\n canvas.lineCap = \"round\";\n canvas.arc(this.circleX, this.circleY, this.circleRadius - (canvas.lineWidth / 2) * 0.5, -Math.PI / 2, 2 * Math.PI * attributes.progress * progressTime - Math.PI / 2);\n canvas.stroke();\n\n // score text\n var message = \"\";\n var tipMessage = \"\";\n if (attributes.progress >= 1.0) {\n message = this.rm.translate(\"results_quality_excellent\");\n tipMessage = this.rm.translate(\"results_quality_message\");\n } else if (attributes.progress >= 0.333) {\n message = this.rm.translate(\"results_quality_good\");\n tipMessage = this.rm.translate(\"results_quality_message\");\n } else {\n message = this.rm.translate(\"results_quality_low\");\n tipMessage = this.rm.translate(\"results_quality_message\");\n }\n\n var textSize = this.rm.getSetupFloat(viewId, elementId, this.landscape, \"fontResult_size\");\n var lineHeight = textSize+1;\n var textFont = this.rm.getSetupResourceId(viewId, elementId, this.landscape, \"fontResult\");\n var align = \"CENTER\";\n var valign = \"TOP\";\n this.drawStringMultiline(canvas, message, { x: 0, y: this.circleY - 5, width: this.width, height: this.height }, scoreColor, textFont, textSize,lineHeight,align,valign);\n\n textSize = this.rm.getSetupFloat(viewId, elementId, this.landscape, \"fontQuality_size\");\n var lineHeight = textSize+1;\n textFont = this.rm.getSetupResourceId(viewId, elementId, this.landscape, \"fontQuality\");\n var align = \"CENTER\";\n var valign = \"TOP\";\n this.drawStringMultiline(canvas, tipMessage, { x: 0, y: this.circleY + 5 + textSize, width: this.width, height: this.height }, scoreColor, textFont, textSize,lineHeight,align,valign);\n\n } else if (elementType == \"animation\") {\n var direction=0;\n //if (attributes.state == \"UCLivenessMoveDetecting\") {\n if (\"livenessMoveDirection\" in attributes)\n direction = attributes.livenessMoveDirection;\n if (elementId!=\"liveness_move\") direction=0;\n //}\n this.drawAnimation(canvas, rect, viewId, elementId, widgetTime, stateTime, mode, attributes,direction);\n } else if (elementId == \"progress\") {\n canvas.fillStyle = this.rm.getSetupColor(viewId, elementId, this.landscape, \"background_color\");\n canvas.fillRect(rect.x, rect.y, rect.width, rect.height);\n\n canvas.fillStyle = this.rm.getSetupColor(viewId, elementId, this.landscape, \"progress_color\");\n canvas.fillRect(rect.x, rect.y, rect.width*attributes.progress, rect.height);\n }\n }", "function onloadCallback(current_image) {\n\t\t//set the image as the background image of the canvas wrapper\n\t\t$('#canvas-wrapper').css('background', 'url(' + current_image.path +') no-repeat center center fixed').css('background-size', 'contain');\n\t}", "function insertImageToCanvas(statusBar, imageAddress) {\n var image = new Image();\n image.crossOrigin = '';\n image.onload = function () {\n var canvas = $(statusBar).find(\"#steg-canvas\").get(0);\n var context = canvas.getContext('2d');\n context.drawImage(image, 0, 0, image.width, image.height, 0, 0, canvas.width, canvas.width * 1.0 * image.width / image.height);\n var imageText = canvas.toDataURL();\n };\n image.src = imageAddress;\n}", "function draw(){\n ctx.fillStyle = \"#fff\";\n ctx.fillRect(0,0,canvas.width, canvas.height);\n if(imgOffsetWidth && imgOffsetHeight){\n ctx.drawImage(img, 0, 0, imgOffsetWidth, imgOffsetHeight); \n } else { \n ctx.drawImage(img, 0,0); \n }\n \n state.boxArr.forEach(function(el){\n ctx.fillStyle = el.style;\n // Set Skew\n \n //ctx.fillRect(el.x, el.y, el.w, el.h);\n ctx.beginPath();\n // Move to upper left corner to begin drawing of block\n ctx.moveTo(el.x, el.y);\n // Draw line across the top right corner of block\n ctx.lineTo((el.x + el.w), (el.y + el.xSkew));\n // Draw line from top right to bottom right corner of block\n ctx.lineTo((el.x + el.w), (el.y + el.h + el.xSkew));\n // Draw line from bottom right to bottom left corner of block\n ctx.lineTo(el.x, (el.y + el.h));\n //ctx.lineTo(el.y);\n ctx.closePath();\n ctx.strokeStyle = '#00ff00';\n ctx.lineWidth = 2;\n ctx.stroke();\n ctx.fill();\n adjustResizeBoxes(el);\n resizeBoxDraw(el);\n ctx.strokeStyle = '#fff';\n ctx.font=\"10px arial\";\n ctx.strokeText(el.key, el.x + 2, el.y + 10);\n ctx.strokeText(el.item, (el.x + el.w) - 20, el.y + 10);\n });\n window.requestAnimationFrame(draw);\n }", "function masterImage(mstrObj){\n //Image Tool Kit\n //console.log(\"in the pit\");\n //properties\n //required\n\n if(mstrObj == undefined){alert(\"canvas object parameter is not defined.\"); return;}\n if(mstrObj.home == undefined){alert(\"canvas object needs \\\"home:'container id string'\\\".\"); return;}\n var home = mstrObj.home;\n\n var iUN = mstrObj.iUN || Math.round(Math.random() * 10000);//see iUN get and set\n var canvas_type = mstrObj.type || \"thumbnail\";//NOTE may not need #remove\n var canvas_mode = mstrObj.mode || \"default\";//NOTE may not need #remove\n\n\n //at 100 x100 or 50 x50 the image is adjusted perfectly\n //100 x 80 the image is stretched\n //NOTE image 4:3 aspect ratio multiply by 3/4ths or .75\n var type_str = (canvas_mode != \"default\") ? canvas_type + \"_\" + canvas_mode : canvas_type;\n\n //used to set the various canvas default dimensions (if they arent manually entered)\n switch(type_str)\n {\n case \"thumbnail\":\n var default_width = 50;\n var default_height = 50;\n break;\n\n case \"profile\":\n var default_width = 100;\n var default_height = 100;\n break;\n\n case \"profile_edit\":\n var default_width = 200;\n var default_height = 200;\n break;\n\n case \"image\":\n var default_width = 100;\n var default_height = 75;\n break;\n }//end switch\n\n\n\n\n var canvas_width = mstrObj.width || default_width;\n var canvas_height = mstrObj.height || default_height;\n\n\n //HTML generated variable\n //window['CANVAS_IMG_URL'] = \"<?php echo JUri::root(); ?>components/com_arc/xfiles/images/\";\n var img_default = window['ARC_IMG_URL'] + \"flame.png\";\n\n //properties\n var canvas = \"\";\n var context_obj = \"\";\n var action = mstrObj.action || \"\";\n var prefix = mstrObj.varName || \"masImg\";//get set\n var fill_content = \"\";\n //console.log(display);\n var custom_class = \"\";\n var add_to_class = \"false\";\n var custom_id = \"\";\n var id_type = \"default\";\n var first_run = \"true\";\n var sli_ctrl_inputA = \"\";\n var\tsli_ctrl_inputB = \"\";\n var mousedown = false;\n var touchdown = false;\n var last_panel_clicked_id = \"\";//remove\n var last_x = \"default\";\n var last_y = \"default\";\n var offset_x = 0;\n var offset_y = 0;\n var img_label = \"default\";\n var slide_limit = 500;\n //var display_size = \"default\";\n\n var img_url = (mstrObj != undefined && mstrObj.url != undefined) ? mstrObj.url : img_default;\n\n //obj_globals\n var src_x = 0;\n var src_y = 5;\n var img_w = 500;\n var img_h = 500;\n var can_x = 0;\n var can_y = 0;\n var can_w = canvas_width;\n var can_h = canvas_height;\n\n //NOTE I don't need this. won't be saving this to local storage #remove\n /*try{\n if(localStorage != undefined && localStorage.canvas_tutorial != undefined && localStorage.canvas_tutorial != \"\")\n {\n var local_str = localStorage.canvas_tutorial;\n var local_ary = local_str.split(\",\");\n img_url = local_ary[0];\n src_x = local_ary[1];\n src_y = local_ary[2];\n img_w = local_ary[3];\n img_h = local_ary[4];\n can_x = local_ary[5];\n can_y = local_ary[6];\n can_w = local_ary[7];\n can_h = local_ary[8];\n }//end if\n }catch(e){\n console.log(\"nope. reload failed.\")\n }*/\n\n var obj_els = {};\n var event_ids = [];\n\n\n //methods\n this.setContent = function(sC){fill_content = sC;}//\n this.get_event_ids = function(){return event_ids;}\n this.setCustomClass = function(clsStr,addPar){custom_class = clsStr; add_to_class = addPar || true;/*addPar is nothing yet*/}\n this.setCustomId = function(cId){custom_id = cId; id_type = \"custom\";}\n\n var image_object=new Image();\n\n\n var create_canvas = function(c_cont){\n\n var bigDaddy = (document.getElementById(c_cont)) ? document.getElementById(c_cont) : document.getElementsByClassName(c_cont)[0];\n //clears container\n //if(clearHome == \"true\"){}\n bigDaddy.innerHTML = \"\";//\n\n /******************************** Sample Code *****************************************\n\n ***************************************************************************************/\n\n //alert(\"data object is \" + dataObject);\n //gets container\n\n\n var add_custom_class = (custom_class != \"\") ? custom_class : \"\";\n\n canvas = document.createElement(\"canvas\");\n canvas.id = prefix + \"_ImgCanvas\" + \"_\" + iUN;\n\n event_ids.push(canvas.id);\n\n canvas.className = prefix + \"__ImgCanvas\" + iUN + \" \" + prefix + \"__ImgCanvas \" + prefix + \" ImgCanvas \" + add_custom_class;\n\n if(fill_content != \"\"){canvas.innerHTML = fill_content;}\n\n bigDaddy.appendChild(canvas);\n\n context_obj = canvas.getContext('2d');\n canvas.width = canvas_width;\n canvas.height = canvas_height;\n\n }//end create_preview\n\n var draw_me = function() {\n\n //console.log(\"draw running\");\n\n //clear the canvas\n //canvas.width = canvas.width;\n\n if (canvas.getContext) {\n\n image_object.onload=function(){\n\n //needs this to keep drawing movements smooth\n canvas.width = canvas_width;\n canvas.height = canvas_height;\n\n context_obj.drawImage(image_object, src_x, src_y, img_w, img_h, can_x, can_y, can_w, can_h);\n //console.log(\"image_object\",image_object);//try here\n\n }//end onload//\n\n\n image_object.src=img_url;\n //console.log(\"image_object\",image_object);//nothing to run yet here so its \"\"\n //var dataURL = canvas.toDataURL(\"image/png\");\n //console.log(\"image_object height = \",image_object.height);\n }//end if\n\n\n }//end draw_me\n\n var canvas_editor = function()\n {\n\n\n\n }//end canvas_editor\n\n\n this.display = function(){\n switch(canvas_mode)\n {\n case \"edit\":\n //prep edit elements that add canvas\n control_panel();\n //draw it\n draw_me();\n break;\n\n default:\n create_canvas(home);\n draw_me();\n break;\n\n }//end switch\n }//end display\n\n\n /******************************** SCRAP SECTION BELOW ****************************************/\n\n //NOTE i don't need this panel array - i will need a btn array in its place.\n var ctrl_ary = [\n {\n \"label\":\"POSIION\",\n \"contents\":\"IP\",\n \"title\":\"Image Position\",\n },\n {\n \"label\":\"SCALE\",\n \"contents\":\"IS\",\n \"title\":\"Image Scale\",\n },\n {\n \"label\":\"BORDERS\",\n \"contents\":\"CB\",\n \"title\":\"Canvas Borders\",\n },\n {\n \"label\":\"BORDER SCALE\",\n \"contents\":\"BS\",\n \"title\":\"Canvas Border scale\",\n },\n {\n \"label\":\"BACKGROUND COLOR\",\n \"contents\":\"BC\",\n \"title\":\"Background Color\",\n },\n {\n \"label\":\"RESET\",\n \"contents\":\"RE\",\n \"title\":\"Reset All\",\n }\n\n ];//end ctrl_ary\n\n var size_ary = [\n {\n \"label\":\"XS\",\n \"contents\":\"XS\",\n \"title\":\"for extra small images\",\n \"size\":\"100\",\n \"scale\":\"200%\",\n \"zoom\":\"5X\",\n \"limit\":\"150\"\n },{\n \"label\":\"S\",\n \"contents\":\"S\",\n \"title\":\"for small images\",\n \"size\":\"640\",\n \"scale\":\"100%\",\n \"zoom\":\"4X\",\n \"limit\":\"700\"\n },\n {\n \"label\":\"M\",\n \"contents\":\"M\",\n \"title\":\"for medium images\",\n \"size\":\"1280\",\n \"scale\":\"50%\",\n \"zoom\":\"3X\",\n \"limit\":\"1330\"\n },\n {\n \"label\":\"L\",\n \"contents\":\"L\",\n \"title\":\"for large images\",\n \"size\":\"2560\",\n \"scale\":\"25%\",\n \"zoom\":\"2X\",\n \"limit\":\"2610\"\n },\n {\n \"label\":\"XL\",\n \"contents\":\"XL\",\n \"title\":\"for extra large images\",\n \"size\":\"5120\",\n \"scale\":\"12.5%\",\n \"zoom\":\"1X\",\n \"limit\":\"5170\"\n }\n\n ];//end size_ary\n\n //size_ary.reverse();\n\n var control_panel = function(){\n\n //object properties\n\n\n //local variables\n\n //jqm collapsible\n var bigDaddy = document.getElementsByClassName(home)[0];\n //clear the container\n bigDaddy.innerHTML = \"\";\n\n var edit_box = document.createElement(\"div\");\n edit_box.id = \"edit_box\" + iUN;\n edit_box.className = \"edit_box\" + iUN + \" edit_box \";//test_orange\n //collapsible set\n\n\n //make the other Stuff\n\n //edit_sectionB\n var edit_sectionB = document.createElement(\"div\");\n edit_sectionB.id = \"edit_sectionB\" + iUN;\n edit_sectionB.className = \"edit_sectionB\" + iUN + \" edit_sectionB \";//test_blue\n\n //canvas_cont\n var canvas_cont = document.createElement(\"div\");\n canvas_cont.id = \"canvas_cont\" + iUN;\n canvas_cont.className = \"canvas_cont\" + iUN + \" canvas_cont \";//test_purple\n obj_els[\"edit_home_id\"] = canvas_cont.id;\n\n\n\n //edit_slider_box\n var edit_slider_box = document.createElement(\"div\");\n edit_slider_box.id = \"edit_slider_box\" + iUN;\n edit_slider_box.className = \"edit_slider_box\" + iUN + \" edit_slider_box \";//test_yellow\n\n //edit_lock_box\n var edit_lock_box = document.createElement(\"div\");\n edit_lock_box.id = \"edit_lock_box\" + iUN;\n edit_lock_box.className = \"edit_lock_box\" + iUN + \" edit_lock_box test_pink\";\n\n //edit_lock_box\n var edit_slider_cont = document.createElement(\"div\");\n edit_slider_cont.id = \"edit_slider_cont\" + iUN;\n edit_slider_cont.className = \"edit_slider_cont\" + iUN + \" edit_slider_cont \";//test_green\n\n\n edit_slider_box.appendChild(edit_lock_box);\n edit_slider_box.appendChild(edit_slider_cont);\n\n edit_sectionB.appendChild(canvas_cont);\n\n //edit_resize_box\n var edit_resize_box = document.createElement(\"div\");\n edit_resize_box.id = \"edit_resize_box\" + iUN;\n edit_resize_box.className = \"edit_resize_box\" + iUN + \" edit_resize_box \";\n\n\n //$(\".ctrl_cont\").addClass(\"hibernate\");\n //$(\".col_label\").removeClass(\"hide\");\n edit_box.appendChild(edit_resize_box);\n edit_box.appendChild(edit_sectionB);\n edit_box.appendChild(edit_slider_box);\n\n //edit_cmd_label\n var edit_cmd_label = document.createElement(\"div\");\n edit_cmd_label.id = \"edit_cmd_label\" + iUN;\n edit_cmd_label.className = \"edit_cmd_label\" + iUN + \" edit_cmd_label test_orange\";\n\n\n var ctrl_box = document.createElement(\"div\");\n ctrl_box.id = \"ctrl_box\" + iUN;\n ctrl_box.className = \"ctrl_box\" + iUN + \" ctrl_box edit_sectionA \";\n\n\n\n edit_box.appendChild(ctrl_box);\n edit_box.appendChild(edit_cmd_label);\n\n\n bigDaddy.appendChild(edit_box);\n\n\n\n\n var test_nbr = 3;\n //content for ctrl_box\n for(var x = 0; x < ctrl_ary.length ; x++){\n\n var ec_Nm = \"edit_ctrl_btn\" + x;\n var edit_ctrl_btn = document.createElement(\"button\");\n edit_ctrl_btn.id = \"edit_ctrl_btn\" + iUN + \"_\" + x;\n edit_ctrl_btn.className = \"edit_ctrl_btn\" + iUN + \"_\" + x + \" edit_ctrl_btn\" + x + \" edit_ctrl_btn \";\n edit_ctrl_btn.setAttribute(\"href\",\"#\");\n edit_ctrl_btn.dataset.nbr = x;\n edit_ctrl_btn.dataset.contents = ctrl_ary[x].contents;\n edit_ctrl_btn.title = ctrl_ary[x].title;\n //edit_ctrl_btn.innerHTML = \"<h5>\" + ctrl_ary[x].label + \"</h5>\";\n obj_els[ec_Nm] = edit_ctrl_btn;\n\n //helps set up the correct call inside the event listener\n obj_els[\"contents\" + x] = ctrl_ary[x].contents;\n\n\n obj_els[ec_Nm].addEventListener(\"click\",function(e){\n //i used this.dataset so it doesn't pass the updated x of the for loop\n //and everything ending up being on click of the last index nbr passed\n e.preventDefault();\n var sNbr = this.dataset.nbr;\n var my_contents = this.dataset.contents\n run_contents(my_contents);\n })//end c_Nm\n\n ctrl_box.appendChild(edit_ctrl_btn);\n\n }//end for\n\n\n //content for edit_resize_box\n for(var y = 0; y < size_ary.length ; y++){\n\n var er_Nm = \"edit_resize_btn\" + y;\n var edit_resize_btn = document.createElement(\"button\");\n edit_resize_btn.id = \"edit_resize_btn\" + iUN + \"_\" + y;\n edit_resize_btn.className = \"edit_resize_btn\" + iUN + \"_\" +y + \" edit_resize_btn\" + y + \" edit_resize_btn \";\n edit_resize_btn.setAttribute(\"href\",\"#\");\n edit_resize_btn.dataset.nbr = y;\n edit_resize_btn.dataset.contents = size_ary[y].contents;\n edit_resize_btn.title = size_ary[y].title;\n edit_resize_btn.innerHTML = \"<h6>\" + size_ary[y].zoom + \"</h6>\";\n obj_els[er_Nm] = edit_resize_btn;\n\n //helps set up the correct call inside the event listener\n obj_els[\"contents\" + y] = size_ary[y].contents;\n\n\n obj_els[er_Nm].addEventListener(\"click\",function(e){\n //i used this.dataset so it doesn't pass the updated x of the for loop\n //and everything ending up being on click of the last index nbr passed\n e.preventDefault();\n var sNbr = this.dataset.nbr;\n var my_contents = this.dataset.contents\n run_contents(my_contents);\n })//end c_Nm\n\n edit_resize_box.appendChild(edit_resize_btn);\n\n }//end for\n\n create_canvas(obj_els[\"edit_home_id\"]);\n run_contents(\"IP\");\n\n }//end control_panel\n\n\n\n var run_contents = function(str)\n {\n switch(str)\n {\n case \"IP\":\n //image position\n add_slider_input(0);\n break;\n\n case \"IS\":\n //image scale\n add_slider_input(1);\n break;\n\n case \"CB\":\n //canvas border\n add_slider_input(2);\n break;\n\n case \"BS\":\n //canvas border scale\n add_slider_input(3);\n break;\n\n case \"BC\":\n\n break;\n\n case \"RE\":\n reset_canvas();\n break;\n\n //resize section\n case \"XS\":\n reset_canvas();\n\n img_w = size_ary[0].size;\n img_h = img_w;\n can_w = canvas_width;\n can_h = canvas_width;\n slide_limit = size_ary[0].limit;\n img_label = size_ary[0].label;\n\n control_panel();\n draw_me();\n\n break;\n\n case \"S\":\n reset_canvas();\n\n img_w = size_ary[1].size;\n img_h = img_w;\n can_w = canvas_width;\n can_h = canvas_width;\n slide_limit = size_ary[1].limit;\n img_label = size_ary[1].label;\n\n control_panel();\n draw_me();\n break;\n\n case \"M\":\n reset_canvas();\n\n img_w = size_ary[2].size;\n img_h = img_w;\n can_w = canvas_width;\n can_h = canvas_width;\n slide_limit = size_ary[2].limit;\n img_label = size_ary[2].label;\n\n control_panel();\n draw_me();\n break;\n\n case \"L\":\n reset_canvas();\n\n img_w = size_ary[3].size;\n img_h = img_w;\n can_w = canvas_width;\n can_h = canvas_width;\n slide_limit = size_ary[3].limit;\n img_label = size_ary[3].label;\n //canvas.width = canvas.width;\n\n control_panel();\n draw_me();\n\n break;\n\n case \"XL\":\n reset_canvas();\n\n img_w = size_ary[4].size;\n img_h = img_w;\n can_w = canvas_width;\n can_h = canvas_width;\n slide_limit = size_ary[4].limit;\n img_label = size_ary[4].label;\n //canvas.width = canvas.width;\n control_panel();\n draw_me();\n\n break;\n\n }//end switch\n\n }//end run_contents\n\n var reset_canvas = function()\n {\n src_x = 0;\n src_y = 0;\n img_w = 500;\n img_h = 500;\n can_x = 0;\n can_y = 0;\n can_w = canvas_width;\n can_h = canvas_width;\n //canvas.width = canvas.width;\n create_canvas(obj_els[\"edit_home_id\"]);\n draw_me();\n\n }//end reset_canvas\n\n //html5 slider research\n //https://codepen.io/collection/DgYaMj/2/\n //http://thenewcode.com/757/Playing-With-The-HTML5-range-Slider-Input\n //http://danielstern.ca/range.css/#/\n //http://www.cssportal.com/style-input-range/\n\n\n var add_slider_input = function(nbr)\n {\n var home = document.getElementsByClassName(\"edit_slider_cont\")[0];\n home.innerHTML = \"\";\n\n \t\t\t//reset slide input\n\t\t\tsli_ctrl_inputA = \"\";\n\t\t\tsli_ctrl_inputB = \"\";\n\n var styleA = (nbr == 0 || nbr == 1) ? \"goofy\" : \"default\";//may need to make this different with html range slider\n var styleB = (nbr == 0 || nbr == 1) ? \"default\" : \"goofy\";//reverse for html slider\n var my_limit = (nbr == 0 || nbr == 1) ? slide_limit: canvas_width;//\n\n //SLIDER A\n var sli_ctrl_contA = document.createElement(\"div\");\n sli_ctrl_contA.id = \"sli_ctrl_contA\";\n sli_ctrl_contA.className = \"sli_ctrl_contA\";//\n\n //input\n /*\n var sli_ctrl_inputA = document.createElement(\"input\");\n sli_ctrl_inputA.id = \"sli_ctrl_inputA\";\n sli_ctrl_inputA.className = \"sli_ctrl_inputA\";//\n sli_ctrl_inputA.setAttribute(\"data-slider-id\",\"sli_ctrl_inputA\");//\n sli_ctrl_inputA.setAttribute(\"data-slider-min\",\"-\" + my_limit);//\n sli_ctrl_inputA.setAttribute(\"data-slider-max\",my_limit);//\n sli_ctrl_inputA.setAttribute(\"data-slider-step\",\"1\");//\n var set_valA = slide_data(\"A\",nbr);\n var goof_A = set_valA * -1;//natural opposite effect\n var ctrl_valA = (style == \"goofy\") ? goof_A : set_valA;\n sli_ctrl_inputA.setAttribute(\"data-slider-value\", ctrl_valA);//\n //sli_ctrl_inputA.setAttribute(\"data-slider-handle\",\"custom\");//ninja stars section\n sli_ctrl_inputA.type = \"text\";\n sli_ctrl_inputA.onfocus = function(){this.select();}\n */\n\n sli_ctrl_inputA = document.createElement(\"input\");\n sli_ctrl_inputA.id = \"sli_ctrl_inputA\";\n sli_ctrl_inputA.className = \"sli_ctrl_inputA sli_ctrl_input slider\";\n sli_ctrl_inputA.name = \"sli_ctrl_inputA\";\n //sli_ctrl_inputA.dataset.type = \"range\";\n sli_ctrl_inputA.type = \"range\";\n sli_ctrl_inputA.setAttribute(\"min\",\"-\" + my_limit);\n //max changes depending on user access\n //verified server side\n //entered range number can't be greater than db record of your max access\n sli_ctrl_inputA.setAttribute(\"max\",my_limit);\n var set_valA = slide_data(\"A\",nbr);\n var goof_A = set_valA * -1;//natural opposite effect\n var ctrl_valA = (styleA == \"goofy\") ? goof_A : set_valA;\n sli_ctrl_inputA.setAttribute(\"value\",ctrl_valA);\n\n sli_ctrl_contA.appendChild(sli_ctrl_inputA);//\n\n //A onchange function below\n\n\n var sli_ctrl_boxA = document.createElement(\"input\");\n sli_ctrl_boxA.id = \"sli_ctrl_boxA\";\n sli_ctrl_boxA.className = \" sli_ctrl_boxA\";//\n sli_ctrl_boxA.value = set_valA;//src_x;\n sli_ctrl_boxA.type = \"number\";\n sli_ctrl_boxA.onfocus = function(){this.select(); }\n\n sli_ctrl_boxA.oninput = function(){\n sli_ctrl_inputA.value = sli_ctrl_boxA.value;\n slide_data(\"A\",nbr,{\"value\" :\tsli_ctrl_boxA.value, \"val_oper\": \"add\"});\n //src_x = sli_ctrl_inputA.value;\n sliderA.setValue();\n draw_me();\n }//end on oninput\n\n\n\n //sli_ctrl_contA.appendChild(sli_ctrl_boxA);\n\n //END SLIDER A\n\n //SLIDER B\n var sli_ctrl_contB = document.createElement(\"div\");\n sli_ctrl_contB.id = \"sli_ctrl_contB\";\n sli_ctrl_contB.className = \"sli_ctrl_contB\";\n\n //input\n /*\n var sli_ctrl_inputB = document.createElement(\"input\");\n sli_ctrl_inputB.id = \"sli_ctrl_inputB\";\n sli_ctrl_inputB.className = \"sli_ctrl_inputB\";//\n sli_ctrl_inputB.setAttribute(\"data-slider-id\",\"sli_ctrl_inputB\");//\n sli_ctrl_inputB.setAttribute(\"data-slider-min\",\"-\" + my_limit);\n sli_ctrl_inputB.setAttribute(\"data-slider-max\",my_limit);//\n sli_ctrl_inputB.setAttribute(\"data-slider-step\",\"1\");//\n var set_valB = slide_data(\"B\",nbr);\n var goof_B = set_valB * -1;//natural opposite effect\n var ctrl_valB = (style == \"goofy\") ? goof_B : set_valB;\n sli_ctrl_inputB.setAttribute(\"data-slider-value\",ctrl_valB);\n sli_ctrl_inputB.setAttribute(\"data-slider-orientation\",\"vertical\");\n //sli_ctrl_inputB.setAttribute(\"data-slider-handle\",\"custom\");//ninja stars section\n sli_ctrl_inputB.type = \"text\";\n sli_ctrl_inputB.onfocus = function(){this.select();}\n */\n\n\n sli_ctrl_inputB = document.createElement(\"input\");\n sli_ctrl_inputB.id = \"sli_ctrl_inputB\";\n sli_ctrl_inputB.className = \"sli_ctrl_inputB sli_ctrl_input slider\";\n sli_ctrl_inputB.name = \"sli_ctrl_inputB\";\n //sli_ctrl_inputB.dataset.type = \"range\";\n sli_ctrl_inputB.type = \"range\";\n sli_ctrl_inputB.setAttribute(\"min\",\"-\" + my_limit);\n //max changes depending on user access\n //verified server side\n //entered range number can't be greater than db record of your max access\n sli_ctrl_inputB.setAttribute(\"max\",my_limit);\n var set_valB = slide_data(\"B\",nbr);\n var goof_B = set_valB * -1;//natural opposite effect\n var ctrl_valB = (styleB == \"goofy\") ? goof_B : set_valB;\n sli_ctrl_inputB.setAttribute(\"value\",ctrl_valB);\n\n sli_ctrl_contB.appendChild(sli_ctrl_inputB);\n\n\n //console.info(\"sli_ctrl_inputB\");//\n //console.dir(sli_ctrl_inputB);\n\n var sli_ctrl_boxB = document.createElement(\"input\");\n sli_ctrl_boxB.id = \"sli_ctrl_boxB\";\n sli_ctrl_boxB.className = \"sli_ctrl_boxB\";//\n sli_ctrl_boxB.value = set_valB;//src_y;\n sli_ctrl_boxB.type = \"number\";\n sli_ctrl_boxB.onfocus = function(){this.select(); }\n\n //boxB input event\n sli_ctrl_boxB.oninput = function(){\n sli_ctrl_inputB.value = sli_ctrl_boxB.value;\n slide_data(\"B\",nbr,{\"value\" : \tsli_ctrl_boxB.value, \"val_oper\": \"add\"});\n //src_y = sli_ctrl_inputB.value;\n sliderB.setValue();\n draw_me();\n }//end on oninput\n\n\n\n //sli_ctrl_contB.appendChild(sli_ctrl_boxB);\n\n home.appendChild(sli_ctrl_contA);\n home.appendChild(sli_ctrl_contB);\n\n /*\n var sliderA = new Slider('#sli_ctrl_inputA', {\n formatter: function(value) {\n return 'Current value: ' + value;\n }\n });//end new slider script\n\n console.info(\"sliderA\");\n console.dir(sliderA);\n //http://seiyria.com/bootstrap-slider/\n\n var sliderB = new Slider('#sli_ctrl_inputB', {\n formatter: function(value) {\n return 'Current value: ' + value;\n }\n });//end new slider script\n */\n\n //$('input').slider();//calls both sliders\n //$('#sli_ctrl_inputA').slider();//\n //$(\"#lat_slider\").on('change',function(){slideUpdate({'mode':gEd_mode,'dir':'lattitude'});});\n //$(\"#lon_slider\").on('change',function(){slideUpdate({'mode':gEd_mode,'dir':'longitude'});});\n\n\n //$(\"#sli_ctrl_contB\").on('change',function(){\n sli_ctrl_inputB.oninput = function(e){\n console.log(\"slider B = \",sli_ctrl_inputB.value);\n\t\t\t\t\t\timage_update({\"ltr\":\"B\", \"nbr\":nbr, \"style\":styleB, \"mode\":\"motion\", \"slide_el\":sli_ctrl_inputB, \"box_el\":sli_ctrl_boxB});\n\n };//end on blur\n\n //A onchange function\n //$(\"#sli_ctrl_contA\").on('change',function(){\n sli_ctrl_inputA.oninput = function(){\n console.log(\"slider A = \",sli_ctrl_inputA.value);\n\t\t\t\t\t\timage_update({\"ltr\":\"A\", \"nbr\":nbr, \"style\":styleA, \"mode\":\"motion\", \"slide_el\":sli_ctrl_inputA, \"box_el\":sli_ctrl_boxA});\n\n };//end on blur//\n //http://seiyria.com/bootstrap-slider/\n\n //END SLIDER B\n\n\t\t\t\t\t\tcanvas_mouse_events(\"set\");\n\n\t\t\t\t\t\tcanvas.onmouseover = function(e)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t//\n\t\t\t\t\t\t\tcanvas_mouse_events(\"set\");\n\n\t\t\t\t\t\t\twindow.onmousemove = function(e)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tmove_my_image(e);\n\t\t\t\t\t\t\t}//end canvas mousemove\n\n }//on mouse over\n\n //mouse has 4 events (mO,mD, mU, mM) touch only has 3 (tS,tE,tM)\n //so i had to do more with less - it was pretty straight forward after that.\n\n canvas.ontouchstart = function(e)\n {\n touchdown = true;\n e.preventDefault();\n\t\t\t\t\t\t\tget_touch_offset(e)\n\t\t\t\t\t\t\tcanvas_mouse_events(\"set\");\n //alert(\"touch started\");\n\n canvas.ontouchmove = function(e)\n\t\t\t\t\t\t\t{\n //alert(\"move started\");\n\t\t\t\t\t\t\t\tmove_my_image(e);\n\t\t\t\t\t\t\t}//end canvas mousemove\n\n }//end ontouchstart\n\n //i put this in a separate function so i can use it for touch and mouse\n //canvas events\n var move_my_image = function(e)\n {\n //console.log(e);\n\t\t\t\t\t\t\t\tif(mousedown == true || touchdown == true)\n\t\t\t\t\t\t\t\t{\n //alert(\"im goin in\");\n //stops the mouse from hightlighting everyting on the page\n\t\t\t\t\t\t\t\t//e.preventDefault();\n var motion_method = (mousedown == true) ? \"mouse\" : (touchdown == true) ? \"touch\" : \"error\";\n\t\t\t\t\t\t\t\t\t//e.clientX,Y = mouse position in the browser window\n\t\t\t\t\t\t\t\t\tvar y = (mousedown == true) ? e.clientY : e.touches[0].clientY;//this number is a large # like 400 or 600\n\t\t\t\t\t\t\t\t\tvar x = (motion_method == \"mouse\") ? e.clientX : e.touches[0].clientX;\n\t\t\t\t\t\t\t\t\tvar pos = (motion_method == \"mouse\") ? getMousePos(e) : getTouchPos(e);\n\t\t\t\t\t\t\t\t\tvar pos_x = pos.x; //converts to a small number like 37\n\t\t\t\t\t\t\t\t\tvar pos_y = pos.y;\n\n //if(motion_method == \"touch\"){alert(\"pos_x = \" + pos_x + \", pos_y = \" + pos_y\n // + \", x = \" + x + \", y = \" + y)}\n\n\n\t\t\t\t\t\t\t\t\tif(last_x != \"default\" && last_x != x)\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t//i use \"default\" initially so i can tell if the object\n\t\t\t\t\t\t\t\t\t\t//ever moved at all, if never used i set it in the else\n\n\t\t\t\t\t\t\t\t\t\tif(x < last_x)\n\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t//then its going right\n\t\t\t\t\t\t\t\t\t\t\t//this if helps me determine which way the mouse is moving\n\n\t\t\t\t\t\t\t\t\t\t\t//console.log(\"x is less\");\n\t\t\t\t\t\t\t\t\t\t\t//calculate how far away the new mouse position is from the\n\t\t\t\t\t\t\t\t\t\t\t//last mouse position\n\t\t\t\t\t\t\t\t\t\t\t//var new_x = last_x - x;\n\t\t\t\t\t\t\t\t\t\t\t//console.log(\"new_x = \",new_x);\n\t\t\t\t\t\t\t\t\t\t\t//var cur_val_x = parseInt(sli_ctrl_inputA.value);\n\t\t\t\t\t\t\t\t\t\t\t//sli_ctrl_inputA.value = cur_val_x - new_x //pos_x;//cur_val_x - 50;\n\n\t\t\t\t\t\t\t\t\t\t\t//what i need is to calculate how far img is from the\n\t\t\t\t\t\t\t\t\t\t\t//point of origin basically the img_last_x then i need to\n\t\t\t\t\t\t\t\t\t\t\t//calculate how far the mouse is from that position and\n\t\t\t\t\t\t\t\t\t\t\t//use it as an offset.\n\n\n\t\t\t\t\t\t\t\t\t\t\tvar cur_val_x = parseInt(sli_ctrl_inputA.value);\n\t\t\t\t\t\t\t\t\t\t\tvar new_x = pos_x + offset_x;\n\t\t\t\t\t\t\t\t\t\t\tconsole.log(\"new_x = \",new_x);\n console.log(\"styleA = \",styleA);\n\t\t\t\t\t\t\t\t\t\t\t//sli_ctrl_inputA.value = new_x;\n\n\n\n\t\t\t\t\t\t\t\t\t\t}else\n\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t//if it uses this section then its going left\n\t\t\t\t\t\t\t\t\t\t\t//console.log(\"x is more\");\n\t\t\t\t\t\t\t\t\t\t\t//var new_x = x - last_x;\n\t\t\t\t\t\t\t\t\t\t\t//console.log(\"new_x = \",new_x);\n\t\t\t\t\t\t\t\t\t\t\t//var cur_val_x = parseInt(sli_ctrl_inputA.value);\n\t\t\t\t\t\t\t\t\t\t\t//sli_ctrl_inputA.value = cur_val_x + new_x//pos_x//cur_val_x + 50;\n\n\t\t\t\t\t\t\t\t\t\t\tvar cur_val_x = parseInt(sli_ctrl_inputA.value);\n\t\t\t\t\t\t\t\t\t\t\tvar new_x = pos_x + offset_x;\n\t\t\t\t\t\t\t\t\t\t\tconsole.log(\"new_x = \",new_x);\n console.log(\"styleA = \",styleA);\n\t\t\t\t\t\t\t\t\t\t\t//sli_ctrl_inputA.value = new_x;\n\n\t\t\t\t\t\t\t\t\t\t}//end else x\n\t\t\t\t\t\t\t\t\t\t//console.log(\"new x val= \",sli_ctrl_inputA.value);\n\t\t\t\t\t\t\t\t\t\tif(nbr == 0)\n\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\tsli_ctrl_inputA.value = new_x;\n\t\t\t\t\t\t\t\t\t\t\timage_update({\"ltr\":\"A\", \"nbr\":nbr, \"style\":styleA, \"mode\":\"motion\", \"slide_el\":sli_ctrl_inputA, \"box_el\":sli_ctrl_boxA});//\n\t\t\t\t\t\t\t\t\t\t}else\n\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\tsrc_x = new_x * -1;\n\t\t\t\t\t\t\t\t\t\t\tdraw_me();\n\t\t\t\t\t\t\t\t\t\t}//end else\n\n\n\t\t\t\t\t\t\t\t\t}//end if last_x\n\n\t\t\t\t\t\t\t\t\tif(last_y != \"default\")\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t//what is important here is whether im above\n\t\t\t\t\t\t\t\t\t\t//or below the origin\n\n\t\t\t\t\t\t\t\t\t\tif(y < last_y && last_y != y)\n\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t//then its going up\n\t\t\t\t\t\t\t\t\t\t\t//console.log(\"y is less\");\n\t\t\t\t\t\t\t\t\t\t\t//var new_y = last_y - y;\n\t\t\t\t\t\t\t\t\t\t\t//console.log(\"new_y = \",new_y);\n\t\t\t\t\t\t\t\t\t\t\t//var cur_val_y = parseInt(sli_ctrl_inputB.value);\n\t\t\t\t\t\t\t\t\t\t\t//sli_ctrl_inputB.value = cur_val_y - new_y//pos_y//poscur_val_y - 50;\n\n\t\t\t\t\t\t\t\t\t\t\t//then its going up\n\t\t\t\t\t\t\t\t\t\t\tvar new_y = pos_y + offset_y;\n\n\t\t\t\t\t\t\t\t\t\t\t//console.log(\"mm pos_y = \",pos_y);\n\t\t\t\t\t\t\t\t\t\t\t//console.log(\"mm new_y = \",new_y);\n\t\t\t\t\t\t\t\t\t\t\t//console.log(\"mm offset_y = \",offset_y);\n\n\t\t\t\t\t\t\t\t\t\t\t//sli_ctrl_inputB.value = new_y;\n\n\t\t\t\t\t\t\t\t\t\t}else\n\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t//console.log(\"y is more\");\n\t\t\t\t\t\t\t\t\t\t\t//var new_y = y - last_y;\n\t\t\t\t\t\t\t\t\t\t\t//console.log(\"new_y = \",new_y);\n\t\t\t\t\t\t\t\t\t\t\t//var cur_val_y = parseInt(sli_ctrl_inputB.value);\n\t\t\t\t\t\t\t\t\t\t\t//sli_ctrl_inputB.value = cur_val_y + new_y//pos_y//cur_val_y + 50;\n\t\t\t\t\t\t\t\t\t\t\t//then its going up\n\t\t\t\t\t\t\t\t\t\t\t//console.log(\"y is less\");\n\n\t\t\t\t\t\t\t\t\t\t\t//var cur_val_y = parseInt(sli_ctrl_inputB.value);\n\t\t\t\t\t\t\t\t\t\t\t//var new_y = pos_y - cur_val_y;\n\t\t\t\t\t\t\t\t\t\t\tvar new_y = pos_y + offset_y;\n\n\t\t\t\t\t\t\t\t\t\t\t//console.log(\"mm pos_y = \",pos_y);\n\t\t\t\t\t\t\t\t\t\t\t//console.log(\"mm new_y = \",new_y);\n\t\t\t\t\t\t\t\t\t\t\t//console.log(\"mm offset_y = \",offset_y);\n\n\t\t\t\t\t\t\t\t\t\t\t//sli_ctrl_inputB.value = new_y;\n\n\t\t\t\t\t\t\t\t\t\t}//end else x\n\n\n\n\t\t\t\t\t\t\t\t\t\t//console.log(\"new input value = \",sli_ctrl_inputB.value);\n\t\t\t\t\t\t\t\t\t\tif(nbr == 0)\n\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\tsli_ctrl_inputB.value = new_y * -1;\n\t\t\t\t\t\t\t\t\t\t\timage_update({\"ltr\":\"B\", \"nbr\":nbr, \"style\":styleB, \"mode\":\"motion\", \"slide_el\":sli_ctrl_inputB, \"box_el\":sli_ctrl_boxB});\n\t\t\t\t\t\t\t\t\t\t}else\n\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t//using this without modification creates\n\t\t\t\t\t\t\t\t\t\t\t//and opposite effect during moving.\n\t\t\t\t\t\t\t\t\t\t\t//src_y = new_y;\n\n\t\t\t\t\t\t\t\t\t\t\t//modify with new_y * -1\n\t\t\t\t\t\t\t\t\t\t\tsrc_y = new_y * -1;\n\n\t\t\t\t\t\t\t\t\t\t\tdraw_me();\n\t\t\t\t\t\t\t\t\t\t}//end else\n\t\t\t\t\t\t\t\t\t}\n\n\n\t\t\t\t\t\t\t\t\t// i use this the clear the default word and to set the\n\t\t\t\t\t\t\t\t\t//last move for each subsequent mousemove after it runs the\n\t\t\t\t\t\t\t\t\t//above processes\n\t\t\t\t\t\t\t\t\tlast_x = x;\n\t\t\t\t\t\t\t\t\tlast_y = y;\n\t\t\t\t\t\t\t\t\t//console.log(\"mouse-x = \",x);\n\t\t\t\t\t\t\t\t\t//console.log(\"last_x = \",last_x);\n\t\t\t\t\t\t\t\t\t//console.log(\"pos_x = \",pos_x);\n\t\t\t\t\t\t\t\t\t//console.log(\"pos_y = \",pos_y);\n\n\t\t\t\t\t\t\t\t}else\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t//clear the tracker\n\t\t\t\t\t\t\t\t\t//last_x = \"\";\n\t\t\t\t\t\t\t\t\t//last_y = \"\";\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t//end if\n\n }//end move my image\n\n\n }//end add_slider_input\n\n\n function getTouchPos(e) {\n var rect = canvas.getBoundingClientRect();\n //alert(\"touch x = \" + e.touches[0].clientX);\n return {\n x: e.touches[0].clientX - rect.left,\n y: e.touches[0].clientY - rect.top\n };\n }\n\n\n var getMousePos = function(e) {\n\n\t\t\t//this section returns the mouse position minus the\n\t\t\t//canvas' top or left window position. \"rect\"\n\n\t\t\tvar canvas_el = document.getElementById(\"tutorial\");\n\t\t\tvar rect = canvas.getBoundingClientRect();\n\n\t\t\t//console.log(\"rect.left\" + rect.left);\n\n\t\t\treturn {\n\t\t\t\tx: (e.clientX - rect.left) ,\n\t\t\t\ty: (e.clientY - rect.top)\n\t\t\t};\n\n\t\t}//- canvas_size/2 - canvas_size/2\n\n\t\tvar canvas_mouse_events = function(aVar,cId)\n\t\t{\n\n\t\t\t//this function adds and removes events that affects the canvas\n\t\t\t//once you are outside of the canvas and you let the mouse up\n\t\t\t//this is designed to clear these mouse events from the memory so\n\t\t\t//no event occurs again until you are \"mouseover\"'d the canvans where\n\t\t\t//which will set up these events again.\n\t\t\tvar action = aVar || \"remove\";\n\t\t\tvar canvas_id = cId;\n\t\t\tvar canvas_el = document.getElementById(cId);\n\n\t\t\tif(action == \"set\"){\n\n\t\t\t\t\t\tcanvas.onmousedown = function(e){\n\t\t\t\t\t\t\tmousedown = true;\n e.preventDefault();\n\t\t\t\t\t\t\tvar d = new Date();\n\t\t\t\t\t\t\t//console.log(\"onmousedown mousedown = \",mousedown);\n\t\t\t\t\t\t\t//console.log(\"time = \",d.toLocaleString());\n\t\t\t\t\t\t\tvar pos = getMousePos(e)\n\t\t\t\t\t\t\tvar pos_x = pos.x;\n\t\t\t\t\t\t\tvar pos_y = pos.y;\n\t\t\t\t\t\t\t//x is dealing with different values so\n\t\t\t\t\t\t\t//the math is addition not subtraction\n\n\t\t\t\t\t\t\t//this offset number has to be\n\t\t\t\t\t\t\t//permanent not recalculating so it\n\t\t\t\t\t\t\t//doesn't migrate to another position\n\n\t\t\t\t\t\t\t//pos_x - src_x; & pos_y - src_y; produced errant results\n\t\t\t\t\t\t\t//pos_x/y is always negative - you cant click on other\n\t\t\t\t\t\t\t//side of origin - so to properly calculate the offset\n\t\t\t\t\t\t\t//change mouse position read out from the positive int\n\t\t\t\t\t\t\t//representing the amount of canvas points from the\n\t\t\t\t\t\t\t//origin to a more accurate negative number representing\n\t\t\t\t\t\t\t//the actual canvas position\n\t\t\t\t\t\t\tvar act_x = (pos_x * -1);\n\t\t\t\t\t\t\tvar act_y = (pos_y * -1);\n\n\t\t\t\t\t\t\toffset_x = act_x - src_x;\n\n\t\t\t\t\t\t\toffset_y = act_y - src_y;\n\n\t\t\t\t\t\t\tcanvas_mouse_events(\"set\");\n\t\t\t\t\t\t}//end onmousedown\n\n\n window.onmouseup = function()\n {\n mousedown = false;\n\n }//end onmousedown\n\n window.ontouchend = function()\n {\n touchdown = false;\n\n }//end ontouchend\n\n\n\t\t\t}else\n {\n\t\t\t\t\t\tmousedown = false;\n\t\t\t\t\t\tcanvas.onmousedown = \"\";\n\t\t\t\t\t\tcanvas.onmousemove = \"\";\n\n touchdown = false;//\n canvas.ontouchstart = \"\";\n canvas.ontouchmove = \"\";\n\n\t\t\t}//end else\n\t\t}//end canvas_mouse_events\n\n var get_touch_offset = function(e)\n {\n var d = new Date();\n\t\t\t\t\t\t\t//console.log(\"onmousedown mousedown = \",mousedown);\n\t\t\t\t\t\t\t//console.log(\"time = \",d.toLocaleString());\n\t\t\t\t\t\t\tvar pos = getTouchPos(e);\n\t\t\t\t\t\t\tvar pos_x = pos.x;\n\t\t\t\t\t\t\tvar pos_y = pos.y;\n\n\t\t\t\t\t\t\tvar act_x = (pos_x * -1);\n\t\t\t\t\t\t\tvar act_y = (pos_y * -1);\n\n\t\t\t\t\t\t\toffset_x = act_x - src_x;\n\n\t\t\t\t\t\t\toffset_y = act_y - src_y;\n //alert(\" offset_x & y = \" + offset_x + \"\\n \" + offset_y);\n\n }//end get touch offset\n\n var image_update = function(mObj){\n\t\t\t//console.info(\"image update running\");\n\n\t\t\tvar style = mObj.style;\n\t\t\tvar ltr = mObj.ltr;\n\n\t\t\tvar nbr = mObj.nbr;\n\t\t\tvar mode = mObj.mode;//\"motion\" or not (\"input\" as other)\n\n\t\t\tvar slide_el = mObj.slide_el;\n\t\t\tvar box_el = mObj.box_el;\n\n\t\t\tvar target_el = (mode == \"motion\") ? slide_el : box_el;\n\n\t\t\tif(mode == \"motion\")\n\t\t\t{\n\t\t\t\t//make regular and goofy foot (opposite) values\n\t\t\t\tvar val_regular_input = target_el.value;\n\t\t\t\tvar val_goof_input = target_el.value * -1;\n\t\t\t\tvar input_val = (style == \"goofy\") ? val_goof_input : val_regular_input;\n\t\t\t\tbox_el.value = input_val;//unique to motion\n\t\t\t}else\n\t\t\t{\n\t\t\t\tif(ltr = \"A\"){\n\t\t\t\t\tsli_ctrl_inputA.value = box_el.value;\n\t\t\t\t}else{\n\t\t\t\t\tsli_ctrl_inputB.value = box_el.value;\n\t\t\t\t}\n\n\t\t\t\tvar input_val = box_el.value;\n\t\t\t\t//slide_data(\"B\",nbr,{\"value\" : \tsli_ctrl_boxB.value, \"val_oper\": \"add\"});\n\t\t\t\t//src_y = sli_ctrl_inputB.value;\n\n\t\t\t}\n\n\t\t\tslide_data(ltr,nbr,{\"value\" :\tinput_val, \"val_oper\": \"add\"});\n\n\n\t\t\tif(mode == \"input\"){\n\t\t\t\tif(ltr == \"A\")\n\t\t\t\t{\n\t\t\t\t\t//make these \"object properties\"\n\t\t\t\t\tsliderA.setValue();//unique to input\n\t\t\t\t}else\n\t\t\t\t{\n\t\t\t\t\tsliderB.setValue();//unique to input\n\t\t\t\t}\n\t\t\t}//end if mode == input\n\n\t\t\tdraw_me();\n\n\t\t}//end image_update\n\n var slide_data = function(ltr,nbr,obj)\n {\n //span_set2 view_span span3 view_span3\n var slide_ltr = ltr;\n var nbr = nbr;\n var val = (obj != undefined && obj.value != undefined) ? obj.value : \"\";\n var val_oper = (obj != undefined && obj.val_oper != undefined) ? obj.val_oper : \"get_value\";\n\n var slide_id = ltr+nbr;\n var span_id_str = \"span\" + slide_id;\n var targetSpan = document.getElementById(span_id_str);\n\n if(val != \"\" && val_oper == \"add\" || val_oper == \"both\"){\n //A covers x and width\n //B covers y and height\n switch(slide_id)\n {\n case \"A0\":\n src_x = val;\n //targetSpan.innerText = val;\n break;\n case \"B0\":\n src_y = val;\n //targetSpan.innerText = val;\n break;\n\n case \"A1\":\n img_w = val;\n //targetSpan.innerText = val;\n break;\n case \"B1\":\n img_h = val;\n //targetSpan.innerText = val;\n break;\n\n case \"A2\":\n can_x = val;\n //targetSpan.innerText = val;\n break;\n case \"B2\":\n can_y = val;\n //targetSpan.innerText = val;\n break;\n\n case \"A3\":\n can_w = val;\n //targetSpan.innerText = val;\n break;\n case \"B3\":\n can_h = val;\n //targetSpan.innerText = val;\n break;\n }//end switch\n }//end if\n\n if(val_oper == \"get_value\" || val_oper == \"both\"){\n switch(slide_id)\n {\n case \"A0\":\n return src_x;\n break;\n case \"B0\":\n return src_y;\n break;\n case \"A1\":\n return img_w;\n break;\n case \"B1\":\n return img_h;\n break;\n case \"A2\":\n return can_x;\n break;\n case \"B2\":\n return can_y;\n break;\n\n case \"A3\":\n return can_w;\n break;\n case \"B3\":\n return can_h;\n break;\n }//end switch\n }//end if\n\n }//end slide_dataA\n\n\n /*\n\n //this.draw_me = function(){ draw_me(); };\n */\n\n\n }", "function drawCanvas() {\r\n // Clear everything\r\n context1.clearRect(0, 0, canvas1.width, canvas1.height); // Clear canvas\r\n\r\n // Background grids\r\n drawGrid(context1,canvas1.width, canvas1.height); // Draw background grid\r\n\r\n // Curve through points and vertices\r\n drawCurve(context1, styleUniformParametrization, computeUniformInterpolation(numberOfPoints, points)); // Draw uniform parametrization\r\n drawCurve(context1, styleNonUniformParametrization, computeNonUniformInterpolation(numberOfPoints, points)); // Draw non-uniform parametrization\r\n\r\n drawVertices(context1, style, points); // Draw vertices as circles\r\n\r\n }", "function loadForegroundImage(){\n //get input from text input\n var fileinput = document.getElementById(\"foreinput\");\n fgcanvas = document.getElementById(\"canvf\");\n \n //create the selected image\n fgImage = new SimpleImage(fileinput);\n // show on the canvas\n fgImage.drawTo(fgcanvas);\n}", "draw()\n {\n let current, context\n const multiplier = Math.ceil(this.scale * this.resolution)\n for (let key in this.textures)\n {\n const texture = this.textures[key]\n if (texture.canvas !== current)\n {\n if (typeof current !== 'undefined')\n {\n context.restore()\n }\n current = texture.canvas\n context = this.canvases[current].getContext('2d')\n context.save()\n context.scale(multiplier, multiplier)\n }\n context.save()\n context.translate(Math.ceil(texture.x / multiplier), Math.ceil(texture.y / multiplier))\n if (this.testBoxes)\n {\n context.fillStyle = this.randomColor()\n context.fillRect(0, 0, Math.ceil(texture.width / multiplier), Math.ceil(texture.height / multiplier))\n }\n switch (texture.type)\n {\n case CANVAS:\n texture.draw(context, texture.param, this.canvases[current])\n break\n\n case IMAGE: case DATA:\n context.drawImage(texture.image, 0, 0)\n break\n }\n if (this.extrude)\n {\n this.extrudeEntry(texture, context, current)\n }\n context.restore()\n }\n context.restore()\n }", "function cutObj(x1,y1,x2,y2){\n currentFrameCanvas();\n let ctx = canvas.getContext('2d');\n ctx.strokeStyle=\"#0000ff\";\n ctx.lineWidth = 3;\n ctx.rect(x1,y1,x2-x1,y2-y1);\n ctx.stroke();\n let cut = document.getElementById(\"canvasCut\");\n cut.width = Math.abs(x2-x1);\n cut.height = Math.abs(y2-y1);\n cut.getContext('2d').drawImage(canvas,x1,y1,x2-x1,y2-y1,0,0,Math.abs(x2-x1),Math.abs(y2-y1));\n imgUrl = cut.toDataURL('image/png');\n}", "function add() {\r\n\t\t//upload car, and background images on the canvas.\r\n\r\n\t\tbackground_img = new Image()\r\n\t\tbackground_img.onload = uploadBackground;\r\n\t\tbackground_img.src = background_image\r\n\t\trover_img = new Image()\r\n\t\trover_img.onload = uploadrover;\r\n\t\trover_img.src = rover_image;\r\n\t\t\r\n}", "function main()\n{\n\t//Function to execute when a canvas is created:\n\tvar canvasLoaded = 0;\n\tvar onLoadCanvas = function()\n\t{\n\t\tif (CB_REM.DEBUG_MESSAGES) { CB_console(\"Canvas '\" + this.getId() + \"' loaded! Mode used: \" + this.getMode()); }\n\n\t\tcanvasLoaded++;\n\n\t\t//Gets the \"context\" object to start working with the canvas:\n\t\tvar canvasContext = this.getContext();\n\t\tif (!canvasContext) { CB_console(\"ERROR: canvas context could not be obtained! Drawing cannot be performed.\"); return; }\n\n\t\t//Stores the canvas in the 'canvases' object:\n\t\tcanvases[this.getId()] = this;\n\n\t\t//If both canvas (normal and buffer) have been created, proceeds with the rendering:\n\t\tif (canvasLoaded >= 2)\n\t\t{\n\t\t\t//When the screen changes its size or its orientation, both canvases will be re-adapted:\n\t\t\tvar onResizeOrChangeOrientationTimeout = null;\n\t\t\tvar onResizeOrChangeOrientation = function()\n\t\t\t{\n\t\t\t\tclearTimeout(onResizeOrChangeOrientationTimeout);\n\t\t\t\tonResizeOrChangeOrientationTimeout = setTimeout //NOTE: needs a delay as some clients on iOS update the screen size information in two or more steps (last step is the correct value).\n\t\t\t\t(\n\t\t\t\t\tfunction()\n\t\t\t\t\t{\n\t\t\t\t\t\t//Resizes the canvas:\n\t\t\t\t\t\tcanvases[\"my_canvas\"].setWidth(CB_Screen.getWindowWidth());\n\t\t\t\t\t\tcanvases[\"my_canvas\"].setHeight(CB_Screen.getWindowHeight());\n\t\t\t\t\t\tcanvases[\"my_canvas\"].clear(); canvases[\"my_canvas\"].disableAntiAliasing();\n\t\t\t\t\t\t\n\t\t\t\t\t\t//Resizes the buffer canvas:\n\t\t\t\t\t\tcanvases[\"my_canvas_buffer\"].setWidth(CB_Screen.getWindowWidth());\n\t\t\t\t\t\tcanvases[\"my_canvas_buffer\"].setHeight(CB_Screen.getWindowHeight());\n\t\t\t\t\t\tcanvases[\"my_canvas_buffer\"].clear();\n\t\t\t\t\t\tcanvases[\"my_canvas_buffer\"].disableAntiAliasing();\n\t\t\t\t\t}\n\t\t\t\t);\n\t\t\t};\n\t\t\tCB_Screen.onResize(onResizeOrChangeOrientation);\n\n\t\t\t//Clears both canvas:\n\t\t\tcanvases[\"my_canvas\"].clear();\n\t\t\tcanvases[\"my_canvas_buffer\"].clear();\n\t\t\t\n\t\t\t//Disables anti-aliasing to avoid problems with adjacent sprites:\n\t\t\tcanvases[\"my_canvas\"].disableAntiAliasing();\n\t\t\tcanvases[\"my_canvas_buffer\"].disableAntiAliasing();\n\t\t\t\n\t\t\t//Creates the sprites groups:\n\t\t\tvar graphicSpritesSceneObject = createSpritesGroups();\n\n\t\t\t//Caches all needed images (performance purposes) and starts rendering sprites groups when all are loaded:\n\t\t\tmyREM = new CB_REM();\n\t\t\tmyREM.cacheImages\n\t\t\t(\n\t\t\t\tgraphicSpritesSceneObject, //CB_GraphicSpritesSceneObject.\n\t\t\t\tundefined, //reload.\n\t\t\t\tfunction(imagesLoaded) //onLoad.\n\t\t\t\t{\n\t\t\t\t\t//Sets the current time as the start time to start counting the FPS (erased each second automatically):\n\t\t\t\t\tmyREM._startTimeFPS = CB_Device.getTiming();\n\n\t\t\t\t\t//Show the FPS (Frames Per Second) every time there is a new value:\n\t\t\t\t\tmyREM.onUpdatedFPS(function(FPS) { graphicSpritesSceneObject.getById(\"fps_group\").getById(\"fps\").src = \"FPS: \" + FPS; });\n\t\t\t\t\t\n\t\t\t\t\t//Processes the sprites groups:\n\t\t\t\t\tif (CB_REM.DEBUG_MESSAGES) { CB_console(\"Starts processing graphic sprites scene ('CB_GraphicSpritesScene' object) constantly...\"); }\n\t\t\t\t\t\n\t\t\t\t\tprocessSpritesGroups(graphicSpritesSceneObject, canvases[\"my_canvas\"], canvases[\"my_canvas\"].getContext(), canvases[\"my_canvas_buffer\"], canvases[\"my_canvas_buffer\"].getContext());\n\t\t\t\t}\n\t\t\t);\n\t\t}\n\t};\n\t\n\t//Creates the canvases:\n\tvar canvases = {};\n\tcanvases[\"my_canvas\"] = new CB_Canvas\n\t(\n\t\t\"my_canvas\", //canvasId. Unique required parameter.\n\t\t\"2d\", //contextType. NOTE: some emulation methods only support \"2d\". Default: \"2d\".\n\t\tCB_Screen.getWindowWidth(), //canvasWidth. Use 'CB_Screen.getWindowWidth()' for complete width. Default: CB_Canvas.WIDTH_DEFAULT.\n\t\tCB_Screen.getWindowHeight(), //canvasHeight. Use 'CB_Screen.getWindowHeight()' for complete height. Default: CB_Canvas.HEIGHT_DEFAULT.\n\t\tonLoadCanvas, //onLoad.\n\t\tfunction(error) { CB_console(\"Canvas object problem! Error: \" + error); }, //onError.\n\t\tundefined, undefined, !!FORCED_EMULATION_METHOD, !!FORCED_EMULATION_METHOD //Forces emulation method.\n\t);\n\tcanvases[\"my_canvas_buffer\"] = new CB_Canvas\n\t(\n\t\t\"my_canvas_buffer\", //canvasId. Unique required parameter.\n\t\t\"2d\", //contextType. NOTE: some emulation methods only support \"2d\". Default: \"2d\".\n\t\tCB_Screen.getWindowWidth(), //canvasWidth. Use 'CB_Screen.getWindowWidth()' for complete width. Default: CB_Canvas.WIDTH_DEFAULT.\n\t\tCB_Screen.getWindowHeight(), //canvasHeight. Use 'CB_Screen.getWindowHeight()' for complete height. Default: CB_Canvas.HEIGHT_DEFAULT.\n\t\tonLoadCanvas, //onLoad.\n\t\tfunction(error) { CB_console(\"Canvas object problem! Error: \" + error); }, //onError.\n\t\tundefined, undefined, !!FORCED_EMULATION_METHOD, !!FORCED_EMULATION_METHOD //Forces emulation method.\n\t);\n}", "async function drawOnCanvas(image, ctx, canvasWidth, canvasHeight, prevX, prevY, currX, currY, color, thickness, dashed=false) {\n\n //get the ration between the current canvas and the one it has been used to draw on the other computer\n let ratioX= cvx.width/canvasWidth;\n let ratioY= cvx.height/canvasHeight;\n\n // update the value of the points to draw\n prevX*=ratioX;\n prevY*=ratioY;\n currX*=ratioX;\n currY*=ratioY;\n if (dashed) {\n ctx.setLineDash([10,5]);\n }\n //draws path\n ctx.beginPath();\n ctx.moveTo(prevX, prevY);\n ctx.lineTo(currX, currY);\n ctx.strokeStyle = color;\n ctx.lineWidth = thickness;\n ctx.stroke();\n ctx.closePath();\n\n //Stores annotation data in idb\n let data = [canvasWidth, canvasHeight, prevX, prevY, currX, currY, color, thickness];\n await storeOther('annotations', data, image, roomNo);\n}", "function drawPicture (drawContext, drawRefCon, renderAttrs) { \n var ctx = drawContext.context,\n t = renderAttrs.transform,\n width = drawRefCon.imageSpec ? drawRefCon.imageSpec.width : 200,\n height = drawRefCon.imageSpec ? drawRefCon.imageSpec.height : 100,\n clip = renderAttrs.clipPolygon, i;\n\n if( !renderAttrs.renderable) {\n return;\n }\n\n ctx.save();\n ctx.globalAlpha *= renderAttrs.opacity;\n\n if( clip && clip.length > 0) {\n ctx.beginPath();\n ctx.moveTo(clip[0].getX(), clip[0].getY());\n for(i = 1; i < clip.length; i++) {\n ctx.lineTo(clip[i].getX(), clip[i].getY());\n }\n ctx.closePath();\n ctx.clip();\n }\n\n\n ctx.transform(t.m00, t.m01, t.m10, t.m11, t.m20, t.m21);\n if( drawRefCon.state === 'ready') {\n //GSP.log('image ready. id:' + drawRefCon.id);\n ctx.drawImage(drawRefCon.img, 0, 0);\n } else if (drawRefCon.state === 'loading') {\n //GSP.log('image not ready. id:' + drawRefCon.id);\n ctx.strokeStyle = 'black';\n ctx.strokeRect(0, 0, width, height);\n } else {\n ctx.strokeStyle = 'red';\n ctx.strokeRect(0, 0, width, height);\n ctx.beginPath();\n ctx.moveTo(0,0);\n ctx.lineTo(width, height);\n ctx.moveTo(width, 0);\n ctx.lineTo(0, height);\n ctx.closePath();\n ctx.stroke();\n }\n\n ctx.restore();\n }", "function putimage(canvas,blob){\n var img = new Image();\n var ctx = canvas.getContext('2d');\n img.onload = function () {\n ctx.drawImage(img,0,0,canvasW, canvasH);\n }\n img.src = blob;\n \n }", "function preview(img, selection) { \n var scaleX = settings.cropwidth / (selection.width || 1); \n var scaleY = settings.cropheight / (selection.height || 1);\n\n canvas = document.getElementById(settings.canvasid);\n canvas.width = settings.cropwidth;\n canvas.height = settings.cropheight;\n context = canvas.getContext('2d');\n \n var imageObj = new Image();\n\n imageObj.onload = function() { \n // draw cropped image\n var sourceX = selection.x1;\n var sourceY = selection.y1;\n var sourceWidth = selection.width || 1;\n var sourceHeight = selection.height || 1;\n var destWidth = settings.cropwidth; \n var destHeight = settings.cropheight;\n var destX = 0;\n var destY = 0;\n\n context.drawImage(imageObj, sourceX, sourceY, sourceWidth, sourceHeight, destX, destY, destWidth, destHeight); \n };\n \n imageObj.src = img.src;\n\n }", "function Baseline(lines) {\n this.lines = lines;\n this.visible = false;\n this.clickMargin = 0.4; //in percent of the image height\n}", "_drawImage() {\n if (!(this._width > 0 && this._height > 0 && !!this._image)) {\n return\n }\n\n let b = this._getBounds()\n\n this._context.drawImage(\n this._image,\n b.sx,\n b.sy,\n b.sw,\n b.sh,\n b.dx,\n b.dy,\n b.dw,\n b.dh,\n )\n\n this._averageColor = this._calculateAverageColor(this.getImageData())\n }", "draw(context)\n\t{\n\t\tif ( !this.visible )\n\t\t\treturn;\n\t\t\n\t\tcontext.setTransform(1,0, 0,1, this.position.x, this.position.y);\n\n\t\t// image, 4 source parameters, 4 destination parameters\n context.drawImage(this.texture.image, \n this.texture.region.position.x, this.texture.region.position.y, \n this.texture.region.width, this.texture.region.height,\n -this.rectangle.width/2, -this.rectangle.height/2, \n this.rectangle.width, this.rectangle.height);\n\t}", "function drawRoberta(){\n\t\n\tcanvas = document.getElementById(\"robertaCanvas\");\n\tctx = canvas.getContext(\"2d\");\n\t\n\timage = document.createElement(\"img\");\n\t\n\timage.onload = function() {\n\t ctx.drawImage(image,canvas.width/2-image.width/2,canvas.height/2-image.width/2);\n };\n\t\n image.src = '../css/img/simulator/dummy_up.png';\n}", "start() {\n console.log('starting');\n this.imageCanvas.addEventListener('mousemove', this.handleMouseMove);\n this.imageCanvas.addEventListener('onwheel', this.handleMouseMove);\n window.addEventListener('resize', this.resizeCanvases);\n //var currentDiv = document.getElementById('beforeThis');\n //var idekDiv = document.getElementById('idek');\n //idekDiv.insertBefore(this.imageCanvas, currentDiv);\n // document.body.appendChild(this.imageCanvas);\n if (this.imageCanvas) {\n this.resizeCanvases();\n this.tick();\n }\n }", "function canvasInit() {\n var _this = this;\n\n this.scope = new paper.PaperScope();\n this.scope.setup(\"canvas\"); // Create a new layer:\n\n var first_layer = new paper.Layer(); // Zero point text\n\n var text = new paper.PointText(new paper.Point(0, -5));\n text.fillColor = 'rgb(0, 0, 0)'; // text.fontSize = 20;\n\n text.content = \"[0,0]\";\n new paper.Layer();\n first_layer.bringToFront();\n /** Create tools **/\n\n this.scale_move_tool = Object(_scale_move_tool_canvas_events__WEBPACK_IMPORTED_MODULE_0__[\"createScaleMoveViewTool\"])(this);\n this.bbox_tool = Object(_bbox_tool__WEBPACK_IMPORTED_MODULE_1__[\"createBboxTool\"])(this);\n this.polygon_tool = Object(_polygon_tool__WEBPACK_IMPORTED_MODULE_2__[\"createPolygonTool\"])(this);\n this.baseline_tool = Object(_baseline_tool__WEBPACK_IMPORTED_MODULE_3__[\"createBaselineTool\"])(this);\n this.join_rows_tool = Object(_join_rows_tool__WEBPACK_IMPORTED_MODULE_4__[\"createJoinRowsTool\"])(this);\n /** Activate default tool and select other **/\n\n this.scale_move_tool.activate();\n this.selected_tool = this.bbox_tool;\n /** Register events **/\n\n $(document).keydown(function (event) {\n if (event.code === \"ControlLeft\") {\n _this.left_control_active = true; // View points of selected row\n\n if (_this.active_row && _this.canvasIsToolActive(_this.scale_move_tool)) {\n _this.active_row.view.baseline.baseline_path.selected = true;\n _this.active_row.view.baseline.baseline_left_path.selected = true;\n _this.active_row.view.baseline.baseline_right_path.selected = true;\n }\n\n event.preventDefault();\n } else if (event.code === \"AltLeft\") {\n _this.left_alt_active = true; // View points of selected region\n\n if (_this.active_region && _this.canvasIsToolActive(_this.scale_move_tool)) {\n _this.active_region.view.path.selected = true;\n }\n\n event.preventDefault();\n } else if (event.code === \"Enter\" || event.code === \"NumpadEnter\") {\n if (_this.active_row && _this.active_row.text.length) {\n _this.active_row.is_valid = true;\n\n _this.emitAnnotationEditedEvent(_this.active_row);\n }\n } else if (event.code === \"Backspace\") {// Remove last\n // this.active_row.text = this.active_row.text.slice(0, -1);\n } else if (event.code === \"Escape\") {// Remove annotation text\n // this.active_row.is_valid = false;\n // this.active_row.text = \"\";\n // this.emitAnnotationEditedEvent(this.active_row);\n } else if (event.code === \"Delete\") {\n if (_this.left_control_active) {\n // Remove last\n _this.canvasSelectTool(_this.scale_move_tool);\n\n _this.removeAnnotation(_this.last_active_annotation.uuid);\n }\n } else if (event.code === \"ArrowUp\") {\n if (_this.active_row) {\n var active_annotation_idx = _this.annotations.rows.findIndex(function (item) {\n return item.uuid === _this.active_row.uuid;\n });\n\n _this.last_active_annotation = _this.active_row = _this.annotations.rows[Math.max(0, active_annotation_idx - 1)];\n }\n } else if (event.code === \"ArrowDown\") {\n if (_this.active_row) {\n var _active_annotation_idx = _this.annotations.rows.findIndex(function (item) {\n return item.uuid === _this.active_row.uuid;\n });\n\n _this.last_active_annotation = _this.active_row = _this.annotations.rows[Math.min(_this.annotations.rows.length, _active_annotation_idx + 1)];\n }\n }\n });\n $(document).keyup(function (event) {\n if (event.code === \"ControlLeft\") {\n _this.left_control_active = false; // Hide points of selected row\n\n if (_this.active_row && _this.canvasIsToolActive(_this.scale_move_tool)) {\n _this.active_row.view.baseline.baseline_path.selected = false;\n _this.active_row.view.baseline.baseline_left_path.selected = false;\n _this.active_row.view.baseline.baseline_right_path.selected = false;\n }\n\n event.preventDefault();\n } else if (event.code === \"AltLeft\") {\n _this.left_alt_active = false; // Hide points of selected region\n\n if (_this.active_region && _this.canvasIsToolActive(_this.scale_move_tool)) {\n _this.active_region.view.path.selected = false;\n }\n\n event.preventDefault();\n } else if (event.code === \"Space\") {}\n });\n this.$on('imageSelectedEv', function (id) {\n _this.canvasSelectImage(id);\n });\n this.$on('annotationListEv_activeRegionChanged', function (region) {\n _this.active_region = region;\n });\n this.$on('annotationListEv_activeRowChanged', function (row) {\n _this.active_row = row;\n });\n this.$on('annotationListEv_activeRowTextChanged', function (row) {\n // Delegate to AnnotatorWrapperComponent\n _this.$emit('row-edited-event', _this.serializeAnnotation(row));\n });\n /** Animation handling **/\n\n this.scope.view.zoom_animation = {\n on: false,\n start_zoom: 0,\n end_zoom: 0,\n center: this.scope.view.center,\n total_time: 0,\n p: 1,\n time_passed: 0\n };\n\n this.scope.view.zoom_animation.reset = function (event) {\n if (self.scope.view.zoom_animation.on) {\n self.scope.view.zoom = self.scope.view.zoom_animation.end_zoom;\n self.scope.view.zoom_animation.on = false;\n }\n\n self.scope.view.zoom_animation.start_zoom = 0;\n self.scope.view.zoom_animation.end_zoom = 0;\n self.scope.view.zoom_animation.center = self.scope.view.center;\n self.scope.view.zoom_animation.total_time = 0;\n self.scope.view.zoom_animation.p = 1;\n self.scope.view.zoom_animation.time_passed = 0;\n };\n\n this.scope.view.translate_animation = {\n on: false,\n start_point: new paper.Point(0, 0),\n end_point: new paper.Point(0, 0),\n total_time: 0,\n p: 1,\n time_passed: 0\n };\n\n this.scope.view.translate_animation.reset = function (event) {\n if (self.scope.view.translate_animation.on) {\n self.scope.view.center = self.scope.view.translate_animation.end_point;\n self.scope.view.translate_animation.on = false;\n }\n\n self.scope.view.translate_animation.start_point = new paper.Point(0, 0);\n self.scope.view.translate_animation.end_point = new paper.Point(0, 0);\n self.scope.view.translate_animation.total_time = 0;\n self.scope.view.translate_animation.p = 1;\n self.scope.view.translate_animation.time_passed = 0;\n };\n\n var self = this;\n\n this.scope.view.onFrame = function (event) {\n if (self.scope.view.zoom_animation.on) {\n var start_zoom = self.scope.view.zoom_animation.start_zoom;\n var end_zoom = self.scope.view.zoom_animation.end_zoom;\n var center = self.scope.view.zoom_animation.center;\n var total_time = self.scope.view.zoom_animation.total_time;\n var p = self.scope.view.zoom_animation.p;\n var time_passed = self.scope.view.zoom_animation.time_passed;\n var previous_zoom = self.scope.view.zoom;\n\n if (time_passed < total_time) {\n var new_zoom = start_zoom + (end_zoom - start_zoom) * reverse_polynomial_trajectory(time_passed, total_time, p);\n\n if (new_zoom >= previous_zoom && new_zoom < end_zoom || new_zoom <= previous_zoom && new_zoom > end_zoom) {\n var scale_factor = new_zoom / previous_zoom; //self.scope.view.zoom = new_zoom;\n\n self.scope.view.scale(scale_factor, center);\n } else {\n var _scale_factor = end_zoom / previous_zoom; //self.scope.view.zoom = end_zoom;\n\n\n self.scope.view.scale(_scale_factor, center);\n }\n } else {\n var _scale_factor2 = end_zoom / previous_zoom; //self.scope.view.zoom = end_zoom;\n\n\n self.scope.view.scale(_scale_factor2, center);\n self.scope.view.zoom_animation.reset();\n }\n\n self.scope.view.zoom_animation.time_passed += event.delta;\n }\n\n if (self.scope.view.translate_animation.on) {\n var start_point = self.scope.view.translate_animation.start_point;\n var end_point = self.scope.view.translate_animation.end_point;\n var _total_time = self.scope.view.translate_animation.total_time;\n var _p = self.scope.view.translate_animation.p;\n var _time_passed = self.scope.view.translate_animation.time_passed;\n\n if (_time_passed < _total_time) {\n var actual_point = start_point.add(end_point.subtract(start_point).multiply(reverse_polynomial_trajectory(_time_passed, _total_time, _p)));\n self.scope.view.center = actual_point;\n } else {\n self.scope.view.center = end_point;\n self.scope.view.translate_animation.reset();\n }\n\n self.scope.view.translate_animation.time_passed += event.delta;\n }\n };\n\n this.scope.view.onResize = function (event) {\n console.log(event);\n };\n}", "draw() {\n this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);\n this.ctx.fillStyle = this.background.getColor();\n this.ctx.fillRect(0, 0, this.canvas.width, this.canvas.height);\n\n // draw the background image if any\n if ( (this.image) && (this.image.src != \"\") && (this.image.ready) && (this.image.complete) ) {\n if (this.bg_display === \"topleft\") {\n this.ctx.drawImage(this.image, 0, 0);\n }\n else if (this.bg_display === \"stretch\") {\n this.ctx.drawImage(this.image, 0, 0, this.w, this.h);\n }\n else if (this.bg_display === \"patch\") {\n this.ctx.fillStyle = ctx.createPattern(this.image, \"repeat\");\n this.ctx.fillRect(0, 0, this.canvas.width, this.canvas.height);\n }\n else if (this.bg_display === \"center\") {\n this.ctx.drawImage(this.image, (this.w-this.image.width)/2, (this.h-this.image.height)/2);\n }\n }\n\n // if not interact with the space\n if (!this.click) {\n // update the graphics to build its primitives\n for(var i=0, l=this.graphics.length; i<l; i++) {\n this.graphics[i].update();\n }\n \n this.primitives = [];\n // split the primitives if needed\n if (this.split) {\n for (var i=0, l=this.graphics.length; i<l; i++) {\n thisGraphics_i = this.graphics[i];\n\n for (var j=i+1; j<l; j++) {\n thisGraphicsNext = this.graphics[j];\n\n thisGraphics_i.splitFace(thisGraphicsNext);\n thisGraphicsNext.splitFace(thisGraphics_i);\n }\n\n this.primitives = this.primitives.concat( thisGraphics_i.primitives || [] );\n }\n }\n else {\n for (var i=0, l=this.graphics.length; i<l; i++) {\n thisGraphics_i = this.graphics[i];\n\n if (thisGraphics_i.split) {\n for (var j=i+1; j<l; j++) {\n thisGraphicsNext = this.graphics[j];\n\n if (thisGraphicsNext.split) {\n thisGraphics_i.splitFace(thisGraphicsNext);\n }\n }\n }\n\n this.primitives = this.primitives.concat( thisGraphics_i.primitives || [] );\n }\n }\n // end split\n }\n\n for(var i=0, l=this.primitives.length; i<l; i++) {\n this.primitives[i].computeDepth(this);\n }\n\n this.primitives = this.primitives.sort(function (a, b) { return b.depth - a.depth; });\n \n // draw the primitives\n if (this.render === \"painter\") {\n this.drawPainter(this.primitives);\n }\n else {\n for(var i=0, l=this.primitives.length; i<l; i++) {\n this.primitives[i].draw(this.ctx, this);\n }\n }\n\n // draw the graphic controls\n for (var i=0, l=this.graphicsCtr.length; i<l; i++) {\n this.graphicsCtr[i].draw();\n }\n }", "function drawBoard() {\n // load the image first\n $(\"canvas\").drawImage({\n source: \"board.jpg\",\n x: 10, y: 10,\n width: 360,\n height: 360,\n fromCenter: false,\n load: drawBoardLines //after image loads, this callback draws the lines on top\n });\n}", "function drawRect(canvas, sensor_data, num) {\n\tvar ctx = canvas.getContext(\"2d\");\n\tvar x = x0;\n\tvar y = y0 + num * 110;\n\tvar image_width = 24;\n\tvar image_height = 32;\n\tvar imageObj = new Image();\n\tvar image_x, image_y;\n\n\timage_x = x+2*width/3;\n\n\tctx.fillStyle = \"#77DAA2\";\n\tctx.shadowColor=\"gray\";\n\tctx.shadowBlur=4;\n\tctx.shadowOffsetX = 4;\n\tctx.shadowOffsetY = 4;\n\n\tctx.fillRect(x,y,width,height);\n\n\tctx.beginPath();\n\n\tctx.strokeStyle=\"#00FF00\";\n\tctx.arc(x + width/3,y + height/2,30,0,2*Math.PI);\n\tctx.lineWidth = 2;\n\tctx.stroke();\n\n//\tctx.strokeStyle=\"#FF0000\";\n//\tctx.arc(image_x,y + height/2,6,0,2*Math.PI);\n//\tctx.lineWidth = 2;\n//\tctx.stroke();\n\n\tctx.fillStyle = \"#000000\";\n\n\t// Sensor address\n\tctx.font = \"12px Arial\";\n\tctx.fillText(sensor_data['name'], x+2, y+10);\n\tctx.font = \"10px Arial\";\n\tctx.fillText(sensor_data['date'], x+width-86, y+height-4);\n\n\t// Sensor data\n\tctx.font = \"Bold 16px Arial\";\n\tctx.fillText(sensor_data['value'] + \"\\xB0\", x+width/3 - 20, y+height/2 + 5);\n\tctx.fillText(sensor_data[4], x+width/3 - 20, y+height/2 + 45);\n\n\tif (sensor_data[4] < -0.1) {\n\t\timageObj.src = 'img/redUpArrow.png';\n\t\timage_y = y + height/2 - image_height;\n\t} else {\n\t\timageObj.src = 'img/blueDownArrow.png';\n\t\timage_y = y + height/2;\n\t}\n\timageObj.onload = function() {\n\t\tctx.drawImage(imageObj, image_x, image_y, image_width, image_height);\n\t};\n\n//\tprint('<map name=sensor_data['address'] + \"_map\">');\n//\tprint(\"/map>\");\n//\ttempUp(ctx);\n}", "function draw_bounding_box(canvas_variables, vs) {\n const ctx = canvas_variables[1];\n ctx.fillStyle = 'red';\n ctx.beginPath();\n ctx.moveTo(vs[0].x, vs[0].y);\n ctx.lineTo(vs[1].x, vs[1].y);\n ctx.lineTo(vs[2].x, vs[2].y);\n ctx.lineTo(vs[3].x, vs[3].y);\n ctx.lineTo(vs[0].x, vs[0].y);\n ctx.fill();\n}", "function draw() {\n if (canvasValid == false) {\n clear(ctx);\n\n // Add stuff you want drawn in the background all the time here\n\n // draw all boxes\n var l = boxes.length;\n for (var i = 0; i < l; i++) {\n drawshape(ctx, boxes[i], boxes[i].fill);\n }\n\n // draw selection\n // right now this is just a stroke along the edge of the selected box\n if (mySel != null) {\n ctx.strokeStyle = mySelColor;\n ctx.lineWidth = mySelWidth;\n ctx.strokeRect(mySel.x,mySel.y,mySel.w,mySel.h);\n }\n\n // Add stuff you want drawn on top all the time here\n\n canvasValid = true;\n //if(mySel != null)\n // fall();\n timeStep();\n }\n}", "function setupCanvas() {\r\n var gameCanvas = \"gameCanvas\";\r\n var height = 500;\r\n var width = 800;\r\n var square = 100;\r\n \r\n backgroundImg = new imageLib(gameCanvas, width, height, 0, 0);\r\n \r\n /*Add background image to canvas*/\r\n backgroundImg.addImg(gameImage.loadedImg[\"background\"]);\r\n \r\n /*Setup interface screens*/\r\n setupInterfaces();\r\n \r\n /*Initiate grid*/\r\n //backgroundImg.canvasGrid(backgroundImg.canvas.width, backgroundImg.canvas.height);\r\n backgroundImg.canvasGrid(square); //Square size\r\n backgroundImg.gridSqHeight = square;\r\n backgroundImg.gridSqWidth = square;\r\n setupGridSpots();\r\n \r\n /*Set up the game ref*/\r\n backgroundImg.gameRef.turn = \"character\";\r\n backgroundImg.gameRef.preTurn = \"wolf\";\r\n \r\n backgroundImg.gameRef.players.push(\"character\");\r\n backgroundImg.gameRef.players.push(\"wolf\");\r\n \r\n backgroundImg.gameRef.actionList.push(\"charRoll\"); \r\n backgroundImg.gameRef.action = \"waitRoll\";\r\n \r\n /*Draw the character on the screen*/\r\n setupCharacter(gameCanvas);\r\n addEnemy(gameCanvas);\r\n \r\n /*Drawing out paths in the game*/\r\n //setupObstacles();\r\n \r\n /*Draw up the cards*/\r\n setupCard(gameCanvas);\r\n setupCardChoices();\r\n \r\n /*Draw up the dice images*/\r\n setupDiceImg(gameCanvas);\r\n \r\n /*Draw up trap images*/\r\n setupTrapImg(gameCanvas);\r\n}", "function drawImageOnCanvas(imageid){\n\t\t\t\tctx.clearRect(0, 0, canvas.width, canvas.height);\n\t\t\t\tdrawImageId=imageid;\n\t\t\t\tvar img = document.getElementById(drawImageId);\n\t\t\t\tctx.drawImage(img, 10, 10);\n\t}", "function uploadimage(){\nvar imgcanvas=document.getElementById(\"can\");\nvar fileInput=document.getElementById(\"input\");\norgimage=new SimpleImage(fileInput);\ngrayimage=new SimpleImage(fileInput);\nredimage=new SimpleImage(fileInput);\nrbimage=new SimpleImage(fileInput);\nblrimage=new SimpleImage(fileInput);\nfiltimage=new SimpleImage(fileInput);\noutputImg=new SimpleImage(fileInput);\norgimage.drawTo(imgcanvas);\n}", "function doCanvas(ctx, canvas) {\n /* draw something */\n ctx.fillStyle = '#f90';\n ctx.fillRect(0, 0, canvas.width, canvas.height);\n ctx.fillStyle = '#fff';\n ctx.font = '60px sans-serif';\n ctx.fillText('Code Project', 10, canvas.height / 2 - 15);\n ctx.font = '26px sans-serif';\n ctx.fillText('Click link below to save this as image', 15, canvas.height / 2 + 35);\n }", "draw() {\n // Displaying the image\n image(experimentImage, 0, 0, width, height);\n }", "draw_bounding_box(annotation_object, ctx, demo=false, offset=null, subtask=null) {\n const px_per_px = this.config[\"px_per_px\"];\n let diffX = 0;\n let diffY = 0;\n if (offset != null) {\n diffX = offset[\"diffX\"];\n diffY = offset[\"diffY\"];\n }\n\n let line_size = null;\n if (\"line_size\" in annotation_object) {\n line_size = annotation_object[\"line_size\"];\n }\n else {\n line_size = this.get_line_size(demo);\n }\n \n // Prep for bbox drawing\n let color = this.get_annotation_color(annotation_object[\"classification_payloads\"], false, subtask);\n ctx.fillStyle = color;\n ctx.strokeStyle = color;\n ctx.lineJoin = \"round\";\n ctx.lineWidth = line_size*px_per_px;\n ctx.imageSmoothingEnabled = false;\n ctx.globalCompositeOperation = \"source-over\";\n \n // Draw the box\n const sp = annotation_object[\"spatial_payload\"][0];\n const ep = annotation_object[\"spatial_payload\"][1];\n ctx.beginPath();\n ctx.moveTo((sp[0] + diffX)*px_per_px, (sp[1] + diffY)*px_per_px);\n ctx.lineTo((sp[0] + diffX)*px_per_px, (ep[1] + diffY)*px_per_px);\n ctx.lineTo((ep[0] + diffX)*px_per_px, (ep[1] + diffY)*px_per_px);\n ctx.lineTo((ep[0] + diffX)*px_per_px, (sp[1] + diffY)*px_per_px);\n ctx.lineTo((sp[0] + diffX)*px_per_px, (sp[1] + diffY)*px_per_px);\n ctx.closePath();\n ctx.stroke();\n }", "function mergeLayers() {\r\n var baseRect = base_canvas.getBoundingClientRect();\r\n var baseCtx = base_canvas.getContext(\"2d\");\r\n [...document.querySelectorAll(\"canvas\")].forEach(canvas => {\r\n var topRect = canvas.getBoundingClientRect();\r\n baseCtx.drawImage(\r\n canvas,\r\n topRect.left - baseRect.left,\r\n topRect.top - baseRect.top\r\n );\r\n });\r\n removeOverlayingEmojiCanvases();\r\n removeOverlayingCaptionCanvases();\r\n $(\".overlay-container\").remove();\r\n $(\"caption-overlay\").remove();\r\n clickX = new Array();\r\n clickY = new Array();\r\n clickDrag = new Array();\r\n clickColor = new Array();\r\n clickSize = new Array();\r\n eraseX = new Array();\r\n eraseY = new Array();\r\n eraseWidth = new Array();\r\n isDrawing = false;\r\n }", "function imageToCanvas(string, callback, blur, width, height){ \n\t\tdecodeImage(string, callback, width, height, tagCanvas);\n\t}", "draw(){\n\t\t\n\t\tlet height = this.height; //100\n\t\tlet width = this.width; //100\n\t\t\n\t\tlet ctx = this.ctx;\n\t\t//save last frame\n\t\tlet lastFrame = ctx.getImageData(0, 0, width, height);\n\t\t//clear canvas\n\t\tctx.clearRect(0, 0, width, height);\n\t\t//now, move frame 1 pixel to the left\n\t\tctx.putImageData(lastFrame, -1, 0);\n\t\t\n\t\t//then, draw the lines\n\t\tfor(var line of this.lines){\n\t\t\t\n\t\t\t\n\t\t\tlet range = line.maxValue - line.minValue;\n\t\t\tlet value = line.value;\n\t\t\t\n\t\t\t//Multiply line's value by the ratio between height and range, to get effective range the same but zero at the top\n\t\t\tvalue *= 1 * height / range;\n\t\t\t\n\t\t\t//Now, zero the value by adding the difference between minValue and 0\n\t\t\tvalue -= line.minValue * height / range;\n\t\t\t\n\t\t\t//Now, invert by subtracting from height\n\t\t\tvalue = height - value;\n\t\t\t\n\t\t\tctx.beginPath();\n\t\t\tctx.strokeStyle = line.color;\n\t\t\tctx.moveTo(width - 2, value);\n\t\t\tctx.lineTo(width, value);\n\t\t\tctx.stroke();\n\t\t}\n\t}", "function predictImage() {\r\n // console.log('processing')\r\n\r\n //step1: Load image\r\n let image = cv.imread(canvas);//to read image\r\n \r\n //Step 2: Covert img to black and white.\r\n cv.cvtColor(image, image, cv.COLOR_RGBA2GRAY, 0); //source and destination both are same img.\r\n cv.threshold(image,image,175,255,cv.THRESH_BINARY);//anything above 175 to white255.\r\n \r\n //step 3:find the contours(outline) to claculate bounding rectangle.\r\n let contours = new cv.MatVector();\r\n let hierarchy = new cv.Mat();\r\n cv.findContours(image, contours, hierarchy, cv.RETR_CCOMP, cv.CHAIN_APPROX_SIMPLE);\r\n \r\n //step 4: Calculating the bounding rectangle.\r\n let cnt = contours.get(0);\r\n let rect = cv.boundingRect(cnt);\r\n \r\n //step 5: Crop the image. Region of Interest.\r\n image = image.roi(rect);\r\n\r\n // step 6: Calculate new size\r\n var height = image.rows;\r\n var width = image.cols;\r\n if (height>width) {\r\n height = 20;\r\n const scaleFactor = image.rows/height;\r\n width = Math.round(image.cols/scaleFactor);\r\n\r\n } else {\r\n width = 20;\r\n const scaleFactor = image.cols/width;\r\n height = Math.round(image.rows/scaleFactor);\r\n \r\n }\r\n \r\n let newSize = new cv.Size(width,height);//dsize\r\n \r\n // step 7: Resize image\r\n cv.resize(image,image,newSize,0,0,cv.INTER_AREA);\r\n\r\n // Step 8: Add Padding\r\n\r\n const LEFT = Math.ceil(4 + (20-width)/2);\r\n const RIGHT = Math.floor(4 + (20-width)/2);\r\n const TOP =Math.ceil(4 + (20-height)/2);\r\n const BOTTOM =Math.floor(4 + (20-height)/2);\r\n // console.log(`top:${TOP}, bottom: ${BOTTOM}, left: ${LEFT}, right:${RIGHT}`);\r\n \r\n const BLACK = new cv.Scalar(0,0,0,0);//color rgb trasprncy.\r\n\r\n cv.copyMakeBorder(image, image, TOP, BOTTOM, LEFT, RIGHT,cv.BORDER_CONSTANT, BLACK); //adding padding\r\n\r\n //step 9: Find the centre of Mass\r\n cv.findContours(image, contours, hierarchy, cv.RETR_CCOMP, cv.CHAIN_APPROX_SIMPLE);\r\n cnt = contours.get(0);\r\n const Moments = cv.moments(cnt,false);//it'snot binary image so false.\r\n \r\n //weight moments.moo is total mass = area of drawn img. max =400=20*20;\r\n const cx = Moments.m10/Moments.m00;//centre 14px,14 because total 28px including padding.\r\n const cy = Moments.m01/Moments.m00;\r\n\r\n // console.log(`M00: ${Moments.m00}, cx: ${cx}, cy: ${cy}`);\r\n\r\n //step 10: Shift the image to the cenre of mass\r\n const X_SHIFT =Math.round(image.cols/2.0 - cx); //14 is the center\r\n const Y_SHIFT = Math.round(image.rows/2.0 - cy);\r\n\r\n newSize = new cv.Size(image.cols,image.rows); //dsize\r\n const M = cv.matFromArray(2, 3, cv.CV_64FC1, [1, 0, X_SHIFT, 0, 1, Y_SHIFT]);\r\n cv.warpAffine(image, image, M, newSize, cv.INTER_LINEAR, cv.BORDER_CONSTANT, BLACK);\r\n\r\n //step 11: Normalize the Pizel value\r\n \r\n let pixelValues = image.data; // the values are b/w 0-255, we will change to 0-1\r\n // console.log(`pixelValues: ${pixelValues}`);\r\n\r\n pixelValues = Float32Array.from(pixelValues);//converting to float\r\n \r\n //for dividing all elements in array\r\n pixelValues = pixelValues.map(function(item) {\r\n return item/255.0; \r\n });\r\n\r\n // console.log(`scaled array: ${pixelValues}`);\r\n \r\n //Step 12: Create a Tensor\r\n const X = tf.tensor([pixelValues]);//bracket for 2dimentions.1 pair aleready in the pixels.\r\n // console.log(`shape of tensor ${X.shape}`);\r\n // console.log(`dtype of tensor ${X.dtype}`);\r\n\r\n // Make prediction\r\n const result = model.predict(X);\r\n console.log(`The written values is: ${result}`);\r\n // console.log(tf.memory());\r\n \r\n // saving output predicted value from the Tensor\r\n const output = result.dataSync()[0];\r\n \r\n\r\n\r\n // //testing only\r\n // const outputCanvas = document.createElement('CANVAS');\r\n // cv.imshow(outputCanvas, image);//todisplay image\r\n // document.body.appendChild(outputCanvas);// adding canvas to body\r\n\r\n //Cleanup\r\n image.delete();\r\n contours.delete();\r\n cnt.delete();\r\n hierarchy.delete();\r\n M.delete();\r\n X.dispose();\r\n result.dispose();\r\n \r\n return output;\r\n}", "function draw() {\n if (canvasValid == false) {\n clear(ctx);\n \n // Add stuff you want drawn in the background all the time here\n \n // draw all boxes\n var l = boxes.length;\n for (var i = 0; i < l; i++) {\n drawshape(ctx, boxes[i], boxes[i].fill);\n }\n \n // draw selection\n // right now this is just a stroke along the edge of the selected box\n\n ctx.beginPath();\n ctx.moveTo( (boxes[0].x + (boxes[0].w / 2)) , (boxes[0].y + (boxes[0].h / 2)) );\n ctx.lineTo( (boxes[1].x + (boxes[1].w / 2)) , (boxes[1].y + (boxes[1].h / 2)) );\n ctx.strokeStyle = \"#000000\";\n ctx.stroke();\n ctx.beginPath();\n ctx.moveTo( (boxes[0].x + (boxes[0].w / 2) -1) , (boxes[0].y + (boxes[0].h / 2) -1) );\n ctx.lineTo( (boxes[1].x + (boxes[1].w / 2) -1) , (boxes[1].y + (boxes[1].h / 2) -1) );\n ctx.strokeStyle = \"#ffffff\";\n ctx.stroke();\n\n\n\n if (mySel != null) {\n ctx.strokeStyle = mySelColor;\n ctx.lineWidth = mySelWidth;\n ctx.strokeRect(mySel.x,mySel.y,mySel.w,mySel.h);\n }\n \n if(myHov != null && isHover) {\n ctx.strokeStyle = myHoverColor;\n ctx.lineWidth = myHoverWidth;\n ctx.strokeRect(myHov.x,myHov.y,myHov.w,myHov.h);\n }\n // Add stuff you want drawn on top all the time here\n \n \n canvasValid = true;\n }\n}", "function setUp() {\n background.x = canvas.width / 2 - bgImage.width / 2;\n background.y = canvas.height / 2 - bgImage.height / 2;\n\n start.x = bgImage.width / 2 - startImage.width / 2;\n start.y = bgImage.height / 2 - startImage.height / 2;\n if (bgReady) {\n ctx.drawImage(bgImage, 0,0);\n }\n if (startReady) {\n ctx.drawImage(startImage, start.x, start.y);\n }\n stW = startImage.width;\n stH = startImage.height;\n stData = [start.x, start.y, stW, stH];\n}", "function draw(){\n context.clearRect(0, 0, canvas.width, canvas.height);\n boxes.forEach(function(box, i){\n context.fillStyle = box.color;\n context.fillRect(box.x, box.y, box.width, box.height);\n });\n}", "function drawImageCallback(context, images, x, y, width, height){\n for(let imageNo in images){\n context.drawImage(images[imageNo], x + ((0.5*imageNo)*width), y, width, height);\n }\n}", "function updateRect() {\n\tcanvasPosX = parseInt(document.getElementById('x-setter').value);\n\tcanvasPosY = parseInt(document.getElementById('y-setter').value);\n\tcanvasWidth = parseInt(document.getElementById('width').value);\n\tcanvasHeight = parseInt(document.getElementById('height').value);\n\tlet preview = document.getElementById('imagepreview');\n\tlet canvas = document.getElementById('canvas');\n\tlet context = canvas.getContext('2d');\n\tlet ctx = preview.getContext('2d');\n\tcontext.clearRect(0, 0, canvas.width, canvas.height);\n\tctx.clearRect(0, 0, preview.width, preview.height);\n\tpreview.height = canvasHeight;\n\tpreview.width = canvasWidth;\n\tcanvas.height = canvasHeight;\n\tcanvas.width = canvasWidth;\n\tctx.drawImage(output, canvasPosX, canvasPosY);\n\tcontext.drawImage(output, canvasPosX, canvasPosY)\n}", "resizeCanvases() {\n if (this.imageCanvas) {\n this.imageCanvas.width = this.lineCanvas.width = document.body.clientWidth;\n this.imageCanvas.height = this.lineCanvas.height = window.innerHeight;\n }\n }", "function img_update () {\n\t\tcontexto.drawImage(canvas, 5,5);\n\t\tcontext.clearRect(0, 0, canvas.width, canvas.height);\n }", "function drawImage( imageObj ) {\n\t\t// Select which of the ASCII ramps to use\n\t\tvar ramp = RampType[rampType];\n\n\t\t// Set up canvas\n\t\tvar canvas = document.getElementById('myCanvas');\n\t\tvar imageWidth = imageObj.width;\n\t\tvar imageHeight = imageObj.height;\n\t\tvar context = canvas.getContext('2d');\n\n\t\tcanvas.width = imageWidth;\n\t\tcanvas.height = imageHeight;\n\n\t\t// This is used as the max number of characters, or\n\t\t// \"ascii pixels\", for a row or column, depending\n\t\t// on the width-height relation of the image.\n\t\tvar columnRowMax = 50.0;\n\n\t\t// Set whether the max number of ASCII pixels should be\n\t\t// the width or the height of the image (judged from\n\t\t// a portrait or a landscape image)\n\t\tvar scaleByWidth = imageWidth > imageHeight;\n\t\tvar factor = scaleByWidth ? imageWidth / columnRowMax : imageHeight / columnRowMax;\n\n\t\t// Trace the image onto the canvas\n\t\tcontext.drawImage(imageObj, 0, 0);\n\n\t\t// Collect image data\n\t\tvar imageData = context.getImageData(0, 0, imageWidth, imageHeight);\n\t\tvar data = imageData.data;\n\n\t\t// iterate over all pixels based on x and y coordinates\n\t\tvar map = [];\n\t\tvar map2d = [];\n\t\tvar avg = 0;\n\n\t\t// Set min and max values for clamping resulting\n\t\t// pixel values\n\t\tvar min = 255, max = 0;\n\t\tfor(var y = 0; y < imageHeight; y++) {\n\t\t\t// loop through each column\n\t\t\tvar row = [];\n\t\t\tfor(var x = 0; x < imageWidth; x++) {\n\t\t\t\tvar red = data[((imageWidth * y) + x) * 4];\n\t\t\t\tvar green = data[((imageWidth * y) + x) * 4 + 1];\n\t\t\t\tvar blue = data[((imageWidth * y) + x) * 4 + 2];\n\t\t\t\tvar alpha = data[((imageWidth * y) + x) * 4 + 3];\n\n\t\t\t\tavg = alpha != 0 ? (red + green + blue) / 3.0 : 255;\n\t\t\t\trow.push (avg / 256.0);\n\t\t\t\tmap.push (avg / 256.0);\n\n\t\t\t\tif (max < avg) max = avg;\n\t\t\t\tif (min > avg) min = avg;\n\t\t\t}\n\t\t\tmap2d.push(row);\n\t\t}\n\n\t\tvar row = \"\";\n\t\tvar index = 0;\n\n\t\t// Create element which treats whitespaces as characters\n\t\tvar pre = document.createElement('pre');\n\n\t\tfor (var y = 0; y < (imageHeight / factor); y++ ) {\n\t\t\t// For each row..\n\t\t\tfor (var x = 0; x < parseInt(imageWidth / factor); x++ ) {\n\t\t\t\t// For each column in the row..\n\t\t\t\t// Set and get the \"ascii pixel value\"\n\t\t\t\tindex = parseInt(x * factor + parseInt(y * imageWidth));\n\n\t\t\t\tvar value = map2d[parseInt(y * factor)][parseInt(x * factor)] * ramp.length;\n\t\t\t\trow += ramp[parseInt(value)].toString() + \" \";\n\t\t\t}\n\n\t\t\tvar p = document.createElement('span');\n\t\t\tp.textContent = row;\n\t\t\tp.style.margin = 0;\n\t\t\tp.style.padding = 0;\n\t\t\tpre.appendChild(p);\n\t\t\tpre.appendChild(document.createElement('br'));\n\t\t\tnextIndex = 0;\n\t\t\trow = '';\n\t\t}\n\n\t\t// Add the ASCII art\n\t\tdocument.getElementById('content').appendChild(pre);\n\n\t\t// Add the image, properly scaled\n\t\tdocument.getElementById('img').style.backgroundImage = 'url(' + imageObj.src + ')';\n\t\t// Remove the canvas used to generate the ART.\n\t\tdocument.body.removeChild(document.getElementById('myCanvas'));\n\t}", "function applyPredictionsToImage() {\n\n let threshold = (thresholdSlider.value / 100);\n let width = imgTarget.width;\n let height = imgTarget.height;\n\n // Create the trace canvas to draw on image\n const canvas = document.createElement('canvas');\n canvas.width = width;\n canvas.height = height;\n\n const ctx = canvas.getContext('2d');\n ctx.drawImage(originalImage, 0, 0, width, height);\n ctx.lineWidth = 2;\n ctx.font = \"15px Arial\";\n\n ctx.beginPath();\n let x1, x2, y1, y2;\n let labelText, classVal, confidence, color;\n for (let i = 0; i < predictions.length; i++) {\n if (predictions[i][1] > threshold) {\n\n classVal = predictions[i][0];\n color = colorArray[predictions[i][0]];\n\n // Set color as per class label index of colorArray and \n ctx.strokeStyle = color;\n\n // Get X/Y points from prediction.\n x1 = predictions[i][2] * width;\n y1 = predictions[i][3] * height;\n x2 = (predictions[i][4] * width) - x1;\n y2 = (predictions[i][5] * height) - y1;\n\n // Draw the box for detections.\n ctx.rect(x1, y1, x2, y2);\n ctx.stroke();\n\n // Draw the label and confidence as text\n confidence = `${Math.round(predictions[i][1] * 10000) / 100} %`;\n labelText = `ID:${i + 1}-${getPredictionLabel(classVal)} - ${confidence}`;\n\n ctx.fillStyle = color;\n ctx.fillText(labelText, x1, y1 - 2);\n\n }\n }\n\n let url = canvas.toDataURL();\n imgTarget.src = url;\n}", "draw(ctx, xPos, yPos, scale) {\n ctx.drawImage(\n this.img,\n this.x,\n this.y,\n this.width,\n this.height,\n xPos,\n yPos, // x, y, width and height of img to draw\n this.width * scale,\n this.height * scale\n );\n }", "function drawImg(img) {\r\n gCtx.drawImage(img, 0, 0, gCanvas.width, gCanvas.height)\r\n}", "function init(){\n\tw = window.innerWidth;\n\th = window.innerHeight;\n\n\timage_canvas.width = w;\n\timage_canvas.height = h;\n\n\tseek_canvas.width = image_canvas.width * (4/5);\n\tseek_canvas.height = 40;\n\n\tseek_overlay_canvas.width = seek_canvas.width;\n\tseek_overlay_canvas.height = seek_canvas.height;\n\n\tseek_canvas.relativeX = image_canvas.width * (1/10);\n\tseek_canvas.relativeY = image_canvas.height - seek_canvas.height - 50;\n}", "function CanvasOverlay(drawCallback) {\n var _this = this;\n this._canvasReady = new Promise(function (resolve, reject) { _this._readyResolver = resolve; });\n this._drawCallback = drawCallback;\n id++;\n }", "function img_update () {\ncontexto.drawImage(canvas, 0, 0);\ncontext.clearRect(0, 0, canvas.width, canvas.height);\n}", "function draw(){\n\n\n // canvas.save();\n // canvas.clearRect(0, 0, width, height);\n // canvas.translate(transform_x, transform_y);\n // canvas.scale(scale_value, scale_value);\n\n coresetData.forEach(function(d){\n canvas.beginPath();\n canvas.rect(parseFloat(d.x), -parseFloat(d.y), parseFloat(d.delta), parseFloat(d.delta));\n canvas.fillStyle = d.color;\n canvas.fill();\n //canvas.closePath();\n });\n }", "function initCanvas()/*:void*/ {var this$=this;\n var initCanvasRequestNumber/*:int*/ = ++this.initCanvasRequestedCounter$AoGC;\n if (this.canvasMgr$AoGC) {\n // Need to destroy the old manager instance first\n this.canvasMgr$AoGC.destroy();\n }\n\n var blobData/*:Blob*/ = AS3.getBindable(this,\"imageBlobValueExpression\").getValue();\n if (blobData) {\n this.imageDimensionsValueExpression$AoGC.loadValue(function (imageDimensions/*:Object*/)/*:void*/ {\n if (initCanvasRequestNumber === this$.initCanvasRequestedCounter$AoGC) {\n this$.imageWidth$AoGC = imageDimensions['width'];\n this$.imageHeight$AoGC = imageDimensions['height'];\n\n if (this$.imageHeight$AoGC > 0 && this$.imageWidth$AoGC > 0) {\n this$.initCanvasManager$AoGC();\n this$.initMapAreas$AoGC();\n\n // in case of \"revert\", restore the canvas with the same scale and zoom values\n var scale/*:Number*/ = this$.getZoomValueExpression().getValue();\n\n if (scale > 0) {\n this$.getZoomValueExpression().setValue(scale);\n this$.canvasMgr$AoGC.setScale(scale);\n }\n this$.fitToWidth();\n }\n }\n });\n }\n }", "function openTestImage() {\n\n var base_image = new Image();\n canvas = document.getElementById(\"image-canvas\");\n canvas2 = document.getElementById(\"anno-canvas\");\n context = canvas.getContext(\"2d\");\n // wait for image to load before drawing canvas\n base_image.onload = function () {\n\n canvas.width = base_image.width;\n canvas.height = base_image.height;\n canvas2.width = base_image.width;\n canvas2.height = base_image.height;\n\n context.drawImage(base_image, 0, 0);\n imageOpen = true;\n };\n base_image.src = \"../images/test.jpg\";\n imageType = true;\n document.getElementById('workingFile').innerHTML = \"testing\";\n\n\n }", "function drawBoxes(objects) {\n\n //clear the previous drawings\n drawCtx.clearRect(0, 0, drawCanvas.width, drawCanvas.height);\n\n //filter out objects that contain a class_name and then draw boxes and labels on each\n objects.forEach(face => {\n let scale = uploadScale();\n let _x = face.x / scale;\n let y = face.y / scale;\n let width = face.w / scale;\n let height = face.h / scale;\n //flip the x axis if local video is mirrored\n if (mirror) {\n x = drawCanvas.width - (_x + width)\n } else {\n x = _x\n }\n\n let rand_conf = face.confidence.toFixed(2);\n let title = \"\" + rand_conf + \"\";\n if (face.name != \"unknown\") {\n drawCtx.strokeStyle = \"magenta\";\n drawCtx.fillStyle = \"magenta\";\n title += ' - ' + face.name\n if (face.predict_proba > 0.0 ) {\n title += \"[\" + face.predict_proba.toFixed(2) + \"]\";\n }\n } else {\n drawCtx.strokeStyle = \"cyan\";\n drawCtx.fillStyle = \"cyan\";\n }\n drawCtx.fillText(title , x + 5, y - 5);\n drawCtx.strokeRect(x, y, width, height);\n\n if(isCaptureExample && examplesNum < maxExamples) {\n console.log(\"capure example: \", examplesNum)\n\n //Some styles for the drawcanvas\n exCtx.drawImage(imageCanvas,\n face.x, face.y, face.w, face.h,\n examplesNum * exampleSize, 0,\n exampleSize, exampleSize);\n\n examplesNum += 1;\n\n if(examplesNum == maxExamples) {\n stopCaptureExamples();\n }\n }\n\n });\n}", "function setupCanvasDrawing() {\n // get canvas and context\n var drawingCanvas = document.getElementById('texture-canvas');\n ctx = drawingCanvas.getContext( '2d' );\n // draw white background\n ctx.fillStyle = '#FFFFFF';\n ctx.fillRect( 0, 0, 1257, 1443 );\n\n img = new Image();\n img.src = \"lines.png\";\n img.onload = function() {\n drawingCanvas.width = img.width;\n drawingCanvas.height = img.height;\n\n ctx.beginPath();\n ctx.rect(0, 0, img.width, img.height);\n ctx.fillStyle = \"white\";\n ctx.fill();\n ctx.drawImage(img, 0, 0);\n\n material.map.needsUpdate = true;\n }\n // set canvas as material.map (this could be done to any map, bump, displacement etc.)\n material.map = new THREE.CanvasTexture( drawingCanvas );\n\n}", "function initCanvas() {\n let posX = 0\n\n // Flip image\n ctx.save()\n if (Math.random() >= 0.5) {\n ctx.scale(-1, 1)\n posX = -img.width\n }\n\n ctx.drawImage(img, posX, 0, img.width, img.height); //clears the canvas\n ctx.restore()\n\n ctx.font = fontSize + 'px ' + fontName;\n ctx.textAlign = \"left\";\n ctx.textBaseline = \"top\";\n }", "function loadImageToCanvas(){\n img.onload = function(){\n ctx.drawImage(img, 0,0);\n }\n img.src = imgHolder.src;\n }", "function drawCanvas() {\n\t\tdraw(context, drawer, colours, solver);\n\t\tsolver.callStateForItem(spanState);\n\t}", "draw (drawCallback) {\n this.ctx.clearRect(0, 0, this.ctx.canvas.width, this.ctx.canvas.height);\n this.ctx.save();\n\n for (let i = 0; i < this.entities.length; i++) {\n this.entities[i].draw(this.ctx);\n }\n \n if (drawCallback) {\n drawCallback(this);\n }\n\n this.ctx.restore();\n }", "function init() {\n clearCanvas()\n drawBackgroundColor()\n drawOrigin()\n }" ]
[ "0.66951317", "0.5971016", "0.59601617", "0.59585005", "0.5803974", "0.57195866", "0.564124", "0.5575592", "0.5516886", "0.54568934", "0.5340093", "0.5338683", "0.5283784", "0.52835274", "0.527635", "0.5232744", "0.5231368", "0.5202946", "0.51907265", "0.5175944", "0.5148292", "0.5135176", "0.5134271", "0.5128568", "0.51122534", "0.5111289", "0.5084432", "0.5082636", "0.50794125", "0.5054004", "0.50503445", "0.5046787", "0.50433683", "0.5039728", "0.5039693", "0.50383496", "0.5015278", "0.50026536", "0.49911845", "0.4988628", "0.49882904", "0.49840033", "0.49818712", "0.49789476", "0.49779615", "0.49759483", "0.49758148", "0.4962101", "0.49614975", "0.4953778", "0.49503198", "0.4947466", "0.49398214", "0.493042", "0.4925946", "0.49248993", "0.49234018", "0.4915708", "0.490859", "0.48960552", "0.48728922", "0.48471504", "0.484325", "0.48372722", "0.48365653", "0.4832864", "0.4825383", "0.4823664", "0.4821701", "0.48191625", "0.48074758", "0.4806093", "0.48037454", "0.48034027", "0.48003018", "0.4791621", "0.47898263", "0.47878504", "0.47832072", "0.47828537", "0.47824007", "0.47776875", "0.47772646", "0.47742048", "0.4773659", "0.4772552", "0.47705895", "0.4767737", "0.47669575", "0.47563702", "0.47560096", "0.47450066", "0.4742393", "0.474186", "0.47396666", "0.4727408", "0.47254044", "0.47239503", "0.47216713", "0.47180116" ]
0.72186077
0
! preview canvas \class PreviewCanvas \param canvas canvas element \param image image draw on the canvas
function PreviewCanvas(canvas, image) { this.canvas = canvas; this.width = canvas.width; this.height = canvas.height; this.ctx = canvas.getContext('2d'); this.image = image; this.visible = false; this.scaleX = 1; this.scaleY = 1; this.isBaseline = false; this.position_up_line = 0; this.position_down_line = 0; this.position_left_line = 0; this.position_right_line = 0; this.position_baseline = 0; this.idElementSelected = 0; var myPreviewCanvas = this; this.image.img.onload = function(){ myPreviewCanvas.draw(); } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function draw_on_canvas(canvas, image) {\n // Giving canvas the image dimension\n\n var ctx = canvas.getContext('2d');\n // Drawing\n ctx.drawImage(image, 0 ,0,canvas.width,canvas.height);\n }", "function drawImageCanvas() {\n // Emulate background-size: cover\n var width = imageCanvas.width;\n var height = imageCanvas.width / image.naturalWidth * image.naturalHeight;\n \n if (height < imageCanvas.height) {\n width = imageCanvas.height / image.naturalHeight * image.naturalWidth;\n height = imageCanvas.height;\n }\n\n imageCanvasContext.clearRect(0, 0, imageCanvas.width, imageCanvas.height);\n imageCanvasContext.globalCompositeOperation = 'source-over';\n imageCanvasContext.drawImage(image, 0, 0, width, height);\n imageCanvasContext.globalCompositeOperation = 'destination-in';\n imageCanvasContext.drawImage(lineCanvas, 0, 0);\n}", "function preview(img, selection) { \n var scaleX = settings.cropwidth / (selection.width || 1); \n var scaleY = settings.cropheight / (selection.height || 1);\n\n canvas = document.getElementById(settings.canvasid);\n canvas.width = settings.cropwidth;\n canvas.height = settings.cropheight;\n context = canvas.getContext('2d');\n \n var imageObj = new Image();\n\n imageObj.onload = function() { \n // draw cropped image\n var sourceX = selection.x1;\n var sourceY = selection.y1;\n var sourceWidth = selection.width || 1;\n var sourceHeight = selection.height || 1;\n var destWidth = settings.cropwidth; \n var destHeight = settings.cropheight;\n var destX = 0;\n var destY = 0;\n\n context.drawImage(imageObj, sourceX, sourceY, sourceWidth, sourceHeight, destX, destY, destWidth, destHeight); \n };\n \n imageObj.src = img.src;\n\n }", "function draw_image( img ) {\n context.clearRect(0, 0, canvas.width, canvas.height);\n context.drawImage(img, 0, 0, canvas.width, canvas.height);\n }", "function CanvasImage(canvas) {\n\n if (canvas.width !== innerWidth || canvas.height !== innerHeight) {\n canvas.width = innerWidth - innerWidth*0.2;\n canvas.height = innerHeight - innerHeight*0.2;\n } else {\n ctx.clearRect(0, 0, canvas.width, canvas.height);\n }\n\n this.canvas = canvas;\n this.context = canvas.getContext(\"2d\");\n this.width = canvas.width;\n this.height = canvas.height;\n this.newImageData = this.context.createImageData(this.width, this.height);\n this.oldImageData = this.context.createImageData(this.width, this.height);\n this.newBuffer = new Uint32Array(this.newImageData.data.buffer);\n this.oldBuffer = new Uint32Array(this.oldImageData.data.buffer);\n }", "drawImageCanvas() {\n // Emulate background-size: cover\n if (this.imageCanvas) {\n var width = this.imageCanvas.width;\n var height = this.imageCanvas.width / this.image.naturalWidth * this.image.naturalHeight;\n \n if (height < this.imageCanvas.height) {\n width = this.imageCanvas.height / this.image.naturalHeight * this.image.naturalWidth;\n height = this.imageCanvas.height;\n }\n \n this.imageCanvasContext.clearRect(0, 0, this.imageCanvas.width, this.imageCanvas.height);\n this.imageCanvasContext.globalCompositeOperation = 'source-over';\n this.imageCanvasContext.drawImage(this.image, 0, 0, width, height);\n this.imageCanvasContext.globalCompositeOperation = 'destination-in';\n this.imageCanvasContext.drawImage(this.lineCanvas, 0, 0);\n }\n }", "function draw(image, thecanvas) {\n\n var context = thecanvas.getContext('2d');\n\n context.drawImage(image, 0, 0, thecanvas.width, thecanvas.height);\n }", "function preview() {\n window.open(document.getElementById(\"myCanvas\").toDataURL(), \"canvasImage\", \"left=0,top=0,width=\" +\n widthCanvas + \",height=\" + heightCanvas + \",toolbar=0,resizable=0\");\n}", "function UpdatePreviewCanvas(){\n var img = this;\n $(\"#img_survey\").hide();\n $(\"#previewcanvascontainer\").css('display', 'inline');\n var canvas = document.getElementById( 'previewcanvas' );\n\n if( typeof canvas === \"undefined\"\n || typeof canvas.getContext === \"undefined\" )\n return;\n\n var context = canvas.getContext( '2d' );\n\n var world = new Object();\n world.width = canvas.offsetWidth;\n world.height = canvas.offsetHeight;\n\n canvas.width = world.width;\n canvas.height = world.height;\n\n if( typeof img === \"undefined\" )\n return;\n\n var WidthDif = img.width - world.width;\n var HeightDif = img.height - world.height;\n\n var Scale = 0.0;\n if( WidthDif > HeightDif )\n {\n Scale = world.width / img.width;\n }\n else\n {\n Scale = world.height / img.height;\n }\n if( Scale > 1 )\n Scale = 1;\n\n var UseWidth = Math.floor( img.width * Scale );\n var UseHeight = Math.floor( img.height * Scale );\n\n var x = Math.floor( ( world.width - UseWidth ) / 2);\n var y = Math.floor( ( world.height - UseHeight ) / 2 );\n\n context.drawImage( img, x, y, 200, 200 );\n}", "drawCanvas(imgData) {\n\t\t// abstract\n\t}", "function handleImage(e){\n var canvas = document.getElementById(\"imgCanvas\");\n\tvar context = canvas.getContext(\"2d\");\n var reader = new FileReader();\n reader.onload = function(event){\n var img = new Image();\n img.onload = function(){\n canvas.width = img.width;\n canvas.height = img.height;\n context.drawImage(img,0,0);\n }\n img.src = event.target.result;\n } \n reader.readAsDataURL(e.target.files[0]); \n}", "function loadImageToCanvas(){\n img.onload = function(){\n ctx.drawImage(img, 0,0);\n }\n img.src = imgHolder.src;\n }", "function showImgPreview(file, img) {\n var reader = new FileReader();\n\n reader.onload = function (e) {\n img.attr('src', reader.result).show();\n };\n reader.readAsDataURL(file);\n }", "function showImage() {\n context.drawImage(v, 0, 0, c.width, c.height);\n \n }", "function create_Picture_Image(){\n\t\t // Source:\n\t\t // https://stackoverflow.com/questions/23745988/get-an-image-from-the-video\n\t\t // postCardCanvasContext.drawImage(document.getElementById(\"vidDisplay\"), 0, 0, postCardCanvas.width, postCardCanvas.height);\n\t\t \n\t\t // Now we'll proceed to follow the changes until the current one\n\t\t for(var x = 1; x< canvasHistoryPointer+1; x++)\n\t\t\t if(canvasHistory[x].type = \"text\"){\n\t\t\t\t // Now recreate the text\n\t\t\t\t postCardCanvasContext.fillStyle = canvasHistory[x].fillStyle;\n\t\t\t\t postCardCanvasContext.font = canvasHistory[x].font;\t \n\t\t\t\t postCardCanvasContext.fillText(canvasHistory[x].text, canvasHistory[x].xCord, canvasHistory[x].yCord);\t\n\t\t\t }\n\t\t \n\t\t // Splice the canvasHistory\n\t\t canvasHistory.splice(canvasHistoryPointer+1);\n\t\t // Reset the Buttons\n\t\t buttons[0].material.color.setHex(0xffffff);\n\t\t buttons[1].material.color.setHex(0x575757);\t\t \n\t\t \n\t\t var history = {\n\t\t\t type:\"Image\",\n\t\t\t image:postCardCanvasContext.getImageData(0, 0, postCardCanvas.width, postCardCanvas.height)\n\t\t }\n\t\t canvasHistory.push(history);\n\t\t canvasHistoryPointer++;\t\t \n\t }", "function drawImageOnCanvas(imageid){\n\t\t\t\tctx.clearRect(0, 0, canvas.width, canvas.height);\n\t\t\t\tdrawImageId=imageid;\n\t\t\t\tvar img = document.getElementById(drawImageId);\n\t\t\t\tctx.drawImage(img, 10, 10);\n\t}", "function displayImage(){\n\t context.drawImage(video,0,0,320,240);\n //This is where we write the picture data and turn it into a dataURL so we can feed it to the API\n\t\tdURL = canvasElement.toDataURL(\"image/jpeg\",1);\n\n\t\t//call the function to send the image to the emotion API\n\t\tfaceProcess();\n}", "function handleImage(e) {\n var reader = new FileReader();\n imgData = 0\n\n reader.onload = function (event) {\n img.onload = function () {\n canvas.width = 400;\n canvas.height = 400 / img.width * img.height;\n\n ctx.drawImage(img, 0, 0, img.width, img.height, 0, 0, canvas.width, canvas.height);\n }\n img.src = event.target.result;\n src = event.target.result;\n canvas.classList.add(\"show\");\n DrawOverlay(img);\n \n\n }\n reader.readAsDataURL(e.target.files[0]);\n\n}", "function takePhoto (e) {\nlet ctx = outputCanvas.getContext('2d')\nctx.drawImage(inputVideo,0,0)\n}", "function updateRect() {\n\tcanvasPosX = parseInt(document.getElementById('x-setter').value);\n\tcanvasPosY = parseInt(document.getElementById('y-setter').value);\n\tcanvasWidth = parseInt(document.getElementById('width').value);\n\tcanvasHeight = parseInt(document.getElementById('height').value);\n\tlet preview = document.getElementById('imagepreview');\n\tlet canvas = document.getElementById('canvas');\n\tlet context = canvas.getContext('2d');\n\tlet ctx = preview.getContext('2d');\n\tcontext.clearRect(0, 0, canvas.width, canvas.height);\n\tctx.clearRect(0, 0, preview.width, preview.height);\n\tpreview.height = canvasHeight;\n\tpreview.width = canvasWidth;\n\tcanvas.height = canvasHeight;\n\tcanvas.width = canvasWidth;\n\tctx.drawImage(output, canvasPosX, canvasPosY);\n\tcontext.drawImage(output, canvasPosX, canvasPosY)\n}", "function createImageCanvas(img) {\n var imageCanvas = document.createElement('canvas'),\n imageContext = imageCanvas.getContext('2d'),\n width = settings.maxWidth,\n height = settings.maxHeight;\n\n imageCanvas.width = width;\n imageCanvas.height = height;\n imageContext.drawImage(img, 0, 0, width, height);\n\n return imageCanvas;\n }", "function previewImage(source, target) {\n var reader = new FileReader();\n reader.readAsDataURL(source.files[0]);\n\n reader.onload = function (reader_event) {\n target.src = reader_event.target.result;\n target.style.border = \"2px solid black\";\n target.style.display = \"inline\";\n };\n}", "function drawImg(img) {\r\n gCtx.drawImage(img, 0, 0, gCanvas.width, gCanvas.height)\r\n}", "function drawToCanvas(canvas, predictions, img) {\n var context = canvas.getContext('2d');\n \n if (img)\n context.drawImage(img, 0, 0 );\n\n if (predictions.length > 0) {\n const result = predictions[0].landmarks;\n drawKeypoints(context, result, predictions[0].annotations);\n canvas.style.border = \"6px solid lightgreen\";\n }\n}", "function initCanvas(onDrawingCallback) {\n let flag = false,\n prevX, prevY, currX, currY = 0;\n let canvasJq = $('#canvas');\n let canvasEle = document.getElementById('canvas');\n let imgEle = document.getElementById('image');\n\n // event on the canvas when the mouse is on it\n canvasJq.on('mousemove mousedown mouseup mouseout', function (e) {\n prevX = currX;\n prevY = currY;\n currX = e.clientX - canvasJq.position().left;\n currY = e.clientY - canvasJq.position().top;\n if (e.type === 'mousedown') {\n flag = true;\n }\n if (e.type === 'mouseup' || e.type === 'mouseout') {\n flag = false;\n }\n // if the flag is up, the movement of the mouse draws on the canvas\n if (e.type === 'mousemove') {\n if (flag) { \n data = { \n canvas: { \n width: canvasEle.width, \n height: canvasEle.height \n }, \n paths: [\n { \n x1: prevX, \n y1: prevY, \n x2: currX, \n y2: currY \n }\n ], \n color: inkColor, \n thickness: thickness \n }\n pushPath(data);\n onDrawingCallback(data);\n }\n }\n });\n\n // Loaded & resize event\n imgEle.addEventListener('load', () => {\n repositionCanvas();\n });\n\n window.addEventListener('resize', () => {\n repositionCanvas();\n });\n\n // If the image has already been loaded.\n if (imgEle.naturalHeight && imgEle.clientWidth > 0) {\n repositionCanvas();\n }\n}", "function loadImageToCanvas(imgData, canvas) {\n canvas.width = imgData.width;\n canvas.height = imgData.height;\n const context = canvas.getContext('2d');\n context.putImageData(imgData, 0, 0);\n}", "function preview() {\n var reader = new FileReader();\n reader.onload = function (e) {\n document.getElementById(\"upload\").src = e.target.result;\n };\n reader.readAsDataURL(this.files[0]);\n\n canvas.style.display = \"block\";\n ctx.clearRect(0, 0, canvas.width, canvas.height);\n\n video.style.display = \"none\";\n snapButton.value = \"Use Camera\";\n snapButton.onclick = clearPreview;\n}", "function img_update (canvasId) {\n\t\tvar canvas = tempCanvasList[canvasId];\n\t\tvar contexto = canvasContextList[canvasId];\n\t\tcontexto.drawImage(canvas, 0, 0);\n\t\tvar context = tempCanvasContextList[canvasId];\n\t\tcontext.clearRect(0, 0, canvas.width, canvas.height);\n }", "function setCanvas(w,h){\n canvas.width = imgHolder.width;\n canvas.height = imgHolder.height;\n\n loadImageToCanvas();\n }", "function createCanvasOverlay(image) {\n\n\t\tvar canvas = document.createElement('canvas'),\n\t\t canvasContext = canvas.getContext(\"2d\");\n\n\t\t// Make it the same size as the image\n\t\tcanvas.width = slideshow.width;\n\t\tcanvas.height = slideshow.height;\n\n\t\t// Drawing the default version of the image on the canvas:\n\t\tcanvasContext.drawImage(image, 0, 0);\n\n\t\t// Taking the image data and storing it in the imageData array:\n\t\tvar imageData = canvasContext.getImageData(0, 0, canvas.width, canvas.height),\n\t\t data = imageData.data;\n\n\t\t// Loop through all the pixels in the imageData array, and modify\n\t\t// the red, green, and blue color values.\n\n\t\tfor (var i = 0, z = data.length; i < z; i++) {\n\n\t\t\t// The values for red, green and blue are consecutive elements\n\t\t\t// in the imageData array. We modify the three of them at once:\n\n\t\t\tdata[i] = data[i] < 128 ? 2 * data[i] * data[i] / 255 : 255 - 2 * (255 - data[i]) * (255 - data[i]) / 255;\n\t\t\tdata[++i] = data[i] < 128 ? 2 * data[i] * data[i] / 255 : 255 - 2 * (255 - data[i]) * (255 - data[i]) / 255;\n\t\t\tdata[++i] = data[i] < 128 ? 2 * data[i] * data[i] / 255 : 255 - 2 * (255 - data[i]) * (255 - data[i]) / 255;\n\n\t\t\t// After the RGB elements is the alpha value, but we leave it the same.\n\t\t\t++i;\n\t\t}\n\n\t\t// Putting the modified imageData back to the canvas.\n\t\tcanvasContext.putImageData(imageData, 0, 0);\n\n\t\t// Inserting the canvas in the DOM, before the image:\n\t\timage.parentNode.insertBefore(canvas, image);\n\t}", "function imageDraw(imgData){\r\n\t\r\n\tif(typeof imgData === \"undefined\") {\r\n\t\treturn;\r\n\t}\r\n\tcanvasWidth = imgData.width * zoom/100;\r\n\tcanvasHeight = imgData.height * zoom/100;\r\n\t\r\n\t// new Size of canvas\r\n\tctx.canvas.width = canvasWidth; \r\n\tctx.canvas.height = canvasHeight;\r\n\t\r\n\t// new Position of Canvas\r\n\tvar deltaX = canvasWidth - canvasOldWidth;\r\n\tvar deltaY = canvasHeight - canvasOldHeight;\r\n\tvar canvXString = $('.image_area').children().css('left');\r\n\tvar canvYString = $('.image_area').children().css('top');\r\n\tvar newCanvX = Number( canvXString.substring(0,canvXString.length-2) ) - deltaX/2;\r\n\tvar newCanvY = Number( canvYString.substring(0,canvYString.length-2) ) - deltaY/2;\r\n\t\r\n\t$('.image_area').children().css('left',newCanvX + 'px');\r\n\t$('.image_area').children().css('top',newCanvY + 'px');\r\n\tcanvasOldWidth = canvasWidth;\r\n\tcanvasOldHeight = canvasHeight;\r\n\t\r\n\t// zoom in or out as canvas operation\r\n\tctx.scale(zoom/100, zoom/100);\r\n\tvar newCanvas = $(\"<canvas>\")\r\n\t\t.attr(\"width\", imgData.width)\r\n\t\t.attr(\"height\", imgData.height)[0];\r\n\tnewCanvas.getContext(\"2d\").putImageData(imgData,0,0);\r\n\t\r\n\tctx.drawImage(newCanvas,0,0);\r\n}", "function updateImg() {\n context.drawImage($tmpCanvas[0], 0, 0); \n tmpContext.clearRect(0, 0, canvasWidth(), canvasHeight());\n }", "drawImage () {\n // Create image object\n var image = new Image()\n // Set image source\n image.src = this.imageSrc\n // Set canvas context as 2d\n var ctx = this.canvas.getContext('2d')\n // Set smooth content = true & hight\n ctx.imageSmoothingEnabled = true\n ctx.imageSmoothingQuality = \"high\"\n // Calculate new width and height, new width = 500px\n var newImgW = 500\n var newImgH = image.height / (image.width/500)\n // Set the new width and height and set to canvas\n this.canvas.width = newImgW\n this.canvas.height = newImgH\n // Draw image to canvas\n ctx.drawImage(image, 0, 0, newImgW, newImgH)\n }", "show(canvas, callback) {\n iSend.onclick = callback;\n iImg.src = canvas.toDataURL();\n orderFrame.style.zIndex = 1000;\n orderFrame.style.width = '100%';\n orderFrame.style.height = '100%';\n }", "function doCanvas(ctx, canvas) {\n /* draw something */\n ctx.fillStyle = '#f90';\n ctx.fillRect(0, 0, canvas.width, canvas.height);\n ctx.fillStyle = '#fff';\n ctx.font = '60px sans-serif';\n ctx.fillText('Code Project', 10, canvas.height / 2 - 15);\n ctx.font = '26px sans-serif';\n ctx.fillText('Click link below to save this as image', 15, canvas.height / 2 + 35);\n }", "function drawCanvas(src){\n \n // redraw animation\n var redraw = false;\n if(filechanged)\n redraw = true;\n \n\t// check whether backgroundcanvas needs to be redrawn\n if(filechanged || vischanged){\n $('#backgroundlayer').remove();\n } \n\t\n\t// draw input image as background to canvas\n\timageObj = new Image();\n\timageObj.onload = function(){\n \n // get image dimensions\n var imgW = imageObj.width;\n var imgH = imageObj.height;\n \n // if fit to screen is selected\n if(fitted){\n // get scaled canvas size\n var arr = scaleDimensions(imgW, imgH);\t\n imgW = Math.round(arr[0]);\n imgH = Math.round(arr[1]);\n }\n \n $('#demo').height(imgH + 400);\n \n if($('#backgroundlayer').length == 0){\n // create canvas with correct dimensions\n $('#imageDiv').append('<canvas id=\"backgroundlayer\" width=\"' + imgW + '\" height=\"' + imgH + '\" style=\"border:3px solid #000000; z-index:1\"></canvas>');\n var backgroundlayer = document.getElementById(\"backgroundlayer\");\n var ctx1 = backgroundlayer.getContext(\"2d\");\n ctx1.clearRect(0,0, imgW, imgH);\n \n $('#backgroundlayer').css({position: 'absolute'});\n \n // draw image to canvas\n ctx1.drawImage(imageObj, 0, 0, imgW, imgH);\n } \n \n // configure animation\n prepareAnimation(redraw);\n prepareClick();\n \n // call specific draw functions\n var value = $('#visSelect').val();\n \n // handle different visualizations\n if(value == \"gazeplot\"){\n \n // register color picker for connecting lines\n registerColorpicker($('#lineColorpicker'), $('#lineColor'), '#000000');\n \n var e = $('#slider-range').slider(\"values\", 1);\n drawClick(e);\n \n // draw selected interval\n if(vischanged){\n var s = $('#slider-range').slider(\"values\", 0);\n var e = $('#slider-range').slider(\"values\", 1);\n drawGazeplotAnimation(e, s, e, true);\n }\n // draw complete gazepath\n else{ \n drawGazeplot();\n } \n }\n \n if(value == \"heatmap\"){\n \n // register color picker\n registerColorpicker($('#c1Colorpicker'), $('#c1Color'), '#0000ff');\n registerColorpicker($('#c2Colorpicker'), $('#c2Color'), '#00ff00');\n registerColorpicker($('#c3Colorpicker'), $('#c3Color'), '#ff0000');\n \n // place color pickers\n $('#c1Colorpicker').css('margin-top', '30px').css('margin-left', '10px');\n $('#c2Colorpicker').css('margin-top', '30px').css('margin-left', '73px');\n $('#c3Colorpicker').css('margin-top', '30px').css('margin-left', '136px');\n \n // draw selected interval\n if(vischanged){\n var s = $('#slider-range').slider(\"values\", 0);\n var e = $('#slider-range').slider(\"values\", 1);\n drawHeatmapAnimation(e, s, e, true);\n }\n // draw complete heatmap\n else{ \n drawHeatmap();\n }\n }\t\n \n if(value == \"attentionmap\"){\n\n // register cover color picker\n registerColorpicker($('#attColorpicker'), $('#attColor'), '#000000');\n \n // place color picker\n $('#attColorpicker').css('margin-top', '30px').css('margin-left', '10px');\n \n // draw selected interval\n if(vischanged){\n var s = $('#slider-range').slider(\"values\", 0);\n var e = $('#slider-range').slider(\"values\", 1);\n drawAttentionmapAnimation(e, s, e, true);\n }\n // draw complete gazepath\n else{ \n drawAttentionmap();\n }\n }\n \n if(filechanged || vischanged){\n filechanged = false;\n vischanged = false;\n }\n \n }; \n // set image source\n\timageObj.src = 'data/' + src; \n}", "function changeImagePreview() {\n let reader = new FileReader();\n reader.onload = function (e) {\n document.getElementById(\"currentImg\").src = e.target.result;\n }\n reader.readAsDataURL(document.getElementById(\"picUpload\").files[0]);\n }", "function ShowImagePreview( files ){\n\n $(\"#imgSalida\").css('display', 'none');\n\n\n if( !( window.File && window.FileReader && window.FileList && window.Blob ) ){\n alert('Por favor Ingrese un archivo de Imagen');\n document.getElementById(\"myForm\").reset();\n return false;\n }\n\n if( typeof FileReader === \"undefined\" ){\n alert( \"El archivo no es una imagen por favor ingrese una\" );\n document.getElementById(\"myForm\").reset();\n return false;\n }\n\n var file = files[0];\n\n if( !( /image/i ).test( file.type ) ){\n alert( \"El archivo no es una imagen\" );\n document.getElementById(\"myForm\").reset();\n return false;\n }\n\n reader = new FileReader();\n reader.onload = function(event)\n { var img = new Image;\n img.onload = UpdatePreviewCanvas;\n img.src = event.target.result; }\n reader.readAsDataURL( file );\n}", "function showimg(){\n// ctx.restore();\n ctx.fillStyle=\"#123456\";\n ctx.fillRect(0,0,50,50);\n ctx.save();\n }", "function PreviewImage() {\n var oFReader = new FileReader();\n oFReader.readAsDataURL(document.getElementById(\"uploadImage\").files[0]);\n\n oFReader.onload = function(oFREvent) {\n document.getElementById(\"uploadPreview\").src = oFREvent.target.result;\n };\n}", "function preview(file) {\n // only do this for images\n if (file.type.match(/image.*/)) {\n // show activity indicator\n loading.show();\n\n var reader = new FileReader();\n\n // read the file from disk\n reader.readAsDataURL(file);\n\n reader.onload = function (e) {\n // use this image element to get the aspect ratio of the image\n var imageData = e.target.result,\n image = $('<img src=\"' + imageData + '\"/>').css('visibility', 'hidden'),\n previewAreaReferenceOffset = {\n left: dropZone.offset().left + (dropZone.outerWidth() - dropZone.innerWidth()) / 2,\n top: dropZone.offset().top + (dropZone.outerHeight() - dropZone.innerHeight()) / 2\n };\n\n // add the image to the preview area so we can read its width/height\n previewArea.append(image).width(dropZone.width()).height(dropZone.height());\n\n image.bind('load', function (e) {\n var dropZoneAspectRatio = dropZone.innerWidth() / dropZone.innerHeight(),\n imageAspectRatio = image.width() / image.height(),\n previewSize = {};\n\n // size the preview according to the preview area's aspect ratio\n if (imageAspectRatio > dropZoneAspectRatio) {\n previewSize.width = Math.round(dropZone.innerHeight() * imageAspectRatio);\n previewSize.height = dropZone.innerHeight();\n } else {\n previewSize.width = dropZone.innerWidth();\n previewSize.height = Math.round(dropZone.innerWidth() / imageAspectRatio);\n }\n\n // render the image data in the preview area and remove the helper image\n previewArea.offset(previewAreaReferenceOffset).css({\n 'background-image': 'url(' + imageData + ')',\n 'background-size': previewSize.width + 'px ' + previewSize.height + 'px',\n 'background-position': '0 0',\n 'background-repeat': 'no-repeat',\n 'width': previewSize.width + 'px',\n 'height' : previewSize.height + 'px',\n 'opacity': '1'\n }).empty();\n\n // reposition the preview image on drag\n if (previewSize.width > dropZone.innerWidth() || previewSize.height > dropZone.innerHeight()) {\n // show the 'move' cursor \n previewArea.css('cursor', 'move');\n\n previewArea.bind('mousedown', function (e) {\n var origin = { // where we click\n X: e.clientX,\n Y: e.clientY\n },\n currentOffset = previewArea.offset();\n\n previewArea.bind('mousemove', function (e) {\n var newOffset = { // compute how far we traveled and add to the current background position\n left: currentOffset.left + (e.clientX - origin.X),\n top: currentOffset.top + (e.clientY - origin.Y)\n };\n \n // adjustments\n if (newOffset.top > previewAreaReferenceOffset.top) { newOffset.top = previewAreaReferenceOffset.top; }\n if (newOffset.left > previewAreaReferenceOffset.left) { newOffset.left = previewAreaReferenceOffset.left; }\n if (previewAreaReferenceOffset.top - newOffset.top + dropZone.innerHeight() > previewArea.height()) {\n newOffset.top = previewAreaReferenceOffset.top - (previewArea.height() - dropZone.innerHeight());\n }\n if (previewAreaReferenceOffset.left - newOffset.left + dropZone.innerWidth() > previewArea.width()) {\n newOffset.left = previewAreaReferenceOffset.left - (previewArea.width() - dropZone.innerWidth());\n }\n\n // redraw\n previewArea.offset(newOffset);\n });\n\n previewArea.bind('mouseup', function (e) {\n // make sure there's only one 'mousemove' handler registered at all times\n previewArea.unbind('mousemove');\n });\n\n e.preventDefault(); // this prevents the cursor from transforming into a 'select' cursor\n });\n }\n\n // hide the activity indicator\n loading.fadeOut();\n });\n };\n }\n }", "function moveAndDrawImageToCanvas(image, target) {\n var ctx = target.getContext('2d')\n image.remove()\n ctx.drawImage(image, 20, 20, 200, 200)\n}", "function drawToCanvas(pic_src) {\n isVideo = false;\n image.onload = function () {\n if (image.width > image.height) {\n Draw.horizontalPicture(context, canvas, image)\n }\n else {\n Draw.verticalPicture(context, canvas, image);\n }\n };\n image.src = \"data:image/jpeg;base64,\" + pic_src;\n }", "function drawToCanvas(pic_src) {\n isVideo = false;\n image.onload = function () {\n if (image.width > image.height) {\n Draw.horizontalPicture(context, canvas, image)\n }\n else {\n Draw.verticalPicture(context, canvas, image);\n }\n };\n image.src = \"data:image/jpeg;base64,\" + pic_src;\n }", "function drawToCanvas(pic_src) {\n isVideo = false;\n image.onload = function() {\n if(image.width > image.height) {\n Draw.horizontalPicture(context, canvas, image)\n }\n else {\n Draw.verticalPicture(context, canvas, image);\n }\n };\n image.src = \"data:image/jpeg;base64,\" + pic_src;\n }", "function putimage(canvas,blob){\n var img = new Image();\n var ctx = canvas.getContext('2d');\n img.onload = function () {\n ctx.drawImage(img,0,0,canvasW, canvasH);\n }\n img.src = blob;\n \n }", "function previewImage(input)\n\t{\n\t\tif (input.files && input.files[0]) {\n var reader = new FileReader();\n\n reader.onload = function (e) {\n $('.previewHolder').attr('src', e.target.result);\n $('.userPic img').attr('src', e.target.result);\n $('.menuBigPic img').attr('src', e.target.result);\n }\n\n reader.readAsDataURL(input.files[0]);\n }\n\t}", "function img_update () {\n\t\tcontexto.drawImage(canvas, 5,5);\n\t\tcontext.clearRect(0, 0, canvas.width, canvas.height);\n }", "function resizeCanvas(canvas, src, _callback) {\r\n\r\n // Dimensions of reszed canvas\r\n var MAX_WIDTH = 20;\r\n var MAX_HEIGHT = 20;\r\n\r\n // Get image of canvas and wait till it loads\r\n var image = new Image();\r\n image.src = src;\r\n image.onload = function () {\r\n console.log(\"1st to execute\");\r\n\r\n // Get new image dimensions \r\n image.width = MAX_WIDTH;\r\n image.height = MAX_HEIGHT;\r\n\r\n // Resize canvas\r\n var ctx = canvas.getContext(\"2d\");\r\n ctx.clearRect(0, 0, canvas.width, canvas.height);\r\n canvas.width = image.width;\r\n canvas.height = image.height;\r\n ctx.drawImage(image, 0, 0, image.width, image.height);\r\n \r\n // Get url of image and return callback\r\n var dataurl = canvas.toDataURL(\"image/png\");\r\n _callback(dataurl);\r\n }\r\n\r\n}", "convertCanvasToImage(canvas) {\n console.log('this is happening now')\n var image = new Image();\n image.src = canvas.toDataURL(\"image/png\");\n image.classList.add('contain-image');\n return image;\n }", "function recolorImageWithCanvasContext(context, img, colorFunc) {\n if (!defined(context)) {\n throw new DeveloperError(i18next.t(\"map.imageryProviderHooks.devError\"));\n }\n\n // Copy the image contents to the canvas\n context.clearRect(0, 0, context.canvas.width, context.canvas.height);\n context.drawImage(img, 0, 0);\n var image = context.getImageData(\n 0,\n 0,\n context.canvas.width,\n context.canvas.height\n );\n image = ImageryProviderHooks.recolorImage(image, colorFunc);\n return image;\n}", "function showPreviewImage(input) {\n if (input.files && input.files[0] && (/\\.(gif|jpe?g|png|svg)$/i).test(input.files[0].name)) {\n var reader = new FileReader();\n\n reader.onload = function (e) {\n var stroke = $(input).closest('.admin-stroke');\n if (stroke.length == 0) { stroke = $(input).closest('.admin-stroke--no') }\n stroke.find('.js__image-preview').attr('src', e.target.result);\n }\n reader.readAsDataURL(input.files[0]);\n }\n}", "function img_update () {\n\t\tcontexto.drawImage(canvas, 0, 0);\n\t\tcontext.clearRect(0, 0, canvas.width, canvas.height);\n }", "function img_update () {\r\n\t\t\tcontexto.drawImage(canvas, 0, 0);\r\n\t\t\tcontext.clearRect(0, 0, canvas.width, canvas.height);\r\n\t\t}", "renderImageOld() { // renderImage\r\n var i = this.image.transferToImageBitmap();\r\n this.resizeOffscreenCanvas();\r\n this.ctx.drawImage(i,0,0,this.image.width, this.image.height);\r\n }", "function renderizaPlanoDeFundo(){\n\t$(\"canvas\").drawImage({\n\tsource: 'paginaBG2.jpg',\n\tx: 400,\n\ty: 300,\n\twidth: $(\"canvas\").width(),\n\theight: $(\"canvas\").height()\n\t});\n}", "function drawToCanvas( canvas, ctx, img ){\n return new Promise( ( resolve, reject ) => {\n canvas.width = img.width;\n canvas.height = img.height;\n ctx.drawImage( img, 0, 0 );\n resolve();\n })\n}", "function resetImage() {\n originalImage.drawTo(canvas);\n}", "function img_update () {\ncontexto.drawImage(canvas, 0, 0);\ncontext.clearRect(0, 0, canvas.width, canvas.height);\n}", "function Canvas(canvas, image, baseline, boundingBox) {\n var myCanvas = this;\n\n this.canvas = canvas;\n this.width = canvas.width;\n this.height = canvas.height;\n this.ctx = canvas.getContext('2d');\n\n this.image = image;\n\n this.baseline = baseline;\n this.boundingBox = boundingBox;\n\n this.dragging = false;\n\n this.scale = 1.0;\n\n this.panX = 0;\n this.panY = 0;\n\n this.selectedCC = [];\n\n this.dragoffx = 0;\n this.dragoffy = 0;\n\n this.image.img.onload = function(){\n myCanvas.image.w = this.width;\n myCanvas.image.h = this.height;\n\n\n myCanvas.image.initialx = myCanvas.width/2 - this.width/2;\n myCanvas.image.initialy = myCanvas.height/2 - this.height/2;\n\n myCanvas.image.x = myCanvas.image.initialx;\n myCanvas.image.y = myCanvas.image.initialy;\n\n\n if(this.width > this.height)\n myCanvas.scale = myCanvas.width /this.width;\n else\n myCanvas.scale = myCanvas.height /this.height;\n myCanvas.draw();\n }\n}", "function paint() {\n ctx.save();\n bufferCtx.drawImage(image, 0, 0, slideshow.width, slideshow.height);\n drawCaption(bufferCtx);\n ctx.drawImage(bufferCanvas, 0, 0, slideshow.width, slideshow.height);\n ctx.restore();\n }", "function loadImg(e){\n const reader = new FileReader(); \n reader.onload = function(){\n imgHolder.src = reader.result;\n }\n reader.readAsDataURL(e.target.files[0]);\n setTimeout(setCanvas, 1000);\n }", "function preview(input){\n if(input.files && input.files[0]){\n var reader = new FileReader();\n reader.onload = function (e) {\n $(\"#div-img\").html(\"<img src='\"+e.target.result+\"' class='img-circle img_cambia'>\");\n }\n reader.readAsDataURL(input.files[0]);\n }\n }", "function drawCanvas() {\n\tif (imageId != null) {\n\t\tdrawJointJS(imageId);\n\t\timageId = null;\n\t}\n}", "function Img(canvas) {\n\tthis.canvas = canvas;\n\n\tthis.context = canvas[0].getContext('2d');\n\n\tthis.image = new Image();\n}", "function takePicture(source) {\n //Todo Save th e state of the image on save\n resetElements('block', 'none', false);\n // Draw image to the canvas\n const context = canvas.getContext('2d');\n // reading the name of the object\n let props = LayerElements[image.dataset.name];\n // console.log(props.width, props.height)\n\n // Draw an image source on the canvas\n context.drawImage(source, 0, 0, width, height);\n /* Draw layer to the canvas */\n context.drawImage(image, props.top, props.left, props.width, props.height);\n\n // Create image from the canvas\n const imgUrl = canvas.toDataURL('image/png');\n\n // Set img src\n mainImage.setAttribute('src', imgUrl);\n\n mainImage.style.filter = filter;\n\n currentImg = {\n data: mainImage.src,\n filter,\n }\n\n video.srcObject.getVideoTracks().forEach(track => track.stop())\n // reset image\n image = undefined;\n state.value == 0;\n}", "function preview() {\n var canvas = document.getElementById('preview-canvas');\n var ctx = canvas.getContext(\"2d\"); // we want a 2d canvas to draw on\n for (var i=0; i<16; i++) { // 16 rows\n for (var j=0; j<16; j++) { // 16 cells\n // fetch color from pixel-<row>-<cell> input cell\n ctx.fillStyle = document.getElementById(\"pixel-\"+i+\"-\"+j).style.backgroundColor;\n ctx.fillRect(j,i,1,1); // draw a 1x1 pixel rectangle (i.e. a pixel)\n }\n }\n // generate a data: url representing the image\n document.getElementById(\"save-icon\").value = canvas.toDataURL();\n}", "function openTestImage() {\n\n var base_image = new Image();\n canvas = document.getElementById(\"image-canvas\");\n canvas2 = document.getElementById(\"anno-canvas\");\n context = canvas.getContext(\"2d\");\n // wait for image to load before drawing canvas\n base_image.onload = function () {\n\n canvas.width = base_image.width;\n canvas.height = base_image.height;\n canvas2.width = base_image.width;\n canvas2.height = base_image.height;\n\n context.drawImage(base_image, 0, 0);\n imageOpen = true;\n };\n base_image.src = \"../images/test.jpg\";\n imageType = true;\n document.getElementById('workingFile').innerHTML = \"testing\";\n\n\n }", "function capturePic(){\n cameraSensor.width = cameraView.videoWidth;\n cameraSensor.height = cameraView.videoHeight;\n cameraSensor.getContext(\"2d\").drawImage(cameraView, 0, 0);\n picPreview.src = cameraSensor.toDataURL(\"image/webp\");\n picPreview.classList.add(\"picPreview\");\n}", "function convertImageToCanvas(image) {\n var canvas = document.createElement(\"canvas\");\n canvas.width = image.width;\n canvas.height = image.height;\n canvas.getContext(\"2d\").drawImage(image, 0, 0);\n \n return canvas;\n }", "function drawImgOnCanvas(imgId) {\n hideAbout();\n showMeme(); //show meme hide gallery\n var userTextPref = memeChoise.text\n memeChoise.upperCase ? userTextPref = userTextPref.toUpperCase() : ''; //if upper case\n //if shadow\n var ctx = gCanvas.getContext('2d');\n var img = new Image();\n img.src = memeChoise.url;\n ctx.clearRect(0, 0, gCanvas.width, gCanvas.height);\n\n img.onload = function () {\n ctx.drawImage(img, 0, 0, gCanvas.width, gCanvas.height);\n ctx.font = memeChoise.fontwight + \" \" + memeChoise.fontSize + \" \" + memeChoise.fontFamily;\n ctx.shadowColor = 'black';\n memeChoise.textShadow ? ctx.shadowBlur = 30 : ctx.shadowBlur = 0;\n ctx.fillStyle = memeChoise.fontColor;\n ctx.strokeText(userTextPref, memeChoise.positionX, memeChoise.positionY);\n ctx.fillText(userTextPref, memeChoise.positionX, memeChoise.positionY);\n };\n}", "function save_Canvas_Changes(){\n\t\t canvasHistory.push(postCardCanvasContext.getImageData(0, 0, postCardCanvas.width, postCardCanvas.height));\n\t\t canvasHistoryPointer++;\n\t }", "function drawImageScaled(img, canvas, ctx) {\n let scale = Math.min(canvas.width / img.width, canvas.height / img.height);\n // get the top left position of the image\n ctx.clearRect(0, 0, canvas.width, canvas.height);\n let x = (canvas.width / 2) - (img.width / 2) * scale;\n let y = (canvas.height / 2) - (img.height / 2) * scale;\n ctx.drawImage(img, x, y, img.width * scale, img.height * scale);\n}", "function img_update () {\n contexto.drawImage(canvas, 0, 0);\n\t\tcontext.clearRect(0, 0, canvas.width, canvas.height);\n }", "function preview() {\n currentImg.textContent = newIndex + 1; //passing current img index to currentImg varible with adding +1\n let imageURL = gallery[newIndex].src; //getting user clicked img url\n previewImg.src = imageURL; //passing user clicked img url in previewImg src\n }", "function readFileCurved() {\n\n if (this.files && this.files[0]) {\n\n var FR = new FileReader();\n\n FR.addEventListener(\"load\", function (e) {\n var imaaag = document.getElementById(\"preview\").src = e.target.result;\n\n var img = new Image();\n img.src = e.target.result;\n\n\n var cvs = canvas;\n var context = cvs.getContext('2d');\n\n console.log(img.height, img.width);\n \n img.onload = function() {\n\n var x1 = img.width / 2;\n var x2 = img.width;\n var y1 = 20; // curve depth\n var y2 = 0;\n\n var eb = (y2*x1*x1 - y1*x2*x2) / (x2*x1*x1 - x1*x2*x2);\n var ea = (y1 - eb*x1) / (x1*x1);\n\n // variable used for the loop\n var currentYOffset;\n\n console.log(img.width, img.height, eb, ea);\n\n for(var x = 0; x < img.width; x++) {\n\n // calculate the current offset\n currentYOffset = 120 + (ea * x * x) + eb * x;\n\n context.drawImage(img,x + 30,0,1,img.height,x + 30,currentYOffset,1,img.height);\n }\n\n\n var perspectiveImage = new Image();\n\n perspectiveImage.onload = function() {\n perspectiveImage.src=cvs.toDataURL();\n console.log(cvs.toDataURL());\n\n fabric.Image.fromURL(perspectiveImage.src, function (myImg) {\n //i create an extra var for to change some image properties\n var img1 = myImg.set({\n left: 30,\n top: 50,\n });\n cvs.add(myImg);\n });\n }\n }\n\n\n\n\n document.getElementById(\"preview\").src = e.target.result;\n });\n FR.readAsDataURL(this.files[0]);\n }\n}", "function onImageClick(imageId) {\n setMemeImgId(imageId)\n drawImgFromlocal(imageId);\n setTimeout(function () {\n document.querySelector('.header2').style.display = 'none';\n document.querySelector('main').style.display = 'none';\n document.querySelector('.my-info').style.display = 'none';\n document.querySelector('.canvas-btn-container').style.display = 'flex';\n resizeCanvas();\n }, 10)\n}", "draw(ctx, camera) {\r\n ctx.drawImage(this.image, this.x - camera.x, this.y - camera.y);\r\n }", "function initPreview() {\n\t\n\t//clear the canvas first\n\tcanvasPreviewContext.clearRect(0, 0, canvasPreview.width, canvasPreview.height);\n\t\n\t//what file type are we dealing with\n\tif (fileType == \"VIDEO\") {\n\t\t\n\t\tsampleWidth = 50;\n\t\tsampleHeight = Math.floor((9/16)*sampleWidth);\n\t\tvideoArea.width = sampleWidth;\n\t\tvideoArea.height = sampleHeight;\n\t\t\n\t\t//reset size of the canvas\n\t\tcanvasPreview.width = sampleWidth;\n\t\tcanvasPreview.height = sampleHeight;\n\t\tpreviewArea.style.width = sampleWidth + \"px\";\n\t\tpreviewArea.style.height = sampleHeight + \"px\";\n\t\t\n\t\t//set the video in the videoArea so it starts playing\n\t\tvideoArea.type = file.type;\n\t\tvideoArea.src = fileURL;\n\t\t\n\t\t//set fileWidth\n\t\tfileWidth = sampleWidth;\n\t\tfileHeight = sampleHeight;\n\t\t\n\t\t//make a sample first\n\t\t/*canvasPreviewContext.drawImage(videoArea, 0, 0, videoArea.width, videoArea.height);*/\n\t\t\n\t\t//initBuffers();\n\t\t\n\t\t\n\t\t/*document.onclick = function() {\n\t\t\tinitCubes();\n\t\t}*/\n\t\t\n\t\t//keep updating cubes based on the options\n\t\t//startUpdateCubesInterval();\n\t\tsetTimeout(initPlanes, 2000);\n\t\tstartUpdatePlanesInterval();\n\t\tstopUpdateCubesInterval();\n\t\t\n\t\t//keep rendering the screen based on mouse/camera position\n\t\tstartThreeInterval();\n\n\t\t\n\t} else if (fileType == \"IMAGE\") {\n\t\t\n\t\t\n\t\tsampleWidth = 30;\n\t\tsampleHeight = Math.floor((9/16)*sampleWidth);\n\t\t\n\t\t//load the image data and display in the preview\n\t\tvar img = new Image();\n\t\timg.onload = function() {\n\n\t\t\t//get the image dimensions so we can drawImage at the right aspect ratio\n\t\t\tsetNewFileDimensions(img);\n\t\t\t\n\t\t\t//draw the image onto the canvas\n\t\t canvasPreviewContext.drawImage(img, 0, 0, fileWidth, fileHeight);\n\t\t\t\n\t\t\t//initBuffers();\n\t\t\tinitCubes();\n\t\t\t//initPlanes();\n\t\t\t\n\t\t\t//keep updating cubes based on the options\n\t\t\tstartUpdateCubesInterval();\n\t\t\tstopUpdatePlanesInterval();\n\t\t\t\n\t\t\t//keep rendering the screen based on mouse/camera position\n\t\t\tstartThreeInterval();\n\n\t\t}\n\t\t\n\t\t//set the src of our new file\n\t\timg.src = fileURL;\n\t\t\n\t\t//we should clear the video tag\n\t\tvideoArea.type = \"\";\n\t\tvideoArea.src = \"\";\n\t\tvideoArea.pause();\n\t\t\n\t\t//we should stop sampling the video if its there\n\t\tstopSamplingVideo();\n\t\t\n\t}\n\t\n}", "function Render(image) {\n selectedImage = image;\n //setup canvas for paper API\n setupPaperCanvas();\n //setup and fill image\n setupPaperImage();\n //setup and fill texts\n setupPaperTexts();\n}", "function preview() {\n currentImg.textContent = newIndex + 1; //passing current img index to currentImg varible with adding +1\n let imageURL = gallery[newIndex].querySelector(\"img\").src; //getting user clicked img url\n previewImg.src = imageURL; //passing user clicked img url in previewImg src\n }", "function loadForegroundImage(){\n //get input from text input\n var fileinput = document.getElementById(\"foreinput\");\n fgcanvas = document.getElementById(\"canvf\");\n \n //create the selected image\n fgImage = new SimpleImage(fileinput);\n // show on the canvas\n fgImage.drawTo(fgcanvas);\n}", "function imagePreview(src){\n\t\t\n\t\t/* Remove preview */\n\t\timgPreview.getElement().setHtml(\"\");\n\t\t\n\t\tif(src == \"base64\") {\n\t\t\t\n\t\t\t/* Disable Checkboxes */\n\t\t\tif(urlCB) urlCB.setValue(false, true);\n\t\t\tif(fileCB) fileCB.setValue(false, true);\n\t\t\t\n\t\t} else if(src == \"url\") {\n\t\t\t\n\t\t\t/* Ensable Image URL Checkbox */\n\t\t\tif(urlCB) urlCB.setValue(true, true);\n\t\t\tif(fileCB) fileCB.setValue(false, true);\n\t\t\t\n\t\t\t/* Load preview image */\n\t\t\tif(urlI) imagePreviewLoad(urlI.getValue());\n\t\t\t\n\t\t} else if(fsupport) {\n\t\t\t\n\t\t\t/* Ensable Image File Checkbox */\n\t\t\tif(urlCB) urlCB.setValue(false, true);\n\t\t\tif(fileCB) fileCB.setValue(true, true);\n\t\t\t\n\t\t\t/* Read file and load preview */\n\t\t\tvar fileI = t.getContentElement(\"tab-source\", \"file\");\n\t\t\tvar n = null;\n\t\t\ttry { n = fileI.getInputElement().$; } catch(e) { n = null; }\n\t\t\tif(n && \"files\" in n && n.files && n.files.length > 0 && n.files[0]) {\n\t\t\t\tif(\"type\" in n.files[0] && !n.files[0].type.match(\"image.*\")) return;\n\t\t\t\tif(!FileReader) return;\n\t\t\t\timgPreview.getElement().setHtml(\"Loading...\");\n\t\t\t\tvar fr = new FileReader();\n\t\t\t\tfr.onload = (function(f) { return function(e) {\n\t\t\t\t\timgPreview.getElement().setHtml(\"\");\n\t\t\t\t\timagePreviewLoad(e.target.result);\n\t\t\t\t}; })(n.files[0]);\n\t\t\t\tfr.onerror = function(){ imgPreview.getElement().setHtml(\"\"); };\n\t\t\t\tfr.onabort = function(){ imgPreview.getElement().setHtml(\"\"); };\n\t\t\t\tfr.readAsDataURL(n.files[0]);\n\t\t\t}\n\t\t}\n\t}", "function drawImageScaled(img, canvas, ctx) {\n // get the scale\n let scale = Math.min(canvas.width / img.width, canvas.height / img.height);\n // get the top left position of the image\n ctx.clearRect(0, 0, canvas.width, canvas.height);\n let x = (canvas.width / 2) - (img.width / 2) * scale;\n let y = (canvas.height / 2) - (img.height / 2) * scale;\n ctx.drawImage(img, x, y, img.width * scale, img.height * scale);\n\n\n}", "drawImage() {\n\tif (this.props.images.length) {\n\t this.props.images[this.state.nextImageIndex].drawImage(this.refs.canvas, this.props.level, this.props.window, this.props.maskColours)\n\t this.state.currImageIndex = this.state.nextImageIndex\n\t}\n }", "function renderImageToCanvas(img, canvas, options, doSquash) {\n var iw = img.naturalWidth, ih = img.naturalHeight;\n var width = options.width, height = options.height;\n var ctx = canvas.getContext('2d');\n ctx.save();\n transformCoordinate(canvas, width, height, options.orientation);\n var subsampled = detectSubsampling(img);\n if (subsampled) {\n iw /= 2;\n ih /= 2;\n }\n var d = 1024; // size of tiling canvas\n var tmpCanvas = document.createElement('canvas');\n tmpCanvas.width = tmpCanvas.height = d;\n var tmpCtx = tmpCanvas.getContext('2d');\n var vertSquashRatio = doSquash ? detectVerticalSquash(img, iw, ih) : 1;\n var dw = Math.ceil(d * width / iw);\n var dh = Math.ceil(d * height / ih / vertSquashRatio);\n var sy = 0;\n var dy = 0;\n while (sy < ih) {\n var sx = 0;\n var dx = 0;\n while (sx < iw) {\n tmpCtx.clearRect(0, 0, d, d);\n tmpCtx.drawImage(img, -sx, -sy);\n ctx.drawImage(tmpCanvas, 0, 0, d, d, dx, dy, dw, dh);\n sx += d;\n dx += dw;\n }\n sy += d;\n dy += dh;\n }\n ctx.restore();\n tmpCanvas = tmpCtx = null;\n }", "function showImage(input){\n if(input.files && input.files[0]){\n \n // Read the image to load it in \n var reader = new FileReader();\n\n // Call the onload function when the reader starts reading in the next line.\n reader.onload = function(e){\n $(\"#image\")\n .attr(\"src\",e.target.result)\n .Jcrop({\n // updateCoords will be called whenever the selector box is altered or moved(dragged).\n onChange: updateCoords,\n onSelect: updateCoords,\n\n // Set the width for the image which in turn will set the scale for the image automatically.\n boxWidth: 450, boxHeight: 400\n },function(){\n\n // Save the current jcrop instance for setting rotate variable in above functions.\n jcrop_api = this;\n }); \n\n };\n\n // Load the image to the image tag.\n reader.readAsDataURL(input.files[0]);\n }\n }", "function preview(){\r\n currentImg.textContent = newIndex + 1; //passing current img index to currentImg varible with adding +1\r\n let imageURL = gallery[newIndex].querySelector(\"img\").src; //getting user clicked img url\r\n previewImg.src = imageURL; //passing user clicked img url in previewImg src\r\n }", "function draw() {\n // clear the canvas\n that.canvas.width = that.canvas.width;\n\n // check if we have a valid image\n if (that.image.width * that.image.height > 0) {\n context.drawImage(that.image, 0, 0, that.width, that.height);\n } else {\n // center the error icon\n context.drawImage(errorIcon.image, (that.width - (that.width / 2)) / 2,\n (that.height - (that.height / 2)) / 2, that.width / 2, that.height / 2);\n that.emit('warning', 'Invalid stream.');\n }\n\n // check for an overlay\n if (overlay) {\n context.drawImage(overlay, 0, 0);\n }\n\n // silly firefox...\n if (navigator.userAgent.toLowerCase().indexOf('firefox') > -1) {\n var aux = that.image.src.split('?killcache=');\n that.image.src = aux[0] + '?killcache=' + Math.random(42);\n }\n }", "function set_Image_on_Canvas(data, rows, cols){\n let image = Array.from({length: rows*cols*4});\n for(let i=0; i<rows; i++){\n for(let j=0; j<cols; j++){\n for(let k=0; k<4; k++){\n image[(i*cols + j)*4 + k] = data[i][j][k];\n }\n }\n }\n context.clearRect(0, 0, editor.width, editor.height);\n let image_data = context.createImageData(cols, rows);\n image_data.data.set(image);\n editor.width = cols;\n editor.height = rows;\n context.putImageData(image_data, 0, 0);\n }", "function takePicture() {\n $('.countdown').show();\n countdown(COUNTDOWNLENGTH);\n setTimeout(function() {\n PhotoBooth.image.getContext('2d')\n .drawImage(PhotoBooth.localVideo, 0, 0,\n PhotoBooth.image.width,\n PhotoBooth.image.height);\n PhotoBooth.preview.getContext('2d')\n .drawImage(PhotoBooth.image, 0, 0, 160, 120);\n $('#preview').show();\n }, COUNTDOWN_TIMEOUT);\n}", "handleFileChosen(e) {\n\n const file = e.target.files[0];\n const reader = new FileReader();\n\n reader.onload = (f) => {\n\n var data = f.target.result;\n fabric.Image.fromURL(data, (img) => {\n\n const canvas = this.state.canvas;\n\n var oImg = img.set({left: 10, \n top: 10, angle: 0}).scale(0.8);\n canvas.add(oImg).renderAll();\n\n this.setState({canvas: canvas});\n });\n };\n\n reader.readAsDataURL(file);\n }", "function showArticleContent(canvas, article) {\n var imageInfo = getImageConfig(article);\n var imageAnnotations = getImageAnnotations(article);\n var imageHighlights = getImageHighlights(article, function(idx) {\n canvas.focusOnZone(idx);\n });\n canvas.setImage({\n image : imageInfo,\n annotations : imageAnnotations,\n highlights : imageHighlights\n });\n }", "function convertCanvasToImage(canvas) {\n var image = new Image();\n image.src = canvas.toDataURL(\"image/png\");\n return image;\n }", "function CanvasImage(width, height)\n{\n // create a new canvas element of requested dimensions\n this.canvas = document.createElement('canvas');\n this.canvas.width = width;\n this.canvas.height = height;\n // store the context for ease of access\n this.ctx = this.canvas.getContext('2d');\n // flag the canvas to be redrawn the first time\n this.forceDraw = true;\n}", "function imagesPreview(input) {\n var cropper;\n galleryImagesContainer.innerHTML = '';\n var img = [];\n if(cropperImageInitCanvas.cropper){\n cropperImageInitCanvas.cropper.destroy();\n cropImageButton.style.display = 'none';\n cropperImageInitCanvas.width = 0;\n cropperImageInitCanvas.height = 0;\n }\n if (input.files.length) {\n var i = 0;\n var index = 0;\n for (let singleFile of input.files) {\n var reader = new FileReader();\n reader.onload = function(event) {\n var blobUrl = event.target.result;\n img.push(new Image());\n img[i].onload = function(e) {\n // Canvas Container\n var singleCanvasImageContainer = document.createElement('div');\n singleCanvasImageContainer.id = 'singleImageCanvasContainer'+index;\n singleCanvasImageContainer.className = 'singleImageCanvasContainer';\n // Canvas Close Btn\n var singleCanvasImageCloseBtn = document.createElement('button');\n var singleCanvasImageCloseBtnText = document.createTextNode('Close');\n // var singleCanvasImageCloseBtnText = document.createElement('i');\n // singleCanvasImageCloseBtnText.className = 'fa fa-times';\n singleCanvasImageCloseBtn.id = 'singleImageCanvasCloseBtn'+index;\n singleCanvasImageCloseBtn.className = 'singleImageCanvasCloseBtn';\n singleCanvasImageCloseBtn.onclick = function() { removeSingleCanvas(this) };\n singleCanvasImageCloseBtn.appendChild(singleCanvasImageCloseBtnText);\n singleCanvasImageContainer.appendChild(singleCanvasImageCloseBtn);\n // Image Canvas\n var canvas = document.createElement('canvas');\n canvas.id = 'imageCanvas'+index;\n canvas.className = 'imageCanvas singleImageCanvas';\n canvas.width = e.currentTarget.width;\n canvas.height = e.currentTarget.height;\n canvas.onclick = function() { cropInit(canvas.id); };\n singleCanvasImageContainer.appendChild(canvas)\n // Canvas Context\n var ctx = canvas.getContext('2d');\n ctx.drawImage(e.currentTarget,0,0);\n // galleryImagesContainer.append(canvas);\n galleryImagesContainer.appendChild(singleCanvasImageContainer);\n while (document.querySelectorAll('.singleImageCanvas').length == input.files.length) {\n var allCanvasImages = document.querySelectorAll('.singleImageCanvas')[0].getAttribute('id');\n cropInit(allCanvasImages);\n break;\n };\n urlConversion();\n index++;\n };\n img[i].src = blobUrl;\n i++;\n }\n reader.readAsDataURL(singleFile);\n }\n // addCropButton();\n // cropImageButton.style.display = 'block';\n }\n }", "function takepicture() {\n var context = canvas.getContext('2d');\n if (width && height) {\n canvas.width = width;\n canvas.height = height;\n context.drawImage(video, 0, 0, width, height);\n \n var data = canvas.toDataURL('image/png');\n photo.setAttribute('src', data);\n } else {\n clearphoto();\n }\n }", "draw() {\n // Displaying the image\n image(experimentImage, 0, 0, width, height);\n }", "function onloadCallback(current_image) {\n\t\t//set the image as the background image of the canvas wrapper\n\t\t$('#canvas-wrapper').css('background', 'url(' + current_image.path +') no-repeat center center fixed').css('background-size', 'contain');\n\t}", "function showHTML5Pic() {\n // get a reference to the current \"pic\" image\n let img = document.getElementById(\"pic\");\n \n // clear the full canvas and then draw the canvas image from the \"pic\" image control\n ctx.clearRect(0, 0, canvas.width, canvas.height);\n \n // draw the canvas image using the \"pic\" version\n // start the image in the upper left hand corner and use current width and height\n // see HTML5_Pic.html for example showing how to do this\n ctx.drawImage(img, 0, 0, objArray[xPic].width, objArray[xPic].height);\n \n // using the currently selected picture object, display the name, width and height properties\n // in the 3 text boxes\n document.getElementById(\"txtName\").value = objArray[xPic].name;\n document.getElementById(\"txtWidth\").value = objArray[xPic].width;\n document.getElementById(\"txtHeight\").value = objArray[xPic].height;\n}" ]
[ "0.7068751", "0.703547", "0.6917276", "0.65423286", "0.6540519", "0.6521173", "0.6430351", "0.6376947", "0.62819546", "0.61796707", "0.617064", "0.61630005", "0.6132825", "0.61168927", "0.6071252", "0.606842", "0.6022635", "0.59700596", "0.5935048", "0.5898193", "0.58706063", "0.58701587", "0.586987", "0.5859282", "0.58546484", "0.5832115", "0.5820728", "0.58139277", "0.5795405", "0.5793206", "0.5770946", "0.57655555", "0.5764362", "0.5753933", "0.57523745", "0.575163", "0.57417387", "0.5729896", "0.5727965", "0.5709695", "0.5708371", "0.57068384", "0.5703443", "0.5703443", "0.570039", "0.5692684", "0.5679541", "0.56578207", "0.56489235", "0.56410784", "0.56387633", "0.5638444", "0.56345725", "0.56294936", "0.56290746", "0.5618365", "0.5606429", "0.5599019", "0.55928224", "0.5590094", "0.55822325", "0.5561249", "0.5548704", "0.55461484", "0.55428535", "0.5539626", "0.5537671", "0.55334985", "0.5530682", "0.5522367", "0.55164254", "0.5506582", "0.55056447", "0.55017173", "0.5491433", "0.54883057", "0.54789996", "0.54778755", "0.5473901", "0.5454178", "0.5447768", "0.5445422", "0.54446876", "0.544082", "0.5437943", "0.5437211", "0.5430459", "0.54276454", "0.5427277", "0.5425227", "0.54188186", "0.54134583", "0.5400506", "0.5397323", "0.53968406", "0.5392059", "0.5391831", "0.5388825", "0.5386503", "0.538618" ]
0.81001174
0
! List of character from labelised Component \class ListCharacter
function ListCharacter(){ this.list = new Map(); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function parseCharList() {\n CST.addBranchNode(\"CharList\");\n if (match([\"T_char\"], false, false) || match([\"T_space\"], false, false)) {\n parseCharList();\n }\n else {\n }\n log(\"Character List\");\n CST.backtrack();\n}", "function addCharacterToList(charString) {\n // create list string\n // listString = charString + \" (\" + characterPositionsMap.get(charString) + \") (사렌과의 거리: \" + characterRelativePositionsMap.get(charString) + \")\";\n listString = charString + \" (사렌과의 거리: \" + characterRelativePositionsMap.get(charString) + \")\";\n // create list entry\n var li = document.createElement(\"li\");\n // set id to be the character name\n li.setAttribute(\"id\",charString);\n // set list class\n li.className = \"list-group-item text-center\";\n // create entry item\n li.appendChild(document.createTextNode(listString));\n // add entry to the list\n sarenList.appendChild(li);\n // register character to the displayed character list\n displayedCharacters.push(charString);\n}", "function getCharacterListUl() {\n return document.querySelector(\"ul.character-list\");\n}", "function lexCharList() {\n\t\tif(errorB) {\n\t\t\terrorB = errorB;\n\t\t}\n\t\telse if(matchWhite()) {\n\t\t\tif(!matchNewLine() && !matchTab()) {\n\t\t\t\ttotalTokens = totalTokens + 1;\n\t\t\t\tputMessage(\"Found space: \\t\" + lexString.charAt(0));\n\t\t\t\ttokens[tokenIndex] = {type: \"space\", value: lexString.charAt(0), line: lineCount};\n\t\t\t\tlexString = lexString.slice(1, lexString.length);\n\t\t\t\ttokenIndex = tokenIndex + 1;\n\t\t\t\tlexCharList();\n\t\t\t}\n\t\t\telse {\n\t\t\t\t// put error message here\n\t\t\t\tputMessage(\"Error: Tabs/New Lines not allowed in Character List\");\n\t\t\t\tputMessage(\"(line \" + lineCount + \")\");\n\t\t\t\tlexString = lexString.slice(1, lexString.length);\n\t\t\t\terrorB = true;\n\t\t\t}\n\t\t}\n\t\telse if(matchChar()) {\n\t\t\ttotalTokens = totalTokens + 1;\n\t\t\tputMessage(\"Found character: \\t\" + lexString.charAt(0));\n\t\t\ttokens[tokenIndex] = {type: \"char\", value: lexString.charAt(0), line: lineCount};\n\t\t\tlexString = lexString.slice(1, lexString.length);\n\t\t\ttokenIndex = tokenIndex + 1;\n\t\t\tlexCharList();\n\t\t}\n\t\telse if(matchQuote()) {\n\t\t\tputMessage(\"Found symbol: \\t\\t\" + \"\\\"\");\n\t\t\ttokens[tokenIndex] = {type: \"symbol\", value: \"\\\"\", line: lineCount};\n\t\t\tlexString = lexString.slice(1, lexString.length);\n\t\t\ttokenIndex = tokenIndex + 1;\n\t\t\ttotalTokens = totalTokens + 1;\n\t\t}\n\t\telse {\n\t\t\t// put error message here\n\t\t\tputMessage(\"Error: \\\"\" + lexString.charAt(0) + \"\\\" not allowed in Character List\");\n\t\t\tputMessage(\"(line \" + lineCount + \")\");\n\t\t\tlexString = lexString.slice(1, lexString.length);\n\t\t\terrorB = true;\n\t\t}\n\t}", "function removeCharacterFromList(charString) {\n // get designated item\n var li = document.getElementById(charString);\n // remove from the list\n sarenList.removeChild(li);\n // remove character from the displayed character list\n displayedCharacters = displayedCharacters.filter(function(value, index, arr) { return value != charString; });\n}", "function appendCharacterToView( character ) {\n var html = '<li data-' + charIDAttr + '=\"' + character.id + '\">';\n html += '<input type=\"checkbox\">\\n';\n html += character.name;\n html += \"</li>\";\n\n $list.append( html );\n }", "function listChars() {\n\t$('body,html').removeClass('fixWidth');\n\tclearTables();\n\tdocument.getElementById(\"News\").style.display = \"none\";\n\tdocument.getElementById(\"sidebar\").style.display = \"none\";\n\t\n\tvar table = document.getElementById(\"characters\");\n\tvar sortedChars = [];\n\tvar insertAt;\n\t\n\tif (!table) {\n\t\ttable = document.createElement(\"table\");\n\t\ttable.id = \"characters\";\n\t\tdocument.getElementById(\"customTables\").appendChild(table);\n\t\ttable.style.display = \"block\";\n\t}\n\t\n\tvar row = table.insertRow(-1);\n\t\n\tfor (var key in charList) {\n\t\tinsertAt = sortedChars.length;\n\t\tfor (var i = 0; i < sortedChars.length; i++) {\n\t\t\tif (key < sortedChars[i]) {\n\t\t\t\tinsertAt = i;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tsortedChars.splice(insertAt, 0, key);\n\t}\n\t\n\tvar mainContainer = $(\"<div id='charList' class='mainTable col-xs-14 row'></div>\");\n\tvar container = $(\"<div class='col-xs-16'></div>\");\n\tfor (var i = 0; i < sortedChars.length; i++) {\n\t\tvar id = \"charList-\" + cleanKey(sortedChars[i]);\n\t\tvar tAdd = \"\";\n\t\tif (arrayContains(ownedChars, sortedChars[i]))\n\t\t\ttAdd = \"Owned\";\n\t\tcontainer.append(\"<div id='\" + id + \"' class='col-xs-3 th charPic charBox' onclick='javascript:charOverview(\\\"\" + cleanKey(sortedChars[i]) + \"\\\")'>\" + sortedChars[i] + \" (\" + charList[sortedChars[i]][\"realm\"] + \")\" + \"<img src='\" + charList[sortedChars[i]][\"image\"] + \"'/>\" + tAdd + \"</div>\");\n\t}\n\t$(mainContainer).append(container);\n\t$(\"#customTables\").append(mainContainer);\n\t\n\tvar $charList = $(\"[id^=charList-]\");\n\t$charList.each(function() {\n\t\t$(this).hover(function() {$(this).toggleClass('thHover')});\n\t});\n}", "setupLetterToBeDisplayed(){\r\n // Check if character is alphabet letter\r\n const matchAlphabetCharacter = /[a-z]/i\r\n const matchSpace = /\\s/g\r\n let textNode\r\n let li\r\n\r\n for (var i =0; i < this.phrase.length; i++){\r\n li = document.createElement('LI');\r\n if (this.phrase.charAt(i).match(matchAlphabetCharacter)){\r\n textNode = document.createTextNode(this.phrase.charAt(i))\r\n li.className = 'letter'\r\n li.setAttribute('id', this.phrase.charAt(i))\r\n li.appendChild(textNode)\r\n phraseDisplayUL.appendChild(li)\r\n } else if (this.phrase.charAt(i).match(matchSpace)){\r\n textNode = document.createTextNode(' ')\r\n li.className = 'space'\r\n li.appendChild(textNode)\r\n phraseDisplayUL.appendChild(li)\r\n }\r\n }\r\n }", "function updateList(searchedCharacters) {\n\n // add saren to the character titles list\n if(searchedCharacters.includes(\"사렌\") == false) {\n searchedCharacters.push(\"사렌\");\n }\n\n // initialize character position dictionary\n var searchedCharactersDictionary = [];\n\n // add all searched characters to the dictionary\n for(var j=0; j < searchedCharacters.length; j++) {\n searchedCharactersDictionary.push([characterPositionsMap.get(searchedCharacters[j]), searchedCharacters[j]]);\n }\n searchedCharactersDictionary.sort();\n\n // clear character positions list\n clearList();\n\n // create the character positions list from the dictionary\n for(var j=0; j < searchedCharactersDictionary.length; j++) {\n addCharacterToList(searchedCharactersDictionary[j][1]);\n }\n\n // highlight character positions list\n highlightList();\n\n}", "function loadCharacters(data) {\n data.forEach((item) => {\n characters.push(item);\n });\n}", "getCharacters(){\n const characters = [\n 'images/char-boy.png',\n 'images/char-horn-girl.png',\n 'images/char-pink-girl.png',\n 'images/char-princess-girl.png',\n 'images/char-cat-girl.png'\n ];\n\n return characters;\n }", "static parseCharList(parseTokens) {\n _Functions.log(\"PARSER - parseCharList()\");\n CSTTree.addNode(\"CharList\", \"branch\");\n if (parseTokens[tokenPointer] === \" \") {\n this.parseSpace(parseTokens);\n }\n else if (characters.test(parseTokens[tokenPointer])) {\n let string = \"\";\n //Builds string until there is a quote.\n while (!quotes.test(parseTokens[tokenPointer])) {\n //this.parseChar(parseTokens);\n string += parseTokens[tokenPointer];\n tokenPointer++;\n }\n _Functions.log(\"PARSER - String: \" + string);\n this.parseString(parseTokens, string);\n }\n else {\n //Not an empty else, represents do nothing.\n }\n CSTTree.climbTree();\n }", "renderList() {\n const lineDistance = this.opts.get('lineDistance');\n const itemCount = this.innerHeight / lineDistance;\n\n for (let i = 1; i <= itemCount; i += 1) {\n const text = document.createElementNS('http://www.w3.org/2000/svg', 'text');\n text.setAttribute('class', 'list-item');\n text.setAttribute('font-size', this.opts.get('listFontSize'));\n text.setAttribute('text-anchor', 'start');\n text.setAttribute('dominant-baseline', 'central');\n text.setAttribute('mask', `url(#${this.id}_clip)`);\n text.setAttribute('x', this.xOffset + lineDistance / 8);\n text.setAttribute('y', lineDistance * i + this.yContentOffset - lineDistance * 0.5);\n text.textContent = this.getListChars(i);\n this.root.appendChild(text);\n }\n }", "addPhraseToDisplay() {\r\n const characters = this.phrase.split('');\r\n const phraseDiv = document.querySelector('#phrase ul')\r\n characters.forEach(character => {\r\n const letter = document.createElement('li');\r\n if (character == ' ') {\r\n letter.setAttribute(\"class\", \"space\");\r\n } else {\r\n letter.setAttribute(\"class\", ` hide letter ${character}`);\r\n }\r\n letter.innerHTML = character;\r\n phraseDiv.appendChild(letter);\r\n });\r\n return characters\r\n }", "function GetCharacters(){\n\n const [characterDisplay, setCharacterDisplay] = useState([])\n\n useEffect(() => {\n fetch(\"http://localhost:3000/characters\")\n .then((r) => r.json())\n .then(data => setCharacterDisplay(data));\n}, [])\n \n return(\n <div>\n <h2>The Office Characters</h2>\n <ul>\n {characterDisplay.map((character) => <CharacterItem character={character} />)}\n </ul>\n </div>\n )\n}", "function clearList() {\n // read number of displayed characters\n var charactersLength = displayedCharacters.length;\n // remove all displayed characters\n for(var j=0; j < charactersLength; j++) {\n removeCharacterFromList(displayedCharacters[0]);\n }\n}", "function showAllCharac() {\n charactersAPI.getFullList()\n .then(allCharac => {\n \n let html = \"\"\n allCharac.data.forEach(elm => {\n html += `<div class=\"character-info\">\n <div class=\"name\">Character Name: <span>${elm.name}</span></div>\n <div class=\"occupation\">Character Occupation: <span>${elm.occupation}</span></div>\n <div class=\"cartoon\">Is a Cartoon?: <span>${elm.cartoon}</span></div>\n <div class=\"weapon\">Character Weapon: <span>${elm.weapon}</span></div>\n </div>`\n document.querySelector('.characters-container').innerHTML = html\n })\n })\n .catch(err => console.log(`Error: ${err}`))\n}", "getFullList() {\n \n return this.axios\n .get('/characters')\n \n }", "addPhraseToDisplay() {\r\n const ul = document.querySelector('#phrase ul');\r\n const letter = this.phrase.split(\"\");\r\n console.log(letter);\r\n for (let i = 0; i < letter.length; i += 1) {\r\n if (letter[i] !== \" \") {\r\n const li = document.createElement('li');\r\n li.textContent = letter[i];\r\n li.classList.add('letter');\r\n ul.appendChild(li);\r\n } else {\r\n const li = document.createElement('li');\r\n li.classList.add('space');\r\n ul.appendChild(li);\r\n }\r\n }\r\n }", "function getText(){\n $(function() {\n var myListItems = $('ul').text();\n console.log(myListItems.length);\n console.log(myListItems.charAt(3));\n });\n}", "constructor(props){\n super(props);\n\n this.state = {\n characters: []\n }\n\n this.getCharacters = this.getCharacters.bind(this);\n }", "addPhraseToDisplay() {\r\n const pDiv = document.querySelector(\"#phrase\");\r\n const ul = document.querySelector(\"ul\");\r\n const splitPhrase = this.phrase.split(\"\");\r\n console.log(splitPhrase);\r\n\r\n splitPhrase.forEach((letter) => {\r\n const li = document.createElement(\"li\");\r\n li.textContent = letter;\r\n if (!/^[a-z]$/.test(letter)) {\r\n li.className = \"space\";\r\n } else {\r\n li.className = `hide letter ${letter}`;\r\n }\r\n ul.appendChild(li);\r\n });\r\n console.log(pDiv);\r\n }", "function searchCharactersAndUpdateList() {\n\n // read text entries from the text input form\n var characterInput = inputByText.value.split(\" \");\n\n // remove any empty entry\n characterInput = characterInput.filter(function(value, index, arr) { return value != \"\"; })\n\n // search characters with the text input\n var searchedCharacters = searchRediveCharactersByKeywords(characterInput, characterPositionsTable, characterTitlesMap, searchLimitedByBasicName.checked, searchExactMatch.checked);\n\n // combine it with the character list from the checkboxes\n searchedCharacters = searchedCharacters.concat(searchRediveCharactersFromCheckboxes(characterTitlesArray));\n\n // update character positions list with the searched characters\n updateList(searchedCharacters);\n\n}", "constructor() {\n this.activeCharacters = [];\n }", "function drawCharacter () {\n let ctx = getContext ()\n for (let char of characters) {\n ctx.drawImage(char.image, char.x, char.y, char.width, char.height)\n }\n}", "addPhraseToDisplay() {\n const phraseUl = document\n .getElementById(\"phrase\")\n .getElementsByTagName(\"ul\")[0];\n const splitPhrase = this.phrase.split(\"\");\n let htmlLetters = [];\n splitPhrase.forEach(letter => {\n let li = document.createElement(\"li\");\n phraseUl.append(li);\n li.innerHTML = letter;\n htmlLetters.push(li);\n if (letter === \" \") {\n li.className = \"space\";\n } else {\n li.className = \"letter\";\n }\n });\n }", "render() {\n // Render MUST return valid JSX.\n return (\n <div className={styles.CharacterList}>\n <h1>Rick &amp; Morty </h1>\n <div>\n <form className={styles.searchbarContainer}>\n <input\n type=\"text\"\n placeholder=\"Find character\"\n className={styles.searchbar}\n onChange={this.filterCharacters}\n />\n </form>\n <div className={styles.CharacterWrapper}>\n {this.state.items.map(char => (\n <Character passedCharacter={char} key={char.id} />\n ))}\n </div>\n </div>\n </div>\n );\n }", "function Character(char) {\n \tthis.name = char.name;\n \tthis.deceased = char.deceased\n \tthis.dislike = char.dislike\n \tthis.quote = char.quote\n \tthis.note = char.note\n \tthis.id = char.id\n \tthis.show = char.show\n this.toDom = function() {\n\n const status = (`Status: ${char.deceased ? \"Deceased\" : \"Alive\"}`)\n const hero = (this.dislike ? \"Villain\" : \"Hero\")\n const newCharacter = `<h3> ${this.name} </h3>\n <div> ${this.note} </div>\n <div><em> ${this.quote} </em></div>\n <div> ${status} </div>\n <div> ${hero} </div>`\n\n $(\"#newCharacters\").append(newCharacter);\n $('form').trigger('reset');\n };\n }", "getFullList () {\r\n $.ajax({\r\n url : this.BASE_URL + \"/characters\",\r\n method : \"GET\",\r\n success : displayCharacterCards,\r\n error : handleError,\r\n });\r\n }", "render() {\n\n const style = {\n backGroundColor: 'white',\n font: 'inherit',\n border: '1px solid blue',\n padding: '8px',\n cursor: 'pointer'\n };\n\n //const charArray = [...this.state.textinput];\n\n let charComponents = this.state.textinput.split('').map((ch, index) => { \n return <CharComponent \n name={ch} \n key={index} // we need key property in the list to identify the record in list uniquely.\n click={() => this.deleteCharHandler(index)} // () => function(arguments)\n />\n }); \n\n\n return (\n <div className=\"App\">\n <h1>Hi, I'm a React App</h1>\n <p>Lists and Conditions Example</p>\n <input type=\"text\" onChange={this.displayTextHandler} value = {this.state.textinput}/>\n\n <p>{this.state.textinput}: {this.state.textlength}</p>\n <ValidationComponent textlength={this.state.textlength}></ValidationComponent>\n {charComponents}\n\n </div> \n );\n\n // return React.createElement('div', {className: 'App'}, React.createElement('h1', null, 'I am a React App !!!!'));\n\n }", "function characterDisplay() {\n //display the first character on the page\n characterSelect(characters[0].name, 1, characters[0].class, characters[0].portrait, characters[0].colors.dark, characters[0].colors.light, characters[0].stats);\n //loop through array and append all of the sprite version\n for (var i = 0; i < characters.length; i++) {\n var chibiContainer = $(\"<div>\").addClass(\"character-container\").attr({\n \"data-class\": characters[i].class,\n \"data-key\": i + 1\n });\n var characterImage = $(\"<img>\").attr(\"src\", characters[i].chibi);\n chibiContainer.append(characterImage);\n $(\".character-list\").append(chibiContainer);\n }\n }", "addPhraseToDisplay() {\n const unorderedList = document.querySelector('ul');\n [...this.phrase].forEach(letter => {\n const listItem = document.createElement('li');\n if(letter !== ' '){ \n listItem.classList.add(`hide`);\n listItem.classList.add(`letter`);\n listItem.classList.add(`${letter}`);\n listItem.innerHTML = letter;\n unorderedList.appendChild(listItem);\n } else {\n listItem.classList.add(`space`);\n listItem.innerHTML = ' ';\n unorderedList.appendChild(listItem);\n }\n })\n }", "listNotes() {\n return [\n 'A',\n 'A#',\n 'Bb',\n 'B',\n 'C',\n 'C#',\n 'Db',\n 'D',\n 'D#',\n 'Eb',\n 'E',\n 'E#',\n 'F',\n 'F#',\n 'Gb',\n 'G',\n 'G#',\n 'Ab',\n ]\n }", "function appendCharacterElements(character, index) {\r\n $('#id-' + index).append(`<label class=\"id\">${character.id}</label>`);\r\n $('#name-' + index).append(`<label class=\"name\">${character.name}</label>`);\r\n $('#occupation-' + index).append(`<label class=\"occupation\">${character.occupation}</label>`);\r\n $('#debt-' + index).append(`<label class=\"debt\">${character.debt}</label>`);\r\n $('#weapon-' + index).append(`<label class=\"weapon\">${character.weapon}</label>`);\r\n}", "function addPhraseToDisplay (arr) {\n for (let i = 0; i < arr.length; i++) {\n const li = document.createElement('li');\n const character = arr[i];\n const ul = document.querySelector('#phraseList');\n\n li.appendChild(document.createTextNode(character));\n ul.appendChild(li);\n if (character !== \" \") {\n li.className = 'letter';\n } else {\n li.className = 'space';\n }\n }\n}", "function validateCharListArray(charList){\r\n\t\t\tfor(var i = 0, len = charList.length, item; i < len; i++){\r\n\t\t\t\titem = charList[i];\r\n\t\t\t\t\r\n\t\t\t\t// item should be array\r\n\t\t\t\tif(!Array.isArray(item))\r\n\t\t\t\t\treturn \"Invalid elements of character list \" + (i + 1) + \"th\";\r\n\r\n\t\t\t\t// array should be of 2 items\r\n\t\t\t\tif(item.length !== 2)\r\n\t\t\t\t\treturn \"Expected 2 elements of character list \" + (i + 1) + \"th\";\r\n\r\n\t\t\t\t// item's elements should be string\r\n\t\t\t\tif(typeof(item[0]) + typeof(item[1]) !== \"stringstring\")\r\n\t\t\t\t\treturn \"Elements of character list \" + (i + 1) + \"th are not strings.\";\r\n\r\n\t\t\t\t// item's elements should be one char in length\r\n\t\t\t\tif(item[0].length !== 1 || item[1].length !== 1)\r\n\t\t\t\t\treturn \"Elements of character list \" + (i + 1) + \"th are not of length 1.\";\r\n\r\n\t\t\t\t// check dupes\r\n\t\t\t\tfor(var j = i + 1; j < len; j++)\r\n\t\t\t\t\tif(item[0] === charList[j][0])\r\n\t\t\t\t\t\treturn \"Elements of character list \" + (i + 1) + \" and \" + (j + 1) + \" are duplicate\";\r\n\t\t\t}\r\n\r\n\t\t\treturn \"true\";\r\n\t\t}", "function listCharacters() {\n console.log(\"Characters:\");\n for(var obj in adventuringParty) {\n console.log(\" * \" + adventuringParty[obj].name);\n }\n}", "function addPhraseToDisplay (characterArray) {\n /*\n <ul>\n <li class=\"letter\">A</li>\n <li class=\"letter\">n</li>\n <li class=\"letter\">d</li>\n <li class=\"letter\">y</li>\n </ul>\n \n */\n\nfor (i = 0; i < characterArray.length; i++) {\n const li = document.createElement(\"LI\");\n const character = characterArray[i]\n li.textContent = character;\nif (character !== \" \") {\n li.classList.add('letter');\n} else {\n li.classList.add('space');\n}\n const ul = phrase.getElementsByTagName('ul')[0];\n ul.appendChild(li);\n} \n\n/*\ninput: randomCharacterArray\ninstructions: \nStep 1: Loops through an array of characters.\n a. Inside the loop, for each character in the array, you’ll create a list item, \n b. put the character inside of the list item, \n c. and append that list item to the #phrase ul in your HTML. \n step 2: If the character in the array is a letter and not a space, the function should add the class “letter” to the list item.\n\n*/\n\n}", "renderWords() {\n let count = -1;\n return this.state.words.map((word, i) => {\n return (\n <ul key={i}>\n {word.split(\"\").map((char, j) => {\n count++;\n return (\n <li\n key={count}\n className={\n this.state.charGreyed[count] ? \"char char-used\" : \"char\"\n }\n >\n {char}\n </li>\n );\n })}\n </ul>\n );\n });\n }", "addPhraseToDisplay() {\n\n const phraseUl = document.querySelector('#phrase ul');\n\n for (let letter of this.phrase) {\n const li = document.createElement('li');\n\n if (letter !== ' ') {\n // li.appendChild(divCon);\n // console.log(li);\n li.className = `hide letter ${letter}`;\n li.textContent = `${letter}`\n phraseUl.appendChild(li);\n } else {\n li.className = 'space';\n li.textContent = ' ';\n phraseUl.appendChild(li);\n }\n }\n\n }", "function getCharming() {\n const charming = require('charming')\n const element = document.getElementById('text')\n charming(element, {\n tagName: 'span',\n classPrefix: 'letter'\n })\n // list text to change color\n return element.children\n}", "function listAutoInsertChars(){\r\n\t\tvar arr = Data.charsToAutoInsertUserList,\r\n\t\t\ttable = $(\"#settings table\"),\r\n\t\t\t// used to generate table in loop\r\n\t\t\tthead, tr, inputBox;\r\n\r\n\t\t// clear the table initially\r\n\t\ttable.html(\"\");\r\n\r\n\t\tfor(var i = 0, len = arr.length; i < len; i++)\r\n\t\t\t// create <tr> with <td>s having text as in current array and Remove\r\n\t\t\ttable.appendChild(createTableRow(arr[i].concat(\"Remove\")));\r\n\r\n\t\tif(len === 0)\r\n\t\t\ttable.html(\"None currently. Add new:\");\r\n\t\telse{ // insert character-complement pair <thead> elements\r\n\t\t\tthead = document.createElement(\"thead\");\r\n\t\t\ttr = document.createElement(\"tr\");\r\n\r\n\t\t\ttr.appendChild(document.createElement(\"th\").html(\"Character\"));\r\n\t\t\ttr.appendChild(document.createElement(\"th\").html(\"Complement\"));\r\n\r\n\t\t\tthead.appendChild(tr);\r\n\r\n\t\t\ttable.insertBefore(thead, table.firstChild);\r\n\t\t}\r\n\r\n\t\tinputBox = table.lastChild.firstChild;\r\n\r\n\t\t// if there is no input box present or there is no auto-insert char\r\n\t\tif( !(inputBox && /input/.test(inputBox.html()) || len === 0) )\r\n\t\t\tappendInputBoxesInTable(table);\r\n\t}", "function populateCharArr(){\n for(i = 0; i < characters.length; i++){\n charArr.push(characters[i].name);\n }\n }", "function addPhraseToDisplay(arr) {\n // loop through array of characters\n for (let i = 0; i < arr.length; i++) {\n const letter = arr[i];\n // For each character, create a list item\n const item = document.createElement('li');\n // Put each character inside the list item\n item.textContent = letter;\n\n // Add the appropriate class to the list items\n if (letter !== \" \") {\n item.className = 'letter';\n } else {\n item.className = 'space';\n }\n\n // Append the list item to the DOM (specifically to the #phrase ul )\n ul.appendChild(item);\n }\n}", "function NCList() {\n}", "function cnstr() { // All of the normal singleton code goes here.\n\t\treturn {\n\t\t\tgetChar: function(val, font) {\n\t\t\t\t\n\t\t\t\tif (typeof(font) === 'undefined') {\n\t\t\t\t\tfont = 'bigblock_bold';\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tvar character = false;\n\t\t\t\t\n\t\t\t\tswitch (font) {\n\n\t\t\t\t\tcase 'bigblock_plain':\t\n\n\t\t\t\t\t\tswitch (val) {\n\t\t\n\t\t\t\t\t\t\tcase ' ':\n\t\t\t\t\t\t\t\tcharacter = [];\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tcase 'A':\n\t\t\t\t\t\t\tcase 'a':\n\t\t\t\t\t\t\t\tcharacter = [\n\t\t\t\t\t\t\t\t\t\t{p:2},{p:3},{p:4},{p:9},{p:13},{p:17},{p:18},{p:19},{p:20},{p:21},{p:25},{p:29},{p:33},{p:37}\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];\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tcase 'B':\n\t\t\t\t\t\t\tcase 'b':\n\t\t\t\t\t\t\t\tcharacter = [\n\t\t\t\t\t\t\t\t\t\t{p:1},{p:2},{p:3},{p:4},{p:9},{p:13},{p:17},{p:18},{p:19},{p:20},{p:25},{p:29},{p:33},{p:34},{p:35},{p:36}\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];\n\t\t\t\t\t\t\tbreak;\t\t\t\t\t\n\t\t\n\t\t\t\t\t\t\tcase 'C':\n\t\t\t\t\t\t\tcase 'c':\n\t\t\t\t\t\t\t\tcharacter = [\n\t\t\t\t\t\t\t\t\t\t{p:2},{p:3},{p:4},{p:9},{p:13},{p:17},{p:25},{p:29},{p:34},{p:35},{p:36}\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];\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tcase 'D':\n\t\t\t\t\t\t\tcase 'd':\n\t\t\t\t\t\t\t\tcharacter = [\n\t\t\t\t\t\t\t\t\t\t{p:1},{p:2},{p:3},{p:4},{p:9},{p:13},{p:17},{p:21},{p:25},{p:29},{p:33},{p:34},{p:35},{p:36}\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];\n\t\t\t\t\t\t\tbreak;\n\t\t\n\t\t\t\t\t\t\tcase 'E':\n\t\t\t\t\t\t\tcase 'e':\n\t\t\t\t\t\t\t\tcharacter = [\n\t\t\t\t\t\t\t\t\t\t{p:1},{p:2},{p:3},{p:4},{p:9},{p:17},{p:18},{p:19},{p:25},{p:33},{p:34},{p:35},{p:36}\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t];\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tcase 'F':\n\t\t\t\t\t\t\tcase 'f':\n\t\t\t\t\t\t\t\tcharacter = [\n\t\t\t\t\t\t\t\t\t\t{p:1},{p:2},{p:3},{p:4},{p:9},{p:17},{p:18},{p:19},{p:25},{p:33}\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\tbreak;\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tcase 'G':\n\t\t\t\t\t\t\tcase 'g':\n\t\t\t\t\t\t\t\tcharacter = [\n\t\t\t\t\t\t\t\t\t\t{p:2},{p:3},{p:4},{p:5},{p:9},{p:17},{p:20},{p:21},{p:25},{p:29},{p:34},{p:35},{p:36},{p:37}\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\tbreak;\t\t\t\t\t\n\t\t\n\t\t\t\t\t\t\tcase 'H':\n\t\t\t\t\t\t\tcase 'h':\n\t\t\t\t\t\t\t\tcharacter = [\n\t\t\t\t\t\t\t\t\t\t{p:1},{p:5},{p:9},{p:13},{p:17},{p:18},{p:19},{p:20},{p:21},{p:25},{p:29},{p:33},{p:37}\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\tbreak;\n\t\t\n\t\t\t\t\t\t\tcase 'I':\n\t\t\t\t\t\t\tcase 'i':\n\t\t\t\t\t\t\t\tcharacter = [\n\t\t\t\t\t\t\t\t\t\t{p:2},{p:3},{p:4},{p:11},{p:19},{p:27},{p:34},{p:35},{p:36}\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t];\n\t\t\t\t\t\t\tbreak;\n\t\t\n\t\t\t\t\t\t\tcase 'J':\n\t\t\t\t\t\t\tcase 'j':\n\t\t\t\t\t\t\t\tcharacter = [\n\t\t\t\t\t\t\t\t\t\t{p:5},{p:13},{p:21},{p:25},{p:29},{p:26},{p:34},{p:35},{p:36}\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t];\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tcase 'K':\n\t\t\t\t\t\t\tcase 'k':\n\t\t\t\t\t\t\t\tcharacter = [\n\t\t\t\t\t\t\t\t\t\t{p:1},{p:5},{p:9},{p:12},{p:17},{p:18},{p:19},{p:25},{p:28},{p:33},{p:37}\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t];\n\t\t\t\t\t\t\tbreak;\t\t\t\t\t\n\t\t\n\t\t\t\t\t\t\tcase 'L':\n\t\t\t\t\t\t\tcase 'l':\n\t\t\t\t\t\t\t\tcharacter = [\n\t\t\t\t\t\t\t\t\t\t{p:1},{p:9},{p:17},{p:25},{p:33},{p:34},{p:35},{p:36}\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t];\n\t\t\t\t\t\t\tbreak;\t\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tcase 'M':\n\t\t\t\t\t\t\tcase 'm':\n\t\t\t\t\t\t\t\tcharacter = [\n\t\t\t\t\t\t\t\t\t\t{p:1},{p:5},{p:9},{p:10},{p:12},{p:13},{p:17},{p:19},{p:21},{p:25},{p:29},{p:33},{p:37}\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t];\n\t\t\t\t\t\t\tbreak;\n\t\t\n\t\t\t\t\t\t\tcase 'N':\n\t\t\t\t\t\t\tcase 'n':\n\t\t\t\t\t\t\t\tcharacter = [\n\t\t\t\t\t\t\t\t\t\t{p:1},{p:5},{p:9},{p:10},{p:13},{p:17},{p:19},{p:21},{p:25},{p:28},{p:29},{p:33},{p:37}\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t];\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tcase 'O':\n\t\t\t\t\t\t\tcase 'o':\n\t\t\t\t\t\t\t\tcharacter = [\n\t\t\t\t\t\t\t\t\t\t{p:2},{p:3},{p:4},{p:9},{p:13},{p:17},{p:21},{p:25},{p:29},{p:34},{p:35},{p:36}\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t];\n\t\t\t\t\t\t\tbreak;\t\t\t\t\t\n\t\t\n\t\t\t\t\t\t\tcase 'P':\n\t\t\t\t\t\t\tcase 'p':\n\t\t\t\t\t\t\t\tcharacter = [\n\t\t\t\t\t\t\t\t\t\t{p:1},{p:2},{p:3},{p:4},{p:9},{p:13},{p:17},{p:18},{p:19},{p:20},{p:25},{p:33}\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t];\n\t\t\t\t\t\t\tbreak;\n\t\t\n\t\t\t\t\t\t\tcase 'Q':\n\t\t\t\t\t\t\tcase 'q':\n\t\t\t\t\t\t\t\tcharacter = [\n\t\t\t\t\t\t\t\t\t\t{p:2},{p:3},{p:4},{p:9},{p:13},{p:17},{p:19},{p:21},{p:25},{p:28},{p:29},{p:34},{p:35},{p:36},{p:37}\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t];\n\t\t\t\t\t\t\tbreak;\n\t\t\n\t\t\t\t\t\t\tcase 'R':\n\t\t\t\t\t\t\tcase 'r':\n\t\t\t\t\t\t\t\tcharacter = [\n\t\t\t\t\t\t\t\t\t\t{p:1},{p:2},{p:3},{p:4},{p:9},{p:13},{p:17},{p:18},{p:19},{p:20},{p:25},{p:29},{p:33},{p:37}\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t];\n\t\t\t\t\t\t\tbreak;\n\t\t\n\t\t\t\t\t\t\tcase 'S':\n\t\t\t\t\t\t\tcase 's':\n\t\t\t\t\t\t\t\tcharacter = [\n\t\t\t\t\t\t\t\t\t\t{p:2},{p:3},{p:4},{p:5},{p:9},{p:18},{p:19},{p:20},{p:29},{p:33},{p:34},{p:35},{p:36}\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t];\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tcase 'T':\n\t\t\t\t\t\t\tcase 't':\n\t\t\t\t\t\t\t\tcharacter = [\n\t\t\t\t\t\t\t\t\t\t{p:1},{p:2},{p:3},{p:4},{p:5},{p:11},{p:19},{p:27},{p:35}\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t];\n\t\t\t\t\t\t\tbreak;\t\t\t\t\t\n\t\t\n\t\t\t\t\t\t\tcase 'U':\n\t\t\t\t\t\t\tcase 'u':\n\t\t\t\t\t\t\t\tcharacter = [\n\t\t\t\t\t\t\t\t\t\t{p:1},{p:5},{p:9},{p:13},{p:17},{p:21},{p:25},{p:29},{p:34},{p:35},{p:36}\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t];\n\t\t\t\t\t\t\tbreak;\n\t\t\n\t\t\t\t\t\t\tcase 'V':\n\t\t\t\t\t\t\tcase 'v':\n\t\t\t\t\t\t\t\tcharacter = [\n\t\t\t\t\t\t\t\t\t\t{p:1},{p:5},{p:9},{p:13},{p:17},{p:21},{p:26},{p:28},{p:35}\t\t\t\t\n\t\t\t\t\t\t\t\t\t];\n\t\t\t\t\t\t\tbreak;\n\t\t\n\t\t\t\t\t\t\tcase 'W':\n\t\t\t\t\t\t\tcase 'w':\n\t\t\t\t\t\t\t\tcharacter = [\n\t\t\t\t\t\t\t\t\t\t{p:1},{p:4},{p:7},{p:9},{p:12},{p:15},{p:17},{p:20},{p:23},{p:25},{p:28},{p:31},{p:34},{p:35},{p:37},{p:38}\t\t\t\t\n\t\t\t\t\t\t\t\t\t];\n\t\t\t\t\t\t\tbreak;\n\t\t\n\t\t\t\t\t\t\tcase 'X':\n\t\t\t\t\t\t\tcase 'x':\n\t\t\t\t\t\t\t\tcharacter = [\n\t\t\t\t\t\t\t\t\t\t{p:1},{p:5},{p:10},{p:12},{p:19},{p:26},{p:28},{p:33},{p:37}\t\t\t\t\n\t\t\t\t\t\t\t\t\t];\n\t\t\t\t\t\t\tbreak;\n\t\t\n\t\t\t\t\t\t\tcase 'Y':\n\t\t\t\t\t\t\tcase 'y':\n\t\t\t\t\t\t\t\tcharacter = [\n\t\t\t\t\t\t\t\t\t\t{p:1},{p:5},{p:10},{p:12},{p:19},{p:27},{p:35}\t\t\t\t\n\t\t\t\t\t\t\t\t\t];\n\t\t\t\t\t\t\tbreak;\n\t\t\n\t\t\t\t\t\t\tcase 'Z':\n\t\t\t\t\t\t\tcase 'z':\n\t\t\t\t\t\t\t\tcharacter = [\n\t\t\t\t\t\t\t\t\t\t{p:1},{p:2},{p:3},{p:4},{p:5},{p:12},{p:19},{p:26},{p:33},{p:34},{p:35},{p:36},{p:37}\t\t\t\t\n\t\t\t\t\t\t\t\t\t];\n\t\t\t\t\t\t\tbreak;\n\t\t\n\t\t\t\t\t\t\t// numbers\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tcase '1':\n\t\t\t\t\t\t\t\tcharacter = [\n\t\t\t\t\t\t\t\t\t\t{p:3},{p:10},{p:11},{p:19},{p:27},{p:35}\t\t\t\n\t\t\t\t\t\t\t\t\t];\n\t\t\t\t\t\t\tbreak;\t\t\t\t\t\n\t\t\n\t\t\t\t\t\t\tcase '2':\n\t\t\t\t\t\t\t\tcharacter = [\n\t\t\t\t\t\t\t\t\t\t{p:1},{p:2},{p:3},{p:4},{p:13},{p:18},{p:19},{p:20},{p:25},{p:33},{p:34},{p:35},{p:36},{p:37}\t\t\t\n\t\t\t\t\t\t\t\t\t];\n\t\t\t\t\t\t\tbreak;\t\n\t\t\n\t\t\t\t\t\t\tcase '3':\n\t\t\t\t\t\t\t\tcharacter = [\n\t\t\t\t\t\t\t\t\t\t{p:1},{p:2},{p:3},{p:4},{p:13},{p:18},{p:19},{p:20},{p:29},{p:33},{p:34},{p:35},{p:36}\t\t\t\n\t\t\t\t\t\t\t\t\t];\n\t\t\t\t\t\t\tbreak;\n\t\t\n\t\t\t\t\t\t\tcase '4':\n\t\t\t\t\t\t\t\tcharacter = [\t\n\t\t\t\t\t\t\t\t\t\t{p:3},{p:4},{p:10},{p:12},{p:17},{p:20},{p:25},{p:26},{p:27},{p:28},{p:29},{p:36}\t\t\t\n\t\t\t\t\t\t\t\t\t];\n\t\t\t\t\t\t\tbreak;\n\t\t\n\t\t\t\t\t\t\tcase '5':\n\t\t\t\t\t\t\t\tcharacter = [\t\n\t\t\t\t\t\t\t\t\t\t{p:1},{p:2},{p:3},{p:4},{p:5},{p:9},{p:17},{p:18},{p:19},{p:20},{p:29},{p:33},{p:34},{p:35},{p:36}\t\t\t\n\t\t\t\t\t\t\t\t\t];\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tcase '6':\n\t\t\t\t\t\t\t\tcharacter = [\t\n\t\t\t\t\t\t\t\t\t\t{p:2},{p:3},{p:4},{p:9},{p:17},{p:18},{p:19},{p:20},{p:25},{p:29},{p:34},{p:35},{p:36}\t\t\t\n\t\t\t\t\t\t\t\t\t];\n\t\t\t\t\t\t\tbreak;\t\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tcase '7':\n\t\t\t\t\t\t\t\tcharacter = [\t\n\t\t\t\t\t\t\t\t\t\t{p:2},{p:3},{p:4},{p:5},{p:13},{p:20},{p:27},{p:35}\t\t\n\t\t\t\t\t\t\t\t\t];\n\t\t\t\t\t\t\tbreak;\t\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tcase '8':\n\t\t\t\t\t\t\t\tcharacter = [\t\n\t\t\t\t\t\t\t\t\t\t{p:2},{p:3},{p:4},{p:9},{p:13},{p:18},{p:19},{p:20},{p:25},{p:29},{p:34},{p:35},{p:36}\t\t\n\t\t\t\t\t\t\t\t\t];\n\t\t\t\t\t\t\tbreak;\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\n\t\t\t\t\t\t\tcase '9':\n\t\t\t\t\t\t\t\tcharacter = [\t\n\t\t\t\t\t\t\t\t\t\t{p:2},{p:3},{p:4},{p:9},{p:13},{p:18},{p:19},{p:20},{p:21},{p:28},{p:34},{p:35},{p:36}\t\t\n\t\t\t\t\t\t\t\t\t];\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tcase '0':\n\t\t\t\t\t\t\t\tcharacter = [\t\n\t\t\t\t\t\t\t\t\t\t{p:2},{p:3},{p:4},{p:9},{p:13},{p:17},{p:21},{p:25},{p:29},{p:34},{p:35},{p:36}\t\t\n\t\t\t\t\t\t\t\t\t];\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\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\t\t\t\t\t\t\t// arrows\n\t\t\n\t\t\t\t\t\t\tcase 'arrow_down':\n\t\t\t\t\t\t\t\tcharacter = [\n\t\t\t\t\t\t\t\t\t\t{p:3},{p:11},{p:17},{p:19},{p:21},{p:26},{p:27},{p:28},{p:35}\t\t\n\t\t\t\t\t\t\t\t\t];\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tcase 'arrow_up':\n\t\t\t\t\t\t\t\tcharacter = [\n\t\t\t\t\t\t\t\t\t\t{p:3},{p:10},{p:11},{p:12},{p:17},{p:19},{p:21},{p:27},{p:35}\t\t\n\t\t\t\t\t\t\t\t\t];\n\t\t\t\t\t\t\tbreak;\t\t\t\t\t\n\t\t\n\t\t\t\t\t\t\tcase 'arrow_left':\n\t\t\t\t\t\t\t\tcharacter = [\n\t\t\t\t\t\t\t\t\t\t{p:3},{p:10},{p:17},{p:18},{p:19},{p:20},{p:21},{p:26},{p:35}\t\t\n\t\t\t\t\t\t\t\t\t];\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tcase 'arrow_right':\n\t\t\t\t\t\t\t\tcharacter = [\n\t\t\t\t\t\t\t\t\t\t{p:3},{p:12},{p:17},{p:18},{p:19},{p:20},{p:21},{p:28},{p:35}\t\t\n\t\t\t\t\t\t\t\t\t];\n\t\t\t\t\t\t\tbreak;\t\t\t\t\t\n\t\t\n\t\t\t\t\t\t\t// punctuation\n\t\t\n\t\t\t\t\t\t\tcase \"!\":\n\t\t\t\t\t\t\t\tcharacter = [\n\t\t\t\t\t\t\t\t\t\t{p:3},{p:11},{p:19},{p:35}\n\t\t\t\t\t\t\t\t\t];\n\t\t\t\t\t\t\tbreak;\t\n\t\t\n\t\t\t\t\t\t\tcase \"@\":\n\t\t\t\t\t\t\t\tcharacter = [\n\t\t\t\t\t\t\t\t\t\t{p:2},{p:3},{p:4},{p:9},{p:11},{p:13},{p:17},{p:19},{p:20},{p:21},{p:25},{p:34},{p:35},{p:36}\n\t\t\t\t\t\t\t\t\t];\n\t\t\t\t\t\t\tbreak;\n\t\t\n\t\t\t\t\t\t\tcase \"#\":\n\t\t\t\t\t\t\t\tcharacter = [\n\t\t\t\t\t\t\t\t\t\t{p:2},{p:4},{p:9},{p:10},{p:11},{p:12},{p:13},{p:18},{p:20},{p:25},{p:26},{p:27},{p:28},{p:29},{p:34},{p:36}\n\t\t\t\t\t\t\t\t\t];\n\t\t\t\t\t\t\tbreak;\n\t\t\n\t\t\t\t\t\t\tcase \"$\":\n\t\t\t\t\t\t\t\tcharacter = [\n\t\t\t\t\t\t\t\t\t\t{p:2},{p:3},{p:4},{p:5},{p:9},{p:11},{p:18},{p:19},{p:20},{p:27},{p:29},{p:33},{p:34},{p:35},{p:36},{p:43}\n\t\t\t\t\t\t\t\t\t];\n\t\t\t\t\t\t\tbreak;\n\t\t\n\t\t\t\t\t\t\tcase \"%\":\n\t\t\t\t\t\t\t\tcharacter = [\n\t\t\t\t\t\t\t\t\t\t{p:1},{p:2},{p:4},{p:9},{p:10},{p:12},{p:19},{p:26},{p:28},{p:29},{p:34},{p:36},{p:37}\n\t\t\t\t\t\t\t\t\t];\n\t\t\t\t\t\t\tbreak;\n\t\t\n\t\t\t\t\t\t\tcase \"^\":\n\t\t\t\t\t\t\t\tcharacter = [\n\t\t\t\t\t\t\t\t\t\t{p:3},{p:10},{p:12}\n\t\t\t\t\t\t\t\t\t];\n\t\t\t\t\t\t\tbreak;\n\t\t\n\t\t\t\t\t\t\tcase \"&\":\n\t\t\t\t\t\t\t\tcharacter = [\n\t\t\t\t\t\t\t\t\t\t{p:2},{p:3},{p:9},{p:12},{p:18},{p:19},{p:25},{p:29},{p:34},{p:35},{p:36},{p:37}\n\t\t\t\t\t\t\t\t\t];\n\t\t\t\t\t\t\tbreak;\n\t\t\n\t\t\t\t\t\t\tcase \"*\":\n\t\t\t\t\t\t\t\tcharacter = [\n\t\t\t\t\t\t\t\t\t\t{p:3},{p:9},{p:11},{p:13},{p:18},{p:19},{p:20},{p:25},{p:27},{p:29},{p:35}\n\t\t\t\t\t\t\t\t\t];\n\t\t\t\t\t\t\tbreak;\n\t\t\n\t\t\t\t\t\t\tcase \"(\":\n\t\t\t\t\t\t\t\tcharacter = [\n\t\t\t\t\t\t\t\t\t\t{p:3},{p:10},{p:18},{p:26},{p:35}\n\t\t\t\t\t\t\t\t\t];\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tcase \")\":\n\t\t\t\t\t\t\t\tcharacter = [\n\t\t\t\t\t\t\t\t\t\t{p:3},{p:12},{p:20},{p:28},{p:35}\n\t\t\t\t\t\t\t\t\t];\n\t\t\t\t\t\t\tbreak;\t\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tcase \"-\":\n\t\t\t\t\t\t\t\tcharacter = [\n\t\t\t\t\t\t\t\t\t\t{p:18},{p:19},{p:20}\n\t\t\t\t\t\t\t\t\t];\n\t\t\t\t\t\t\tbreak;\t\t\t\t\t\t\t\t\t\n\t\t\n\t\t\t\t\t\t\tcase \"_\":\n\t\t\t\t\t\t\t\tcharacter = [\n\t\t\t\t\t\t\t\t\t\t{p:34},{p:35},{p:36},{p:37}\n\t\t\t\t\t\t\t\t\t];\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tcase \"=\":\n\t\t\t\t\t\t\t\tcharacter = [\n\t\t\t\t\t\t\t\t\t\t{p:10},{p:11},{p:12},{p:13},{p:26},{p:27},{p:28},{p:29}\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\tbreak;\t\t\t\t\t\n\t\t\n\t\t\t\t\t\t\tcase \"+\":\n\t\t\t\t\t\t\t\tcharacter = [\n\t\t\t\t\t\t\t\t\t\t{p:3},{p:11},{p:17},{p:18},{p:19},{p:20},{p:21},{p:27},{p:35}\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\tbreak;\t\n\t\t\n\t\t\t\t\t\t\tcase \";\":\n\t\t\t\t\t\t\t\tcharacter = [\n\t\t\t\t\t\t\t\t\t\t{p:3},{p:27},{p:34}\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t];\n\t\t\t\t\t\t\tbreak;\n\t\t\n\t\t\t\t\t\t\tcase \":\":\n\t\t\t\t\t\t\t\tcharacter = [\n\t\t\t\t\t\t\t\t\t\t{p:11},{p:35}\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t];\n\t\t\t\t\t\t\tbreak;\n\t\t\n\t\t\t\t\t\t\tcase \"'\":\n\t\t\t\t\t\t\t\tcharacter = [\n\t\t\t\t\t\t\t\t\t\t{p:3},{p:10},{p:18}\t\n\t\t\t\t\t\t\t\t\t];\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\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\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\t\t\t\t\n\t\t\t\t\t\t\tcase ',':\n\t\t\t\t\t\t\t\tcharacter = [\n\t\t\t\t\t\t\t\t\t\t{p:34},{p:41}\t\t\t\n\t\t\t\t\t\t\t\t\t];\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tcase \".\":\n\t\t\t\t\t\t\t\tcharacter = [\n\t\t\t\t\t\t\t\t\t\t{p:33}\t\n\t\t\t\t\t\t\t\t\t];\n\t\t\t\t\t\t\tbreak;\t\n\t\t\n\t\t\t\t\t\t\tcase '<':\n\t\t\t\t\t\t\t\tcharacter = [\n\t\t\t\t\t\t\t\t\t\t{p:3},{p:10},{p:17},{p:26},{p:35}\t\t\n\t\t\t\t\t\t\t\t\t];\n\t\t\t\t\t\t\tbreak;\n\t\t\n\t\t\t\t\t\t\tcase '>':\n\t\t\t\t\t\t\t\tcharacter = [\n\t\t\t\t\t\t\t\t\t\t{p:3},{p:12},{p:21},{p:28},{p:35}\t\t\n\t\t\t\t\t\t\t\t\t];\n\t\t\t\t\t\t\tbreak;\n\t\t\n\t\t\t\t\t\t\tcase \"/\":\n\t\t\t\t\t\t\t\tcharacter = [\n\t\t\t\t\t\t\t\t\t\t{p:4},{p:12},{p:19},{p:26},{p:34}\n\t\t\t\t\t\t\t\t\t];\n\t\t\t\t\t\t\tbreak;\t\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tcase \"?\":\n\t\t\t\t\t\t\t\tcharacter = [\n\t\t\t\t\t\t\t\t\t\t{p:1},{p:2},{p:3},{p:12},{p:18},{p:19},{p:34}\n\t\t\t\t\t\t\t\t\t];\n\t\t\t\t\t\t\tbreak;\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\n\t\t\t\t\t\t\tcase \"{\":\n\t\t\t\t\t\t\t\tcharacter = [\n\t\t\t\t\t\t\t\t\t\t{p:3},{p:4},{p:11},{p:18},{p:27},{p:35},{p:36}\n\t\t\t\t\t\t\t\t\t];\n\t\t\t\t\t\t\tbreak;\n\t\t\n\t\t\t\t\t\t\tcase \"}\":\n\t\t\t\t\t\t\t\tcharacter = [\n\t\t\t\t\t\t\t\t\t\t{p:2},{p:3},{p:11},{p:20},{p:27},{p:34},{p:35}\n\t\t\t\t\t\t\t\t\t];\n\t\t\t\t\t\t\tbreak;\t\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tcase \"[\":\n\t\t\t\t\t\t\t\tcharacter = [\n\t\t\t\t\t\t\t\t\t\t{p:3},{p:4},{p:11},{p:19},{p:27},{p:35},{p:36}\n\t\t\t\t\t\t\t\t\t];\n\t\t\t\t\t\t\tbreak;\n\t\t\n\t\t\t\t\t\t\tcase \"]\":\n\t\t\t\t\t\t\t\tcharacter = [\n\t\t\t\t\t\t\t\t\t\t{p:2},{p:3},{p:11},{p:19},{p:27},{p:34},{p:35}\n\t\t\t\t\t\t\t\t\t];\n\t\t\t\t\t\t\tbreak;\n\t\t\n\t\t\t\t\t\t\tcase \"|\":\n\t\t\t\t\t\t\t\tcharacter = [\n\t\t\t\t\t\t\t\t\t\t{p:3},{p:11},{p:19},{p:27},{p:35}\n\t\t\t\t\t\t\t\t\t];\n\t\t\t\t\t\t\tbreak;\n\n\t\t\t\t\t\t\t// currency\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tcase \"currency_cents\":\n\t\t\t\t\t\t\t\tcharacter = [\n\t\t\t\t\t\t\t\t\t{p:2},{p:9},{p:10},{p:11},{p:17},{p:25},{p:26},{p:27},{p:34}\n\t\t\t\t\t\t\t\t\t];\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\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\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\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\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tbreak;\t\t\t\t\t\n\t\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\tcase 'bigblock_bold':\t\t\t\t\t\n\t\t\t\t\n\t\t\t\t\t\tswitch (val) {\n\t\t\n\t\t\t\t\t\t\tcase ' ':\n\t\t\t\t\t\t\t\tcharacter = [];\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tcase 'A':\n\t\t\t\t\t\t\tcase 'a':\n\t\t\t\t\t\t\t\tcharacter = [\n\t\t\t\t\t\t\t\t\t{p : 4},{p : 5},{p : 12},{p : 13},{p : 18},{p : 19},{p : 22},{p : 23},{p : 26},{p : 27},{p : 30},{p : 31},{p : 34},{p : 35},{p : 36},{p : 37},{p : 38},{p : 39},{p : 42},{p : 43},{p : 44},{p : 45},{p : 46},{p : 47},{p : 50},{p : 51},{p : 54},{p : 55},{p : 58},{p : 59},{p : 62},{p : 63}\t\t\t\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\tbreak;\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tcase 'B':\n\t\t\t\t\t\t\tcase 'b':\n\t\t\t\t\t\t\t\tcharacter = [\n\t\t\t\t\t\t\t\t\t{p:2},{p:3},{p:10},{p:11},{p:18},{p:19},{p:20},{p:21},{p:22},{p:23},{p:26},{p:27},{p:28},{p:29},{p:30},{p:31},{p:34},{p:35},{p:38},{p:39},{p:42},{p:43},{p:46},{p:47},{p:50},{p:51},{p:52},{p:53},{p:54},{p:55},{p:58},{p:59},{p:60},{p:61},{p:62},{p:63}\t\t\t\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\tbreak;\t\t\t\t\t\n\t\t\n\t\t\t\t\t\t\tcase 'C':\n\t\t\t\t\t\t\tcase 'c':\n\t\t\t\t\t\t\t\tcharacter = [\n\t\t\t\t\t\t\t\t\t{p:2},{p:3},{p:4},{p:5},{p:6},{p:7},{p:10},{p:11},{p:12},{p:13},{p:14},{p:15},{p:18},{p:19},{p:26},{p:27},{p:34},{p:35},{p:42},{p:43},{p:50},{p:51},{p:52},{p:53},{p:54},{p:55},{p:58},{p:59},{p:60},{p:61},{p:62},{p:63}\t\t\t\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\tbreak;\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tcase 'D':\n\t\t\t\t\t\t\tcase 'd':\n\t\t\t\t\t\t\t\tcharacter = [\n\t\t\t\t\t\t\t\t\t{p:2},{p:3},{p:4},{p:5},{p:10},{p:11},{p:12},{p:13},{p:18},{p:19},{p:22},{p:23},{p:26},{p:27},{p:30},{p:31},{p:34},{p:35},{p:38},{p:39},{p:42},{p:43},{p:46},{p:47},{p:50},{p:51},{p:52},{p:53},{p:58},{p:59},{p:60},{p:61}\t\t\t\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\tbreak;\n\t\t\n\t\t\t\t\t\t\tcase 'E':\n\t\t\t\t\t\t\tcase 'e':\n\t\t\t\t\t\t\t\tcharacter = [\n\t\t\t\t\t\t\t\t\t{p:2},{p:3},{p:4},{p:5},{p:6},{p:7},{p:10},{p:11},{p:12},{p:13},{p:14},{p:15},{p:18},{p:19},{p:26},{p:27},{p:34},{p:35},{p:36},{p:37},{p:42},{p:43},{p:44},{p:45},{p:50},{p:51},{p:52},{p:53},{p:54},{p:55},{p:58},{p:59},{p:60},{p:61},{p:62},{p:63}\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t];\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tcase 'F':\n\t\t\t\t\t\t\tcase 'f':\n\t\t\t\t\t\t\t\tcharacter = [\n\t\t\t\t\t\t\t\t\t{p:2},{p:3},{p:4},{p:5},{p:6},{p:7},{p:10},{p:11},{p:12},{p:13},{p:14},{p:15},{p:18},{p:19},{p:26},{p:27},{p:34},{p:35},{p:36},{p:37},{p:42},{p:43},{p:44},{p:45},{p:50},{p:51},{p:58},{p:59}\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\tbreak;\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tcase 'G':\n\t\t\t\t\t\t\tcase 'g':\n\t\t\t\t\t\t\t\tcharacter = [\n\t\t\t\t\t\t\t\t\t{p:2},{p:3},{p:4},{p:5},{p:6},{p:7},{p:10},{p:11},{p:12},{p:13},{p:14},{p:15},{p:18},{p:19},{p:26},{p:27},{p:34},{p:35},{p:38},{p:39},{p:42},{p:43},{p:46},{p:47},{p:50},{p:51},{p:52},{p:53},{p:54},{p:55},{p:58},{p:59},{p:60},{p:61},{p:62},{p:63}\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\tbreak;\t\t\t\t\t\n\t\t\n\t\t\t\t\t\t\tcase 'H':\n\t\t\t\t\t\t\tcase 'h':\n\t\t\t\t\t\t\t\tcharacter = [\n\t\t\t\t\t\t\t\t\t{p:2},{p:3},{p:6},{p:7},{p:10},{p:11},{p:14},{p:15},{p:18},{p:19},{p:22},{p:23},{p:26},{p:27},{p:30},{p:31},{p:34},{p:35},{p:36},{p:37},{p:38},{p:39},{p:42},{p:43},{p:44},{p:45},{p:46},{p:47},{p:50},{p:51},{p:54},{p:55},{p:58},{p:59},{p:62},{p:63}\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t];\n\t\t\t\t\t\t\tbreak;\n\t\t\n\t\t\t\t\t\t\tcase 'I':\n\t\t\t\t\t\t\tcase 'i':\n\t\t\t\t\t\t\t\tcharacter = [\n\t\t\t\t\t\t\t\t\t{p:2},{p:3},{p:4},{p:5},{p:6},{p:7},{p:10},{p:11},{p:12},{p:13},{p:14},{p:15},{p:20},{p:21},{p:28},{p:29},{p:36},{p:37},{p:44},{p:45},{p:50},{p:51},{p:52},{p:53},{p:54},{p:55},{p:58},{p:59},{p:60},{p:61},{p:62},{p:63}\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t];\n\t\t\t\t\t\t\tbreak;\n\t\t\n\t\t\t\t\t\t\tcase 'J':\n\t\t\t\t\t\t\tcase 'j':\n\t\t\t\t\t\t\t\tcharacter = [\n\t\t\t\t\t\t\t\t\t{p:6},{p:7},{p:14},{p:15},{p:22},{p:23},{p:30},{p:31},{p:34},{p:35},{p:38},{p:39},{p:42},{p:43},{p:46},{p:47},{p:50},{p:51},{p:52},{p:53},{p:54},{p:55},{p:58},{p:59},{p:60},{p:61},{p:62},{p:63}\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t];\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tcase 'K':\n\t\t\t\t\t\t\tcase 'k':\n\t\t\t\t\t\t\t\tcharacter = [\n\t\t\t\t\t\t\t\t\t{p:2},{p:3},{p:6},{p:7},{p:10},{p:11},{p:14},{p:15},{p:18},{p:19},{p:22},{p:23},{p:26},{p:27},{p:30},{p:31},{p:34},{p:35},{p:36},{p:37},{p:42},{p:43},{p:44},{p:45},{p:50},{p:51},{p:54},{p:55},{p:58},{p:59},{p:62},{p:63}\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t];\n\t\t\t\t\t\t\tbreak;\t\t\t\t\t\n\t\t\n\t\t\t\t\t\t\tcase 'L':\n\t\t\t\t\t\t\tcase 'l':\n\t\t\t\t\t\t\t\tcharacter = [\n\t\t\t\t\t\t\t\t\t{p:2},{p:3},{p:10},{p:11},{p:18},{p:19},{p:26},{p:27},{p:34},{p:35},{p:42},{p:43},{p:50},{p:51},{p:52},{p:53},{p:54},{p:55},{p:58},{p:59},{p:60},{p:61},{p:62},{p:63}\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t];\n\t\t\t\t\t\t\tbreak;\t\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tcase 'M':\n\t\t\t\t\t\t\tcase 'm':\n\t\t\t\t\t\t\t\tcharacter = [\n\t\t\t\t\t\t\t\t\t{p:2},{p:3},{p:6},{p:7},{p:10},{p:11},{p:14},{p:15},{p:18},{p:19},{p:20},{p:21},{p:22},{p:23},{p:26},{p:27},{p:28},{p:29},{p:30},{p:31},{p:34},{p:35},{p:36},{p:37},{p:38},{p:39},{p:42},{p:43},{p:44},{p:45},{p:46},{p:47},{p:50},{p:51},{p:54},{p:55},{p:58},{p:59},{p:62},{p:63}\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t];\n\t\t\t\t\t\t\tbreak;\n\t\t\n\t\t\t\t\t\t\tcase 'N':\n\t\t\t\t\t\t\tcase 'n':\n\t\t\t\t\t\t\t\tcharacter = [\n\t\t\t\t\t\t\t\t\t{p:2},{p:3},{p:4},{p:5},{p:10},{p:11},{p:12},{p:13},{p:18},{p:19},{p:22},{p:23},{p:26},{p:27},{p:30},{p:31},{p:34},{p:35},{p:38},{p:39},{p:42},{p:43},{p:46},{p:47},{p:50},{p:51},{p:54},{p:55},{p:58},{p:59},{p:62},{p:63}\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t];\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tcase 'O':\n\t\t\t\t\t\t\tcase 'o':\n\t\t\t\t\t\t\t\tcharacter = [\n\t\t\t\t\t\t\t\t\t{p:2},{p:3},{p:4},{p:5},{p:6},{p:7},{p:10},{p:11},{p:12},{p:13},{p:14},{p:15},{p:18},{p:19},{p:22},{p:23},{p:26},{p:27},{p:30},{p:31},{p:34},{p:35},{p:38},{p:39},{p:42},{p:43},{p:46},{p:47},{p:50},{p:51},{p:52},{p:53},{p:54},{p:55},{p:58},{p:59},{p:60},{p:61},{p:62},{p:63}\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t];\n\t\t\t\t\t\t\tbreak;\t\t\t\t\t\n\t\t\n\t\t\t\t\t\t\tcase 'P':\n\t\t\t\t\t\t\tcase 'p':\n\t\t\t\t\t\t\t\tcharacter = [\n\t\t\t\t\t\t\t\t\t{p:2},{p:3},{p:4},{p:5},{p:6},{p:7},{p:10},{p:11},{p:12},{p:13},{p:14},{p:15},{p:18},{p:19},{p:22},{p:23},{p:26},{p:27},{p:30},{p:31},{p:34},{p:35},{p:36},{p:37},{p:38},{p:39},{p:42},{p:43},{p:44},{p:45},{p:46},{p:47},{p:50},{p:51},{p:58},{p:59}\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t];\n\t\t\t\t\t\t\tbreak;\n\t\t\n\t\t\t\t\t\t\tcase 'Q':\n\t\t\t\t\t\t\tcase 'q':\n\t\t\t\t\t\t\t\tcharacter = [\n\t\t\t\t\t\t\t\t\t{p:2},{p:3},{p:4},{p:5},{p:6},{p:7},{p:10},{p:11},{p:12},{p:13},{p:14},{p:15},{p:18},{p:19},{p:22},{p:23},{p:26},{p:27},{p:30},{p:31},{p:34},{p:35},{p:36},{p:37},{p:38},{p:39},{p:42},{p:43},{p:44},{p:45},{p:46},{p:47},{p:54},{p:55},{p:62},{p:63}\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t];\n\t\t\t\t\t\t\tbreak;\n\t\t\n\t\t\t\t\t\t\tcase 'R':\n\t\t\t\t\t\t\tcase 'r':\n\t\t\t\t\t\t\t\tcharacter = [\n\t\t\t\t\t\t\t\t\t{p:2},{p:3},{p:4},{p:5},{p:6},{p:7},{p:10},{p:11},{p:12},{p:13},{p:14},{p:15},{p:18},{p:19},{p:22},{p:23},{p:26},{p:27},{p:30},{p:31},{p:34},{p:35},{p:36},{p:37},{p:42},{p:43},{p:44},{p:45},{p:50},{p:51},{p:54},{p:55},{p:58},{p:59},{p:62},{p:63}\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t];\n\t\t\t\t\t\t\tbreak;\n\t\t\n\t\t\t\t\t\t\tcase 'S':\n\t\t\t\t\t\t\tcase 's':\n\t\t\t\t\t\t\t\tcharacter = [\n\t\t\t\t\t\t\t\t\t{p:2},{p:3},{p:4},{p:5},{p:6},{p:7},{p:10},{p:11},{p:12},{p:13},{p:14},{p:15},{p:18},{p:19},{p:26},{p:27},{p:36},{p:37},{p:38},{p:39},{p:44},{p:45},{p:46},{p:47},{p:50},{p:51},{p:52},{p:53},{p:54},{p:55},{p:58},{p:59},{p:60},{p:61},{p:62},{p:63}\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t];\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tcase 'T':\n\t\t\t\t\t\t\tcase 't':\n\t\t\t\t\t\t\t\tcharacter = [\n\t\t\t\t\t\t\t\t\t{p:2},{p:3},{p:4},{p:5},{p:6},{p:7},{p:10},{p:11},{p:12},{p:13},{p:14},{p:15},{p:20},{p:21},{p:28},{p:29},{p:36},{p:37},{p:44},{p:45},{p:52},{p:53},{p:60},{p:61}\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t];\n\t\t\t\t\t\t\tbreak;\t\t\t\t\t\n\t\t\n\t\t\t\t\t\t\tcase 'U':\n\t\t\t\t\t\t\tcase 'u':\n\t\t\t\t\t\t\t\tcharacter = [\n\t\t\t\t\t\t\t\t\t{p:2},{p:3},{p:6},{p:7},{p:10},{p:11},{p:14},{p:15},{p:18},{p:19},{p:22},{p:23},{p:26},{p:27},{p:30},{p:31},{p:34},{p:35},{p:38},{p:39},{p:42},{p:43},{p:46},{p:47},{p:50},{p:51},{p:52},{p:53},{p:54},{p:55},{p:58},{p:59},{p:60},{p:61},{p:62},{p:63}\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t];\n\t\t\t\t\t\t\tbreak;\n\t\t\n\t\t\t\t\t\t\tcase 'V':\n\t\t\t\t\t\t\tcase 'v':\n\t\t\t\t\t\t\t\tcharacter = [\n\t\t\t\t\t\t\t\t\t{p:2},{p:3},{p:6},{p:7},{p:10},{p:11},{p:14},{p:15},{p:18},{p:19},{p:22},{p:23},{p:26},{p:27},{p:30},{p:31},{p:34},{p:35},{p:38},{p:39},{p:42},{p:43},{p:46},{p:47},{p:52},{p:53},{p:60},{p:61}\t\t\t\t\n\t\t\t\t\t\t\t\t\t];\n\t\t\t\t\t\t\tbreak;\n\t\t\n\t\t\t\t\t\t\tcase 'W':\n\t\t\t\t\t\t\tcase 'w':\n\t\t\t\t\t\t\t\tcharacter = [\n\t\t\t\t\t\t\t\t\t{p:1},{p:2},{p:7},{p:8},{p:9},{p:10},{p:15},{p:16},{p:17},{p:18},{p:23},{p:24},{p:25},{p:26},{p:31},{p:32},{p:33},{p:34},{p:37},{p:38},{p:39},{p:40},{p:41},{p:42},{p:45},{p:46},{p:47},{p:48},{p:49},{p:50},{p:51},{p:52},{p:53},{p:54},{p:55},{p:56},{p:57},{p:58},{p:59},{p:60},{p:61},{p:62},{p:63},{p:64}\t\t\t\t\n\t\t\t\t\t\t\t\t\t];\n\t\t\t\t\t\t\tbreak;\n\t\t\n\t\t\t\t\t\t\tcase 'X':\n\t\t\t\t\t\t\tcase 'x':\n\t\t\t\t\t\t\t\tcharacter = [\n\t\t\t\t\t\t\t\t\t{p:2},{p:3},{p:6},{p:7},{p:10},{p:11},{p:14},{p:15},{p:18},{p:19},{p:22},{p:23},{p:26},{p:27},{p:30},{p:31},{p:36},{p:37},{p:44},{p:45},{p:50},{p:51},{p:54},{p:55},{p:58},{p:59},{p:62},{p:63}\t\t\t\t\n\t\t\t\t\t\t\t\t\t];\n\t\t\t\t\t\t\tbreak;\n\t\t\n\t\t\t\t\t\t\tcase 'Y':\n\t\t\t\t\t\t\tcase 'y':\n\t\t\t\t\t\t\t\tcharacter = [\n\t\t\t\t\t\t\t\t\t{p:2},{p:3},{p:6},{p:7},{p:10},{p:11},{p:14},{p:15},{p:18},{p:19},{p:22},{p:23},{p:26},{p:27},{p:30},{p:31},{p:36},{p:37},{p:44},{p:45},{p:52},{p:53},{p:60},{p:61}\t\t\t\t\n\t\t\t\t\t\t\t\t\t];\n\t\t\t\t\t\t\tbreak;\n\t\t\n\t\t\t\t\t\t\tcase 'Z':\n\t\t\t\t\t\t\tcase 'z':\n\t\t\t\t\t\t\t\tcharacter = [\n\t\t\t\t\t\t\t\t\t{p:2},{p:3},{p:4},{p:5},{p:6},{p:7},{p:10},{p:11},{p:12},{p:13},{p:14},{p:15},{p:20},{p:21},{p:22},{p:23},{p:28},{p:29},{p:30},{p:31},{p:34},{p:35},{p:36},{p:37},{p:42},{p:43},{p:44},{p:45},{p:50},{p:51},{p:52},{p:53},{p:54},{p:55},{p:58},{p:59},{p:60},{p:61},{p:62},{p:63}\t\t\t\t\n\t\t\t\t\t\t\t\t\t];\n\t\t\t\t\t\t\tbreak;\n\t\t\n\t\t\t\t\t\t\t// numbers\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tcase '1':\n\t\t\t\t\t\t\t\tcharacter = [\n\t\t\t\t\t\t\t\t\t{p:4},{p:5},{p:12},{p:13},{p:18},{p:19},{p:20},{p:21},{p:26},{p:27},{p:28},{p:29},{p:36},{p:37},{p:44},{p:45},{p:50},{p:51},{p:52},{p:53},{p:54},{p:55},{p:58},{p:59},{p:60},{p:61},{p:62},{p:63}\t\t\t\n\t\t\t\t\t\t\t\t\t];\n\t\t\t\t\t\t\tbreak;\t\t\t\t\t\n\t\t\n\t\t\t\t\t\t\tcase '2':\n\t\t\t\t\t\t\t\tcharacter = [\n\t\t\t\t\t\t\t\t\t{p:2},{p:3},{p:4},{p:5},{p:6},{p:7},{p:10},{p:11},{p:12},{p:13},{p:14},{p:15},{p:22},{p:23},{p:30},{p:31},{p:34},{p:35},{p:36},{p:37},{p:42},{p:43},{p:44},{p:45},{p:50},{p:51},{p:52},{p:53},{p:54},{p:55},{p:58},{p:59},{p:60},{p:61},{p:62},{p:63}\t\t\t\n\t\t\t\t\t\t\t\t\t];\n\t\t\t\t\t\t\tbreak;\t\n\t\t\n\t\t\t\t\t\t\tcase '3':\n\t\t\t\t\t\t\t\tcharacter = [\n\t\t\t\t\t\t\t\t\t{p:2},{p:3},{p:4},{p:5},{p:6},{p:7},{p:10},{p:11},{p:12},{p:13},{p:14},{p:15},{p:22},{p:23},{p:30},{p:31},{p:36},{p:37},{p:38},{p:39},{p:44},{p:45},{p:46},{p:47},{p:50},{p:51},{p:52},{p:53},{p:54},{p:55},{p:58},{p:59},{p:60},{p:61},{p:62},{p:63}\t\t\t\n\t\t\t\t\t\t\t\t\t];\n\t\t\t\t\t\t\tbreak;\n\t\t\n\t\t\t\t\t\t\tcase '4':\n\t\t\t\t\t\t\t\tcharacter = [\t\n\t\t\t\t\t\t\t\t\t{p:2},{p:3},{p:6},{p:7},{p:10},{p:11},{p:14},{p:15},{p:18},{p:19},{p:22},{p:23},{p:26},{p:27},{p:30},{p:31},{p:34},{p:35},{p:36},{p:37},{p:38},{p:39},{p:42},{p:43},{p:44},{p:45},{p:46},{p:47},{p:54},{p:55},{p:62},{p:63}\t\t\t\n\t\t\t\t\t\t\t\t\t];\n\t\t\t\t\t\t\tbreak;\n\t\t\n\t\t\t\t\t\t\tcase '5':\n\t\t\t\t\t\t\t\tcharacter = [\t\n\t\t\t\t\t\t\t\t\t{p:2},{p:3},{p:4},{p:5},{p:6},{p:7},{p:10},{p:11},{p:12},{p:13},{p:14},{p:15},{p:18},{p:19},{p:26},{p:27},{p:34},{p:35},{p:36},{p:37},{p:38},{p:39},{p:42},{p:43},{p:44},{p:45},{p:46},{p:47},{p:52},{p:53},{p:54},{p:55},{p:60},{p:61},{p:62},{p:63}\t\t\t\n\t\t\t\t\t\t\t\t\t];\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tcase '6':\n\t\t\t\t\t\t\t\tcharacter = [\t\n\t\t\t\t\t\t\t\t\t{p:2},{p:3},{p:10},{p:11},{p:18},{p:19},{p:20},{p:21},{p:22},{p:23},{p:26},{p:27},{p:28},{p:29},{p:30},{p:31},{p:34},{p:35},{p:38},{p:39},{p:42},{p:43},{p:46},{p:47},{p:50},{p:51},{p:52},{p:53},{p:54},{p:55},{p:58},{p:59},{p:60},{p:61},{p:62},{p:63}\t\t\t\n\t\t\t\t\t\t\t\t\t];\n\t\t\t\t\t\t\tbreak;\t\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tcase '7':\n\t\t\t\t\t\t\t\tcharacter = [\t\n\t\t\t\t\t\t\t\t\t{p:2},{p:3},{p:4},{p:5},{p:6},{p:7},{p:10},{p:11},{p:12},{p:13},{p:14},{p:15},{p:22},{p:23},{p:30},{p:31},{p:38},{p:39},{p:46},{p:47},{p:54},{p:55},{p:62},{p:63}\t\t\n\t\t\t\t\t\t\t\t\t];\n\t\t\t\t\t\t\tbreak;\t\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tcase '8':\n\t\t\t\t\t\t\t\tcharacter = [\t\n\t\t\t\t\t\t\t\t\t{p:2},{p:3},{p:4},{p:5},{p:6},{p:7},{p:10},{p:11},{p:12},{p:13},{p:14},{p:15},{p:18},{p:19},{p:22},{p:23},{p:26},{p:27},{p:30},{p:31},{p:34},{p:35},{p:36},{p:37},{p:38},{p:39},{p:42},{p:43},{p:44},{p:45},{p:46},{p:47},{p:50},{p:51},{p:52},{p:53},{p:54},{p:55},{p:58},{p:59},{p:60},{p:61},{p:62},{p:63}\t\t\n\t\t\t\t\t\t\t\t\t];\n\t\t\t\t\t\t\tbreak;\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\n\t\t\t\t\t\t\tcase '9':\n\t\t\t\t\t\t\t\tcharacter = [\t\n\t\t\t\t\t\t\t\t\t{p:2},{p:3},{p:4},{p:5},{p:6},{p:7},{p:10},{p:11},{p:12},{p:13},{p:14},{p:15},{p:18},{p:19},{p:22},{p:23},{p:26},{p:27},{p:30},{p:31},{p:34},{p:35},{p:36},{p:37},{p:38},{p:39},{p:42},{p:43},{p:44},{p:45},{p:46},{p:47},{p:54},{p:55},{p:62},{p:63}\t\n\t\t\t\t\t\t\t\t\t];\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tcase '0':\n\t\t\t\t\t\t\t\tcharacter = [\t\n\t\t\t\t\t\t\t\t\t{p:2},{p:3},{p:4},{p:5},{p:6},{p:7},{p:10},{p:11},{p:12},{p:13},{p:14},{p:15},{p:18},{p:19},{p:22},{p:23},{p:26},{p:27},{p:30},{p:31},{p:34},{p:35},{p:38},{p:39},{p:42},{p:43},{p:46},{p:47},{p:50},{p:51},{p:52},{p:53},{p:54},{p:55},{p:58},{p:59},{p:60},{p:61},{p:62},{p:63}\t\t\n\t\t\t\t\t\t\t\t\t];\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\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\t\t\t\t\t\t\t// arrows\n\t\t\n\t\t\t\t\t\t\tcase 'arrow_down':\n\t\t\t\t\t\t\t\tcharacter = [\n\t\t\t\t\t\t\t\t\t{p:4},{p:5},{p:12},{p:13},{p:20},{p:21},{p:28},{p:29},{p:33},{p:34},{p:35},{p:36},{p:37},{p:38},{p:39},{p:40},{p:42},{p:43},{p:44},{p:45},{p:46},{p:47},{p:51},{p:52},{p:53},{p:54},{p:60},{p:61}\t\t\n\t\t\t\t\t\t\t\t\t];\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tcase 'arrow_up':\n\t\t\t\t\t\t\t\tcharacter = [\n\t\t\t\t\t\t\t\t\t{p:4},{p:5},{p:11},{p:12},{p:13},{p:14},{p:18},{p:19},{p:20},{p:21},{p:22},{p:23},{p:25},{p:26},{p:27},{p:28},{p:29},{p:30},{p:31},{p:32},{p:36},{p:37},{p:44},{p:45},{p:52},{p:53},{p:60},{p:61}\t\t\n\t\t\t\t\t\t\t\t\t];\n\t\t\t\t\t\t\tbreak;\t\t\t\t\t\n\t\t\n\t\t\t\t\t\t\tcase 'arrow_left':\n\t\t\t\t\t\t\t\tcharacter = [\n\t\t\t\t\t\t\t\t\t{p:4},{p:11},{p:12},{p:18},{p:19},{p:20},{p:25},{p:26},{p:27},{p:28},{p:29},{p:30},{p:31},{p:32},{p:33},{p:34},{p:35},{p:36},{p:37},{p:38},{p:39},{p:40},{p:42},{p:43},{p:44},{p:51},{p:52},{p:60}\t\t\n\t\t\t\t\t\t\t\t\t];\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tcase 'arrow_right':\n\t\t\t\t\t\t\t\tcharacter = [\n\t\t\t\t\t\t\t\t\t{p:5},{p:13},{p:14},{p:21},{p:22},{p:23},{p:25},{p:26},{p:27},{p:28},{p:29},{p:30},{p:31},{p:32},{p:33},{p:34},{p:35},{p:36},{p:37},{p:38},{p:39},{p:40},{p:45},{p:46},{p:47},{p:53},{p:54},{p:61}\t\t\n\t\t\t\t\t\t\t\t\t];\n\t\t\t\t\t\t\tbreak;\t\t\t\t\t\n\t\t\n\t\t\t\t\t\t\t// punctuation\n\t\t\n\t\t\t\t\t\t\tcase \"!\":\n\t\t\t\t\t\t\t\tcharacter = [\n\t\t\t\t\t\t\t\t\t{p:4},{p:5},{p:12},{p:13},{p:20},{p:21},{p:28},{p:29},{p:52},{p:53},{p:60},{p:61}\n\t\t\t\t\t\t\t\t\t];\n\t\t\t\t\t\t\tbreak;\t\n\t\t\n\t\t\t\t\t\t\tcase \"@\":\n\t\t\t\t\t\t\t\tcharacter = [\n\t\t\t\t\t\t\t\t\t{p:3},{p:4},{p:5},{p:6},{p:11},{p:12},{p:13},{p:14},{p:17},{p:18},{p:21},{p:22},{p:23},{p:24},{p:25},{p:26},{p:29},{p:30},{p:31},{p:32},{p:33},{p:34},{p:41},{p:42},{p:51},{p:52},{p:53},{p:54},{p:59},{p:60},{p:61},{p:62}\n\t\t\t\t\t\t\t\t\t];\n\t\t\t\t\t\t\tbreak;\n\t\t\n\t\t\t\t\t\t\tcase \"#\":\n\t\t\t\t\t\t\t\tcharacter = [\n\t\t\n\t\t\t\t\t\t\t\t\t{p:2},{p:3},{p:6},{p:7},{p:9},{p:10},{p:11},{p:12},{p:13},{p:14},{p:15},{p:16},{p:17},{p:18},{p:19},{p:20},{p:21},{p:22},{p:23},{p:24},{p:26},{p:27},{p:30},{p:31},{p:34},{p:35},{p:38},{p:39},{p:41},{p:42},{p:43},{p:44},{p:45},{p:46},{p:47},{p:48},{p:49},{p:50},{p:51},{p:52},{p:53},{p:54},{p:55},{p:56},{p:58},{p:59},{p:62},{p:63}\n\t\t\t\t\t\t\t\t\t];\n\t\t\t\t\t\t\tbreak;\n\t\t\n\t\t\t\t\t\t\tcase \"$\":\n\t\t\t\t\t\t\t\tcharacter = [\n\t\t\t\t\t\t\t\t\t{p:4},{p:5},{p:11},{p:12},{p:13},{p:14},{p:15},{p:18},{p:19},{p:20},{p:21},{p:22},{p:27},{p:28},{p:29},{p:36},{p:37},{p:38},{p:43},{p:44},{p:45},{p:46},{p:47},{p:50},{p:51},{p:52},{p:53},{p:54},{p:60},{p:61}\n\t\t\t\t\t\t\t\t\t];\n\t\t\t\t\t\t\tbreak;\n\t\t\n\t\t\t\t\t\t\tcase \"%\":\n\t\t\t\t\t\t\t\tcharacter = [\n\t\t\t\t\t\t\t\t\t{p:2},{p:3},{p:6},{p:7},{p:10},{p:11},{p:14},{p:15},{p:22},{p:23},{p:28},{p:29},{p:30},{p:31},{p:34},{p:35},{p:36},{p:37},{p:42},{p:43},{p:50},{p:51},{p:54},{p:55},{p:58},{p:59},{p:62},{p:63}\n\t\t\t\t\t\t\t\t\t];\n\t\t\t\t\t\t\tbreak;\n\t\t\n\t\t\t\t\t\t\tcase \"^\":\n\t\t\t\t\t\t\t\tcharacter = [\n\t\t\t\t\t\t\t\t\t{p:4},{p:5},{p:12},{p:13},{p:19},{p:20},{p:21},{p:22},{p:27},{p:28},{p:29},{p:30},{p:34},{p:35},{p:38},{p:39},{p:42},{p:43},{p:46},{p:47}\n\t\t\t\t\t\t\t\t\t];\n\t\t\t\t\t\t\tbreak;\n\t\t\n\t\t\t\t\t\t\tcase \"&\":\n\t\t\t\t\t\t\t\tcharacter = [\n\t\t\t\t\t\t\t\t\t{p:3},{p:4},{p:11},{p:12},{p:17},{p:18},{p:21},{p:22},{p:25},{p:26},{p:27},{p:28},{p:29},{p:30},{p:35},{p:36},{p:41},{p:42},{p:47},{p:48},{p:49},{p:50},{p:51},{p:52},{p:53},{p:54},{p:55},{p:56},{p:59},{p:60},{p:61},{p:62}\n\t\t\t\t\t\t\t\t\t];\n\t\t\t\t\t\t\tbreak;\n\t\t\n\t\t\t\t\t\t\tcase \"*\":\n\t\t\t\t\t\t\t\tcharacter = [\n\t\t\t\t\t\t\t\t\t{p:4},{p:10},{p:12},{p:14},{p:20},{p:21},{p:25},{p:26},{p:27},{p:28},{p:29},{p:30},{p:31},{p:35},{p:36},{p:37},{p:42},{p:44},{p:46},{p:52}\n\t\t\t\t\t\t\t\t\t];\n\t\t\t\t\t\t\tbreak;\n\t\t\n\t\t\t\t\t\t\tcase \"(\":\n\t\t\t\t\t\t\t\tcharacter = [\n\t\t\t\t\t\t\t\t\t{p:4},{p:5},{p:12},{p:13},{p:18},{p:19},{p:26},{p:27},{p:34},{p:35},{p:42},{p:43},{p:52},{p:53},{p:60},{p:61}\n\t\t\t\t\t\t\t\t\t];\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tcase \")\":\n\t\t\t\t\t\t\t\tcharacter = [\n\t\t\t\t\t\t\t\t\t{p:4},{p:5},{p:12},{p:13},{p:22},{p:23},{p:30},{p:31},{p:38},{p:39},{p:46},{p:47},{p:52},{p:53},{p:60},{p:61}\n\t\t\t\t\t\t\t\t\t];\n\t\t\t\t\t\t\tbreak;\t\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tcase \"-\":\n\t\t\t\t\t\t\t\tcharacter = [\n\t\t\t\t\t\t\t\t\t{p:26},{p:27},{p:28},{p:29},{p:30},{p:31},{p:34},{p:35},{p:36},{p:37},{p:38},{p:39}\n\t\t\t\t\t\t\t\t\t];\n\t\t\t\t\t\t\tbreak;\t\t\t\t\t\t\t\t\t\n\t\t\n\t\t\t\t\t\t\tcase \"_\":\n\t\t\t\t\t\t\t\tcharacter = [\n\t\t\t\t\t\t\t\t\t{p:50},{p:51},{p:52},{p:53},{p:54},{p:55},{p:58},{p:59},{p:60},{p:61},{p:62},{p:63}\n\t\t\t\t\t\t\t\t\t];\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tcase \"=\":\n\t\t\t\t\t\t\t\tcharacter = [\n\t\t\t\t\t\t\t\t\t{p:10},{p:11},{p:12},{p:13},{p:14},{p:15},{p:18},{p:19},{p:20},{p:21},{p:22},{p:23},{p:42},{p:43},{p:44},{p:45},{p:46},{p:47},{p:50},{p:51},{p:52},{p:53},{p:54},{p:55}\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\tbreak;\t\t\t\t\t\n\t\t\n\t\t\t\t\t\t\tcase \"+\":\n\t\t\t\t\t\t\t\tcharacter = [\n\t\t\t\t\t\t\t\t\t{p:12},{p:13},{p:20},{p:21},{p:26},{p:27},{p:28},{p:29},{p:30},{p:31},{p:34},{p:35},{p:36},{p:37},{p:38},{p:39},{p:44},{p:45},{p:52},{p:53}\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\tbreak;\t\n\t\t\n\t\t\t\t\t\t\tcase \";\":\n\t\t\t\t\t\t\t\tcharacter = [\n\t\t\t\t\t\t\t\t\t{p:12},{p:13},{p:20},{p:21},{p:36},{p:37},{p:44},{p:45},{p:50},{p:51},{p:58},{p:59}\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t];\n\t\t\t\t\t\t\tbreak;\n\t\t\n\t\t\t\t\t\t\tcase \":\":\n\t\t\t\t\t\t\t\tcharacter = [\n\t\t\t\t\t\t\t\t\t{p:12},{p:13},{p:20},{p:21},{p:44},{p:45},{p:52},{p:53}\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t];\n\t\t\t\t\t\t\tbreak;\n\t\t\n\t\t\t\t\t\t\tcase \"'\":\n\t\t\t\t\t\t\t\tcharacter = [\n\t\t\t\t\t\t\t\t\t{p:6},{p:7},{p:14},{p:15},{p:20},{p:21},{p:28},{p:29}\t\n\t\t\t\t\t\t\t\t\t];\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\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\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\t\t\t\t\n\t\t\t\t\t\t\tcase ',':\n\t\t\t\t\t\t\t\tcharacter = [\n\t\t\t\t\t\t\t\t\t{p:37},{p:38},{p:45},{p:46},{p:51},{p:52},{p:59},{p:60}\t\t\t\n\t\t\t\t\t\t\t\t\t];\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tcase \".\":\n\t\t\t\t\t\t\t\tcharacter = [\n\t\t\t\t\t\t\t\t\t{p:52},{p:53},{p:60},{p:61}\t\n\t\t\t\t\t\t\t\t\t];\n\t\t\t\t\t\t\tbreak;\t\n\t\t\n\t\t\t\t\t\t\tcase '<':\n\t\t\t\t\t\t\t\tcharacter = [\n\t\t\t\t\t\t\t\t\t{p:14},{p:15},{p:20},{p:21},{p:22},{p:23},{p:26},{p:27},{p:28},{p:29},{p:34},{p:35},{p:36},{p:37},{p:44},{p:45},{p:46},{p:47},{p:54},{p:55}\t\t\n\t\t\t\t\t\t\t\t\t];\n\t\t\t\t\t\t\tbreak;\n\t\t\n\t\t\t\t\t\t\tcase '>':\n\t\t\t\t\t\t\t\tcharacter = [\n\t\t\t\t\t\t\t\t\t{p:10},{p:11},{p:18},{p:19},{p:20},{p:21},{p:28},{p:29},{p:30},{p:31},{p:36},{p:37},{p:38},{p:39},{p:42},{p:43},{p:44},{p:45},{p:50},{p:51}\t\t\n\t\t\t\t\t\t\t\t\t];\n\t\t\t\t\t\t\tbreak;\n\t\t\n\t\t\t\t\t\t\tcase \"/\":\n\t\t\t\t\t\t\t\tcharacter = [\n\t\t\t\t\t\t\t\t\t{p:5},{p:6},{p:13},{p:14},{p:20},{p:21},{p:28},{p:29},{p:35},{p:36},{p:43},{p:44},{p:50},{p:51},{p:58},{p:59}\n\t\t\t\t\t\t\t\t\t];\n\t\t\t\t\t\t\tbreak;\t\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tcase \"?\":\n\t\t\t\t\t\t\t\tcharacter = [\n\t\t\t\t\t\t\t\t\t{p:2},{p:3},{p:4},{p:5},{p:6},{p:7},{p:10},{p:11},{p:12},{p:13},{p:14},{p:15},{p:22},{p:23},{p:30},{p:31},{p:36},{p:37},{p:44},{p:45},{p:60},{p:61}\n\t\t\t\t\t\t\t\t\t];\n\t\t\t\t\t\t\tbreak;\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\n\t\t\t\t\t\t\tcase \"{\":\n\t\t\t\t\t\t\t\tcharacter = [\n\t\t\t\t\t\t\t\t\t{p:5},{p:6},{p:13},{p:14},{p:20},{p:21},{p:27},{p:28},{p:29},{p:35},{p:36},{p:37},{p:44},{p:45},{p:53},{p:54},{p:61},{p:62}\n\t\t\t\t\t\t\t\t\t];\n\t\t\t\t\t\t\tbreak;\n\t\t\n\t\t\t\t\t\t\tcase \"}\":\n\t\t\t\t\t\t\t\tcharacter = [\n\t\t\t\t\t\t\t\t\t{p:3},{p:4},{p:11},{p:12},{p:20},{p:21},{p:28},{p:29},{p:30},{p:36},{p:37},{p:38},{p:44},{p:45},{p:51},{p:52},{p:59},{p:60}\n\t\t\t\t\t\t\t\t\t];\n\t\t\t\t\t\t\tbreak;\t\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tcase \"[\":\n\t\t\t\t\t\t\t\tcharacter = [\n\t\t\t\t\t\t\t\t\t{p:3},{p:4},{p:5},{p:6},{p:11},{p:12},{p:13},{p:14},{p:19},{p:20},{p:27},{p:28},{p:35},{p:36},{p:43},{p:44},{p:51},{p:52},{p:53},{p:54},{p:59},{p:60},{p:61},{p:62}\n\t\t\t\t\t\t\t\t\t];\n\t\t\t\t\t\t\tbreak;\n\t\t\n\t\t\t\t\t\t\tcase \"]\":\n\t\t\t\t\t\t\t\tcharacter = [\n\t\t\t\t\t\t\t\t\t{p:3},{p:4},{p:5},{p:6},{p:11},{p:12},{p:13},{p:14},{p:21},{p:22},{p:29},{p:30},{p:37},{p:38},{p:45},{p:46},{p:51},{p:52},{p:53},{p:54},{p:59},{p:60},{p:61},{p:62}\n\t\t\t\t\t\t\t\t\t];\n\t\t\t\t\t\t\tbreak;\n\t\t\n\t\t\t\t\t\t\tcase \"|\":\n\t\t\t\t\t\t\t\tcharacter = [\n\t\t\t\t\t\t\t\t\t{p:4},{p:5},{p:12},{p:13},{p:20},{p:21},{p:28},{p:29},{p:36},{p:37},{p:44},{p:45},{p:52},{p:53},{p:60},{p:61}\n\t\t\t\t\t\t\t\t\t];\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t// currency\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tcase \"currency_cents\":\n\t\t\t\t\t\t\t\tcharacter = [\n\t\t\t\t\t\t\t\t\t{p:3},{p:4},{p:9},{p:10},{p:11},{p:12},{p:13},{p:14},{p:17},{p:18},{p:19},{p:20},{p:21},{p:22},{p:25},{p:26},{p:33},{p:34},{p:41},{p:42},{p:43},{p:44},{p:45},{p:46},{p:49},{p:50},{p:51},{p:52},{p:53},{p:54},{p:59},{p:60}\n\t\t\t\t\t\t\t\t\t];\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\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\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\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\t\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tbreak;\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\tbreak;\n\t\t\t\t\t\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\treturn character;\t\t\t\t\n\t\t\t}\n\t\t};\n\t}", "function findCountry(list, character) {\n if (list.length === 0) {\n return 'Invalid Data'\n }\n \n let output = []\n for (let i = 0; i < list.length; i++) {\n for (let j = 0; j < list[i].length; j++) {\n let currentCountry = list[i][j]\n if (currentCountry[0] === character) {\n output.push(currentCountry)\n }\n }\n }\n return output\n}", "function renderCharacters () {\n console.log('rendering characters')\n // iterate through characters object,\n // render each character to the charactersSelect div\n var keys = Object.keys(characters)\n for (var i = 0; i < keys.length; i++) {\n // get the current character out of the object\n var characterKey = keys[i]\n var character = characters[characterKey]\n // append elements to the #character-area element\n var charDiv = createCharDiv(character, characterKey)\n $('#character-area').append(charDiv)\n }\n}", "getAllPossibleCharacters() {\n\t\tlet characters = [];\n\t\tif (this.options.uppercase) characters = characters.concat(Characters.uppercase);\n\n\t\tif (this.options.numbers) characters = characters.concat(Characters.numbers);\n\n\t\tif (this.options.symbols) characters = characters.concat(Characters.symbols);\n\n\t\tif (characters.length == 0 || this.options.lowercase)\n\t\t\tcharacters = characters.concat(Characters.lowercase);\n\n\t\treturn characters;\n\t}", "addPhraseToDisplay() {\r\n // select the ul in the phrase section\r\n const phraseSection = document.querySelector('#phrase ul');\r\n\r\n // loopinng through characters in the phrase, checks for space\r\n for (let i = 0; i < this.phrase.length; i ++) {\r\n let phraseChar = this.phrase.charAt([i]);\r\n\r\n // create the li\r\n const charLi = document.createElement('li');\r\n\r\n // create necessary list items\r\n if (phraseChar === \" \") {\r\n charLi.className = \"space\";\r\n charLi.innerText = \" \";\r\n } else {\r\n const charClass = `hide letter ${phraseChar}`;\r\n charLi.className = charClass;\r\n charLi.innerText = phraseChar;\r\n }\r\n // append to the ul\r\n phraseSection.appendChild(charLi);\r\n }\r\n }", "list() {\n }", "function Listify() {\r\n}", "function buildList(){\n for (var i = 0; i < actArray.length; i++) {\n\n // 1. Create a variable named \"listItem\" equal to a list item\n var listItem = $(\"<li>\");\n\n // 2. Gives each list item a list-group-item\n listItem.addClass(\"list-group-item\");\n\n // 3. Then give each \"listItem\" a data-attribute called \"place\".\n listItem.attr(\"data-place\", i);\n\n // 4. Then give each \"listItem\" a text equal to \"letters[i]\".\n //listItem.text(actArray[i]);\n listItem.append(\"<span>\"+ actArray[i] + \"</span>\");\n\n listItem.append(\"<button class = 'btn-sm delete' data-attribute = \" + i + \"><icon class = 'fa fa-trash'></icon></button>\");\n\n listItem.append(\"<button class = 'btn-sm edit' value = \" + i + \"><icon class = 'fa fa-pencil'></icon></button>\");\n\n // 5. Finally, append each \"letterItem\" to the \"#listy\" div (provided).\n $(\"#listy\").append(listItem);\n }\n}", "addPhraseToDisplay() {\n //Targets the phrase\n const phraseElement = document.querySelector('#phrase ul');\n const splitPhrase = this.phrase.split('');\n splitPhrase.forEach(character => {\n const liElementChar = document.createElement('li');\n liElementChar.innerHTML = (`${character}`);\n phraseElement.append(liElementChar);\n liElementChar.classList.add('hide');\n if (character === ' ') {\n liElementChar.classList.add('space');\n } else {\n liElementChar.classList.add('letter');\n }\n });\n }", "addPhraseToDisplay(){\r\n const phraseUl = document.querySelector('#phrase ul');\r\n const phraseArr = this.phrase.split('');\r\n let html = '';\r\n// go thru each letter of the phraseArr and create and <Li>\r\n// added the respective class to each item\r\n// then appended to the dom\r\n phraseArr.forEach(character => {\r\n if(character !== ' '){\r\n html += `<li class=\"hide letter ${character}\">${character}</li>`;\r\n } else {\r\n html += `<li class=\"hide space\">${character}</li>`;\r\n }\r\n });\r\n phraseUl.innerHTML = html;\r\n return phraseUl;\r\n }", "getCharacter() {\n let characters = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ-. *$/+%';\n return characters;\n }", "addPhraseToDisplay() {\n let html = '';\n let letter = '';\n\n for (let i = 0; i < this.phrase.length; i++) {\n letter = this.phrase.charAt(i);\n if (letter === ' ') {\n html += `<li class =\"space\"> ${letter}</li>`;\n } else {\n html += `<li class=\"hide letter ${letter}\">${letter}</li>`;\n }\n }\n ul.innerHTML = (html);\n }", "function populateList(){\n\t\tlistbuilder.empty();\n\t\t$.each(el.val().split(options.delimChar), function(){\n\t\t\tif(this != ''){ listbuilder.append( listUnit(this) ); }\n\t\t});\n\t\t//append typeable component\n\t\tlistbuilder.append('<li class=\"listbuilder-entry-add\"><input type=\"text\" value=\"\" title=\"'+ options.userDirections +'\" /></li>');\n\t}", "function gotList(thelist) {\n print(\"List of Serial Ports:\");\n // theList is an array of their names\n for (let i = 0; i < thelist.length; i++) {\n // Display in the console\n print(i + \" \" + thelist[i]);\n }\n}", "getAsCharData() {\n return [this.fg, this.getChars(), this.getWidth(), this.getCode()];\n }", "getAsCharData() {\n return [this.fg, this.getChars(), this.getWidth(), this.getCode()];\n }", "function getListSymbol() {\r\n\tchrome.storage.sync.get({\r\n\t\tlist_symbol: '',\r\n\t}, function (items) {\r\n\t\tlet current_choice = items.list_symbol;\r\n\t\tswitch (current_choice) {\r\n\t\t\tcase 'dot':\r\n\t\t\t\tisListWithNumber = false;\r\n\t\t\t\tLIST_SYMBOL = DOT;\r\n\t\t\t\tbreak;\r\n\t\t\tcase 'dash':\r\n\t\t\t\tisListWithNumber = false;\r\n\t\t\t\tLIST_SYMBOL = DASH;\r\n\t\t\t\tbreak;\r\n\t\t\tcase 'square':\r\n\t\t\t\tisListWithNumber = false;\r\n\t\t\t\tLIST_SYMBOL = SQUARE;\r\n\t\t\t\tbreak;\r\n\t\t\tcase 'number':\r\n\t\t\t\tisListWithNumber = true;\r\n\t\t\t\tbreak;\r\n\t\t\tdefault:\r\n\t\t\t\tisListWithNumber = false;\r\n\t\t\t\tLIST_SYMBOL = DOT;\r\n\t\t\t\tudateListSymbol(DOT);\r\n\t\t}\r\n\t});\r\n}", "function highlightList() {\n // read characters excluding saren\n var displayedCharactersExceptSaren = displayedCharacters.filter(function(value, index, arr) { return value != \"사렌\"; });\n // initialize character positions array\n var displayedCharactersTitlesArray = [];\n var displayedCharactersRelativePositionsArray = [];\n // read character positions. Read from the largest to the smallest position\n for(var j=displayedCharactersExceptSaren.length-1; j >= 0; j--) {\n displayedCharactersTitlesArray.push(displayedCharactersExceptSaren[j]);\n displayedCharactersRelativePositionsArray.push(characterRelativePositionsMap.get(displayedCharactersExceptSaren[j]));\n }\n // compute index of minimum entry. If multiple minima, character with largest position is chosen\n var minIndex = displayedCharactersRelativePositionsArray.indexOf(Math.min(...displayedCharactersRelativePositionsArray));\n // read objects representing saren and closest character\n var liSaren = document.getElementById(\"사렌\");\n var liClosestCharacter = document.getElementById(displayedCharactersTitlesArray[minIndex]);\n // highlight saren and closest character\n liSaren.className = \"list-group-item list-group-item-light text-center\";\n if(displayedCharacters.length > 1) {\n liClosestCharacter.className = \"list-group-item list-group-item-success text-center font-weight-bold\";\n }\n}", "addPhraseToDisplay() {\n //seperates the letters and spacing\n let letters = this.phrase.split('');\n //set empty template literal to variable\n let phraseUl = ``;\n\n //iterates through letters and creates a list object while simultaneously adding it to the template literal\n letters.forEach(letter => {\n if (letter.charAt(0) === ' ') {\n phraseUl += `<li class=\"space\"> </li>`;\n } else {\n phraseUl += `<li class=\"hide letter ${letter}\">${letter}</li>`;\n }\n });\n //adds phraseUl to html\n $('#phrase ul').append(phraseUl);\n }", "addPhraseToDisplay() {\n let chars = this.phrase.split('');\n const phraseUl = document.getElementById('phrase').children[0];\n\n chars.forEach(char => {\n if(char != ' ') {\n let li = document.createElement('li');\n li.setAttribute('class', `hide letter ${char}`);\n li.textContent = char;\n phraseUl.appendChild(li);\n }else {\n let li = document.createElement('li');\n li.setAttribute('class', `space`);\n li.textContent = char;\n phraseUl.appendChild(li);\n }\n })\n }", "function gotList(thelist) {\n \n println(\"List of Serial Ports:\");\n // theList is an array of their names\n for (var i = 0; i < thelist.length; i++) {\n // Display in the console\n println(i + \" \" + thelist[i]);\n }\n}", "function addPhrasetoDisplay (chosenPhrase) {\r\n for ( let i = 0; i < chosenPhrase.length; i++){\r\n const li = document.createElement(\"li\");\r\n li.textContent = chosenPhrase[i];\r\n ul.appendChild(li);\r\n if ( li.textContent == \" \") {\r\n li.className = \"space\"\r\n }else {\r\n li.className =\"letter\"\r\n }\r\n }\r\n}", "addPhraseToDisplay() {\n for (let i = 0; i < this.phrase.length; i++) {\n let listItem = document.createElement('li');\n (/\\s/g.test(this.phrase.charAt(i))) ? listItem.className = 'space' : listItem.classList.add('hide', 'letter', `${this.phrase.charAt(i)}`); //If the character is a space, it is given a different class name.\n listItem.innerHTML = `${this.phrase.charAt(i)}`;\n document.getElementById('phrase').children[0].appendChild(listItem);\n }\n }", "function addPhraseToDisplay () {\n var letter=getRandomPhraseAsArray();\n for (var i= 0; i<letter.length; i++){\n if (letter[i] !== \" \"){\n var li=document.createElement(\"li\");\n li.appendChild(document.createTextNode(letter[i]));\n li.classList.add(\"letter\");\n ul.appendChild(li);\n } else {\n var li=document.createElement(\"li\");\n li.appendChild(document.createTextNode(letter[i]));\n li.classList.add(\"space\");\n ul.appendChild(li);\n }\n }\n return letter;\n}", "function populateLiElements(input, list, ul) {\n var html = \"\";\n var selectedClass = \"selected\";\n list.forEach(function(element) {\n var index = element.indexOf(input);\n var pre = element.substring(0, index);\n var post = element.substring(index + input.length);\n html = html + '<li class=\"' + selectedClass + '\" element=\"' + element + '\"><p>' + pre + '<span>' + input + '</span>' + post + '</p></li>';\n selectedClass = \"\";\n });\n ul.innerHTML = html;\n}", "function gotList(thelist) {\n println(\"List of Serial Ports:\");\n // theList is an array of their names\n for (var i = 0; i < thelist.length; i++) {\n // Display in the console\n println(i + \" \" + thelist[i]);\n }\n}", "function List( element ) {\n\tthis.element = element;\n}", "optionsList(){\n this.alphabet = 64;\n return this.props.question.options.map((item,index)=>{\n return(\n <span key={index} className=\"option\">{String.fromCharCode(++this.alphabet)} - {item}</span>\n )\n })\n }", "characterList() {\n var charSearch = this.state.charSearch;\n var url = `https://gateway.marvel.com/v1/public/characters?nameStartsWith=${charSearch}&limit=50&ts=1&apikey=24b734a9df515f87bbe1bac66f8dbd5c&hash=a4374486b969b3e7b91f44c63fe5a64d`;\n return $.ajax({\n url: url,\n method: \"GET\",\n success: data => {\n const newAddress = `${data.attributionHTML.slice(\n 0,\n 27\n )} target=\"_blank\"${data.attributionHTML.slice(27)}`;\n\n this.setState({\n characters: data.data.results,\n // credit: data.attributionHTML\n credit: newAddress\n });\n }\n });\n }", "function character(necessaryConditions,triggers,precludingConditions,bigImage,lilImage,charAsString){\n this.necessaryConditions = necessaryConditions;\n this.triggers = triggers;\n this.precludingConditions = precludingConditions;\n /* \n Each character has a big and lil image variety. The lil image variety is used when the character is being added\n to a super script or a subscript \n */\n this.bigImage = bigImage;\n this.lilImage = lilImage;\n this.charAsString = charAsString;\n\n}", "renderList(list, asteroid) {\n\t\tlist.innerHTML += `\n\t\t<li class=\"list-group-item d-flex justify-content-between align-items-center\">\n\t\t\t<span>${asteroid}</span>\n\t\t\t<i class=\"delete\">X</i>\n\t\t</li>`;\n\t}", "function gotList(thelist) {\n print(\"List of Serial Ports:\");\n // theList is an array of their names\n for (var i = 0; i < thelist.length; i++) {\n // Display in the console\n print(i + \" \" + thelist[i]);\n }\n}", "function createEmojiList(list, lvl) {\r\n let selected = []\r\n for (let i = 0; i < lvl + 2; i++) {\r\n let index = Math.floor(Math.random() * list.length)\r\n selected.push(list[index]);\r\n \r\n }\r\n \r\n return selected\r\n}", "function generateListItem(content, buffer) {\n var indent = '';\n for (var i = 0; i < buffer; i++) {\n indent += ' ';\n }\n return `${indent}- ${content}`;\n}", "render() {\n //Whenever the state is updated the render method is called, the result is rendered in CharacterList.\n //Note that a reference to the function is passed.\n const characters = this.state.characters\n return (\n <div>\n <SearchForm searchFn={this.searchFn} />\n {this.state.isJarJar &&\n <h2>Nobody likes Jar Jar binks!</h2>\n }\n\n {characters &&\n <CharacterList characters={characters} />\n }\n\n </div>\n );\n }", "function CharacterDefinition() {\n this.character_category_map = new Uint8Array(65536); // for all UCS2 code points\n this.compatible_category_map = new Uint32Array(65536); // for all UCS2 code points\n this.invoke_definition_map = null;\n\n}", "addPhraseToDisplay() {\n const ul = document.querySelector(\"ul\");\n let disPhrase = this.phrase;\n //this will add the phrase to the display\n for (let i = 0; i < disPhrase.length; i++) {\n if (disPhrase[i] !== \" \") {\n let li = document.createElement(\"li\");\n li.classList.add(\"letter\");\n li.classList.add(\"hide\");\n li.textContent = disPhrase.charAt(i);\n ul.appendChild(li);\n } else if (disPhrase[i] === \" \") {\n let liSpace = document.createElement(\"li\");\n liSpace.classList.add(\"space\");\n liSpace.textContent = disPhrase.charAt(i);\n ul.appendChild(liSpace);\n }\n }\n return ul;\n }", "function listControl(e) {\n\n const input = target(e);\n if (!input || !input.datalist) return;\n\n switch (e.keyCode) {\n\n case 40: {\n // arrow down\n let opt = input.datalist.firstElementChild;\n opt && opt.focus();\n break;\n }\n\n case 27: // tab\n case 9: // tab\n listHide(input.datalist);\n break;\n\n case 13: // enter\n case 32: // space\n listSet(e);\n break;\n\n }\n\n }", "addPhraseToDisplay() {\r\n let eachLetter = this.phrase.split('');\r\n const phraseUL = document.querySelector('#phrase ul');\r\n for (let i = 0; i < eachLetter.length; i++) {\r\n let li = document.createElement('li');\r\n let text = document.createTextNode(eachLetter[i]);\r\n li.appendChild(text);\r\n phraseUL.appendChild(li);\r\n if (eachLetter[i] != ' ') {\r\n li.className = 'hide letter';\r\n li.classList.add(eachLetter[i]);\r\n } else {\r\n li.className = 'space';\r\n }\r\n }\r\n }", "function displayChar(c) {\n LaunchBar.displayInLargeType({\n\ttitle: c.name,\n\tstring: c.c,\n });\n}", "addPhraseToDisplay() {\n const keyboard = this.phrase.split('');\n for (let i = 0; i < keyboard.length; i++){\n let li = document.createElement('li');\n li.textContent = keyboard[i];\n keyboard[i] === ' ' ? li.className = 'hide space' : li.className = `hide letter ${keyboard[i]}`\n document.querySelector('#phrase ul').appendChild(li);\n }\n }", "set list(list){\n this._list = list;\n this.render()\n }", "function nameTable(list) {\r\n var result = '<table class=\"w3-table-all w3-hoverable\" border=\"2\"><tr><th>Number</th><th>Name</th><th>Link to Character Page</th><tr>';\r\n var a = list.split(\",\");\r\n indexList = a.slice(0); //copy the cgi output to the indexList global variable.\r\n var aLen = a.length;\r\n //there are 11 pieces of character info we are using so we have to increment by 12. Also, we are only using three columns for the table.\r\n for (var i = 0; i < aLen; i+=12) {\r\n\tresult += \"<tr><td>\"+a[i] +\"</td><td>\"+\"<div class='charname' data=\\'\"+ i + \"\\'>\" + a[i+1]+\"</div>\" + \"</td><td>\"+ \"<a href =\" +a[i+2]+ \">Link</a>\"+\"</td></tr>\";\r\n }\r\n result += \"</table>\";\r\n\r\n return result;\r\n}", "function gotList(thelist) {\n println(\"List of Serial Ports:\");\n // theList is an array of their names\n for (var i = 0; i < thelist.length; i++) {\n // Display in the console\n println(i + \" \" + thelist[i]);\n }\n}", "addPhraseToDisplay() {\r\n //str.match(/[a-z]/i\r\n let ul = document.querySelector('UL'),\r\n li;\r\n let displayPhrase = this.phrase;\r\n for (let i = 0; i < displayPhrase.length; i++) {\r\n if (displayPhrase[i].match(/[a-z]/i)) {\r\n li = document.createElement('LI');\r\n li.classList.add('hide', 'letter');\r\n li.innerText = displayPhrase[i];\r\n ul.appendChild(li);\r\n } else if (displayPhrase[i].match('')) {\r\n li = document.createElement('LI');\r\n li.classList.add('space');\r\n li.innerText = displayPhrase[i];\r\n ul.appendChild(li);\r\n }\r\n }\r\n }", "function Object_Character(record, data) {\n var ref, ref1;\n Object_Character.__super__.constructor.call(this, data);\n\n /**\n * The object's source rectangle on screen.\n * @property srcRect\n * @type gs.Rect\n */\n this.srcRect = new Rect();\n\n /**\n * The object's z-index.\n * @property zIndex\n * @type number\n */\n this.zIndex = 200;\n\n /**\n * The object's mask.\n * @property mask\n * @type gs.Mask\n */\n this.mask = new gs.Mask();\n\n /**\n * The color tone of the object used for the visual presentation.\n * @property tone\n * @type gs.Tone\n */\n this.tone = new Tone(0, 0, 0, 0);\n\n /**\n * Indicates if the object's visual presentation should be mirrored horizontally.\n * @property mirror\n * @type boolean\n */\n this.mirror = (ref = data != null ? data.mirror : void 0) != null ? ref : false;\n\n /**\n * The object's image used for visual presentation.\n * @property image\n * @type string\n */\n this.image = \"\";\n\n /**\n * The ID of the character-record used.\n * @property rid\n * @type number\n */\n this.rid = (data != null ? data.id : void 0) || ((ref1 = record != null ? record.index : void 0) != null ? ref1 : -1);\n\n /**\n * The character's expression(database-record)\n * @property expression\n * @type Object\n */\n this.expression = RecordManager.characterExpressions[(data != null ? data.expressionId : void 0) || 0];\n\n /**\n * The character's behavior component which contains the character-specific logic.\n * @property behavior\n * @type vn.Component_CharacterBehavior\n */\n this.behavior = new vn.Component_CharacterBehavior();\n this.logic = this.behavior;\n\n /**\n * The object's animator-component to execute different kind of animations like move, rotate, etc. on it.\n * @property animator\n * @type vn.Component_Animator\n */\n this.animator = new gs.Component_Animator();\n\n /**\n * The object's visual-component to display the game object on screen.\n * @property visual\n * @type gs.Component_Sprite\n */\n this.visual = new gs.Component_Sprite();\n this.visual.imageFolder = \"Graphics/Characters\";\n this.addComponent(this.logic);\n this.addComponent(this.visual);\n this.addComponent(this.animator);\n this.componentsFromDataBundle(data);\n }", "function get_character(workspace, char) {\n const x = (char * font_width) % (font_width * spritesheet_columns);\n const y = font_height * Math.floor(char / spritesheet_columns);\n return workspace.spritesheet_ctx.getImageData(x, y, font_width, font_height);\n }", "function Character() {\n this.race = race(Math.floor(Math.random() * Math.floor(5)));\n this.charClass = charClass(Math.floor(Math.random() * Math.floor(5)));\n this.ability1 = abilities(Math.floor(Math.random() * Math.floor(5)));\n this.ability2 = abilities(Math.floor(Math.random() * Math.floor(5)));\n this.ability3 = abilities(Math.floor(Math.random() * Math.floor(5)));\n this.ability4 = abilities(Math.floor(Math.random() * Math.floor(5)));\n this.age = Math.floor(Math.random() * Math.floor(40) + 11);\n //ability: {\" \", \" \", \" \", \" \"}\n}", "function character(index, name, photo, healthPoints, attackPower, baseAttackPower, counterAttackPower,status)\n\t\t{\n\t\t this.characterIndex = index;\n\t\t this.characterName = name;\n\t\t this.characterPhoto = photo;\n\t\t this.characterHealthPoints = healthPoints;\n\t\t this.characterAttackPower = attackPower;\n\t\t this.characterBaseAttackPower = baseAttackPower;\n\t\t this.characterCounterAttackPower = counterAttackPower;\n\t\t this.characterStatus = '';\n\t\t}", "addPhraseToDisplay() {\r\n //display the number of letters in the activePhrase, each letters gets a box\r\n //store the phrase div\r\n const phraseDiv = document.querySelector('#phrase');\r\n const ul = phraseDiv.firstElementChild;\r\n // console.log(ul);\r\n\r\n //create a loop to go through the number of leters in the activePhrase\r\n // console.log(`active phrase has ${this.phrase.length} letters`);\r\n\r\n for(let i = 0; i < this.phrase.length; i++){\r\n // console.log(`in for loop`);\r\n //create li elements\r\n const li = document.createElement('li');\r\n ul.appendChild(li);\r\n\r\n //if there is a space\r\n if(this.phrase.charAt(i) === ' '){\r\n li.setAttribute('class', `hide space`);\r\n } else{\r\n li.setAttribute('class', `hide letter ${this.phrase.charAt(i)}`);\r\n li.textContent = this.phrase.charAt(i);\r\n }\r\n };\r\n }", "getWordList(dataList){\n var temp = [];\n for(const word of dataList){\n temp.push(\n <ToggleButton value = {word}>{word}</ToggleButton>\n )\n }\n return temp;\n }", "function printLexemesInList(list) {\n sessionService.getSession().then(function (session) {\n var config = session.projectSettings().config;\n var ws = config.entry.fields.lexeme.inputSystems[1];\n var arr = [];\n for (var i = 0; i < list.length; i++) {\n if (angular.isDefined(list[i].lexeme[ws])) {\n arr.push(list[i].lexeme[ws].value);\n }\n }\n\n console.log(arr);\n });\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 loadHeroChoices(listElem) {\r\n\r\n listElem.empty();\r\n for (var i = 0;\r\n (i < heroes.length); i++) {\r\n var li = $(\"<li>\");\r\n $(li).addClass(\"list-group-item\");\r\n $(li).addClass(\"character-choice\");\r\n $(li).text(heroes[i].name);\r\n $(li).attr(\"data-name\", heroes[i].name);\r\n listElem.append(li)\r\n }\r\n}", "function showSymbols(e) {\n let letters = findSymbols(e.target.value, names, nameMap);\n let list = '';\n for (const index in letters) {\n list +=\n `<div class='label'> ${letters[index][0]} </div>` +\n `<textarea onclick='copyToClipboard(\"${letters[index][1]}\")' class='symbol' readonly='true' rows='1' cols='1' >${letters[index][1]}</textarea>`;\n }\n nameList.innerHTML = list;\n}" ]
[ "0.7503867", "0.70428145", "0.6462923", "0.6369874", "0.6329092", "0.6191434", "0.61053944", "0.5982004", "0.5904742", "0.5833651", "0.5802779", "0.5763262", "0.57569045", "0.5744987", "0.57270724", "0.5718097", "0.56480795", "0.5628221", "0.5623102", "0.5618244", "0.55883265", "0.55866784", "0.5585691", "0.557805", "0.55719453", "0.55702037", "0.5548012", "0.5543907", "0.54928476", "0.54865", "0.54740673", "0.5472911", "0.5464971", "0.5458593", "0.5452113", "0.5451303", "0.5441496", "0.54411805", "0.54337114", "0.54326165", "0.5426126", "0.541543", "0.5411986", "0.5410757", "0.5409604", "0.53980786", "0.53906447", "0.5387709", "0.5381359", "0.5373052", "0.5368232", "0.5362535", "0.53601784", "0.5351647", "0.53452516", "0.5344089", "0.5340984", "0.533785", "0.532707", "0.532595", "0.532595", "0.53215134", "0.53144175", "0.52977806", "0.52977216", "0.52874947", "0.5286699", "0.5285435", "0.5282207", "0.5277329", "0.5268958", "0.5266143", "0.52630967", "0.5262012", "0.5261962", "0.5261141", "0.5249051", "0.5248928", "0.5247954", "0.5241727", "0.52413976", "0.52349955", "0.5233779", "0.52317774", "0.5227021", "0.52218056", "0.52213925", "0.5216879", "0.5211372", "0.5208735", "0.52010995", "0.51964706", "0.5194365", "0.51924264", "0.51886505", "0.5184908", "0.518383", "0.5179012", "0.5175809", "0.51726794" ]
0.695069
2
! Init all element to usage \param src source of the image \param boundingBox list of boundingBox from the server \param baselines list of baselines from the server
function init(src, boundingBox, baseline) { var image = new ProcessingImage(src); var imagePreview = new ProcessingImage(src); var listRect = new Array(); for (var rect in boundingBox) { listRect.push(new Rectangle({x:boundingBox[rect].x, y:boundingBox[rect].y, w:boundingBox[rect].width, h: boundingBox[rect].height},boundingBox[rect].idCC, boundingBox[rect].idLine)); } var boundingBox = new BoundingBox(listRect); var listBaseline = new Array(); for (var line in baseline) { listBaseline.push(new Line(baseline[line].idLine, baseline[line].x_begin,baseline[line].y_baseline,baseline[line].x_end)); } var baseline = new Baseline(listBaseline); var previewCanvas = new PreviewCanvas(document.getElementById('small_canvas'), imagePreview); var normalCanvas = new Canvas(document.getElementById('canvas'), image, baseline, boundingBox); var listCharacter = new ListCharacter(); var controller = new Controller(normalCanvas, previewCanvas, listCharacter); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function Baseline(lines) {\n this.lines = lines;\n this.visible = false;\n this.clickMargin = 0.4; //in percent of the image height\n}", "function setImages(data){\r\n for(i=0;i<data.length; i++)\r\n {\r\n imgBlocks[i].src = data[i].URL; \r\n imgBlocks[i].name = data[i].name;\r\n imgBlocks[i].alt = data[i].alt; \r\n } \r\n}", "function addRectImage(imageSrc) {\n var tryOnObj = new Image();\n tryOnObj.src = imageSrc;\n\n tryOnObj.onload = function() {\n var rectImage = new Box2Image;\n rectImage.x = 20;\n rectImage.y = 20;\n rectImage.w = tryOnObj.width;\n rectImage.h = tryOnObj.height;\n rectImage.imageObj = tryOnObj;\n boxes2Images.push(rectImage);\n invalidate();\n };\n\n \n}", "function mkBoxes() {\n boxes.forEach(function(val){\n ctx.drawImage(boxImg, val[0] * boxSize, val[1] * boxSize, boxSize, boxSize);\n })\n}", "function _via_load_canvas_regions() {\n // load all existing annotations into _via_canvas_regions\n var regions = _via_img_metadata[_via_image_id].regions;\n _via_canvas_regions = [];\n for ( var i = 0; i < regions.length; ++i ) {\n var region_i = new ImageRegion();\n for ( var key in regions[i].shape_attributes ) {\n region_i.shape_attributes[key] = regions[i].shape_attributes[key];\n }\n _via_canvas_regions.push(region_i);\n\n switch(_via_canvas_regions[i].shape_attributes['name']) {\n case VIA_REGION_SHAPE.RECT:\n var x = regions[i].shape_attributes['x'] / _via_canvas_scale;\n var y = regions[i].shape_attributes['y'] / _via_canvas_scale;\n var width = regions[i].shape_attributes['width'] / _via_canvas_scale;\n var height = regions[i].shape_attributes['height'] / _via_canvas_scale;\n var name = regions[i].region_attributes['name'];\n var color = _via_class_names.get(name)[1];\n\n _via_canvas_regions[i].shape_attributes['x'] = Math.round(x);\n _via_canvas_regions[i].shape_attributes['y'] = Math.round(y);\n _via_canvas_regions[i].shape_attributes['width'] = Math.round(width);\n _via_canvas_regions[i].shape_attributes['height'] = Math.round(height);\n _via_canvas_regions[i].region_attributes['name'] = name;\n _via_canvas_regions[i].region_attributes['color'] = color;\n break;\n }\n }\n\n//this is where we load our saved data\n if (sessionStorage.getItem(\"page_data\") == null) {\n _via_first_load = false;\n }\n if (_via_first_load){\n info = JSON.parse(sessionStorage.getItem(\"page_data\"));\n //manually add the metadata into what we have\n var new_metadata = new ImageMetadata;\n new_metadata[\"filename\"] = \"cars.png\";\n new_metadata[\"fileref\"] = \"cars.png\";\n new_metadata[\"base64_img_data\"] = \"cars.png\";\n new_metadata[\"file_attributes\"] = info[\"cars.png62201\"][\"file_attributes\"];\n new_metadata[\"size\"] = info[\"cars.png62201\"][\"size\"];\n\n for (var i = 0; i < info[\"cars.png62201\"][\"regions\"].length; i++){\n var new_region = new ImageRegion;\n new_region[\"is_user_selected\"] = info[\"cars.png62201\"][\"regions\"][i][\"is_user_selected\"];\n new_region[\"region_attributes\"] = info[\"cars.png62201\"][\"regions\"][i][\"region_attributes\"];\n new_region[\"shape_attributes\"] = info[\"cars.png62201\"][\"regions\"][i][\"shape_attributes\"];\n new_metadata[\"regions\"].push(new_region);\n if(sessionStorage.getItem(\"global_index\") == 0){\n _via_canvas_regions.push(new_region);\n }\n }\n\n _via_img_metadata[\"cars.png62201\"] = new_metadata;\n\n var new_metadata = new ImageMetadata;\n new_metadata[\"filename\"] = \"lot.jpeg\";\n new_metadata[\"fileref\"] = \"lot.jpeg\";\n new_metadata[\"base64_img_data\"] = \"lot.jpeg\";\n new_metadata[\"file_attributes\"] = info[\"lot.jpeg71862\"][\"file_attributes\"];\n new_metadata[\"size\"] = info[\"lot.jpeg71862\"][\"size\"];\n\n\n for (var i = 0; i < info[\"lot.jpeg71862\"][\"regions\"].length; i++){\n var new_region = new ImageRegion;\n new_region[\"is_user_selected\"] = info[\"lot.jpeg71862\"][\"regions\"][i][\"is_user_selected\"];\n new_region[\"region_attributes\"] = info[\"lot.jpeg71862\"][\"regions\"][i][\"region_attributes\"];\n new_region[\"shape_attributes\"] = info[\"lot.jpeg71862\"][\"regions\"][i][\"shape_attributes\"];\n new_metadata[\"regions\"].push(new_region);\n //_via_canvas_regions.push(new_region);\n\n if(sessionStorage.getItem(\"global_index\") == 1){\n \n _via_canvas_regions.push(new_region);\n }\n\n\n }\n\n _via_img_metadata[\"lot.jpeg71862\"] = new_metadata;\n\n var new_metadata = new ImageMetadata;\n new_metadata[\"filename\"] = \"outside.jpeg\";\n new_metadata[\"fileref\"] = \"outside.jpeg\";\n new_metadata[\"base64_img_data\"] = \"outside.jpeg\";\n new_metadata[\"file_attributes\"] = info[\"outside.jpeg21513\"][\"file_attributes\"];\n new_metadata[\"size\"] = info[\"outside.jpeg21513\"][\"size\"];\n\n\n for (var i = 0; i < info[\"outside.jpeg21513\"][\"regions\"].length; i++){\n var new_region = new ImageRegion;\n new_region[\"is_user_selected\"] = info[\"outside.jpeg21513\"][\"regions\"][i][\"is_user_selected\"];\n new_region[\"region_attributes\"] = info[\"outside.jpeg21513\"][\"regions\"][i][\"region_attributes\"];\n new_region[\"shape_attributes\"] = info[\"outside.jpeg21513\"][\"regions\"][i][\"shape_attributes\"];\n new_metadata[\"regions\"].push(new_region);\n //_via_canvas_regions.push(new_region);\n\n if(sessionStorage.getItem(\"global_index\") == 2){\n \n _via_canvas_regions.push(new_region);\n }\n }\n\n _via_img_metadata[\"outside.jpeg21513\"] = new_metadata;\n\n\n repopulate();\n _via_redraw_reg_canvas();\n show_all_canvas();\n\n _via_is_window_resized = true;\n show_image(_via_image_index);\n _via_first_load = false;\n }\n}", "function aladin_setImage(\n aladin,\n imgsource,\n imgname,\n pos_ra, pos_dec\n){\n var IMG = new Image();\n IMG.src = imgsource;\n var cat = A.catalog({shape: IMG, name: imgname})\n aladin.addCatalog(cat);\n cat.addSources(A.source(pos_ra, pos_dec))\n}", "function image_widget()\n{\n var widget = {\n init:function(bbox){ \n this.group = draw.group(); \n this.bbox = bbox; \n }, \n\n update:function(json){ \n this.group.clear(); \n this.group.image(json.url, json.width, json.height); \n fit_svg(this.group, this.bbox); \n }, \n } \n return widget;\n}", "function initialize(){\n\t\n\t//initialize global objects\n\tsvs = new google.maps.StreetViewService();\n\tgeocoder = new google.maps.Geocoder();\n\tmaxRad = 50;\n\t\n\t//retreive list of house and image results\n\tvar houseList = document.getElementsByClassName(\"address\");\n\t//var imgList = getElementsByClassName(\"img\");\n/*\n\t//process each house\n\tfor(var i = 0; i < houseList.length; i++){\n\t\t//alert(houseList[i].innerText);\n\t\tsetSVC(houseList[i]);\n \t document.getElementById(\"img\"+i).setAttribute(\"src\",imgURL);\n\n\t}*/\n\tsetSVC(houseList[0]);\n\tdocument.getElementByID(\"img\"+i).setAttribute(\"src\",imgURL);\n}", "function drawBoxes(boxes) {\n progressMessage.setProgressMessage(\"draw bounding boxes\");\n boxpolys = new Array(boxes.length);\n for (var i = 0; i < boxes.length; i++) {\n boxpolys[i] = new google.maps.Rectangle({\n bounds: boxes[i],\n fillOpacity: 0,\n strokeOpacity: 1.0,\n strokeColor: '#000000',\n strokeWeight: 1,\n map: map\n });\n }\n}", "function addBgImg() {\n var bgImgExist = false;\n if (Maids[pageFocus].length > 0 && Maids[pageFocus][0][\"type\"] == \"genericLoaderImgFull/generic\") {\n bgImgExist = true;\n }\n if (!bgImgExist) {\n var newItem = new cloneObject(modelMaid);\n newItem[\"function\"] = \"ImgLoaderFull\";\n newItem[\"id\"] = \"clip\" + (Maids[pageFocus].length + 1);\n newItem[\"type\"] = \"genericLoaderImgFull/generic\";\n newItem[\"data\"][\"img\"] = env + \"img/BG.jpg\";\n if (!imgLibrary[newItem[\"data\"][\"img\"]]) {\n var rt = new Image();\n rt.crossOrigin = 'crossdomain.xml';\n rt.src = proxy + newItem[\"data\"][\"img\"];\n rt.onload = function() {\n imgLibrary[newItem[\"data\"][\"img\"]] = rt;\n newItem[\"x\"] = 0;\n newItem[\"y\"] = 0;\n newItem[\"w\"] = rt.naturalWidth;\n newItem[\"h\"] = rt.naturalHeight;\n newItem[\"data\"][\"width\"] = rt.naturalWidth;\n newItem[\"data\"][\"height\"] = rt.naturalHeight;\n newItem[\"data\"][\"relRot\"] = 0;\n maidSelect = newItem;\n dataMode = new Array(Number(maidSelect[\"x\"]), Number(maidSelect[\"y\"]), Number(maidSelect[\"data\"][\"width\"]), Number(maidSelect[\"data\"][\"height\"]));\n Maids[pageFocus].splice(0, 0, newItem);\n returnToEditor();\n }\n rt.onerror = function() {\n imgLibrary[newItem[\"data\"][\"img\"]] = common.toolImages.errorImg[1];\n newItem[\"x\"] = 0;\n newItem[\"y\"] = 0;\n newItem[\"w\"] = rt.naturalWidth;\n newItem[\"h\"] = rt.naturalHeight;\n newItem[\"data\"][\"width\"] = rt.naturalWidth;\n newItem[\"data\"][\"height\"] = rt.naturalHeight;\n newItem[\"data\"][\"relRot\"] = 0;\n maidSelect = newItem;\n dataMode = new Array(Number(maidSelect[\"x\"]), Number(maidSelect[\"y\"]), Number(maidSelect[\"data\"][\"width\"]), Number(maidSelect[\"data\"][\"height\"]));\n Maids[pageFocus].splice(0, 0, newItem);\n returnToEditor();\n }\n } else {\n newItem[\"x\"] = 0;\n newItem[\"y\"] = 0;\n newItem[\"w\"] = imgLibrary[newItem[\"data\"][\"img\"]].naturalWidth;\n newItem[\"h\"] = imgLibrary[newItem[\"data\"][\"img\"]].naturalHeight;\n newItem[\"data\"][\"width\"] = imgLibrary[newItem[\"data\"][\"img\"]].naturalWidth;\n newItem[\"data\"][\"height\"] = imgLibrary[newItem[\"data\"][\"img\"]].naturalHeight;\n newItem[\"data\"][\"relRot\"] = 0;\n maidSelect = newItem;\n dataMode = new Array(Number(maidSelect[\"x\"]), Number(maidSelect[\"y\"]), Number(maidSelect[\"data\"][\"width\"]), Number(maidSelect[\"data\"][\"height\"]));\n Maids[pageFocus].splice(0, 0, newItem);\n returnToEditor();\n }\n } else {\n alert(\"Ya existe una imagen de fondo elim�nala primero o cambiala desde el panel del maid\");\n returnToEditor();\n }\n\n}", "_initSources() {\n // finally load every sources already in our plane html element\n // load plane sources\n let loaderSize = 0;\n if(this.autoloadSources) {\n const images = this.htmlElement.getElementsByTagName(\"img\");\n const videos = this.htmlElement.getElementsByTagName(\"video\");\n const canvases = this.htmlElement.getElementsByTagName(\"canvas\");\n\n // load images\n if(images.length) {\n this.loadImages(images);\n }\n\n // load videos\n if(videos.length) {\n this.loadVideos(videos);\n }\n\n // load canvases\n if(canvases.length) {\n this.loadCanvases(canvases);\n }\n\n loaderSize = images.length + videos.length + canvases.length;\n }\n\n this.loader._setLoaderSize(loaderSize);\n\n this._canDraw = true;\n }", "function init() {\n renderImgs(gImgs, '.gallery-cont');\n renderCloud(gKeywords);\n \n $('.img').click(function () {\n gState.selectedImgId = this.id;\n $('.main-cont').toggle();\n $('.meme-cont').toggle();\n renderCanvas(gState, gMapImg);\n })\n\n \n\n \n}", "function onSourceLoad() {\n var con = document.createElement('div');\n con.innerHTML = document.querySelector('.source_con .source').value;\n\n // reset pins\n resetImageState();\n removeAllPins();\n\n try {\n var img = con.querySelector('img');\n\n var coords = [];\n // from data-pins (clickimage.js parsing method)\n if(img.dataset.pins != undefined) coords = parsePinCoordinates(img.dataset.pins); //eslint-disable-line\n // from onload (own method)\n else if(img.getAttribute('onload') != undefined) coords = parsePinCoordinatesFromOnLoad(img);\n\n createPinsFromCoordinates(coords);\n loadPinInfos(con.querySelector('.pininfo').children);\n // get actual src string, without any domain addition (like img.src)\n document.querySelector('.general_edit .image_src').value = img.getAttribute(\"src\");\n document.querySelector('.general_edit .image_invert_colors').checked =\n con.querySelector('.imagebox').classList.contains('invert');\n } catch(e) {\n //TODO display some error\n }\n\n resetPageState();\n }", "function initImageLoading() {\n var imageBox = document.querySelector('.image_box');\n var fileChooser = imageBox.querySelector('.box_file');\n\n if(advancedLoad) {\n imageBox.className += \" advanced\";\n initDragDropListeners(imageBox);\n }\n\n imageBox.addEventListener('click', function() {\n resetInfos(imageBox);\n fileChooser.click();\n });\n\n fileChooser.addEventListener('change', function() {\n checkFiles(imageBox, this.files);\n });\n }", "function initImg(){\r\n \r\n // alert(\"Starting initImg\");\r\n \r\n img = document.getElementById('id_img1');\r\n\r\n var newimg = new Image();\r\n\r\n newimg.onload = function()\r\n {\r\n img.src = newimg.src;\r\n shapeImg(newimg.width , newimg.height);\r\n // alert(\"initImg: img.width = \" + img.width );\r\n // alert(\"initImg: img.height = \" + img.height );\r\n }\r\n\r\n newimg.src = images[imgindex];\r\n\r\n // ## The following works in Mozilla&Firefox but not MS-IE.\r\n // document.id_img1.src = images[imgindex];\r\n\r\n\r\n\r\n document.getElementById('label1').innerHTML=String(imgindex + 1);\r\n document.getElementById('label2').innerHTML=images.length.toString(10);\r\n document.getElementById('label3').innerHTML=String(imgindex + 1);\r\n document.getElementById('label4').innerHTML=images.length.toString(10);\r\n document.getElementById('label5').innerHTML=String(imgindex + 1);\r\n document.getElementById('label6').innerHTML=images.length.toString(10);\r\n}", "constructor(imageTotal, element){\n\t\tsuper(imageTotal)\n\t\tthis.ELEMENT = element\n\t\tthis.GRID_DOM = this.createGD(this.GRID)\n\t\tthis.DOM_BEFORE = null;\n\t}", "constructor( e, x, label=undefined )\n {\n this.e = e;\n this.oType = \"Homebase\";\n this.p = new Point( x, 0, 2 );\n this.label = label;\n this.imgFactor = .6;\n this.colRect = [ -12, 1, 12, 0 ];\n\n this.resupTimer = Base.BASE_RESUP_INTERVAL; // increase our resources\n // Base has resources that the Chopper can take when it lands.\n let r = Helicopter.resourceMaxAmount;\n this.curAmount = { fuel : r.fuel,\n StructI : r.StructI,\n bullets : r.bullets,\n missileA : r.missileA,\n missileB : r.missileB,\n bombs : r.bombs };\n \n if( !Base.image )\n {\n Base.img = new Image();\n Base.img.src = \"./images/backgrounds/base.gif\";\n }\n }", "function addFloorImages() {\n // images from preview pane\n var currentImages = $('#currentImages');\n // images from navigation carousel\n var navigationImages = $('#navigationImages');\n var floorNames = Object.keys(buildingFloors);\n floorNames.alphanumSort(true);\n // add floor images to carousels in alphanumeric order of floor names\n for (var i = 0; i < floorNames.length; i++) {\n var floorName = floorNames[i];\n var image = floorImages[floorName];\n var dataURL = image.dataURL;\n var imageStr = image.imageStr;\n var stageImage = $('<li><img class=\"currentImage\" src=\"' + dataURL + imageStr + '\"></li>');\n var navImage = $('<li><img data-internalid='+floorName+' class=\"navigationImage\" src=\"' + dataURL + imageStr + '\"></li>');\n currentImages.append(stageImage);\n navigationImages.append(navImage);\n // initialize canvas with lowest floor\n if (i === 0) {\n var currentFloor = stateManager.getCurrentFloor();\n currentFloor.globals.canvas.image = $('<img class=\"currentImage\" src=\"' + dataURL + imageStr + '\">')[0];\n }\n }\n setTimeout(function() {\n initCarousels();\n $('#loading').css('display', 'none');\n }, 0) \n}", "function init() {\r\n //tie the inputfile element labels to an change event listener\r\n var inputs = document.querySelectorAll(\".files\")\r\n //setup the onchange events for all the file load elements\r\n Array.prototype.forEach.call(inputs, (input) => {\r\n input.addEventListener(\"change\", (e) => loadTileSet(e))\r\n })\r\n}", "function init() {\n usa_img = document.getElementById('usa');\n brit_img = document.getElementById('brit');\n console.log(\"INIT\");\n canvases = document.getElementsByClassName(\"rotate\");\n canvases_offset = document.getElementsByClassName(\"rotate_offset\");\n draw();\n}", "function drawBoxes(objects) {\n\n //clear the previous drawings\n drawCtx.clearRect(0, 0, drawCanvas.width, drawCanvas.height);\n\n //filter out objects that contain a class_name and then draw boxes and labels on each\n objects.forEach(face => {\n let scale = uploadScale();\n let _x = face.x / scale;\n let y = face.y / scale;\n let width = face.w / scale;\n let height = face.h / scale;\n //flip the x axis if local video is mirrored\n if (mirror) {\n x = drawCanvas.width - (_x + width)\n } else {\n x = _x\n }\n\n let rand_conf = face.confidence.toFixed(2);\n let title = \"\" + rand_conf + \"\";\n if (face.name != \"unknown\") {\n drawCtx.strokeStyle = \"magenta\";\n drawCtx.fillStyle = \"magenta\";\n title += ' - ' + face.name\n if (face.predict_proba > 0.0 ) {\n title += \"[\" + face.predict_proba.toFixed(2) + \"]\";\n }\n } else {\n drawCtx.strokeStyle = \"cyan\";\n drawCtx.fillStyle = \"cyan\";\n }\n drawCtx.fillText(title , x + 5, y - 5);\n drawCtx.strokeRect(x, y, width, height);\n\n if(isCaptureExample && examplesNum < maxExamples) {\n console.log(\"capure example: \", examplesNum)\n\n //Some styles for the drawcanvas\n exCtx.drawImage(imageCanvas,\n face.x, face.y, face.w, face.h,\n examplesNum * exampleSize, 0,\n exampleSize, exampleSize);\n\n examplesNum += 1;\n\n if(examplesNum == maxExamples) {\n stopCaptureExamples();\n }\n }\n\n });\n}", "function loadImages(element,name, xPos, yPos, cursor, rot, container,alpha){\n var _bitmap = new createjs.Bitmap(queue.getResult(element)).set({});\n _bitmap.x = xPos;\n _bitmap.y = yPos;\n _bitmap.name = name;\n _bitmap.alpha = alpha;\n _bitmap.rotation = rot; \n _bitmap.cursor = cursor; \n if ( name == \"needle_zoom\" || name == \"zoom_bg\" ) {\n _bitmap.mask = zoom_area; /** Adding mask to zoom portion of lense */ \n } else if ( name == \"zoom_scale_ruler\" ) {\n _bitmap.mask = zoom_scale_mask;\n }\n if ( name == \"arrow_left\" ) {\n _bitmap.scaleY = -1;\n }\n container.addChild(_bitmap); /** Adding bitmap to the container */ \n stage.update();\n}", "portControl(helper) {\n stroke(83, 124, 123);\n strokeWeight(5);\n noFill();\n rect(this.x + this.width / 2 - 100, this.y + 280, 200, 200, 20);\n //headline\n textFont(myFontBold);\n textSize(60);\n fill(247, 240, 226);\n textAlign(CENTER);\n noStroke();\n text(\"Hafenkontrollen\", this.x + this.width / 2, this.y + 110);\n //describtion\n textSize(30);\n fill(83, 124, 123);\n text(\"Schütze deinen Hafen vor\", this.x + this.width / 2, this.y + 220);\n text(\"illegaler Fischerei\", this.x + this.width / 2, this.y + 250);\n //main image\n image(\n assets.visual.default.portControl,\n this.x + this.width / 2 - 75,\n this.y + 310,\n 150,\n 150\n );\n //clickable image array\n let x = this.x;\n let y = this.y;\n for (let i = 0; i < 10; i++) {\n image(assets.interactive.portControl, this.x + 130, this.y + 530, 40, 40);\n this.x += 45;\n if (i === 4) {\n this.y += 50;\n this.x = x;\n }\n }\n this.x = x;\n this.y = y;\n this.visualize.colorCheck();\n for (let i = 0; i < 10; i++) {\n image(\n assets.visual.default.portControl,\n this.x + 130,\n this.y + 530,\n 40,\n 40\n );\n if (\n mouseX > this.x + 130 &&\n mouseX < this.x + 170 &&\n mouseY > this.y + 530 &&\n mouseY < this.y + 570\n ) {\n this.chosenIndex = i + 1;\n }\n this.x += 45;\n if (i === 4) {\n this.y += 50;\n this.x = x;\n }\n }\n this.x = x;\n this.y = y;\n this.visualize.checkKey();\n this.visualize.doForKey(helper);\n this.portControlClicked();\n this.chosenIndex = 0;\n }", "function New_Image_Display(n) {\n image_index += n;\n if (image_index > image_files_in_dir.length) {\n image_index = 1\n }\n if (image_index < 1) {\n image_index = image_files_in_dir.length\n };\n \n val_obj = {descriptionInput:'', taglist:'', imgMain:image_files_in_dir[image_index - 1]}\n //view_annotate_module.Annotation_DOM_Alter(val_obj)\n\n //UNOCMMENT LATER!!!!\n tagging_view_annotate.Annotation_DOM_Alter(val_obj)\n\n //Load_State_Of_Image()\n\n //UNOCMMENT LATER!!!!\n Load_State_Of_Image_IDB() \n\n}", "constructor(id, src, environment, w=100, h=100) {\n this.id = id;\n this.image = new Image(w, h);\n this.image.src = src;\n this.environment = environment;\n }", "function backendOCR(base64Image, imageWidth, imageHeight) {\n ocrReq({image: base64Image})\n .then(lines => {\n lines.lines = lines;\n for (var idx = 0; idx < lines.lines.length; idx++) {\n lines.lines[idx].bbox.x0 = Math.round(lines.lines[idx].bbox.x0 * imageWidth);\n lines.lines[idx].bbox.x1 = Math.round(lines.lines[idx].bbox.x1 * imageWidth);\n lines.lines[idx].bbox.y0 = Math.round(lines.lines[idx].bbox.y0 * imageHeight);\n lines.lines[idx].bbox.y1 = Math.round(lines.lines[idx].bbox.y1 * imageHeight);\n }\n console.log(lines);\n handleOCRResult(lines);\n })\n .catch(error => {\n console.error(error);\n });\n}", "function uploadIMG(){\r\n image = new SimpleImage(fileinput);\r\n image1 = new SimpleImage(fileinput);\r\n image2 = new SimpleImage(fileinput);\r\n image3 = new SimpleImage(fileinput);\r\n image.drawTo(imgcanvas);\r\n clearAnon();\r\n}", "function init() {\n\t\t\tif (!container) return;\n\t\t\trequestImages();\n\t\t\tbuildLayout();\n\t\t}", "constructor({\n x = 128,\n y = 128,\n vx = 0,\n vy = 0,\n w = 24,\n h = 24,\n color = \"white\",\n assetImg = new Image(),\n isPlayer = false,\n hp = 0,\n isCollectible = false,\n POSES = [\n { qmax: 8, pv: 12 },\n { qmax: 8, pv: 12 },\n { qmax: 8, pv: 12 },\n { qmax: 8, pv: 12 },\n ],\n } = {}) {\n this.x = x;\n this.y = y;\n this.vx = vx;\n this.vy = vy;\n this.w = w;\n this.h = h;\n this.color = color;\n this.cena = null;\n this.mx = null;\n this.my = null;\n this.isCollectible = isCollectible;\n this.isPlayer = isPlayer;\n this.collected = 0;\n this.assetImg = assetImg;\n this.SIZE = 64;\n this.hp = hp;\n this.pose = 0;\n this.quadro = 0;\n this.POSES = POSES;\n }", "function processImageAnnotations( id, bb ) {\n annos[ id ] = {};\n for (var j = 0; j < bb.length; j++ ) {\n var v = bb[ j ];\n if ( !annos[ id ][ v[\"rdfs:note\"] ] ) { annos[ id ][ v[\"rdfs:note\"] ] = []; }\n annos[ id ][ v[\"rdfs:note\"] ].push( JSON.parse( v[\"cnt:bytes\"] ) );\n }\n viewer[ id ].goToPage( viewer[ id ].currentPage() ); // trigger page click to load page annotations\n}", "constructor () {\n this.size = 16;\n this.grid_status = this.makeStatus();\n this.boxies = this.makeBoxes();\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 }", "function initialisationOfImages() {\n var _blur_apply = new createjs.BlurFilter(12, 12, 12);\n getChild(\"focus_object\").filters = [_blur_apply]; \n getChild(\"focus_object\").cache(0, 0, getChild(\"focus_object\").image.width, getChild(\"focus_object\").image.height);\n stage.getChildByName(\"container_final\").visible = false;\n getChildFinal(\"Mercury\").alpha = 0;\n getChildFinal(\"Hydrogen\").alpha = 0;\n getChildFinal(\"Neon\").alpha = 0;\n getChildFinal(\"grating\").alpha = 0;\n getChildFinal(\"arrow_two_side\").alpha = 0;\n}", "static initialize(obj, title, image, ingredients, instructions, readyInMinutes, servings, mask, backgroundImage) { \n obj['title'] = title;\n obj['image'] = image;\n obj['ingredients'] = ingredients;\n obj['instructions'] = instructions;\n obj['readyInMinutes'] = readyInMinutes;\n obj['servings'] = servings;\n obj['mask'] = mask;\n obj['backgroundImage'] = backgroundImage;\n }", "function BoundingBox(rects) {\n this.rects = rects;\n}", "function initArm() {\n armDom = document.createElement(\"img\");\n armDom.src = BigBlueApp.assetsUrl + '/images/arm-part.svg';\n armDom.classList.add(\"bigblue-logo\");\n armDom.style.visibility = \"hidden\";\n armDom.style.zIndex = 9;\n container.appendChild(armDom);\n\n fistDom = document.createElement(\"img\");\n fistDom.src = BigBlueApp.assetsUrl + '/images/fist.svg';\n fistDom.classList.add(\"bigblue-logo\");\n fistDom.style.visibility = \"hidden\";\n fistDom.style.zIndex = 10;\n container.appendChild(fistDom);\n }", "function initMapAreas()/*:void*/ {var this$=this;\n var currentIdSuffixes/*:Array*/ = [];\n\n this.structValueExpression$AoGC.loadValue(function (struct/*:StructRemoteBeanImpl*/)/*:void*/ {\n if (struct) {\n struct.removeValueChangeListener(AS3.bind(this$,\"imageMapChangeHandler$AoGC\"));\n struct.addValueChangeListener(AS3.bind(this$,\"imageMapChangeHandler$AoGC\"));\n }\n\n struct.load(function()/*:void*/ {\n //noinspection JSMismatchedCollectionQueryUpdate\n var imageMapAreas/*:Array*/ = struct.get(com.coremedia.cms.studio.im.ImageMapEditorConstants.IMAGEMAP_STRUCT_NAME);\n if (imageMapAreas) {\n imageMapAreas.forEach(function (areaStruct/*:Struct*/)/*:void*/ {\n this$.canvasMgr$AoGC.addArea(areaStruct.toObject ? areaStruct.toObject() : areaStruct);\n currentIdSuffixes.push(parseInt(areaStruct.get(com.coremedia.cms.studio.im.ImageMapEditorConstants.AREA_ID).split(com.coremedia.cms.studio.im.ImageMapEditorConstants.AREA_ID_PREFIX)[1]));\n });\n }\n // Use re-route via .apply() to pass currentIdSuffixes array as 'arguments' array for .max()\n this$.areaIdSuffixCounter$AoGC = currentIdSuffixes.length > 0 ? Math.max.apply(null, currentIdSuffixes) + 1 : 0;\n });\n });\n\n // init with no selection\n this.canvasMgr$AoGC.clearSelection();\n }", "loadImages(): void {\n let self = this;\n let items = this.getState().items;\n for (let i = 0; i < items.length; i++) {\n let item: ItemType = items[i];\n // Copy item config\n let config: ImageViewerConfigType = {...item.viewerConfig};\n if (_.isEmpty(config)) {\n config = makeImageViewerConfig();\n }\n let url = item.url;\n let image = new Image();\n image.crossOrigin = 'Anonymous';\n self.images.push(image);\n image.onload = function() {\n config.imageHeight = this.height;\n config.imageWidth = this.width;\n self.store.dispatch({type: types.LOAD_ITEM, index: item.index,\n config: config});\n };\n image.onerror = function() {\n alert(sprintf('Image %s was not found.', url));\n };\n image.src = url;\n }\n }", "_create() {\n if (this.element.is(\"img\")) {\n let src = this.element.attr(\"src\");\n this.src = src;\n this.element.addClass(this.options.classes.root);\n this.wrapperEl = this._createWrapper();\n this.wrapperEl.addClass(this.options.classes.wrapper);\n this.piecesContainerEl = this.options.appendPiecesTo != undefined ? $(this.options.appendPiecesTo) : this._createPiecesContainer();\n this.slotsContainerEl = this._createSlotsContainer();\n if (this.options.appendPiecesTo == undefined) {\n this.wrapperEl.append(this.piecesContainerEl);\n }\n this.wrapperEl.append(this.slotsContainerEl);\n this.wrapperEl.insertAfter(this.element);\n this.slotsContainerEl.append(this.element);\n this.pieces = [];\n this.piecesMatrix = [];\n this._resolveDimensions();\n if ((this.imageWidth != Infinity && this.imageWidth != 0) && (this.imageHeight != Infinity && this.imageHeight != 0)) {\n this._construct();\n }\n else {\n this.element.one(\"load\", this._construct.bind(this));\n }\n }\n else {\n throw \"[SnapPuzzleGame] The widget must be initialized for <img> elements\";\n }\n }", "function vdDemo_modifyImgs(){\n\tGLB.vehicle.modifyRoadImg();\n\tGLB.vehicle.modifyDriverImg();\n}", "initializeGrid() {\n const tanks = this.filterAsset(\"tank\");\n for(const tank of tanks) {\n this.addTank(tank);\n }\n\n const tubes = this.filterAsset(\"tube\");\n for(const tube of tubes) {\n this.placeTube(tube.path);\n }\n\n const miscs = this.filterAsset(\"misc\");\n for(const misc of miscs) {\n this.addMiscAsset(misc);\n }\n\n this.cleanupData();\n }", "function add_bounding_area(uid, a,b,c,d) {\n var group=addAreaLayerGroup(a,b,c,d);\n var tmp={\"uid\":uid,\"latlngs\":[{\"lat\":a,\"lon\":b},{\"lat\":c,\"lon\":d}]};\n ucvm_area_list.push(tmp);\n load_a_layergroup(uid, AREA_ENUM, group, EYE_NORMAL);\n}", "constructor(img, srcX, srcY, srcW, srcH) {\n this.img = img;\n this.srcX = srcX;\n this.srcY = srcY;\n this.srcW = srcW;\n this.srcH = srcH;\n }", "constructor(src, x, y, properties){\r\n super(src, properties);\r\n Global.currentRenderer.addUI(this, x, y);\r\n }", "function Canvas(canvas, image, baseline, boundingBox) {\n var myCanvas = this;\n\n this.canvas = canvas;\n this.width = canvas.width;\n this.height = canvas.height;\n this.ctx = canvas.getContext('2d');\n\n this.image = image;\n\n this.baseline = baseline;\n this.boundingBox = boundingBox;\n\n this.dragging = false;\n\n this.scale = 1.0;\n\n this.panX = 0;\n this.panY = 0;\n\n this.selectedCC = [];\n\n this.dragoffx = 0;\n this.dragoffy = 0;\n\n this.image.img.onload = function(){\n myCanvas.image.w = this.width;\n myCanvas.image.h = this.height;\n\n\n myCanvas.image.initialx = myCanvas.width/2 - this.width/2;\n myCanvas.image.initialy = myCanvas.height/2 - this.height/2;\n\n myCanvas.image.x = myCanvas.image.initialx;\n myCanvas.image.y = myCanvas.image.initialy;\n\n\n if(this.width > this.height)\n myCanvas.scale = myCanvas.width /this.width;\n else\n myCanvas.scale = myCanvas.height /this.height;\n myCanvas.draw();\n }\n}", "function renderProperImages(x) {\n fabric.Image.fromURL(sources[1], function(img) {\n var img1 = img.set({\n left: 100,\n top: x\n });\n group.push(img1);\n\n fabric.Image.fromURL(sources[1], function(img) {\n var img2 = img.set({\n left: 240,\n top: x\n });\n group.push(img2);\n fabric.Image.fromURL(sources[12], function(img) {\n var img3 = img.set({\n left: 380,\n top: x\n });\n group.push(img3);\n });\n });\n });\n}", "function add() {\r\n\t\t//upload car, and background images on the canvas.\r\n\r\n\t\tbackground_img = new Image()\r\n\t\tbackground_img.onload = uploadBackground;\r\n\t\tbackground_img.src = background_image\r\n\t\trover_img = new Image()\r\n\t\trover_img.onload = uploadrover;\r\n\t\trover_img.src = rover_image;\r\n\t\t\r\n}", "function add_bounding_line(uid,a,b,c,d) {\n var group =addLineLayerGroup(a,b,c,d);\n var tmp={\"uid\":uid,\"latlngs\":[{\"lat\":a,\"lon\":b},{\"lat\":c,\"lon\":d}]};\n ucvm_line_list.push(tmp);\n load_a_layergroup(uid,LINE_ENUM,group);\n}", "function loadPlayerBase(base){\n var bg = game.add.sprite(game.world.centerX - 150, game.world.centerY/2, base.background);\n bg.anchor.setTo(.5, .5);\n bg.crop(new Phaser.Rectangle(0, 0, 800, 600));\n bg.scale.setTo(.75, .75);\n for(var i = 0; i < base.list.length; ++i){\n var temp = game.add.sprite((base.list[i].position.x - 130)/2 + game.world.centerX/2 - 150, (base.list[i].position.y + 110)/2, base.list[i].image);\n temp.anchor.setTo(0.5, 0.5);\n temp.scale.setTo(0.5, 0.5);\n }\n }", "function selectBox() {\n\tclear();\n\t$('#imgcanvas').imgAreaSelect({\n\t\thandles : true,\n\t\tonSelectEnd : function(img, selection) {\n\t\t\t// create box\n\t\t\tvar box = [selection.x1, selection.y1, selection.width, selection.height];\n\t\t\t// do fitting\n\t\t\tpositions = estimatePositions(box);\n\t\t\tif (!positions) {\n\t\t\t\tclear();\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\t// put boundary on estimated points\n\t\t\tfor (var i = 0;i < positions.length;i++) {\n\t\t\t\tif (positions[i][0][0] > img.width) {\n\t\t\t\t\tpositions[i][0][0] = img.width;\n\t\t\t\t} else if (positions[i][0][0] < 0) {\n\t\t\t\t\tpositions[i][0][0] = 0;\n\t\t\t\t}\n\t\t\t\tif (positions[i][0][1] > img.height) {\n\t\t\t\t\tpositions[i][0][1] = img.height;\n\t\t\t\t} else if (positions[i][0][1] < 0) {\n\t\t\t\t\tpositions[i][0][1] = 0;\n\t\t\t\t}\n\t\t\t}\n\t\t\t// render points\n\t\t\trenderPoints(positions, img.width, img.height);\n\t\t\tstoreCurrent();\n\t\t},\n\t\tautoHide : true\n\t});\n}", "function initialize_boxes() {\n \n // build stuff for the focus hero\n boxes['focus'] = {};\n boxes['focus']['talents'] = new TalentBox(6, null, [], [], vgvContainer);\n boxes['focus']['abilities'] = [];\n for (var i = 0; i < 6; i++) {\n boxes['focus']['abilities'].push(new AbilityBox(i, 6, null, [], vgvContainer));\n }\n boxes['focus']['items'] = [];\n for (var i = 0; i < 9; i++) {\n boxes['focus']['items'].push(new ItemBox(i, 6, null, vgvContainer));\n }\n \n // build hero avatar boxes\n boxes['avatars'] = [];\n for (var i = 0; i < 10; i++) {\n boxes['avatars'].push(new AvatarBox(i, vgvContainer));\n // boxes['avatars'][i].element.addEventListener('click', function(event) {console.log(TIMER)});\n }\n}", "function main() {\n $('.box').css('left', originX - rbx);\n $('.box').css('top', originY + lty);\n $('.box').css('width', rbx - ltx);\n $('.box').css('height', rby - lty);\n\n html2canvas(document.body, {\n allowTaint: true,\n logging: true,\n width: 1484,\n height: 1119,\n onrendered: function(canvas) {\n $('.bg').css('display', 'none');\n $('.box').css('display', 'none');\n var img = new Image();\n img.setAttribute('crossOrigin', 'anonymous');\n img.src = canvas.toDataURL();\n document.body.appendChild(img);\n }\n });\n}", "function imgDivConstructor(photosArray) {\n let imgSourceURL = assembleImageSourceURL(photosArray[0])\n imgDiv.innerHTML = `<img src = '${imgSourceURL}'>`\n}", "function camSetEnemyBases(bases)\n{\n\tvar reload = !camDef(bases);\n\tif (!reload)\n\t{\n\t\t__camEnemyBases = bases;\n\t\t__camNumEnemyBases = 0;\n\t}\n\t// convert label strings to groups and store\n\tfor (var blabel in __camEnemyBases)\n\t{\n\t\tvar bi = __camEnemyBases[blabel];\n\t\tvar obj = getObject(blabel);\n\t\t//define these here to avoid linter warnings\n\t\tvar idx = 0;\n\t\tvar len = 0;\n\t\tvar s;\n\t\tif (camDef(obj) && obj) // group already defined\n\t\t{\n\t\t\tif (!camDef(bi.group))\n\t\t\t{\n\t\t\t\tbi.group = obj.id;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tvar structures = enumGroup(bi.group);\n\t\t\t\taddLabel({ type: GROUP, id: bi.group }, blabel);\n\t\t\t\tfor (idx = 0, len = structures.length; idx < len; ++idx)\n\t\t\t\t{\n\t\t\t\t\ts = structures[idx];\n\t\t\t\t\tif (s.type !== STRUCTURE || __camIsValidLeftover(s))\n\t\t\t\t\t{\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tif (!camDef(bi.player) || camPlayerMatchesFilter(s.player, bi.player))\n\t\t\t\t\t{\n\t\t\t\t\t\tcamTrace(\"Auto-adding\", s.id, \"to base\", blabel);\n\t\t\t\t\t\tgroupAdd(bi.group, s);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (!camDef(bi.cleanup)) // auto-detect cleanup area\n\t\t\t{\n\t\t\t\tvar objs = enumGroup(bi.group);\n\t\t\t\tif (objs.length > 0)\n\t\t\t\t{\n\t\t\t\t\tvar a = {\n\t\t\t\t\t\ttype: AREA,\n\t\t\t\t\t\tx: mapWidth, y: mapHeight,\n\t\t\t\t\t\tx2: 0, y2: 0\n\t\t\t\t\t};\n\t\t\t\t\t// smallest rectangle to contain all objects\n\t\t\t\t\tfor (idx = 0, len = objs.length; idx < len; ++idx)\n\t\t\t\t\t{\n\t\t\t\t\t\tvar o = objs[idx];\n\t\t\t\t\t\tif (o.x < a.x) a.x = o.x;\n\t\t\t\t\t\tif (o.y < a.y) a.y = o.y;\n\t\t\t\t\t\tif (o.x > a.x2) a.x2 = o.x;\n\t\t\t\t\t\tif (o.y > a.y2) a.y2 = o.y;\n\t\t\t\t\t}\n\t\t\t\t\t// but a bit wider\n\t\t\t\t\ta.x -= 2; a.y -= 2; a.x2 += 2; a.y2 += 2;\n\t\t\t\t\tcamTrace(\"Auto-detected cleanup area for\", blabel, \":\", a.x, a.y, a.x2, a.y2);\n\t\t\t\t\tbi.cleanup = \"__cam_enemy_base_cleanup__\" + blabel;\n\t\t\t\t\taddLabel(a, bi.cleanup);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\telse // define a group automatically\n\t\t{\n\t\t\tif (!camDef(bi.cleanup))\n\t\t\t{\n\t\t\t\tcamDebug(\"Neither group nor cleanup area found for\", blabel);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tbi.group = camNewGroup();\n\t\t\taddLabel({ type: GROUP, id: bi.group }, blabel);\n\t\t\tvar structs = enumArea(bi.cleanup, ENEMIES, false);\n\t\t\tfor (idx = 0, len = structs.length; idx < len; ++idx)\n\t\t\t{\n\t\t\t\ts = structs[idx];\n\t\t\t\tif (s.type !== STRUCTURE || __camIsValidLeftover(s))\n\t\t\t\t{\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif (!camDef(bi.player) || camPlayerMatchesFilter(s.player, bi.player))\n\t\t\t\t{\n\t\t\t\t\tcamTrace(\"Auto-adding\", s.id, \"to base\", blabel);\n\t\t\t\t\tgroupAdd(bi.group, s);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (groupSize(bi.group) === 0)\n\t\t{\n\t\t\tcamDebug(\"Base\", blabel, \"defined as empty group\");\n\t\t}\n\t\tif(!reload)\n\t\t{\n\t\t\tbi.detected = false;\n\t\t\tbi.eliminated = false;\n\t\t}\n\t\tcamTrace(\"Resetting label\", blabel);\n\t\tresetLabel(blabel, CAM_HUMAN_PLAYER); // subscribe for eventGroupSeen\n\t}\n}", "constructor(pic, x, y) {\n this.pic = pic; //string\n this.x = x;\n this.y = y;\n this.img = p.loadImage(this.pic);\n \n }", "function setImgFromDefault( domId, ownerCollection, ownerId, label, widthPx, heightPx, callback) {\n setImgFromDefaultMR( '', domId, ownerCollection, ownerId, label, widthPx, heightPx, callback);\n }", "function BoxesManager() {\n\t\t \tvar iBoxsNum = name.length; \n\t\t\t//Creates the imgs\n\t\t\tfor (var i=0; i<iBoxsNum; i++) {\n\t\t\t\t//Create new img instance\n\t\t\t\tvar box = new Box(i);\t\n\t\t\t}\n\t\t\tvar div = document.createElement('div');\n\t\t\tdiv.className = \"clear\";\n\t\t\tvar main = document.getElementsByTagName(\"main\")[0];\n\t\t\tmain.appendChild(div);\n\n\t\t}", "loadImages () {\n this.load.image('ground', ground)\n }", "constructor() {\n super();\n this.img = null;\n this.defaultSrc = null;\n this.sources = [];\n this.updateImageSrc = () => {\n const matchedSource = AoflPicture.findMatchingSource(this.sources);\n this.setMediaSrc(matchedSource);\n };\n }", "async init (scene, data) {\n this.scene = scene\n this._engine = scene.getEngine()\n this.canvas = this._engine.getRenderingCanvas() \n this.objects = {}\n \n this.label = this.createLabel()\n console.log('dataaaaa//////// ', data)\n if (!data.electData) {\n this.electData = {\n ComponentParts: [], // name of parts\n ComponentToParts: [], // conect comp pins with part pins\n PartToPart: [], // conect part pins, nets\n PartToPartNames: [], // name of nets\n need: {}, // need pins settings\n pass: {}, // pass pins settings\n }\n }\n else {\n for (let key in data.electData) {\n this.electData[key] = data.electData[key]\n }\n }\n\n if (!data.assets) {\n data.compSize = [20, 20] // keep comp size\n data.nets = this.nets // keep nets details\n data.routing_data = [] // keep data of routes - 3d objects\n data.assets = [] // objects loaded\n }\n\n this.data.nets = this.nets = data.nets\n this.data.routing_data = data.routing_data\n this.data.assets = data.assets\n this.data.compSize = data.compSize\n \n this.scene.actionManager = new BABYLON.ActionManager(this.scene);\n this.scene.actionManager.registerAction(\n new BABYLON.ExecuteCodeAction(BABYLON.ActionManager.OnEveryFrameTrigger, (evt) => {\n if (this.curentOpt !== 5) {\n return\n } \n\n if (this.lastPosition !== null) {\n const pos = this.getGroundPosition(evt)\n this.draw3dlines(pos, false)\n }\n }))\n\n this.addBoard()\n await this.importAssets(this.data.assets)\n\n this._engine.resize()\n }", "drawCanvas() {\n //TODO find better version of how to structure so that the margin can be programmatically set\n this.ctx.clearRect(0, 0, this.can.width, this.can.height)\n this.invisictx.clearRect(0, 0, this.can.width, this.can.height)\n // remove previous tooltips\n while (this.infoHolder.firstChild) {\n this.infoHolder.removeChild(this.infoHolder.firstChild)\n }\n let red = {\n r: 227, g: 74, b: 51\n }\n let gray = {\n r: 254, g: 232, b: 200\n }\n let blue = {\n r: 67, g: 162, b: 202\n }\n // iterate over the boundary data\n for (let region of this.paneOb.sliceData.features) {\n // this is the object that has features, and properties\n for (let coords of region.geometry.coordinates) {\n this.ctx.lineWidth = 2\n this.ctx.beginPath()\n this.invisictx.beginPath()\n // create simplified variable with points and region name\n let linedata = { points: coords, region: region.properties.regionName }\n\n // begin actual drawing to the canvas\n let first = linedata.points[0]\n let x = this.xinterp.calc(first[0])\n let y = this.yinterp.calc(first[1])\n this.ctx.moveTo(x, y)\n this.invisictx.moveTo(x, y)\n for (let i = 1; i < linedata.points.length; i++) {\n let pt = linedata.points[i]\n let x = this.xinterp.calc(pt[0])\n let y = this.yinterp.calc(pt[1])\n this.ctx.lineTo(x, y)\n this.invisictx.lineTo(x, y)\n }\n this.ctx.closePath()\n this.invisictx.closePath()\n // check if its a roilisted\n if (this.paneOb.rois[linedata.region]) {\n if (this.paneOb.rois[linedata.region]) {\n this.ctx.strokeStyle = \"black\"\n this.ctx.lineWidth = 5\n this.ctx.stroke()\n }\n // add tooltips that are visible\n let regId = linedata.region.replace(/[-_]/g, \"\")\n // if we don't find the element must make the tooltip, make search specific to pane\n if (!this.paneOb.paneDiv.querySelector(`#tooltip${regId}`)) {\n this.tooltipMaker(linedata.region, this.paneOb.rois[linedata.region])\n }\n }\n\n // default stroke gray, update if nec\n this.ctx.strokeStyle = \"gray\"\n this.ctx.stroke()\n // these aren't defined yet\n if (this.regNameToValueMap != undefined) {\n if (this.regNameToValueMap[linedata.region]) {\n let scanData = this.regNameToValueMap[linedata.region].value\n let lerpc\n if (scanData < 0) {\n // use the blue to gray instead of gray to red\n let t = this.colInterpolator.calc(scanData)\n lerpc = LerpCol( t)\n } else {\n let t = this.colInterpolator.calc(scanData)\n lerpc = LerpCol( t)\n }\n this.ctx.fillStyle = lerpc\n this.ctx.fill()\n // query the region to color map\n }\n }\n this.invisictx.fillStyle = `rgb(${this.regToColMap[linedata.region][0]},${this.regToColMap[linedata.region][1]},${this.regToColMap[linedata.region][2]})`\n this.invisictx.fill()\n }\n }\n if (this.scanDatamin != undefined && this.scanDatamax != undefined) {\n // setup a legend in the corner\n let gradient = this.ctx.createLinearGradient(0, 0, 0, this.can.height / 4)\n // color stop for rgb\n if (this.scanDatamin < 0 && this.scanDatamax > 0) {\n gradient.addColorStop(1, `rgb(${blue.r},${blue.g},${blue.b})`)\n gradient.addColorStop(.5, `rgb(${gray.r},${gray.g},${gray.b})`)\n gradient.addColorStop(0, `rgb(${red.r},${red.g},${red.b})`)\n } else if (this.scanDatamax > 0) {\n gradient.addColorStop(1.0, `rgb(255,255,178)`)\n gradient.addColorStop(0.75, `rgb(254,204,92)`)\n gradient.addColorStop(0.5, `rgb(253,141,60)`)\n gradient.addColorStop(0.25, `rgb(240,59,32)`)\n gradient.addColorStop(.0, `rgb(189,0,38)`)\n } else {\n // this is the case of blue only\n console.log(this.scanDatamax, \"max\", this.scanDatamin, \"min\")\n gradient.addColorStop(0, `rgb(${gray.r},${gray.g},${gray.b})`)\n gradient.addColorStop(1, `rgb(${blue.r},${blue.g},${blue.b})`)\n }\n let gradientWidth = 10\n this.ctx.fillStyle = gradient\n let startx = this.can.width - this.margin - gradientWidth\n let endx = this.can.width - this.margin * 2\n this.ctx.fillRect(startx, 0, endx, this.can.height / 4)\n // add numeric values to the gradient\n // measure the text so it sits right next to the gradient\n this.ctx.font = \"15px Arial\"\n let minmeasure = this.ctx.measureText(this.scanDatamin).width\n let maxmeasure = this.ctx.measureText(this.scanDatamax).width\n this.ctx.fillStyle = \"black\"\n // the -5 is a spacer for the text next to the gradient bar\n this.ctx.fillText(this.scanDatamin, startx - minmeasure - 5, this.can.height / 4)\n this.ctx.fillText(this.scanDatamax, startx - maxmeasure - 5, 15)\n }\n }", "function load_custombb () {\n document.querySelectorAll('span[style=\"color:resimg\"]').forEach(e => {\n $(e).replaceWith(`<img src=\"https://${e.innerHTML}\"></img>`);\n });\n document.querySelectorAll('span[style=\"color:reshighlight\"]').forEach(e => {\n $(e).replaceWith(`<mark>${e.innerHTML}</mark>`);\n });\n document.querySelectorAll('span[style=\"color:resleft\"]').forEach(e => {\n $(e).replaceWith(`<p align=\"left\">${e.innerHTML}</p>`);\n });\n document.querySelectorAll('span[style=\"color:resright\"]').forEach(e => {\n $(e).replaceWith(`<p align=\"right\">${e.innerHTML}</p>`);\n });\n document.querySelectorAll('a[href^=\"https://gist.github.com/\"]').forEach(e => {\n var url = encodeURI('data:text/html;charset=utf-8,<body><script src=\"' + $(e).attr(\"href\") + \".js\" + '\"></script></body>');\n $(e).append(`<br><iframe src='` + url + `' width=\"100%\" height=\"400\" scrolling=\"auto\" frameborder=\"no\" align=\"center\"></iframe>`);\n });\n }", "function mkLoadingArea() {\n for (var i=0; i<loadingArea.length; i++){\n ctx.drawImage(warningStripes, loadingArea[i][0] * boxSize, loadingArea[i][1] * boxSize, boxSize, boxSize)\n }\n \n}", "function initialize_listing_previews(){\n for (var i = 0; i < window.ST.poolToolRows; i++) {\n\n // Function in a loop. Do not use i in there!\n /*jshint -W083 */\n $('#rowheader' + i).on('mouseover', function(ev){\n if (ev.currentTarget.firstChild.firstChild){\n var id = ev.currentTarget.id;\n var text = ev.currentTarget.firstChild.firstChild.data;\n var ii = parseInt(id.substr(9,1));\n var alreadyThere = false;\n\n if (gon.source[ii].image && gon.source[ii].name === text){\n for(var j=0; j<window.ST.poolToolImages.length; j++){\n if (ii === window.ST.poolToolImages[j]){\n alreadyThere = true;\n }\n }\n window.ST.poolToolImages.push(ii);\n\n if(alreadyThere){\n $('#rowheader_image' + ii).show();\n }else{\n var img = $('<img id=\"rowheader_image'+ ii +'\" height=\"' + $(\".spacer\").height() + '\"/>').attr('src', gon.source[ii].image)\n // Function in a loop. Do not use i in there!\n /*jshint -W083 */\n .on('load', function(){\n if (!this.complete || typeof this.naturalWidth === \"undefined\" || this.naturalWidth === 0) {\n } else {\n $(\".spacer\").append(img);\n img.show();\n }\n });\n }\n }\n }\n });\n\n // Function in a loop. Do not use i in there.\n /*jshint -W083 */\n $('#rowheader'+i).on('mouseout', function(ev){\n var id = ev.currentTarget.id;\n var ii = parseInt(id.substr(9,1));\n\n $('#rowheader_image' + ii).hide();\n });\n }\n }", "loadImages() {\n let loadCount = 0;\n let loadTotal = this.images.length;\n\n if (WP.shuffle) {\n this.images = this.shuffle(this.images);\n }\n\n const imageLoaded = (() => {\n loadCount++;\n\n if (loadCount >= loadTotal) {\n // All images loaded!\n this.setupCanvases();\n this.bindShake();\n this.loadingComplete();\n }\n }).bind(this);\n\n for (let image of this.images) {\n // Create img elements for each image\n // and save it on the object\n const size = this.getBestImageSize(image.src);\n image.img = document.createElement('img'); // image is global\n image.img.addEventListener('load', imageLoaded, false);\n image.img.src = image.src[size][0];\n }\n }", "function pre(allLoadedCallback) {\n \n var allImg = [],\n imgLoaded = 0,\n uncached = function (src) {\n if (!src || src=='') return false;\n var img = new Image();\n img.src = src;\n return !img.complete;\n },\n imgLoad = function(self, img) {\n imgLoaded++;\n\n self.naturalimgwd = img.width;\n self.naturalimghg = img.height;\n\n if (imgLoaded >= allImg.length) {\n \n f.$el.removeClass('loading');\n f.o.cbStarted();\n \n allLoadedCallback.call(f);\n \n return false;\n }\n }\n \n // gets all frame images\n $.each(f.o.config, function() {\n if (f.o.src || this.src) {\n //allImg.push((f.o.src)? f.o : this)\n allImg.push((this.src)? this : f.o)\n if (typeof(this.src) != 'undefined' && this.src !== '') \n \tthis.hasOwnImage = true;\n else\n \tthis.hasOwnImage = false;\n }\n });\n\n f.$el.addClass('loading');\n $.each(allImg, function() {\n var img = new Image(),\n self = this;\n if(uncached(this.src)) {\n img.onload = function() {\n imgLoad(self, img)\n }\n img.src = this.src || f.o.src;\n } else {\n img.src = this.src || f.o.src;\n imgLoad(self, img)\n }\n });\n if(!allImg.length){\n imgLoad(f.o, '')\n }\n }", "function loadIceBin() {\n\t\t\t\t\t\t\t\texistingicebinList =new Array();\n\t\t\t\t\t\t\t\tfor (var i = 0; i < self.IceBins.length; i++) {\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\tvar icebin = new fabric.Rect({\n\t\t\t\t\t\t\t\t\t\tx : parseInt(self.IceBins[i].ix),\n\t\t\t\t\t\t\t\t\t\ty : parseInt(self.IceBins[i].iy),\n\t\t\t\t\t\t\t\t\t\twidth : self.IceBins[i].width,\n\t\t\t\t\t\t\t\t\t\theight : self.IceBins[i].length,\n\t\t\t\t\t\t\t\t\t\tid : parseInt(self.IceBins[i].id),\n\t\t\t\t\t\t\t\t\t\tname : 'Icebin',\n\t\t\t\t\t\t\t\t\t\ttext : 'rexct',\n\t\t\t\t\t\t\t\t\t\tfill : '#a2a8ad',\n\t\t\t\t\t\t\t\t\t\tstroke : 'black',\n\t\t\t\t\t\t\t\t\t\tstrokeWidth : 2,\n\t\t\t\t\t\t\t\t\t\tClass : 'test',\n\t\t\t\t\t\t\t\t\t\tdraggable : true\n\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\t existingicebinList.push(icebin);\n\t\t\t\t\t\t\t\t\t// setEventToTable(icebin);\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}", "function onBodyChanged()\r\n{\r\n\t//Update the display showing which indices these are.\r\n\tupdateSelectorBox();\r\n\t\r\n\t//Set head, torso and legs images\r\n\theadImage.src = headImages[headIndex];\r\n\ttorsoImage.src = torsoImages[torsoIndex];\r\n\tlegsImage.src = legsImages[legsIndex];\r\n}", "createBases (dataObj) {\n const textures_d = dataObj.dataBase.textures [dataObj.dataValues.p.textureName]; // ref texture:diffuse\n const textures_n = dataObj.dataBase.textures_n [dataObj.dataValues.p.textureName]; // ref texture:normal\n const d = new PIXI.extras.AnimatedSprite(textures_d);\n const n = new PIXI.Sprite(textures_n[0]);\n this.Sprites = {d,n};\n this.batchWithNormals(n,textures_n);\n \n }", "loadImg() {\n let loadedCount = 0\n function onLoad() {\n loadedCount++\n if (loadedCount >= this.imgPaths.length) {\n this.flowStart()\n }\n }\n this.baseImages = this.imgPaths.map(path => {\n const image = new Image()\n image.onload = onLoad.bind(this)\n image.src = path\n return image\n })\n }", "function loadImages() {\r\n\r\n let blocks = ['black_concrete', 'black_terracotta', 'netherrack', 'nether_wart_block', 'red_concrete_powder', 'dark_oak_log', 'green_terracotta', 'brown_concrete', 'melon_top', 'orange_concrete', 'green_concrete', 'green_wool', 'green_concrete_powder', 'oak_log', 'orange_concrete_powder', 'lime_concrete', 'lime_concrete', 'lime_concrete_powder', 'hay_block_top', 'yellow_concrete', 'lime_wool', 'lime_concrete', 'lime_concrete_powder', 'melon_top', 'yellow_concrete', 'black_wool', 'gravel', 'spruce_planks', 'pink_terracotta', 'red_concrete_powder', 'cyan_terracotta', 'coarse_dirt', 'bricks', 'light_gray_terracotta', 'red_concrete_powder', 'brown_concrete_powder', 'dark_prismarine', 'acacia_log', 'acacia_planks', 'acacia_planks', 'dark_prismarine', 'lime_terracotta', 'lime_terracotta', 'oak_planks', 'yellow_concrete_powder', 'slime_block', 'slime_block', 'lime_wool', 'melon_top', 'yellow_concrete', 'blue_concrete', 'mycelium_top', 'mycelium_top', 'pink_terracotta', 'red_concrete_powder', 'lapis_block', 'blue_terracotta', 'magenta_terracotta', 'magenta_terracotta', 'magenta_concrete', 'cyan_concrete', 'cracked_stone_bricks', 'andesite', 'granite', 'jungle_planks', 'dark_prismarine', 'green_concrete', 'green_concrete_powder', 'hay_block_top', 'birch_planks', 'slime_block', 'slime_block', 'slime_block', 'slime_block', 'yellow_concrete_powder', 'blue_concrete', 'blue_wool', 'magenta_concrete', 'magenta_concrete', 'pink_concrete', 'blue_wool', 'blue_concrete_powder', 'purple_concrete', 'magenta_concrete_powder', 'magenta_concrete_powder', 'light_blue_concrete', 'blue_concrete_powder', 'purpur_block', 'pink_concrete', 'pink_wool', 'cyan_concrete_powder', 'cobblestone', 'clay', 'birch_log', 'diorite', 'prismarine_bricks', 'prismarine_bricks', 'prismarine_bricks', 'end_stone', 'end_stone', 'blue_concrete', 'blue_concrete', 'purple_concrete', 'purple_concrete_powder', 'pink_concrete', 'blue_concrete_powder', 'blue_concrete_powder', 'purple_concrete', 'purple_wool', 'pink_concrete', 'light_blue_concrete', 'light_blue_wool', 'lapis_block', 'purpur_block', 'pink_concrete', 'light_blue_concrete_powder', 'light_blue_concrete_powder', 'blue_ice', 'packed_ice', 'white_concrete', 'light_blue_concrete_powder', 'light_blue_concrete_powder', 'light_blue_concrete_powder', 'packed_ice', 'bone_block_side'];\r\n\r\n for (let block of blocks) {\r\n blockImages[block] = new Image();\r\n blockImages[block].src = block + \".png\";\r\n blockImages[block].onload = function() {\r\n console.log(\"Loaded \" + block + \".png\");\r\n }\r\n }\r\n}", "function imageGrid(fileList) {\n let imageGrid = document.getElementsByClassName(\"box-grid\");\n for (let i in fileList) {\n let file = fileList[i];\n let boxSingle = createImageBox(imageGrid);\n createSingleImage(file, boxSingle);\n let boxCaption = createImageTextBox(boxSingle);\n createImageText(file, boxCaption);\n }\n}", "function loadForegroundImage(){\n //get input from text input\n var fileinput = document.getElementById(\"foreinput\");\n fgcanvas = document.getElementById(\"canvf\");\n \n //create the selected image\n fgImage = new SimpleImage(fileinput);\n // show on the canvas\n fgImage.drawTo(fgcanvas);\n}", "constructor(name, pixelWidth, pixelHeight, pixelOffsetX, pixelOffsetY,\n sight, hitPoints, cost, spriteImages, defaults, buildableGrid, passableGrid, baseWidth, baseHeight) {\n super(name, pixelWidth, pixelHeight, pixelOffsetX, pixelOffsetY, sight, hitPoints, cost, spriteImages, defaults);\n //set the list of buildable units based on each units builtFrom property\n this.unitList = [];\n //add all the units that the building can build to its unit list\n for (let unit in units) {\n if (units.hasOwnProperty(unit)) {\n if (units[unit].builtFrom === this.name) {\n this.unitList.push(units[unit]);\n }\n }\n }\n this.defaults.unitList = this.unitList;\n //set default building specific properties\n this.defaults.type = 'buildings';\n this.baseWidth = baseWidth;\n this.baseHeight = baseHeight;\n this.buildableGrid = buildableGrid;\n this.passableGrid = passableGrid;\n this.imageOffset = 0;\n this.animationIndex = 0;\n }", "function createImage(source, blob) {\n var pastedImage = new Image();\n //clear gcode\n pastedImage.onload = function() {\n Potrace.loadImageFromFile(blob);\n Potrace.info.alphamax = getvalue(\"smooth\");\n Potrace.process(function() {\n //displayImg();\n //displaySVG(scale);\n text1 = Potrace.getSVG(1);//.toUpperCase();\n\n refreshgcode();\n\n });\n }\n pastedImage.src = source;\n}", "function setupImageData() {\n var countsBySrc = [{}, {}];\n imageData = [\n [],\n []\n ];\n\n (model.properties.images || []).forEach(function(desc) {\n var layerIndex = desc.imageLayer === 1 ? 1 : 0;\n var layer = imageData[layerIndex];\n var countBySrc = countsBySrc[layerIndex];\n var src = getImagePath(desc);\n var referencePoint;\n var capturesPointer;\n var x;\n var y;\n\n if (desc.imageHostType) {\n // imageHostType => image is \"attached\" to an atom or obstacle, and x and y specify the\n // model coordinates of its center.\n referencePoint = CENTER;\n // Images attached to objects still allow the underlying object to be dragged.\n capturesPointer = false;\n } else {\n // no imageHostType => image is at a fixed coordinate in the model space, and x and y\n // specify the model coordinates of its upper left corner.\n referencePoint = UPPER_LEFT;\n // Unattached images prevent dragging of whatever is beneath them, in the usual way.\n capturesPointer = true;\n // Update x and y now; updateImageCoordinates will be a noop.\n x = modelView.model2px(desc.imageX);\n y = modelView.model2pxInv(desc.imageY);\n }\n\n loadImage(src, desc.scale);\n\n layer.push({\n imageDescription: desc,\n src: src,\n // Use src + srcIndex to create a unique key for images. This allows us to use a\n // conservative data join and thereby avoid having to modify the href of <image> elements.\n // That prevents the browser from issuing unnecessary requests.\n srcIndex: countBySrc[src] === undefined ? (countBySrc[src] = 0) : ++countBySrc[src],\n x: x,\n y: y,\n rotation: desc.rotation,\n scale: desc.scale,\n opacity: desc.opacity,\n referencePoint: referencePoint,\n capturesPointer: capturesPointer,\n zOrder: desc.imageLayerPosition || 0,\n visible: desc.visible\n });\n });\n\n // Finally, because imageData for each layer is 1:1 with svg image elements, sort the\n // imageData for each layer by the intended z order of the images.\n imageData.forEach(function(layer) {\n layer.sort(function(a, b) {\n return d3.ascending(a.zOrder, b.zOrder);\n });\n });\n\n updateImageCoordinates();\n }", "bind(el, binding) {\n // Check DOM has children\n if (el.children.tagName !== 'IMG' && el.children.length > 0 && !el.src) {\n const groupOptions = {\n 'group': el.dataset.group || null,\n 'title': el.title || null,\n 'thumbnails': ga(el, 'data-thumbnails') || false,\n 'download': ga(el, 'data-download') || false,\n 'events': {},\n };\n options = Object.assign(options, groupOptions);\n // Reset tagName not go follow to url on `a` tag\n if (el.tagName === 'A') {\n el.setAttribute('data-href', el.href);\n el.setAttribute('href', 'javascript:void(0);');\n }\n // Begin set listener\n for (let index = 0; index < el.children.length; index++) {\n const children = el.children[index];\n if (children.tagName === 'IMG') {\n vImageListener(children, binding, options);\n } else {\n for (let i = 0; i < children.children.length; i++) {\n if (children.children[i].tagName === 'IMG') {\n vImageListener(children.children[i], binding, options);\n }\n }\n }\n }\n } else {\n // This is image\n vImageListener(el, binding, options);\n }\n\n /**\n * Make Image event Listener\n *-------------------\n * @author malayvuong\n * @param {Element} el\n * @param {Object} binding\n * @param {Object} options\n *\n **/\n function vImageListener(el, binding, options) {\n const addedAttributes = addImageAttributes(el, binding, options);\n // Finding existing vm, or creating new one\n let vm = window.vueImg;\n if (!vm) {\n const element = document.createElement('div');\n element.setAttribute('id', 'v-image');\n document.querySelector('body').appendChild(element);\n // eslint-disable-next-line no-multi-assign\n vm = window.vueImg = new Screen().$mount('#v-image');\n }\n\n // Updating vm's data\n el.addEventListener(addedAttributes.openOn, () => {\n let images;\n const groupName = el.dataset.group;\n if (!groupName) {\n images = [el];\n } else {\n images = [\n ...document.querySelectorAll(`img[data-group=\"${groupName}\"]`),\n ];\n }\n\n Vue.set(vm, 'images', images.map((e) => e.dataset.src));\n Vue.set(vm, 'thumbs', images.map((e) => ga(e, 'src')));\n Vue.set(vm, 'titles', images.map((e) => e.dataset.title));\n Vue.set(vm, 'download', images.map(\n (e) => e.dataset.download === 'true'));\n Vue.set(vm, 'thumbnails', el.dataset.thumbnails === 'true');\n Vue.set(vm, 'currentIndex', images.indexOf(el));\n Vue.set(vm, 'handlers', addedAttributes.events);\n Vue.set(vm, 'closed', false);\n });\n }\n }", "function loadBox(box) {\n BD18.bx = null;\n BD18.bx = box;\n if (typeof(box.links) !== 'undefined' && box.links.length > 0) {\n loadLinks(box.links);\n }\n $.getJSON(\"php/linkGet.php\", 'gameid='+BD18.gameID,function(data) {\n if (data.stat === \"success\" && typeof(data.links) !== 'undefined' \n && data.links.length > 0) { loadLinks(data.links); }\n });\n var market = BD18.bx.market;\n var sheets = BD18.bx.tray;\n BD18.mktImage = new Image();\n BD18.mktImage.src = market.imgLoc;\n BD18.mktImage.onload = itemLoaded; \n BD18.loadCount++ ;\n BD18.tsImages = [];\n var ttt = sheets.length;\n for(var i=0; i<ttt; i++) {\n BD18.tsImages[i] = new Image();\n BD18.tsImages[i].src = sheets[i].imgLoc;\n BD18.tsImages[i].onload = itemLoaded;\n BD18.loadCount++;\n }\n BD18.doneWithLoad = true;\n itemLoaded(); // Just in case onloads are very fast.\n}", "constructor([imgIn = hct.getImageData(0,0,hcanvas.width,hcanvas.height), xpos = 0, ypos = 0]){\n\t\tsuper([imgIn, xpos, ypos]);\n\t\tthis.skeltonize();\n\t}", "constructor(row,col)\n {\n this.imgWall = new Image();\n this.imgNotWall = new Image();\n this.imgWall.src = \"assets/Wall.png\";\n this.imgNotWall.src = \"assets/NotWall.png\";\n this.containsWall = false;\n this.row = row;\n this.col = col;\n this.squareSize = 75;\n\n\n }", "function initialize() {\n\t\t\n\t\tsvg = scope.selection.append(\"svg\").attr(\"id\", scope.id).style(\"overflow\", \"visible\").attr(\"class\", \"vizuly\");\n\t\tbackground = svg.append(\"rect\").attr(\"class\", \"vz-background\");\n\t\tdefs = vizuly2.util.getDefs(viz);\n\t\tplot = svg.append('g');\n\t\t\n\t\tscope.dispatch.apply('initialized', viz);\n\t}", "function ObjectFitIt() {\n $('.news-detail__media .imageslider__image').each(function(){\n var imgSrc = $(this).attr('src');\n var fitType = 'contain';\n /*if($(this).data('fit-type')) {\n fitType = $(this).data('fit-type');\n }*/\n $(this).parent().css({ 'background' : 'transparent url(\"'+imgSrc+'\") no-repeat left center/'+fitType, });\n $(this).css('opacity','0');\n });\n }", "createBases (dataObj) {\n const dataBase = dataObj.dataBase; // getter\n const s = new PIXI.projection.Spine2d(dataBase.spineData); //new PIXI.spine.Spine(sd);\n const [d,n] = s.hackAttachmentGroups(\"_n\",null,null); // (nameSuffix, group)\n //PIXI.projection.Spine2d.call(this,dataBase.spineData);\n /*if(dataObj.dataValues.p.skinName){\n s.skeleton.setSkinByName(dataObj.dataValues.p.skinName);//FIXME: player have no skin for now\n };\n s.state.setAnimation(0, dataObj.dataValues.p.defaultAnimation , true); // default animation 'idle' TODO: add more in getDataValues_spine\n s.skeleton.setSlotsToSetupPose();*/\n this.Sprites = {s,d,n};\n \n }", "function load_images() {\n data.each(function(frame) {\n var imgs = []\n frame.images.each(function(imgstr) {\n var img = new Image(IMG_WIDTH, IMG_HEIGHT);\n img.src = \"/img/\" + imgstr;\n img.style.float = \"left\";\n imgs.push(img); \n });\n frame['imageobjs'] = imgs;\n }) \n }", "function BoundingBox(sprite) {\n\n\n // --\n // ------- PROPERTIES ----------------------------------------\n // --\n\n\n // general\n this.id = Nickel.UTILITY.assign_id();\n this.type = 'BoundingBox';\n\n // pos\n this.left = 0;\n this.right = 0;\n this.top = 0;\n this.bottom = 0;\n\n // size\n this.w = 0;\n this.h = 0;\n\n // parent\n this.target = sprite;\n\n // indicates if we have already bounded around the sprite\n this.updated = false;\n\n\n // --\n // ------- METHODS -------------------------------------------\n // --\n\n\n this.update = function() {\n //-- Main update function\n //--\n\n // indicate that we must bound self when needed\n this.updated = false;\n }\n\n this.bound = function(force_bound=false) {\n //-- Bounds self around a target sprite\n //--\n\n // ignore if this function if we already updated\n if (this.updated && !force_bound) return;\n\n // indicate that we have bounded self\n this.updated = true;\n\n // corners of sprite\n var tl = this.target.get_topleft();\n var tr = this.target.get_topright();\n var bl = this.target.get_bottomleft();\n var br = this.target.get_bottomright();\n\n // top left of bbox\n var AXnew = Math.min(tl[0], tr[0], bl[0], br[0]);\n var AYnew = Math.min(tl[1], tr[1], bl[1], br[1]);\n\n // dimensions of bbox\n var Wnew = Math.max(tl[0], tr[0], bl[0], br[0]) - AXnew;\n var Hnew = Math.max(tl[1], tr[1], bl[1], br[1]) - AYnew;\n\n // apply\n this.left = AXnew;\n this.right = AXnew + Wnew;\n this.top = AYnew;\n this.bottom = AYnew + Hnew;\n this.w = Wnew;\n this.h = Hnew;\n }\n\n this.get_cx = function() {\n //-- Returns the center x pos of the bbox\n //--\n\n return this.left + this.w / 2;\n }\n\n this.get_cy = function() {\n //-- Returns the center y pos of the bbox\n //--\n\n return this.top + this.h / 2;\n }\n\n this.get_center = function() {\n //-- Returns the center pos of the bbox\n //--\n\n return [this.get_cx(),this.get_cy()];\n }\n\n}//end BoundingBox", "constructor(i){\n this.src = levelsImages[i];\n this.src.loadPixels();\n console.log(this.src);\n }", "function buildsRect8BasePoints()\n {\n // rectangle points\n if (appstate.showRectPts) {\n\t //constructPts(dr.leftPts, baseMax, \"inscribed tofill\", sconf.FINEPTS_RADIUS);\n\t constructPts(dr.leftPts, baseMax, \"inscribed\", sconf.FINEPTS_RADIUS);\n\t constructPts(dr.righPts, baseMax, \"circumscribed\", sconf.FINEPTS_RADIUS);\n\t constructPts(dr.curvPts, baseMax, \"figure\", sconf.FINEPTS_RADIUS);\n }\n constructBasePts_dom(appstate.showRectPts, dr.basePts);\n }", "function arConstructorImg() { \n constructorBases.forEach((base) => {\n // Change the main image\n let container = base.parentNode;\n let kovrikBase = container.getElementsByTagName('img')[1];\n let kovrikOkantovka = container.getElementsByTagName('img')[0];\n \n kovrikBase.src = urlBase + currentKovrikColor + ((standartImg.checked)? '_rombi' : '_3D') + '_kovrik.png';\n kovrikOkantovka.src = urlBase + currentOkantovkaColor + ((standartImg.checked)? \"\" : \"_3D\") + '_okantovka.png';\n\n //Change the class of images for shildiks and podpatniks\n if(!standartImg.checked) {\n let shildik = container.getElementsByClassName('dynamic-shildik')[0];\n if(shildik) {\n shildik.classList.add('dynamic-3D-shildik');\n shildik.src = urlBase + shildik.dataset.threedimg;\n }\n\n let podpatnik = container.getElementsByClassName('dynamic-podpatnik')[0];\n if(podpatnik) {\n podpatnik.classList.add('dynamic-3D-podpatnik');\n podpatnik.src = urlBase + podpatnik.dataset.threedimg;\n }\n } else {\n let shildik = container.getElementsByClassName('dynamic-shildik')[0];\n if(shildik) {\n shildik.classList.remove('dynamic-3D-shildik');\n shildik.src = urlBase + shildik.dataset.img;\n }\n\n let podpatnik = container.getElementsByClassName('dynamic-podpatnik')[0];\n if(podpatnik) {\n podpatnik.classList.remove('dynamic-3D-podpatnik');\n podpatnik.src = urlBase + podpatnik.dataset.img;\n }\n }\n });\n\n // Change the number of schemes\n if(standartImg.checked) {\n complectOptions[complectOptions.length - 1].style.visibility = 'visible';\n complectOptions[complectOptions.length - 2].style.visibility = 'visible';\n complectOptions[complectOptions.length - 3].style.visibility = 'visible';\n\n complectOptions[complectOptions.length - 1].getElementsByTagName('input')[0].disabled = false;\n complectOptions[complectOptions.length - 2].getElementsByTagName('input')[0].disabled = false;\n complectOptions[complectOptions.length - 3].getElementsByTagName('input')[0].disabled = false;\n } else {\n complectOptions[complectOptions.length - 1].style.visibility = 'hidden';\n complectOptions[complectOptions.length - 2].style.visibility = 'hidden';\n complectOptions[complectOptions.length - 3].style.visibility = 'hidden';\n\n complectOptions[complectOptions.length - 1].getElementsByTagName('input')[0].checked = false;\n complectOptions[complectOptions.length - 2].getElementsByTagName('input')[0].checked = false;\n complectOptions[complectOptions.length - 3].getElementsByTagName('input')[0].checked = false;\n\n complectOptions[complectOptions.length - 1].getElementsByTagName('input')[0].disabled = true;\n complectOptions[complectOptions.length - 2].getElementsByTagName('input')[0].disabled = true;\n complectOptions[complectOptions.length - 3].getElementsByTagName('input')[0].disabled = true;\n\n complectOptions[complectOptions.length - 1].style.backgroundColor = '';\n complectOptions[complectOptions.length - 2].style.backgroundColor = '';\n complectOptions[complectOptions.length - 3].style.backgroundColor = '';\n }\n}", "draw(canvas, rect, viewId, elementId, elementType, widgetTime, stateTime, mode, attributes) {\n\n canvas.imageSmoothingEnabled=true;\n\n if (elementType == \"background\") {\n\n this.drawBackground(canvas, rect, viewId, elementId, widgetTime, stateTime, mode, attributes);\n\n } else if (elementType == \"button\") {\n\n this.drawButton(canvas, rect, viewId, elementId);\n\n } else if (elementType == \"buttonImage\") {\n\n this.drawButtonImage(canvas, rect, viewId, elementId, widgetTime, stateTime, mode, attributes);\n\n } else if (elementType == \"image\") {\n \n this.drawImage(canvas, rect, viewId, elementId, widgetTime, stateTime, mode, attributes);\n \n } else if (elementType == \"imageError\") {\n\n this.drawImageError(canvas, rect, viewId, elementId, widgetTime, stateTime, mode, attributes);\n\n } else if (elementType == \"text\") {\n\n this.drawText(canvas, rect, viewId, elementId, widgetTime, stateTime, mode, attributes);\n\n } else if (elementType == \"faceSearcher\") {\n \n this.drawFaceSearcher(canvas, rect, viewId, elementId, widgetTime, stateTime, mode, attributes);\n \n } else if (elementType == \"video\") {\n\n if (viewId == \"Extractor\") {\n if (this.extractionMode == FPhi.Selphi.Mode.Register)\n this.drawImageWithClippingCircle(canvas, rect, attributes.player, rect.x + rect.width / 2.0, rect.y + rect.height / 2.0, rect.width / 2.0);\n } else {\n this.drawImageWithClippingCircle(canvas, rect, attributes.player, rect.x + rect.width / 2.0, rect.y + rect.height / 2.0, rect.width / 2.0);\n }\n //this.drawImage(canvas,rect,attributes.player);\n\n } else if (elementType == \"camera\") {\n\n var progress = attributes.progress;\n var borderWidth = this.rm.getSetupFloat(\"facephi-widget-conf\", \"\", this.landscape, \"width_progress_bar\");\n var colorProgress = this.rm.getSetupColor(\"facephi-widget-conf\", \"\", this.landscape, \"color_progress_bar\");\n var colorWarning = this.rm.getSetupColor(\"facephi-widget-conf\", \"\", this.landscape, \"color_warning_message\");\n var colorExcellent = this.rm.getSetupColor(\"facephi-widget-conf\", \"\", this.landscape, \"color_quality_excellent\");\n var colorLow = this.rm.getSetupColor(\"facephi-widget-conf\", \"\", this.landscape, \"color_quality_low\");\n\n /*\n canvas.save();\n canvas.translate(this.width, 0);\n canvas.scale(-1, 1);\n\n\n this.cameraWidth = attributes.width;\n this.cameraHeight = attributes.height;\n this.cameraRotation = attributes.cameraRotation;\n this.faceDataRect = attributes.faceDataRect;\n this.faceTracking = attributes.faceTracking;\n\n // draw camera image to visible canvas\n if ((this.faceDataRect != 'undefined') && (this.faceDataRect != null) && (this.faceTracking)) {\n this.faceCenterOffsetTarget = { x: (this.faceDataRect.x + this.faceDataRect.width / 2.0) - this.circleX, y: (this.faceDataRect.y + this.faceDataRect.height / 2.0) - this.circleY }\n }\n this.faceCenterOffset.x += (this.faceCenterOffsetTarget.x - this.faceCenterOffset.x) * 0.1;\n this.faceCenterOffset.y += (this.faceCenterOffsetTarget.y - this.faceCenterOffset.y) * 0.1;\n var tRect = this.scaleRect({ width: this.cameraWidth, height: this.cameraHeight }, { x: 0, y: 0, width: this.width, height: this.height });\n\n // limit camera offset to circle bounds.\n var localCameraX = tRect.x + this.faceCenterOffset.x;\n if (localCameraX >= this.circleX - this.circleRadius) localCameraX = this.circleX - this.circleRadius;\n if (localCameraX + tRect.width <= this.circleX + this.circleRadius) localCameraX = this.circleX + this.circleRadius - tRect.width;\n var localCameraY = tRect.y - this.faceCenterOffset.y;\n if (localCameraY >= this.circleY - this.circleRadius) localCameraY = this.circleY - this.circleRadius;\n if (localCameraY + tRect.height <= this.circleY + this.circleRadius) localCameraY = this.circleY + this.circleRadius - tRect.height;\n\n*/\n canvas.save();\n canvas.beginPath();\n canvas.arc(this.circleX, this.circleY, this.circleRadius, 0, 2 * Math.PI, false);\n canvas.clip();\n //canvas.drawImage(attributes.camera, localCameraX, localCameraY, tRect.width, tRect.height);\n \n if ((attributes.state == \"UCLivenessMoveStabilizing\") || (attributes.state==\"UCLivenessMoveStabilized\") || (attributes.state==\"UCLivenessMoveDetecting\") || (attributes.state==\"UCLivenessMoveProcessing\")) {\n // Capa translucida negra para resaltar las letras\n canvas.fillStyle = \"#00000033\";\n canvas.fillRect(rect.x, rect.y, rect.width, rect.height);\n }\n\n //canvas.drawImage(attributes.camera, tRect.x, tRect.y, tRect.width, tRect.height);\n canvas.restore();\n\n //canvas.drawImage(attributes.camera, 0,0, tRect.width, tRect.height);\n\n var circleColor = colorProgress; // this.rm.getSetupColor(\"facephi-widget-conf\", \"\", \"color_progress_bar\");\n if (mode == \"Warning\")\n circleColor = colorWarning; // this.rm.getSetupColor(\"facephi-widget-conf\", \"\", \"color_warning_message\");\n\n if (progress == 0.0 && mode == \"Warning\") {\n // Arco completo\n canvas.beginPath();\n canvas.strokeStyle = colorLow; // this.rm.getSetupColor(\"facephi-widget-conf\",\"\",\"color_quality_low\");\n canvas.lineWidth = borderWidth; // this.rm.getSetupFloat(\"facephi-widget-conf\", \"\", \"width_progress_bar\");\n canvas.lineCap = \"round\";\n canvas.arc(this.circleX, this.circleY, this.circleRadius - (canvas.lineWidth / 2) + 0.5, -Math.PI / 2, 2 * Math.PI - Math.PI / 2);\n canvas.stroke();\n }\n\n if ((attributes.state == \"UCLivenessMoveStabilizing\") || (attributes.state==\"UCLivenessMoveStabilized\") || (attributes.state==\"UCLivenessMoveDetecting\") || (attributes.state==\"UCLivenessMoveProcessing\")) {\n progress = 1.0;\n if (attributes.liveness_move_last_result) circleColor = colorExcellent; // this.rm.getSetupColor(\"facephi-widget-conf\",\"\",\"color_quality_excellent\");\n else circleColor = colorLow; // this.rm.getSetupColor(\"facephi-widget-conf\",\"\",\"color_quality_low\");\n \n if (attributes.state==\"UCLivenessMoveDetecting\" || attributes.state==\"UCLivenessMoveProcessing\") {\n // Arco completo\n canvas.beginPath();\n canvas.strokeStyle = colorProgress; // this.rm.getSetupColor(\"facephi-widget-conf\",\"\",\"color_progress_bar\");;\n canvas.lineWidth = borderWidth; // this.rm.getSetupFloat(\"facephi-widget-conf\", \"\", \"width_progress_bar\");\n canvas.lineCap = \"round\";\n canvas.arc(this.circleX, this.circleY, this.circleRadius - (canvas.lineWidth / 2) + 0.5, -Math.PI / 2, 2 * Math.PI - Math.PI / 2);\n canvas.stroke(); \n }\n\n } else {\n \n if (progress > 1.0) progress=1.0;\n if (this.extractionMode == FPhi.Selphi.Mode.Authenticate)\n progress = progress*progress*(3.0 - 2.0*progress); //smoothstep\n\n canvas.beginPath();\n canvas.strokeStyle = circleColor;\n canvas.lineWidth = borderWidth; // this.rm.getSetupFloat(\"facephi-widget-conf\", \"\", \"width_progress_bar\");\n canvas.lineCap = \"round\";\n canvas.arc(this.circleX, this.circleY, this.circleRadius - (canvas.lineWidth / 2) + 0.5, -Math.PI / 2, 2 * Math.PI * progress - Math.PI / 2);\n canvas.stroke();\n\n var colorShutter = this.rm.getSetupColor(\"facephi-widget-conf\", \"\", this.landscape, \"color_shutter\");\n this.drawBlind(canvas, this.circleX, this.circleY, this.circleRadius, attributes.eyesYLevel, attributes.blind, colorShutter, attributes.blindText); \n }\n\n\n\n } else if (elementType == \"results\") {\n\n var totalTransitionTime = 1.000 + 1.500 * attributes.progress;\n var progressTime = stateTime / totalTransitionTime;\n if (progressTime > 1.0) {\n progressTime = 1.0;\n }\n\n // Calculamos la interpolacion de la barra de progreso (OutQuad -> InOutQuad)\n progressTime = progressTime * (2.0 - progressTime);\n progressTime = progressTime < 0.5 ? 2 * progressTime * progressTime : -1 + (4 - 2 * progressTime) * progressTime;\n\n canvas.beginPath();\n canvas.fillStyle = this.rm.getSetupColor(viewId, elementId, this.landscape, \"background_color\");\n canvas.arc(this.circleX, this.circleY, this.circleRadius, -Math.PI / 2, 2 * Math.PI - Math.PI / 2);\n canvas.fill();\n\n var scoreColor = this.rm.getSetupColor(\"facephi-widget-conf\", \"\", this.landscape, \"color_quality_excellent\");\n if (attributes.progress <= 0.33)\n scoreColor = this.rm.getSetupColor(\"facephi-widget-conf\", \"\", this.landscape, \"color_quality_low\");\n else if (attributes.progress <= 0.66)\n scoreColor = this.rm.getSetupColor(\"facephi-widget-conf\", \"\", this.landscape, \"color_quality_good\");\n\n canvas.beginPath();\n canvas.strokeStyle = scoreColor;\n canvas.lineWidth = this.rm.getSetupFloat(\"facephi-widget-conf\", \"\", this.landscape, \"width_progress_bar\");\n canvas.lineCap = \"round\";\n canvas.arc(this.circleX, this.circleY, this.circleRadius - (canvas.lineWidth / 2) * 0.5, -Math.PI / 2, 2 * Math.PI * attributes.progress * progressTime - Math.PI / 2);\n canvas.stroke();\n\n // score text\n var message = \"\";\n var tipMessage = \"\";\n if (attributes.progress >= 1.0) {\n message = this.rm.translate(\"results_quality_excellent\");\n tipMessage = this.rm.translate(\"results_quality_message\");\n } else if (attributes.progress >= 0.333) {\n message = this.rm.translate(\"results_quality_good\");\n tipMessage = this.rm.translate(\"results_quality_message\");\n } else {\n message = this.rm.translate(\"results_quality_low\");\n tipMessage = this.rm.translate(\"results_quality_message\");\n }\n\n var textSize = this.rm.getSetupFloat(viewId, elementId, this.landscape, \"fontResult_size\");\n var lineHeight = textSize+1;\n var textFont = this.rm.getSetupResourceId(viewId, elementId, this.landscape, \"fontResult\");\n var align = \"CENTER\";\n var valign = \"TOP\";\n this.drawStringMultiline(canvas, message, { x: 0, y: this.circleY - 5, width: this.width, height: this.height }, scoreColor, textFont, textSize,lineHeight,align,valign);\n\n textSize = this.rm.getSetupFloat(viewId, elementId, this.landscape, \"fontQuality_size\");\n var lineHeight = textSize+1;\n textFont = this.rm.getSetupResourceId(viewId, elementId, this.landscape, \"fontQuality\");\n var align = \"CENTER\";\n var valign = \"TOP\";\n this.drawStringMultiline(canvas, tipMessage, { x: 0, y: this.circleY + 5 + textSize, width: this.width, height: this.height }, scoreColor, textFont, textSize,lineHeight,align,valign);\n\n } else if (elementType == \"animation\") {\n var direction=0;\n //if (attributes.state == \"UCLivenessMoveDetecting\") {\n if (\"livenessMoveDirection\" in attributes)\n direction = attributes.livenessMoveDirection;\n if (elementId!=\"liveness_move\") direction=0;\n //}\n this.drawAnimation(canvas, rect, viewId, elementId, widgetTime, stateTime, mode, attributes,direction);\n } else if (elementId == \"progress\") {\n canvas.fillStyle = this.rm.getSetupColor(viewId, elementId, this.landscape, \"background_color\");\n canvas.fillRect(rect.x, rect.y, rect.width, rect.height);\n\n canvas.fillStyle = this.rm.getSetupColor(viewId, elementId, this.landscape, \"progress_color\");\n canvas.fillRect(rect.x, rect.y, rect.width*attributes.progress, rect.height);\n }\n }", "function evtListener__skeletonOverlay_bgImage_setup ( elem , imgSrc__string ) {\n\n\t\t\telem.classList.add('skeletonOverlay');\n\n\t\t\tvar img = new Image();\n\t\t\timg.skeletonOverlay_bgImage_targetElem = elem;\n\n\t\t\timg.addEventListener('load', evtListener__skeletonOverlay_bgImage_onLoad);\n\t\t\timg.src = imgSrc__string || img__elem.getAttribute('data-bgImg-src');\n\t\t}", "function init() {\n setupThumbnailGallery(0);\n bindEvents();\n }", "function drawBoxes(boxes) {\n boxpolys = new Array(boxes.length);\n for (var i = 0; i < boxes.length; i++) {\n boxpolys[i] = new google.maps.Rectangle({\n bounds: boxes[i],\n fillOpacity: 0,\n strokeOpacity: 1.0,\n strokeColor: '#000000',\n strokeWeight: 1,\n map: map\n });\n };\n }", "function initializeObstacles() {\r\n\r\n\r\n\t// BOUNDARIES (invisible obstacles)\r\n\t// Starts from left of cave\r\n\t\r\n\t\r\n\tboxes.push ( new Boundary(-225, canvasHeight - 50, 185, 8) ); // Horizontal\r\n\tboxes.push( new Boundary(-40,canvasHeight - 50, 3, 50) ); // Vertical\r\n\r\n\t// Initial Floor\r\n\tboxes.push( new Boundary(-50,canvasHeight - 10, 200, 8) ); // H\r\n\r\n\t\r\n\t// Right floating island platform\r\n\t\r\n\tboxes.push( new Boundary(540,540, 300, 8) ); // H\r\n\t\r\n\tboxes.push( new Boundary(750,440, 8,100 ) ); // V\r\n\t\r\n\tboxes.push( new Boundary(760,440, 180, 8) ); // H\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t// PLATFORMS (visible obstacles)\r\n\r\n\r\n\t// Left stage part\r\n\r\n\tboxes.push ( new LargeObstacle(-300, 500, false) );\r\n\tboxes.push ( new RegularObstacle(-350, 700, false) );\r\n\tboxes.push ( new BouncyObstacle(-395, 780) );\r\n\t\r\n\tboxes.push ( new LargeObstacle(-500, 500, false) );\r\n\tboxes.push ( new LargeObstacle(-750, 500, false) );\r\n\r\n\t\r\n\t// Farther left\r\n\t\r\n\tboxes.push ( new RegularObstacle(-850, 400, false) );\r\n\tboxes.push ( new BouncyObstacle(-900, 400, false) );\r\n\t\r\n\tboxes.push ( new RegularObstacle(-980, 90, false) );\r\n\t\r\n\tboxes.push ( new RegularObstacle(-1100, 200, false) );\r\n\tboxes.push ( new RegularObstacle(-1050, 320, false) );\r\n\t\r\n\tboxes.push ( new LargerObstacle(-1350, 120, false) );\r\n\tboxes.push ( new Present(-1300, 110) );\r\n\t\r\n\r\n\t// Going under mainland platform & right\r\n\t\r\n\tboxes.push ( new SmallObstacle(-250, 800, false) );\r\n\tboxes.push ( new SmallObstacle(-125, 900, false) );\r\n\tboxes.push ( new SmallObstacle(75, 900, false) );\r\n\tboxes.push ( new RegularObstacle(125, 1100, false) );\r\n\tboxes.push ( new BouncyObstacle(200, 1100, false) );\r\n\tboxes.push ( new BouncyObstacle(500, 1100, false) );\r\n\tboxes.push ( new BouncyObstacle(500, 850, false) );\r\n\t\r\n\tboxes.push ( new Present(350, 780, false) );\r\n\t\r\n\r\n\t//player.initCheckpoint();\r\n\t//player.init(463,476);\r\n\t\r\n\t\r\n\t// Right stage part over platforms\r\n\r\n\tboxes.push( new LargeObstacle(215, 500, false) );\r\n\t\r\n\tboxes.push( new BouncyObstacle(315, 600, false) );\r\n\tboxes.push( new BouncyObstacle(315, 240, false) );\r\n\t\r\n\tboxes.push( new LargeObstacle(415, 500, false) );\r\n\r\n\t\r\n\tboxes.push( new Present(835, 425, false) );\r\n\t\r\n\t\r\n\t// Going up then left\r\n\t\r\n\tboxes.push( new LargerObstacle(190, -80, false) );\r\n\t\r\n\tboxes.push( new RegularObstacle(0, -100, false) );\r\n\t\r\n\tboxes.push( new SmallObstacle(-100, -200, false) );\r\n\tboxes.push( new Present(-100, -215, false) );\r\n\r\n\r\n\r\n\r\n}", "function drawBoxes() {\n boxpolys = new Array(boxes.length);\n for (var i = 0; i < boxes.length; i++) {\n boxpolys[i] = new google.maps.Rectangle({\n bounds: boxes[i],\n fillOpacity: 0,\n strokeOpacity: 1.0,\n strokeColor: '#000000',\n strokeWeight: 1,\n map: map\n });\n }\n}", "function lazyLoad(elements) {\n elements.forEach(item => {\n if (item.intersectionRatio > 0) {\n observer.unobserve(item.target);\n loadImage(item.target);\n console.log('oberved! :', item.target);\n };\n });\n}", "function prepareAndStyle(){var viewBoxSize=this.config?this.config.viewBoxSize:config.defaultViewBoxSize;angular.forEach({'fit':'','height':'100%','width':'100%','preserveAspectRatio':'xMidYMid meet','viewBox':this.element.getAttribute('viewBox')||'0 0 '+viewBoxSize+' '+viewBoxSize,'focusable':false// Disable IE11s default behavior to make SVGs focusable\n\t},function(val,attr){this.element.setAttribute(attr,val);},this);}", "function init() {\n\n if (group != null){\n group.selectAll(\"*\").remove();\n d3.select(\".cubes\").selectAll(\"*\").remove();\n }\n\n // SET THE SCALE (AUTO OR MANUAL)\n if(frozen == 0){\n if(hasAdjusted == 0){\n findScale();\n } else{\n hasAdjusted = 0;\n }\n }\n\n\n //******* CREATE THE CUBES AND PUSH THEM ********\n\n // ARRAYS OF ELEMENTS FOR EACH OBJECT IN THE IMAGE\n // VERTICES\n cubesData = [];\n yLine = [];\n xLine = [];\n // STRING\n xLabel = [];\n yLabel = [];\n\n // CUBE VARIABLES; ID, COLOR, ATTRIBUTE\n var cnt = 0;\n var ycolor;\n var xattr;\n\n // DATA VARIABLES; USER CHOICE, LENGTH OF DATA VARIABLES\n var results = getResult();\n var q = getLength(results[0]);\n var p = getLength(results[1]);\n\n var con = []; // STORES VALUES OF THE YEAR 2007 FOR USE IN CALCULATING GROWTH\n\n for (var z = 0; z < q; z++) {\n\n firstData = first(results, z); // OBTAIN FIRST VARIABLE'S DATA\n xattr = xLabel[z] // RETRIEVE X LABEL FOR THE CURRENT CUBE\n console.log(\"ITS OVER HERE\");\n\n for (var x = 0; x < p; x++) {\n\n secData = second(firstData, results[1], x); // OBTAIN SECOND VARIABLE'S DATA\n\n // ------------------------ CUBE ------------------------------\n\n var y = parseFloat((-1 * (secData) / diviser).toFixed(5)); // NUMBER OF DIGITS TO APPEAR AFTER DECIMAL POINT = 5 (10000)\n var a = 5 * x - 5*(p/2); // ADJUST SIZE\n var b = 5 * z - 5*(q/2); // ADJUST SIZE\n\n // ADJUST DATA TO SHOW GROWTH\n if(datatype == 1){\n if(z == 0){ // YEAR 2007\n con.push(secData);\n y=0;\n } else{\n // CALCULATIONS FOR GROWTH GO HERE\n // USE THE VALUES IN CON AND SECDATA\n // TO CALCULATE THE NEW Y FOR GROWTH\n\n var val;\n val = ((secData-con[x])/con[x])*100\n y = (-val)/10\n }\n }\n\n // MAKE THE CUBE\n var _cube = makeCube(a, y, b); // MAKE THE CUBE USING BASE (X,Y,Z)\n _cube.id = 'cube_' + cnt++; // THE NAME OF THE CUBE i.e cube_1\n _cube.height = y; // RECORDS THE HEIGHT OF THE CUBE\n ycolor = yLabel[x];\n console.log(\"ARE WE UNDEFINED?\", yLabel)\n _cube.ycolor = ycolor;\n _cube.xattr = xattr;\n cubesData.push(_cube); // ADDS CUBE TO ARRAY\n\n // ------------------------ LINES ------------------------------\n\n var x_line_edge = 5 * (p - 1)- 5*(p/2) + 5;\n var y_line_edge = 5 * (q - 1)- 5*(q/2) + 5;\n\n xLine.push([x_line_edge, 1, b]);\n yLine.push([a, 1, y_line_edge]);\n }\n\n }\n console.log(cubesData.length);\n\n var allData = [\n cubes3D(cubesData),\n yScale3d([yLine]),\n xScale3d([xLine]),\n ];\n ycolorLegend();\n\n console.log(\">>>>>>>>>>>> xLabel: \", xLabel);\n console.log(\">>>>>>>>>>>> yLabel: \", yLabel);\n processData(allData, 1000); // DRAW THE SVG\n }", "function initialize() {\n\tinitialColorScale(imageData);\n\tloadIconImages(imageData);\n\tdrawBarChart(imageData);\n\tdrawSliderBar(imageData);\n\tdrawTreemap(imageData);\n}", "function mViewer(client, imgDivID)\n{\n var me = this;\n\n me.debug = false;\n\n me.client = client;\n\n me.timeoutVal = 150;\n\n\n me.imgDiv = document.getElementById(imgDivID);\n\n me.display = jQuery('<div/>').appendTo(me.imgDiv);\n\n me.display = jQuery(me.display).get(0);\n\n me.gc = new iceGraphics(me.display);\n\n me.canvasWidth = jQuery(me.imgDiv).width();\n me.canvasHeight = jQuery(me.imgDiv).height();\n\n me.jsonText;\n me.updateJSON; // Contains general view information\n me.pickJSON; // Contains current reference point information\n\n\n// Current reference point coordinates\n\n me.currentX = 0;\n me.currentY = 0; \n me.currentRA = 0;\n me.currentDec = 0;\n\n\n me.updateCallbacks = [];\n\n var resizeTimeout = 0;\n var initializeTimeout = 0;\n\n\n// Window resizing can cause some overloading since the\n// resize events happen more rapidly than the back-end can\n// regenerate the image. To avoid this, we use the trick of\n// having the window resize trigger a timer which then gets \n// reinitialized if another resize event come along or, if the\n// user pauses in their resizing, calls a true \"resizeFinal\"\n// method which contacts the back-end.\n\n\n me.resize = function()\n {\n if(me.debug)\n console.log(\"DEBUG> mViewer.resize()\");\n\n if(resizeTimeout)\n clearTimeout(resizeTimeout);\n\n resizeTimeout = setTimeout(me.resizeFinal, me.timeoutVal);\n }\n\n\n// This is the \"resizeFinal\" code, which sends a \"resize <width> <height>\"\n// command to the back-end Python code.\n\n me.resizeFinal = function()\n {\n if(me.debug)\n console.log(\"DEBUG> mViewer.resizeFinal()\");\n\n me.grayOut(true);\n me.grayOutMessage(true);\n\n areaWidth = jQuery(me.imgDiv).width();\n areaHeight = jQuery(me.imgDiv).height();\n\n jQuery(me.display).height(areaHeight);\n jQuery(me.display).width (areaWidth);\n\n if(me.gc != null)\n {\n me.gc.clear();\n me.gc.refitCanvas();\n }\n\n me.canvasWidth = jQuery(me.imgDiv).width();\n me.canvasHeight = jQuery(me.imgDiv).height();\n\n var cmd = \"resize \"\n + me.canvasWidth + \" \"\n + me.canvasHeight + \" \";\n\n if(me.debug)\n console.log(\"DEBUG> cmd: \" + cmd);\n\n me.client.send(cmd);\n }\n\n\n// Initial sizing of the image is handled slightly differently \n// from a resize on the backend, but the logic for processing\n// the commands on this end is similar. The following two functions\n// could be merged with the previous two at some point. Presently \n// the functions are short enough that the duplication of code is \n// not considered an issue. \n\n me.initialize = function()\n {\n if(me.debug)\n console.log(\"DEBUG> mViewer.initialize()\");\n\n if(initializeTimeout)\n clearTimeout(initializeTimeout);\n\n initializeTimeout = setTimeout(me.initializeFinal, me.timeoutVal);\n }\n\n\n// An \"initializeFinal\" function, similar to \"resizeFinal\" above.\n\n me.initializeFinal = function()\n {\n if(me.debug)\n console.log(\"DEBUG> mViewer.initializeFinal()\");\n\n me.grayOut(true);\n me.grayOutMessage(true);\n\n areaWidth = jQuery(me.imgDiv).width();\n areaHeight = jQuery(me.imgDiv).height();\n\n jQuery(me.display).height(areaHeight);\n jQuery(me.display).width (areaWidth);\n\n if(me.gc != null)\n {\n me.gc.clear();\n me.gc.refitCanvas();\n }\n\n me.canvasWidth = jQuery(me.imgDiv).width();\n me.canvasHeight = jQuery(me.imgDiv).height();\n\n var cmd = \"initialize \"\n + me.canvasWidth + \" \"\n + me.canvasHeight + \" \";\n\n if(me.debug)\n console.log(\"DEBUG> cmd: \" + cmd);\n\n me.client.send(cmd);\n }\n\n\n\n// Add update callbacks\n\n me.addUpdateCallback = function(fName)\n {\n me.updateCallbacks.push(fName);\n }\n\n\n// When commands like \"resize\" or \"zoom\" are sent to the back-end\n// they ultimately result in a return request to the Javascript asking\n// it to display an updated image, update the display in some other\n// way, or shut down.\n\n me.processUpdate = function(cmd)\n {\n if(me.debug)\n console.log(\"DEBUG> Processing: \" + cmd);\n\n args = cmd.split(\" \");\n \n var cmd = args[0];\n\n\tif(me.debug)\n console.log(\"DEBUG> processUpdate(\" + cmd + \")\");\n\n // IMAGE Command \n if(cmd == \"image\")\n {\n me.gc.clear();\n\n me.gc.refitCanvas();\n\n if(me.debug)\n console.log(\"DEBUG> Retrieving new PNG.\");\n\n me.gc.setImage(args[1] + \"?seed=\" + (new Date()).valueOf());\n\n me.getJSON();\n }\n\n // RESIZED Command \n else if(cmd == \"resized\")\n {\n me.zoomCallback(0, 0, me.updateJSON.disp_width, me.updateJSON.disp_height); \n }\n\n // PICK Command \n else if(cmd == \"pick\")\n {\n me.getPick();\n }\n\n // HEADER Command \n else if(cmd == \"header\")\n {\n me.getHeader(args[1]);\n }\n\n // UPDATE DISPLAY Command \n else if(cmd == \"updateDisplay\")\n {\n if(me.debug)\n console.log(\"DEBUG> Requesting server update.\");\n\n var cmd = \"update\";\n\n if(me.debug)\n console.log(\"DEBUG> cmd: \" + cmd);\n\n me.client.send(cmd);\n }\n\n // CLOSE Command \n else if(cmd == \"close\")\n {\n window.close();\n }\n }\n\n\n// Get the JSON that corresponds to the current view (updateJSON)\n\n me.getJSON = function()\n {\n var xmlhttp;\n var jsonURL;\n\n if(me.debug)\n console.log(\"DEBUG> getJSON()\");\n\n jsonURL = \"view.json?seed=\" + (new Date()).valueOf();\n\n try {\n xmlhttp = new XMLHttpRequest();\n }\n catch (e) {\n xmlhttp=false;\n }\n\n if (!xmlhttp && window.createRequest)\n {\n try {\n xmlhttp = window.createRequest();\n }\n catch (e) {\n xmlhttp=false;\n }\n }\n\n xmlhttp.open(\"GET\", jsonURL);\n\n xmlhttp.send(null);\n\n xmlhttp.onreadystatechange = function()\n {\n if (xmlhttp.readyState==4 && xmlhttp.status==200)\n {\n me.jsonText = xmlhttp.responseText;\n\n me.updateJSON = jQuery.parseJSON(xmlhttp.responseText);\n\n \t for(i=0; i<me.updateCallbacks.length; ++i)\n {\n me.updateCallbacks[i]();\n }\n }\n else if(xmlhttp.status != 200)\n alert(\"Remote service error[1].\");\n }\n }\n\n\n// Get the JSON(s) with the statistics about the current pick\n// reference point (pick0.json, pick1.json, pick2.json)\n\n me.getPick = function()\n {\n var xmlhttp;\n\n var jsonURL;\n\n if(me.debug)\n console.log(\"DEBUG> getPick()\");\n\n jsonURL = \"pick.json?seed=\" + (new Date()).valueOf();\n\n try {\n xmlhttp = new XMLHttpRequest();\n }\n catch (e) {\n xmlhttp=false;\n }\n\n if (!xmlhttp && window.createRequest)\n {\n try {\n xmlhttp = window.createRequest();\n }\n catch (e) {\n xmlhttp=false;\n }\n }\n\n xmlhttp.open(\"GET\", jsonURL);\n\t \n xmlhttp.send(null);\n\n xmlhttp.onreadystatechange = function()\n {\n if (xmlhttp.readyState==4 && xmlhttp.status==200)\n {\n me.jsonText = xmlhttp.responseText;\n\n me.pickJSON = jQuery.parseJSON(xmlhttp.responseText);\n }\n else if(xmlhttp.status != 200)\n {\n alert(\"Remote service error[1].\");\n }\n\n \n // Initialize (populate) RegionStats object (corresponding \n // dialog may or may not be visible at this point)\n\n statsDisplay.init();\n\n me.currentX = statsDisplay.xref;\n me.currentY = statsDisplay.yref; \n me.currentRA = statsDisplay.raref;\n me.currentDec = statsDisplay.decref;\n\n jQuery(\"#currentPickX\").html(me.currentRA);\n jQuery(\"#currentPickY\").html(me.currentDec);\n\t } \n }\n\n\n// Get FITS header information\n\n me.getHeader = function(mode)\n {\n if (mode == \"gray\")\n {\n headerURL = \"header0.html?seed=\" + (new Date()).valueOf();\n jQuery(\"#grayHdr\").load(headerURL);\n }\n else if (mode == \"color\")\n {\n headerURL = \"header0.html?seed=\" + (new Date()).valueOf();\n jQuery(\"#blueHdr\").load(headerURL);\n\n headerURL = \"header1.html?seed=\" + (new Date()).valueOf();\n jQuery(\"#greenHdr\").load(headerURL);\n\n headerURL = \"header2.html?seed=\" + (new Date()).valueOf();\n jQuery(\"#redHdr\").load(headerURL);\n }\n else\n {\n console.log(\"Bad Header Directive: \" + mode);\n } \n }\n\n\n// Any number of controls may modify the JSON view structure\n// then call this routine to have it sent to the server to have\n// the image updated.\n\n me.submitUpdateRequest = function()\n {\n if(me.debug)\n console.log(\"DEBUG> mViewer.submitUpdateRequest()\");\n\n var cmd = \"submitUpdateRequest '\" + JSON.stringify(me.updateJSON) + \"'\";\n \n if(me.debug)\n console.log(\"DEBUG> cmd: \" + cmd);\n\n me.client.send(cmd); \n }\n\n\n// When the user draws a box on the screen, the most\n// common reaction is to ask the server to zoom the \n// image based on that box.\n\n me.zoomCallback = function(xmin, ymin, xmax, ymax)\n {\n var tmp;\n\n if(me.debug)\n console.log(\"DEBUG> mViewer.zoomCallback()\");\n\n me.grayOutMessage(true);\n me.grayOut(true);\n\n if(xmin > xmax)\n {\n tmp = xmin;\n xmin = xmax;\n xmax = tmp;\n }\n\n if(xmin == xmax)\n xmax = xmin + 1.e-9;\n\n me.canvasWidth = jQuery(me.imgDiv).width();\n me.canvasHeight = jQuery(me.imgDiv).height();\n\n ymin = (me.canvasHeight - ymin);\n ymax = (me.canvasHeight - ymax);\n\n if(ymin > ymax)\n {\n tmp = ymin;\n ymin = ymax;\n ymax = tmp;\n }\n\n if(ymin == ymax)\n ymax = ymin + 1.e-9;\n\n\n // If the zoom box is extremely small, it is almost certainly\n // a misinterpreted \"pick\". Treat it as such, and clear\n // the zoom box drawing from canvas.\n\n if((ymax-ymin)<5 && (xmax-xmin)<5) // arbitrary cutoff\n {\n me.grayOutMessage(false);\n me.grayOut(false);\n\n me.gc.clearDrawing();\n\n var cmd = \"pick \"\n + xmax + \" \"\n + ymax;\n\n if(me.debug)\n console.log(\"DEBUG> small box: \" + cmd);\n\n me.client.send(cmd);\n\n return;\n }\n\n if(me.debug)\n {\n console.log(\"DEBUG> min (screen): \" + xmin + \", \" + ymin);\n console.log(\"DEBUG> max (screen): \" + xmax + \", \" + ymax);\n }\n\n\n // Otherwise, zoom based on the zoom box boundaries.\n\n var cmd = \"zoom \"\n + xmin + \" \"\n + xmax + \" \"\n + ymin + \" \"\n + ymax;\n\n if(me.debug)\n console.log(\"DEBUG> cmd: \" + cmd);\n\n me.client.send(cmd);\n }\n\n\n// Special buttons are provided for resetting the zoom,\n// zooming in and zooming out. See \"ZoomControl.js\" \n// for related documentation.\n\n me.resetZoom = function()\n {\n var tmp;\n\n if(me.debug)\n console.log(\"DEBUG> mViewer.resetZoom()\");\n\n me.grayOutMessage(true);\n me.grayOut(true);\n\n var cmd = \"zoomReset\"\n\n if(me.debug)\n console.log(\"DEBUG> cmd: \" + cmd);\n\n me.client.send(cmd);\n }\n\n me.zoomIn = function()\n {\n var tmp;\n\n if(me.debug)\n console.log(\"DEBUG> mViewer.zoomIn()\");\n\n me.grayOutMessage(true);\n me.grayOut(true);\n\n var cmd = \"zoomIn\"\n\n if(me.debug)\n console.log(\"DEBUG> cmd: \" + cmd);\n\n me.client.send(cmd);\n }\n\n me.zoomOut = function()\n {\n var tmp;\n\n if(me.debug)\n console.log(\"DEBUG> mViewer.zoomOut()\");\n\n me.grayOutMessage(true);\n me.grayOut(true);\n\n var cmd = \"zoomOut\"\n\n if(me.debug)\n console.log(\"DEBUG> cmd: \" + cmd);\n\n me.client.send(cmd);\n }\n\n\n// Special buttons are provided for panning up, down, left, right\n// and diagonally between said directions. See \"ZoomControl.js\" \n// for related documentation.\n\n me.panUp = function()\n {\n var tmp;\n\n if(me.debug)\n console.log(\"DEBUG> mViewer.panUp()\");\n\n me.grayOutMessage(true);\n me.grayOut(true);\n\n var cmd = \"panUp\"\n\n if(me.debug)\n console.log(\"DEBUG> cmd: \" + cmd);\n\n me.client.send(cmd);\n }\n\n me.panDown = function()\n {\n var tmp;\n\n if(me.debug)\n console.log(\"DEBUG> mViewer.panDown()\");\n\n me.grayOutMessage(true);\n me.grayOut(true);\n\n var cmd = \"panDown\"\n\n if(me.debug)\n console.log(\"DEBUG> cmd: \" + cmd);\n\n me.client.send(cmd);\n }\n\n me.panLeft = function()\n {\n var tmp;\n\n if(me.debug)\n console.log(\"DEBUG> mViewer.panLeft()\");\n\n me.grayOutMessage(true);\n me.grayOut(true);\n\n var cmd = \"panLeft\"\n\n if(me.debug)\n console.log(\"DEBUG> cmd: \" + cmd);\n\n me.client.send(cmd);\n }\n\n me.panRight = function()\n {\n var tmp;\n\n if(me.debug)\n console.log(\"DEBUG> mViewer.panRight()\");\n\n me.grayOutMessage(true);\n me.grayOut(true);\n\n var cmd = \"panRight\"\n\n if(me.debug)\n console.log(\"DEBUG> cmd: \" + cmd);\n\n me.client.send(cmd);\n }\n\n me.panUpLeft = function()\n {\n var tmp;\n\n if(me.debug)\n console.log(\"DEBUG> mViewer.panUpLeft()\");\n\n me.grayOutMessage(true);\n me.grayOut(true);\n\n var cmd = \"panUpLeft\"\n\n if(me.debug)\n console.log(\"DEBUG> cmd: \" + cmd);\n\n me.client.send(cmd);\n }\n\n me.panUpRight = function()\n {\n var tmp;\n\n if(me.debug)\n console.log(\"DEBUG> mViewer.panUpRight()\");\n\n me.grayOutMessage(true);\n me.grayOut(true);\n\n var cmd = \"panUpRight\"\n\n if(me.debug)\n console.log(\"DEBUG> cmd: \" + cmd);\n\n me.client.send(cmd);\n }\n\n me.panDownLeft = function()\n {\n var tmp;\n\n if(me.debug)\n console.log(\"DEBUG> mViewer.panDownLeft()\");\n\n me.grayOutMessage(true);\n me.grayOut(true);\n\n var cmd = \"panDownLeft\"\n\n if(me.debug)\n console.log(\"DEBUG> cmd: \" + cmd);\n\n me.client.send(cmd);\n }\n\n me.panDownRight = function()\n {\n var tmp;\n\n if(me.debug)\n console.log(\"DEBUG> mViewer.panDownRight()\");\n\n me.grayOutMessage(true);\n me.grayOut(true);\n\n var cmd = \"panDownRight\"\n\n if(me.debug)\n console.log(\"DEBUG> cmd: \" + cmd);\n\n me.client.send(cmd);\n }\n\n\n// Center view on current \"pick\" reference point\n// (without changing zoom scale) See \"ZoomControl.js\" \n// for related documentation.\n\n me.center = function()\n {\n var tmp;\n \n if(me.debug)\n console.log(\"DEBUG> mViewer.center()\");\n\n me.grayOutMessage(true);\n me.grayOut(true);\n\n var cmd = \"center\"\n\n if(me.debug)\n console.log(\"DEBUG> cmd: \" + cmd);\n\n me.client.send(cmd);\n }\n\n\n// Show color stretch dialog. See \"ColorStretch.js\" \n// for related documentation.\n\n me.showColorStretch = function()\n {\n colorStretch.init();\n\n stretchDiv.dialog({\n autoOpen: false,\n resizable: false,\n width:'auto'\n });\n\n if(stretchDiv.dialog(\"isOpen\")==true)\n {\n stretchDiv.dialog(\"moveToTop\");\n }\n else\n {\n stretchDiv.parent().position({\n my: \"center\",\n at: \"center\",\n of: window\n });\n\n jQuery(\"#stretch\").dialog(\"open\");\n }\n }\n\n\n// Show layer control (overlay) dialog. See \"LayerControl.js\" \n// for related documentation. \n\n me.showOverlay = function()\n {\n layerControl.init();\n\n layerDiv.dialog({\n autoOpen: false,\n resizable: true,\n width:'auto',\n });\n\n if(layerDiv.dialog(\"isOpen\")==true)\n {\n layerDiv.dialog(\"moveToTop\");\n }\n else\n {\n layerDiv.parent().position({\n my: \"center\",\n at: \"center\",\n of: window\n });\n\n jQuery(\"#overlay\").dialog(\"open\");\n }\n }\n\n\n// Show region statistics dialog (mExamine results). \n// See \"RegionStats.js\" for related documentation. \n\n me.showStats = function()\n {\n me.getPick();\n \n statsDiv.dialog({\n autoOpen: false,\n resizable: false,\n width: 520, // manually determined width\n });\n\n if(statsDiv.dialog(\"isOpen\")==true)\n {\n statsDiv.dialog(\"moveToTop\");\n }\n else\n {\n jQuery(\"#stats\").dialog(\"option\", \"position\", { \n my: \"center\", \n at: \"center\", \n of: window\n });\n\n jQuery(\"#stats\").dialog(\"open\");\n }\n }\n\n\n// Show FITS header display dialog. See \"FITSHeaderViewer.js\" \n// for related documentation.\n\n me.showHeader = function()\n {\n headerDisplay.init();\n\n fitsDiv.dialog({\n autoOpen: false,\n resizable: false,\n width:'auto'\n });\n\n if(fitsDiv.dialog(\"isOpen\")==true)\n {\n fitsDiv.dialog(\"moveToTop\");\n }\n else\n {\n fitsDiv.parent().position({\n my: \"center\",\n at: \"center\",\n of: window\n });\n\n jQuery(\"#fitsheader\").dialog(\"open\");\n }\n }\n\n\n// Show dialog with image file name(s) and mode. \n// See \"InfoDisplay.js\" for related documentation.\n\n me.showInfoDisplay = function()\n {\n infoDisplay.init();\n\n infoDiv.dialog({\n autoOpen: false,\n resizable: true,\n width:'auto'\n });\n\n if(infoDiv.dialog(\"isOpen\")==true)\n {\n infoDiv.dialog(\"moveToTop\");\n }\n else\n {\n infoDiv.parent().position({\n my: \"center\",\n at: \"center\",\n of: window\n });\n\n jQuery(\"#infoArea\").dialog(\"open\");\n }\n }\n\n\n// Show zoom/pan/center control panel. See \"ZoomControl.js\" \n// for related documentation.\n\n me.showZoomControl = function()\n {\n zoomControl.init();\n\n zoomDiv.dialog({\n autoOpen: false,\n resizable: false,\n width:'auto'\n });\n\n if(zoomDiv.dialog(\"isOpen\")==true)\n {\n zoomDiv.dialog(\"moveToTop\");\n }\n else\n {\n jQuery(\"#zoomControl\").dialog(\"option\", \"position\", { \n my: \"left top\", \n at: \"right-190 bottom-420\", // manually determined position\n of: window\n });\n\n jQuery(\"#zoomControl\").dialog(\"open\");\n }\n }\n\n\n// If there are any registered update callbacks, \n// we call them here.\n\n me.clickCallback = function(x, y)\n {\n me.canvasWidth = jQuery(me.imgDiv).width();\n me.canvasHeight = jQuery(me.imgDiv).height();\n \n y = (me.canvasHeight - y);\n\n var cmd = \"pick \"\n + x + \" \"\n + y;\n\n if(me.debug)\n console.log(\"DEBUG> cmd: \" + cmd + \" \" + x + \" \" + y);\n\n me.client.send(cmd);\n }\n\n\n// For now, we will stub out right click\n\n me.rightClickCallback = function(x, y)\n {\n // Do nothing.\n }\n\n\n me.gc.boxCallback = me.zoomCallback;\n me.gc.clickCallback = me.clickCallback;\n me.gc.rightClickCallback = me.rightClickCallback;\n\n\n// Gray-out functions \n\n me.grayOut = function(vis, options)\n {\n // Pass true to gray out screen, false to ungray. Options are optional.\n // This is a JSON object with the following (optional) properties:\n //\n // opacity:0-100 // Lower number = less grayout higher = more of a blackout\n // zindex: # // HTML elements with a higher zindex appear on top of the gray out\n // bgcolor: (#xxxxxx) // Standard RGB Hex color code\n //\n // e.g., me.grayOut(true, {'zindex':'50', 'bgcolor':'#0000FF', 'opacity':'70'});\n //\n // Because 'options' is JSON, opacity/zindex/bgcolor are all optional and can appear\n // in any order. Pass only the properties you need to set.\n\n var options = options || {};\n var zindex = options.zindex || 5000;\n var opacity = options.opacity || 70;\n var opaque = (opacity / 100);\n var bgcolor = options.bgcolor || '#000000';\n\n var dark = document.getElementById('darkenScreenObject');\n\n if(!dark)\n {\n // The dark layer doesn't exist, it's never been created. So we'll\n // create it here and apply some basic styles.\n\n var tbody = document.getElementsByTagName(\"body\")[0];\n\n var tnode = document.createElement('div');\n\n tnode.style.position ='absolute'; // Position absolutely\n tnode.style.top ='0px'; // In the top\n tnode.style.left ='0px'; // Left corner of the page\n tnode.style.overflow ='hidden'; // Try to avoid making scroll bars\n tnode.style.display ='none'; // Start out Hidden\n tnode.id ='darkenScreenObject'; // Name it so we can find it later\n\n tbody.appendChild(tnode); // Add it to the web page\n\n dark = document.getElementById('darkenScreenObject'); // Get the object.\n }\n\n if(vis)\n {\n // Calculate the page width and height\n\n if( document.body && ( document.body.scrollWidth || document.body.scrollHeight ) )\n {\n var pageWidth = document.body.scrollWidth+'px';\n var pageHeight = (document.body.scrollHeight+1000)+'px';\n }\n else if( document.body.offsetWidth )\n {\n var pageWidth = document.body.offsetWidth+'px';\n var pageHeight = (document.body.offsetHeight+1000)+'px';\n }\n else\n {\n var pageWidth = '100%';\n var pageHeight = '100%';\n }\n\n\n // Set the shader to cover the entire page and make it visible.\n\n dark.style.opacity = opaque;\n dark.style.MozOpacity = opaque;\n dark.style.filter = 'alpha(opacity='+opacity+')';\n dark.style.zIndex = zindex;\n dark.style.backgroundColor = bgcolor;\n dark.style.width = pageWidth;\n dark.style.height = pageHeight;\n dark.style.display = 'block';\n }\n\n else\n dark.style.display='none';\n }\n\n\n// Display, \"Loading...\" message with animated clock gif\n\n me.grayOutMessage = function(vis)\n {\n var msg = document.getElementById('messageScreenObject');\n\n if(!msg)\n {\n var tbody = document.getElementsByTagName(\"body\")[0];\n\n var tnode = document.createElement('div');\n\n tnode.style.width = '125px';\n tnode.style.height = '30px';\n tnode.style.position = 'absolute';\n tnode.style.top = '50%';\n tnode.style.left = '50%';\n tnode.style.zIndex = '5500';\n tnode.style.margin = '-50px 0 0 -100px';\n tnode.style.padding = '5px';\n tnode.style.backgroundColor = '#ffffff';\n tnode.style.display = 'none';\n\n tnode.innerHTML = '<div style=\"padding: 1px 0px 0px 0px\">'\n + '&nbsp;<img src=\"waitClock.gif\"/></div>'\n + '<div style=\"padding:5px 0px 0px 0px\">'\n + '&nbsp;&nbsp;&nbsp;&nbsp;Loading...</div>';\n\n tnode.id = 'messageScreenObject';\n\n tbody.appendChild(tnode);\n \n msg = document.getElementById('messageScreenObject');\n }\n\n if(vis)\n msg.style.display = 'block';\n else\n msg.style.display = 'none';\n }\n}", "function initReels() {\n // iterate through all canvas elements, create context and new image\n canvases.forEach(function (canvas) {\n let ctx = canvas.getContext('2d');\n let img = new Image();\n img.src = 'images/Symbol_1.png';\n\n img.onload = function () {\n ctx.drawImage(\n img,\n spriteObject.sourceX, spriteObject.sourceY, spriteObject.sourceWidth, spriteObject.sourceHeight,\n spriteObject.x, spriteObject.y, spriteObject.width, spriteObject.height\n )\n };\n })\n }" ]
[ "0.578059", "0.5546543", "0.5403429", "0.5346193", "0.52966976", "0.52873456", "0.5264467", "0.52365804", "0.5184634", "0.5176011", "0.51637805", "0.51560503", "0.5112056", "0.5102133", "0.50975466", "0.50894904", "0.5087844", "0.5081945", "0.5068172", "0.50580996", "0.50417686", "0.50396097", "0.5038003", "0.5026489", "0.502191", "0.50207055", "0.50153804", "0.50020766", "0.49997485", "0.4990716", "0.49889055", "0.49867946", "0.49811795", "0.4977211", "0.49712104", "0.4970895", "0.49670705", "0.49644276", "0.4955246", "0.49546513", "0.4954438", "0.49505723", "0.49431577", "0.49414164", "0.4939462", "0.4936331", "0.4934001", "0.4927734", "0.49266836", "0.49192628", "0.49189582", "0.49155596", "0.49082533", "0.4891586", "0.4887745", "0.48776007", "0.48766282", "0.48747057", "0.4868703", "0.48615053", "0.4859276", "0.48569566", "0.485154", "0.48511595", "0.4850697", "0.48492792", "0.48432225", "0.48405048", "0.48386928", "0.48370558", "0.48345527", "0.48285636", "0.48234448", "0.48232296", "0.4822986", "0.48228547", "0.4820664", "0.4816252", "0.4814124", "0.48132464", "0.4809165", "0.4808093", "0.48040274", "0.47992307", "0.47956604", "0.4795235", "0.47918683", "0.47894132", "0.47879204", "0.47825077", "0.4778801", "0.47743988", "0.47722647", "0.4771274", "0.47636932", "0.47578052", "0.47548607", "0.47514528", "0.47460416", "0.4743431" ]
0.7491489
0
eslint noempty: 0 / eslint noparamreassign: 0 / eslint preferrestparams: 0
function splitNested(str) { return [str].join('.').replace(/\[/g, '.').replace(/\]/g, '').split('.'); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "addEmptyItemIfNeeded(initialItems: ?Object): Object {\n return _.isEmpty(initialItems) ? { '1': null } : initialItems;\n }", "_setParamIfEmpty(param){\r\n\t\t\r\n\t\tif(param == null) param = {};\r\n\t\t\r\n\t\tif(param['ajax_url'] == null) param['ajax_url'] = 'dummy';\r\n\t\t\r\n\t\treturn param;\r\n\t}", "_setParamIfEmpty(param){\r\n\t\t\r\n\t\tif(param == null) param = {};\r\n\t\t\r\n\t\tif(param['ja_flg'] == null) param['ja_flg'] = 1; \r\n\t\tif(param['datetimepicker_f'] == null) param['datetimepicker_f'] = 0; \r\n\t\t\r\n\t\treturn param;\r\n\t}", "function addEmptyParameter(list) {\n return list.push({ 'label': '', 'value': '', 'name': '' });\n}", "function _cleanUpEmptyParams(fp) {\n if (typeof fp === 'object') {\n // remove params namespaces if empty\n ['q', 'r'].forEach(function(ns) {\n if (typeof fp[ns] === 'object' && Object.keys(fp[ns]).length === 0) {\n delete fp[ns];\n }\n });\n }\n return fp;\n}", "promiseParams() {\n return {};\n }", "stripDefaultParams(params, defaults) {\n if(defaults) {\n let stripped =_.pick(params, (value, key) => {\n // setting the default value of a term to null in a state definition is a very explicit way to ensure it will NEVER generate a search tag, even with a non-default value\n return defaults[key] !== value && key !== 'order_by' && key !== 'page' && key !== 'page_size' && defaults[key] !== null;\n });\n let strippedCopy = _.cloneDeep(stripped);\n if(_.keys(_.pick(defaults, _.keys(strippedCopy))).length > 0){\n for (var key in strippedCopy) {\n if (strippedCopy.hasOwnProperty(key)) {\n let value = strippedCopy[key];\n if(_.isArray(value)){\n let index = _.indexOf(value, defaults[key]);\n value = value.splice(index, 1)[0];\n }\n }\n }\n stripped = strippedCopy;\n }\n return _(strippedCopy).map(this.decodeParam).flatten().value();\n }\n else {\n return _(params).map(this.decodeParam).flatten().value();\n }\n }", "getParams() {\n return {\n ...this.object,\n ...this.cacheData,\n };\n }", "prepareParams() {\n const { filters } = this.props;\n const params = {};\n\n if (filters !== undefined) {\n // Add status filter to param\n if (filters.status !== undefined && filters.status.value !== null) {\n params.status = filters.status.value;\n }\n\n // Add customer filter to params\n if (filters.customers !== undefined && filters.customers !== null) {\n params.ownerName = Array.from(filters.customers, customer => customer.value);\n }\n }\n\n return params;\n }", "function reqNone () {\n return [];\n}", "mapPropsToValues({ firstName, lastName, birthDate }) {\n return {\n firstName: firstName || \"\",\n lastName: lastName || \"\", \n birthDate: birthDate || \"\"\n };\n }", "function Common_removeEmptyStrings(obj){\n\t switch(typeof obj){\n\t\t case 'object':\n\t\t\t for(let key in obj){\n\t\t\t\t obj[key] = Common_removeEmptyStrings(obj[key]);\n\t\t\t }\n\t\t\tbreak;\n\t\t case 'string':\n\t\t\t if(obj.length <= 0){\n\t\t\t\t obj = null;\n\t\t\t }\n\t\t\tbreak;\n\t }\n\n\t return obj;\n}", "handleSubmit(e) {\n e.preventDefault();\n let name = this.state.name.trim();\n let email = this.state.email.trim();\n let subject = this.state.subject.trim();\n let content = this.state.content.trim();\n if (!name || !email||!subject ||!content) {\n return;\n }\n this.handleUserSubmit({ name: name, email: email,subject: subject,content: content });\n this.setState({ name: '', email: '' , subject: '' ,content: '' });\n }", "_handleSave () {\n let password = this.state.userData[1].value;\n let name = this.state.userData[2].value;\n let email = this.state.userData[3].value;\n let homeCurrency = this.state.userData[4].value;\n let userData = {\n userName: this.state.userData[0].value,\n password: password !== this.state.originalUserData[1].value ? password : null,\n name: name !== this.state.originalUserData[2].value ? name : null,\n email: email !== this.state.originalUserData[3].value ? email : null,\n homeCurrency: homeCurrency !== this.state.originalUserData[4].value ? homeCurrency : null,\n };\n this.props.dispatch(putUser(userData));\n }", "function fn1([{}]) {}", "function reqNone() {\n return [];\n}", "_prepareParams (params) {\n if (params == null) {\n params = {}\n }\n if (params.auth == null) {\n params.auth = {}\n }\n if (params.auth.key == null) {\n params.auth.key = this._authKey\n }\n if (params.auth.expires == null) {\n params.auth.expires = this._getExpiresDate()\n }\n\n return JSON.stringify(params)\n }", "function restParam (...rest) {\n console.log(rest)\n}", "_updateCommonFields(updateData, {\n firstName, lastName, picture, website, interests, careerGoals, retired,\n }) {\n if (firstName) {\n updateData.firstName = firstName;\n }\n if (lastName) {\n updateData.lastName = lastName;\n }\n if (picture) {\n updateData.picture = picture;\n }\n if (website) {\n updateData.website = website;\n }\n if (interests) {\n updateData.interestIDs = Interests.getIDs(interests);\n }\n if (careerGoals) {\n updateData.careerGoalIDs = CareerGoals.getIDs(careerGoals);\n }\n if (_.isBoolean(retired)) {\n updateData.retired = retired;\n }\n // console.log('_updateCommonFields', updateData);\n }", "constructor(...param) {\n this.firstname = param[0];\n this.lastname = param[1];\n this.address = param[2];\n this.city = param[3];\n this.state = param[4];\n this.zip = param[5];\n this.phoneNo = param[6];\n this.email = param[7];\n }", "function requireValue(isset) {\n if (!isset) {\n throw new Error(\"reduce of empty array with no initial value\");\n }\n }", "_fields2request(includeEmpty) {\n let result = [];\n\n for (const name of this.uniqueFieldNames) {\n var newName = name;\n\n // send clonables as list (even if there's only one field) and other fields as plain values\n let potentialClones = this.fields.filter(f =>\n f.name === name && (typeof f.value !== 'undefined') && (f.value !== \"\" || includeEmpty)\n );\n\n if (potentialClones.length === 0) continue;\n\n // encode ArrayBuffer as Base64 and change field name as a flag\n let encodeValue = (val) => {\n if (val instanceof ArrayBuffer) {\n newName = `_encoded_base64_${name}`;\n return btoa(String.fromCharCode(...new Uint8Array(val)));\n }\n else {\n return val;\n }\n };\n\n let value = potentialClones[0].clonable\n ? potentialClones.map(c => encodeValue(c.value)) // array for clonable fields\n : encodeValue(potentialClones[0].value) // or plain value otherwise\n // setting 'result' must be separate step as encodeValue() modifies 'newName'\n result[newName] = value;\n\n debug(`${name} = ${ potentialClones[0].clonable ? `[${result[newName]}]` : `\"${result[newName]}\"` }`);\n }\n return result;\n }", "function removeEmptyValueFromJSON(reqArr) {\n\tfor ( var key in reqArr) {\n\t\tif (reqArr[key] == undefined || reqArr[key] == '') {\n\t\t\tdelete reqArr[key];\n\t\t}\n\t\tfor ( var inKey in reqArr[key]) {\n\t\t\tif (reqArr[key][inKey] == undefined || reqArr[key][inKey] == '') {\n\t\t\t\tdelete reqArr[key][inKey];\n\t\t\t}\n\t\t}\n\t}\n\treturn reqArr;\n}", "function b(a){if(null===a||a===void 0)throw new TypeError('Object.assign cannot be called with null or undefined');return Object(a)}", "function resetFields(...args) {\r\n args.forEach(argument => argument.value=\"\");\r\n}", "function check_param(par) { \n return (par != null && par.length > 0) ? par:'';\n}", "mapPropsToValues({ name, age, email }) {\n return {\n name: name || '',\n age: age || '',\n email: email || ''\n }\n }", "function addUndefinedCheck(req, res, next) {\r\n if (\r\n typeof req.body.username == 'undefined' ||\r\n typeof req.body.name == 'undefined' ||\r\n typeof req.body.mobile == 'undefined' ||\r\n typeof req.body.email == 'undefined' ||\r\n typeof req.body.passwordHash == 'undefined' ||\r\n typeof req.body.address == 'undefined'\r\n ) {\r\n res.status(501).send(`Specify all parameters`);\r\n } else {\r\n console.log('addUndefinedCheck OK');\r\n next();\r\n }\r\n}", "isEmpty (value, msg) {\n assert(lodash.isEmpty(value), msg || `params must be empty, but got ${value}`);\n }", "updateUser() {\n let updatedUser = {};\n\n Object.keys(this.props.data.user).map(i => {\n if (this.state[i] === \"\" || this.state[i] === undefined) {\n return (updatedUser[i] = this.props.data.user[i]);\n } else {\n return (updatedUser[i] = this.state[i]);\n }\n });\n\n let {\n first_name,\n last_name,\n bio,\n username,\n github_url,\n linkedin_url,\n portfolio_url,\n website_url,\n twitter_url,\n blog_url\n } = updatedUser;\n\n this.props\n .mutate({\n variables: {\n first_name,\n last_name,\n username,\n github_url,\n bio,\n linkedin_url,\n portfolio_url,\n website_url,\n twitter_url,\n blog_url\n }\n })\n .then(({ data }) => {\n // console.log(data);\n // Leaving here for reference.\n })\n .catch(err => {\n console.error(err);\n });\n }", "function restParamsNArrays()\n{\n //constant, has to be initialized and cant be changed.\n const a = 100;\n\n // a = 50;\n let array = [100, 200, 300, 400, 500];\n let v1, v2, rest;\n\n //destructuring arrays and rest params. \n //rest params collect rest of the paramters in an array.\n [v1, v2,...rest] = array;\n console.log(a, v1, v2, rest);\n\n let v4, v5, rest1;\n [, v5,...rest1] = array;\n console.log(v4, v5, rest);\n\n //destructing objects.\n let car = {id : 400, style: \"convertible\"};\n //let {id, style} = car; //works fine.\n let id, style;\n ({id, style} = car); //needs paranthesis for diff between a code black and destructuring.\n console.log(id, style);\n\n //spread params ...opposite of rest...converts array to parameters.\n let nums = [1, 2, 3, 4, 5];\n testSpread(...nums);\n\n let str = 'abcdef';\n testSpread(...str); //string is iterable and gets converted to array of char on spread.\n\n}", "function emptyFields(req, res, next) {\r\n const values = Object.values(req.body);\r\n values.forEach((element) => {\r\n if (element.length == 0) {\r\n res.status(502).send(`Dont leave empty values`);\r\n throw new Error('user sent parameter with empty value');\r\n }\r\n });\r\n console.log('emptyFields OK');\r\n next();\r\n}", "checkParams(params) {\n if(params) {\n for(let i=0; i<params.length; i++) {\n if(params[i]==null) {\n return {\n check: false,\n res: error.params\n };\n }\n }\n }\n return {\n check: true\n };\n }", "beforeUpdate() {\n this.args.splice(0, this.args.length);\n for (const arg of this.body.args) {\n arg['value'] = \"\";\n this.args.push(arg);\n }\n }", "set full(value) {\n if (value) {\n this._namedArgs.full = \"1\";\n } else {\n delete this._namedArgs[\"full\"];\n }\n }", "function f28(x) {\n var a = _extends({}, _object_destructuring_empty(x)); // Error\n}", "function newConcat(val1, ...restParam) {\n\t// this returns a new array\n\tlet newArray = [...val1];\n\tconsole.log(restParam);\n\tfor (let i = 0; i < restParam.length; i++) {\n\t\tif (Array.isArray(restParam[i])) {\n\t\t\tnewArray = [...newArray, ...restParam[i]];\n\t\t} else {\n\t\t\tnewArray = [...newArray, restParam[i]];\n\t\t}\n\t}\n\treturn newArray;\n}", "function validatePut() {\n return true\n}", "convertHashArgsIfNeeded(inputArgs) {\n if (!(inputArgs.length == 1 && typeof inputArgs[0] == 'object' && !Array.isArray(inputArgs[0]))) return [[], inputArgs];\n inputArgs = inputArgs[0]; //first element is hashmap\n\n let args = [], errors = [];\n\n for (let inputName of Object.keys(inputArgs)) {\n let input = this._method.getInputByNameLike(inputName);\n\n if (!input) errors.push(`Unknown input ${inputName} for method ${this._method.name}`);\n else args[input.pos] = inputArgs[inputName];\n }\n return [errors, args];\n }", "_cleanParams(params) {\n for (const k in params) {\n const v = params[k];\n if (/^[0-9]*$/.test(v)) {\n params[k] = +v;\n }\n }\n return params;\n }", "_params(req, opts) {\n const body = req.body || {};\n\n if (opts.name) body.Name = opts.name;\n if (opts.session) body.Session = opts.session;\n if (opts.token) {\n body.Token = opts.token;\n delete opts.token;\n }\n if (opts.near) body.Near = opts.near;\n if (opts.template) {\n const template = utils.normalizeKeys(opts.template);\n if (template.type || template.regexp) {\n body.Template = {};\n if (template.type) body.Template.Type = template.type;\n if (template.regexp) body.Template.Regexp = template.regexp;\n }\n }\n if (opts.service) {\n const service = utils.normalizeKeys(opts.service);\n body.Service = {};\n if (service.service) body.Service.Service = service.service;\n if (service.failover) {\n const failover = utils.normalizeKeys(service.failover);\n if (typeof failover.nearestn === \"number\" || failover.datacenters) {\n body.Service.Failover = {};\n if (typeof failover.nearestn === \"number\") {\n body.Service.Failover.NearestN = failover.nearestn;\n }\n if (failover.datacenters) {\n body.Service.Failover.Datacenters = failover.datacenters;\n }\n }\n }\n if (typeof service.onlypassing === \"boolean\") {\n body.Service.OnlyPassing = service.onlypassing;\n }\n if (service.tags) body.Service.Tags = service.tags;\n }\n if (opts.dns) {\n const dns = utils.normalizeKeys(opts.dns);\n if (dns.ttl) body.DNS = { TTL: dns.ttl };\n }\n\n req.body = body;\n }", "function postRequest(url, list) {//data would be newlist\n const json_list = [];\n if (list.length > 0){\n list.forEach((item)=>{ //translates the local List to the requirements of the API\n json_list.push({\"label\": item.name, \"done\":false});\n });\n }else if (list.length === 0){\n json_list.push({\"label\": 'empty', \"done\":false}); //Generic Value!\n }\n return fetch(url, {\n \n method: 'PUT', // 'GET', 'PUT', 'DELETE', etc.\n body: JSON.stringify(json_list), // Coordinate the body type with 'Content-Type'\n headers: {\n 'Content-Type': 'application/json'\n }\n })\n .then(response => response.json())\n .then (data=>{\n //console.log(data);\n })\n }", "parseQueryParam(params) {\n const key = matchQueryParams(this.remaining);\n\n if (!key) {\n return;\n }\n\n this.capture(key);\n let value = '';\n\n if (this.consumeOptional('=')) {\n const valueMatch = matchUrlQueryParamValue(this.remaining);\n\n if (valueMatch) {\n value = valueMatch;\n this.capture(value);\n }\n }\n\n const decodedKey = decodeQuery(key);\n const decodedVal = decodeQuery(value);\n\n if (params.hasOwnProperty(decodedKey)) {\n // Append to existing values\n let currentVal = params[decodedKey];\n\n if (!Array.isArray(currentVal)) {\n currentVal = [currentVal];\n params[decodedKey] = currentVal;\n }\n\n currentVal.push(decodedVal);\n } else {\n // Create a new value\n params[decodedKey] = decodedVal;\n }\n }", "function fill (val) {\n while (typeof val === 'function') {\n val = val(req)\n }\n if (val === undefined || val === null) return ''\n if (typeof val === 'string') return val\n if (Array.isArray(val)) {\n return val.map(fill).join('')\n }\n // not much we can after here, so this is more diagnostic\n if (typeof val === 'object') return val // H.safe, JSON.stringify(val)\n return val.toString()\n }", "formatParams(params) {\n const whitelistedQuery = store.get(params.operationName);\n if (!whitelistedQuery) {\n console.log(\"This query/operation is not whitelisted\");\n }\n params['query'] = whitelistedQuery;\n return params;\n }", "isEmpty (param) {\n if (param == null || param === '') {\n return true\n }\n return false\n }", "static get _submitDataKwargs() {\r\n return {\r\n useCase: undefined, // String\r\n url: undefined, // String\r\n header: { // Object\r\n method: 'POST', // String\r\n body: undefined // String\r\n },\r\n data: {}, // Object\r\n primaryKeyName: undefined, // String\r\n primaryKey: '', // String\r\n indexKeyName: undefined, // String\r\n indexKey: undefined, // Integer\r\n shouldThrow: true, // Boolean\r\n shouldUpdateDbIfNoNetwork: true // Boolean\r\n };\r\n }", "function spread(o) { return { ...o }; }", "$_fillRecursive(formData) {}", "ensurePath(path, last = {}) {\n var object = this.getSearch().request;\n path.split('.')\n .forEach((part, index, arr) => {\n if( !object[part] ) {\n if( arr.length-1 === index ) object[part] = last;\n else object[part] = {};\n }\n object = object[part];\n });\n \n\n }", "addFieldsToParam(searchParam) {\n let allFields = this.fields.split(',');\n allFields.push('Id');\n allFields.push('Name');\n let cleanFields = this.dedupeArray(allFields).join(',');\n searchParam.fieldsToQuery = cleanFields;\n }", "function returnFirst(...items){\n // resting x # items into array (...items)\n // destructuring items array\n // [firstItem = items[0], blank for items[1], thirdItem = items[2]]\n // if you leave an empty part the destructuring it will pass it's assignment of items[1]\n const [firstItem,,thirdItem] = items; /*change this line to be es6*/\n //firstItem = 1, thirdItem = 3 -- 1+3 =4\n return firstItem + thirdItem\n}", "_onSubmit(evt) {\n evt.preventDefault();\n const {updateProfileFormState} = this.props.data;\n this.props.onSubmit(updateProfileFormState.firstName, updateProfileFormState.lastName, updateProfileFormState.project, updateProfileFormState.releaseDate, updateProfileFormState.primarySkills, updateProfileFormState.secondarySkills, updateProfileFormState.yearsOfExperience, updateProfileFormState.trainings, updateProfileFormState.qualification, updateProfileFormState.mobileNo, updateProfileFormState.email);\n}", "function consumePathArgs(args, needValue) {\n args = Array.prototype.slice.call(args, 0);\n var value = undefined;\n if (needValue) {\n if (args.length < 2) {\n throw new Error(\"too few path arguments; expected keys and value, got \" +\n JSON.stringify(args));\n }\n value = args[args.length-1];\n args = args.slice(0, args.length-1);\n }\n if (args.length === 0) {\n throw new Error(\"empty path not allowed\");\n }\n\n for (var i=0, len=args.length; i<len; i++) {\n if (typeof args[i] !== \"string\" || args[i].length === 0) {\n throw new Error(\"empty element (\" + i + \") in path: { \" + args[i] + \" }\");\n }\n }\n\n return {\n keys: args,\n value: value,\n };\n}", "notEmpty (value, msg) {\n assert(!lodash.isEmpty(value), msg || `params must be not empty, but got ${value}`);\n }", "parseQueryParam(params) {\n const key = matchQueryParams(this.remaining);\n if (!key) {\n return;\n }\n this.capture(key);\n let value = '';\n if (this.consumeOptional('=')) {\n const valueMatch = matchUrlQueryParamValue(this.remaining);\n if (valueMatch) {\n value = valueMatch;\n this.capture(value);\n }\n }\n const decodedKey = decodeQuery(key);\n const decodedVal = decodeQuery(value);\n if (params.hasOwnProperty(decodedKey)) {\n // Append to existing values\n let currentVal = params[decodedKey];\n if (!Array.isArray(currentVal)) {\n currentVal = [currentVal];\n params[decodedKey] = currentVal;\n }\n currentVal.push(decodedVal);\n }\n else {\n // Create a new value\n params[decodedKey] = decodedVal;\n }\n }", "parseQueryParam(params) {\n const key = matchQueryParams(this.remaining);\n if (!key) {\n return;\n }\n this.capture(key);\n let value = '';\n if (this.consumeOptional('=')) {\n const valueMatch = matchUrlQueryParamValue(this.remaining);\n if (valueMatch) {\n value = valueMatch;\n this.capture(value);\n }\n }\n const decodedKey = decodeQuery(key);\n const decodedVal = decodeQuery(value);\n if (params.hasOwnProperty(decodedKey)) {\n // Append to existing values\n let currentVal = params[decodedKey];\n if (!Array.isArray(currentVal)) {\n currentVal = [currentVal];\n params[decodedKey] = currentVal;\n }\n currentVal.push(decodedVal);\n }\n else {\n // Create a new value\n params[decodedKey] = decodedVal;\n }\n }", "parseQueryParam(params) {\n const key = matchQueryParams(this.remaining);\n if (!key) {\n return;\n }\n this.capture(key);\n let value = '';\n if (this.consumeOptional('=')) {\n const valueMatch = matchUrlQueryParamValue(this.remaining);\n if (valueMatch) {\n value = valueMatch;\n this.capture(value);\n }\n }\n const decodedKey = decodeQuery(key);\n const decodedVal = decodeQuery(value);\n if (params.hasOwnProperty(decodedKey)) {\n // Append to existing values\n let currentVal = params[decodedKey];\n if (!Array.isArray(currentVal)) {\n currentVal = [currentVal];\n params[decodedKey] = currentVal;\n }\n currentVal.push(decodedVal);\n }\n else {\n // Create a new value\n params[decodedKey] = decodedVal;\n }\n }", "parseQueryParam(params) {\n const key = matchQueryParams(this.remaining);\n if (!key) {\n return;\n }\n this.capture(key);\n let value = '';\n if (this.consumeOptional('=')) {\n const valueMatch = matchUrlQueryParamValue(this.remaining);\n if (valueMatch) {\n value = valueMatch;\n this.capture(value);\n }\n }\n const decodedKey = decodeQuery(key);\n const decodedVal = decodeQuery(value);\n if (params.hasOwnProperty(decodedKey)) {\n // Append to existing values\n let currentVal = params[decodedKey];\n if (!Array.isArray(currentVal)) {\n currentVal = [currentVal];\n params[decodedKey] = currentVal;\n }\n currentVal.push(decodedVal);\n }\n else {\n // Create a new value\n params[decodedKey] = decodedVal;\n }\n }", "parseQueryParam(params) {\n const key = matchQueryParams(this.remaining);\n if (!key) {\n return;\n }\n this.capture(key);\n let value = '';\n if (this.consumeOptional('=')) {\n const valueMatch = matchUrlQueryParamValue(this.remaining);\n if (valueMatch) {\n value = valueMatch;\n this.capture(value);\n }\n }\n const decodedKey = decodeQuery(key);\n const decodedVal = decodeQuery(value);\n if (params.hasOwnProperty(decodedKey)) {\n // Append to existing values\n let currentVal = params[decodedKey];\n if (!Array.isArray(currentVal)) {\n currentVal = [currentVal];\n params[decodedKey] = currentVal;\n }\n currentVal.push(decodedVal);\n }\n else {\n // Create a new value\n params[decodedKey] = decodedVal;\n }\n }", "function rest(...arg)\n{\n /*let sum=0;\n for(let i in arg) sum+=arg[i];\n return sum;*/\n return arg.reduce((a,b)=> a+b);\n}", "fillFields(newParameters, newOptional) {\n this.setState({parameters: newParameters, optional:newOptional})\n\n }", "function sum_rest(...args){\r\n return args.reduce((accumulator, currentValue) => accumulator + currentValue); //using reduce...\r\n} //Rest Operator", "function createEmptyParam() {\n vm.parametersList.addEmptyItem();\n }", "removeEmpty(obj){\n Object.keys(obj).forEach(key => {\n if (obj[key] && typeof obj[key] === 'object'){ \n this.removeEmpty(obj[key]);\n }\n else if (obj[key] == null){\n delete obj[key];\n } \n });\n return obj;\n }", "function validateItem(item) {\n // this removes undefined values from item.\n return _.merge({},item)\n}", "constructor(...params)\n {\n //defining first name, last name, address , city, state, zip, phone number and email\n this.firstName= params[0];\n this.lastName= params[1];\n this.address= params[2];\n this.city= params[3];\n this.state= params[4];\n this.zip= params[5];\n this.phoneNumber= params[6];\n this.email= params[7];\n }", "value(obj){\n return obj == null ? null : obj.name || obj.full_name || obj;\n }", "function blau(a,b,...params){\n return params;\n}", "function foo({first=10, second=true} = {}) {\n\n}", "function checkParams(cb) {\n if (Array.isArray(request.params)) {\n\t //since were limiting to two request we're only taking first two items from params array\n makeRequests(request.params.slice(0, 2));\n } else {\n if (typeof request.params === 'string') {\n makeSingleRequest(request.params);\n }\n }\n}", "_setValue(value) {\n if (value !== null) {\n // Also allow for \"componentName\" as \"component\" is a MSON keyword and results in compilation\n value = {\n ...value,\n component: value.component ? value.component : value.componentName,\n componentName: undefined,\n };\n }\n\n super._setValue(value);\n }", "cleanEmptyLeaves() {\n var body = this.getSearch().request;\n for( var key in body ) {\n if( typeof body[key] === 'object' ) {\n this._cleanEmptyLeaves(body, key);\n }\n }\n }", "cloneJSON(input){\n this.id = input.id;\n this.name = input.name;\n this.initialState = input.initialState;\n this.revisionHistory = input.revisionHistory;\n this.clientPos = input.clientPos;\n this.clientSocketID = input.clientSocketID;\n this.revisionAuthors = input.revisionAuthors; \n }", "static validateNupdate(input, output) {\r\n \r\n if (output[0].indexOf(input) === -1 && typeof input !== null && typeof input !== undefined) {\r\n output[0].push(input);\r\n }\r\n // console.log(output[0], input);\r\n return output;\r\n }", "put(requisicao, resposta, next){\n const { user_id, user_name, user_email } = requisicao.body;\n\n //name only letters validation\n if (!regexName.test(user_name)){\n next(ApiError.badRequest({\n \"erro\": true,\n \"code\": 3141,\n \"detail\": 'user_name: must be only letters'\n }));\n return;\n }\n\n //email pattern validation\n if (!regexEmailA.test(user_email) & !regexEmailB.test(user_email)){\n next(ApiError.badRequest({\n \"erro\": true,\n \"code\": 1618,\n \"detail\": 'user_email: must be a valid email pattern'\n }));\n return;\n }\n \n //no body filter\n if(JSON.stringify(requisicao.body)===JSON.stringify({})){\n next(ApiError.badRequest({\n \"erro\": true,\n \"detail\": 'Request body not found'\n }));\n return;\n }\n //no name, email or id filter\n if(!user_name || !user_email || !user_id){\n next(ApiError.badRequest({\n \"erro\": true,\n \"detail\": 'User_name, user_email or user_id not found'\n }));\n return;\n }\n try{\n const postgre = new postgresDB();\n const response = postgre.updateUser(requisicao, resposta, next);\n return response;\n\n }\n catch(error){\n resposta.status(503).send(error);\n }\n\n }", "function varParams(name, ...rest) {\n console.log('name: ', name);\n console.log('rest: ', rest);\n // console.log(rest.push);\n}", "changeProfileName(firstname,lastname) {\n let queryString = ''\n if (this.state.user.firstName !== firstname) {\n queryString+= 'firstName='+firstname\n }\n if (this.state.user.lastName !== lastname) {\n if (queryString !== '') {queryString+='&'}\n queryString += 'lastName='+lastname\n }\n //patch user firstname and lastname\n fetch('http://localhost:443/user?'+queryString,{\n method: \"PATCH\",\n headers: {\n Authorization: 'Bearer ' + this.props.token\n }\n })\n .then(res => res.json())\n .then(res => {\n //update frontend version of user\n let data = this.state.user;\n data.firstName = firstname;\n data.lastName = lastname;\n let memb = this.state.members\n memb[memb.indexOf(this.state.user)] = data\n this.setState({user:data, members:memb})\n })\n //hit backend instead\n }", "function validateNamedOptionalPropertyEquals(functionName,inputName,optionName,input,expected){if(input!==undefined){validateNamedPropertyEquals(functionName,inputName,optionName,input,expected);}}", "cleanedItem(item) {\n var newItem = JSON.parse(JSON.stringify(item));\n for (var propName in newItem) {\n if (newItem[propName] == null || !newItem[propName] || newItem[propName] == 0 || newItem[propName] == \"\") {\n delete newItem[propName];\n }\n }\n\n return newItem;\n }", "function defaults(dst,src){forEach(src,function(value,key){if(!isDefined(dst[key])){dst[key]=value;}});}", "function Jr(){return Jr=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},Jr.apply(this,arguments)}", "function checkActionBodyData() {\n return (req, res, next) => {\n if (\n !req.body.project_id ||\n !req.body.description ||\n !req.body.notes ||\n !req.body.completed\n ) {\n return res\n .status(400)\n .json({ message: \"missing project_id, description, notes, completed\" });\n }\n //stop here and send to next stack\n next();\n };\n}", "function completeConnector(partial = {}, full) {\n const checkAndAssign = (methodName) => {\n if (typeof partial[methodName] === 'undefined') {\n partial[methodName] = full[methodName]; // eslint-disable-line no-param-reassign\n }\n }\n\n checkAndAssign('create')\n checkAndAssign('read')\n checkAndAssign('update')\n checkAndAssign('delete')\n\n return partial\n}", "function correctPlistBlanks(obj) {\n for (const key in obj) {\n const val = obj[key];\n if (!val) obj[key] = \"\";\n }\n\n return obj;\n }", "function noempty(input_value, default_value)\n{\n if (!input_value)\n {\n return default_value;\n }\n if (input_value.length==0)\n {\n return default_value;\n }\n return input_value;\n}", "async assignUsers(stub, args) {\n\n //check args length should be 6\n if (args.length != 6) {\n console.info(`Argument length should be 6 with the order example: \n {\n user_id: \"abc\",\n organization: \"Seller\",\n user_id: \"MCB Bank\",\n organization: \"Bank\"\n mobile: \"0312*********\",\n address: \"F-10 Markaz\"\n }`);\n\n return shim.error(`Argument length should be 6 with the order example: \n {\n user_id: \"abc\",\n organization: \"Seller\",\n user_id: \"MCB Bank\",\n organization: \"Bank\"\n mobile: \"0312*********\",\n address: \"F-10 Markaz\"\n }`);\n }\n\n // let returnAsBytes = await stub.getPrivateData((args[1].charAt(0).toLowerCase() + args[1].slice(1)) + \"_users\", args[0]);\n let userBytes = await stub.getState(args[0]);\n console.info(userBytes)\n if (!userBytes || userBytes.length === 0) {\n throw new Error(`User with id ${args[2]} does not exist`);\n }\n\n let userBytes1 = await stub.getState(args[2]);\n console.info(userBytes1)\n if (!userBytes1 || userBytes1.length === 0) {\n throw new Error(`User2 of org ${args[3]} with id ${args[2]} does not exist`);\n }\n\n let user = JSON.parse(userBytes.toString());\n let userToAdd = {};\n\n userToAdd.name = args[2];\n userToAdd.addMember = args[4];\n userToAdd.addMember = args[5];\n\n if (args[3] === 'seller') {\n user.sellers.push(userToAdd);\n }\n else if (args[3] === 'trader') {\n user.traders.push(userToAdd);\n }\n else if (args[3] === 'buyer') {\n user.buyers.push(userToAdd);\n }\n else if (args[3] === 'banker') {\n user.bankers.push(userToAdd);\n }\n else if (args[3] === 'shipper') {\n user.shippers.push(userToAdd);\n }\n await stub.putState(args[0], Buffer.from(JSON.stringify(user)));\n }", "function correctPlistBlanks (obj) {\n for (var key in obj) {\n var val = obj[key]\n if (!val) obj[key] = ''\n }\n\n return obj\n }", "static _correctEmptyFields(episode: TraktEpisode): TraktEpisode {\n if (!episode) return episode;\n episode.title = episode.title ? episode.title : `Episode ${episode.number}`;\n return episode;\n }", "async getNoParam() {\n\t\treturn \"\";\n\t}", "constructor({\n title = '',\n name = title,\n status = 'unknown',\n experimental = false,\n date = new Date().toISOString(),\n publisher = '',\n description = '',\n items = [],\n ...restProps\n } = {}) {\n\n // Initialize fields\n this.title = title;\n this.name = name;\n this.status = status;\n this.experimental = experimental;\n this.date = date;\n this.publisher = publisher;\n this.description = description;\n this.items = items;\n Object.assign(this, restProps);\n\n // Check for uniqueness in itemIds\n const itemStack = [...items];\n const seenIds = new Set();\n while (itemStack.length) {\n const { itemId, items } = itemStack.pop();\n if (seenIds.has(itemId))\n throw new Error(`Item id ${itemId} is not unique.`);\n seenIds.add(itemId);\n itemStack.push(...items);\n }\n }", "function copyParam(param) {\n var copy = {};\n copy.name = param.name;\n copy.id = param.id;\n copy.minOccurs = param.minOccurs;\n copy.maxOccurs = param.maxOccurs;\n copy.mandatory = param.mandatory;\n copy.description = param.description;\n copy.type = param.type;\n copy.isArray = param.isArray;\n\n if (param.type === 'simple') {\n copy.default = param.default;\n copy.binding = param.binding;\n copy.unit = param.unit;\n copy.restriction = param.restriction;\n copy.ext = param.ext;\n copy.save = [];\n for (var i = 0; i < copy.minOccurs; i++) {\n copy.save.push(copy.default);\n }\n } else {\n copy.inputs = [];\n var paramInputs = param.inputs;\n //only duplicate minOccurs number of group occurrences.\n for (var j = 0; j < copy.minOccurs; j++) {\n var grpInputs = [];\n var params = paramInputs[j];\n var nbParams = params.length;\n for (var k = 0; k <nbParams; k++) {\n grpInputs.push(copyParam(params[k]));\n }\n copy.inputs.push(grpInputs);\n }\n }\n return copy;\n }", "function deepObjectAssign() {\n var merged = deepObjectAssignNonentry.apply(void 0, arguments);\n stripDelete(merged);\n console.log(merged);\n return merged;\n}", "function deepObjectAssign() {\n var merged = deepObjectAssignNonentry.apply(void 0, arguments);\n stripDelete(merged);\n console.log(merged);\n return merged;\n}", "removeJsonList(input) {\n let pathList = input.path.split(\"#\")\n let idList = input.id.split(\"#\")\n let valueList = input.value.split(\"#\")\n let jvalue = this.get(pathList[0]);\n\n if (pathList.length == 2) {\n if (jvalue) { //ACCOUNTS\n if (jvalue.constructor === Array) {\n let listObj = jvalue.find(obj => obj[idList[0]] === valueList[0]); // ONE ACNT OBJ\n const foundIndex = jvalue.findIndex(obj => obj[input.id] === input.value);\n\n if (listObj) {\n let rvalue = findValue(listObj, pathList[1]);\n if (rvalue.constructor === Array) {\n let filter = rvalue.filter(obj => obj[idList[1]] !== valueList[1]); // ONE ACNT OBJ\n const jeditor = new this.constructor(listObj);\n jeditor.set(pathList[1], filter);\n listObj = jeditor.toObject();\n } else {\n return ({ isError: true, error: { errorType: \"BadRequest\", \"message\": \"Expecting Array but found Object/String.\" } });\n }\n jvalue[foundIndex] = listObj;\n this.set(pathList[0], jvalue);\n } else {\n return ({ isError: true, error: { errorType: \"BadRequest\", \"message\": \"No Such object found.\" } });\n }\n\n } else {\n return ({ isError: true, error: { errorType: \"BadRequest\", \"message\": \"Expecting Array but found Object/String.\" } });\n }\n }\n }else if (pathList.length == 1){\n if (jvalue) { //ACCOUNTS\n if (jvalue.constructor === Array) {\n let filter = jvalue.filter(obj => obj[idList[0]] !== valueList[0]);\n this.set(pathList[0], filter);\n } else {\n return ({ isError: true, error: { errorType: \"BadRequest\", \"message\": \"Expecting Array but found Object/String.\" } });\n }\n }\n }else {\n return ({ isError: true, error: { errorType: \"BadRequest\", \"message\": \"Not handling more than two level list iteration.\" } });\n }\n\n return ({ isError: false, data: this.toObject() });\n }", "function restParams(a, b = 10, ...params) {\n log('a == ' + a);\n log('b == ' + b);\n log(\"params.length == \" + params.length);\n for(let a of params) {\n log(a);\n }\n }", "function OneArgWithRestParams (x, ... rest) {\n console.log('x: ${x}')\n console.log(rest)\n}", "function assignableArg(fragment) {\n if (fragment === undefined) {\n text = assignableArg(text)\n\t\tif (text === undefined) {\n\t\t\ttext = \"\"\n\t\t}\n\t\treturn\n\t}\n\n\tfragment = fragment.trim()\n\tvar prefix = getRegexPrefix(INDEXED_RE, fragment)\n \n\tif (prefix === false) {\n\t\tfragment = nameArg(fragment)\n\t} else {\n\t\tfragment = fragment.substring(prefix.length)\n\t\tfragment = expressionArg(fragment)\n fragment = expect(\")\", fragment)\n\n\t\tprogram.push(prefix)\n\t}\n\t\n\treturn fragment\n}", "function multiParameterUnderstanding(gotParam1, gotParam2) {\n\tconsole.log(\"Unassigned Multiple Marameters: \"+gotParam1+gotParam2)\n}", "function myFunc2(x, y, ...params) { // used rest operator here\n console.log(x);\n console.log(y);\n console.log(params);\n}", "onSubmit(data) {\n const { action, contextUserId, submit } = this.props\n action.userIdParameters.forEach(paramName => { data[paramName] = contextUserId; });\n submit(data);\n }" ]
[ "0.5616332", "0.55584323", "0.53030664", "0.5282773", "0.52214426", "0.5169118", "0.5055994", "0.5034779", "0.50234026", "0.5011705", "0.50060415", "0.498882", "0.49808842", "0.49668577", "0.49664873", "0.4960146", "0.49425292", "0.49409488", "0.4936963", "0.4906966", "0.48633757", "0.48539665", "0.48288402", "0.48202172", "0.48193088", "0.48027807", "0.47946164", "0.47942522", "0.47895792", "0.47853163", "0.47830608", "0.47825885", "0.47804445", "0.4779969", "0.4766428", "0.47636944", "0.4759629", "0.47471032", "0.47461784", "0.47357702", "0.47263932", "0.47227022", "0.47173786", "0.47142154", "0.4708233", "0.47057113", "0.47048184", "0.47047967", "0.4701095", "0.46912217", "0.46887994", "0.46872574", "0.46864298", "0.46799168", "0.46715716", "0.46674153", "0.46674153", "0.46674153", "0.46674153", "0.46674153", "0.46600398", "0.46562415", "0.4645629", "0.46409956", "0.46383438", "0.46381658", "0.46345544", "0.46309745", "0.46273002", "0.46241614", "0.46194416", "0.46192616", "0.46178097", "0.46150002", "0.46145192", "0.46087193", "0.46004042", "0.4599955", "0.45939252", "0.45928675", "0.45917836", "0.45893273", "0.45887962", "0.45840645", "0.45817453", "0.45812133", "0.45728907", "0.4569702", "0.45624322", "0.45617184", "0.4561627", "0.45588908", "0.4558758", "0.4558758", "0.45572877", "0.455716", "0.45567265", "0.4553965", "0.45502773", "0.4548947", "0.45474252" ]
0.0
-1
end of on click fav icon
function toggleFavorite(url, movieId, isFavored) { !isFavored ? favCount++ : favCount--; favCount > 9 ? $('#nav__fav-count').html('9+') : $('#nav__fav-count').html(favCount); $('.movie-' + movieId).toggleClass('fw-900'); if ($('.movie-' + movieId).closest('.favorite').length) { $('.movie-' + movieId).closest('.movie').remove(); }//end of if $.ajax({ url: url, method: 'POST', });//end of ajax call }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function closeFav(e) {\n if ($(e.target).is($(this))) {\n $(this).removeClass('favs-open');\n $favTrigger.attr('aria-expanded', false);\n $favWrapper.attr('aria-hidden', true); \n $favPanel.attr('aria-hidden', true); \n }\n }", "function favoriteClickHandler(){\n\t\n\t/**\n\t * Capture analytics event for favorite button click for reporting purposes\n\t */\n\tTi.Analytics.featureEvent('app.briefcase.favoritebtn.clicked');\n\n\t/**\n\t * update the state variable for the button\n\t */\n\tfavoriteStatus = !favoriteStatus;\n\t\n\t/**\n\t * set the icon variable to the proper reference based on the state\n\t */\n\tvar icon = !favoriteStatus ? 'icon-star-empty' : 'icon-star';\n\t$.favoriteBtn.setIcon(icon);\n}", "async function favClick(icon, storyId) {\n $(icon).toggleClass(\"far fas\");\n if ($(icon).hasClass(\"fas\")) {\n await User.addFavorite(storyId, currentUser);\n } else {\n await User.removeFavorite(storyId, currentUser);\n }\n // updates currentUser data\n await updateCurrentUser();\n }", "function removeFav() {\n\tif (event.target.closest('.fav-icon-copy')) {\n\t\t// store reference to the clicked icon\n\t\tconst favIconToRemove = event.target.closest('.fav-icon-copy');\n\t\tif (favIconToRemove.closest('.fav-card')) {\n\t\t\tconst favToRemove = favIconToRemove.closest('.fav-card');\n\n\t\t\t// update .fav-icon on result card so it displays correctly and is clickable again\n const favId = favToRemove.getAttribute('data-id');\n // get correct results category, restaurants or events to be able to access relevant nodeList\n\t\t\tconst favIdPrefix = favId.split('-')[0];\n\t\t\tupdateFavIconOnRemove(favId, favIdPrefix);\n\n\t\t\tfavToRemove.remove();\n\t\t\t\n\t\t\t// reset favorites to LS\n\t\t\tlocalStorage.setItem('faves', JSON.stringify(favoritesGridEl.innerHTML));\n\t\t}\n\t}\n}", "function setHeartIcon () {\n var image = data.images ? data.images[data.index] : data.image;\n if (Saved.has(image)) {\n page.querySelector('.app-button.heart').classList.add('fav');\n } else {\n page.querySelector('.app-button.heart').classList.remove('fav');\n }\n }", "function mouseoutFunc() {\n\tvar hoverIcon = makeMarkerIcon('D3D3D3');\n\tif (!newvm.marks()[this.id].favourite())\n\t\tthis.setIcon(hoverIcon);\n}", "function removeFavourite(ev) {\r\n const removeId = parseInt(ev.currentTarget.id);\r\n const clicked = favList[removeId];\r\n\r\n const indexFav = favList.indexOf(clicked);\r\n favList.splice(indexFav, 1);\r\n\r\n setLocalStorage();\r\n paintSeries();\r\n paintFav();\r\n}", "function handleFav(ev) {\n const livalue = ev.target.innerHTML;\n favoriteShow.push(livalue);\n renderFav();\n}", "listenAddFavourite() {\n this._qs(\".favourite\").addEventListener(\"click\", async () => {\n this.wait(\".favourite\");\n if (this._qs(\".favourite\").dataset.data == \"add\") {\n const res = await this.addFavourite(\"add\");\n if (res) {\n this._qs(\".favourite\").innerHTML =\n '<img src=\"/assets/icon/Favourite/Heart_Filled_24px.png\"></img>';\n this._qs(\".favourite\").title = \"Remove from favourite\";\n this._qs(\".favourite\").dataset.data = \"remove\";\n } else this.unwait(\".favourite\");\n } else {\n const res = await this.addFavourite(\"remove\");\n if (res) {\n this._qs(\".favourite\").innerHTML =\n '<img src=\"/assets/icon/Favourite/Heart_NotFilled_24px.png\"></img>';\n this._qs(\".favourite\").title = \"Add to favourite\";\n this._qs(\".favourite\").dataset.data = \"add\";\n } else this.unwait(\".favourite\");\n }\n });\n }", "function backToIconHome(){\n $(this).text(\"\");\n $(this).append(\"<img src=\\'../icons/homeicon.png\\' alt=\\'circleicon\\'>\");\n}", "function addFav(e){\r\n\tvar url=\"http://www.ipeen.com.tw\";\r\n\tvar title=\"iPeen 愛評網 - 美食消費經驗分享\";\r\n\tvar nav = navigator.userAgent;\r\n \r\n\tif(document.all) {\r\n\t \te.href = 'javascript:void(0);';\r\n\t\twindow.external.AddFavorite(url, title);\r\n\t\treturn false;\r\n\t} else if(nav.indexOf(\"SeaMonkey\") != -1) {\r\n \t\te.href = 'javascript:void(0);';\r\n\t\twindow.sidebar.addPanel(title, url, '');\r\n\t\treturn false;\r\n\t}\r\n}", "onSaveFavoriteClicked() {\n this._saveFavorite();\n }", "function onFavouriteButtonClicked() {\n this.toggleFavouriteActive();\n let isFavoured = this.buttons.favourite.classList.contains(\"active\");\n this.notifyAll(new Event(Config.POST_DETAIL_VIEW.EVENT\n .FAVOURISED_BUTTON_CLICKED, {\n favourite: isFavoured,\n post: this.openPost,\n }));\n}", "function onFavBtn(idMeal) {\n favBtn[1].style.color = \"red\";\n addMealsToLs(idMeal);\n setFavMealsOnDom();\n}", "function toggleFav(event) {\n $favWrapper.toggleClass('favs-open');\n $favTabsBtns.removeClass('active');\n var $favID = $(this).attr('data-fav-id'),\n $favType = $(this).attr('data-fav-type'),\n $state = $(this).attr('aria-expanded') === 'false' ? true : false;\n //update aria state\n $(this).attr('aria-expanded', $state);\n $favPanel.attr('aria-hidden', !$state); \n //show tab based on if user is viewing courses or programs. \n //For example, if user is on the program listings we show the program tab.\n if ($cpPrograms.add($programLanding).length){\n $favTabsBtns.last().addClass('active');\n $favList.find('li').hide();\n $favList.find('li').filter('.au-program').show(); \n noFavCheck('.au-program');\n } else {\n $favTabsBtns.first().addClass('active');\n $favList.find('li').hide();\n $favList.find('li').filter('.au-course').show(); \n noFavCheck('.au-course');\n } \n }", "function onSaveFavor() {\n AppManager.favorManager.addItem({\n url: src,\n title: nav.innerText,\n icon: nav.dataset.favicon\n });\n }", "function twistTheIcon() {\n $(this)\n .addClass(\"twist-it\")\n .one(endAnimation, function() {\n $(this).removeClass(\"twist-it\");\n });\n }", "function iconClicked(e) {\n // Get the icon element from the target of the event\n let icon = e.target;\n // Get the overall app div (the parent)\n let app = icon.parentElement;\n // Get the badge element by class name (we use [0] to get the first, and only\n // element in the returned set of elements - there's only one badge)\n let badge = app.getElementsByClassName('badge')[0];\n // Get the badge count\n let badgeCount = getBadgeCount(badge);\n // Reduce the badge count by one\n badgeCount--;\n // Don't let the badge count drop below 0\n if (badgeCount < 0) {\n badgeCount = 0;\n }\n // Set the new badge count on the badge\n setBadgeCount(badge, badgeCount);\n}", "function hideIcon () {\n currentBookmark = undefined\n browser.pageAction.hide(currentTab.id)\n updateIcon(false)\n}", "favFlick(item, flick, _ev){\n flick.fav = item.classList.toggle('fav'); //toggle returns true/ false. when on, it returns true, otherwise it returns false. hence we change the prop of object using this!\n }", "function triggerClick() {\n $('.feed:first-child .heart').trigger('click');\n return $('.feed:first-child').hasClass('favorite'); \n }", "toggleFavouriteActive() {\n let isFavoured = this.buttons.favourite.classList.toggle(\"active\"),\n favouredNum;\n if (isFavoured) {\n favouredNum = this.openPost.favourites.length + 1;\n } else {\n favouredNum = this.openPost.favourites.length - 1;\n }\n if (favouredNum >= Config.POST_DETAIL_VIEW.MAX_FAVOUR_NUM) {\n this.elements.favNumber.innerHTML = Config.POST_DETAIL_VIEW\n .OVER_FAVOUR_MAX;\n } else {\n this.elements.favNumber.innerHTML = favouredNum;\n }\n }", "function removeFav(e) {\n e.preventDefault();\n $this = $(this);\n var $favID = $this.attr(\"data-fav-id\"),\n $favType = $(this).attr('data-fav-type'),\n $favToRemove = $this.parents('.fav-item'),\n //what is the active tab\n $activeTab = $(this).closest('.cp-fav').find('.wrapper').find('.cp-fav-tabs').find('.active').attr('data-tabs'),\n $activeTabText = $(this).closest('.cp-fav').find('.wrapper').find('.cp-fav-tabs').find('.active').find('span').text();\n //Remove \"favorited\" class on card\n $('[data-fav-id=\"'+$favID+'\"]').removeClass('favorited');\n //Apply some animation to show item being removed\n $favToRemove.removeClass('in-list'),\n //Remove item from dom after slight delay\n setTimeout(function () {\n $favToRemove.remove();\n //Count number of items favorited after item removal\n getFavCount();\n //check if there is any more favorites in the current active tab. \n noFavCheck($activeTab, $activeTabText)\n }, 500);\n //after removal from DOM, delete the cookie\n delete_cookie($favType, $favID);\n }", "async function handleFavoriteButton(evt) {\n console.debug('handleFavoriteButton');\n // get the storyId from the li attribute\n const storyId = evt.target.closest('li').id;\n const story = storyList.stories.find(story => story.storyId === storyId);\n\n if(evt.target.classList.contains('fas')) {\n await currentUser.removeFavorite(currentUser, story);\n evt.target.classList.toggle(\"fas\");\n evt.target.classList.toggle(\"far\");\n } else {\n await currentUser.addFavorite(currentUser, story);\n evt.target.classList.toggle(\"far\");\n evt.target.classList.toggle(\"fas\");\n }\n}", "function updateIcon () {\n browser.browserAction.setIcon({\n path: currentBookmark\n ? {\n 19: '../public/star-filled-19.png',\n 38: '../public/star-filled-38.png'\n }\n : {\n 19: '../public/star-empty-19.png',\n 38: '../public/star-empty-38.png'\n },\n tabId: currentTab.id\n })\n browser.browserAction.setTitle({\n // Screen readers can see the title\n title: currentBookmark ? 'Unbookmark it!' : 'Bookmark it!',\n tabId: currentTab.id\n })\n}", "function saveFav() {\n}", "function noFav() {\n if (numberOfFav === 0) {\n $('#no-fav').show(); \n } else {\n $('#no-fav').hide();\n }\n}", "function mainAudioEnded() {\n // we'll do according to the icon means if user has set icon to loop song then we'll repeat\n // the current song and will do further accordingly\n\n let getText = repeatBtn.current.innerText; // getting innnerText icon\n // let's do different changes on different icon click using switch\n switch (getText) {\n case \"repeat\": // if this icon is repeat then read the next song\n nextMusic();\n break;\n case \"repeat_one\": // if this icon is repeat one then read thesame song\n repeatOneMusic();\n break;\n case \"shuffle\": // if this icon is shuffle then read a song at random\n shuffleMusic();\n break;\n default:\n break;\n }\n }", "function eventoFavoritos(btn){\n btn.addEventListener('click', function(){\n var urlImg = this.getAttribute('id');\n\n if(this.getAttribute('src') == '../img/favorites2.png'){\n this.setAttribute('src', '../img/favorites.png');\n var id = this.getAttribute('id-json');\n borrarFavoritos(id);\n } else {\n this.setAttribute('src', '../img/favorites2.png');\n aniadirFav(urlImg, btn);\n }\n \n });\n}", "function favorite() {\n var self = this;\n var id = $(this).attr('data-name');\n var data = {\n \"id\": id\n };\n\n if ($(self).hasClass(('glyphicon-star')))\n return;\n\n var request = $.post('/favorite', JSON.stringify(data));\n request.done(function() {\n $(self).removeClass('glyphicon-star-empty');\n $(self).addClass('glyphicon-star');\n });\n}", "function removeFav(item){\r\n //trouver l'index de ce favoris\r\n var numeroIndex = indexOF(favorisHistorique,item);\r\n //enlever un element d'une liste à un index donné, donc ici notre favoris\r\n favorisHistorique.splice(numeroIndex,1);\r\n //enlever l'ancienne liste\r\n window.localStorage.removeItem('favorisHistorique');\r\n //placer la nouvelle liste en localStorage\r\n window.localStorage.setItem('favorisHistorique', JSON.stringify(favorisHistorique));\r\n //Load l'affichage de la liste des favoris\r\n loadFavoris();\r\n //changer l'affichage de l'étoile pour put fav et la fonction onclick\r\n favoris.className = 'btn_clicable';\r\n favoris.removeAttribute(\"disabled\");\r\n imgFav.src = \"images/etoile-vide.svg\";\r\n favoris.setAttribute('onclick','putfav()');\r\n}", "function addToFavorites(event) {\n var clickedHartje = event.target;\n if (clickedHartje.innerHTML == \"♡\") {\n /* leeg hartje wordt vervangen door gevult hartje */\n clickedHartje.innerHTML = \"♥\"; updateWishlist(\"plus\");\n }\n else {\n clickedHartje.innerHTML = \"♡\"; updateWishlist(\"min\");\n }\n}", "function navFavoritesClick (evt) {\n\tconsole.debug('navFavoritesClick', evt);\n\thidePageComponents();\n\tputFavoritesListOnPage();\n}", "function addThisFav() {\r\n //Show all elements\r\n $('#favButton').addClass('favShow');\r\n\r\n window.setTimeout(function () {\r\n //Get the current url path\r\n var slicePath = window.location.pathname;\r\n\r\n var tit = document.getElementById('contentContainer');\r\n tit = tit.getElementsByTagName('h2')[0];\r\n tit = tit.innerHTML.split(tit.getElementsByTagName('small')[0].outerHTML)[0];\r\n\r\n //Add the current series to favorites\r\n addFavorite(slicePath, tit)\r\n\r\n window.setTimeout(function () {\r\n //Hide table\r\n $('#favButton').removeClass('favShow');\r\n }, 500);\r\n\r\n }, 500);\r\n}", "function FavIcon(x, name) {\r\n\r\n if (x.classList.contains(\"fa-star-o\")) {\r\n x.classList.remove(\"fa-star-o\");\r\n x.classList.add(\"fa-star\");\r\n\r\n if (localStorage.length > 0) {\r\n var i = Number(localStorage.length);\r\n if(localStorage.getItem(i) != null){\r\n while(localStorage.getItem(i) != null){\r\n i++;\r\n }\r\n }\r\n localStorage.setItem(i, name);\r\n }\r\n else {\r\n localStorage.setItem(0, name);\r\n }\r\n writeFav();\r\n }\r\n\r\n else {\r\n x.classList.remove(\"fa-star\");\r\n x.classList.add(\"fa-star-o\");\r\n\r\n for (let i = 0; i <= localStorage.length; i++) {\r\n const key = localStorage.key(i);\r\n var storageValue = localStorage.getItem(key);\r\n\r\n if (storageValue.localeCompare(name) == 0) {\r\n localStorage.removeItem(key);\r\n break;\r\n }\r\n }\r\n writeFav();\r\n }\r\n}", "function toggleFav(restID) {\n if ($(`i[data-id=\"${restID}\"]`).hasClass(\"fa-heart\")) {\n axios.delete(`/api/fav/rest/${restID}`).then(() => {\n $(`i[data-id=\"${restID}\"]`).removeClass(\"fa-heart\");\n $(`i[data-id=\"${restID}\"]`).addClass(\"fa-heart-o\");\n })\n }\n if ($(`i[data-id=\"${restID}\"]`).hasClass(\"fa-heart-o\")) {\n axios.post(`/api/fav/rest/${restID}`).then(() => {\n $(`i[data-id=\"${restID}\"]`).removeClass(\"fa-heart-o\");\n $(`i[data-id=\"${restID}\"]`).addClass(\"fa-heart\");\n })\n }\n }", "function favoritesClick() {\n staticImgPosition();\n bFavoritesDelay = false;\n bDiscoveryMsgDisplay = false;\n\n // Call discovery center function to show / hide discovery msg\n show_Discovery_Center_Changes();\n\n // Collapse all other section except Favorites\n clearCollapse(\"favorites\");\n\n setTimeout(function () {\n if (bFavoritesDelay)\n return;\n bBounchingAnimationStop = true;\n favoritesExpand();\n\n $(\"#favorites-box\").stop(true, true).fadeTo(550, 1);\n // Show Favorites content section \n $(\"#favorites-box\").css({\n transform: 'scale(1.0)',\n display: 'block'\n });\n\n // Hide Discovery section \n $(\"#divDiscoverySection\").css({\n //opacity: '0'\n display: 'none'\n });\n }, 50);\n }", "hideFavoriteList() {\n this.blockBtnTemporarily(this.elem.favTrigger, this.animDur.favList);\n this.elem.favSection.classList.remove(this.class.fav.active);\n }", "function removeFav(ev) {\n ev.currentTarget.remove();\n let favArray = getFavInd();\n\n const serieToRemove = favArray.indexOf(parseInt(ev.currentTarget.id));\n seriesFav.splice(serieToRemove, 1);\n localStorage.removeItem('favSeries');\n if (seriesFav.length > 0) {\n setLocalStorage(seriesFav);\n }\n\n const eachSerie__containers = document.querySelectorAll('.eachSerie__container');\n for (const container of eachSerie__containers) {\n if (container.id == parseInt(ev.currentTarget.id)) {\n container.classList.remove('alreadyFav');\n }\n }\n}", "function removeThisFav() {\r\n //Show all Elements\r\n $('#favButton').addClass('favShow');\r\n\r\n //Wait\r\n window.setTimeout(function () {\r\n //Get the current url path\r\n var slicePath = window.location.pathname;\r\n slicePath = slicePath.split('/');\r\n //Remove the current series to favorites\r\n removeFavorite(slicePath[2]);\r\n\r\n window.setTimeout(function () {\r\n //Hide table\r\n $('#favButton').removeClass('favShow');\r\n }, 500);\r\n\r\n }, 500);\r\n}", "function updateIcon() {\n if (current == \"cutebaycat-icon.png\") {\n current = \"cutebaycat-icon2.png\";\n chrome.browserAction.setIcon({path:current});\n chrome.browserAction.setTitle({text:\"Bid first. Bid last!\"});\n } else if (current == \"cutebaycat-icon2.png\") {\n current = \"cutebaycat-icon3.png\";\n chrome.browserAction.setIcon({path:current});\n chrome.browserAction.setTitle({text:\"Bid last. No bid!\"});\n } else {\n current = \"cutebaycat-icon.png\";\n chrome.browserAction.setIcon({path:current});\n chrome.browserAction.setTitle({text:\"No bid! Bid first!\"});\n }\n/* chrome.tabs.getSelected(null, function(tab) {\n chrome.tabs.sendMessage(tab.id, {greeting: current}, function(response) {\n console.log(response.farewell);\n });\n });*/\n}", "function toggleFavTabs(e) {\n e.preventDefault();\n //hide all list items first\n $favList.find('li').hide();\n var $favTabsActive = $(this).attr('data-tabs'),\n $favTabsBtnsTitle = $(this).find('span').text();\n //remove active state on other tab\n $favTabsBtns.not(this).removeClass('active');\n //add active state on clicked tab\n $(this).addClass('active');\n //show favorites that relate to currently selected tab\n $favList.find('li').filter($favTabsActive).show();\n //check if favorites are present and decided if we need to show a message\n noFavCheck($favTabsActive, $favTabsBtnsTitle);\n }", "onFavNum(fav) {\n this.totalFav = fav;\n if (this.totalFav.length == 5) {\n this.toastr.success('Click the nomination button in the top right corner to view your nominations', 'You now have 5 nominations', { positionClass: 'toast-top-center' });\n }\n }", "function addAndRemoveFavorites(item) {\n const isItemInFavourites = userFavourites.find(favourite => favourite._id === item._id);\n\n const favoritesIcon = document.querySelector('.favorites-div');\n const favIcon = favoritesIcon.querySelector('.advertisement-card-favorites-svg')\n if (isItemInFavourites) { favIcon.classList.add('js-mark-favorites-svg') }\n\n favoritesIcon.addEventListener('click', event => {\n if (!refsHeader.authorizationBlock.classList.contains('is-hidden')) {\n noticeToReg('Для начала зарегистрируйтесь!');\n openForm();\n } else {\n if (!favIcon.classList.contains('js-mark-favorites-svg')) {\n favIcon.classList.toggle('js-mark-favorites-svg');\n return addItemToFavourite(event.currentTarget.dataset.id);\n }\n favIcon.classList.toggle('js-mark-favorites-svg');\n return deleteItemFromFavourite(event.currentTarget.dataset.id);\n }\n });\n}", "addtocart() {\n this.favicon.waitForClickable({\n timeout: 30000,\n });\n this.favicon.click();\n }", "function stopIcon() {\n\n\tplaylist.stop();\n\tplaylist.renderInElement(playlistElement);\n\n\tif (playButton.innerHTML === '<i class=\"fa fa-stop\"></i>') {\n\t\treturn playButton.innerHTML = '<i class=\"fa fa-play\"></i>';\n\t}\n\n}", "function onToggleFollowingInsightSuccess(data) {\n\tvar favicon = $(\".addfav\", \".insight_\" + data.uniqueId);\n\tif(data.follow) {\n\t\tfavicon.addClass(\"active\");\n\t} else {\n\t\tfavicon.removeClass(\"active\");\n\t}\n}", "function rightRemoveHighlight(){\n\n $('#rightClick').fadeIn('slow', function(){\n $('#rightClick').attr(\"src\", \"icons/right_unclicked.png\");\n });\n}", "function favoritesMark(idGif) {\r\n favoriteGifs = localStorage.getItem(\"favoriteGifs\");\r\n favoriteGifs = favoriteGifs ? JSON.parse(favoriteGifs) : [];\r\n favoriteGifs.map(function (gif) {\r\n if (gif.id === idGif) {\r\n let favorite = document.querySelectorAll(\".iconFavorite[name='\" + idGif + \"']\");\r\n favorite.forEach(fav => {\r\n fav.classList.add('active');\r\n fav.removeEventListener('click', addFavoriteGif);\r\n });\r\n }\r\n });\r\n}", "function updateIcon() {\n browser.browserAction.setIcon({\n path: currentBookmark ? {\n 19: \"icons/star-filled-19.png\",\n 38: \"icons/star-filled-38.png\"\n } : {\n 19: \"icons/star-empty-19.png\",\n 38: \"icons/star-empty-38.png\"\n } \n });\n browser.browserAction.setTitle({\n // Screen readers can see the title\n title: currentBookmark ? 'Acceptable' : 'Not Acceptable'\n }); \n}", "showFavoriteList() {\n this.blockBtnTemporarily(this.elem.favTrigger, this.animDur.favList);\n this.elem.favSection.classList.add(this.class.fav.active);\n }", "function star() {\r\n //$('#channel-star').attr('src', 'http://ip.lfe.mw.tum.de/sections/star.png');\r\n $('#channel-star').toggleClass('fas far');\r\n\r\n}", "function addToFaveSearchResult(div) {\n for (let i of div.children) {\n i.addEventListener(\"click\", (e) => {\n if (e.target.classList.contains(\"re-heart\")) {\n addToFavInRandom(\n e.target.parentElement.parentElement.lastElementChild,\n e.target.parentElement.parentElement.firstElementChild\n );\n e.target.classList.toggle(\"far\");\n e.target.classList.toggle(\"fas\");\n e.target.classList.toggle(\"red\");\n }\n });\n }\n}", "function checkFav(){\r\n if (currentManipulatedUser && currentManipulatedUser.fav){\r\n addFav.style.color = \"gold\";\r\n // console.log(currentManipulatedUser);\r\n return;\r\n }\r\n addFav.style.color = \"white\";\r\n }", "function removeFav() {\n var remove = JSON.parse(localStorage.getItem('favorites')); //parse the favorites array\n var currentIndex = $(this).attr('src') //grab the current gif\n console.log(currentIndex)\n\n remove.splice(currentIndex, 1); //remove image from remove array\n favorites = remove; //turn remove back into favorites array\n $(`.favDiv_${currentIndex}`).remove();\n\n localStorage.setItem('favorites', JSON.stringify(remove)) //re set the array\n }", "function removeFavs() {\n // targets only buttons with class of 'remove'\n if ($(\"button\").hasClass(\"remove\")) {\n $(\".remove\").on(\"click\", function(){\n // removing elements from DOM\n var gifContent = $(this).prevAll();\n var gifButton = $(this);\n gifContent.remove();\n gifButton.remove();\n // targeting localStorage items with data-id\n var itemId = $(this).attr(\"data-id\");\n // removing items from localStorage\n localStorage.removeItem(\"rating-\" + itemId);\n localStorage.removeItem(\"gif-dataset-\" + itemId);\n // getting value of \"num-favorites\" to determine whether or not to remove it or decrement\n var currentStoredNum = parseInt(localStorage.getItem(\"num-favorites\"));\n if (currentStoredNum > 0) {\n currentStoredNum = currentStoredNum - 1;\n localStorage.setItem(\"num-favorites\", JSON.stringify(currentStoredNum));\n } else {\n localStorage.removeItem(\"num-favorites\");\n favNum = 0;\n }\n }); \n }\n \n }", "function changeFavButtonSearchResults() {\r\n const addFavorites = document.querySelectorAll('.js-series-card-favs');\r\n addFavorites.forEach((addFav) => {\r\n let found = favorites.find((fav) => fav.show.id === parseInt(addFav.id));\r\n /* if found exists, then series is already favorited */\r\n if (found) {\r\n addFav.classList.add('js-series-favs-remove'); /*changes colors*/\r\n addFav.innerHTML = `<i class=\"fas fa-minus-square\" aria-hidden=\"true\"></i> Remove from Favs`;\r\n } else {\r\n addFav.classList.remove('js-series-favs-remove');\r\n addFav.innerHTML = `<i class=\"fas fa-plus-square\"></i> Add to Favs`;\r\n }\r\n });\r\n}", "function starItem(){\r\n var current = getCurrentEntry();\r\n var currentEntry = current.getElementsByTagName(\"star\")[0];\r\n // var currentEntry = $(\"#current-entry .entry-actions .star\");\r\n simulateClick(currentEntry);\r\n }", "function addFavorite(event, type='details') {\n // Витягаю .item-favorite для того, щоб nextElementSibling спрацював\n const favoriteItem = event.target;\n // Витягаю alt в img по якому буду додавати фільми в LocalStorage\n let title = '';\n if (type === 'item')\n title = favoriteItem.nextElementSibling.getAttribute('alt');\n else\n title = favoriteItem.parentNode.parentNode.previousElementSibling.getAttribute('alt');\n \n if (title !== null && title !== undefined) {\n // Перевірка чи існує такий фільм у LocalStorage\n if (localStorage.getItem('favorites')) {\n const favorites = JSON.parse(localStorage.getItem('favorites'));\n\n // Шукає фільм в LocalStorage і вертає індекс масиву або -1\n const findElement = favorites.findIndex(item => {\n if (item === title) return item;\n });\n\n // Перевіряє наявність фільму в LocalStorage і якщо такий відстуній то додає\n if (findElement === -1) {\n favorites.push(title);\n } else {\n favorites.splice(findElement, 1);\n }\n\n localStorage.setItem('favorites', JSON.stringify(favorites));\n favoriteItem.classList.toggle('item__favorite--full');\n favoriteItem.classList.toggle('item-details__favorite--full');\n } else {\n const arrFavorite = [title];\n localStorage.setItem('favorites', JSON.stringify(arrFavorite));\n favoriteItem.classList.toggle('item__favorite--full');\n favoriteItem.classList.toggle('item-details__favorite--full');\n }\n }\n}", "function iconEndDrag(item, handle){\r\n\tEffect.Shake(item);\r\n\tposition = $(item).cumulativeOffset();\r\n\t\r\n\t//var icon = getIconHandle(handle)\r\n\tvar params = {\"type\":\"data\",\"class\":\"System\",\"do\":\"iconUpdate\",'icon_id':handle,'asynchronous':true,'_itop':position[1],'_ileft':position[0] };\r\n\tDobleOSAPI.executeApplication(params);\r\n}", "function addFavorites() {\n // changing text of button with add-fav class\n var addBtn = $(this)[0];\n addBtn.firstChild.data = \"Added to Favorites\";\n // creating a new div that will hold clone of favorite gif\n var newFav = $(\"<div>\");\n newFav.addClass(\"new-fav\");\n // grabs info from selected div and clones it\n var favGif = $(this).prevAll().clone();\n // creates button allowing for removal of favorited gif\n var removeFav = $(\"<button>\");\n removeFav.addClass(\"btn btn-info my-fav remove\");\n removeFav.text(`Remove from Favorites`);\n removeFav.attr(\"data-id\", favNum);\n // appending gif and removal button to newFav div\n newFav.append(favGif[1], removeFav);\n\n // saving key info to localStorage for later\n localStorage.setItem(\"num-favorites\", favNum);\n localStorage.setItem(\"rating-\" + favNum, JSON.stringify(favGif[0].innerHTML));\n localStorage.setItem(\"gif-dataset-\" + favNum, JSON.stringify(favGif[1].dataset));\n\n // adding newFav div to favorites section\n $(\"#fav\").append(newFav);\n // running function to allow for removal of favorite gifs\n removeFavs();\n favNum++;\n }", "onMarkerClick(props, marker, e) {\n if (this.state.favorites.includes(marker)) {\n this.setState({ favorites: this.state.favorites.filter(favorite => favorite != marker)})\n marker.setIcon('https://www.google.com/mapfiles/marker.png')\n } else {\n this.setState({ favorites: this.state.favorites.concat([marker]) })\n marker.setIcon('https://www.google.com/mapfiles/marker_green.png')\n }\n }", "function clearFavs() {\n storage.removeItem(\"favs\");\n }", "function getClickedImage() {\n \"use strict\";\n var mIC; //short for miscImageCounter\n if (document.getElementById(\"marbleCircle\")) {\n list = document.getElementById(\"marbleCircle\");\n item = $(list.lastChild);\n \n if ($(item).is('img')) {\n $(list.lastChild).remove();\n }\n for (mIC = 0; mIC < miscImageHolder.length; mIC++) {\n if ($(miscImageHolder[mIC]).attr(\"alt\") === $(item).attr(\"alt\")) {\n $(miscImageHolder[mIC]).parent().parent().addClass(\"reveal\");\n } else {\n $(miscImageHolder[mIC]).parent().parent().addClass(\"hide\");\n }\n }\n placeCenterMaterial();\n }\n}", "function toggleImportant(){\n console.log(\"Icon clicked\");\n\n if(!isItImportant){\n $(\"#iImportant\").removeClass(\"far\").addClass(\"fas\");\n isItImportant = true;\n }else{\n isItImportant = false;\n $(\"#iImportant\").removeClass(\"fas\").addClass(\"far\");\n };\n}", "function clickme(index) {\n\t$(\"#clickme\"+index).css(\"display\",\"none\");\n\tprogress[index-1] = 0.01;\n}", "function star() {\r\n $('#channel-star').toggleClass(\"fas far\");\r\n \r\n}", "function favFunction(){\n \n var favFlg=$(this).attr(\"fav-status\");\n var favorites=$(this); \n\n\n if(favFlg===\"yes\"){\n //when the favorite tag is unselected, call the delete favorite function\n deleteFavFunction();\n favorites.attr(\"fav-status\",\"no\");\n favorites.css(\"color\",\"black\");\n }else{\n // add the favorite car key to favoriteArr\n // if(!favoriteArr.includes(carKey)){\n favoriteArr.push({user:userId,carkey:carKey}); \n //save the favorite array to the local storage\n localStorage.setItem(\"favorite\",JSON.stringify(favoriteArr));\n // }\n //change favorite tag's status and color\n favorites.attr(\"fav-status\",\"yes\");\n favorites.css(\"color\",\"red\");\n \n }\n}", "function FavoriteListItem(glitem) {\n\n glitem.className = 'FavoriteItem';\n var button = glitem.getElementsByClassName('favoritebutton')[0];\n button.setAttribute('src', 'star.jpg');\n button.setAttribute('onclick', 'unfavorite(this.id, this)');\n\n return glitem;\n}", "function imgClick(e) {\n musicInfo = e.target.alt;\n splitInfo = musicInfo.split('_');\n DOMString.getCurrentMusicVideoTitle.textContent = splitInfo[0];\n DOMString.getCurrentMusicVideoArtist.textContent = splitInfo[1];\n DOMString.getCurrentMusicVideo.src = e.target.dataset.src;\n\n DOMString.getCurrentMusicVideoHeading.classList.add('fadeIn');\n setTimeout(() => DOMString.getCurrentMusicVideoHeading.classList.remove('fadeIn'), 500);\n }", "function onClickHeart(){\n if(compname === \"\"){\n notification['warning']({\n message: 'Function Error',\n description:\n 'There is no company selected.',\n });\n }else{\n if(heartState === true){\n setheartState(false);\n notification.open({\n message: 'My Favourite List Change !',\n description:\n `${compname} has been removed from My Favourite.`,\n icon: <HeartOutlined style={{ color: 'red' }} />,\n });\n }else{\n setheartState(true);\n notification.open({\n message: 'My Favourite List Change !',\n description:\n `${compname} has been added to My Favourite.`,\n icon: <HeartFilled style={{ color: 'red' }} />,\n });\n }\n }\n }", "function closePopUp () {\n if ( event.target == bell.querySelector('.icon')) {\n list.style.display = 'none'\n }}", "get favicon() {\n return $('//button[@name=\"add to wishlist\"]');\n }", "metaFavicon(img:string):void {\n\n\t\tthis.append(this.metaLink(img,\"shortcut icon\",\"image/png\"));\n\n\t}", "function addFavouriteListener() {\n const favButton = document.querySelectorAll(\".fav__button\");\n favButton.forEach(button => {\n button.addEventListener(\"click\", function(event) {\n const favourite = document.createElement(\"li\");\n favourite.className = \"favourite__item\"\n favourite.textContent = Array.from(event.target.parentNode.childNodes)[1].textContent;\n appendFavouriteItem(favourite);\n })\n })\n}", "function enableFavorites(items) {\n var _loop_1 = function (k) {\n var $icndiv = items[k].children().eq(1); // icons div\n var $favicn = $icndiv.children().eq(0); // 'like' <img> element\n // retrieve hike no from content div\n var hikelink = $icndiv.next().children().eq(0).attr('href');\n var digitpos = hikelink.indexOf('=') + 1;\n var hno = hikelink.substr(digitpos);\n var hikeno = parseInt(hno);\n $favicn.off('click').on('click', function () {\n var ajaxdata = { no: hikeno };\n var isrc = $(this).attr('src');\n var newsrc;\n var $tooltip = $(this).parent().prev();\n var $that = $(this);\n if (isrc.indexOf('Yellow') !== -1) { // currently a not favorite\n ajaxdata.action = 'add';\n $.ajax({\n url: \"markFavorites.php\",\n method: \"post\",\n data: ajaxdata,\n dataType: \"text\",\n success: function (results) {\n if (results === \"OK\") {\n newsrc = isrc.replace('Yellow', 'Red');\n $tooltip.text('Unmark');\n $that.attr('src', newsrc);\n }\n else {\n alert(\"You must be a registered user\\n\" +\n \"in order to save Favorites\");\n }\n },\n error: function () {\n var msg = \"A server error occurred\\nYou will not be able \" +\n \"to save Favorites at this time:\\nThe admin has been \" +\n \"notified\";\n alert(msg);\n var ajxerr = { err: \"Mark favorites php error: save\" };\n $.post('../php/ajaxError.php', ajxerr);\n }\n });\n }\n else { // currently a favorite\n ajaxdata.action = 'delete';\n $.ajax({\n url: \"markFavorites.php\",\n method: \"post\",\n data: ajaxdata,\n dataType: \"text\",\n success: function (results) {\n if (results === 'OK') {\n newsrc = isrc.replace('Red', 'Yellow');\n $tooltip.text('Add to Favorites');\n $that.attr('src', newsrc);\n }\n else {\n alert(\"You must be a registered user\\n\" +\n \"in order to save Favorites\");\n }\n },\n error: function () {\n var msg = \"A server error occurred\\nYou will not be able \" +\n \"to unsave Favorites at this time:\\nThe admin has been \" +\n \"notified\";\n alert(msg);\n var ajxerr = { err: \"Mark favorites php error: unsave\" };\n $.post('../php/ajaxError.php', ajxerr);\n }\n });\n }\n });\n };\n for (var k = 0; k < items.length; k++) {\n _loop_1(k);\n }\n return;\n}", "function onToggleFollowingUserSuccess(data) {\n\tvar favicon = $(\".addfav\", \".user_\" + data.id);\n\tif(data.follow) {\n\t\tfavicon.addClass(\"active\");\n\t} else {\n\t\tfavicon.removeClass(\"active\");\n\t}\n}", "function addToFavourites(e) {\n if (e.target.classList.contains('favourite')) {\n addToLocalstorage(e.target.getAttribute('value'));\n modal.classList.remove(\"show\");\n checkLocalStorage();\n }\n}", "function finalRating(){\n let stars = $(\".fa-star\");\n $(stars[stars.length-1]).toggleClass(\"fa-star fa-star-o\");\n}", "function app_fav_add(imgCell) {\r\n\r\n // Setup image data sources\r\n let imgData = $(imgCell).parent().children('img');\r\n let src = imgData.attr('data-fav');\r\n\r\n if (appData.favList.includes(src)) { return null }\r\n\r\n // Change outline/heart color to green\r\n $(imgCell).parent().css('backgroundColor', '#26ad5e');\r\n $(imgCell).children('.fas').css('color', '#26ad5e')\r\n\r\n // Push to array and save to local storage\r\n appData.favList.push(src);\r\n localStorage.setItem('dataListFavorites', JSON.stringify(appData.favList));\r\n\r\n // Append latest favorites entry inside fav container\r\n app_render_favorites_append();\r\n}", "function updateFavIconOnRemove(favId, favIdPrefix) {\n\tif (favIdPrefix === 'restau') {\n\t\tconst restauNodeList = restauCarouselEl.querySelectorAll('.carousel-item');\n\t\trestauNodeList.forEach(function(restauNode) {\n\t\t\tconst restauNodeId = restauNode.getAttribute('data-id');\n\n\t\t\tif (favId === restauNodeId) {\n\t\t\t\tconst nodeIcon =\n\t\t\t\t\trestauNode.querySelector('.fav-icon-copy') ||\n\t\t\t\t\trestauNode.querySelector('.fav-icon');\n\t\t\t\tnodeIcon.classList = 'material-icons fav-icon';\n\t\t\t\tnodeIcon.innerText = 'favorite_border';\n\t\t\t}\n\t\t});\n\t} else {\n\t\tconst eventNodeList = eventCarouselEl.querySelectorAll('.carousel-item');\n\t\teventNodeList.forEach(function(eventNode) {\n\t\t\tconst eventNodeId = eventNode.getAttribute('data-id');\n\n\t\t\tif (favId === eventNodeId) {\n\t\t\t\tconst nodeIcon =\n\t\t\t\t\teventNode.querySelector('.fav-icon-copy') ||\n\t\t\t\t\teventNode.querySelector('.fav-icon');\n\t\t\t\tnodeIcon.classList = 'material-icons fav-icon';\n\t\t\t\tnodeIcon.innerText = 'favorite_border';\n\t\t\t}\n\t\t});\n\t}\n}", "notifyIconAction() {}", "function todaysFavoite(songData) {\n var info = {\n artist: songData.artist.name,\n song: songData.name,\n listeners: songData.listeners,\n image: songData.image[3]['#text']\n };\n generateTemplate('favorite', info);\n }", "function asyncFavicon (e) {\r\n let bnId = e.data[0]; // Id of BookmarkNode\r\n let uri = e.data[1]; // String\r\n let BN = curBNList[bnId];\r\n if (BN == undefined) // The bookmark was deleted meanwhile ... so just skip it, do nothing\r\n\treturn;\r\n\r\n//console.log(\"Async uri received for BN.id: \"+bnId+\" url: \"+BN.url+\" uri: <<\"+uri.substr(0,50)+\">>\");\r\n\r\n // Refresh display of the icon, and save it\r\n if (uri.startsWith(\"error:\")) { // Got an error ... trace it\r\n\ttrace(\"Error on getting favicon for \"+bnId+\":\\r\\n\"\r\n\t\t +\"title: \"+BN.title+\"\\r\\n\"\r\n\t\t +\"url: \"+BN.url+\"\\r\\n\"\r\n\t\t +uri+\"\\r\\n\"\r\n\t\t +\"--------------------\");\r\n\tsetNoFavicon(bnId);\r\n }\r\n else if (uri.startsWith(\"starting:\")) { // We started retrieving a new favicon, signal it\r\n\t\t\t\t\t\t\t\t\t\t // on the bookmarks table by a \"waiting\" icon\r\n\tsetWaitingFavicon(bnId);\r\n }\r\n else if (!uri.startsWith(\"data:image/\")\r\n\t \t && !uri.startsWith(\"data:application/octet-stream\")\r\n\t \t && !uri.startsWith(\"data:text/plain\")\r\n\t \t && !uri.startsWith(\"data:text/html\")\r\n\t \t && !uri.startsWith(\"/icons/\")\r\n \t\t ) { // Received another data type than image ...!\r\n\ttrace(\"Didn't get an image on favicon for \"+bnId+\":\\r\\n\"\r\n\t\t +\"url: \"+BN.url+\"\\r\\n\"\r\n\t\t +uri+\"\\r\\n\"\r\n\t\t +\"--------------------\");\r\n\tsetNoFavicon(bnId);\r\n }\r\n else { // Valid URI returned\r\n\tsetFavicon(bnId, uri);\r\n }\r\n}", "removeFav(e) {\n let objectId = +e.target.getAttribute(\"value\");\n this.pushFav(objectId);\n }", "function app_render_favorites_append() {\r\n let i = appData.favList.length - 1;\r\n let imgSource = appData.favList[i]\r\n //let imgURL = appData.favList[i].imgEmbed;\r\n let myHTML = `\r\n <div class=\"app_content_cell app_favorites_cell fade-in\">\r\n <div class=\"app_content_cell_options\" onclick=\"app_fav_remove(this, ${i})\">\r\n <i class=\"fas fa-times\"></i>\r\n </div>\r\n <img class=\"fade-in-fwd\" src=\"${imgSource}\">\r\n </div>`;\r\n\r\n $('.app_favorites_content').append(myHTML);\r\n\r\n // Update Favorites Container Size\r\n app_favorites_update_size();\r\n\r\n}", "function followingArtistClick(){\n followingOpened = false;\n searchArtist($(this).attr(\"data-name\"));\n currentSubject = \"\";\n}", "function removeFavourite(key){\n\t\t$(\".result-item[data-key='\" + key + \"']\").removeClass(\"favourited\"); //remove class\n\t\tfavourites.splice($.inArray(key, favourites), 1);\n\t \tlocalStorage.setItem(\"TWL-favourites\", JSON.stringify(favourites));\n\t\tdisplayFavouritesSection();\n\t}", "function refreshFaviconSearch (btnId, uri) {\n if (SearchTextInput.value.length > 0) { // Refresh only if a search is active\n\tlet row = curResultRowList[btnId];\n\tif (row != undefined) { // There is a result in search pane corresponding to that BTN\n\t // Update only the row, do not change anything else\n\t let bkmkitem = row.firstElementChild.firstElementChild;\n\t let oldImg = bkmkitem.firstElementChild;\n\t let cn = oldImg.className;\n\t if (uri == \"/icons/nofavicon.png\") {\n\t\tif ((cn == undefined) || !cn.includes(\"nofavicon\")) { // Change to nofavicon only if not already a nofavicon\n\t\t let tmpElem = document.createElement(\"div\");\n\t\t tmpElem.classList.add(\"nofavicon\");\n\t\t tmpElem.draggable = false; // True by default for <img>\n\t\t bkmkitem.replaceChild(tmpElem, oldImg);\n\t\t}\n\t }\n\t else {\n\t\tif ((cn != undefined) && cn.includes(\"nofavicon\")) { // Change type from <div> to <img> if it was a nofavicon\n\t\t let tmpElem = document.createElement(\"img\"); // Assuming it is an HTMLImageElement\n\t\t tmpElem.classList.add(\"favicon\");\n\t\t tmpElem.draggable = false; // True by default for <img>\n\t\t tmpElem.src = uri;\n\t\t bkmkitem.replaceChild(tmpElem, oldImg);\n\t\t}\n\t\telse {\n\t\t oldImg.src = uri;\n\t\t}\n\t }\n\t}\n }\n}", "function removeStar() {\n $('.fa-star').last().attr('class', 'fa fa-star-o');\n numStars--;\n}", "function toggleFavorite(evt) {\n console.debug(\"toggleFavorite\",evt);\n let $storyId = $(evt.target).closest('li').attr('id');\n let story = findStory($storyId);\n \n // Adds or removes story from favorites based on inclusion in favorites list\n if (!checkFavorite(story)) {\n currentUser.addFavorite(story);\n $(evt.target).addClass(\"fas\").removeClass(\"far\");\n }\n else {\n currentUser.removeFavorite(story);\n $(evt.target).addClass(\"far\").removeClass(\"fas\");\n }\n}", "function navFavoritesClick(evt) {\n evt.preventDefault();\n console.debug(\"navFavoritesClick\", evt);\n putFavoritesListOnPage();\n}", "function favSeries(ev) {\n const serieToInclude = series.find((name) => name.show.id == ev.currentTarget.id);\n const id = serieToInclude.show.id;\n\n let favArray = getFavInd();\n\n if (favArray.indexOf(parseInt(id)) == -1) {\n seriesFav.push(serieToInclude);\n ev.currentTarget.classList.add('alreadyFav');\n\n const favContainer = document.querySelector('.fav__container');\n const containerAddedToFav = paintSerie(serieToInclude, id, favContainer, 'eachSerieFav__container', false, 'resultFavTitle');\n containerAddedToFav.addEventListener('click', removeFav);\n localStorage.removeItem('favSeries');\n if (seriesFav.length > 0) {\n setLocalStorage(seriesFav);\n }\n } else {\n removeFavFromResult(ev.currentTarget.id);\n }\n}", "function myTnInit( $e, item, GOMidx ) {\n var st='position:absolute;top:50%;left:50%;padding:10px;'\n $e.find('.nGY2GThumbnailSub').append('<button style=\"'+st+'\" type=\"button\" class=\"ngy2info\" data-ngy2action=\"info\">photo info</button>');\n TnSetFavorite( item);\n}", "function fav(savediv, parentdiv) {\n\tposition = favlist.indexOf(parentdiv);\n\tif (! ~position ){\n\t\tfavlist.push(parentdiv);\n\t\tvar cookie = \"\"\n\t\tfor (i = 0; i < favlist.length; ++i) {\n\t\t\tvar box = favlist[i]\n\t\t\tcookie = cookie + basename(box.getElementsByTagName(\"audio\")[0].src) + \",\";\n\t\t}\n\t\tcookie = cookie.slice(0,-1);\n\t\tsetCookie(\"favlist\", cookie, 2);\n\t\tsavediv.style.color = \"green\";\n\t}\n\telse{\n\t\tfavlist.splice(position, 1);\n\t\tvar cookie = \"\"\n\t\tfor (i = 0; i < favlist.length; ++i) {\n\t\t\tvar box = favlist[i]\n\t\t\tcookie = cookie + basename(box.getElementsByTagName(\"audio\")[0].src) + \",\";\n\t\t}\n\t\tcookie = cookie.slice(0,-1);\n\t\tsetCookie(\"favlist\", cookie, 2);\n\t\tsavediv.style.color = \"black\";\n\t}\n}", "function positionFavToolTip(tipdiv, icon) {\n var likeSym = icon.attr('src');\n if (likeSym.indexOf('Yellow') === -1) {\n tipdiv[0].innerHTML = 'Unmark Favorite';\n }\n icon.on('mouseover', function () {\n var pos = $(this).offset();\n var left = pos.left - 128 + 'px'; // width of tip is 120px\n var top = pos.top + 'px';\n tipdiv[0].style.top = top;\n tipdiv[0].style.left = left;\n tipdiv[0].style.display = 'block';\n });\n icon.on('mouseout', function () {\n tipdiv[0].style.display = 'none';\n });\n return;\n}", "function displayIcon()\n\t{\n\t\tif( lastUrl != document.location.href )\n\t\t\tchrome.extension.sendMessage(\"displayIcon\");\n\n\t\tlastUrl = document.location.href;\n\n\t\tsetTimeout( displayIcon, 1000 );\n\t}", "function menuRefreshFav (BN_id) {\n let BN = curBNList[BN_id];\n\n // Trigger asynchronous favicon retrieval process\n let url = BN.url;\n if ((url != undefined)\n\t && !url.startsWith(\"file:\")\t // file: has no favicon => no fetch\n\t && !url.startsWith(\"about:\")) { // about: is protected - security error .. => no fetch\n \t// This is a bookmark, so here no need for cloneBN(), there is no tree below\n// faviconWorker.postMessage([\"get2\", BN_id, url, options.enableCookies]);\n\tlet postMsg = [\"get2\", BN_id, url, options.enableCookies];\n\tif (backgroundPage == undefined) {\n\t sendAddonMsgGetFavicon(postMsg);\n\t}\n\telse {\n\t backgroundPage.faviconWorkerPostMessage({data: postMsg});\n\t}\n }\n}", "function addFavorites(event) {\n const listItems = document.querySelectorAll('.list__item');\n console.log('list items', listItems);\n const imgs = document.querySelectorAll('.series__image');\n const titles = document.querySelectorAll('.series__title');\n const ides = document.querySelectorAll('span');\n const popcornimg = document.querySelectorAll('.popcorn');\n console.log('current', event.currentTarget);\n console.log('target', event.target);\n for (let i = 0; i < listItems.length; i++) {\n if (event.target === listItems[i] || event.target === imgs[i] || event.target === titles[i]) {\n listItems[i].classList.toggle('favorite');\n popcornimg[i].classList.toggle('hide-pop');\n if (listItems[i].classList.contains('favorite')) {\n seriesFav.push(titles[i].innerHTML);\n localStorage.setItem('favorites', JSON.stringify(seriesFav));\n } else {\n for (let j = 0; j < seriesFav.length; j++) {\n if (titles[i].innerHTML === seriesFav[j]) {\n seriesFav.splice(j, 1);\n localStorage.setItem('favorites', JSON.stringify(seriesFav));\n }\n }\n }\n }\n }\n}", "function auxClicked(ev) {\n clicked(ev, dificuldade, score);\n }", "function getFavourite(){\r\n\t//\r\n}" ]
[ "0.7102287", "0.6714305", "0.6602222", "0.6367555", "0.6350983", "0.62708914", "0.6232233", "0.6224489", "0.6218182", "0.6196483", "0.6137929", "0.6106638", "0.6079774", "0.60511374", "0.6044465", "0.6037493", "0.59577394", "0.5939137", "0.5910749", "0.5891274", "0.58740234", "0.58581007", "0.5848021", "0.5844869", "0.5818811", "0.58018106", "0.5801085", "0.57983345", "0.5795874", "0.5794626", "0.5787623", "0.5779314", "0.5775211", "0.57726973", "0.57545644", "0.57492536", "0.57468534", "0.5717686", "0.5716109", "0.5710955", "0.57003367", "0.5691052", "0.5680599", "0.56641906", "0.56630397", "0.5653637", "0.5638164", "0.56315756", "0.5629007", "0.5615991", "0.56075954", "0.5572351", "0.5564816", "0.55631036", "0.55565697", "0.555204", "0.5551373", "0.5539499", "0.5535735", "0.55353314", "0.5521485", "0.55213624", "0.5519954", "0.55192614", "0.5509778", "0.55087495", "0.5506629", "0.55054593", "0.5503142", "0.54953253", "0.54936755", "0.54910666", "0.54900146", "0.5485556", "0.5485043", "0.5480804", "0.5479671", "0.54723537", "0.54708326", "0.54706216", "0.5465083", "0.5456587", "0.54386926", "0.54342157", "0.5434212", "0.54261017", "0.54252434", "0.54239106", "0.5421968", "0.5415908", "0.5412292", "0.54104924", "0.54038525", "0.54001075", "0.53949386", "0.5393281", "0.53929377", "0.53918886", "0.5389903", "0.53841984", "0.53804" ]
0.0
-1
randomly selects a track
function getRandomInt(max) { return Math.floor(Math.random() * Math.floor(max)); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function randomIndex(){\n let last_index = audio_utility.index_curr_track;\n let current_index = getRandomIntInclusive(0, audio_utility.track_list_length-1);\n while(last_index == current_index){\n current_index = getRandomIntInclusive(0, audio_utility.track_list_length-1);\n }\n audio_utility.index_curr_track = current_index;\n}", "function selectTrack() {\n\t\t// get selected track\n\t\tvar selection = list.getSelection();\n\t\tvar trackURI = selection.uris;\n\t\t\n\t\t// display track info\n\t\t$(\"#trackName\")\n\t\t\t.empty()\n\t\t\t.append(trackURI[0]);\n\n\t\t// pull track rating from DB\n\t\tvar request = {};\n\t\trequest[\"TrackURI\"] = trackURI[0];\n\t\t\n\t\tvar requestBuilder = new SpotifyRequestBuilder();\n\t\trequestBuilder.postRequest(common.getTrackRatingURL, onGetTrackRating, JSON.stringify(request));\n\t}", "function chooseSongNumber() {\n songNumber = Math.floor(Math.random() * songArray.length)}", "selectRandom() {\n const index = Math.floor(Math.random() * 6) + 1;\n const { id } = self.data[index];\n self.selectClub(id);\n }", "function selectRandomly(/* TODO parameter(s) go here */) {\n // TODO complete this function\n}", "playRandom()\n\t{\n\t\tif(this.currentPlaylist)\n\t\t\tthis.play(this.currentPlaylist[Math.floor(Math.random() * this.currentPlaylist.length)]);\n\t\telse\n\t\t\tthis.play(Math.floor(Math.random() * this.tracks.length));\n\t}", "selectRand() {\n\t}", "function chooseTrack(track) {\n setPlayingTrack(track)\n }", "playRandom(){\n this.request(this.routes.randomTrack, this.play);\n }", "selectRandomText()\n {\n const textes = this.state.textes; \n this.setState({selectedText: textes[Math.floor(Math.random() * textes.length)]});\n this.setState({currentAudioUrl: null});\n }", "function NextTrack() {\n /*currentSong++;\n if( currentSong == $( \"#playlist li a\" ).length ) {\n currentSong = 0;\n }*/\n\n var listLength = $( \"#playlist li a\" ).length\n var randomTrack = Math.floor( Math.random() * listLength );\n var currentSong = randomTrack\n\n return currentSong\n}", "function playMusic(){\n var songIndex = Math.floor(Math.random()*songs.length);\n songSelect = window.songs[Math.floor(Math.random()*songs.length)];\n var sound = soundManager.createSound({\n id: songSelect.filename,\n url: songSelect.url\n });\n//a function that will play the song on the click of a button an the play icon\n sound.play();\n\n for (var i = 0; i < buttons.length; i++) {\n\n buttons[i].innerHTML=songSelect.answers[i].answer;\n \n \n \n }\n}", "function selectStories(collection) {\n storyArray = collection;\n for (let i = 0; i < 10; i++) {\n random = Math.floor(Math.random() * (storyArray.length - 1));\n selectedStories.push(storyArray[random]);\n storyArray.splice(random, 1)\n }\n startRound();\n}", "function nextRandomMusic(){ \n\t\n\tvar siguiente = Math.floor(Math.random() * canciones.length)// random number\n\t\n\tremoveActive()\n\tvar item=document.getElementById(siguiente)\n\titem.classList.add(\"active\");\n\tloadMusic(canciones[siguiente]);\n\tplayer.play()\n\tindiceActual[0] = siguiente\n\treproduccionActual(\"Playing: \"+ canciones[siguiente])\n\tclassIconPlay()\n}", "playF() {\n const randNum = Math.floor(Math.random() * this.soundList.length);\n\n console.log(randNum);\n this.__audio.src = this.soundList[randNum];\n this.__audio.play();\n }", "function pickAnswer(){//pick counrty from array\r\n var index=Math.floor(Math.random()*country.length);\r\n return country[index];\r\n}", "static selectRandomPlayer() {\n let newTeamPlayers = Character.instances.filter((player) => {\n player.state != LOSER;\n });\n return newTeamPlayers.sort(() => Math.random() - 0.5);\n }", "handlePick() {\n const randomNumber = Math.floor(Math.random() * this.state.options.length);\n const option = this.state.options[randomNumber];\n }", "function nextSong(){\n let selected;\n if(!state.randomize){\n state.counter++;\n state.counter >= musicArray.length ?\n state.counter=0:\"\";\n selected=state.counter;\n}\nelse if(state.randomize){\n randomNumber();\n selected=state.random;\n}\n chooseNextSong(selected);\n classNameAdd(zplayerPlayerNextBtn,\"clickEffect\");\n classNameRemove(zplayerPlayerNextBtn,\"clickEffect\",300);\n}", "function selectShape() {\n instrumentMode = 2 // we are in track_mode!\n selectedShape = maxNumShapes;\n //if you press for 2 seconds you create a new track\n if(instrumentMode != 0){\n myTimeout = setTimeout(function() {\n maxNumShapes = maxNumShapes + 1;\n updateArrays();\n }, 2000);\n}\n}", "function RandomPick() {\r\n // Randomly select one colour and return it back\r\n var picks = [\"Red\", \"Green\", \"Yellow\", \"Blue\"];\r\n return picks[Math.floor(Math.random()*picks.length)];\r\n}", "function playRandomSound() {\n var index = Math.round(Math.random() * (sounds.length - 1));\n sounds[index].play();\n}", "function getNewChord() {\r\n if (started) {\r\n // Line below selects random\r\n var newChord = chordList[Math.floor(Math.random() * chordList.length)];\r\n while (newChord == ans) {\r\n newChord = chordList[Math.floor(Math.random() * chordList.length)];\r\n }\r\n ans = newChord;\r\n guessed = false;\r\n changeTrainerTitle(\"Guess!\");\r\n play(ans);\r\n }\r\n}", "function chooseRandom(){\n const choices = ['rock', 'paper', 'scissors']\n return choices[Math.floor(Math.random()*3)]\n}", "function pickRandomChoice(){\n return choices[Math.floor(Math.random() * choices.length)];\n}", "async likeTrack() {\n let prevSeedTracks = this.state.seedTracks;\n prevSeedTracks.push(this.state.selectedTrack);\n if (prevSeedTracks.length > 4) prevSeedTracks.shift(); //Remove oldest seed element\n await this.setState({\n seedTracks: prevSeedTracks,\n });\n await this.findNewTracks();\n }", "function play_random() {\n\tisQuiz = true;\n\tbigPic.innerHTML = \"What animal name did I just say in Chinese?\";\n\trandomAudio.pause();\n\trandomNum = loadrandom();\n\tmyelement = customArray[randomNum];\n\trandomAudio = myelement.chinRec;\n\trandomAudio.play();\n\trandomID = myelement;\n\tchinCharDiv.style.display = \"block\";\n\tchinCharPic.src = myelement.chinChar.src;\n}", "function playRandomSample() {\r\n // 1) clear beatArray\r\n beatArray = [];\r\n // 2) fill beatArray with 5 radnom numbers\r\n for (var i_1 = 0; i_1 < 5; i_1++) {\r\n var randomNum = Math.floor(Math.random() * 9);\r\n // fill beatarray with random number\r\n beatArray.push(randomNum);\r\n }\r\n // 3) play beatsArray\r\n boolPlayStop = true;\r\n checkBeat();\r\n // 4) show stop button\r\n toggleClasses(playButton, stopButton);\r\n}", "function playNextShuffled() {\n\n\t\tif (plsShuffledIndex < (plsShuffled.length - 1)) {\n\t\t\tplsShuffledIndex += 1;\n\t\t\tplay(plsShuffled[plsShuffledIndex]);\n\t\t} else {\n\t\t\tif (isContinuous) {\n\t\t\t\tsetPlsShuffled();\n\t\t\t\tplay(plsShuffled[0]);\n\t\t\t} else {\n\t\t\t\tif (Amplitude.getSongPlayedPercentage() === 100) {\n\t\t\t\t\tcurTrack.classList.remove('selected');\n\t\t\t\t\tfirePlayEnd();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}", "function computerSelected() {\n computerGuess = computerChoices[Math.floor(Math.random() * computerChoices.length)];\n}", "selectRand(length = 1) {\n\t}", "function computerPlay () {\n var computerChoice = options[Math.floor(Math.random()*options.length)];\n return computerChoice;\n }", "function prevRandomMusic(){ \n\n\tvar siguiente = Math.floor(Math.random() * canciones.length)// random number\n\n\t\n\tremoveActive()\n\tvar item=document.getElementById(anterior)\n\titem.classList.add(\"active\");\n\tloadMusic(canciones[anterior]);\n\tplayer.play()\n\tindiceActual[0]= anterior\n\treproduccionActual(\"Reproduciendo: \"+ canciones[anterior])\n\tclassIconPlay()\n}", "function winSound (){\n if (win==true){\n let what= Math.floor(Math.random() * 3);\n var victory = new Howl({src:winSounds[what]});\n victory.play();\n }\n}", "function choose(options) {\n return options[Math.floor(Math.random() * options.length)];\n}", "function selectionChange(){\n var selected = document.getElementById(\"trackSelect\").value;\n document.getElementById(\"aud-source\").setAttribute(\"src\", \"./mp3/\"+selected);\n document.getElementById(\"playBtn\").disabled = false;\n document.getElementById(\"pauseBtn\").disabled = false;\n document.getElementById(\"stopBtn\").disabled = false;\n document.getElementById(\"tracktime\").style.visibility = \"visible\";\n document.getElementById(\"submit\").disabled = false;\n if (!returningTrack)\n play();\n}", "playRandomBgMusic() {\n this.bgmusic[Math.floor(Math.random() * this.bgmusic.length)].play();\n }", "handlePick() {\n const randomNum = Math.floor(Math.random() * this.state.options.length);\n const option = this.state.options[randomNum];\n alert(option);\n }", "function selectTweet(tweets) {\n const index = Math.floor(Math.random() * tweets.length)\n return tweets[index];\n}", "function randomizeSelection(length) {\n return Math.floor(Math.random() * length);\n}", "function playRandomLocalMedia() {\n playLocalMedia(audioElement, Global.SOUNDS[Helper.getRandomInt(0, Global.SOUNDS.length)]);\n }", "function toggleShuffle(albums, numberOfAlbums) {\n var selectedAlbum = albums[Math.floor((Math.random() * numberOfAlbums) + 1)]; // Get random album\n updatePlayer(selectedAlbum.getAttribute(\"data-path\"), selectedAlbum.getAttribute(\"data-title\"), selectedAlbum.getAttribute(\"data-cover\"));\n audioPlayer.play();\n playToggle.addClass(\"btn__play--enabled\");\n}", "function playRandom() {\n var musicList = document.getElementsByClassName('play_this');\n \n var rand = Math.floor(Math.random() * musicList.length);\n \n while (player.getAttribute('src')\n && player.getAttribute('src') === musicList[rand].parentNode.parentNode.getAttribute('data-mpeg')) {\n rand = Math.floor(Math.random() * musicList.length);\n }\n \n setPlayerInfo(musicList[rand].parentNode.parentNode);\n playItem(musicList[rand].parentNode.parentNode);\n}", "function randomSFX() {\r\n\tvar audioType = Math.floor(Math.random() * sfxSounds.length);\r\n\tsfxSounds[audioType].play();\r\n\tsfxSounds[audioType].currentTime = 0;\r\n}", "function randomStatSound() {\r\n\t//take a random value within the array's length and round it down to a valid index\r\n\tvar audioType = Math.floor(Math.random() * statSounds.length);\r\n\t//only call the array once\r\n\tsfxElem = statSounds[audioType];\r\n\tsfxElem.play();\r\n\tsfxElem.currentTime = 0;\r\n}", "function scissorsPlayer() {\n\tplayChoice=3;\n\trandomNumber();\n}", "function crystalsRandomSel() {\n var C = Math.floor(Math.random() * 12) + 1;\n return C;\n }", "function chooseTrack() {\n var id = this.value;\n // entities have the same id as the track in the db. zooms to the corresponding entity\n viewer.zoomTo(viewer.entities.getById(id));\n // iterates over tracklist to find the element with the correct id and saves to elem\n var elem;\n for (var i=0; i<tracklist.length; i++) {\n if (tracklist[i].ID == id) {\n elem = tracklist[i];\n }\n }\n // gets the elements properties and displays them in table\n document.getElementById(\"length\").innerHTML = elem.laenge;\n document.getElementById(\"description\").innerHTML = elem.desc;\n document.getElementById(\"difficulty\").innerHTML = elem.difficulty;\n document.getElementById(\"start\").innerHTML = elem.start;\n\n }", "chooseNextChaser() {\n if (this.idsLeft === undefined) {\n this.idsLeft = this.players.map((p) => p.id);\n }\n return this.idsLeft.pop(Math.floor(Math.random()*this.idsLeft.length));\n }", "function houseSelection() {\n return choice[Math.floor(Math.random() * choice.length)];\n}", "function paperPlayer() {\n\tplayChoice=2;\n\trandomNumber();\n}", "function computerPlay() {\n return choices[Math.floor(Math.random() * choices.length)];\n }", "function randomiseCue(selection) {\n let cue = {\n index: [],\n image: \"\"\n };\n \n \n \n let cueSeq = [];\n let cueIndex = [];\n \n if (selection == 1){\n if (trial.cue1.length == undefined){ // If there's only one possible outcome (same below)\n cueIndex = 0;\n } else {\n for(let i = 0; i < trial.cue1.length; i++) { cueSeq.push(i); }\n cueIndex = jsPsych.randomization.sampleWithReplacement(cueSeq, 1, trial.cueProbs1);\n \n }\n cue.image = trial.cue1[cueIndex];\n } else if (selection == 2){\n if (trial.cue2.length == undefined){\n cueIndex = 0;\n } else {\n for(let i = 0; i < trial.cue2.length; i++) { cueSeq.push(i); }\n cueIndex = jsPsych.randomization.sampleWithReplacement(cueSeq, 1, trial.cueProbs2);\n \n }\n cue.image = trial.cue2[cueIndex];\n }\n \n cue.index = cueIndex;\n \n return(cue)\n }", "function newRound() {\n currentClue = random(clues);\n responsiveVoice.speak(currentClue);\n timer = 30 * 60;\n}", "function random(){\n var possibleShot = Math.floor(Math.random() * 9);\n if(!allShots.includes(String(possibleShot))){\n currentShot = possibleShot;\n } else {\n random();\n } \n }", "function computerPlay() {\r\n let rockPaperScissors = [\"rock\", \"paper\", \"scissors\"];\r\n computerSelection = rockPaperScissors[Math.floor(Math.random()*3)];\r\n return computerSelection;\r\n}", "function nextSeguence(){\r\n levelNumber++;\r\n $(\"h1\").text(\"Level \" + levelNumber);\r\n var randomNumber = Math.round(Math.random()*3);\r\n var randomChosenColor = buttonColors[randomNumber];\r\n gamePattern.push(randomChosenColor);\r\n $(\".\" + randomChosenColor).fadeOut(100).fadeIn(100);\r\n playSound(randomChosenColor);\r\n}", "function sample(set) {\r\n return (set[Math.floor(Math.random() * set.length)]);\r\n}", "randomPicker(quotArr) {\n return Math.floor(Math.random() * quotArr.length);\n }", "function selectedCountry() {\n chosenCountry = countries[Math.floor(Math.random() * countries.length)];\n return chosenCountry;\n}", "function selectquest(){\n numberTaken = (Math.floor((Math.random() * questlength) + 1));\n if(arrUsedBefore.length-1 == questlength){restartUsed();}\n for(var x = 0; x <= arrUsedBefore.length-1; x++){\n if(numberTaken == arrUsedBefore[x] || numberTaken == lastUsed)\n {\n wasUsed++;\n }\n }\n if(wasUsed > 0){\n wasUsed = 0;\n tryRandom();\n }\n else{\n wasUsed = 0;\n printQuest();\n }\n }", "function computerPlay(){\n return choices[Math.floor(Math.random() * 3)];\n}", "function computerPlay() {\n computerSelection = availablePlays[Math.floor(Math.random()*availablePlays.length)];\n console.log(computerSelection);\n return computerSelection;\n }", "function speak() {\n const number = Math.floor(Math.random()*8);\n const audio = new Audio(magicVoiceArray[number]);\n \n audio.play();\n \n }", "function grabRandomSlide() {\n var temp = Math.floor(Math.random() * ((slides.length-1)+ 1));\n if (temp != currentSlide) {\n currentSlide = temp;\n } else {\n grabRandomSlide();\n }\n }", "function pickE(){\n\tchosenE = allE.splice(Math.floor(allE.length * Math.random()), 1)[0]; /*splice returns an array with the selected contents so we need the '[0]' at the end to set the variable to the actual object*/\n}", "function nextSequence() {\r\n var randomNumber = Math.floor(Math.random() * 4);\r\n var randomChosenColour = buttonColours[randomNumber];\r\n var colourSound = new Audio(\"sounds/\" + randomChosenColour + \".mp3\");\r\n\r\n gamePattern.push(randomChosenColour);\r\n playSound(colourSound);\r\n $(\"#\" + randomChosenColour).fadeOut(100).fadeIn(100);\r\n level++;\r\n $(\"#level-title\").text(\"Level \" + level);\r\n}", "function computerPlay() {\n return gameMoveSelection[getRandomIndex(gameMoveSelection.length)];\n}", "function choose(choices) {\n var index = Math.floor(Math.random() * choices.length);\n return choices[index];\n}", "function selector (min,max) {\n return min + (Math.floor(Math.random() * max));\n }", "function choose(choices) {\n var index = Math.floor(Math.random() * choices.length);\n return choices[index];\n}", "function select_player(){\n \t\t//Right now just drafts the last player available, probably fine but could be based on rank or user preference\n \t\t//Figure out how to randomize that\n \t\t\n \t\tplayer_id = $('input:radio[name=player_id]').last().val()\n \t\t$.post('/bizarro/draft/{{draft_id}}/', {'player_id':player_id})\n \t\t}", "function randomateSurvPerks() {\n \n // Shuffles the array and returns it\n var Survshuffled = SurvImgSrc.sort(function () {\n return .5 - Math.random()\n });\n // Select the first 4 in the new array \n var Survselected = Survshuffled.slice(0, 4);\n\n // Puts the first 4 in slots made in html.\n document.getElementById(\"perkslotone\").innerHTML = Survselected[0];\n document.getElementById(\"perkslottwo\").innerHTML = Survselected[1];\n document.getElementById(\"perkslotthree\").innerHTML = Survselected[2];\n document.getElementById(\"perkslotfour\").innerHTML = Survselected[3];\n\n}", "function randItem(selectedArray) {\n return selectedArray[Math.floor(Math.random()*selectedArray.length)];\n}", "function botChoice(){\n\tMath.floor((Math.random() * 3) + 1);\n\tif \n}", "function computerplay() {\n var Computer = Math.floor(Math.random()*optionsarray.length);\n return optionsarray[Computer];\n}", "function random(list) {\n\n var randNum = Math.random() * list.length;\n randNum = Math.floor(randNum);\n console.log(randNum);\n name = list[randNum];\n list.splice(randNum, 1);\n\n chooseOption(name, randNum);\n}", "play(view){\n\n\t\tvar possible_moves = view.getMoves();\n\t\tvar max = possible_moves.length;\n\t\tvar i = Math.floor(Math.random() * max);\n\t\treturn possible_moves[i].toString();\n\t}", "function rockPlayer() {\n\tplayChoice=1;\n\trandomNumber();\n}", "function selectRandom(cards){\n // we need an integer in [0,cards.length]\n index=Math.floor(Math.random()*cards.length); // multiply by cards.length and floor\n return cards[index]; // return card at that index\n}", "function pickSong() {\n chooseSongNumber();\n currentSong = songArray[songNumber];\n console.log(currentSong);\n}", "function computerPlay() {\n return choices[Math.floor(Math.random() * choices.length)];\n}", "function nextSong(){\n var audio=document.querySelector('audio');\n // console.log(audio.duration);\n var len=songs.length;\n\n if (willShuffle == 1) {\n var nextSongNumber = randomExcluded(1,len,currentSongNumber); // Calling our function for random selection\n var nextSongObj = songs[nextSongNumber-1];\n songIndex(nextSongObj,audio);\n currentSongNumber = nextSongNumber;\n }\n\n else if(currentSongNumber < len) {\n for(var i=0;i<len;i++){\n if(audio.src.search(songs[i].fileName)!=-1)\n break;\n }\n currentSongNumber=i+1;\n if(currentSongNumber < len){\n var nextSongObj = songs[currentSongNumber];\n songIndex(nextSongObj,audio);\n }\n\n else if(willLoop == 1) {\n var nextSongObj = songs[0];\n songIndex(nextSongObj,audio);\n currentSongNumber = 1;\n }\n\n else {\n currentSongNumber=len-1;\n lastSongClick(audio);\n }\n }\n\n else {\n lastSongClick(audio);\n }\n}", "function playRandomVideo() {\n var $urls = $('[href^=\"/watch\"]');\n var i = Math.floor(Math.random() * $urls.length);\n\n var href = $urls[Math.floor(Math.random() * $urls.length)].href;\n var id = /[?&]v=([^&]+)(?:&|$)/.exec(href)[1];\n\n starting = true;\n\n player.loadVideoById(id);\n }", "function playback() {\n let randomNote = allNotesArray[Math.floor(Math.random() * allNotesArray.length)];\n const playSound = ctx.createBufferSource();\n playSound.buffer = randomNote;\n playSound.connect(ctx.destination);\n playSound.start(ctx.currentTime);\n randomNoteIndex = allNotesArray.indexOf(randomNote);\n console.log(randomNoteIndex);\n}", "function randomCover() {\n let num = Math.floor( Math.random() * covers.length );\n let img = covers[ num ];\n return img;\n}", "function computerPlay() {\n let computerSelection = inputOption[Math.floor(Math.random() * inputOption.length)];\n return(computerSelection)\n}", "function randomNumber() {\n pick = Math.floor(Math.random() * parkList.length);\n}", "function computerPlay() {\n var randomNum = getRandomInt(0, 2);\n var choices = [\"Rock\", \"Paper\", \"Scissors\"];\n \n computerChoice = choices[randomNum];\n}", "function selectPassage()\n{\n\tvar randIndex = Math.floor(Math.random() * 4);\n\n\tselectedPassageTitle = passages[randIndex][0];\n\tselectedPassageText = passages[randIndex][1];\n\n\tconsole.log(selectedPassageTitle + \"\\n\\n\" + selectedPassageText);\n\n}", "function get_song_to_play() {\n var track = null;\n\n var last_toprank_i = -1;\n for (var i = 0; i < tracks.length &&\n parseInt(tracks[i]['@attr'].rank) <= FIRST_RANKS_TO_PLAY;\n i++) {\n last_toprank_i++;\n }\n\n // play random one of the top songs if we can\n if (last_toprank_i > -1) {\n track = tracks.splice(getRandomInt(0, last_toprank_i + 1), 1)[0];\n } else {\n track = tracks.splice(getRandomInt(0, tracks.length), 1)[0];\n }\n played.push(track);\n\n if (tracks.length == 0) {\n tracks = played;\n played = [];\n }\n\n return track;\n}", "function computerPlay() {\n let computerTurnOptions = [\"ROCK\", \"PAPER\", \"SCISSORS\"]; \n function getRandom(min, max) {\n return Math.random() * (max - min) + min;\n } \n let randomNumber = Math.floor(getRandom(3,0)); \n return computerTurnOptions[randomNumber]; \n}", "function playNote() {\n // Pick a random frequency from the array\n let frequency = frequencies[Math.floor(Math.random() * frequencies.length)];\n // Set the synth's frequency\n synth.frequency = frequency;\n // If it's note already play, play the synth\n synth.play();\n}", "function computerPlay(){\n\tlet choiceList = ['rock', 'paper', 'scissors'];\n\tlet choiceSelected = Math.floor(Math.random() * 3);\n\treturn choiceList[choiceSelected];\n}", "function computerPlay() {\n\treturn Math.floor(Math.random() * 3) + 1;\n}", "function getRandomOption() {\n\treturn Math.floor(Math.random() * (12 - 1)) + 1;\n}", "function random() {\r\n\t//creates random number and pushes it to the playList for game use\r\n\tplayList.push(Math.floor(Math.random() * 4));\r\n}", "function pick() {\r\n index = Math.floor(Math.random() * words.length);\r\n return words[index];\r\n}", "function nextSequence() {\n $(\"#level-title\").text(`Level ${++level}`);\n var randomNum = Math.floor(Math.random() * 4);\n var randomChosenColor = choiceArray[randomNum];\n simonArray.push(randomChosenColor);\n $(`#${randomChosenColor}`).fadeOut(100).fadeIn(100);\n playSound(randomChosenColor);\n}", "function previousSong(){\n let selected;\nif(!state.randomize){\n state.counter--;\n state.counter < 0?\n state.counter=musicArray.length-1:\"\";\n selected=state.counter;\n}\nelse if(state.randomize){\n randomNumber();\n selected=state.random;\n}\n chooseNextSong(selected);\n classNameAdd(zplayerPlayerPrevBtn,\"clickEffect\");\n classNameRemove(zplayerPlayerPrevBtn,\"clickEffect\",300);\n}", "function playRandomNote() {\r\n playSound(newFreq);\r\n}" ]
[ "0.6862653", "0.6634456", "0.66009253", "0.6591241", "0.64826614", "0.6460763", "0.6450181", "0.6431804", "0.6314623", "0.6257871", "0.6173092", "0.613817", "0.61357975", "0.6086945", "0.6075537", "0.6050641", "0.6042523", "0.6033984", "0.60284376", "0.60029864", "0.5989513", "0.59789795", "0.5960563", "0.5959778", "0.59527093", "0.59440124", "0.59323573", "0.5930847", "0.5929371", "0.59259546", "0.5905354", "0.5901878", "0.5889318", "0.5886339", "0.5884084", "0.58827907", "0.5874841", "0.587289", "0.5870908", "0.5869227", "0.5864559", "0.5861888", "0.5852186", "0.5845584", "0.5840954", "0.583012", "0.5805632", "0.5794091", "0.578904", "0.5780891", "0.5776298", "0.5764205", "0.5751967", "0.5744873", "0.57372224", "0.57363445", "0.5732367", "0.5730712", "0.5722842", "0.57186884", "0.5716271", "0.5716201", "0.57153", "0.5714181", "0.57096905", "0.5705384", "0.57038295", "0.5685279", "0.56824803", "0.5681797", "0.56785536", "0.56689316", "0.5661364", "0.5661175", "0.5659428", "0.5659094", "0.5655233", "0.5652744", "0.564787", "0.56454563", "0.56291837", "0.562757", "0.5617611", "0.5616878", "0.56168133", "0.5615223", "0.56105494", "0.5609943", "0.5608294", "0.5603586", "0.56016105", "0.5596853", "0.5595446", "0.5595411", "0.5588541", "0.55879337", "0.5582921", "0.5582538", "0.5579483", "0.55782354", "0.5577657" ]
0.0
-1
reorganizes musicArray to prevent song repetitions
function preventRepeatingSong() { let currentVideo = player.getVideoUrl(); let currentVideoId = currentVideo.slice(currentVideo.indexOf("v="),currentVideo.length); currentVideoId = currentVideoId.slice(2, currentVideoId.length); musicArray.splice(musicArray.indexOf(currentVideoId), 1); musicArray.push(currentVideoId); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function amplitude_shuffle_songs(){\n var amplitude_nodes = document.getElementById('amplitude-playlist').getElementsByTagName('audio');\n amplitude_shuffle_playlist_temp = new Array(amplitude_nodes.length);\n for (i=0; i<amplitude_nodes.length; i++) {\n amplitude_shuffle_playlist_temp[i] = amplitude_nodes[i].getAttribute(\"id\");\n }\n for (i = amplitude_nodes.length - 1; i > 0; i--){\n var amplitude_rand_num = Math.floor((Math.random()*i)+1);\n amplitude_shuffle_swap(amplitude_shuffle_playlist_temp, i, amplitude_rand_num);\n }\n\n amplitude_shuffle_list = amplitude_shuffle_playlist_temp;\n}", "function shuffleSongs() {\n /*\n\t\t\tBuilds a temporary array with the length of the config.\n\t\t*/\n let shuffleTemp = new Array(config.songs.length);\n\n /*\n\t\t\tSet the temporary array equal to the songs array.\n\t\t*/\n for (let i = 0; i < config.songs.length; i++) {\n shuffleTemp[i] = config.songs[i];\n }\n\n /*\n\t\t\tIterate ove rthe songs and generate random numbers to\n\t\t\tswap the indexes of the shuffle array.\n\t\t*/\n for (let i = config.songs.length - 1; i > 0; i--) {\n let randNum = Math.floor(Math.random() * config.songs.length + 1);\n shuffleSwap(shuffleTemp, i, randNum - 1);\n }\n\n /*\n\t\t\tSet the shuffle list to the shuffle temp.\n\t\t*/\n config.shuffle_list = shuffleTemp;\n }", "function handleArrayBuffer(musicArrayBuffer, currentSong) {\n omniButtonIcon.classList = \"fa fa-cog fa-spin omniButtonIconNoVisualization\"\n\n\n var musicDataView = new DataView(musicArrayBuffer);\n\n var frameCount = 0;\n var tagIndex = 0;\n var sampleCount = 0;\n\n var frameType = mp3Parser.readTags(musicDataView)[0]._section.type;\n\n //Skips any frames at the start that dont contain music data\n var frameType = mp3Parser.readTags(musicDataView)[0]._section.type;\n while (frameType != \"frame\") {\n tagIndex++;\n frameType = mp3Parser.readTags(musicDataView)[tagIndex]._section.type\n }\n var samplingRate = mp3Parser.readTags(musicDataView)[tagIndex].header.samplingRate\n currentSong.samplingRate = samplingRate;\n\n var mp3tags = mp3Parser.readTags(musicDataView)[tagIndex];\n while (true) {\n if (mp3tags._section.type === 'frame') {\n frameCount++;\n sampleCount = sampleCount + mp3tags._section.sampleLength;\n } else {\n //If it doesnt contain music data? TRASH IT!\n musicArrayBuffer.splice(mp3tags._section.nextFrameIndex - mp3tags._section.sampleLength, mp3tags_section.nextFrameIndex);\n }\n mp3tags = mp3Parser.readFrame(musicDataView, mp3tags._section.nextFrameIndex);\n if (mp3tags == null) {\n break;\n }\n }\n //Clear up memory\n musicDataView = null;\n //Put the data into the audiotag\n\n currentSong.musicArrayBuffer = musicArrayBuffer;\n var songBlob = new Blob([musicArrayBuffer], { type: \"audio/mpeg3\" });\n currentSong.songObjectURL = window.URL.createObjectURL(songBlob);\n\n getMusicData(musicArrayBuffer, sampleCount, samplingRate, currentSong);\n songs.push(currentSong);\n\n //Clear up memory\n musicArrayBuffer = null;\n\n}", "refresh(song, action) {\n\t\tvar newArr = this.state.next_song\n\t\tif(action) {\n\t\t\tnewArr.push(song.tracks[0])\n\t\t} else {\n\t\t\tvar index = newArr.map((song) => song.id).indexOf(song.tracks[0].id)\n\t\t\tif(index > -1) {\n\t\t\t\tnewArr.splice(index, 1)\n\t\t\t}\n\t\t}\n\t\tthis.setState({\n\t\t\tnext_song: newArr\n\t\t})\n\t}", "function prevMusic() {\n musicIndex--;\n musicIndex < 1 ? (musicIndex = allMusic.length) : (musicIndex = musicIndex);\n loadMusic(musicIndex);\n playMusic();\n playingNow();\n}", "function convertSongsToStations (songsArray){\n\tconst stations={};\n\tsongsArray.map (song => {\n\t\tstations [song.genre] ? stations [song.genre].push (song) : stations [song.genre]= [song];\t\t\n\t})\n\treturn stations;\n}", "async normalizeSongTitles() {\n const docs = await this.db.getDocuments('music');\n const titles = {};\n\n for(let i = 0; i < docs.length; i++) {\n const doc = docs[i];\n const title = utils.beautifySongTitle(doc.title);\n\n if(titles[title] && titles[title] != doc.$loki) {\n await this.db.deleteDocument(doc);\n continue;\n }\n\n doc.title = title;\n titles[title] = doc.$loki;\n await this.db.updateMusicDocument(doc, { beautify: false });\n }\n }", "function groupSounds() {\n\t\n\tvar modifiedSounds = {general:[], audioSprites:[], music: music};\n\tvar usedIndexesGeneral = [];\n\tvar usedIndexesAudioSprites = [];\n\tvar lastIndexGeneral = 0;\n\tvar lastIndexAudioSprites = 0;\n\t\n\tfor (var i = 0; i < rooms.length; i++) {\n\t\tif (rooms[i].group != undefined && rooms[i].group != \"\") {\n\t\t\tvar groupIndex = parseInt(rooms[i].group);\n\t\t\tif (lastIndexGeneral < groupIndex) {\n\t\t\t\tlastIndexGeneral = groupIndex;\n\t\t\t}\n\t\t\tif (lastIndexAudioSprites < groupIndex) {\n\t\t\t\tlastIndexAudioSprites = groupIndex;\n\t\t\t}\n\t\t\tfor (var j = 0; j < sounds.general.length; j++) {\n\t\t\t\tif (sounds.general[j][0] == rooms[i].name) {\n\t\t\t\t\tif (modifiedSounds.general[groupIndex] == undefined) {\n\t\t\t\t\t\tmodifiedSounds.general[groupIndex] = [];\n\t\t\t\t\t}\n\t\t\t\t\tmodifiedSounds.general[groupIndex].push(jQuery.extend(true, [], sounds.general[j]));\n\t\t\t\t\tif (usedIndexesGeneral.indexOf(j) == -1) {\n\t\t\t\t\t\tusedIndexesGeneral.push(j);\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor (var j = 0; j < sounds.audioSprites.length; j++) {\n\t\t\t\tif (sounds.audioSprites[j][0] == rooms[i].name) {\n\t\t\t\t\tif (modifiedSounds.audioSprites[groupIndex] == undefined) {\n\t\t\t\t\t\tmodifiedSounds.audioSprites[groupIndex] = [];\n\t\t\t\t\t}\n\t\t\t\t\tmodifiedSounds.audioSprites[groupIndex].push(jQuery.extend(true, [], sounds.general[j]));\n\t\t\t\t\tif (usedIndexesAudioSprites.indexOf(j) == -1) {\n\t\t\t\t\t\tusedIndexesAudioSprites.push(j);\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t\n\tif (modifiedSounds.general[0] == undefined) {\n\t\tmodifiedSounds.general[0] = [];\n\t}\n\tif (modifiedSounds.audioSprites[0] == undefined) {\n\t\tmodifiedSounds.audioSprites[0] = [];\n\t}\n\tfor (var i = 0; i < sounds.general.length; i++) {\n\t\tif (usedIndexesGeneral.indexOf(i) == -1) {\n\t\t\tmodifiedSounds.general[0].push(jQuery.extend(true, [], sounds.general[i]));\n\t\t}\n\t}\n\tfor (var i = 0; i < sounds.audioSprites.length; i++) {\n\t\tif (usedIndexesAudioSprites.indexOf(i) == -1) {\n\t\t\tmodifiedSounds.audioSprites[0].push(jQuery.extend(true, [], sounds.audioSprites[i]));\n\t\t}\n\t}\n\tfor (var i = 0; i < (lastIndexGeneral+1); i++) {\n\t\tif (modifiedSounds.general[i] == undefined) {\n\t\t\tmodifiedSounds.general[i] = [];\n\t\t}\n\t}\n\tfor (var i = 0; i < (lastIndexAudioSprites+1); i++) {\n\t\tif (modifiedSounds.audioSprites[i] == undefined) {\n\t\t\tmodifiedSounds.audioSprites[i] = [];\n\t\t}\n\t}\n\t\n\treturn modifiedSounds;\n}", "function rotateSongsRandomly(){\r\n\tvar rotations = Math.ceil( songs.length*Math.random() ); //ceiling for a least one rotation\r\n\tfor(var i = 0; i < rotations; i++){\r\n\t\trotateOnce();\r\n\t}\r\n\tsong = songs[0];\r\n\tplayer.src = url + song + \".mp3\";\r\n\t//===| helpers |===\r\n\tfunction rotateOnce(){\r\n\t\tsongs.push(songs.shift());\r\n\t}\r\n}", "function addSongDurations( arr)\n{\n var keys = Object.keys( arr);\n\n for( var i=0; i<keys.length-1; i++) {\n arr[keys[i]] = {duration:parseFloat(keys[i+1])-parseFloat(keys[i])-0.001,file:arr[keys[i]]};\n }\n arr[keys[keys.length-1]] = {duration:null,file:arr[keys[keys.length-1]]};\n}", "function updateMusicArray() {\n let addedVideo = scriptInput.value;\n let addedVideoId = addedVideo.slice(addedVideo.indexOf(\"v=\"),addedVideo.length);\n addedVideoId = addedVideoId.slice(2, addedVideoId.length);\n if (musicArray.includes(addedVideoId)) {\n alert(\"Video is already included in the track-list.\");\n } else {\n musicArray.unshift(addedVideoId);\n document.getElementById(\"musicArrayText\").innerText = musicArray;\n }\n \n}", "function shuffleTracks(linkArr, reorderedLinkArr, access_token) {\n\t$('#text-description')[0].innerHTML = \"Getting Songs...\"\n\tsetTimeout(function() {\n\t\tdeleteLinks(linkArr, reorderedLinkArr, access_token);\n\t}, 100);\n}", "function amplitude_previous_song() {\n if(amplitude_active_song.getAttribute('amplitude-visual-element-id') != ''){\n if(document.getElementById(amplitude_active_song.getAttribute('amplitude-visual-element-id'))){\n document.getElementById(amplitude_active_song.getAttribute('amplitude-visual-element-id')).className = document.getElementById(amplitude_active_song.getAttribute('amplitude-visual-element-id')).className.replace('amplitude-now-playing', '');\n }\n }\n var amplitude_nodes = document.getElementById('amplitude-playlist').getElementsByTagName('audio');\n //If the shuffle is activated, then go to the previous song in the shuffle array. Otherwise go back in the playlist.\n if(amplitude_shuffle){\n for(i=0; i<amplitude_shuffle_list.length; i++){\n if(amplitude_shuffle_list[i] == amplitude_active_song.getAttribute('id')){\n if(typeof amplitude_shuffle_list[i-1] != 'undefined'){\n amplitude_play(amplitude_shuffle_list[i-1]);\n }else{\n amplitude_play(amplitude_shuffle_list[amplitude_shuffle_list.length-1]);\n }\n break;\n }\n }\n }else{\n for (i=0; i<amplitude_nodes.length; i++) {\n if (amplitude_nodes[i].getAttribute(\"id\") == amplitude_active_song.getAttribute('id')) {\n if (typeof amplitude_nodes[i-1] != 'undefined') {\n amplitude_play(amplitude_nodes[i-1].getAttribute(\"id\"));\n }else{\n amplitude_play(amplitude_nodes[amplitude_nodes.length-1].getAttribute(\"id\"));\n }\n break;\n }\n }\n }\n\n amplitude_active_song_information['cover_art'] = amplitude_active_song.getAttribute('amplitude-album-art-url');\n amplitude_active_song_information['artist'] = amplitude_active_song.getAttribute('amplitude-artist');\n amplitude_active_song_information['album'] = amplitude_active_song.getAttribute('amplitude-album');\n amplitude_active_song_information['title'] = amplitude_active_song.getAttribute('amplitude-title');\n\n if(typeof amplitude_config != 'undefined'){\n if(typeof amplitude_config.amplitude_previous_song_callback != 'undefined'){\n var amplitude_previous_song_callback_function = window[amplitude_config.amplitude_previous_song_callback];\n amplitude_previous_song_callback_function();\n }\n }\n}", "function soundSetup(){\n updateState(false, false);\n varSong = [];\n varSongID = [];\n currentVarSongIndex = 0;\n varSongLength = 4;\n mainSong = new Howl({\n src: ['Songs/1_main.mp3'],\n loop:true\n });\n for(var x = 1; x<=varSongLength; x++){\n varSong[x-1] = new Howl({\n src: ['Songs/1_var'+x+'.mp3']\n });\n}\nresetIDs();\n\n}", "function rebuildQuestionsArray() {\n questionsArray = questionsArray.concat(questionsAnswered);\n questionsAnswered = [];\n}", "function arrayInitializer() {\n shuffle(soundArray); // Shuffles the array using helper function which can be located at the bottom of this doc\n let numb = 13;\n for(i = 0; i < soundArray.length; i++) {\n soundArray[i]['pin'] = numb; // Add a pin number to each array entry\n numb--; // Starting the number from 13 (pin) and going down\n }\n updateSong();\n}", "addToLocalStorage() {\n const songsInStorage = localStorage.getItem(\"Songs\");\n let currentArray = [];\n if (songsInStorage) {\n currentArray = JSON.parse(songsInStorage);\n currentArray.unshift(this.props.info);\n currentArray = Array.from(new Set(currentArray));\n localStorage.setItem(\"Songs\", JSON.stringify(currentArray));\n } else {\n currentArray = [];\n currentArray.unshift(this.props.info);\n localStorage.setItem(\"Songs\", JSON.stringify(currentArray));\n }\n }", "addTrack(track) {\n/* if (!this.state.playlistTracks.includes(track)) { // Step 41\n this.setState({playlistTracks: this.state.playlistTracks.splice(this.state.playlistTracks.count,0,track.id)}); //add a track at the end of the playlist\n*/\n if (this.state.playlistTracks.indexOf(track) === -1) {\n const newPlayList = this.state.playlistTracks;\n newPlayList.push(track);\n this.setState({playListTracks: newPlayList})\n // this.setState({playlistTracks: this.state.playlistTracks.push(track)});\n }\n }", "function deduplicteMediaItems() {\n\n}", "playSong(position) {\n let played_song = this.songs[position];\n //return the song information to be played by the player\n //Update to everyone in the room\n\n //if position - this.position > 1, splice from original pos and put\n //into new position right after this.position,\n //go next\n\n if (position - this.position > 1)\n {\n this.songs.splice( position, 1);\n this.songs.splice( this.position + 1, 0 , played_song);\n this.next();\n }\n else if (position - this.position == 1)\n {\n this.next();\n }\n else if (position - this.position == -1)\n {\n this.prev();\n }\n //This means that loungeMaster is playing from music that are way before,\n //Thus add current song to history and add another copy of song in history\n //To song list\n else if (position - this.position <= -2)\n {\n this.songs.splice( this.position + 1, 0, played_song);\n this.next();\n }\n\n return played_song;\n }", "function repeatOneMusic() {\n // here we'll reset the musicIndex accordingly\n musicIndex = musicIndex;\n loadMusic(musicIndex);\n playMusic();\n }", "function updateThreeKeys()\n{\n\t//should only do this when songs change\n\tsongTitle.innerHTML = allRiffs[currentRifNumber].title;\n\t// document.querySelector('#songTitle').innerHTML = allRiffs[currentRifNumber].name;\n\tlet nextRiff = allRiffs[currentRifNumber+1];\n\tif(nextRiff == null) nextRiff = allRiffs[0];\n\tlet nextThreeNotes = []; //1st 2nd 3rd\n\t// count how many of each key, if > 1, writeAt\n\n\tif(riffProgress >= currentRiff.notes.length-2)\n\t{\n\t\t//need check if repeating, allRiffs build to include same array multiple times\n\t\tlet hitsTillEnd = currentRiff.notes.length-riffProgress;\n\t\tif(hitsTillEnd == 2)\n\t\t{\n\t\t\tnextThreeNotes[2] = nextRiff.notes[0].soundName;\n\t\t\tnextThreeNotes[1] = currentRiff.notes[riffProgress+1].soundName;\n\t\t}\n\t\telse if(hitsTillEnd == 1)\n\t\t{\n\t\t\tnextThreeNotes[2] = nextRiff.notes[1].soundName;\n\t\t\tnextThreeNotes[1] = nextRiff.notes[0].soundName;\n\t\t}\n\t}\n\telse\n\t{\n\t\tnextThreeNotes[2] = currentRiff.notes[riffProgress+2].soundName;\n\t\tnextThreeNotes[1] = currentRiff.notes[riffProgress+1].soundName;\n\t}\n\n\tif(riffProgress == currentRiff.notes.length)\n\t{\n\t\tnextThreeNotes[2] = nextRiff.notes[2].soundName;\n\t\tnextThreeNotes[1] = nextRiff.notes[1].soundName;\n\t\tnextThreeNotes[0] = nextRiff.notes[0].soundName;\n\t}\n\telse\n\t{\n\t\tnextThreeNotes[0] = currentRiff.notes[riffProgress].soundName;\n\t}\n\tcountAnyRepeats();\n\t// countAnyRepeatsLastThree(nextThreeNotes);\n\tdocument.getElementById(nextThreeNotes[2]).src = 'images/whiteH3.png';\n\tdocument.getElementById(nextThreeNotes[1]).src = 'images/whiteH2.png';\n\tdocument.getElementById(nextThreeNotes[0]).src = 'images/whiteH1.png';\n}", "function createSong(songString){\n\t\tvar newSong = [], size = 3;\n\t\tvar songArray = songString.split(',');\n\t\t\n\t\twhile (songArray.length > 0 && songArray.length % size == 0){\n\t\t\tdebug('songArray: ' + songArray);\n\t\t newSong.push(songArray.splice(0, size));\n\t\t debug('songArray after splice: ' + songArray);\n\t\t debug('newSong: ' + songArray);\n\t\t};\n\t\tdebug('newSong: ' + newSong);\n\t\t\n\t\treturn newSong;\n\t}", "function remixAllTheTracks(num){\n if (num===trackIDs.length){\n //base case\n //ship up the bars/their durations\n var bars = [];\n var durations = [];\n for (i=0;i<tracks.length;i++) {\n var barArray = tracks[i].analysis.bars;\n for (j=0;j<barArray.length;j++) {\n bars.push(barArray[j]);\n durations.push(barArray[j].duration);\n }\n }\n console.log('bars', bars);\n //sketchily set a metric fuckton of global variables\n window.bars = bars;\n window.durations = durations;\n window.tracks = tracks;\n window.trackNames = [];\n for (i=0;i<tracks.length;i++) {\n window.trackNames.push(tracks[i].title);\n }\n // console.log('trackNames: init', window.trackNames)\n window.currentIndex = 0;\n window.switchDuration = 10;\n window.nextSwitchIn = 5;\n //render ring based on duration of each bar\n renderRing(durations);\n // get track titles/sources, append them to target div\n var srcs = $('.links').attr('name').split(',');\n var newHTML = getNewHTML(srcs, tracks.reverse());\n // $('body').append('<script src=\"/javascripts/switch.js\" />');\n }\n else{\n remixer.remixTrackById(trackIDs[num], trackURL, function(t, percent){\n track = t;\n\n // $(\"#info\").text(percent + \"% of Track \"+(trackIDs.length-num)+\"loaded\");\n if (percent == 100) {\n // $(\"#info\").text(percent + \"% of the track loaded, remixing...\");\n }\n\n if (track.status == 'ok') {\n // $(\"#bars\").text(\"The track has \" + track.analysis.bars.length + \" bars\");\n // $(\"#beats\").text(\"The track has \" + track.analysis.beats.length + \" beats\");\n // $(\"#info\").text(\"Remix complete!\");\n console.log(track)\n tracks.push(track);\n remixAllTheTracks(num+1);\n }\n });\n }\n }", "function prev_song(){\r\n if(index_no>0){//Verifica que el indice no sea menor que 0\r\n index_no-=1;//Cambia el indice en 1 al indice anterior\r\n load_track(index_no);//Carga la canción\r\n playsong();//Reproduce la cancion\r\n }else{\r\n index_no = All_song.length;//Cuando el indice supera la longitud de la lista se vuelve el valor maximo de la longitud de la lista\r\n load_track(index_no);//Carga la canción\r\n playsong();//Reproduce la cancion\r\n }\r\n }", "function prevSong() {\r\n if (shuffle) {\r\n if (shuffleIndex > 0) {\r\n shuffleIndex--;\r\n streamSong(songs[shuffled[shuffleIndex]]);\r\n log (\r\n \"Shuffle Index: \" + shuffleIndex\r\n + \" --song-> \" + shuffled[shuffleIndex]);\r\n \r\n } else if (shuffleIndex <= 0 && repeat) {\r\n shuffleIndex = shuffled.length - 1;\r\n streamSong(songs[shuffled[shuffled.length - 1]]);\r\n log (\r\n \"Shuffle Index: \" + shuffleIndex\r\n + \" --song-> \" + shuffled[shuffleIndex]);\r\n }\r\n } else {\r\n if (playlistIndex > 0) {\r\n streamSong(songs[playlistIndex-1]);\r\n log (\"Playlist Index: \" + (playlistIndex));\r\n } else if (playlistIndex <= 0 && repeat) {\r\n streamSong(songs[songs.length-1]);\r\n log (\"Playlist Index: \" + (playlistIndex));\r\n }\r\n }\r\n }", "function parseSongs(songData) {\n let songs = [];\n for (let i = 0; i < songData.length; i++) {\n let data = songData[i];\n let artists = [];\n for (let j = 0; j < data.artists.length; j++) {\n artists.push(data.artists[j].name);\n }\n let song = {\n id: i,\n name: data.name,\n album: data.album.name,\n artists: artists,\n art: data.album.images[0].url,\n song_url: data.external_urls.spotify,\n album_url: data.album.external_urls.spotify,\n };\n songs.push(song);\n }\n return songs;\n}", "function populateAnimationArray()\r\n{\r\n\tswapped = true;\r\n\twhile(swapped)\r\n\t{\r\n\t\tswapped = false;\r\n\t\tvar i = 0;\r\n\t\twhile( i < valueArray.length )\r\n\t\t{\r\n\t\t\tif(valueArray[i] > valueArray[i+1])\r\n\t\t\t{\r\n\t\t\t\tanimationArray.push(\r\n\t\t\t\t\tnew swapRecord(\r\n\t\t\t\t\t\tanimArray[i],\r\n\t\t\t\t\t\tanimArray[i+1],\r\n\t\t\t\t\t\ti));\r\n\t\t\t\tvar temp = valueArray[i];\r\n\t\t\t\tvalueArray[i] = valueArray[i+1];\r\n\t\t\t\tvalueArray[i+1] = temp;\r\n\t\t\t\ttemp = animArray[i];\r\n\t\t\t\tanimArray[i] = animArray[i+1];\r\n\t\t\t\tanimArray[i+1] = temp;\r\n\t\t\t\tswapped = true;\r\n\t\t\t}\r\n\t\t\ti++;\r\n\t\t}\r\n\t}\r\n\tvar i = 0;\r\n}", "function createShuffle() {\r\n shuffled = [];\r\n for (var i = 0; i < songs.length; i++) {\r\n shuffled.push(i);\r\n }\r\n return randomize(shuffled);\r\n }", "function nextSong() {\r\n musicIndex = musicIndex + 1;\r\n if (musicIndex > music.length - 1) {\r\n musicIndex = 0;\r\n loadSong(musicIndex);\r\n playSong();\r\n } else {\r\n loadSong(musicIndex);\r\n playSong();\r\n }\r\n}", "next() {\n const { songFile, upNext, previousPlays, songs, repeat, shuffle } = this.state;\n // stop current song with timestampId\n songFile.pause();\n clearInterval(this.timestampID);\n // check if repeating that song\n if (repeat === 'Song') {\n songFile.currentTime = 0;\n this.setState({ timestamp: 0 });\n } else {\n // 1) Splice first song in upNext and push to previousPlays\n previousPlays.push(upNext.shift());\n // 2) If both upNext and songs are empty, call mount to reset state: songs, upnext songfile\n if (upNext.length === 0 && songs.length === 0) {\n this.mount();\n } else {\n // 3) If upNext is empty and set to shuffle, grab a random song to push to upNext\n // 4) Else if upNext is just empty, splice first song in songs and push to upNext\n if (upNext.length === 0 && shuffle === '-alt') {\n const randomIndex = Math.floor(Math.random() * songs.length);\n const randomSong = songs.splice(randomIndex, 1)[0];\n upNext.push(randomSong);\n } else if (upNext.length === 0) {\n upNext.push(songs.shift());\n } \n // Either way, set state: songs, upNext, previousPlays, *new* songFile, timestamp 0\n this.setState({\n upNext,\n previousPlays,\n songs,\n timestamp: 0,\n songFile: new Audio(upNext[0].songFile),\n });\n }\n }\n }", "function addSongsResult (result, clear) {\n\n\t\tif (clear) {\n\t\t\tupNext = [];\n\t\t\tnowPlaying = 0;\n\t\t}\n\n\t\tfor (var row of result.rows) {\n\t\t\tdelete row.doc._rev;\n\t\t\tupNext.push(row.doc);\n\t\t}\n\n\t}", "function loadResults(songMetaData) {\n playlist.unshift(songMetaData);\n // console.log(playlist);\n saveFile();\n}", "function refreshAlbum(container, array) {\n for (var i = 0; i < array.length; i++) {\n container.appendChild(array[i]); }\n}", "static listMusic() {\n let music = new Array();\n\n music.push('sounds/music/incompetech/delightful_d.ogg');\n music.push('sounds/music/incompetech/twisting.ogg'); // Moody, good for cave.\n music.push('sounds/music/incompetech/pookatori_and_friends.ogg');\n music.push('sounds/music/incompetech/getting_it_done.ogg');\n music.push('sounds/music/incompetech/robobozo.ogg');\n music.push('sounds/music/incompetech/balloon_game.ogg');\n music.push('sounds/music/incompetech/cold_sober.ogg');\n music.push('sounds/music/incompetech/salty_ditty.ogg');\n music.push('sounds/music/incompetech/townie_loop.ogg'); // Very peaceful, flute.\n music.push('sounds/music/incompetech/mega_hyper_ultrastorm.ogg'); // Super energetic. Maybe for special.\n // Legacy\n music.push('sounds/music/music_peaceful_contemplative_starling.ogg');\n music.push('sounds/music/twinmusicom_8_bit_march.ogg');\n music.push('sounds/music/twinmusicom_nes_overworld.ogg');\n music.push('sounds/music/music_juhanijunkala_chiptune_01.ogg');\n\n return music;\n }", "function albumArrayGet() {\n\t\t\tfor (var arrayLenCount = 0; arrayLenCount < topAlbumsOf.topalbums.album.length; arrayLenCount++) {\n\t\t\t\tvar albumArt_Loop = topAlbumsOf.topalbums.album[arrayLenCount].image[2]\n\t\t\t\tvar albumImagesArray_Loop = $.map(albumArt_Loop, function(value, index) { // To turn the object into an array 'imagesArray'\n\t\t\t\t\t\treturn [value];\n\t\t\t\t});\n\n\t\t\t\tif (album_photo_check === true) {\n\t\t\t\t\tif (topAlbumsOf.topalbums.album[arrayLenCount].playcount > criteraCount && albumImagesArray_Loop[0] !== \"\") { // if the albums 'playcount' is within the critera (see above), and album has a photo link (if not the array sends an empty string \"\")\n\t\t\t\t\t\tarrayCounting++;\n\t\t\t\t\t\tif (albumArrayGetRan === true) {\n\t\t\t\t\t\t\talbumHold[arrayCounting][0] = albumImagesArray_Loop[0]; // albumHold[x][0] = album photo link\n\t\t\t\t\t\t\talbumHold[arrayCounting][1] = topAlbumsOf.topalbums.album[arrayLenCount].name; // albumHold[x][1] = album title/name\n\t\t\t\t\t\t\talbumHold[arrayCounting][2] = topAlbumsOf.topalbums.album[arrayLenCount].artist.name; // albumHold[x][2] = artist name\n\t\t\t\t\t\t\talbumHold[arrayCounting][3] = topAlbumsOf.topalbums.album[arrayLenCount].url.substring(26 + artistNameAlbum.length)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tif (topAlbumsOf.topalbums.album[arrayLenCount].playcount > criteraCount) { // Same as above if statement, but without checking for album photo\n\t\t\t\t\t\tarrayCounting++;\n\t\t\t\t\t\tif (albumArrayGetRan === true) { // All is same as above\n\t\t\t\t\t\t\talbumHold[arrayCounting][0] = albumImagesArray_Loop[0];\n\t\t\t\t\t\t\talbumHold[arrayCounting][1] = topAlbumsOf.topalbums.album[arrayLenCount].name;\n\t\t\t\t\t\t\talbumHold[arrayCounting][2] = topAlbumsOf.topalbums.album[arrayLenCount].artist.name\n\t\t\t\t\t\t\talbumHold[arrayCounting][3] = topAlbumsOf.topalbums.album[arrayLenCount].url.substring(26 + artistNameAlbum.length)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t/* For pagination\n\n\t\t\tHave two arrays, albumHold being the default, and another that only takes up to 12 'arrays'.\n\t\t\tFor example;\n\t\t\t\tPage 1 : AlbumHold (give 12 'albums') > AlbumPage [currentPage = 1]\n\t\t\t\tPage 2 : AlbumHold (give 12 more from that 12, so 12 > 24) > AlbumPage [currentPage = 2]\n\t\t\t\tPage 3 : AlbumHold (give 12 more from that 12, so 24 > 36) > AlbumPage [currentPage = 3]\n\n\t\t\t\tOn click (the pagination (i.e, 1 2 3 4 . . .)) it will advance to that page and put that number into currentPage Array)\n\n\t\t\t*/\n\n\t\t\tif (albumArrayGetRan !== true) {\n\t\t\t\tfunction createArr(x, y) { // function to run to create an array\n\t\t\t\t\talbumHold = new Array(x);\n\n\t\t\t\t\tfor (var i = 0; i < x; i++) {\n\t\t\t\t\t\talbumHold[i] = new Array(y);\n\t\t\t\t\t}\n\n\t\t\t\t\treturn albumHold;\n\t\t\t\t}\n\t\t\t\talbumArrayGetRan = true;\n\t\t\t\tcreateArr(arrayCounting + 1, 3) // arrayCounting is the amount of 'filtered' albums, + 1 (cheap fix to an error) extra 'array' level gets removed (see below)\n\t\t\t\tarrayCounting = 0; // resets var back to 0 for second function run (below)\n\t\t\t\talbumArrayGet(); // runs the function once more (second call)\n\t\t\t}\n\t\t}", "function createRandomizedPlaylist() {\n // First, copy the playlist\n let temp = [...playlist];\n randomizedPlaylist = [];\n\n // Next copy one at a time at random\n for (let i = 0; i < playlist.length; i++) {\n let j = Math.floor(Math.random() * temp.length);\n console.log(\"Pushing position: \" + j);\n randomizedPlaylist.push(temp.splice(j,1));\n }\n\n if (playlistRandom) {\n // If playing a random playlist, then reset the index to start over.\n currentPlaylistIndex = 0;\n }\n console.log(\"Playlist.length = \" + playlist.length + \" Randomized list length: \" + randomizedPlaylist.length);\n console.log(\"Playlist: \" + JSON.stringify(playlist));\n console.log(\"Randomized: \" + JSON.stringify(randomizedPlaylist));\n}", "function songDecoder(song){\n var arr2 = [];//\n var arr = song.split('WUB');\n\n\n// for(var i=0; i<arr.lenth; i++){\n// if (arr[i] === ''){\n// arr2.push(arr[i]);\n// }\n// }\n//\n\n var str = arr.join(' ');\n \n str = str.replace(/\\s+/g, ' ');\n str = str.trim();\n console.log(str);\n\n return str;\n}", "function topPortugal() {\r\n // ARRAYS para guardar os valores das musicas \r\n var musicArray = [];\r\n var trackImg = [];\r\n\r\n //call da API\r\n $.ajax({\r\n type: 'POST',\r\n url: 'http://ws.audioscrobbler.com/2.0/',\r\n data:\r\n 'method=tag.gettoptracks&' +\r\n 'api_key=97dd7464b0a13ef1d8ffa1562a6546eb&' +\r\n 'tag=portugal&' +\r\n 'format=json',\r\n dataType: 'json',\r\n async: false, // Só continua o código quando o ajax completa, em vez de fazer em background\r\n success: function (data) {\r\n musicArray = data.tracks.track;\r\n },\r\n })\r\n\r\n console.log(musicArray);\r\n musicArray = Object.assign({}, musicArray);\r\n for (var i = 0; i < 10; i++) {\r\n console.log(musicArray[i]);\r\n trackImg.push(musicArray[i].image[3]);\r\n }\r\n\r\n //slideshow \r\n var index = 0;\r\n var theImage = document.getElementById(\"main-image\");\r\n\r\n theImage.src = trackImg[0][\"#text\"];\r\n\r\n $('#main-text').text((\r\n \"Rank: \" + (index + 1) + \" | \" + musicArray[index].artist.name + \" - \" + musicArray[index].name\r\n ));\r\n\r\n $('#btnLeft').click(function () {\r\n index--;\r\n\r\n if (index < 0)\r\n index = trackImg.length - 1;\r\n\r\n theImage.src = trackImg[index][\"#text\"];\r\n\r\n $('#main-text').text((\r\n \"Rank: \" + (index + 1) + \" | \" + musicArray[index].artist.name + \" - \" + musicArray[index].name\r\n ));\r\n\r\n\r\n //verifica se ja existe nos favoritos\r\n var musica = $('#main-text').text();\r\n var favMusics = JSON.parse(localStorage.getItem(\"favoritos\"));\r\n\r\n //faz o corte do artista e musica nas strigns do array predefinido das musicas\r\n var artist_track = musica;\r\n var artist_trackA = new Array();\r\n artist_trackA = artist_track.split(' | ');\r\n musica = artist_trackA[1];\r\n\r\n if (favMusics.includes(musica))\r\n $(\"#addFav\").html('Adicionar aos Favs🌟');\r\n else\r\n $(\"#addFav\").html('Adicionar aos Favs');\r\n\r\n });\r\n\r\n $('#btnRight').click(function () {\r\n index++;\r\n index %= trackImg.length;\r\n\r\n if (index < 0)\r\n index = trackImg.length - 1;\r\n\r\n theImage.src = trackImg[index][\"#text\"];\r\n\r\n $('#main-text').text((\r\n \"Rank: \" + (index + 1) + \" | \" + musicArray[index].artist.name + \" - \" + musicArray[index].name\r\n ));\r\n\r\n //verifica se ja existe nos favoritos\r\n var musica = $('#main-text').text();\r\n var favMusics = JSON.parse(localStorage.getItem(\"favoritos\"));\r\n\r\n //faz o corte do artista e musica nas strigns do array predefinido das musicas\r\n var artist_track = musica;\r\n var artist_trackA = new Array();\r\n artist_trackA = artist_track.split(' | ');\r\n musica = artist_trackA[1];\r\n\r\n console.log(musica);\r\n if (favMusics.includes(musica))\r\n $(\"#addFav\").html('Adicionar aos Favs🌟');\r\n else\r\n $(\"#addFav\").html('Adicionar aos Favs');\r\n\r\n });\r\n}", "function formatAlbums (albumSet) {\n\n\t\tvar albums = [];\n\n\t\tfor (var album in albumSet) {\n\n\t\t\tvar songs = sortSongs(albumSet[album]);\n\n\t\t\talbums.push({ name: album, songs: songs });\n\n\t\t}\n\n\t\treturn albums;\n\n\t}", "addSong(songInfo, position) {\n if (position == \"start\")\n {\n //this.songs.unshift(songInfo);\n //Adds song to right after the currently playing song\n this.songs.splice( this.position + 1, 0, songInfo);\n }\n else if (position == \"end\")\n {\n this.songs.push(songInfo);\n }\n\n //Probably tries to update for everyone too\n }", "function pickRandomSongs(songList) {\n var rand = Math.floor(Math.random() * (songList.length));\n var song = [];\n var againNum;\n do {\n var tempSong;\n if(song.length > 0) {\n tempSong = getSong(songList, song[song.length-1]);\n \n } else {\n tempSong = songList[rand];\n }\n var songHistory = songCache.get(tempSong.title);\n if(songHistory != null) {\n if(songHistory == \"beg\") {\n againNum =Math.random() * 11;\n removeSong(tempSong, songList);\n }\n } else {\n if(Math.random() * 100 > 80 && tempSong.splittable !== \"0\" && song.length < 3) {\n // cache song as beginning \n songCache.set(tempSong.title, \"beg\");\n againNum = 10;\n } else {\n againNum = Math.random() * 11;\n removeSong(tempSong, songList);\n }\n }\n \n song.push(tempSong);\n } while (againNum > 8 && song.length < 4);\n\n return song;\n}", "prepareFilesList(files) {\n console.log(this.position);\n console.log(this.matrixData);\n if (this.matrixData[this.displayedActionType][this.position[0]][this.position[1]].action.value == 'MF') {\n for (const item of files) {\n //item.progress = 0;\n this.matrixData[this.displayedActionType][this.position[0]][this.position[1]].musicfiles.push(item);\n // FileSaver.saveAs(item, 'test.wav');\n }\n }\n else {\n this.matrixData[this.displayedActionType][this.position[0]][this.position[1]].musicfiles = [files[0]];\n }\n }", "function prevSong(){\n i--;\n if(i < 0){\n i = songs.length - 1;\n }\n loadSong(songs[i]);\n playSong();\n}", "function theBeatlesPlay(musicians, instruments) {\n var emptyarr = []\n for (let i = 0; i < musicians.length; i++) {\n emptyarr.push( musicians[i] + \" plays \" + instruments[i]);\n }\n return emptyarr\n}", "function nextMusic() {\n musicIndex++;\n musicIndex > allMusic.length ? (musicIndex = 1) : (musicIndex = musicIndex);\n loadMusic(musicIndex);\n playMusic();\n playingNow();\n}", "function previousSong() {\r\n if (index_no > 0) {\r\n index_no -= 1;\r\n loadTrack(index_no);\r\n playSong();\r\n } else {\r\n index_no = All_songs.length;\r\n loadTrack(index_no);\r\n playSong();\r\n }\r\n}", "function removeResults(songMetaData) {\n playlist.shift(songMetaData);\n // console.log(playlist);\n saveFile();\n}", "function amplitude_next_song() {\n if(amplitude_active_song.getAttribute('amplitude-visual-element-id') != ''){\n if(document.getElementById(amplitude_active_song.getAttribute('amplitude-visual-element-id'))){\n document.getElementById(amplitude_active_song.getAttribute('amplitude-visual-element-id')).className = document.getElementById(amplitude_active_song.getAttribute('amplitude-visual-element-id')).className.replace('amplitude-now-playing', '');\n }\n }\n var amplitude_nodes = document.getElementById('amplitude-playlist').getElementsByTagName('audio');\n //If ths shuffle is activated, then go to next song in the shuffle array. Otherwise go down the playlist.\n if(amplitude_shuffle){\n for(i=0; i<amplitude_shuffle_list.length; i++){\n if(amplitude_shuffle_list[i] == amplitude_active_song.getAttribute('id')){\n if(typeof amplitude_shuffle_list[i+1] != 'undefined'){\n amplitude_play(amplitude_shuffle_list[i+1]);\n }else{\n amplitude_play(amplitude_shuffle_list[0]);\n }\n break;\n }\n }\n }else{\n for (i=0; i<amplitude_nodes.length; i++) {\n if (amplitude_nodes[i].getAttribute(\"id\") == amplitude_active_song.getAttribute('id')) {\n if (typeof amplitude_nodes[i+1] != 'undefined') {\n amplitude_play(amplitude_nodes[i+1].getAttribute(\"id\"));\n }else{\n amplitude_play(amplitude_nodes[0].getAttribute(\"id\"));\n }\n break;\n }\n }\n }\n\n amplitude_active_song_information['cover_art'] = amplitude_active_song.getAttribute('amplitude-album-art-url');\n amplitude_active_song_information['artist'] = amplitude_active_song.getAttribute('amplitude-artist');\n amplitude_active_song_information['album'] = amplitude_active_song.getAttribute('amplitude-album');\n amplitude_active_song_information['song_title'] = amplitude_active_song.getAttribute('amplitude-title');\n\n if((typeof amplitude_config != 'undefined') && (typeof amplitude_config.amplitude_next_song_callback != 'undefined')){\n var amplitude_next_song_callback_function = window[amplitude_config.amplitude_next_song_callback];\n amplitude_next_song_callback_function();\n }\n}", "function appendArrays() {\n let name = $(\"#song-name\").val();\n let artist = $(\"#artist\").val();\n let length = $(\"#length\").val();\n let image = $(\"#picture-link\").val();\n let link = $(\"#song-link\").val();\n \n if (name !== \"\") {\n numSongs = allSongsArray.length;\n console.log(numSongs);\n allSongsArray[numSongs] = {\"name\": name, \"artist\": artist, \"length\": length, \"image\": image, \"link\": link};\n \n \n\n //PUSH TO LOCAL STORAGE\n // localStorage.setItem(\"songNamesArrayJSON\", JSON.stringify(songNamesArray));\n // localStorage.setItem(\"artistsArrayJSON\", JSON.stringify(artistsArray));\n // localStorage.setItem(\"lengthsArrayJSON\", JSON.stringify(lengthsArray));\n // localStorage.setItem(\"imagesArrayJSON\", JSON.stringify(imagesArray));\n // localStorage.setItem(\"songLinksArrayJSON\", JSON.stringify(songLinksArray));\n localStorage.setItem(\"allSongsArrayJSON\", JSON.stringify(allSongsArray));\n ////////////////////////\n \n }\n else {\n \n }\n}", "function sortSongArray( treeNode, arr) {\n var leftArr = Array();\n var rightArr = Array();\n var keys = Object.keys( arr);\n\n //add durations if they aren't already there\n if( typeof arr[keys[0]].duration == 'undefined') {\n this.addSongDurations( arr);\n }\n\n var nodeInsert= {\n value:{\n time:parseFloat(keys[Math.floor(keys.length/2)]),\n duration:parseFloat(arr[keys[Math.floor(keys.length/2)]].duration),\n file:arr[keys[Math.floor(keys.length/2)]].file\n },\n left:null,\n right:null,\n };\n\n for( var i=0; i< Math.floor(keys.length/2); i++) {\n leftArr[keys[i]]= arr[keys[i]];\n }\n for( var i=(Math.floor(keys.length/2))+1; i< keys.length; i++) {\n rightArr[keys[i]]= arr[keys[i]];\n }\n\n if( treeNode == null) {\n treeNode = nodeInsert;\n } if( parseFloat(nodeInsert.value.time) < parseFloat(treeNode.value.time)) {\n treeNode.left = nodeInsert;\n } else if( parseFloat(nodeInsert.value.time) > parseFloat(treeNode.value.time)) {\n treeNode.right = nodeInsert;\n }\n\n if(Object.keys(leftArr).length>0) {\n this.sortSongArray( nodeInsert, leftArr);\n }\n\n if(Object.keys(rightArr).length>0) {\n this.sortSongArray( nodeInsert, rightArr);\n }\n return treeNode;\n}", "tracksForPlaylist(genres , duration){\n let tracks = this.getTracksMatchingGenres(genres);\n let res = [];\n for(let i=0;this.sumarTiempoDeTracks(res)<duration && i<tracks.length;i++){ \n res[i]=tracks[i];\n }\n return res;\n}", "loadSongs(songs) {\n for (var song of songs)\n {\n this.addSong(song, \"end\");\n }\n }", "function nextSong(){\n var audio=document.querySelector('audio');\n // console.log(audio.duration);\n var len=songs.length;\n\n if (willShuffle == 1) {\n var nextSongNumber = randomExcluded(1,len,currentSongNumber); // Calling our function for random selection\n var nextSongObj = songs[nextSongNumber-1];\n songIndex(nextSongObj,audio);\n currentSongNumber = nextSongNumber;\n }\n\n else if(currentSongNumber < len) {\n for(var i=0;i<len;i++){\n if(audio.src.search(songs[i].fileName)!=-1)\n break;\n }\n currentSongNumber=i+1;\n if(currentSongNumber < len){\n var nextSongObj = songs[currentSongNumber];\n songIndex(nextSongObj,audio);\n }\n\n else if(willLoop == 1) {\n var nextSongObj = songs[0];\n songIndex(nextSongObj,audio);\n currentSongNumber = 1;\n }\n\n else {\n currentSongNumber=len-1;\n lastSongClick(audio);\n }\n }\n\n else {\n lastSongClick(audio);\n }\n}", "function createSeedPlaylist(variety) { \n //hacky\n var temp =[];\n $.each(songSeedList, function(i, el){\n if($.inArray(el, temp) === -1) temp.push(el);\n });\n songSeedList = temp;\n\n // while (songSeedList.length > 5) {\n // songSeedList = songSeedList.splice(4,3);\n // }\n console.log(songSeedList);\n // for (var i = 0; i < 20; i++) {\n // if (songSeedList.length > 5) {\n // console.log('here');\n // songSeedList = songSeedList.splice(4,1);\n // console.log('new: ' + songSeedList)\n // }\n // }\n var url = 'http://developer.echonest.com/api/v4/playlist/static?api_key=' + apiKey + '&callback=?';\n $.getJSON(url, \n { \n 'track_id': songSeedList, 'format':'jsonp', \n 'bucket': [ 'id:spotify', \n 'tracks'], 'limit' : true,\n 'variety' : variety,\n 'results': 10, 'type':'song-radio', \n }, \n function(data) {\n info(\"\");\n $(\"#results\").empty();\n if (! ('songs' in data.response)) {\n info(\"Can't find that artist\");\n } else {\n $(\"#all_results\").show();\n var tracks = \"\";\n for (var i = 0; i < data.response.songs.length; i++) {\n var song = data.response.songs[i];\n var tid = song.tracks[0].foreign_id.replace('spotify:track:', '');\n tracks = tracks + tid + ',';\n }\n var tembed = embed.replace('TRACKS', tracks);\n tembed = tembed.replace('PREFEREDTITLE' + ' playlist');\n var li = $(\"<span>\").html(tembed);\n $(\"#results\").append(li);\n }\n }\n );\n}", "function playArrayOfNotes(arr){\n\n var arrCopy = arr.slice();\n playNoteFromArray(arrCopy);\n}", "function prevSong(){\n songIndex--\n if(songIndex<0)\n {\n songIndex=songs.length-1\n }\n PickSong(songs[songIndex]);\n playSong()\n}", "function previousSong(){\n var audio=document.querySelector('audio');\n // console.log(audio.duration);\n var len=songs.length;\n\n if (willShuffle == 1) {\n var nextSongNumber = randomExcluded(1,len,currentSongNumber); // Calling our function for random selection\n var nextSongObj = songs[nextSongNumber-1];\n songIndex(nextSongObj,audio);\n currentSongNumber = nextSongNumber;\n }\n\n else if(currentSongNumber > -1) {\n for(var i=0;i<len;i++){\n if(audio.src.search(songs[i].fileName)!=-1)\n break;\n }\n currentSongNumber=i-1;\n if(currentSongNumber > -1){\n var nextSongObj = songs[currentSongNumber];\n songIndex(nextSongObj,audio);\n }\n else if(willLoop == 1) {\n var nextSongObj = songs[len-1];\n songIndex(nextSongObj,audio);\n currentSongNumber = 1;\n }\n else {\n lastSongClick(audio);\n }\n }\n else {\n lastSongClick(audio);\n }\n}", "collectAlbums(){\n let resultadoAlbums = this.artists.map((fArtist) => fArtist.albums);\n let flatResultado = resultadoAlbums.reduce(function(a, b) { \n return a.concat(b);\n }, new Array);\n return flatResultado;\n }", "function prevMusic() {\n if( audio.currentTime > 3 ) audio.currentTime = 0\n else startMusic-- \n\n if( startMusic < 0 ) startMusic = musicList.length - 1\n loadMusic( musicList[startMusic] )\n playMusic()\n}", "separateByDiscNumber(tracks){\n let discCounter = 1;\n let separatedDiscs = [];\n separatedDiscs.push([]);\n tracks.forEach((item) => {\n if (discCounter < item.disc_number) {\n separatedDiscs.push([]);\n discCounter++;\n }\n separatedDiscs[discCounter - 1].push(item);\n });\n return separatedDiscs;\n }", "removeTrack(track) {\n if (this.state.playlistTracks.indexOf(track) > -1) { //step 49\n const newPlayList = this.state.playListTracks;\n newPlayList.splice(newPlayList.indexOf(track),1);\n// newPlayList.filter(this.playlistTracks.indexOf(track));\n// this.setState({playListTracks: his.playlistTracks.splice(this.playListTracks.indexOf(track),1)}) //remove the track from playlist at index of given track\n this.setState({playListTracks: newPlayList});\n }\n }", "function makeSongList(genreList, genreArray, decadeArray, selectedClean) {\n let songList = [];\n if (genreArray === null && decadeArray === null) {\n songList = Object.values(genreList.songs);\n } else if (decadeArray === null) {\n for (key in genreList.songs) {\n if (genreArray.includes(genreList.songs[key].genre)) {\n songList.push(genreList.songs[key]);\n }\n }\n } else if (genreArray === null || genreArray.length === 0) {\n for (key in genreList.songs) {\n if (decadeArray[0] <= genreList.songs[key].year && genreList.songs[key].year <= decadeArray[1]) {\n songList.push(genreList.songs[key]);\n }\n }\n } else {\n for (key in genreList.songs) {\n if (genreArray.includes(genreList.songs[key].genre) && decadeArray[0] <= genreList.songs[key].year && genreList.songs[key].year <= decadeArray[1]) {\n songList.push(genreList.songs[key]);\n }\n }\n }\n\n if (selectedClean) {\n return songList.filter(song=>song.explicit == false);\n } else {\n return songList;\n }\n \n}", "function loadSongs() {\n if (!store.getItem('songs')) createStore()\n var songArray = JSON.parse(store.getItem('songs'))\n for (var i = 0; i < songArray.length; i++) {\n var para = document.createElement('P');\n var t = document.createTextNode(songArray[i]);\n para.appendChild(t);\n document.querySelector('.songs').appendChild(para);\n }\n}", "function gotData(data) {\n console.log('retrieveSong gotData');\n for (var i = 0; i < 5; i++) {\n var tempArray = [];\n lastKey[i] = Object.keys(data.val()[i]).length;\n console.log('retrieveSong gotData for1');\n for (var j = 0; j < 3; j++) {\n var randID = Math.floor(random(lastKey[i]));\n var resultURI = data.val()[i][randID][0];\n var randomFreq = Math.floor(random(10)) * 10;\n var tempArray2 = [];\n tempArray2.push(resultURI, randomFreq);\n tempArray.push(tempArray2);\n console.log('retrieveSong gotData for2');\n }\n foundSongs.push(tempArray);\n }\n // document.getElementById(\"spotifyPreviewB\").src = 'https://open.spotify.com/embed?uri=' + resultURI;\n}", "function updateSongPos()\r\n{\r\n for (var i=0; i < songsPlayed.length; i++) {\r\n songsPlayed[i][\"place\"] = i;\r\n }\r\n}", "collecTracks(listAlbums){\n let resultadoTracks = listAlbums.map((fAlbum) => fAlbum.getTracks());\n let flatResultado = resultadoTracks.reduce(function(a, b) { \n return a.concat(b); \n }, new Array);\n return flatResultado;\n }", "function renderSimilarSongs(data) {\n for (var i = 0; i < 100; i++) {\n var trackArtistResult = {\n similarArtist: data.similartracks.track[i].artist.name,\n similarSong: data.similartracks.track[i].name,\n };\n similarResultsArr.push(trackArtistResult);\n }\n getLastFMSongInfo();\n }", "function nextSong(){\n stopSong();\n songIndex= songIndex + 1;\n if(songIndex>songs.length-1){\n songIndex =0;\n }\n // songIndex>songs.length-1 ? songIndex = 0 : songIndex;\n loadSong(songs[songIndex]);\n playSong(songs[songIndex]);\n // console.log(songIdex);\n \n console.log(songs[sonIndex]);\n \n}", "function sortSongs (songs) {\n\n\t\treturn songs.sort(function compare (a, b) {\n\n\t\t\tif (a.number > b.number) {\n\t\t\t\treturn 1;\n\t\t\t} else if (a.number < b.number) {\n\t\t\t\treturn -1;\n\t\t\t}\n\n\t\t\treturn 0;\n\n\t\t});\n\n\t}", "getAlbums() {\n let results = [];\n\n if (!this.currentArtistName) {\n for (let i=0; i < this.albums.length; ++i) {\n results.push(this.albums[i].title);\n }\n\n return results;\n }\n else {\n let artistId = this._getArtistId();\n\n for (let i = 0; i < this.albums.length; ++i) {\n if (this.albums[i].artistId === artistId) {\n results.push(this.albums[i].title);\n }\n }\n }\n\n return results;\n }", "function get_genre(album_array) {\r\n let genre_array = [];\r\n // console.log(album_array);\r\n\r\n album_array.forEach((album) => {\r\n // get all album.genre and push in array if not includes\r\n if (!genre_array.includes(album.genre)) {\r\n genre_array.push(album.genre);\r\n }\r\n });\r\n // console.log(genre_array);\r\n return genre_array;\r\n }", "addToAlbum(album) {\n var albums = this.state.albums;\n\n if(!album.id) {\n // New album\n var lastID = parseInt(albums[albums.length - 1].id, 10);\n var newAlbum = { id: ++lastID,\n name: album.name,\n pictures: this.state.checkedPictures\n }\n\n albums.push(newAlbum);\n\n } else {\n // Add to existing album\n var existingAlbumIndex = albums.findIndex(function(el) { return el.id === album.id; });\n var existingAlbum = albums[existingAlbumIndex];\n\n existingAlbum.pictures = existingAlbum.pictures.concat(this.state.checkedPictures);\n $.uniqueSort(existingAlbum.pictures); // remove duplicate pictures\n\n // Replace the existing album\n albums.splice(existingAlbumIndex, 1, existingAlbum);\n }\n\n this.setState({\n albums: albums,\n checkedPictures: []\n });\n }", "function generateArray(con){\n\tvar generate_arr = [];\n\tvar generateNotes_arr = [];\n\tvar id = '';\n\t$('.playerNotes .notesWrapper').each(function(index, element) {\n\t\tid = $(this).attr('data-type');\n\t\tgenerateNotes_arr = [];\n\t\t$(this).find('div.note').each(function(index, element) {\n generateNotes_arr.push(parseInt($(this).css('left')));\n });\n\t\tgenerateNotes_arr.sort(function(a, b){return a-b});\n generate_arr.push({id:$(this).attr('id'), noteid:id, top:parseInt($(this).css('top')), notes:generateNotes_arr});\n });\n\tsortOnObject(generate_arr, 'top');\n\t\n\tvar final_arr = [];\n\tfor(n=0;n<generate_arr.length;n++){\n\t\t$('#'+generate_arr[n].id).attr('data-array', n);\n\t\tfinal_arr.push({position:generate_arr[n].top / heightScale, id:generate_arr[n].noteid, notes:generate_arr[n].notes});\n\t}\n\t\n\tmusic_arr[curMusic].notes = final_arr;\n\t\n\t$('#listofnotes').empty();\n\tif(curNote > final_arr.length - 1){\n\t\tcurNote = 0;\n\t}\n\t\n\tvar outputString = '';\n\tfor(n=0;n<final_arr.length;n++){\n\t\t$('#listofnotes').append($(\"<option/>\", {\n\t\t\tvalue: n,\n\t\t\ttext: (n+1)\n\t\t}));\n\t\toutputString+='{position:'+final_arr[n].position+', id:\"'+final_arr[n].id+'\", notes:['+final_arr[n].notes+']},';\n\t}\n\t$(\"#listofnotes\").val(curNote);\n\t\n\tif(con)\n\t\t$(\"#output\").val(outputString);\n}", "function makeMusic(keyPlayed) {\n\n\twindow.frequencies = {\n\n\t\t'C2': 65.4064, 'C#2': 69.2957, 'D2': 73.4162, 'D#2': 77.7817, 'E2': 82.4069, 'F2': 87.3071,\n\t\t'F#2': 92.4986, 'G2': 97.9989, 'G#2': 103.826, 'A2': 110.000, 'A#2': 116.541, 'B2': 123.471,\n\n\t\t'C3': 130.813, 'C#3': 138.591, 'D3': 146.832, 'D#3': 155.563, 'E3': 164.814, 'F3': 174.614,\n\t\t'F#3': 184.997, 'G3': 195.998, 'G#3': 207.652, 'A3': 220.000, 'A#3': 233.082, 'B3': 246.942,\n\n\t\t'C4': 261.626, 'C#4': 277.183, 'D4': 293.665, 'D#4': 311.127, 'E4': 329.628, 'F4': 349.228,\n\t\t'F#4': 369.994, 'G4': 391.995, 'G#4': 415.305, 'A4': 440.000, 'A#4': 466.164, 'B4': 493.883,\n\n\t\t'C5': 523.251, 'C#5': 554.365, 'D5': 587.330, 'D#5': 622.254, 'E5': 659.255, 'F5': 698.456,\n\t\t'F#5':739.989, 'G5': 783.991, 'G#5': 830.609, 'A5': 880.000, 'A#5': 932.328,'B5': 987.767,\n\t\t\n\t\t'C6': 1046.50, 'C#6': 1108.73, 'D6': 1174.66, 'D#6': 1244.51, 'E6': 1318.51, 'F6': 1396.91,\n\t\t'F#6': 1479.98, 'G6': 1567.98, 'G#6': 1661.22, 'A6': 1760.00, 'A#6': 1864.66, 'B6': 1975.53,\n\n\t};\n\n\twindow.playNote = function (note, time, duration) {\n\t\tvar ctx = window.audioContext;\n\t\tvar osc = ctx.createOscillator();\n\t\tosc.frequency.value = frequencies[note];\n\t\tosc.connect(ctx.destination);\n\t\tosc.noteOn(ctx.currentTime + time);\n\t\tosc.noteOff(ctx.currentTime + time + duration);\n\t\treturn osc;\n\t}\n\n\tplayNote(keyPlayed, 0.0, 0.25);\n\n}", "function syncSongs (db, songs, oldItems, libraryId, artistId, albumId) {\n\n\tlet additions = [];\n\n\tfor (let song of songs) {\n\n\t\tadditions.push(syncSong(db, song, oldItems, libraryId, artistId,\n\t\t\talbumId));\n\n\t}\n\n\treturn Promise.all(additions);\n\n}", "function uploadMusic() {\n //returns array of music available for ringtone after reading from file, is used for \"tones\" array\n}", "function SortMediaList() {\n self.MediaColList.col_1.length = 0;\n self.MediaColList.col_2.length = 0;\n self.MediaColList.col_3.length = 0;\n if (!MediaService.myGalleryList) {\n self.noResult = true;\n } else {\n var total = MediaService.myGalleryList.length;\n if (total == 0) {self.noResult = true;} else {self.noResult = false;}\n var rest = total % 3;\n for (var i = 0; i < total; i++) {\n if ($rootScope.sinceDate > parseDateTime(MediaService.myGalleryList[i].userDate).unix && $rootScope.untilDate < parseDateTime(MediaService.myGalleryList[i].userDate).unix) {\n if ((i % 3) === 0) {\n MediaObjSet(MediaService.myGalleryList[i] , self.MediaColList.col_1);\n } else if ((i % 3) === 1) {\n MediaObjSet(MediaService.myGalleryList[i] , self.MediaColList.col_2);\n } else if ((i % 3) === 2) {\n MediaObjSet(MediaService.myGalleryList[i] , self.MediaColList.col_3);\n }\n }\n }\n }\n }", "function runPiano() {\n\t// input the individual note into a json object and uploaded to the\n\t// VF.StaveNote function in order to print the music note notation\n\n\t// json2obj function can convert the three array list, alphabet, repeats, and speed sound\n\t// into a object\n\tfunction json2obj(notes_list, repeat_list, timeout_list){\n\t\tvar i = 1;\n\t\t// verifying wheter there is no duplicate\n\t\tif (i == repeat_list) {\n\t\t\t// appending into a new array\n\t\t\tnotes_parsed.push(notes_list)\n\t\t\tnotes_time.push(timeout_list)\n\t\t\t// generating the syntax string in order to converted into a json\n\t\t\tvar json1 = '{\"keys\": [\"';\n\t\t\tvar json2 = notes_list + '/4\"], \"duration\": \"q\"}';\n\t\t\tvar json3 = json1.concat(json2)\n\t\t\t// parse the json into a object\n\t\t\tconst obj = JSON.parse(json3);\n\t\t\t// create a note using Vexflow\n\t\t\tvar note = new VF.StaveNote(obj);\n\t\t\t// append the final result\n\t\t\tnotes.push(note);\n\t\t\treturn notes;\n\t\t} else {\n\t\t\t\t// generate the duplicate audio\n\t\t\t\twhile( i <= repeat_list)\n\t\t\t\t{\n\t\t\t\t// append the input into a new array\n\t\t\t\tnotes_parsed.push(notes_list)\n\t\t\t\tnotes_time.push(timeout_list)\n\t\t\t\t// generating the syntax string in oreder to converted into a json\n\t\t\t\tvar json1 = '{\"keys\": [\"';\n\t\t\t\tvar json2 = notes_list + '/4\"], \"duration\": \"q\"}';\n\t\t\t\tvar json3 = json1.concat(json2)\n\t\t\t\t// parse the json into a object\n\t\t\t\tconst obj = JSON.parse(json3);\n\t\t\t\t// create a note using Vexflow\n\t\t\t\tvar note = new VF.StaveNote(obj);\n\t\t\t\t\n\t\t\t\t// append the input\n\t\t\t\tnotes.push(note);\n\t\t\t\ti = i + 1;\n\t\t\t\t\n\t\t\t}\n\t\t\t// return the final result\n\t\t\treturn notes;\n\t\t}\n\t\t\n\t}\n\n\t// getUnique function will eliminate any duplicate in the array\n\tfunction getUnique(array) {\n\t\tvar uniqueArray = [];\n\t\t// Loop through array values\n\t\tfor (i = 0; i < array.length; i++) {\n\t\t\t// check wheter there is no duplicate\n\t\t\tif (uniqueArray.indexOf(array[i]) === -1) {\n\t\t\t\t// append into the array\n\t\t\t\tuniqueArray.push(array[i]);\n\t\t\t}\n\t\t}\n\t\t// return the result\n\t\treturn uniqueArray;\n\n\t}\n\t// try and catch used for Error Handling\n\ttry {\n\n\tvar complete_note_list = [\"A\", \"B\", \"C\", \"D\", \"E\", \"F\", \"G\"];\n\t// delete the lines\n\tnotes_raw = $(\"#input_notes\").val().split(/\\r?\\n/);\n\t\n\tlet onlyLetters = /[a-zA-Z]+/g\n\tlet onlyNumeric = /[+-]?(\\d+([.]\\d*)?(e[+-]?\\d+)?|[.]\\d+(e[+-]?\\d+)?)/g\n\tlet onlyFloat = /[+-]?(\\d+([.]\\d*)?(e[+-]?\\d+)?|[.]\\d+(e[+-]?\\d+)?)/g\n\t// generate an array only show the repetition\n\tnotes_repeat = $(\"#input_notes\").val().match(onlyNumeric).map(s => s.slice(0, 1));\n\t// generate an array only show the speed\n\tnotes_timeout = ($(\"#input_notes\").val().match(onlyFloat)).map(s => s.slice(1, 4));\n\t\n\n\t//////////////////////////////\n\t// Error Handling //\n\t/////////////////////////////\n\tvar max_repeat_numb_notes = 9;\n\t// Error try and catch\n\t// It constrains the user to use only one note per line.\n\n\t// This for loop clean the white spaces and appends into new string array\n\t// empty array\n\tnew_notes_raw = [];\n\tnotes_letter = [];\n\t// for loop go through alphabet notes input\n\tfor (m = 0; m < notes_raw.length; m++) {\n\t\t// trim every row that does have any white space\n\t\tnumber_rows = notes_raw[m].trim();\n\t\tif (Boolean(number_rows)) {\n\t\t\t// store the letter into a variable\n\t\t\tletter = number_rows.match(onlyLetters)[0];\n\t\t\t// append the letter,duplicate, and speed\n\t\t\tnew_notes_raw.push(number_rows);\n\t\t\t// append the letter\n\t\t\tnotes_letter.push(letter)\n\t\t}\n\t}\n\t\n\t\n\t// Sorting and Unique the Alphabet Notes\n\tsort_letters = notes_letter.sort();\n\tsort_uniq_letters = getUnique(sort_letters);\n\t\n\n\t// Debuginnin to see what is going on in the code\n\t/*console.log(new_notes_raw);\n\tconsole.log(notes_letter);\n\tconsole.log(sort_uniq_letters);\n\tconsole.log(complete_note_list);\n\tconsole.log(notes_repeat);\n\tconsole.log(notes_timeout);\n\t*/\n\t\n\n\t// Check the number of row per each line \n\t// if there is more than one note will stop the code\n\tfor (m = 0; m < new_notes_raw.length; m++) {\n\t\t// split the space of the input value note\n\t\tnumber_rows = new_notes_raw[m].split(\" \").length;\n\t\t\n\t\t//console.log(number_rows)\n\t\t// if there are two or more inputs in one row\n\t\tif (number_rows > 1) {\n\t\t\t// Give error to the user\n\t\t\tthrow \"Please add one note per line!\";\n\t\t} \n\n\t}\n\t// Use the filter command to determine the difference and it is not in the notes of the alphabet\n\tlet difference = sort_uniq_letters.filter(element => !complete_note_list.includes(element));\n\t//console.log(difference);\n\t// if there more than one in the difference array that means the user has alphabet that does not \n\t// follow the alphabet notes\n\tif (difference.length > 0 ) {\n\t\tthrow \"Please use first seven letters of the alphabet!\"\n\t}\n\t// Use only 1-9 repetitions\n\t// If statement will constraint the user and allow to use only certain number of repetitions\n\tif (max_repeat_numb_notes > 10){\n\t\tthrow \"Please use no more than 9 duplicates!\"\n\t}\n\n\t\n\t\n /////////////////////\n\t// Reference Notes //\n\t/////////////////////\n\n\t// It will print the symbol note notation for the user to help follow the audio\n\n\tVF1 = Vex.Flow;\n\t\n\t// Create an SVG renderer and attach it tot he DIV element named \"reference notes\"\n\tvar div1 = document.getElementById(\"reference_notes\")\n\n\tvar renderer = new VF1.Renderer(div1, VF1.Renderer.Backends.SVG);\n\n\tpx1=500;\n\t// Size SVG\n\trenderer.resize(px1+100, px1/4);\n\t// and get a drawing context\n\tvar context1 = renderer.getContext();\n\t\n\tcontext1.setFont(\"Times\", 10, \"\").setBackgroundFillStyle(\"#eed\");\n\n\tvar stave1 = new VF1.Stave(10, 0, px1);\n\n\tstave1.addClef(\"treble\");\n\t// Connect it to the rendering context and draw!\n\tstave1.setContext(context1).draw();\n\t// Generate your input notes\n\tvar notes_ref = [\n\t\tnew VF1.StaveNote({ keys: [\"a/4\"], duration: \"q\" }),\n\t\tnew VF1.StaveNote({ keys: [\"b/4\"], duration: \"q\" }),\n\t\tnew VF1.StaveNote({ keys: [\"c/4\"], duration: \"q\" }),\n\t\tnew VF1.StaveNote({ keys: [\"d/4\"], duration: \"q\" }),\n\t\tnew VF1.StaveNote({ keys: [\"e/4\"], duration: \"q\" }),\n\t\tnew VF1.StaveNote({ keys: [\"f/4\"], duration: \"q\" }),\n\t\tnew VF1.StaveNote({ keys: [\"g/4\"], duration: \"q\" })\n\t];\t\n\n\t// Create a voice in 4/4 and add above notes\n\tvar voice_ref = new VF1.Voice({ num_beats: 7, beat_value: 4 });\n\tvoice_ref.addTickables(notes_ref);\n\n\t// Format and justify the notes to 400 pixels.\n\tvar formatter1 = new VF1.Formatter().joinVoices([voice_ref]).format([voice_ref], px1);\n\n\t// Render voice\n\tvoice_ref.draw(context1, stave1);\n\t\n\n\t/////////////////////\n\t// Real-Time Notes //\n\t/////////////////////\n\n\tVF = Vex.Flow;\n\n\t// Create an SVG renderer and attach it to the DIV element named \"play piano\".\n\tvar div = document.getElementById(\"play_piano\")\n\tvar renderer = new VF.Renderer(div, VF.Renderer.Backends.SVG);\n\n\t//px = notes_letter.length * 500;\n\tpx=1000;\n\t// Configure the rendering context.\n\n\trenderer.resize(px+100, px/5);\n\tvar context = renderer.getContext();\n\t\n\tcontext.setFont(\"Arial\", 10, \"\").setBackgroundFillStyle(\"#eed\");\n\t// 13 notes = 500 px\n\t// Create a stave of width 400 at position 10, 40 on the canvas.\n\t\n\tvar stave = new VF.Stave(10, 0, px);\n\t\n\t// Add a clef and time signature.\n\t\n\tstave.addClef(\"treble\");\n\t// Connect it to the rendering context and draw!\n\tstave.setContext(context).draw();\n\t\n\t// empty array\n\tvar notes_parsed = []\n\tvar notes_time = []\n\tvar notes=[];\n\t\n\t\n\t// for loop will convert the array into json to object\n\tfor (index = 0; index < notes_raw.length; index++) {\n\t\t\tfor (n = 0; n < notes_raw.length; n++) {\n\t\t\t\tfor (i = 0; i < complete_note_list.length; i++){\n\t\t\t\t\t// compare if the notes are identical\n\t\t\t\t\tif (notes_raw[index][n] == complete_note_list[i]) {\n\t\t\t\t\t\t// call the json to object function\n\t\t\t\t\t\tnotes = json2obj(notes_raw[index][n], notes_repeat[index],notes_timeout[index]);\n\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t}\n\t}\n\n\n\t\n\tconsole.log(notes)\n\t\n\t// for loop determine whether the following notes belong to the \n\t// correct audio\n\ttiming = 0\n\t//index_ms_offset = 3000\n\t// Adding a weight to speed or slow down the audio note\n\tweight=30000;\n\tfor (index = 0; index < notes_parsed.length; index++) {\n\t\tif (notes_parsed[index] == 'A') {\n\t\t\t// Time delay\n\t\t\tsetTimeout( function() {\n\t\t\t// Play Audio\t\n\t\t\t\tnew Audio('media/high_a.mp3').play()\n\t\t\t}, weight*notes_time[index] * index)\n\t\t} else if (notes_parsed[index] == 'B' ) {\t\n\t\t\t// Time delay\n\t\t\tsetTimeout(function() {\n\t\t\t// Play Audio\t\n\t\t\t\tnew Audio('media/high_b.mp3').play()\n\t\t\t}, weight*notes_time[index] * index )\n\t\t} else if (notes_parsed[index] == 'C' ) {\n\t\t\t// Time delay\t\t\n\t\t\tsetTimeout(function() {\t\n\t\t\t// Play Audio\t\n\t\t\t\tnew Audio('media/high_c.mp3').play()\n\t\t\t}, weight*notes_time[index] * index )\n\t\t} else if (notes_parsed[index] == 'D' ) {\n\t\t\t// Time delay\t\n\t\t\tsetTimeout(function() {\n\t\t\t// PLay Audio\t\n\t\t\t\tnew Audio('media/high_d.mp3').play()\n\t\t\t}, weight*notes_time[index] * index ) \n\t\t} else if (notes_parsed[index] == 'E' ) {\n\t\t\t\n\t\t\t// Time Audio\n\t\t\tsetTimeout(function() {\n\t\t\t// Play Audio\n\t\t\t\tnew Audio('media/high_e.mp3').play()\n\t\t\t}, weight*notes_time[index] * index )\n\t\t} else if (notes_parsed[index] == 'F') {\n\t\t\t\n\t\t\t// Time Audio\n\t\t\tsetTimeout(function() {\n\t\t\t// Play Audio\n\t\t\t\tnew Audio('media/high_f.mp3').play()\n\t\t\t}, weight*notes_time[index] * index )\n\t\t} else if (notes_parsed[index] == 'G') {\n\t\t\t\n\t\t\t// Time Audio\n\t\t\tsetTimeout(function() {\n\t\t\t// Play Audio\t\n\t\t\t\tnew Audio('media/high_g.mp3').play()\n\t\t\t}, weight*notes_time[index] * index )\n\n\t\t}\n\t}\n\t\n\t//alert(notes_parsed)\n\tconsole.log(notes);\n\n\n\n// Create a voice in 4/4 and add above notes\nvar voice = new VF.Voice({num_beats: notes_parsed.length, beat_value: 4});\nvoice.addTickables(notes);\n\n// Format and justify the notes to 400 pixels.\nvar formatter = new VF.Formatter().joinVoices([voice]).format([voice], px);\n\n// Render voice\nvoice.draw(context, stave);\n\n\n\t// Javascript Buttons -> HTML5\n\tvar clearBtn = document.getElementById('ClearNote');\n\tclearBtn.addEventListener('click', e => {\n\t\t\n\t\tconst staff1 = document.getElementById('reference_notes')\n\t\twhile (staff1.hasChildNodes()) {\n\t\t\tstaff1.removeChild(staff1.lastChild);\n\t\t}\n\n\t\tconst staff2 = document.getElementById('play_piano')\n\t\twhile (staff2.hasChildNodes()) {\n\t\t\tstaff2.removeChild(staff2.lastChild);\n\t\t}\n\n\t})\n\t// Generate the concatenate code for stand-alone html5\n\t\tvar htmlTEMPLATE=\"<!doctype html>\"\n\t\thtmlTEMPLATE=htmlTEMPLATE+\"<html>\\n<head><\\/head>\\n<body>\\n\"\n\t\thtmlTEMPLATE=htmlTEMPLATE+\"<script>@@@PLAY_CODE<\\/script>\"\n\t\thtmlTEMPLATE = htmlTEMPLATE+\"<\\/body>\\n<\\/html>\\n\"\n\n\n\t\t// for loop and if statement\n\t\t// generating the code for each note and audio note\n\t\tcode_output = \"\\n\"\n\t\ttiming = 0\n\t\t//index_ms_offset = 1000\n\t\tweight = 30000;\n\t\tfor (index = 0; index < notes_parsed.length; index++) {\n\t\t\tif (notes_parsed[index] == 'A') {\n\t\t\t\tcode_output = code_output + \"setTimeout( function(){\\n\"\n\t\t\t\tcode_output = code_output + \"new Audio('media/high_a.mp3').play()\"\n\t\t\t\tcode_output = code_output + \"}, \" + weight + \" * \" + notes_time[index] + \" * \" + index + \");\\n \"\n\t\t\t} else if (notes_parsed[index] == 'B') {\n\t\t\t\tcode_output = code_output + \"setTimeout( function(){\\n\"\n\t\t\t\tcode_output = code_output + \"new Audio('media/high_b.mp3').play()\"\n\t\t\t\tcode_output = code_output + \"}, \" + weight + \" * \" + notes_time[index] + \" * \" + index + \");\\n \"\n\t\t\t} else if (notes_parsed[index] == 'C') {\n\t\t\t\tcode_output = code_output + \"setTimeout( function(){\\n\"\n\t\t\t\tcode_output = code_output + \"new Audio('media/high_c.mp3').play()\"\n\t\t\t\tcode_output = code_output + \"}, \" + weight + \" * \" + notes_time[index] + \" * \" + index + \");\\n \"\n\t\t\t} else if (notes_parsed[index] == 'D') {\n\t\t\t\tcode_output = code_output + \"setTimeout( function(){\\n\"\n\t\t\t\tcode_output = code_output + \"new Audio('media/high_d.mp3').play()\"\n\t\t\t\tcode_output = code_output + \"}, \" + weight + \" * \" + notes_time[index] + \" * \" + index + \");\\n \"\n\t\t\t} else if (notes_parsed[index] == 'E') {\n\t\t\t\tcode_output = code_output + \"setTimeout( function(){\\n\"\n\t\t\t\tcode_output = code_output + \"new Audio('media/high_e.mp3').play()\"\n\t\t\t\tcode_output = code_output + \"}, \" + weight + \" * \" + notes_time[index] + \" * \" + index + \");\\n \"\n\t\t\t} else if (notes_parsed[index] == 'F') {\n\t\t\t\tcode_output = code_output + \"setTimeout( function(){\\n\"\n\t\t\t\tcode_output = code_output + \"new Audio('media/high_f.mp3').play()\"\n\t\t\t\tcode_output = code_output + \"}, \" + weight + \" * \" + notes_time[index] + \" * \" + index + \");\\n \"\n\t\t\t} else if (notes_parsed[index] == 'G') {\n\t\t\t\tcode_output = code_output + \"setTimeout( function(){\\n\"\n\t\t\t\tcode_output = code_output + \"new Audio('media/high_g.mp3').play()\"\n\t\t\t\tcode_output = code_output + \"}, \" + weight + \" * \" + notes_time[index] + \" * \" + index + \");\\n \"\n\t\t\t}\n\t\t}\n\n\t// print the code\n\t$(\"#compiled_code\").val(htmlTEMPLATE.replace(\"@@@PLAY_CODE\", code_output))\n\t} catch(err) {\n\t\talert(\"Error: \" + err);\n\t\t\n\t\t\n\t}\n\t\n}", "resetPlays(){\n this.playsValues = [];\n this.playsCoords = [];\n }", "function dedupeArr(arr){\n\n}", "function prevAudio(){\r\n currentSong--;\r\n if(currentSong < 0){\r\n currentSong = audios.length - 1 ;\r\n }\r\n audio.src = audios[currentSong] ; \r\n img.src = imgs[currentSong] ;\r\n\r\n playAudio();\r\n}", "function removeSong(song) {\n if (!store.getItem('songs')) createStore()\n var songArray = JSON.parse(store.getItem('songs'))\n var index = songArray.indexOf(song)\n songArray.splice(index, 1)\n store.setItem('songs', JSON.stringify(songArray))\n}", "function updateSong() {\n var updatedSong = {\n songName: songNameInput.value,\n albumTitle: albumTitleInput.value,\n playCount: playCountInput.value,\n releaseYear: releaseYearInput.value,\n youTubeLink: youTubeLinkInput.value\n };\n //Remove element and insert new updated song into songs array\n songs.splice(updateSongIndexArray[1], 1, updatedSong);\n //Switch buttons back\n updateButton.classList.add(\"hidden\");\n createButton.classList.remove(\"hidden\");\n //Clear out the input forms\n songNameInput.value = \"\";\n albumTitleInput.value = \"\";\n playCountInput.value = \"\";\n releaseYearInput.value = \"\";\n youTubeLinkInput.value = \"\";\n //Rerender the updated data\n renderData();\n}", "_populatePre(voiceIndex, measure, startTick, tickmap) {\n const voice = {\n notes: []\n };\n let i = 0;\n let j = 0;\n let ticksToFill = tickmap.durationMap[startTick];\n // TODO: bug here, need to handle tuplets in pre-part, create new tuplet\n for (i = 0; i < measure.voices[voiceIndex].notes.length; ++i) {\n const note = measure.voices[voiceIndex].notes[i];\n // If this is a tuplet, clone all the notes at once.\n if (note.isTuplet) {\n const tuplet = measure.getTupletForNote(note);\n if (!tuplet) {\n continue; // we remove the tuplet after first iteration\n }\n const ntuplet = SmoTuplet.cloneTuplet(tuplet);\n voice.notes = voice.notes.concat(ntuplet.notes);\n measure.removeTupletForNote(note);\n measure.tuplets.push(ntuplet);\n ticksToFill -= tuplet.tickCount;\n } else if (ticksToFill >= note.tickCount) {\n ticksToFill -= note.tickCount;\n voice.notes.push(SmoNote.clone(note));\n } else {\n const duration = note.tickCount - ticksToFill;\n const durMap = smoMusic.gcdMap(duration);\n for (j = 0; j < durMap.length; ++j) {\n const dd = durMap[j];\n SmoNote.cloneWithDuration(note, {\n numerator: dd,\n denominator: 1,\n remainder: 0\n });\n }\n ticksToFill = 0;\n }\n if (ticksToFill < 1) {\n break;\n }\n }\n return voice;\n }", "function nomeMusicas() {\r\n arrMusica = [];\r\n arrArtista = [];\r\n arrCompleto = [];\r\n strTotalMusicas = document.getElementsByClassName('TrackListHeader__entity-additional-info');\r\n intTotalMusicas = parseInt(strTotalMusicas[0].innerText.substring(0,3)) - 1;\r\n for (let i = 0; i <= intTotalMusicas; i++) {\r\n musicas = document.getElementsByClassName('tracklist-name');\r\n artistas = document.getElementsByClassName('TrackListRow__artists');\r\n arrMusica.push(musicas[i].innerText);\r\n arrArtista.push(artistas[i].innerText);\r\n arrCompleto.push(musicas[i].innerText + ' - ' + artistas[i].innerText);\r\n }\r\n // console.log(arrMusica);\r\n // console.log(arrArtista);\r\n console.log(arrCompleto);\r\n console.save(arrCompleto);\r\n}", "function transformTrickPlayList() {\n var downloadables,\n trickplayList = [];\n\n // There should only be one trick play track with both the\n // large and small stream info. So get the downloadables of\n // the first trickplay track\n if (manifest['trickPlayTracks'] && manifest['trickPlayTracks'].length) {\n downloadables = manifest['trickPlayTracks'][0]['downloadables'];\n if (downloadables) {\n trickplayList = downloadables.map(function(trickPlay) {\n return new TrickPlay(\n playback,\n trickPlay['id'],\n trickPlay['resHeight'],\n trickPlay['resWidth'],\n trickPlay['pixHeight'],\n trickPlay['pixWidth'],\n trickPlay['size'],\n trickPlay['urls']);\n });\n } else {\n log.warn('Trickplay track has no downloadables');\n }\n } else {\n log.warn('There are no trickplay tracks');\n }\n\n trickplayList.sort(function(a, b) {\n return a.size - b.size;\n });\n\n log.trace('Transformed trick play tracks', {\n 'Count': trickplayList.length\n });\n return trickplayList;\n }", "function makeArrayOfPossTimes (bigArray) {\n\tbigArray.forEach(function(item){\n\t\tif (uniqueTimesArray.indexOf(item) === -1) {\n\t\t\tuniqueTimesArray.push(item);\n\t\t}\n\t});\n \t// console.log(\"times array\", uniqueTimesArray);\n\tsortTimes(uniqueTimesArray);\n}", "function sortAlbums(albums, letter){\n \n/*\n for(let i = 0; i < albums.length; i++){\n let oneAlbumObject = albums[i];\n sortedObjectArray.push(oneAlbumObject);\n }\n\n \n sortedObjectArray.sort((a,b) => {\n var nameA = a.artists[0] ? a.artists[0].name : '';\n var nameB = b.artists[0] ? b.artists[0].name : '';\n return (nameA < nameB) ? -1 : (nameA > nameB) ? 1 : 0;\n })\n \n displayCard(sortedObjectArray, letter); \n\n*/ \n \n albums.sort((a,b) => {\n var nameA = a.artists[0] ? a.artists[0].name : '';\n var nameB = b.artists[0] ? b.artists[0].name : '';\n return (nameA < nameB) ? -1 : (nameA > nameB) ? 1 : 0;\n })\n\n \n displayCard(albums, letter); \n \n}", "function rehashTrackIndex() {\n\n var i;\n\n // Empty current index\n trackIndex = {};\n\n // Fill with current data\n for (i = 0; i < tracks.length; i += 1) {\n trackIndex[tracks[i].getTrackId()] = i;\n }\n }", "function record() {\n let currentStanza = 0; // 1st stanza\n let timeTrack = 0;\n song = [[]];\n\n const low = Math.floor(ranges[sample['instrument']]['low'] / (44100 / 16384));\n const high = Math.ceil(ranges[sample['instrument']]['high'] / (44100 / 16384));\n\n // Average time of each stanza in milliseconds\n const stanzaLength = ((sample['length']['hours'] ? sample['length']['hours'] * 60 * 60 * 1000 : 0) + \n (sample['length']['minutes'] * 60 * 1000) + (sample['length']['seconds'] * 1000)) / sample['stanzas'];\n\n analyser.fftSize = 32768;\n const dataArrayAlt = new Uint8Array(analyser.frequencyBinCount);\n\n let mem = {};\n let count = 0;\n \n const computeFFT = (newtime) => {\n if (stop) return;\n\n recallComputeFFT = requestAnimationFrame(computeFFT); \n\n now = newtime ? newtime : window.performance.now();\n elapsed = now - then;\n\n if (now - startTime > stanzaLength) {\n startTime = now;\n song.push([]);\n currentStanza += 1;\n }\n\n if (elapsed > fpsInterval) {\n\n then = now - (elapsed % fpsInterval);\n\n analyser.getByteFrequencyData(dataArrayAlt);\n\n let amp = 0;\n let freq = null;\n for (let i = low; i <= high; i += 1) {\n // Collect the highest frequency\n // if (dataArrayAlt[i] > 100) {\n // mem.push(i);\n // }\n if (dataArrayAlt[i] > amp) {\n amp = dataArrayAlt[i];\n freq = i;\n }\n }\n mem[freq] = amp;\n count++;\n if (count === 10) {\n // let domFreq = 0;\n // for (let frequency in mem) {\n // if (mem[frequency] > domFreq) {\n // domFreq = mem[frequency];\n // }\n // }\n mem = {};\n count = 0;\n song[currentStanza].push(mem);\n }\n // // Include at this point in time on the current stanza the highest frequency\n // if (freq) song[currentStanza].push(freq);\n }\n };\n\n computeFFT();\n }", "function addNewMusic(responseText, songData) {\n let newSongData = responseText;\n // console.log(\"TESTING\", musicProgram.testVar);\n newSongData.forEach(function(object){\n songData.unshift(object);\n songPrint(songData);\n });\n }", "function songRandomiser(arr) {\n let random = Math.floor(Math.random() * arr.length);\n let songObj = {\n title: arr[random].song,\n singer: arr[random].artist\n }\n return songObj;\n \n}", "addTrack(track) {\n let playlistTracks = this.state.playlistTracks;\n if (playlistTracks.find(savedTrack => savedTrack.id === track.id)) {\n return;\n }\n playlistTracks.unshift(track);\n this.setState({ playlistTracks: playlistTracks });\n }", "function sortPlaylist() {\n playlistArr = Object.entries(livePlaylist);\n\n if (playlistArr.length > 2) {\n var sorted = false;\n while (!sorted) {\n sorted = true;\n for (var i = 1; i < playlistArr.length - 1; i++) {\n if ((playlistArr[i][1].upvote < playlistArr[i + 1][1].upvote)) {\n sorted = false;\n var temp = playlistArr[i];\n playlistArr[i] = playlistArr[i + 1];\n playlistArr[i + 1] = temp;\n // })\n }\n // playlistArr[i][1].index = i;\n }\n }\n }\n return playlistArr;\n}", "async cleanUpMusic() {\n const docs = await this.db.getDocuments('music');\n const hashes = {};\n \n for(let i = 0; i < docs.length; i++) {\n const doc = docs[i];\n \n if(\n !doc.fileHash || \n typeof doc.fileHash != 'string' ||\n (\n !this.isFileAdding(doc.fileHash) && \n !await this.hasFile(doc.fileHash) &&\n await this.db.getMusicByFileHash(doc.fileHash)\n )\n ) {\n await this.db.deleteDocument(doc);\n continue;\n }\n\n hashes[doc.fileHash] = true;\n }\n\n await this.iterateFiles(async filePath => {\n try {\n const hash = path.basename(filePath);\n\n if(!hashes[hash] && !this.isFileAdding(hash) && !await this.db.getMusicByFileHash(hash)) {\n await this.removeFileFromStorage(hash);\n }\n }\n catch(err) {\n this.logger.warn(err.stack);\n }\n });\n }", "function next_song(){\r\n if(index_no<All_song.length - 1){ //Verifica que el indice no sea mayor que el largo de la lista\r\n index_no+=1;//Cambia el indice en 1 al siguiente indice\r\n load_track(index_no);//Carga la canción\r\n playsong();//Reproduce la cancion\r\n }else{\r\n index_no = 0;//Cuando el indice supera la longitud de la lista se vuelve 0\r\n load_track(index_no);//Carga la canción\r\n playsong();//Reproduce la cancion\r\n }\r\n }", "getTracks() {\n let results = [];\n\n if (!this.currentArtist && !this.currentName) {\n for (let i = 0; i < this.tracks.length; ++i) {\n results.push(this.tracks[i].title);\n }\n }\n else {\n if (this.currentArtist) {\n let artistId = _getArtistId();\n\n for (let i = 0; i < this.tracks.length; ++i) {\n if (this.tracks.artistId === artistId) {\n results.push(this.tracks[i].title);\n }\n }\n }\n\n if (this.currentAlbum) {\n let albumId = _getAlbumId();\n let filteredResults = [];\n\n for (let i = 0; i < results.length; ++i) {\n if (results.albumId === albumId) {\n results.push(this.tracks[i].title);\n }\n }\n\n results = filteredResults;\n }\n }\n\n return results;\n }", "function repopulateArray() {\n molecules = [];\n createCanvas(700, 700);\n\n for (var i = 0; i < config.numOfMols; i++) {\n new Molecule(random(this.width), random(this.height), random(5, this.maxMolSize));\n molecules.push(new Molecule(i));\n }\n\n }", "function makeArrayOfThreeNumbers() {\n//set oldPicsArray equals to newPicsArray because we need to prevent each time the code runs it would wipe out the previous array. The \"For\" loops (set up later in the code) will helps this run. This essentially turn new array into old array and so on as it runs through the loop.\n oldPicsArray[0] = newPicsArray[0];\n oldPicsArray[0] = newPicsArray[0];\n oldPicsArray[0] = newPicsArray[0];\n\n// Below is the logic to prevent duplicates with prior set of images (compare newPicsArray with newPicsArray) and within current set of images (compare newPicsArray with oldPicsArray)\n\n // set initial array to a random set to 3 numbers with indexes [0], [1], [2]\n newPicsArray[0] = rand();\n // while loop to rule out duplicate between new array index [0] and the old(\"next\") array index [0] , [1] and [2]\n while (newPicsArray[0] === oldPicsArray[0] || newPicsArray[0] === oldPicsArray[1] || newPicsArray[0] === oldPicsArray[2]) {\n // console.log(newPicsArray);\n //after it has ruled out that there is no duplicate, set the array index [0] to a random number\n newPicsArray[0] = rand();\n }\n\n newPicsArray[1] = rand();\n // first: validate within the new array that there's no duplicate between index [0] and [1]. Note: we didnt' have to worry about that for the newPicsArray[0] above because there wasn't any number generated prior to it.\n //second: rule out duplicate between new array index [1] and the old(\"next\") array index [0], [1], [2]\n while (newPicsArray[1] === newPicsArray[0] || newPicsArray[1] === oldPicsArray[0] || newPicsArray[1] === oldPicsArray[1] || newPicsArray[1] === oldPicsArray[2]) {\n //after it has ruled out that there is no duplicate, set the array index [1] to a random number\n newPicsArray[1] = rand();\n }\n\n newPicsArray[2] = rand();\n //first: validate within the new array that there's no duplicate between index [0] and [1] and [2]. That is index [2] # [0] # [1]\n //second: rule out duplicate between new array index [2] and the old(\"next\") array index [0], [1], [2]\n while (newPicsArray[2] === newPicsArray[0] || newPicsArray[2] === newPicsArray[1] || newPicsArray[2] === oldPicsArray[0] || newPicsArray[2] === oldPicsArray[1] || newPicsArray[2] === oldPicsArray[2]) {\n //after it has ruled out that there is no duplicate, set the array index [2] to a random number\n newPicsArray[2] = rand();\n }\n\n}" ]
[ "0.625816", "0.6160294", "0.6153754", "0.60650957", "0.6040407", "0.60079885", "0.5992116", "0.5948826", "0.59356004", "0.59153634", "0.58729434", "0.58645564", "0.5855034", "0.5844271", "0.58163667", "0.58055615", "0.5768132", "0.57142323", "0.570434", "0.5682144", "0.5668855", "0.5642018", "0.5637481", "0.56223875", "0.5613155", "0.5607542", "0.5600295", "0.5594296", "0.55863875", "0.5553493", "0.55464005", "0.5543529", "0.55270684", "0.55131537", "0.5506891", "0.55041695", "0.55024856", "0.54951704", "0.5493118", "0.5488141", "0.54801714", "0.5470736", "0.54681104", "0.5457495", "0.54489213", "0.54462945", "0.54397285", "0.5439147", "0.54340667", "0.5432935", "0.5411351", "0.54082507", "0.5404948", "0.53991467", "0.53918016", "0.5361366", "0.53521305", "0.5339037", "0.5330119", "0.5319948", "0.5311485", "0.5308762", "0.5300685", "0.5298366", "0.5290805", "0.5290422", "0.5290087", "0.5290078", "0.52844566", "0.52823216", "0.5275827", "0.5272203", "0.52662915", "0.5264669", "0.52587295", "0.5258174", "0.5246379", "0.52415603", "0.5238334", "0.5234693", "0.5229408", "0.5228555", "0.5212203", "0.52030754", "0.5197164", "0.5197152", "0.5196315", "0.5192133", "0.51883763", "0.5179912", "0.5176512", "0.51724875", "0.5170882", "0.51644206", "0.51580614", "0.5156585", "0.5151058", "0.51473004", "0.514674", "0.51432353" ]
0.60283417
5
The API will call this function when the video player is ready.
function onPlayerReady(event) { event.target.playVideo(); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function videoReady() { }", "function onPlayerReady(event) {\n Controller.load_video();\n }", "function videoReady() {\n console.log('Video is ready!!!');\n}", "function onPlayerReady(event) {\n event.target.loadVideo();\n }", "function onPlayerReady(event) {\n videosLoaded++;\n allVideosLoaded();\n}", "function onPlayerReady(event) {\n event.target.loadVideoById(link,0,'medium');\n event.target.playvideo();\n\t invokeAtIntervals();\n\n }", "function onPlayerReady(event) {\n event.target.playVideo();\n }", "function onPlayerReady(event) {\n event.target.playVideo();\n }", "function onPlayerReady(event) {\n event.target.playVideo();\n }", "function onPlayerReady(event) {\r\n event.target.playVideo();\r\n }", "function onPlayerReady(event) {\n event.target.playVideo();\n }", "function onPlayerReady(event) {\n\t\t\tevent.target.playVideo();\n\t\t}", "function onPlayerReady(event) {\n event.target.playVideo();\n\n }", "function onPlayerReady(event) {\n event.target.playVideo();\n }", "function onPlayerReady(event) {\n event.target.playVideo();\n }", "function onPlayerReady(event) {\n\n\tloadVideoId();\n\tevent.target.playVideo();\n\n}", "function onPlayerReady(event) {\n // event.target.playVideo();\n changeStatus(\"Pause\");\n }", "function onPlayerReady(event) {\n\t event.target.playVideo();\n }", "function startVideo() {\n video.isReady = true;\n}", "function onPlayerReady(event) {\n event.target.playVideo();\n }", "function onPlayerReady(event) {\r\n getPlayerData( player.getDuration(), player.getCurrentTime() ); \r\n event.target.playVideo();\r\n }", "function onPlayerReady(event) {\n event.target.playVideo();\n sendVideoProgressToAndroidDevice(); \n startVideoProgress();\n startAdTimer(testAd);\n }", "function onPlayerReady(event) {\n event.target.playVideo();\n console.log(\"start!!\");\n}", "function onPlayerReady(event) {\n\tevent.target.playVideo();\n}", "function onPlayerReady(event) {\n console.log('onPlayerREady', event);\n event.target.playVideo();\n }", "function onPlayerReady(event) {\n\t// When the player is created, but not started\n\tconsole.log(\"Video Started\")\n\tlivePlayer.player = event.target\n\t// livePlayer.player.mute()\n\tlivePlayer.player.seekTo(0)\n\tlivePlayer.player.playVideo()\n\n\t$('#vidTitle').text(livePlayer.player.getVideoData().title)\n\t$('#vidAuthor').text(\"By \" + livePlayer.player.getVideoData().author)\n\n\n\tvar t = setInterval(function(){\n\t\tif(livePlayer.player.getVideoData().author != \"\"){\n\t\t\t$('#vidAuthor').text(\"By \" + livePlayer.player.getVideoData().author)\n\t\t\tclearInterval(t)\n\t\t}\n\t}, 100);\n}", "_onReady (videoId) {\n if (this.destroyed) return\n\n this._ready = true\n\n // Once the player is ready, always call `load(videoId, [autoplay, [size]])`\n // to handle these possible cases:\n //\n // 1. `load(videoId, true)` was called before the player was ready. Ensure that\n // the selected video starts to play.\n //\n // 2. `load(videoId, false)` was called before the player was ready. Now the\n // player is ready and there's nothing to do.\n //\n // 3. `load(videoId, [autoplay])` was called multiple times before the player\n // was ready. Therefore, the player was initialized with the wrong videoId,\n // so load the latest videoId and potentially autoplay it.\n this.load(this.videoId, this._autoplay, this._start)\n\n this._flushQueue()\n }", "function onPlayerReady(event) {\n //event.target.playVideo();\n event.target.pauseVideo();\n }", "function onPlayerReady(event) {\r\n event.target.playVideo();\r\n}", "function onPlayerReady(event) {\n event.target.playVideo();\n}", "function onPlayerReady(event) {\n event.target.playVideo();\n}", "function onPlayerReady(event) {\n event.target.playVideo();\n}", "function onPlayerReady(event) {\n event.target.playVideo();\n}", "function onPlayerReady(event) {\n event.target.playVideo();\n}", "function onPlayerReady(event) {\n\t//event.target.playVideo();\n}", "function onPlayerReady(event) {\n event.target.playVideo();\n}", "function onPlayerReady(event) {\n event.target.playVideo();\n}", "function onPlayerReady(event) {\n event.target.playVideo();\n}", "function onPlayerReady(event) {\n event.target.playVideo();\n}", "function onPlayerReady(event) {\n event.target.playVideo();\n}", "function onPlayerReady(event) {\n event.target.playVideo();\n}", "function onPlayerReady(event) {\n event.target.playVideo();\n}", "function onPlayerReady(event) {\n event.target.playVideo();\n}", "function onPlayerReady(event) {\n event.target.playVideo();\n}", "function onPlayerLoaded() {\n\t\tvideo.fp_play(0);\n\t\t//installControlbar();\n\t}", "function onPlayerReady(event) {\n // event.target.playVideo();\n }", "function onPlayerReady(event) {\n \tconsole.log('player! onPlayerReady');\n // event.target.playVideo();\n $win.trigger('yt-player:ready');\n // playNext();\n }", "function onPlayerReady(event) {\n event.target.playVideo();\n }", "function videoReady() {\n videoStatus.innerText = 'Video ready!';\n}", "function VideoPlayer_NotifyLoaded()\n{\n\t//update the video properties\n\tVideoPlayer_UpdateOptions(this.InterpreterObject);\n\t//update the video SRC\n\tVideoPlayer_UpdateSource(this.InterpreterObject);\n}", "function onPlayerReady(event) {\n console.log(\"GO Video\");\n // event.target.playVideo();\n}", "function onPlayerReady(evt) {\n evt.target.setPlaybackQuality('hd1080');\n var videoData = getVideoOptions(evt);\n var videoTitle = evt.target.getVideoData().title;\n playOnClickCheck();\n\n // Prevent tabbing through YouTube player controls until visible\n document.getElementById(videoData.id).setAttribute('tabindex', '-1');\n\n sizeBackgroundVideos();\n setButtonLabels(videoData.videoWrapper, videoTitle);\n\n // Customize based on options from the video ID\n if (videoData.type === 'background') {\n evt.target.mute();\n privatePlayVideo(videoData.id);\n }\n\n videoData.videoWrapper.classList.add(classes.loaded);\n \n \tdocument.getElementById(\"home-video-control-btn\").addEventListener(\"click\", function(){ \n console.log(\"video play\");\n videoPlayers[videoData.id].seekTo(280);\n document.getElementById(\"Video-161599832034872565\").style.display = \"block\";\n document.getElementById(\"Video-161599832034872565\").style.opacity = 1;\n document.getElementById(\"home-video-control-btn\").style.display = \"none\";\n });\n \n \tdocument.getElementById(\"mb-home-video-control-btn\").addEventListener(\"click\", function(){ \n console.log(\"video play\");\n videoPlayers[videoData.id].seekTo(280);\n document.getElementById(\"Video-161599832034872565\").style.display = \"block\";\n document.getElementById(\"Video-161599832034872565\").style.opacity = 1;\n document.getElementById(\"mb-home-video-control-btn\").style.display = \"none\";\n }); \n \n }", "function onPlayerReady(event) {\n \n}", "function onPlayerReady(){\n\t\tg_isPlayerReady = true;\n\t\t\n\t}", "function onPlayerReady(event) {\n //writeUserData(video)\n //event.target.playVideo();\n}", "function onPlayerReady()\n{\n\tvar videotime = 0;\n\tvar timeupdater = null;\n \tfunction updateTime()\n \t{\n \tvar oldTime = videotime;\n \tif(player && player.getCurrentTime)\n \t{\n \t\tvideotime = player.getCurrentTime();\n \t}\n \tif(videotime !== oldTime)\n \t{\n \t\tonProgress(videotime);\n \t}\n \t}\n \ttimeupdater = setInterval(updateTime, 100);\n}", "function onPlayerReady(event) {\n event.target.pauseVideo();\n }", "function onPlayerReady(event) {\n // event.target.playVideo();\n}", "function onPlayerReady (event) {\n event.target.playVideo()\n}", "static onYouTubeIframeAPIReady() {\n\t\tGlobals.player = new YT.Player('player', {\n\t\t\theight : '90%',\n\t\t\twidth : '90%',\n\t\t\tvideoId : '',\n\t\t\tevents : {\n\t\t\t\t'onReady' : YouTubeAPI.onPlayerReady,\n\t\t\t\t'onStateChange' : YouTubeAPI.onStateChange\n\t\t\t}\n\t\t});\n\t}", "function onPlayerReady(event) {\n \n console.log('onPlayerReady:'+event.data);\n //event.target.playVideo();\n}", "function onYouTubeIframeAPIReady() {\n player = new YT.Player('player', {\n videoId: /[?&]v=([^&]+)(?:&|$)/.exec(window.location.search)[1],\n events: {\n onReady: onPlayerReady,\n onStateChange: onPlayerStateChange\n }\n });\n }", "function onPlayerReady(event) {\r\n //event.target.playVideo();\r\n}", "function onPlayerReady(event) {\n // event.target.playVideo();\n}", "function onPlayerReady(event) {\r\n playerReady = true;\r\n\r\n }", "function onYouTubePlayerReady(playerId) {\r\n plController.onPlayerReady()\r\n}", "function onPlayerReady(event) {\n console.log(\"Player is ready\");\n }", "async init() {\n // FIXME: VideoLink appears after 1.5 seconds, it's too slow, find better way\n this.vidlink = null;\n this.video = await Player.untilVideoAppears();\n\n this.ads = new PlayerAds();\n this.events = new PlayerEvents(this.video);\n this.timeline = new PlayerTimeline(this.video);\n this.annotations = new PlayerAnnotations();\n\n this.rightControls = Player.findRightControls();\n this.controlsContainer = Player.findControlsContainer();\n\n Player.untilVideoLinkAppears().then((link) => { this.vidlink = link; });\n }", "onPlayerReady(evt) {\n\t\tevt.target.setPlaybackQuality('hd1080');\n\t\tvar videoData = this.getVideoOptions(evt);\n\t\tvar videoTitle = evt.target.getVideoData().title;\n\t\tthis.playOnClickCheck();\n\n\t\t// Prevent tabbing through YouTube player controls until visible\n\t\tdocument.getElementById(videoData.id).setAttribute('tabindex', '-1');\n\n\t\tthis.sizeBackgroundVideos();\n\t\tthis.setButtonLabels(videoData.videoWrapper, videoTitle);\n\n\t\t// Customize based on options from the video ID\n\t\tif (videoData.type === 'background') {\n\t\t\tevt.target.mute();\n\t\t\tthis.privatePlayVideo(videoData.id);\n\t\t}\n\n\t\tvideoData.videoWrapper.classList.add(classes.loaded);\n\t}", "function onPlayerReady() {\r\n player.playVideo();\r\n /*let time = player.getCurrentTime();\r\n if(player.stopVideo()){\r\n let time2 = player.getCurrentTime();\r\n \r\n player.playVideo(time2);\r\n }*/\r\n \r\n }", "function onPlayerReady(event) {\n console.log(\"PLAYER READY\");\n\n // if we want the video to autoplay we can uncomment out this code\n // (although we could set 'autoplay': 1 in the \"playerVars\" of the YT.Player object)\n // event.target.playVideo();\n}", "function onPlayerReady(event) {\n event.target.playVideo();\n\n // Get the duration of the currently playing video\n const videoDuration = event.target.getDuration();\n \n // When the video is playing, compare the total duration\n // To the current passed time if it's below 2 and above 0,\n // Return to the first frame (0) of the video\n // This is needed to avoid the buffering at the end of the video\n // Which displays a black screen + the YouTube loader\n setInterval(function (){\n const videoCurrentTime = event.target.getCurrentTime();\n const timeDifference = videoDuration - videoCurrentTime;\n \n if (2 > timeDifference > 0) {\n event.target.seekTo(0);\n }\n }, 1000);\n}", "function onPlayerReady(event) {\n // event.target.playVideo();\n event.target.loadPlaylist(listeVideosNature);\n}", "function onPlayerReady(event) {\n //event.target.playVideo();\n}", "function onPlayerReady(event) {\n //event.target.playVideo();\n}", "function onPlayerReady(e) {\n}", "function onPlayerReady(event) { \n //event.target.playVideo();\n detenerVideo();\n}", "function ytOnPlayerReady(event) {\n event.target.playVideo();\n}", "function onPlayerReady(event) {\n console.log(\"Player ready\");\n console.log(player.getPlayerState());\n console.log(event.data);\n console.log(event.target);\n event.target.playVideo();\n}", "function onPlayerReady(event) {\n console.log('player ready');\n}", "function onPlayerReady(event) {\n console.log(\"player is ready\");\n event.target.pauseVideo();\n}", "function initVideo() {\n \n Enabler.loadModule(studio.module.ModuleId.VIDEO, function() {\n // Video module loaded.\n var videoElement = document.getElementById('video');\n studio.video.Reporter.attach('video', videoElement);\n });\n\n video.addEventListener('ended',OnComplete);\n video.oncanplaythrough = OnStart();\n videoContainer.style.visibility = \"visible\";\n}", "function onPlayerReady(event) {\n\t\tconsole.log(\"onPlayerReady\", arguments); //This shows in console\n\t\tevent.target.playVideo();\n\t}", "function onYouTubePlayerReady(playerId){\n app.videoView.player = document.getElementById(\"player\");\n app.videoView.player.addEventListener(\"onStateChange\", \"onYouTubeStateChange\");\n app.videoView.addVideoEvents();\n}", "function onPlayerReady() {\n // Yes it is intentionally left empty. DO NOT remove this function!\n}", "function videoReady() {\n select('#videoStatus').html('Video ready!');\n}", "function videoReady() {\n select('#videoStatus').html('Video ready!');\n}", "function onYouTubeIframeAPIReady() {\n _player = new YT.Player('player', {\n videoId: videoId,\n events: {\n 'onReady': onPlayerReady,\n 'onStateChange': onPlayerStateChange\n }\n });\n }", "function onYouTubePlayerAPIReady() {\n\t // create the global player from the specific iframe (#video)\n\t player = new YT.Player('video', {\n\t events: {\n\t // call this function when player is ready to use\n\t 'onReady': onPlayerReady\n\t }\n\t });\n\t}", "function initialize() {\n // will create HTML5 video element in staging area if not present\n getDOMVideo();\n isInitialized = true;\n }", "function onPlayerReady(event) {\n videoUrl.value = player.getVideoUrl();\n}", "function onYouTubeIframeAPIReady() {\n theme.Video.loadVideos();\n \n var home_player;\n function onYouTubeIframeAPIReady() {\n home_player = new YT.Player('Video-161599832034872565', {\n events: {\n 'onReady': onPlayerReady,\n 'onStateChange': onPlayerStateChange\n }\n });\n }\n}", "function onYouTubePlayerAPIReady(){mejs.YouTubeApi.iFrameReady()}", "function onYouTubePlayerAPIReady(){mejs.YouTubeApi.iFrameReady()}", "function onYouTubePlayerAPIReady(){mejs.YouTubeApi.iFrameReady()}", "function onPlayerReady(event) {\r\n event.target.pauseVideo();\r\n }", "function onPlayerReady(evt) {\n\t\tevt.target.setPlaybackQuality('hd1080');\n\t\tvar videoData = getVideoOptions(evt);\n\n\t\tplayOnClickCheck();\n\n\t\t// Prevent tabbing through YouTube player controls until visible\n\t\t$('#' + videoData.id).attr('tabindex', '-1');\n\n\t\tsizeBackgroundVideos();\n\n\t\t// Customize based on options from the video ID\n\t\tswitch (videoData.type) {\n\t\t\tcase 'background-chrome':\n\t\t\tcase 'background':\n\t\t\tevt.target.mute();\n\t\t\t// Only play the video if it is in the active slide\n\t\t\tif (videoData.$parentSlide.hasClass(classes.currentSlide)) {\n\t\t\t\tprivatePlayVideo(videoData.id);\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\n\t\tvideoData.$parentSlide.addClass(classes.loaded);\n\t}", "_onReady (videoId) {\n if (this.destroyed) return\n\n this._ready = true\n\n // If the videoId that was loaded is not the same as `this.videoId`, then\n // `load()` was called twice before `onReady` fired. Just call\n // `load(this.videoId)` to load the right videoId.\n if (videoId !== this.videoId) {\n this.load(this.videoId)\n }\n\n this._flushQueue()\n }", "function onYouTubePlayerAPIReady() {\n\t// create the global player from the specific iframe (#video)\n\tplayer = new YT.Player('video', {\n\t\tevents: {\n\t\t\t// call this function when player is ready to use\n\t\t\t'onReady': onPlayerReady\n\t\t}\n\t});\n}", "function onYouTubeIframeAPIReady() {\n //creates the player object\n var yt_player_iframe = new YT.Player('yt_player_iframe');\n \n console.log('Video API is loaded');\n \n //subscribe to events\n yt_player_iframe.addEventListener(\"onReady\", \"onYouTubePlayerReady\");\n yt_player_iframe.addEventListener(\"onStateChange\", \"onYouTubePlayerStateChange\");\n }" ]
[ "0.8600132", "0.8431369", "0.81294066", "0.80556196", "0.7933902", "0.7930072", "0.79006296", "0.79006296", "0.79006296", "0.7893968", "0.7857887", "0.78502524", "0.7843109", "0.78053206", "0.7789895", "0.7766721", "0.7742206", "0.773466", "0.7699259", "0.76964366", "0.7682772", "0.76399744", "0.7636381", "0.76303023", "0.7618543", "0.7610756", "0.7595006", "0.7571151", "0.75679827", "0.754405", "0.754405", "0.754405", "0.754405", "0.754405", "0.754143", "0.7541292", "0.7541292", "0.7541292", "0.7541292", "0.7541292", "0.7541292", "0.7541292", "0.7541292", "0.7541292", "0.7532342", "0.75301445", "0.7528511", "0.75251186", "0.7521351", "0.7499135", "0.74938565", "0.74846506", "0.7473874", "0.7467237", "0.7464256", "0.745933", "0.745197", "0.7450366", "0.7448208", "0.7439126", "0.7427684", "0.7425785", "0.74224764", "0.7402778", "0.7389771", "0.73863953", "0.7368063", "0.73674107", "0.7357852", "0.7343948", "0.7330047", "0.7317319", "0.73158526", "0.73135626", "0.73135626", "0.7312842", "0.7303453", "0.7290552", "0.7290262", "0.7289478", "0.72868913", "0.72845334", "0.72783375", "0.72654366", "0.7256469", "0.72507346", "0.72507346", "0.72451997", "0.72348446", "0.7178128", "0.717504", "0.7165703", "0.7163186", "0.7163186", "0.7163186", "0.71538544", "0.71499246", "0.71432745", "0.713169", "0.71282566" ]
0.7571747
27
update the musicArray with the ids scriptInput and scriptButton and prevent duplicates
function updateMusicArray() { let addedVideo = scriptInput.value; let addedVideoId = addedVideo.slice(addedVideo.indexOf("v="),addedVideo.length); addedVideoId = addedVideoId.slice(2, addedVideoId.length); if (musicArray.includes(addedVideoId)) { alert("Video is already included in the track-list."); } else { musicArray.unshift(addedVideoId); document.getElementById("musicArrayText").innerText = musicArray; } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function soundSetup(){\n updateState(false, false);\n varSong = [];\n varSongID = [];\n currentVarSongIndex = 0;\n varSongLength = 4;\n mainSong = new Howl({\n src: ['Songs/1_main.mp3'],\n loop:true\n });\n for(var x = 1; x<=varSongLength; x++){\n varSong[x-1] = new Howl({\n src: ['Songs/1_var'+x+'.mp3']\n });\n}\nresetIDs();\n\n}", "function updateSong() {\n var updatedSong = {\n songName: songNameInput.value,\n albumTitle: albumTitleInput.value,\n playCount: playCountInput.value,\n releaseYear: releaseYearInput.value,\n youTubeLink: youTubeLinkInput.value\n };\n //Remove element and insert new updated song into songs array\n songs.splice(updateSongIndexArray[1], 1, updatedSong);\n //Switch buttons back\n updateButton.classList.add(\"hidden\");\n createButton.classList.remove(\"hidden\");\n //Clear out the input forms\n songNameInput.value = \"\";\n albumTitleInput.value = \"\";\n playCountInput.value = \"\";\n releaseYearInput.value = \"\";\n youTubeLinkInput.value = \"\";\n //Rerender the updated data\n renderData();\n}", "handleMusicButtonClicked(musicButtonId){\n let buttons = [...this.state.buttons];\n\n\n if(this.props.mappingSound){\n buttons[musicButtonId-1].value = this.props.mappingSound;\n this.props.onMappingDone(\"\");\n return;\n }\n\n if(buttons[musicButtonId-1].value === \".\"){return;}//if some button has no sound\n\n let soundInfo = this.props.getInfoToSound(buttons[musicButtonId-1].value, false);\n\n if(soundInfo.uploadedAudio !== undefined){//if some uploaded sound should be played\n var dst = new ArrayBuffer(soundInfo.uploadedAudio.byteLength);\n new Uint8Array(dst).set(new Uint8Array(soundInfo.uploadedAudio));\n soundInfo.uploadedAudio = dst;\n }else{//if its a standard sound\n soundInfo.URL = process.env.PUBLIC_URL+'/padSoundAudio/'+ buttons[musicButtonId-1].value +'.wav';\n }\n new PadSoundPlayer(soundInfo);\n }", "function playMusic(){\n var songIndex = Math.floor(Math.random()*songs.length);\n songSelect = window.songs[Math.floor(Math.random()*songs.length)];\n var sound = soundManager.createSound({\n id: songSelect.filename,\n url: songSelect.url\n });\n//a function that will play the song on the click of a button an the play icon\n sound.play();\n\n for (var i = 0; i < buttons.length; i++) {\n\n buttons[i].innerHTML=songSelect.answers[i].answer;\n \n \n \n }\n}", "function addToCookiePl() {\n let addButtonArr = document.getElementsByClassName(\"cookiepl\");\n //Split the song ids in cookie string and add each id to mapObj with a value true\n let mapObj = {};\n let cookieplOG = getCookie(\"cookiepl\");\n let cookieplOGArr = cookieplOG.split(\"-\");\n for (let z = 1; z < cookieplOGArr.length; z++) {\n mapObj[cookieplOGArr[z]] = true;\n }\n //Callback function for event listener'click'\n function onClickAdd(event) {\n let cookiepl = getCookie(\"cookiepl\");\n //Adds song id to cookie string\n cookiepl = cookiepl + \"-\" + event.target.id;\n console.log(cookiepl);\n setCookie(\"cookiepl\", cookiepl, 1);\n event.target.classList.remove(\"btn-info\");\n event.target.classList.add(\"btn-danger\");\n event.target.innerText = \"ADDED TO COOKIE PLAYLIST\";\n //Removes 'click' event listener from button after song has been added to playlist cookie\n event.target.removeEventListener(\"click\", onClickAdd, false);\n }\n //Adds event listener to all buttons \n for (let i = 0; i < addButtonArr.length; i++) {\n addButtonArr[i].addEventListener(\"click\", onClickAdd);\n const addBut = addButtonArr[i];\n const addButID = addBut.id;\n //if song is already in cookie playlist, change button display \n if (mapObj[addButID]) {\n addBut.classList.remove(\"btn-info\");\n addBut.classList.add(\"btn-danger\");\n addBut.innerText = \"ADDED TO COOKIE PLAYLIST\";\n addBut.removeEventListener(\"click\", onClickAdd, false);\n }\n }\n}", "function amplitude_shuffle_songs(){\n var amplitude_nodes = document.getElementById('amplitude-playlist').getElementsByTagName('audio');\n amplitude_shuffle_playlist_temp = new Array(amplitude_nodes.length);\n for (i=0; i<amplitude_nodes.length; i++) {\n amplitude_shuffle_playlist_temp[i] = amplitude_nodes[i].getAttribute(\"id\");\n }\n for (i = amplitude_nodes.length - 1; i > 0; i--){\n var amplitude_rand_num = Math.floor((Math.random()*i)+1);\n amplitude_shuffle_swap(amplitude_shuffle_playlist_temp, i, amplitude_rand_num);\n }\n\n amplitude_shuffle_list = amplitude_shuffle_playlist_temp;\n}", "function runPiano() {\n\t// input the individual note into a json object and uploaded to the\n\t// VF.StaveNote function in order to print the music note notation\n\n\t// json2obj function can convert the three array list, alphabet, repeats, and speed sound\n\t// into a object\n\tfunction json2obj(notes_list, repeat_list, timeout_list){\n\t\tvar i = 1;\n\t\t// verifying wheter there is no duplicate\n\t\tif (i == repeat_list) {\n\t\t\t// appending into a new array\n\t\t\tnotes_parsed.push(notes_list)\n\t\t\tnotes_time.push(timeout_list)\n\t\t\t// generating the syntax string in order to converted into a json\n\t\t\tvar json1 = '{\"keys\": [\"';\n\t\t\tvar json2 = notes_list + '/4\"], \"duration\": \"q\"}';\n\t\t\tvar json3 = json1.concat(json2)\n\t\t\t// parse the json into a object\n\t\t\tconst obj = JSON.parse(json3);\n\t\t\t// create a note using Vexflow\n\t\t\tvar note = new VF.StaveNote(obj);\n\t\t\t// append the final result\n\t\t\tnotes.push(note);\n\t\t\treturn notes;\n\t\t} else {\n\t\t\t\t// generate the duplicate audio\n\t\t\t\twhile( i <= repeat_list)\n\t\t\t\t{\n\t\t\t\t// append the input into a new array\n\t\t\t\tnotes_parsed.push(notes_list)\n\t\t\t\tnotes_time.push(timeout_list)\n\t\t\t\t// generating the syntax string in oreder to converted into a json\n\t\t\t\tvar json1 = '{\"keys\": [\"';\n\t\t\t\tvar json2 = notes_list + '/4\"], \"duration\": \"q\"}';\n\t\t\t\tvar json3 = json1.concat(json2)\n\t\t\t\t// parse the json into a object\n\t\t\t\tconst obj = JSON.parse(json3);\n\t\t\t\t// create a note using Vexflow\n\t\t\t\tvar note = new VF.StaveNote(obj);\n\t\t\t\t\n\t\t\t\t// append the input\n\t\t\t\tnotes.push(note);\n\t\t\t\ti = i + 1;\n\t\t\t\t\n\t\t\t}\n\t\t\t// return the final result\n\t\t\treturn notes;\n\t\t}\n\t\t\n\t}\n\n\t// getUnique function will eliminate any duplicate in the array\n\tfunction getUnique(array) {\n\t\tvar uniqueArray = [];\n\t\t// Loop through array values\n\t\tfor (i = 0; i < array.length; i++) {\n\t\t\t// check wheter there is no duplicate\n\t\t\tif (uniqueArray.indexOf(array[i]) === -1) {\n\t\t\t\t// append into the array\n\t\t\t\tuniqueArray.push(array[i]);\n\t\t\t}\n\t\t}\n\t\t// return the result\n\t\treturn uniqueArray;\n\n\t}\n\t// try and catch used for Error Handling\n\ttry {\n\n\tvar complete_note_list = [\"A\", \"B\", \"C\", \"D\", \"E\", \"F\", \"G\"];\n\t// delete the lines\n\tnotes_raw = $(\"#input_notes\").val().split(/\\r?\\n/);\n\t\n\tlet onlyLetters = /[a-zA-Z]+/g\n\tlet onlyNumeric = /[+-]?(\\d+([.]\\d*)?(e[+-]?\\d+)?|[.]\\d+(e[+-]?\\d+)?)/g\n\tlet onlyFloat = /[+-]?(\\d+([.]\\d*)?(e[+-]?\\d+)?|[.]\\d+(e[+-]?\\d+)?)/g\n\t// generate an array only show the repetition\n\tnotes_repeat = $(\"#input_notes\").val().match(onlyNumeric).map(s => s.slice(0, 1));\n\t// generate an array only show the speed\n\tnotes_timeout = ($(\"#input_notes\").val().match(onlyFloat)).map(s => s.slice(1, 4));\n\t\n\n\t//////////////////////////////\n\t// Error Handling //\n\t/////////////////////////////\n\tvar max_repeat_numb_notes = 9;\n\t// Error try and catch\n\t// It constrains the user to use only one note per line.\n\n\t// This for loop clean the white spaces and appends into new string array\n\t// empty array\n\tnew_notes_raw = [];\n\tnotes_letter = [];\n\t// for loop go through alphabet notes input\n\tfor (m = 0; m < notes_raw.length; m++) {\n\t\t// trim every row that does have any white space\n\t\tnumber_rows = notes_raw[m].trim();\n\t\tif (Boolean(number_rows)) {\n\t\t\t// store the letter into a variable\n\t\t\tletter = number_rows.match(onlyLetters)[0];\n\t\t\t// append the letter,duplicate, and speed\n\t\t\tnew_notes_raw.push(number_rows);\n\t\t\t// append the letter\n\t\t\tnotes_letter.push(letter)\n\t\t}\n\t}\n\t\n\t\n\t// Sorting and Unique the Alphabet Notes\n\tsort_letters = notes_letter.sort();\n\tsort_uniq_letters = getUnique(sort_letters);\n\t\n\n\t// Debuginnin to see what is going on in the code\n\t/*console.log(new_notes_raw);\n\tconsole.log(notes_letter);\n\tconsole.log(sort_uniq_letters);\n\tconsole.log(complete_note_list);\n\tconsole.log(notes_repeat);\n\tconsole.log(notes_timeout);\n\t*/\n\t\n\n\t// Check the number of row per each line \n\t// if there is more than one note will stop the code\n\tfor (m = 0; m < new_notes_raw.length; m++) {\n\t\t// split the space of the input value note\n\t\tnumber_rows = new_notes_raw[m].split(\" \").length;\n\t\t\n\t\t//console.log(number_rows)\n\t\t// if there are two or more inputs in one row\n\t\tif (number_rows > 1) {\n\t\t\t// Give error to the user\n\t\t\tthrow \"Please add one note per line!\";\n\t\t} \n\n\t}\n\t// Use the filter command to determine the difference and it is not in the notes of the alphabet\n\tlet difference = sort_uniq_letters.filter(element => !complete_note_list.includes(element));\n\t//console.log(difference);\n\t// if there more than one in the difference array that means the user has alphabet that does not \n\t// follow the alphabet notes\n\tif (difference.length > 0 ) {\n\t\tthrow \"Please use first seven letters of the alphabet!\"\n\t}\n\t// Use only 1-9 repetitions\n\t// If statement will constraint the user and allow to use only certain number of repetitions\n\tif (max_repeat_numb_notes > 10){\n\t\tthrow \"Please use no more than 9 duplicates!\"\n\t}\n\n\t\n\t\n /////////////////////\n\t// Reference Notes //\n\t/////////////////////\n\n\t// It will print the symbol note notation for the user to help follow the audio\n\n\tVF1 = Vex.Flow;\n\t\n\t// Create an SVG renderer and attach it tot he DIV element named \"reference notes\"\n\tvar div1 = document.getElementById(\"reference_notes\")\n\n\tvar renderer = new VF1.Renderer(div1, VF1.Renderer.Backends.SVG);\n\n\tpx1=500;\n\t// Size SVG\n\trenderer.resize(px1+100, px1/4);\n\t// and get a drawing context\n\tvar context1 = renderer.getContext();\n\t\n\tcontext1.setFont(\"Times\", 10, \"\").setBackgroundFillStyle(\"#eed\");\n\n\tvar stave1 = new VF1.Stave(10, 0, px1);\n\n\tstave1.addClef(\"treble\");\n\t// Connect it to the rendering context and draw!\n\tstave1.setContext(context1).draw();\n\t// Generate your input notes\n\tvar notes_ref = [\n\t\tnew VF1.StaveNote({ keys: [\"a/4\"], duration: \"q\" }),\n\t\tnew VF1.StaveNote({ keys: [\"b/4\"], duration: \"q\" }),\n\t\tnew VF1.StaveNote({ keys: [\"c/4\"], duration: \"q\" }),\n\t\tnew VF1.StaveNote({ keys: [\"d/4\"], duration: \"q\" }),\n\t\tnew VF1.StaveNote({ keys: [\"e/4\"], duration: \"q\" }),\n\t\tnew VF1.StaveNote({ keys: [\"f/4\"], duration: \"q\" }),\n\t\tnew VF1.StaveNote({ keys: [\"g/4\"], duration: \"q\" })\n\t];\t\n\n\t// Create a voice in 4/4 and add above notes\n\tvar voice_ref = new VF1.Voice({ num_beats: 7, beat_value: 4 });\n\tvoice_ref.addTickables(notes_ref);\n\n\t// Format and justify the notes to 400 pixels.\n\tvar formatter1 = new VF1.Formatter().joinVoices([voice_ref]).format([voice_ref], px1);\n\n\t// Render voice\n\tvoice_ref.draw(context1, stave1);\n\t\n\n\t/////////////////////\n\t// Real-Time Notes //\n\t/////////////////////\n\n\tVF = Vex.Flow;\n\n\t// Create an SVG renderer and attach it to the DIV element named \"play piano\".\n\tvar div = document.getElementById(\"play_piano\")\n\tvar renderer = new VF.Renderer(div, VF.Renderer.Backends.SVG);\n\n\t//px = notes_letter.length * 500;\n\tpx=1000;\n\t// Configure the rendering context.\n\n\trenderer.resize(px+100, px/5);\n\tvar context = renderer.getContext();\n\t\n\tcontext.setFont(\"Arial\", 10, \"\").setBackgroundFillStyle(\"#eed\");\n\t// 13 notes = 500 px\n\t// Create a stave of width 400 at position 10, 40 on the canvas.\n\t\n\tvar stave = new VF.Stave(10, 0, px);\n\t\n\t// Add a clef and time signature.\n\t\n\tstave.addClef(\"treble\");\n\t// Connect it to the rendering context and draw!\n\tstave.setContext(context).draw();\n\t\n\t// empty array\n\tvar notes_parsed = []\n\tvar notes_time = []\n\tvar notes=[];\n\t\n\t\n\t// for loop will convert the array into json to object\n\tfor (index = 0; index < notes_raw.length; index++) {\n\t\t\tfor (n = 0; n < notes_raw.length; n++) {\n\t\t\t\tfor (i = 0; i < complete_note_list.length; i++){\n\t\t\t\t\t// compare if the notes are identical\n\t\t\t\t\tif (notes_raw[index][n] == complete_note_list[i]) {\n\t\t\t\t\t\t// call the json to object function\n\t\t\t\t\t\tnotes = json2obj(notes_raw[index][n], notes_repeat[index],notes_timeout[index]);\n\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t}\n\t}\n\n\n\t\n\tconsole.log(notes)\n\t\n\t// for loop determine whether the following notes belong to the \n\t// correct audio\n\ttiming = 0\n\t//index_ms_offset = 3000\n\t// Adding a weight to speed or slow down the audio note\n\tweight=30000;\n\tfor (index = 0; index < notes_parsed.length; index++) {\n\t\tif (notes_parsed[index] == 'A') {\n\t\t\t// Time delay\n\t\t\tsetTimeout( function() {\n\t\t\t// Play Audio\t\n\t\t\t\tnew Audio('media/high_a.mp3').play()\n\t\t\t}, weight*notes_time[index] * index)\n\t\t} else if (notes_parsed[index] == 'B' ) {\t\n\t\t\t// Time delay\n\t\t\tsetTimeout(function() {\n\t\t\t// Play Audio\t\n\t\t\t\tnew Audio('media/high_b.mp3').play()\n\t\t\t}, weight*notes_time[index] * index )\n\t\t} else if (notes_parsed[index] == 'C' ) {\n\t\t\t// Time delay\t\t\n\t\t\tsetTimeout(function() {\t\n\t\t\t// Play Audio\t\n\t\t\t\tnew Audio('media/high_c.mp3').play()\n\t\t\t}, weight*notes_time[index] * index )\n\t\t} else if (notes_parsed[index] == 'D' ) {\n\t\t\t// Time delay\t\n\t\t\tsetTimeout(function() {\n\t\t\t// PLay Audio\t\n\t\t\t\tnew Audio('media/high_d.mp3').play()\n\t\t\t}, weight*notes_time[index] * index ) \n\t\t} else if (notes_parsed[index] == 'E' ) {\n\t\t\t\n\t\t\t// Time Audio\n\t\t\tsetTimeout(function() {\n\t\t\t// Play Audio\n\t\t\t\tnew Audio('media/high_e.mp3').play()\n\t\t\t}, weight*notes_time[index] * index )\n\t\t} else if (notes_parsed[index] == 'F') {\n\t\t\t\n\t\t\t// Time Audio\n\t\t\tsetTimeout(function() {\n\t\t\t// Play Audio\n\t\t\t\tnew Audio('media/high_f.mp3').play()\n\t\t\t}, weight*notes_time[index] * index )\n\t\t} else if (notes_parsed[index] == 'G') {\n\t\t\t\n\t\t\t// Time Audio\n\t\t\tsetTimeout(function() {\n\t\t\t// Play Audio\t\n\t\t\t\tnew Audio('media/high_g.mp3').play()\n\t\t\t}, weight*notes_time[index] * index )\n\n\t\t}\n\t}\n\t\n\t//alert(notes_parsed)\n\tconsole.log(notes);\n\n\n\n// Create a voice in 4/4 and add above notes\nvar voice = new VF.Voice({num_beats: notes_parsed.length, beat_value: 4});\nvoice.addTickables(notes);\n\n// Format and justify the notes to 400 pixels.\nvar formatter = new VF.Formatter().joinVoices([voice]).format([voice], px);\n\n// Render voice\nvoice.draw(context, stave);\n\n\n\t// Javascript Buttons -> HTML5\n\tvar clearBtn = document.getElementById('ClearNote');\n\tclearBtn.addEventListener('click', e => {\n\t\t\n\t\tconst staff1 = document.getElementById('reference_notes')\n\t\twhile (staff1.hasChildNodes()) {\n\t\t\tstaff1.removeChild(staff1.lastChild);\n\t\t}\n\n\t\tconst staff2 = document.getElementById('play_piano')\n\t\twhile (staff2.hasChildNodes()) {\n\t\t\tstaff2.removeChild(staff2.lastChild);\n\t\t}\n\n\t})\n\t// Generate the concatenate code for stand-alone html5\n\t\tvar htmlTEMPLATE=\"<!doctype html>\"\n\t\thtmlTEMPLATE=htmlTEMPLATE+\"<html>\\n<head><\\/head>\\n<body>\\n\"\n\t\thtmlTEMPLATE=htmlTEMPLATE+\"<script>@@@PLAY_CODE<\\/script>\"\n\t\thtmlTEMPLATE = htmlTEMPLATE+\"<\\/body>\\n<\\/html>\\n\"\n\n\n\t\t// for loop and if statement\n\t\t// generating the code for each note and audio note\n\t\tcode_output = \"\\n\"\n\t\ttiming = 0\n\t\t//index_ms_offset = 1000\n\t\tweight = 30000;\n\t\tfor (index = 0; index < notes_parsed.length; index++) {\n\t\t\tif (notes_parsed[index] == 'A') {\n\t\t\t\tcode_output = code_output + \"setTimeout( function(){\\n\"\n\t\t\t\tcode_output = code_output + \"new Audio('media/high_a.mp3').play()\"\n\t\t\t\tcode_output = code_output + \"}, \" + weight + \" * \" + notes_time[index] + \" * \" + index + \");\\n \"\n\t\t\t} else if (notes_parsed[index] == 'B') {\n\t\t\t\tcode_output = code_output + \"setTimeout( function(){\\n\"\n\t\t\t\tcode_output = code_output + \"new Audio('media/high_b.mp3').play()\"\n\t\t\t\tcode_output = code_output + \"}, \" + weight + \" * \" + notes_time[index] + \" * \" + index + \");\\n \"\n\t\t\t} else if (notes_parsed[index] == 'C') {\n\t\t\t\tcode_output = code_output + \"setTimeout( function(){\\n\"\n\t\t\t\tcode_output = code_output + \"new Audio('media/high_c.mp3').play()\"\n\t\t\t\tcode_output = code_output + \"}, \" + weight + \" * \" + notes_time[index] + \" * \" + index + \");\\n \"\n\t\t\t} else if (notes_parsed[index] == 'D') {\n\t\t\t\tcode_output = code_output + \"setTimeout( function(){\\n\"\n\t\t\t\tcode_output = code_output + \"new Audio('media/high_d.mp3').play()\"\n\t\t\t\tcode_output = code_output + \"}, \" + weight + \" * \" + notes_time[index] + \" * \" + index + \");\\n \"\n\t\t\t} else if (notes_parsed[index] == 'E') {\n\t\t\t\tcode_output = code_output + \"setTimeout( function(){\\n\"\n\t\t\t\tcode_output = code_output + \"new Audio('media/high_e.mp3').play()\"\n\t\t\t\tcode_output = code_output + \"}, \" + weight + \" * \" + notes_time[index] + \" * \" + index + \");\\n \"\n\t\t\t} else if (notes_parsed[index] == 'F') {\n\t\t\t\tcode_output = code_output + \"setTimeout( function(){\\n\"\n\t\t\t\tcode_output = code_output + \"new Audio('media/high_f.mp3').play()\"\n\t\t\t\tcode_output = code_output + \"}, \" + weight + \" * \" + notes_time[index] + \" * \" + index + \");\\n \"\n\t\t\t} else if (notes_parsed[index] == 'G') {\n\t\t\t\tcode_output = code_output + \"setTimeout( function(){\\n\"\n\t\t\t\tcode_output = code_output + \"new Audio('media/high_g.mp3').play()\"\n\t\t\t\tcode_output = code_output + \"}, \" + weight + \" * \" + notes_time[index] + \" * \" + index + \");\\n \"\n\t\t\t}\n\t\t}\n\n\t// print the code\n\t$(\"#compiled_code\").val(htmlTEMPLATE.replace(\"@@@PLAY_CODE\", code_output))\n\t} catch(err) {\n\t\talert(\"Error: \" + err);\n\t\t\n\t\t\n\t}\n\t\n}", "function addNewMusic(){\n\tlet title = document.getElementById(\"inputSong\").value;\n\tlet artist = document.getElementById(\"inputArtist\").value;\n\tlet album = document.getElementById(\"inputAlbum\").value;\n\tlet songObj = {\"title\": title, \"artist\": artist, \"album\": album};\n\t// console.log(\"songObj\", songObj);\n\tLoader.addToLibrary(songObj);\n\tLoader.showSongs(callBack);\n\n\tclearTextInputs();\n}", "function preventRepeatingSong() {\n let currentVideo = player.getVideoUrl();\n let currentVideoId = currentVideo.slice(currentVideo.indexOf(\"v=\"),currentVideo.length);\n currentVideoId = currentVideoId.slice(2, currentVideoId.length);\n musicArray.splice(musicArray.indexOf(currentVideoId), 1);\n musicArray.push(currentVideoId);\n}", "function addSongInfo(){\n \n var songInput = $(\"#song\").val();\n var imageInput = $(\"#image\").val();\n var artistInput = $(\"#artist\").val();\n var lengthInput = $(\"#length\").val();\n var linkInput = $(\"#links\").val();\n \n //This pushes the songs into the variables.\n songs.push(songInput);\n images.push(imageInput);\n artists.push(artistInput);\n lengths.push(lengthInput);\n links.push(linkInput);\n\n}", "addList(instruments) {\n for (let j = 0; j < instruments.length; j++) {\n var buttonSubArray = new Array();\n var sequencerSubArray = new Array();\n for (let i = 0; i < 16; i++) {\n buttonSubArray[i] = new Object();\n buttonSubArray[i].id = i;\n buttonSubArray[i].class = instruments[j];\n buttonSubArray[i].click = this.toggle(i);\n buttonSubArray[i].stepActive = false;\n buttonSubArray[i].color = \"white\";\n // 0 means no volume == false, sequencerArray saves dynamic velocity\n sequencerSubArray.push(0);\n }\n this.buttonArray[j] = buttonSubArray;\n this.sequencerArray[j] = sequencerSubArray;\n }\n //console.log(this.sequencerArray);\n }", "function insertToLoop(p) {\n let newplayingLoop = [...playingLoop, { audio: p.audio, id: p.id }]\n setPlayingLoop(newplayingLoop)\n console.log(newplayingLoop)\n }", "function preloadSongs(data) {\r\n $('#songsTab').html(\"\");\r\n for (var i = 0; i < data.songs.length; i++) {\r\n $('#addModalTitle').text('Edit playlist');\r\n $('#songsTab').append(`\r\n <form class=\"song\">\r\n <label>Name: <input name=\"name\" class=\"newSongName\" value=\"`+data.songs[i].name+`\"></input></label>\r\n <label>Url: <input name=\"url\" class=\"newSongUrl\" value=\"`+data.songs[i].url+`\"></input></label><br>\r\n </form>`);\r\n $('#submitPlaylist').hide();\r\n $('#saveEdits').show();\r\n };\r\n }", "function nomeMusicas() {\r\n arrMusica = [];\r\n arrArtista = [];\r\n arrCompleto = [];\r\n strTotalMusicas = document.getElementsByClassName('TrackListHeader__entity-additional-info');\r\n intTotalMusicas = parseInt(strTotalMusicas[0].innerText.substring(0,3)) - 1;\r\n for (let i = 0; i <= intTotalMusicas; i++) {\r\n musicas = document.getElementsByClassName('tracklist-name');\r\n artistas = document.getElementsByClassName('TrackListRow__artists');\r\n arrMusica.push(musicas[i].innerText);\r\n arrArtista.push(artistas[i].innerText);\r\n arrCompleto.push(musicas[i].innerText + ' - ' + artistas[i].innerText);\r\n }\r\n // console.log(arrMusica);\r\n // console.log(arrArtista);\r\n console.log(arrCompleto);\r\n console.save(arrCompleto);\r\n}", "function AudioButtonFunc1(n_audio) {\n if (audioPlaying[n_audio] == false) {\n audioArray1[n_audio].loop = true;\n audioArray1[n_audio].play();\n audioArray1[n_audio].volume = 1.0;\n audioPlaying[n_audio] = true;\n } else {\n audioArray1[n_audio].pause();\n audioPlaying[n_audio] = false;\n }\n debugShowLog(audioPlaying);\n // END if audioPlaying\n} // END AudioButtonFunc", "function appendArrays() {\n let name = $(\"#song-name\").val();\n let artist = $(\"#artist\").val();\n let length = $(\"#length\").val();\n let image = $(\"#picture-link\").val();\n let link = $(\"#song-link\").val();\n \n if (name !== \"\") {\n numSongs = allSongsArray.length;\n console.log(numSongs);\n allSongsArray[numSongs] = {\"name\": name, \"artist\": artist, \"length\": length, \"image\": image, \"link\": link};\n \n \n\n //PUSH TO LOCAL STORAGE\n // localStorage.setItem(\"songNamesArrayJSON\", JSON.stringify(songNamesArray));\n // localStorage.setItem(\"artistsArrayJSON\", JSON.stringify(artistsArray));\n // localStorage.setItem(\"lengthsArrayJSON\", JSON.stringify(lengthsArray));\n // localStorage.setItem(\"imagesArrayJSON\", JSON.stringify(imagesArray));\n // localStorage.setItem(\"songLinksArrayJSON\", JSON.stringify(songLinksArray));\n localStorage.setItem(\"allSongsArrayJSON\", JSON.stringify(allSongsArray));\n ////////////////////////\n \n }\n else {\n \n }\n}", "function musicChannelUI() {\n musicBack = document.createElement('button')\n musicBack.style.position = \"absolute\"\n musicBack.className = \"miiBack\"\n musicBack.innerHTML = \"Back\"\n musicBack.onclick = function() {\n while(oldNodes.firstChild)\n {\n oldNodes.removeChild(oldNodes.firstChild);\n }\n restoreWiiMenu()\n try {\n dir = fs.readdirSync(FileSystem.currentDirectory);\n replaceButtons(dir, 0)\n \n } catch(err) {\n return 1;\n }\n\n }\n document.getElementById(\"buttons\").appendChild(musicBack)\n\n buttonTop = 160\n for(i = 0; i < 6; i++)\n {\n songButton = document.createElement('button')\n songButton.className = \"songButton\"\n songButton.style.position = \"absolute\"\n songButton.style.left = \"20px\"\n songButton.style.top = (buttonTop) + \"px\"\n if(i === 0)\n {\n songButton.innerHTML = \"Wii Theme\"\n songButton.onclick = function() {\n oldSong = document.getElementById(\"music\")\n newSong = oldSong.cloneNode(true)\n newSong.src = \"Main Menu.mp3\"\n oldSong.parentNode.replaceChild(newSong, oldSong)\n }\n }\n else if(i === 1)\n {\n songButton.innerHTML = \"Mii Theme\"\n songButton.onclick = function() {\n oldSong = document.getElementById(\"music\")\n newSong = oldSong.cloneNode(true)\n newSong.src = \"Mii Channel.mp3\"\n oldSong.parentNode.replaceChild(newSong, oldSong)\n }\n }\n else if(i === 2)\n {\n songButton.innerHTML = \"Wii Shop Theme\"\n songButton.onclick = function() {\n oldSong = document.getElementById(\"music\")\n newSong = oldSong.cloneNode(true)\n newSong.src = \"Shop Channel.mp3\"\n oldSong.parentNode.replaceChild(newSong, oldSong)\n }\n }\n else if(i === 3)\n {\n songButton.innerHTML = \"Wii Sports (Bowling)\"\n songButton.onclick = function() {\n oldSong = document.getElementById(\"music\")\n newSong = oldSong.cloneNode(true)\n newSong.src = \"Bowling.mp3\"\n oldSong.parentNode.replaceChild(newSong, oldSong)\n }\n }\n else if(i === 4)\n {\n songButton.innerHTML = \"Wii Sports Theme\"\n songButton.onclick = function() {\n oldSong = document.getElementById(\"music\")\n newSong = oldSong.cloneNode(true)\n newSong.src = \"Wii Sports.mp3\"\n oldSong.parentNode.replaceChild(newSong, oldSong)\n }\n }\n else\n {\n songButton.innerHTML = \"Your Own Music\"\n songButton.onclick = function() {\n dialog.showOpenDialog(function (chosenSong) {\n oldSong = document.getElementById(\"music\")\n newSong = oldSong.cloneNode(true)\n if(chosenSong.length > 1)\n {\n dialog.showMessageBox({message: \"Please select one song at a time!\", title: \"Oops!\"})\n }\n else if((chosenSong[0].substr(chosenSong[0].lastIndexOf(\".\") + 1)) !== \"mp3\") {\n dialog.showMessageBox({message: \"Sorry, only MP3 files are accepted!\", title: \"Oops!\"})\n }\n else\n {\n newSong.src = chosenSong[0]\n oldSong.parentNode.replaceChild(newSong, oldSong)\n }\n })\n }\n }\n document.getElementById(\"buttons\").appendChild(songButton)\n buttonTop += 52\n }\n\n muteButton = document.createElement('button')\n muteButton.className = \"muteButton\"\n muteButton.style.position = \"absolute\"\n muteButton.onclick = function() {\n oldSong = document.getElementById(\"music\")\n newSong = oldSong.cloneNode(true)\n newSong.src = \"\"\n oldSong.parentNode.replaceChild(newSong, oldSong)\n }\n document.getElementById(\"buttons\").appendChild(muteButton)\n\n miiPic = document.createElement('IMG')\n miiPic.style.position = \"absolute\"\n miiPic.className = \"musicPic\"\n miiPic.src = \"MarioDance.png\"\n miiPic.id = \"miiPicture\"\n document.getElementById(\"buttons\").appendChild(miiPic)\n}", "function addSong(){\r\n var song = {};\r\n \r\n // prompt user for data\r\n song.title = prompt(\"please enter the title of the song\");\r\n song.artist = prompt(\"please enter the name of the artist of the song\");\r\n song.videoId = prompt(\"please enter the video id\");\r\n data.songs.push(song);\r\n\r\n // if the current playist isnt also the all songs playlist\r\n if(current_playlist.songs != data.songs){\r\n // add song to data\r\n var songCopy = {};\r\n songCopy.title = song.title;\r\n songCopy.artist = song.artist;\r\n songCopy.videoId = song.videoId;\r\n current_playlist.songs.push(songCopy);\r\n }\r\n updateSongPane();\r\n}", "function play(lbtn, id) {\n newid = id;\n if (audio.src && oldid === newid) {\n if (audio.paused) {\n audio.play();\n playbtn.firstElementChild.classList.remove(\"fa-play-circle\");\n playbtn.firstElementChild.classList.add(\"fa-pause-circle\");\n // changing icon for the left play button\n lbtn.children[0].classList.remove(\"fa-play-circle\");\n lbtn.children[0].classList.add(\"fa-pause-circle\");\n } else {\n audio.pause();\n playbtn.firstElementChild.classList.remove(\"fa-pause-circle\");\n playbtn.firstElementChild.classList.add(\"fa-play-circle\");\n // changing icon for the left play button\n lbtn.children[0].classList.remove(\"fa-pause-circle\");\n lbtn.children[0].classList.add(\"fa-play-circle\");\n console.log(\"yes\");\n }\n } else {\n oldid = id;\n audio.src = songs[source];\n audio.play();\n playbtn.firstElementChild.classList.remove(\"fa-play-circle\");\n playbtn.firstElementChild.classList.add(\"fa-pause-circle\");\n // changing icon for the left play button\n lbtn.children[0].classList.remove(\"fa-play-circle\");\n lbtn.children[0].classList.add(\"fa-pause-circle\");\n displayname();\n updatethumb();\n console.log(\"no\");\n lbtn = document.querySelectorAll(\"#lbtn\");\n lbtn.forEach((x) => {\n cid = x.dataset.source;\n if (cid === newid) {\n } else {\n x.children[0].classList.remove(\"fa-pause-circle\");\n x.children[0].classList.add(\"fa-play-circle\");\n }\n });\n }\n}", "function updateAllId(){\n const bookContainers = document.querySelectorAll('.book-container');\n bookContainers.forEach((book, index) => {\n myLibrary[index].id = index;\n book.id = index;\n })\n}", "function musicPicker(){\n push();\n clear();\n background(0);\n\n // add heading\n push();\n fill(120, 120, 120, 90);\n rect(0,0,width, height/6);\n textSize(40);\n fill(255, 90, 90);\n stroke(10,70,190);\n strokeWeight(5);\n text('Stage One : Choose Music ', width/4, height/10);\n textSize(20);\n stroke(2);\n text('* ( Click on the notes to listen ) ', width/7*6, height/8);\n pop();\n\n\n // set mouseOver effect\n mouseOver();\n\n\n // set click-on effect --- which means current selected music\n if(musicChosen1 == true){\n button1.show();\n selectedMusic = music1;\n fill(100, 40, 120);\n mouseOverWhich(width/6, pic2, width/6, 'Music 1', width/6, height/2+height/6);\n }\n if(musicChosen2 == true){\n button2.show();\n selectedMusic = music2;\n fill(40, 120, 100);\n mouseOverWhich(width/6*2, pic3, width/6*2, 'Music 2', width/6*2, height/2+height/6);\n }\n if(musicChosen3 == true){\n button3.show();\n selectedMusic = music3; \n fill(120, 100, 40);\n mouseOverWhich(width/2, pic4, width/2, 'Music 3', width/2, height/2+height/6);\n }\n if(musicChosen4 == true){\n button10.show();\n selectedMusic = music4; \n fill(120, 100, 40);\n mouseOverWhich(width/6*4, pic2, width/6*4, 'Music 4', width/6*4, height/2+height/6);\n }\n if(musicChosen5 == true){\n button11.show();\n selectedMusic = music5; \n fill(120, 100, 40);\n mouseOverWhich(width/6*5, pic3, width/6*5, 'Music 5', width/6*5, height/2+height/6);\n }\n\n // set playing effect for prelistening the music\n playingMode(music1, pic7, width/6, height/2);\n playingMode(music2, pic8, width/6*2, height/2);\n playingMode(music3, pic9, width/2, height/2);\n playingMode(music4, pic7, width/6*4, height/2);\n playingMode(music5, pic8, width/6*5, height/2);\n\n // graphic of notes\n push();\n tint(255,125);\n image(pic2, width/6, height/2, width/13, width/13);\n image(pic3, width/6*2, height/2, width/13, width/13);\n image(pic4, width/2, height/2, width/13, width/13);\n image(pic2, width/6*4, height/2, width/13, width/13);\n image(pic3, width/6*5, height/2, width/13, width/13);\n\n pop();\n\n}", "HardReset(){\n this.refHolder.getComponent('AudioController').PlayTap();\n\n\n\n for(let i =0 ; i < this.inputButs.length;i++){\n this.inputButs[i].destroy();\n }\n for(let i =0 ; i < this.tmpInputButs.length;i++){\n this.tmpInputButs[i].destroy();\n }\n this.inputButs = [];\n this.tmpInputButs = [];\n this.prevID = 10;\n\n this.refHolder.getComponent(\"GamePlay\").butArray = [];\n this.Reset();\n this.refHolder.getComponent(\"GamePlay\").CreatePuzzle();\n\n\n }", "function update_song_view(song, i, num_songs) {\n\t\t$('#song_counter').html(parseFloat(i + 1) + '/' + num_songs);\n\t\t$('#song-playback').attr('src', song.url);\n\t\tvar btn_nums = [ 0, 1, 2, 3 ];\n\t\tbtn_nums = shuffle(btn_nums);\n\t\tvar correct_btn = btn_nums.pop();\n\t\t$('#btn' + correct_btn).html(song.songname);\n\t\t$('#btn' + correct_btn).css('background', '#23272b');\n\t\tvar id_num;\n\n\t\tfor (var i = 0; i < 3; i++) {\n\t\t\tid_num = btn_nums.pop();\n\t\t\t$('#btn' + id_num).html(song.related_songs[i]);\n\t\t\t$('#btn' + id_num).css('background', '#23272b');\n\t\t}\n\t}", "function addSongs(music) {\n musicProgram.addMoreSongsButton()\n .then(function(json) {\n console.log(\"ADD MORE SONGS\");\n musicProgram.addNewMusic(json, musicProgram.songData);\n $moreButton.prop('disabled', true);\n\n addDeleteButtons();\n\n });\n}", "function gotData(data) {\n console.log('retrieveSong gotData');\n for (var i = 0; i < 5; i++) {\n var tempArray = [];\n lastKey[i] = Object.keys(data.val()[i]).length;\n console.log('retrieveSong gotData for1');\n for (var j = 0; j < 3; j++) {\n var randID = Math.floor(random(lastKey[i]));\n var resultURI = data.val()[i][randID][0];\n var randomFreq = Math.floor(random(10)) * 10;\n var tempArray2 = [];\n tempArray2.push(resultURI, randomFreq);\n tempArray.push(tempArray2);\n console.log('retrieveSong gotData for2');\n }\n foundSongs.push(tempArray);\n }\n // document.getElementById(\"spotifyPreviewB\").src = 'https://open.spotify.com/embed?uri=' + resultURI;\n}", "function musicControl(){\r\n if (audioon == 0) {\r\n document.getElementById(\"MusicButton\").style.background = 'url(\"project/img/audioon.png\") no-repeat';\r\n audioon = 1;\r\n if (document.getElementById(\"centerBox\").style.visibility == \"visible\" || document.getElementById(\"centerBox2\").style.visibility == \"visible\") {\r\n music[0].muted = false;\r\n music[0].play();\r\n music[0].loop = true;\r\n }\r\n else if (document.getElementById(\"ButtonPause\").style.visibility == \"hidden\" && !gameoverOn) {\r\n music[1].muted = false;\r\n music[1].play();\r\n } else if(gameoverOn){\r\n music[2].muted = false;\r\n music[2].play();\r\n music[2].onended = function() { music[0].play(); music[0].loop = true;};\r\n }\r\n }\r\n else {\r\n // if (errors == 0 && gameoverOn){\r\n // document.getElementById(\"MusicButton\").style.background = 'url(\"project/img/audiooff.png\") no-repeat';\r\n // music[2].muted = true;\r\n // gameoverOn = 0;\r\n // }\r\n // else if(errors == 0 && gameoverOn==0 && gameReset ==0){\r\n // document.getElementById(\"MusicButton\").style.background = 'url(\"project/img/audioon.png\") no-repeat';\r\n // music[2].muted = false;\r\n // gameoverOn= 1;\r\n // gameReset = 1;\r\n // }\r\n // else{\r\n document.getElementById(\"MusicButton\").style.background = 'url(\"project/img/audiooff.png\") no-repeat';\r\n audioon = 0;\r\n music[0].pause();\r\n music[1].muted = true;\r\n music[2].pause();\r\n music[3].pause();\r\n music[4].pause();\r\n // }\r\n\r\n\r\n }\r\n document.getElementById(\"MusicButton\").style.backgroundSize = \"cover\";\r\n}", "function playlistHover() {\n var musicArray = [];\n\n $('.playlist-section').on('click', '.search-songs', function() {\n var artist = $(this).find('h2').text();\n var song = $(this).find('.song').text();\n if (song !== '') {\n var music = {\n \"artist\": artist,\n \"song\": song\n };\n\n musicArray.push(music);\n localStorage.setItem(\"musicArray\", JSON.stringify(musicArray));\n var retrievedObject = JSON.parse(localStorage.getItem(\"musicArray\"));\n\n generateTemplate('your-playlist', music);\n }\n });\n }", "function addSongToPlaylist() {\n let listEle = document.getElementById('newplaylistName');\n if (listEle.value.length == 0 || listEle.value == \"\") {\n listEle.focus();\n alert('Enter valid playlist name');\n }\n else {\n let songData = {\n name: document.getElementById('newplaylistName').value,\n song: [\n {\n songName: document.getElementById('songtitle').value,\n songurl: document.getElementById('songurl').value\n }\n ]\n }\n\n if (playlistsArr.length === 0) {\n playlistsArr.push(songData);\n addPlaylistsName();\n }\n else {\n let i = 0;\n for (i = 0; i < playlistsArr.length; i++) {\n\n if (playlistsArr[i].name == songData.name) {\n addSongToExistingPlaylist(songData.song[0].songName, songData.song[0].songurl, songData.name);\n break;\n }\n\n }\n if (i == playlistsArr.length) {\n playlistsArr.push(songData);\n addPlaylistsName();\n }\n }\n }\n reloadPlaylists();\n}", "function handaleOff(p) {\n let play = playingLoop.filter(l => l.id === p.id)\n play[0].audio.pause()\n let newplayingLoop = [...playingLoop]\n newplayingLoop = newplayingLoop.filter(l => l.id !== p.id)\n setPlayingLoop(newplayingLoop)\n console.log(newplayingLoop)\n }", "function updatePlaylist(){\n /*\n Get all checked checkboxes.\n This can be done in this case, because the only checkboxes in the UI are tracks, the user wants to replace.\n It would be better to search by a better selector.\n\n TODO: Use a better selector - Getting all inputs could break the whole thing at one point. Using a class would be better\n\n Also, an empty body array will be created.\n This body will be the body of the POST request to the backend by the SpotifyUpdater bridge class.\n\n Then the script will iterate over the checked tracks\n\n The Spotify API needs a snapshot ID of a playlist to be able to delete local tracks.\n This ID is stored as a data attribute with the original track and added to the body of the request.\n */\n\n\n let originalTracks = document.querySelectorAll(\"input[type='checkbox']:checked\")\n\n let body = {\n \"snapshot\": originalTracks[0].dataset.snapshot,\n \"playlist\": originalTracks[0].dataset.playlist,\n \"tracklist\": []\n };\n\n originalTracks.forEach(function(originalTrack){\n /*\n A data-something-something attribute is accessible via JavaScript as dataset.somethingSomething.\n The line below extracts the original URI from the checkbox attribute.\n */\n\n let track = originalTrack.dataset.originalUri;\n let position = originalTrack.dataset.position;\n\n /*\n The following lines select all the checked radio boxes which have the original URI as their name,\n and extract the replacement URIs\n Since this can only be one, we can safely just take element 0 of the resulting array.\n */\n\n let replacement = document.querySelectorAll(\"input[type='radio'][name='\"+track+\"']:checked\");\n let replacementUri = replacement[0].dataset.replacementUri;\n\n /*\n Now the original URI and the replacement URI are added to the result object.\n This result object will then be pushed (appended) to the body array.\n The backend will later be able to send the result to the API\n */\n\n let result = {\n position: position,\n original: track,\n replacement: replacementUri\n };\n body.tracklist.push(result);\n });\n\n spotupdtr.replaceSongs(body);\n}", "addSong(input) {\n this.songs.push(input);\n }", "function PlayX(button) {\n \t\t\t\t\t\t\t\t\t\t\trunningFunction=\"PlayX\"; \t\t\t\t\t\n \t\t\t\t\t\t\t\t\t\t\tvar x = button.id // take the id value from the button you play (all the buttons point to this function) \n \t\t\t\t\t\t\t\t\t\t\tvar Played = button.value; // CLICK take the value which represent the played note from the relative button in html \n\t\t\t\t\t\t\t\t\t\t\tplaySound(Played);\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\tconsole.log(Played); \t\t\t\t\t\n \t\t\t\t\t\t\t\t\t\t\tthePlayerSequence.push(Played);//push the button value into the user array thePlayerSequence \t \n\t\t\t\t\t\t\t\t\t\t\tconsole.log(thePlayerSequence);\t\t \n\t\t\t\t\t\t\t\t\t\t\tclickCounter ++; //keep count of the clicks \n\t\t\t\t\t\t\t\t\t\t\tdisplayVar();\n\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\tcheckIfCorrect(); //call the function which check il the entry is correct\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t}", "SetupAuds(playerMedia) {\n this.logger.info('Calling for setup Auds !!!');\n let audsBtn = null;\n let i = 0;\n let item = null;\n this.mediaPlayer = playerMedia;\n const audioTracks = this.mediaPlayer.getAudioLanguages();\n this.audsExist = false;\n this.logger.info(' Trying to setup menu Auds , text tracks length : ', audioTracks);\n\n // check if exist\n if ((!audioTracks) || (audioTracks.length <= 1)) {\n this.audsExist = false;\n this.logger.log(' Audio Menu not created !');\n return false;\n }\n // Setting inner of btn div\n audsBtn = document.getElementById(this.audsBtnId);\n this.logger.info('Setting the btn ', audsBtn, ' from id ', this.audsBtnId);\n // this.video array\n this.audsList = document.getElementById(this.audsMenuListId);\n // clear old\n if (this.audsList !== null) {\n while (this.audsList.firstChild) {\n this.audsList.removeChild(this.audsList.firstChild);\n }\n } else {\n this.audsMenuDiv = document.createElement('div');\n this.audsMenuDiv.classList.add('settingMenuDiv');\n this.audsMenuDiv.classList.add('fj-hide');\n this.audsMenuDiv.innerHTML = `${'<div class=\"fj-list-title\"> Audios </div> '\n + '<ul class=\"fj-list\" id=\"'}${this.audsMenuListId}\" >`\n + '</ul>';\n this.menusDiv.appendChild(this.audsMenuDiv);\n // Add events for audios button\n audsBtn.addEventListener('click', (ev) => {\n this.onshowHideMenu(this.audsMenuDiv, this, ev);\n });\n // audios list\n this.audsList = document.getElementById(this.audsMenuListId);\n }\n\n for (i = 0; i < audioTracks.length; i += 1) {\n item = document.createElement('li');\n if (this.mediaPlayer.isAudioLangEnabled(i) === true) {\n item.classList.add('subtitles-menu-item-actif');\n } else {\n item.classList.add('subtitles-menu-item');\n }\n\n item.setAttribute('index', i);\n item.innerHTML = this.mediaPlayer.getAudioLangLabel(i);\n this.audsList.appendChild(item);\n item.addEventListener('click', () => {\n this.activate(this, false);\n });\n }\n\n this.logger.debug(' Audio Menu created !', audioTracks.length, '! ', this.audsList);\n return this.audsExist;\n }", "playerUpdate() {\n this.players.forEach((player) => {\n let a = [];\n a = a.concat(this.currentquestion.a);\n a.push(this.currentquestion.correct);\n //TODO: shuffle a\n player.socket.emit('question', {\n q: this.currentquestion.q,\n a: shuffle(a)\n });\n });\n }", "function setPresets() {\n\n //check the buttons id, whatever id it has is the preset it needs to select\n let myID = event.srcElement.id;\n presetID = myID\n\n let idArray = myID.split(\" \")\n let seqID = parseInt(idArray[0]) + 1\n let preID = idArray[1]\n\n console.log(seqID, preID)\n\n let whichButton = {...userPresets[seqID][preID]};\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 waveform = setWaveform\n let setPitchScheme = whichButton.pitchArray;\n console.log(setPitchScheme)\n \n userSequencer[seqID-1].polyMatrix = setSequence;\n userSequencer[seqID-1].polyNotes = setPitchScheme;\n\n userSynth[seqID-1].set({\n 'oscillator': {\n 'type': setWaveform\n },\n 'envelope': {\n 'attack': setAttack,\n 'decay': setDecay,\n 'sustain': setSustain,\n 'release': setRelease\n }\n });\n\n attackSlider[seqID - 1].value(setAttack);\n decaySlider[seqID - 1].value(setDecay);\n sustainSlider[seqID - 1].value(setSustain);\n releaseSlider[seqID - 1].value(setRelease);\n \n userSequencer[seqID - 1].drawMatrix();\n userSequencer[seqID - 1].polyMatrixNotes();\n\n let placeholderString = setPitchScheme.toString();\n let newPitchString = placeholderString.replace(/,/g, ' ')\n pitchInput[seqID - 1].attribute(\"placeholder\", newPitchString)\n\n waveInput[seqID - 1].attribute(\"placeholder\", setWaveform)\n \n //When Votes selected\n if (whichButton.haveVoted === false){\n yesButton[seqID - 1].show();\n noButton[seqID - 1].show();\n questionP[seqID - 1].show();\n voteP[seqID - 1].hide();\n }else{\n yesButton[seqID - 1].hide();\n noButton[seqID - 1].hide();\n questionP[seqID - 1].hide();\n voteP[seqID - 1].show();\n }\n}", "function populatePlaylist() {\n\n for (i in playlist) {\n // Display the search results and an add button to vote section\n var playlistContainer = document.createElement('div');\n playlistContainer.className = \"current\";\n\n var playlistTitle = document.createElement('h4');\n playlistTitle.innerHTML = playlist[i].title;\n\n var playlistThumbnail = document.createElement('img');\n playlistThumbnail.src = playlist[i].imgSrc;\n\n $('#playback-bar').append(playlistContainer);\n playlistContainer.append(playlistThumbnail);\n playlistContainer.append(playlistTitle);\n\n playlistContainer.id = playlist[i].songId;\n\n // console.log(playlistContainer.id);\n }\n }", "function topPortugal() {\r\n // ARRAYS para guardar os valores das musicas \r\n var musicArray = [];\r\n var trackImg = [];\r\n\r\n //call da API\r\n $.ajax({\r\n type: 'POST',\r\n url: 'http://ws.audioscrobbler.com/2.0/',\r\n data:\r\n 'method=tag.gettoptracks&' +\r\n 'api_key=97dd7464b0a13ef1d8ffa1562a6546eb&' +\r\n 'tag=portugal&' +\r\n 'format=json',\r\n dataType: 'json',\r\n async: false, // Só continua o código quando o ajax completa, em vez de fazer em background\r\n success: function (data) {\r\n musicArray = data.tracks.track;\r\n },\r\n })\r\n\r\n console.log(musicArray);\r\n musicArray = Object.assign({}, musicArray);\r\n for (var i = 0; i < 10; i++) {\r\n console.log(musicArray[i]);\r\n trackImg.push(musicArray[i].image[3]);\r\n }\r\n\r\n //slideshow \r\n var index = 0;\r\n var theImage = document.getElementById(\"main-image\");\r\n\r\n theImage.src = trackImg[0][\"#text\"];\r\n\r\n $('#main-text').text((\r\n \"Rank: \" + (index + 1) + \" | \" + musicArray[index].artist.name + \" - \" + musicArray[index].name\r\n ));\r\n\r\n $('#btnLeft').click(function () {\r\n index--;\r\n\r\n if (index < 0)\r\n index = trackImg.length - 1;\r\n\r\n theImage.src = trackImg[index][\"#text\"];\r\n\r\n $('#main-text').text((\r\n \"Rank: \" + (index + 1) + \" | \" + musicArray[index].artist.name + \" - \" + musicArray[index].name\r\n ));\r\n\r\n\r\n //verifica se ja existe nos favoritos\r\n var musica = $('#main-text').text();\r\n var favMusics = JSON.parse(localStorage.getItem(\"favoritos\"));\r\n\r\n //faz o corte do artista e musica nas strigns do array predefinido das musicas\r\n var artist_track = musica;\r\n var artist_trackA = new Array();\r\n artist_trackA = artist_track.split(' | ');\r\n musica = artist_trackA[1];\r\n\r\n if (favMusics.includes(musica))\r\n $(\"#addFav\").html('Adicionar aos Favs🌟');\r\n else\r\n $(\"#addFav\").html('Adicionar aos Favs');\r\n\r\n });\r\n\r\n $('#btnRight').click(function () {\r\n index++;\r\n index %= trackImg.length;\r\n\r\n if (index < 0)\r\n index = trackImg.length - 1;\r\n\r\n theImage.src = trackImg[index][\"#text\"];\r\n\r\n $('#main-text').text((\r\n \"Rank: \" + (index + 1) + \" | \" + musicArray[index].artist.name + \" - \" + musicArray[index].name\r\n ));\r\n\r\n //verifica se ja existe nos favoritos\r\n var musica = $('#main-text').text();\r\n var favMusics = JSON.parse(localStorage.getItem(\"favoritos\"));\r\n\r\n //faz o corte do artista e musica nas strigns do array predefinido das musicas\r\n var artist_track = musica;\r\n var artist_trackA = new Array();\r\n artist_trackA = artist_track.split(' | ');\r\n musica = artist_trackA[1];\r\n\r\n console.log(musica);\r\n if (favMusics.includes(musica))\r\n $(\"#addFav\").html('Adicionar aos Favs🌟');\r\n else\r\n $(\"#addFav\").html('Adicionar aos Favs');\r\n\r\n });\r\n}", "function enableSonglistControls(songlistID) {\n\t// Get a reference to this song list adn its' songs\n\tvar songList = document.querySelector(songlistID);\n\tvar songs = songList.children;\n\n\t// Initialize an empty object to store key:value pairs for each\n\t// song's title and source file. Later will be passed to a Tone.js\n\t// Multiplayer sampler\n\tvar songSources = {};\n\n\t// Wait for DOM to load and begin building multitrack audio sampler\n\twindow.addEventListener('DOMContentLoaded', function(e) {\n\t\t// Loop through all songs in this playlist\n\t\tfor(var i = 0; i < songs.length; i++) {\n\t\t\t// Build a key:value pair for this song and add to songSources\n\t\t\tvar songTitle = songs[i].children[2].innerHTML;\n\t\t\tvar songSrc = songs[i].children[0].getAttribute('data-src');\n\t\t\tsongSources[songTitle] = songSrc;\n\t\t}\n\n\t\t// Build a multisampler with Tone.js - pass songSources object\n\t\tvar multiPlayer = new Tone.MultiPlayer(songSources, function(){}).toMaster();\n\n\t\t// Add Event Listeners to each song's audio buttons\n\t\tfor(var i = 0; i < songs.length; i++) {\n\t\t\t// Get song's play and stop buttons\n\t\t\tvar playBtn = songs[i].children[0];\n\t\t\tvar stopBtn = songs[i].children[1];\n\n\t\t\t// Play button listener\n\t\t\tplayBtn.addEventListener('click', function(e) {\n\t\t\t\t// Stop redirect to song's single page\n\t\t\t\te.stopImmediatePropagation();\n\t\t\t\t// Hide all stop buttons\n\t\t\t\thideAllStopButtons(songs);\n\t\t\t\t// Show all of the play buttons\n\t\t\t\tshowAllPlayButtons(songs);\n\t\t\t\t// Get this play buttons's song title and stop button\n\t\t\t\tvar songTitle = this.parentElement.children[2].innerHTML;\n\t\t\t\tvar thisStopBtn = this.parentElement.children[1];\n\t\t\t\t// Hide play button and show stop button for this song\n\t\t\t\tthis.style.display = 'none';\n\t\t\t\tthisStopBtn.style.display = 'block';\n\t\t\t\t// Stop all samples\n\t\t\t\tmultiPlayer.stopAll();\n\t\t\t\t// Play Multiplayer loop sample that matches song's title\n\t\t\t\tmultiPlayer.start(songTitle);\n\t\t\t}, false);\n\n\t\t\t// Stop button listener\n\t\t\tstopBtn.addEventListener('click', function(e) {\n\t\t\t\t// Stop redirect to song's single page\n\t\t\t\te.stopImmediatePropagation();\n\t\t\t\t// Get this stop button's sibling play button\n\t\t\t\tvar thisPlayBtn = this.parentElement.children[0];\n\t\t\t\t// Hide stop button and show play button for this song\n\t\t\t\tthis.style.display = 'none';\n\t\t\t\tthisPlayBtn.style.display = 'block';\n\t\t\t\t// Stop all samples\n\t\t\t\tmultiPlayer.stopAll();\n\t\t\t});\n\t\t}\n\n\t\t// Add Event Listeners to each song list item\n\t\t// Redirects user to song's url\n\t\tfor(var i = 0; i < songs.length; i++) {\n\t\t\tsongs[i].addEventListener('click', function() {\n\t\t\t\tvar url = this.getAttribute('data-url');\n\t\t\t\twindow.location = url;\n\t\t\t}, false);\n\t\t}\n\t}, false);\n}", "play(id) {\n this.playSound(id);\n userSequence.push(id);\n for(i=0; i<userSequence.length; i++){\n if(userSequence[i] != gameSequence[i]){\n gameOver = true;\n this.setState({flashIndex: 0});\n Alert.alert(\"Try Again!\")\n this.addAndUpdate();\n }\n }\n if (gameOver == false && (userSequence.length == gameSequence.length)){\n this.setState({score: this.state.score + 1});\n userSequence = [];\n gameSequence.push(random(1, 4));\n this.playColor(gameSequence);\n \n }\n }", "function setAudioSources() {\n if (bank == 1) {\n for (let i = 0; i < LETTERS.length; i++) {\n $(\"#\" + LETTERS[i]).attr(\"src\", SOUNDS[i + 9]);\n $(\"#\" + makeValidText(i)).attr(\"id\", makeValidText(i + 9));\n }\n } else\n {\n for (let i = 0; i < LETTERS.length; i++) {\n $(\"#\" + LETTERS[i]).attr(\"src\", SOUNDS[i]);\n $(\"#\" + makeValidText(i + 9)).attr(\"id\", makeValidText(i));\n }\n }\n }", "function playMusic(id) {\n\n var url = \"api/playlist.php?type=songs&id=\" + id;\n $.get(url, function(response, songs) {\n console.log(response.data.songs);\n console.log('dsadasd');\n var object = response.data.songs;\n\n $('.songsList').empty();\n object.forEach(function(songs, album) {\n\n var li = $(\"<li class=\\\"songName \\\"><span id='songNameList' class='playIcon'></span><a href=\\\"javascript:void(0);\\\">\" +\n songs.name + \"</a></li>\");\n\n $('.songsList').append(li);\n\n li.click(function() {\n $(\"audio\").attr(\"src\", songs.url);\n isPlaying = true;\n $(\".playItemSmall .fa\").removeClass('fa-play').addClass('fa-pause');\n $('.name').html(`Now Playing: ${songs.name}`);\n $(document).attr('title', $('.name').html());\n $('.songsList i').remove();\n $(this).prepend(`<i class=\"fa fa-play\"></i>`);\n\n });\n\n })\n\n\n $('.songsList li:first-child').click();\n\n $(\"#player .buttons .btn-edit .fa\").attr(\"data-edit\", id);\n\n //$(\"audio\").attr(\"src\", object[0].url);\n\n\n var isPlaying = true;\n\n $(\".playItemSmall .fa\").removeClass('fa-play').addClass('fa-pause');\n\n $(\".playItemSmall\").click(function() {\n if (isPlaying) {\n\n $(\"audio\").trigger('pause');\n $('.playListImage').removeClass('rotatingImage');\n $(\".playItemSmall .fa\").removeClass('fa-pause').addClass('fa-play');\n\n isPlaying = false;\n } else {\n\n $(\"audio\").trigger('play');\n $('.playListImage').addClass('rotatingImage');\n $(\".playItemSmall .fa\").removeClass('fa-play').addClass('fa-pause');\n isPlaying = true;\n }\n });\n\n\n\n });\n}", "function addSongsToFav(searchFav){\n var aux3 = true;//boolean\n songContainer = document.getElementById(\"results\").querySelectorAll(\".card-container\");\n //Select all song buttons\n heartButtons = document.getElementById(\"results\").querySelectorAll(\"button\");\n heartButtons.forEach(function(button,index){\n button.addEventListener(\"click\", function(){\n heartIcon = button.querySelector(\"img\").src.split(\"/\");//take the icon name\n if(heartIcon[heartIcon.length-1] == \"heart.png\"){\n for(var i=0; i<favSongList.length; i++){\n if(favSongList[i].outerHTML == songContainer[index].outerHTML){\n if(searchFav){\n var songId = songContainer[index].querySelector(\"button\").id;//search song id\n document.getElementById(songId).parentNode.parentNode.remove();//remove from DOM\n }\n favSongList.splice(i,1);//remove song from fav list\n }\n } \n button.querySelector(\"img\").src=\"icon/heart-outline.png\";\n }else{\n button.querySelector(\"img\").src=\"icon/heart.png\";\n if(favSongList.length > 0){\n for(var i=0; i<favSongList.length; i++){\n if(favSongList[i].outerHTML == songContainer[index].outerHTML){\n aux3 = false;\n }\n }\n if(aux3){\n favSongList.push(songContainer[index]);\n }\n }\n else{\n favSongList.push(songContainer[index]);\n }\n }\n });\n });\n}", "function updateThreeKeys()\n{\n\t//should only do this when songs change\n\tsongTitle.innerHTML = allRiffs[currentRifNumber].title;\n\t// document.querySelector('#songTitle').innerHTML = allRiffs[currentRifNumber].name;\n\tlet nextRiff = allRiffs[currentRifNumber+1];\n\tif(nextRiff == null) nextRiff = allRiffs[0];\n\tlet nextThreeNotes = []; //1st 2nd 3rd\n\t// count how many of each key, if > 1, writeAt\n\n\tif(riffProgress >= currentRiff.notes.length-2)\n\t{\n\t\t//need check if repeating, allRiffs build to include same array multiple times\n\t\tlet hitsTillEnd = currentRiff.notes.length-riffProgress;\n\t\tif(hitsTillEnd == 2)\n\t\t{\n\t\t\tnextThreeNotes[2] = nextRiff.notes[0].soundName;\n\t\t\tnextThreeNotes[1] = currentRiff.notes[riffProgress+1].soundName;\n\t\t}\n\t\telse if(hitsTillEnd == 1)\n\t\t{\n\t\t\tnextThreeNotes[2] = nextRiff.notes[1].soundName;\n\t\t\tnextThreeNotes[1] = nextRiff.notes[0].soundName;\n\t\t}\n\t}\n\telse\n\t{\n\t\tnextThreeNotes[2] = currentRiff.notes[riffProgress+2].soundName;\n\t\tnextThreeNotes[1] = currentRiff.notes[riffProgress+1].soundName;\n\t}\n\n\tif(riffProgress == currentRiff.notes.length)\n\t{\n\t\tnextThreeNotes[2] = nextRiff.notes[2].soundName;\n\t\tnextThreeNotes[1] = nextRiff.notes[1].soundName;\n\t\tnextThreeNotes[0] = nextRiff.notes[0].soundName;\n\t}\n\telse\n\t{\n\t\tnextThreeNotes[0] = currentRiff.notes[riffProgress].soundName;\n\t}\n\tcountAnyRepeats();\n\t// countAnyRepeatsLastThree(nextThreeNotes);\n\tdocument.getElementById(nextThreeNotes[2]).src = 'images/whiteH3.png';\n\tdocument.getElementById(nextThreeNotes[1]).src = 'images/whiteH2.png';\n\tdocument.getElementById(nextThreeNotes[0]).src = 'images/whiteH1.png';\n}", "function load_new_tuning(tuning){\n //set buttons\n let option, audio, string;\n for(let i = 6; i >= 1; i--){\n option = tuning[i];\n string = document.getElementById(i);\n let pos = find_index(option);\n string.onclick = function(){\n sounds[pos].play();\n };\n string.innerHTML = option;\n }\n}", "function reloadAudioEditorComponentPositions() {\n var components = $('._audio_editor_component');\n components.each(function(index) {\n $(this).data('position', (index + 1));\n $(this).find('._audio_component_input_position').val(index + 1);\n $(this).find('._audio_component_icon').html(index + 1);\n });\n}", "function add_to_list(){\n for(var count = 0; count < title.length; count++){\n html = '';\n html += '<li class=\"listItemPlay \" onclick=\"play_music('+count+')\" data-item=\"'+count+'\">';\n html += '<div class=\"row\">';\n html += '<span>'+title[count]+'</span>';\n html += '<p>'+artists[count]+'</p>';\n html += '</div>';\n html += '<span class=\"currentPlaying'+count+' button button-sm\"><i class=\"fas fa-play\"></i><i class=\"fas fa-pause\"></i></span>';\n html += '</li>';\n $('#my_musics').append(html);\n }\n \n}", "function setUpPlaylist()\n{\nvar songDetailsHTML = '<span class=\"song-name\"> </span>'+\n '<span class=\"song-artist\"> </span>'+ \n '<span class=\"song-album\"> </span>'+\n '<span class=\"song-length\"> </span>' ;\n \n $('.totalsongs').text('Total no of Songs in the Playlist: ' + totalsongs);\n\nfor (var i=0; i < songs.length ; i++) {\n var song = songs[i]; \n $('.song-list').append('<div id=\"song'+ i + '\" class=\"song\">'+ songDetailsHTML +'</div>');\n \n $('#song'+ i + ' .song-name').text(song.name);\n $('#song'+ i + ' .song-artist').text(song.artist);\n $('#song'+ i + ' .song-album').text(song.album);\n $('#song'+ i + ' .song-length').text(song.duration);\n\n $('#song'+ i).attr('data-song-position', i) ;\n \n //Setting the Click event for songs\n $('#song' + i).click(function(){\n \n //Selecting audio element and storing it in a variable\n var audio = document.querySelector('audio');\n // Condition to check if song is not current one\n if($(this).attr('data-song-position') != currentSongPosition){\n \n // Getting the value when clicked\n var songPosition = $(this).attr('data-song-position');\n \n songPosition = parseInt(songPosition) ;\n audio.src = songs[songPosition].fileName ;\n \n //Make sure you update the variable to mark the current song\n currentSongPosition = songPosition ;\n addSongNameClickEvent(songPosition);\n \n }\n togglesong();\n });\n \n \n }\n}", "function createAdditionalVariation(){\n \n variations = new Array();\n \n for(i = 0; i < sources.length; i++){\n var variation = new Variation(sources[i].id);\n variations.push(variation);\n }\n \n currentNeume.pitches.splice(currentPitchIndex, 0, variations);\n \n document.getElementById(\"meiOutput\").value = createMEIOutput();\n document.getElementById(\"input\").innerHTML = pitchDataChangeForm();\n createSVGOutput();\n}", "function makeSoundFiles(){\n let audioFile = $(\"#audio0\"); \n for (let i=1; i<11; i++){\n let newAudio = $(audioFile).clone();\n $(newAudio).attr(\"src\", (\"audio/child\"+i+\".ogg\")); \n $(newAudio).attr(\"id\", \"audio\"+i);\n $(\"body\").append(newAudio); \n } \n}", "_setUniqueIds() {\n this.ids = this.titleElements.map(() => getRandomInt())\n }", "function generateMusic() {\n buttonMusic();\n return audioA.paused ? audioA.play() : audioA.pause();\n}", "function clickBoton(id) {\r\n // agrego el botón a la secuencia del jugador y pongo el sonido y la animacion\r\n audios[id].play();\r\n sp.push(parseInt(id));\r\n console.log(sp);\r\n\r\n document.querySelector(\".\" + botones[id]).classList.add(\"activo\");\r\n window.navigator.vibrate(70);\r\n setTimeout(function() {\r\n document.querySelector(\".\" + botones[id]).classList.remove(\"activo\");\r\n }, 1000);\r\n\r\n // si el jugador se equivoca termino el juego y reinicio las variables\r\n if (comparar()) {\r\n if (nivel - 1 > parseInt(window.localStorage[\"record\"])) {\r\n localStorage.setItem(\"record\", nivel - 1);\r\n actualizarRecord();\r\n document.querySelector(\".submitRecord\").style.display = \"block\";\r\n window.scrollTo({ top: 100, behavior: \"smooth\" });\r\n document.querySelector(\".submitRecord button\").onclick = function() {\r\n submitRecord(nivel - 1);\r\n };\r\n }\r\n document.querySelector(\".mensajes\").innerHTML =\r\n \"Has fallado, vuelve a intentarlo\";\r\n window.navigator.vibrate(700);\r\n desactivarBotones();\r\n audios[4].play();\r\n } else {\r\n // si alcancé el final del patrón sin errores avanzo al siguiente nivel\r\n if (patron.length == sp.length) {\r\n document.querySelector(\".mensajes\").innerHTML =\r\n \"Has avanzado al siguiente nivel\";\r\n desactivarBotones();\r\n\r\n setTimeout(function() {\r\n siguienteNivel();\r\n }, 2000);\r\n }\r\n }\r\n}", "function addNewMusic(responseText, songData) {\n let newSongData = responseText;\n // console.log(\"TESTING\", musicProgram.testVar);\n newSongData.forEach(function(object){\n songData.unshift(object);\n songPrint(songData);\n });\n }", "prepareFilesList(files) {\n console.log(this.position);\n console.log(this.matrixData);\n if (this.matrixData[this.displayedActionType][this.position[0]][this.position[1]].action.value == 'MF') {\n for (const item of files) {\n //item.progress = 0;\n this.matrixData[this.displayedActionType][this.position[0]][this.position[1]].musicfiles.push(item);\n // FileSaver.saveAs(item, 'test.wav');\n }\n }\n else {\n this.matrixData[this.displayedActionType][this.position[0]][this.position[1]].musicfiles = [files[0]];\n }\n }", "function updateTrackElements() { //function invoked programmatically when processing the Spotify server's response to a request for an artist's popular tracks\n for(let i=0; i<trackButtons.length; i++) { //for as long as there are elements in the 'trackButtons' array\n trackButtons[i].innerHTML += artistStrings[i] + trackTitles[i]; //set the innerHTML of the 'i'th element of 'trackButtons' to the concatenation of the 'i'th element of the 'artistStrings' and 'trackTitles' arrays\n trackULs[i].children[0].innerHTML += trackPopularities[i]; //set the innerHTML of the first <li> child element of the 'i'th element of 'trackULs' to its existing innerHTML plus the 'i'th element of the 'trackPopularities' array\n trackULs[i].children[1].innerHTML += durations[i]; //set the innerHTML of the second <li> child element of the 'i'th element of 'trackULs' to its existing innerHTML plus the 'i'th element of the 'durations' array\n }\n}", "addSong(){\n const url = urlInput.value\n const id = url.substr(url.indexOf(\"=\") + 1)\n const title = titleInput.value\n \n var validate = validation()\n if(!validate.isValidInput(playList, id, url, title)){\n return validate.render()\n }\n \n const song = {\n id: id,\n title: title\n }\n \n selectedVideo = id \n playList.push(song)\n this.render()\n }", "addFavourite() {\n if (localStorage.music) {\n let musiclist = localStorage.music.split(',');\n musiclist.push(this.music.src);\n localStorage.music = musiclist;\n // sid\n let sidlist = localStorage.sid.split(',');\n sidlist.push(this.src_sid);\n localStorage.sid = sidlist;\n // picture\n let picturelist = localStorage.picture.split(',');\n picturelist.push(this.src_picture);\n localStorage.picture = picturelist;\n // singer\n let singerlist = localStorage.singer.split(',');\n singerlist.push(this.src_singerName);\n localStorage.singer = singerlist;\n // title\n let titlelist = localStorage.title.split(',');\n titlelist.push(this.src_musicName);\n localStorage.title = titlelist;\n } else {\n let musiclist = [];\n musiclist.push(this.music.src);\n localStorage.music = musiclist;\n\n // sid\n let sidlist = [];\n sidlist.push(this.src_sid);\n localStorage.sid = sidlist;\n // picture\n let picturelist = [];\n picturelist.push(this.src_picture);\n localStorage.picture = picturelist;\n // singer\n let singerlist = [];\n singerlist.push(this.src_singerName);\n localStorage.singer = singerlist;\n // title\n let titlelist = [];\n titlelist.push(this.src_musicName);\n localStorage.title = titlelist;\n }\n }", "addToLocalStorage() {\n const songsInStorage = localStorage.getItem(\"Songs\");\n let currentArray = [];\n if (songsInStorage) {\n currentArray = JSON.parse(songsInStorage);\n currentArray.unshift(this.props.info);\n currentArray = Array.from(new Set(currentArray));\n localStorage.setItem(\"Songs\", JSON.stringify(currentArray));\n } else {\n currentArray = [];\n currentArray.unshift(this.props.info);\n localStorage.setItem(\"Songs\", JSON.stringify(currentArray));\n }\n }", "function amplitude_previous_song() {\n if(amplitude_active_song.getAttribute('amplitude-visual-element-id') != ''){\n if(document.getElementById(amplitude_active_song.getAttribute('amplitude-visual-element-id'))){\n document.getElementById(amplitude_active_song.getAttribute('amplitude-visual-element-id')).className = document.getElementById(amplitude_active_song.getAttribute('amplitude-visual-element-id')).className.replace('amplitude-now-playing', '');\n }\n }\n var amplitude_nodes = document.getElementById('amplitude-playlist').getElementsByTagName('audio');\n //If the shuffle is activated, then go to the previous song in the shuffle array. Otherwise go back in the playlist.\n if(amplitude_shuffle){\n for(i=0; i<amplitude_shuffle_list.length; i++){\n if(amplitude_shuffle_list[i] == amplitude_active_song.getAttribute('id')){\n if(typeof amplitude_shuffle_list[i-1] != 'undefined'){\n amplitude_play(amplitude_shuffle_list[i-1]);\n }else{\n amplitude_play(amplitude_shuffle_list[amplitude_shuffle_list.length-1]);\n }\n break;\n }\n }\n }else{\n for (i=0; i<amplitude_nodes.length; i++) {\n if (amplitude_nodes[i].getAttribute(\"id\") == amplitude_active_song.getAttribute('id')) {\n if (typeof amplitude_nodes[i-1] != 'undefined') {\n amplitude_play(amplitude_nodes[i-1].getAttribute(\"id\"));\n }else{\n amplitude_play(amplitude_nodes[amplitude_nodes.length-1].getAttribute(\"id\"));\n }\n break;\n }\n }\n }\n\n amplitude_active_song_information['cover_art'] = amplitude_active_song.getAttribute('amplitude-album-art-url');\n amplitude_active_song_information['artist'] = amplitude_active_song.getAttribute('amplitude-artist');\n amplitude_active_song_information['album'] = amplitude_active_song.getAttribute('amplitude-album');\n amplitude_active_song_information['title'] = amplitude_active_song.getAttribute('amplitude-title');\n\n if(typeof amplitude_config != 'undefined'){\n if(typeof amplitude_config.amplitude_previous_song_callback != 'undefined'){\n var amplitude_previous_song_callback_function = window[amplitude_config.amplitude_previous_song_callback];\n amplitude_previous_song_callback_function();\n }\n }\n}", "function checkPlaylists(value) {\n var song;\n var index = -1;\n for(i = 0; i < temp_songs.length; i++) {\n if(temp_songs[i].href == value) {\n song = temp_songs[i];\n };\n };\n\n var name = prompt(\"Enter playlist name\");\n for (i = 1; i < user_playlists.length; i++) {\n if(user_playlists[i].name == name) {\n index = i;\n };\n };\n\n if(index == -1) {\n alert(\"Playlist by that name does not exist\");\n return;\n };\n\n var color = document.getElementById(\"1\" + value).style.color;\n if (color == 'red') {\n for (i = 0; i < user_playlists[index].songs.length; i++) {\n if(user_playlists[index].songs.href == value) {\n document.getElementById(value).style.color = 'black';\n return;\n };\n };\n user_playlists[index].songs.push(song);\n document.getElementById(\"1\" + value).style.color = 'black';\n }\n else {\n var j;\n for (i = 0; i < user_playlists[index].songs.length; i++) {\n if(user_playlists[index].songs.href == value) {\n j = i;\n };\n };\n user_playlists[index].songs.splice(j, 1);\n document.getElementById(\"1\" + value).style.color = 'red';\n };\n}", "function addToPlaying(){\n Chord.audio.playing.push(this);\n }", "addSong(selectedSong){\r\n let newItem = this.userBand + \" - \" + selectedSong;\r\n //prevents adding of duplicate songs\r\n this.userSetlist.indexOf(newItem) === -1 ? this.userSetlist.push(newItem) : console.log(\"This song is already in the list\");\r\n }", "function giveHintsButtonHandler() {\n //add click sound\n if (allowSound) { playClick.play() };\n \n for (let i = 1; i <= 8; i++) {\n for (let j = 1; j <= 8; j++) {\n if (document.getElementById(i+'-'+j).classList.contains('hints')) {\n document.getElementById(i+'-'+j).classList.remove('hints');\n }\n }\n }\n \n let allHintsArr = findAllHints();\n \n if (allHintsArr.length > 0) {\n let m = Math.floor(Math.random()*(allHintsArr.length));\n for (let i = 0; i < allHintsArr[m].length; i++) {\n document.getElementById(allHintsArr[m][i][0] + '-' + allHintsArr[m][i][1]).classList.add('hints');\n }\n if (allowSound) { \n setTimeout(playHintsUsed.play(), 300);\n }\n \n }\n\n score -= 30;\n playerScore.textContent = score;\n \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 inputUpdater () {\n possibleInputs = {\n previous: [imgArray[previousFirst], imgArray[previousSecond], imgArray[previousThird]],\n current: [imgArray[firstImageNumber], imgArray[secondImageNumber], imgArray[thirdImageNumber]],\n blank: [{name: 'click', path: './assets/blank.jpg'}, {name: 'an', path: './assets/blank.jpg'}, {name: 'image', path: './assets/blank.jpg'}]\n };\n}", "function redoArrays() {\n // Pop out the selected defender character id from the original \n // array.\n charNames.splice(selectedChar.Id, 1);\n // Pop out the selected defender character Pid Addres id \n // from the original array.\n charPicIndexAddres.splice(selectedChar.Id, 1);\n // Pop out the selected defender character Thumbnail Pid Addres id \n // from the original array.\n charThumbnailPicSAddres.splice(selectedChar.Id, 1);\n // Pop out the selected defender character Company id \n // from the original array.\n charSelCompany.splice(selectedChar.Id, 1);\n\n}", "update() {\n // deal with input\n if (G.input.isPressed(G.input.ESC)) {\n G.audio.playSE('se/menu-back.mp3');\n // press ESC to back to title\n G.scene = new SceneTitle();\n G.lastSelectMusic = this.selected;\n } else if (G.input.isPressed(G.input.UP) || G.input.isPressed(G.input.LEFT)) {\n // press UP or LEFT to select music above\n this.selected = (this.selected - 1 + G.musics.length) % G.musics.length;\n G.audio.playSE('se/menu-cursor.mp3');\n this.animateMusicSprites();\n } else if (G.input.isPressed(G.input.DOWN) || G.input.isPressed(G.input.RIGHT)) {\n // press DOWN or RIGHT to select music below\n this.selected = (this.selected + 1) % G.musics.length;\n G.audio.playSE('se/menu-cursor.mp3');\n this.animateMusicSprites();\n } else if (G.input.isPressed(G.input.ENTER)) {\n G.audio.playSE('se/menu-click.mp3');\n // press ENTER to enter playfield or editor\n G.lastSelectMusic = this.selected;\n switch (G.mode) {\n case 'play':\n G.scene = new SceneGaming(this.selected);\n break;\n case 'edit':\n G.scene = new SceneEditor(this.selected);\n break;\n default:\n break;\n }\n }\n }", "function updateSongPos()\r\n{\r\n for (var i=0; i < songsPlayed.length; i++) {\r\n songsPlayed[i][\"place\"] = i;\r\n }\r\n}", "function addBookToLibrary() {\n let title = document.querySelector('#titleinput').value\n let author = document.querySelector('#authorinput').value\n let pages = document.querySelector('#pagesinput').value\n let read = document.querySelector('#modal-check').checked\n let newBook = new Book(title, author, pages, read)\n myLibrary.push(newBook)\n document.querySelector('#modal').classList.remove('active') \n document.querySelector('#overlay').classList.remove('active')\n document.querySelectorAll(\"input\").forEach(input => {\n input.value = \"\"\n }) \n clear()\n refresh() \n}", "function arrayInitializer() {\n shuffle(soundArray); // Shuffles the array using helper function which can be located at the bottom of this doc\n let numb = 13;\n for(i = 0; i < soundArray.length; i++) {\n soundArray[i]['pin'] = numb; // Add a pin number to each array entry\n numb--; // Starting the number from 13 (pin) and going down\n }\n updateSong();\n}", "function init(){\n\t\tvar playButtonA = document.getElementById('a');\n\t\tplayButtonA.addEventListener('click', playAudioA, false);\n\n\t\tvar playButtonB = document.getElementById('b');\n\t\tplayButtonB.addEventListener('click', playAudioB, false);\n\t\t\t\n\t\tvar playButtonC = document.getElementById('c');\n\t\tplayButtonC.addEventListener('click', playAudioC, false);\n\n\t\tvar playButtonD = document.getElementById('d');\n\t\tplayButtonD.addEventListener('click', playAudioD, false);\n\n\t\tvar playButtonE = document.getElementById('e');\n\t\tplayButtonE.addEventListener('click', playAudioE, false);\n\t\t\t\n\t\tvar playButtonF = document.getElementById('f');\n\t\tplayButtonF.addEventListener('click', playAudioF, false);\n\n\t\tvar playButtonG = document.getElementById('g');\n\t\tplayButtonG.addEventListener('click', playAudioG, false);\n\n\t\tvar playButtonH = document.getElementById('h');\n\t\tplayButtonH.addEventListener('click', playAudioH, false);\n\t\t\t\n\t\tvar playButtonI = document.getElementById('i');\n\t\tplayButtonI.addEventListener('click', playAudioI, false);\n\n\t\tvar playButtonJ = document.getElementById('j');\n\t\tplayButtonJ.addEventListener('click', playAudioJ, false);\n\t\t}//init end ***", "function setMusicIndex(index){\n\tdocTitle.innerText= list_songs[index].title;\n\tdocArtist.innerText= list_songs[index].artist;\n\tdocImage.src=`images/${list_songs[index].image}.jpg`;\n\tmusic.src=`music/${list_songs[index].title}.mp3`;\n}", "function saveAndUpdate() {\n for (var y = 0 ; y < MarketingItem.allImages.length ; y ++ ){\n if (localStorageExists){\n clickarray[y] += MarketingItem.allImages[y].clicks;\n seenarray[y] += MarketingItem.allImages[y].timesShown;\n } else {\n //if local storage doesnt exist, push into empty storage array\n clickarray.push( MarketingItem.allImages[y].clicks );\n seenarray.push( MarketingItem.allImages[y].timesShown );\n }\n }\n}", "function init(){\n\n // enable key listeners\n\n enableKeyboardKeys();\n enableSliders();\n\n\n var song = [63, 70, 78, 56, 34, 63];\n //playArrayOfNotes(song);\n\n}", "reloadscriptlist(){\n this.scriptcomponents = [];\n this.gunobjectlist('scriptcomponents',(_obj)=>{\n //console.log(_obj);\n this.scriptcomponents.push(_obj);\n });\n }", "function songDiv(j, type) {\n let songModal = document.createElement(\"div\");\n songModal.classList.add(\"modal\", `modal-${type}`)\n songModal.innerHTML = `<div class=\"modal-cut material-icons\">west</div>`;\n\n let data = getFilteredData(type);\n for (let i = 0; i < data.length; i++) {\n songModal.appendChild(createSingleSongDiv(data[i].song, data[i].artist, data[i].type))\n }\n\n document.querySelector(\".searched-items-container\").append(songModal);\n\n let numberOfSongs = document.querySelectorAll(\".song-play-pause\")\n for (let i = 0; i < numberOfSongs.length; i++) {\n numberOfSongs[i].addEventListener(\"click\", function () {\n\n document.querySelector(\".container-image\").setAttribute(\"src\", `./Cover/${data[i].type}/${data[i].song}.jpg`)\n document.querySelector(\".song-details-container\").innerHTML = `${data[i].song} - ${data[i].artist}`;\n\n myAudio.setAttribute(\"src\", `./Music/${data[i].type}/${data[i].song}.mp3`)\n\n console.log(myAudio.duration)\n\n if (numberOfSongs[i].innerHTML === \"play_circle_filled\") {\n for (let i = 0; i < numberOfSongs.length; i++) {\n numberOfSongs[i].innerHTML = \"play_circle_filled\"\n }\n document.querySelector(\"#play-pause\").innerHTML = numberOfSongs[i].innerHTML = \"pause_circle_filled\"\n myAudio.play();\n\n } else {\n document.querySelector(\"#play-pause\").innerHTML = numberOfSongs[i].innerHTML = \"play_circle_filled\"\n myAudio.pause();\n }\n\n })\n }\n\n document.querySelector(\".modal-cut\").addEventListener(\"click\", function () {\n songModal.remove()\n })\n}", "function addToWikidataArray(wikidataId) {\n var selected = whatsSelected();\n //console.log(selected);\n //console.log(wikidataIds.length);\n //console.log(\"Das ist die Wikidata ID: \"+wikidataId);\n wikidataIds[selected].push(wikidataId);\n //console.log(wikidataIds);\n createOutput();\n}", "function giphyButtons() {\n\n $(\"#puppyLibrary\").empty();\n\n for ( var i = 0; i < allPuppies.length; i++) {\n var button = $(\"<button>\" + allPuppies[i] + \"</button>\");\n button.attr(\"data-dog-type\",allPuppies[i]);\n $(\"#puppyLibrary\").append(button);\n }\n }", "function playNotes(){\n\t var playButtonA= document.getElementById('a');\n\t playButtonA.addEventListener('click', playAudioA, false);\n\n\t var playButtonAs = document.getElementById('A#');\n\t playButtonAs.addEventListener('click', playAudioAs, false);\n\n\t var playButtonB = document.getElementById('b');\n\t playButtonB.addEventListener('click', playAudioB, false);\n\n\t var playButtonC = document.getElementById('c');\n\t playButtonC.addEventListener('click', playAudioC, false);\n\n\t var playButtonCs = document.getElementById('C#');\n\t playButtonCs.addEventListener('click', playAudioCs, false);\n\n\t var playButtonD = document.getElementById('d');\n\t playButtonD.addEventListener('click', playAudioD, false);\n\n\t var playButtonDs = document.getElementById('D#');\n\t playButtonDs.addEventListener('click', playAudioDs, false);\n\n\t var playButtonE = document.getElementById('e');\n\t playButtonE.addEventListener('click', playAudioE, false);\n\n\t var playButtonE = document.getElementById('f');\n\t playButtonF.addEventListener('click', playAudioF, false);\n\n\t var playButtonFs = document.getElementById('F#');\n\t playButtonFs.addEventListener('click', playAudioFs, false);\n\n\t var playButtonG = document.getElementById('g');\n\t playButtonG.addEventListener('click', playAudioG, false);\n\n\t var playButtonGs = document.getElementById('G#');\n\t playButtonGs.addEventListener('click', playAudioGs, false);\n\n\t var playButtonA2 = document.getElementById('a2');\n\t playButtonA2.addEventListener('click', playAudioA2, false);\n\n\t var playButtonA2s = document.getElementById('A#2');\n\t playButtonA2s.addEventListener('click', playAudioA2s, false);\n\n\t var playButtonB2 = document.getElementById('b2');\n\t playButtonB2.addEventListener('click', playAudioB2, false);\n\t }", "function updateSongSelectorPerm0() {\n// position 0\n createARegularSongDiv(3, 0);\n// position 1\n createARegularSongDiv(4, 1);\n// position 2 - main position\n createMiddleSongDiv(0, 2);\n// position 3\n createARegularSongDiv(1, 3);\n// position 4\n createARegularSongDiv(2, 4);\n}", "function updateFileList() {\n for (var i = 0; i < fileUpload.files.length; i++) {\n renderFile(fileUpload.files[i]);\n }\n\n\n omniButtonIcon.classList = \"fa fa-cog omniButtonIconNoVisualization\";\n omniButton.mode = \"generateWorkout\";\n omniButtonPrompt.innerHTML = \"Analyze Your Awesome Songs\"\n fileUpload.classList += \" hidden\";\n\n}", "function displaySongUpdateStatus(data) {\r\n\tvar obj = JSON.parse(data);\r\n\tvar cssSelector = {\r\n\t\tjPlayer: \"#jquery_jplayer_2\",\r\n\t\tcssSelectorAncestor: \"#jp_container_2\"\r\n\t};\r\n\tvar playlist = [];\r\n\tvar options = {\r\n\t\tswfPath: \"js\",\r\n\t\tsupplied: \"mp3\",\r\n\t\tuseStateClassSkin: true\r\n\t};\r\n\tvar myPlaylist = new jPlayerPlaylist(cssSelector, playlist, options);\r\n\t/*Loop through the JSon array and add it to the playlist*/\r\n\tvar l=obj.length;\r\n\tfor (var i=0;i<l; i++) {\r\n \tmyPlaylist.add({\r\n\t\t\ttitle: obj[i].title,\r\n\t\t\tmp3: obj[i].mp3\r\n\t\t});\r\n\t}\r\n}", "changeRating(id, rating) {\n console.log('Code reached in the MusicPanel', id, rating)\n\n let newSongs = [...this.state.songs]\n\n newSongs.forEach((ele, index, arr) => {\n if (ele._id == id) {\n arr[index].rating = rating\n }\n })\n\n this.setState({ songs: newSongs })\n this.modifySong(id, rating)\n }", "static renderMixtapes(mixtapesInfo){\n clearContainer(mixtapesContainer())\n Mixtape.all = []\n mixtapesInfo.forEach(mixtape => {\n let new_mixtape = new Mixtape(mixtape.id, mixtape.title, mixtape.description, mixtape.artist, mixtape.likes, mixtape.opinions)\n Mixtape.all.push(new_mixtape)\n // let mixtape = new Mixtape(mixtapeInfo.id, mixtapeInfo.title, mixtapeInfo.description, mixtapeInfo.artist, mixtapeInfo.likes, mixtapeInfo.opinions,)\n // mixtape.save\n let div = document.createElement(\"div\")\n let h3 = document.createElement(\"h3\")\n let p = document.createElement('p')\n let p2 = document.createElement('p')\n let likeButton = document.createElement('button')\n let ul = document.createElement('ul')\n let tapeLikes = document.createElement('p')\n let deleteButton = document.createElement('button')\n let form = document.createElement(\"form\")\n let input = document.createElement(\"input\")\n let submitOpinion = document.createElement(\"button\")\n\n let mixtapeOpinions = Opinion.renderOpinions(mixtape.opinions) \n //filling in that imaginary box with that inforamtion \n div.id = mixtape.id\n div.style.padding = \"40px\"\n div.style.backgroundColor = \"#FADCF3\"\n div.className = 'card'\n h3.innerText = mixtape.title\n p.innerText = mixtape.artist\n p2.innerText = mixtape.description\n tapeLikes.innerText = mixtape.likes\n likeButton.innerText = \"♥\"\n likeButton.addEventListener('click', Mixtape.likeMixtape.bind(mixtape))\n deleteButton.innerText = \"x\"\n deleteButton.addEventListener(\"click\", Mixtape.deleteMixtape.bind(mixtape))\n\n input.type = \"text\"\n input.placeholder = \"type your opinion here...\"\n submitOpinion.type = \"submit\"\n submitOpinion.innerText = \"Submit\"\n form.addEventListener(\"submit\", Mixtape.createOpinion.bind(mixtape))\n form.appendChild(input)\n form.appendChild(submitOpinion)\n\n //appending to child bringing that imagainary box to life on the browser to see\n div.appendChild(h3)\n div.appendChild(p)\n div.appendChild(tapeLikes)\n div.appendChild(p2)\n div.appendChild(likeButton)\n div.appendChild(deleteButton)\n mixtapeOpinions.forEach(li => ul.appendChild(li))\n div.appendChild(ul)\n div.appendChild(form)\n mixtapesContainer().appendChild(div)\n\n\n })\n }", "function update(array){\n let newTodo = textinput.value;\n array.push(newTodo);\n console.log('array', array);\n chrome.storage.sync.set({ list: array }, function() {\n console.log(\"added to list with new values\");\n });\n displayTodos();\n}", "setVolume(volumeMusic, volumeSound, max){\n //comprobamos que sea musica comparando su nombre con los assets correspondientes\n let aux = max - volumeMusic > 0 ? Math.log(max - volumeMusic) : 0;\n volumeMusic = (1- (aux/ Math.log(max)));\n aux = max - volumeSound > 0 ? Math.log(max - volumeSound) : 0;\n volumeSound = (1- (aux/ Math.log(max)));\n\n let music = new Map().set(\"game-theme.mp3\", true);\n if(this.sound_manager != null){\n $.each(this.sound_manager.sounds, function(index, sound){\n if(sound != null && sound.name != null){\n if(music.get(sound.name.split(\"/\").pop()) === true){\n sound.volume = volumeMusic;\n }else{\n sound.volume = volumeSound;\n }\n }\n });\n }\n }", "function render0() {\n var picker0 = 0;\n picker0 = ranNum();\n oldPics.push(picker0);\n console.log('first rando: ' + picker0);\n // Now we make our loop to temporarily trash used indices\n while (picker0 === oldPics[0]) {\n ranNum();\n picker0 = ranNum();\n console.log('new rando: ' + picker0);\n }\n console.log('shiny new rando: ' + picker0);\n oldPics[0] = picker0;\n // populate that used index value into the trash\n staple.src = allProducts[picker0].idName;\n // oldPics[0] = picker0;\n // console.log(oldPics[0]);\n}", "function addToFavourites(id) {\n favourites.push(id);\n // uniqueFavourites = [...new Set(favourites)];\n document.getElementById(id).disabled = true;\n return;\n}", "function setQuestions(){\n for(i = 0; i < quizLength; i++){\n var randomNum = Math.floor(Math.random() * quiz.length);\n if(questionsArray.indexOf(randomNum) != -1){\n i--;\n } else {\n questionsArray.push(randomNum);\n }\n }\n }", "function repeatOneMusic() {\n // here we'll reset the musicIndex accordingly\n musicIndex = musicIndex;\n loadMusic(musicIndex);\n playMusic();\n }", "function ArrChanges(VidTitle){\r\n var ArrNR = AllVideoArr.length-1\r\n\r\n //Main\r\n var Main = document.createElement(\"Main\")\r\n Main.setAttribute(\"id\",\"VidResult\"+AllVideoArr.length)\r\n Main.setAttribute(\"class\",\"resultVid\")\r\n\r\n //Control Div\r\n var ControlDiv = document.createElement(\"Main\")\r\n ControlDiv.setAttribute(\"id\",\"VidCtrl_\"+AllVideoArr.length)\r\n ControlDiv.setAttribute(\"class\",\"VidCtrl\")\r\n\r\n //iframe\r\n var ifrm = document.createElement(\"iframe\");\r\n ifrm.setAttribute(\"id\", \"VidID_\"+AllVideoArr.length)\r\n ifrm.setAttribute(\"class\",\"VideIframe\")\r\n ifrm.setAttribute(\"src\",AllVideoArr[ArrNR].Src);\r\n //title\r\n var VidTxt = document.createElement(\"h4\")\r\n VidTxt.innerHTML = VidTitle\r\n\r\n\r\n\r\n // 3 Control Buttons\r\n var playBtn = document.createElement(\"button\")\r\n playBtn.setAttribute(\"id\",\"playBtn_\"+AllVideoArr.length)\r\n playBtn.setAttribute(\"onclick\",\"YTcontrol(this.id)\")\r\n playBtn.setAttribute(\"class\",\"PlayBtn\")\r\n playBtn.innerHTML=\"Play\"\r\n\r\n var pauseBtn = document.createElement(\"button\")\r\n pauseBtn.setAttribute(\"id\",\"pauseBtn_\"+AllVideoArr.length)\r\n pauseBtn.setAttribute(\"onclick\",\"YTcontrol(this.id)\")\r\n pauseBtn.setAttribute(\"class\",\"PauseBtn\")\r\n pauseBtn.innerHTML=\"Pause\"\r\n\r\n var stopBtn = document.createElement(\"button\")\r\n stopBtn.setAttribute(\"id\",\"stopBtn_\"+AllVideoArr.length)\r\n stopBtn.setAttribute(\"onclick\",\"YTcontrol(this.id)\")\r\n stopBtn.setAttribute(\"class\",\"StopBtn\")\r\n stopBtn.innerHTML=\"Stop\"\r\n\r\n var RemoveBtn = document.createElement(\"button\")\r\n RemoveBtn.setAttribute(\"onclick\",\"removeVid(this.id)\")\r\n RemoveBtn.setAttribute(\"id\",\"removeBtn_\"+AllVideoArr.length)\r\n RemoveBtn.setAttribute(\"class\",\"RemoveBtn\")\r\n RemoveBtn.innerHTML=\"X\"\r\n\r\n //append child\r\n ControlDiv.appendChild(playBtn)\r\n ControlDiv.appendChild(pauseBtn)\r\n ControlDiv.appendChild(stopBtn)\r\n ControlDiv.appendChild(RemoveBtn)\r\n Main.appendChild(ifrm)\r\n Main.appendChild(VidTxt)\r\n Main.appendChild(ControlDiv)\r\n document.getElementById(\"YT_Playlist\").appendChild(Main)\r\n\r\n console.log(AllVideoArr)\r\n}", "function updateID(array) {\n if (array.length != 0) {\n for (let i = 0; i < array.length; i++) {\n array[i].id = i;\n }\n }\n}", "onAddToPlaylist(index) {\n const { addToPlaylist, addClipToPlaylist, clip } = this.props;\n\n // Add the clip to playlist.list\n addToPlaylist(clip.list[index]);\n\n // Set in the clip that is part of the playlist\n addClipToPlaylist(clip.list[index].id);\n }", "setCookieConsentScriptsArray(){\n\n let title;\n const json_data = this.cookieBannerScripts;\n\n if(json_data.length > 0 ){\n for(let i = 0; i < json_data.length; i++) {\n //get all scripts and activate them\n if(this.cookieConsent === \"allow\"){\n //must be encoded in cookie values\n title = encodeURIComponent(json_data[i].script_title);\n this.cookieConsentScriptsArray.set(title,{allowed:true})\n }\n else{\n //get just standard activated scripts\n if(json_data[i].script_cookies_standard === 'activated'){\n //must be encoded in cookie values\n title = encodeURIComponent(json_data[i].script_title);\n this.cookieConsentScriptsArray.set(title,{allowed:true})\n }\n }\n }\n }\n //set values to cookie cookieconsent_scripts\n this.setConsentScriptsToCookie(this.cookieConsentScriptsArray);\n\n const data = this.cookieConsentScriptsArray;\n\n this.createScriptCode(data);\n }", "function clicked(musicId) {\n musicIndex = musicId;\n loadMusic(musicIndex);\n playMusic();\n playingNow();\n }", "function searchTracks() {\n let searchResults = trackInput.value;\n\n fetch('https://api.soundcloud.com/tracks/?client_id=86b6a66bb2d863f5d64dd8a91cd8de94&q=' + searchResults).then(function(response) {\n if (response.status != 200) {\n console.log('Looks like there was a problem. Status Code' + response.status);\n return;\n }\n\n response.json().then(function(data) {\n let track = data;\n console.log(track);\n\n\n\n let searchedFor = document.createElement('div');\n\n searchedFor.id = 'searchedFor';\n document.body.appendChild(searchedFor);\n document.getElementById('searched').appendChild(searchedFor);\n searchedFor.className = 'searchedFor';\n searchedFor.innerHTML = \"Recent Searches\" +\": \"+ searchResults;\n\n\n\n var clientId = \"/?client_id=86b6a66bb2d863f5d64dd8a91cd8de94\";\n function renderTracks() {\n\n return `\n ${track.map(track =>\n `<div class=\"box\">\n <div class=\"blankImage\"></div>\n <div src=\"${track.stream_url}\"></div>\n <button id=\"albumBtn\" class=\"albumButton\"><img id=\"${track.stream_url}${clientId}\" src=\"${track.artwork_url}\"></img></button>\n <div id=\"songTitle\" class=\"title\">${track.title}</div>\n </div>`\n )}\n `\n }\n\n let markup = `${renderTracks()}`;\n document.getElementById('bands').innerHTML = markup;\n\n var playThis = document.getElementsByClassName('albumButton');\n var playInDocument = document.getElementById('bands').addEventListener('click', function (event) {\n event.target = playThis;\n let playTrack = `<audio src=\"${event.target.id}\" id=\"audio\" controls=\"controls\"></audio>`\n \n return document.getElementById('playAudioHere').innerHTML = playTrack\n\n\n })\n\n\n })\n })\n}", "function audioupdate(data){\n let client = findclientbyid(data.clientid);\n if(client.clientid == userid || client == null)\n return;\n let videobox = client.videobox;\n client.cameraaudio = data.cameraaudio;\n if(client.cameraaudio == false){\n buttonOff(videobox.querySelector('.videobox__icon.audio'));\n }else{\n buttonOn(videobox.querySelector('.videobox__icon.audio'));\n }\n}", "function muteSound() {\n let soundOff = \"<i class='fas fa-volume-mute'></i>\";\n let soundOn = \"<i class='fas fa-volume-up'></i>\";\n let soundsArray = [buttonPress, correctAnswerSound, wrongAnswerSound, highScoreSound, wellDoneSound, sadSound];\n if ($(\".mute-sound\").attr(\"data-sound\") === \"off\") {\n $(\".mute-sound\").html(soundOn);\n $(\".mute-sound\").attr(\"data-sound\", \"on\");\n buttonPress.sound.volume = 0.7;\n for (let item of soundsArray) {\n item.sound.muted = false;\n }\n buttonPress.play();\n } else {\n $(\".mute-sound\").html(soundOff);\n $(\".mute-sound\").attr(\"data-sound\", \"off\");\n for (let item of soundsArray) {\n item.sound.muted = true;\n }\n }\n}", "function updateWikidataArray(previousColor, wikidataId) {\n var selected = whatsSelected();\n //Find out which district number is previousColor\n var i = stdColors.indexOf(previousColor);\n //console.log(\"The previous color is at array position: \" +i);\n //Find the Wikdata ID in the subarray\n var j = wikidataIds[i].indexOf(wikidataId);\n //console.log(\"The Wikidata ID to be removed is at subarray position: \" +j);\n //Remove the Wikidata ID from subarray\n wikidataIds[i].splice(j,1); //at position j remove 1 item\n //Add the Wikidata ID to the newly selected district\n wikidataIds[selected].push(wikidataId);\n console.log(wikidataIds);\n createOutput();\n}", "refresh(song, action) {\n\t\tvar newArr = this.state.next_song\n\t\tif(action) {\n\t\t\tnewArr.push(song.tracks[0])\n\t\t} else {\n\t\t\tvar index = newArr.map((song) => song.id).indexOf(song.tracks[0].id)\n\t\t\tif(index > -1) {\n\t\t\t\tnewArr.splice(index, 1)\n\t\t\t}\n\t\t}\n\t\tthis.setState({\n\t\t\tnext_song: newArr\n\t\t})\n\t}" ]
[ "0.60121244", "0.584303", "0.56773216", "0.56380814", "0.56331545", "0.561573", "0.5596808", "0.55637485", "0.5543055", "0.55359364", "0.55076516", "0.55037385", "0.5479161", "0.54761815", "0.54678607", "0.545355", "0.5438671", "0.5424687", "0.5396854", "0.5377546", "0.536396", "0.53393173", "0.53207105", "0.5316764", "0.5309431", "0.5308651", "0.52819496", "0.52638906", "0.52635247", "0.5252991", "0.5248001", "0.5227894", "0.52180916", "0.52088666", "0.5207561", "0.5193246", "0.51856714", "0.51518226", "0.51499933", "0.51436925", "0.51403755", "0.5135675", "0.51265234", "0.51248556", "0.5124323", "0.5120926", "0.51206607", "0.51125133", "0.5091919", "0.5089129", "0.5081285", "0.507995", "0.50685054", "0.506537", "0.50632", "0.50540024", "0.5046374", "0.5044428", "0.50432485", "0.50432163", "0.50411874", "0.5024914", "0.50221896", "0.5015702", "0.5002211", "0.49920258", "0.49910638", "0.49823675", "0.49783882", "0.4976829", "0.4974987", "0.49717736", "0.49710056", "0.49536508", "0.49527115", "0.49518672", "0.49508393", "0.49451125", "0.49444002", "0.49416065", "0.49401745", "0.4939134", "0.4938245", "0.4937116", "0.49343765", "0.49261624", "0.4925513", "0.49231288", "0.4921786", "0.49081123", "0.49031475", "0.49027577", "0.48985928", "0.4897417", "0.4896018", "0.4890344", "0.4888376", "0.48883212", "0.4883159", "0.48827174" ]
0.7030591
0
eg: Fri, 16 Aug 2019 10.31 AM
static momentToFormat1(momentObj) { let datetime = Moment(momentObj); return (datetime.format('ddd, DD MMM YYYY h:mm A')); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "processDate ( ) {\n let days = [ 'Monday', 'Tuesday', 'Wednesday',\n 'Thursday', 'Friday', 'Saturday', 'Sunday' ];\n let date = new Date ( this.data.release_date ).toDateString ( );\n let split = date.split ( ' ' );\n let fullday = days.filter ( x => x.indexOf ( split [ 0 ] ) !== -1 );\n return `${fullday}, ${split [ 1 ]} ${ split [ 2 ]} ${split [ 3 ]}`;\n }", "function getDateStamp() {\n ts = moment().format('MMMM Do YYYY, h:mm:ss a')\n ts = ts.replace(/ /g, '-') // replace spaces with dash\n ts = ts.replace(/,/g, '') // replace comma with nothing\n ts = ts.replace(/:/g, '-') // replace colon with dash\n console.log('recording date stamp: ', ts)\n return ts\n}", "static format (doc) {\n return moment(doc.createdAt).format('M/D h:mm a')\n }", "getFormattedDate(date) {\n return dayjs(date).format(\"MMM MM, YYYY\");\n }", "formatted_date() {\n return this.created_at.toLocaleDateString()\n }", "renderDate() {\n return moment.utc(this.props.party.date).format('MM/DD/YYYY [at] h:mm A');\n }", "dateForHumans(item) {\n if (!item.date) return \"\";\n let startDate = DateTime.fromISO(item.date).toFormat(\"d LLLL yyyy\");\n if (!item.time && !item.enddate) return startDate;\n if (item.time) return `${startDate} at ${item.time}`;\n if (!item.enddate) return startDate;\n\n let endDate = DateTime.fromISO(item.enddate).toFormat(\"d LLLL yyyy\");\n return `${startDate} to ${endDate}`;\n }", "function formatDate(){\n\n // Date format FEB 11, 2016\n var month = streamInfo['updated_at'].substr(5,2);\n\n switch (month){\n case '01':\n month = 'JAN ';\n break;\n case '02':\n month = 'FEB ';\n break;\n case '03':\n month = 'MAR ';\n break;\n case '04':\n month = 'APR ';\n break;\n case '05':\n month = 'MAY ';\n break;\n case '06':\n month = 'JUN ';\n break;\n case '07':\n month = 'JUL ';\n break;\n case '08':\n month = 'AUG ';\n break;\n case '09':\n month = 'SEP ';\n break;\n case '10':\n month = 'OCT,';\n break;\n case '11':\n month = 'NOV,';\n break;\n case '12':\n month = 'DEC,';\n break;\n default :\n month = '';\n }\n\n var date = month + streamInfo['updated_at'].substr(8,2)+ ', ' + streamInfo['updated_at'].substr(0,4);\n\n return date;\n }", "function a(e,a,t){var n=\" \";return(e%100>=20||e>=100&&e%100==0)&&(n=\" de \"),e+n+{ss:\"secunde\",mm:\"minute\",hh:\"ore\",dd:\"zile\",MM:\"luni\",yy:\"ani\"}[t]}", "eventDetailsFullDate(date) {\n\t\treturn Moment(date).format('ddd, DD of MMMM gggg');\n\t}", "function createdOnParser(data) {\n let str = data.split('T');\n let date = str[0];\n let time = str[1].split('.')[0];\n return `${ date } at ${ time }`;\n }", "getFormattedDate(event) {\n console.log(event[\"startDate\"]);\n let arr = event[\"startDate\"].split(' ');\n let arr2 = arr[0].split('-');\n let arr3 = arr[1].split(':');\n let date = new Date(arr2[0] + '-' + arr2[1] + '-' + arr2[2] + 'T' + arr3[0] + ':' + arr3[1] + '-05:00');\n return date;\n }", "static get timestamp() {\n return `[${moment().format('MM/DD/YYYY HH:mm:ss')}]`;\n }", "format(value) {\n return moment.utc(value).format('YYYY-MM-DD');\n }", "tConvert(time, format) {\n if (format == 12) {\n let timeArr = time.split(\":\");\n let hours = timeArr[0];\n let _ext = \"AM\";\n if (hours >= 12) {\n hours = timeArr[0] % 12;\n _ext = \"PM\";\n }\n return hours + \":\" + timeArr[1] + \":\" + timeArr[2] + \" \" + _ext;\n } else {\n }\n }", "function render_datetime(data){\n\t var datetime = data.split(' ');\n\t var date = datetime[0].split('-').reverse().join('/');\n\t var time = datetime[1].substring(0,5);\n\t return date+' às '+time;\n\t}", "display_date_formate(date) {\n if (!date)\n return null;\n const [year, month, day] = date.split('-');\n let new_date = `${day}-${month}-${year}`;\n return new_date;\n }", "function timeformater(ts){\n let date = new Date(ts);\n let Y = date.getFullYear() + '-';\n let M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '-';\n let D = date.getDate() + ' ';\n let result = Y+M+D\n return result; \n }", "function formatTimeStamp() {\n var sendTime = Date().slice(16,21)\n var sendHour = sendTime.slice(0, 2)\n var pm = sendHour > 11 && sendHour < 24 ? true : false\n\n if (sendHour > 12) {\n sendHour = sendHour % 12\n }\n return sendHour + sendTime.slice(2) + (pm ? \" PM\" : \" AM\");\n}", "function formatDate(date) {\n return moment(date, \"dddd, D/M/YYYY, H:mm:ss\").format(\n \"dddd, d MMMM - h:mm A\"\n );\n }", "formatForecast(forecast) {\n const days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];\n const date = new Date(forecast.dt*1000);\n const hour = date.getHours() - 12 > 0 ? date.getHours() - 12 + 'PM' : date.getHours() + 'AM';\n const day = `${days[date.getDay()]} ${date.getMonth()+1}/${date.getDate()} `;\n \n const temperature = Math.floor(forecast.main.temp) + 'F';\n\n return {\n day,\n hour,\n temperature\n };\n }", "function beautifyDate(date) {\n\tlet hour = date.getHours(), minute = date.getMinutes();\n\tlet isAm = hour < 12;\n\treturn `${isAm ? hour : hour - 12}:${minute < 10 ? '0' + minute : minute} ${isAm ? 'am' : 'pm'}`\n}", "function viewDateFormat(strDateISO) {\n return moment(strDateISO).format(\"DD/MM/YYYY HH:mm\")\n}", "function ft(e,t,a){var s=\" \";return(e%100>=20||e>=100&&e%100==0)&&(s=\" de \"),e+s+{ss:\"secunde\",mm:\"minute\",hh:\"ore\",dd:\"zile\",ww:\"săptămâni\",MM:\"luni\",yy:\"ani\"}[a]}", "function formatDateTime(toConvert){\n\tif (toConvert == null) { return null; }\n let datetimeArray = toConvert.split(\" \");\n let date = moment(datetimeArray[0] + \" \" + datetimeArray[1]);\n return date.format('l LT');\n}", "function a(e,a,c){var n={ss:\"secunde\",mm:\"minute\",hh:\"ore\",dd:\"zile\",ww:\"săptămâni\",MM:\"luni\",yy:\"ani\"},t=\" \";return(e%100>=20||e>=100&&e%100===0)&&(t=\" de \"),e+t+n[c]}", "getInvalidDate(){\n return \"13/45/5555 50:49:99 CM\"\n }", "function universal() {\n return doFormat(date, {\n year: 'numeric',\n month: 'long',\n day: 'numeric',\n weekday: 'long',\n hour: 'numeric',\n minute: '2-digit',\n second: '2-digit'\n });\n }", "getDate() {\n const monthArray = [\n \"January\",\n \"February\",\n \"March\",\n \"April\",\n \"May\",\n \"June\",\n \"July\",\n \"August\",\n \"September\",\n \"October\",\n \"November\",\n \"December\"\n ];\n const dateObj = new Date();\n const numericMonth = dateObj.getUTCMonth();\n const monthName = monthArray[numericMonth];\n const day = dateObj.getUTCDate();\n const year = dateObj.getUTCFullYear();\n // const hour = dateObj.getUTCHours() - 12;\n const time = dateObj.toLocaleString(\"en-US\", {\n hour: \"numeric\",\n minute: \"numeric\",\n hour12: true\n });\n return `${monthName} ${day}, ${year} at ${time}`;\n }", "formatDate(x) {\n let date = new Date(x)\n let _month = date.getMonth() + 1 < 10 ? `0${date.getMonth() + 1}` : date.getMonth() + 1\n let _date = date.getDate() < 10 ? `0${date.getDate()}` : date.getDate()\n let _hour = date.getHours() < 10 ? `0${date.getHours()}` : date.getHours()\n let _minute = date.getMinutes() < 10 ? `0${date.getMinutes()}` : date.getMinutes()\n let _second = date.getSeconds() < 10 ? `0${date.getSeconds()}` : date.getSeconds()\n let dateStr = `${date.getFullYear()}-${_month}-${_date} ${_hour}:${_minute}:${_second}`\n return dateStr\n }", "formatTime(d){\n let time = new Date(d.replace('Z', ''));\n let date = new Date(time);\n let hours = date.getHours();\n let minutes = date.getMinutes();\n let ampm = hours >= 12 ? 'PM' : 'AM';\n hours = hours % 12;\n hours = hours ? hours: 12;\n minutes = minutes < 10 ? '0'+minutes : minutes;\n let formatedTime = `${hours}:${minutes} ${ampm}`\n\n return formatedTime;\n }", "function dateFormat(datum){\n \t\t\tvar day = datum.getDay();\n \t\t\tvar date = datum.getDate();\n \t\t\tvar month = datum.getMonth();\n \t\t\tvar year = datum.getYear();\n \t\t\tvar hour = datum.getHours();\n \t\t\tvar minutes = datum.getMinutes();\n\t\t}", "date_fmt (date, force_time_only) {\n const dt = moment(new Date(parseInt(date)));\n if (force_time_only || dt.isSame(new Date(), \"day\")) {\n console.log(dt)\n return dt.format(\"HH:mm:ss.SSS\");\n }\n else {\n return dt.format(\"L HH:mm:ss.SSS\");\n }\n }", "function date(data) {\n try {\n let date = new Date(data);\n const ye = new Intl.DateTimeFormat('en', { year: 'numeric' }).format(date)\n const mo = new Intl.DateTimeFormat('en', { month: 'short' }).format(date)\n const da = new Intl.DateTimeFormat('en', { day: '2-digit' }).format(date)\n return `${da} ${mo} ${ye}`;\n } catch (error) {\n console.log(error);\n }\n}", "function e(t,e,n){var i=\" \";return(t%100>=20||t>=100&&t%100==0)&&(i=\" de \"),t+i+{ss:\"secunde\",mm:\"minute\",hh:\"ore\",dd:\"zile\",MM:\"luni\",yy:\"ani\"}[n]}", "function e(t,e,n){var i=\" \";return(t%100>=20||t>=100&&t%100==0)&&(i=\" de \"),t+i+{ss:\"secunde\",mm:\"minute\",hh:\"ore\",dd:\"zile\",MM:\"luni\",yy:\"ani\"}[n]}", "function e(t,e,n){var i=\" \";return(t%100>=20||t>=100&&t%100==0)&&(i=\" de \"),t+i+{ss:\"secunde\",mm:\"minute\",hh:\"ore\",dd:\"zile\",MM:\"luni\",yy:\"ani\"}[n]}", "function e(t,e,n){var i=\" \";return(t%100>=20||t>=100&&t%100==0)&&(i=\" de \"),t+i+{ss:\"secunde\",mm:\"minute\",hh:\"ore\",dd:\"zile\",MM:\"luni\",yy:\"ani\"}[n]}", "function getFormattedTime() {\n var today = new Date();\n //return moment(today).format(\"YYYYMMDDHHmmssSSS\");\n return moment(today).format(\"DDHHmmssSSS\");\n }", "static dateFormatter(cell) {\n const date = new Date(cell).toDateString();\n return date;\n }", "formatTime(date) {\n let hr = date.getHours();\n let min = date.getMinutes();\n if (min < 10) {\n min = \"0\" + min;\n }\n let ampm = \"am\";\n if( hr > 12 ) {\n hr = hr - 12;\n ampm = \"pm\";\n } else if (hr == 12) {\n ampm = \"pm\"\n }\n\n return `${hr}:${min} ${ampm.toUpperCase()}`;\n }", "function dateFormat(i){\n var date = data.list[i].dt_txt;\n var year = date.slice(0,4);\n var day = date.slice(5,7);\n var month = date.slice(8,10);\n\n var newDateFormat = day + \"/\" + month + \"/\" + year;\n console.log(newDateFormat);\n return newDateFormat;\n }", "function e(t,e,n){var r=\" \";return(t%100>=20||t>=100&&t%100==0)&&(r=\" de \"),t+r+{ss:\"secunde\",mm:\"minute\",hh:\"ore\",dd:\"zile\",MM:\"luni\",yy:\"ani\"}[n]}", "getCurrentDateFormated() {\n let today = new Date();\n let day = today.getDate();\n let month = today.getMonth()+1;\n let year = today.getFullYear();\n\n if( day < 10) {\n day = \"0\" + day;\n }\n\n if(month < 10) {\n month = \"0\"+month\n }\n\n return `${year}-${month}-${day}`\n }", "function longForm(){\n return Date.parse(date.split(\",\")[1].match(/[a-zA-Z0-9 \\:]+/)[0].trim().replace(\" at \", \" \"));\n }", "get date_string() {\n return dayjs__WEBPACK_IMPORTED_MODULE_3__(this.date).format('DD MMM YYYY');\n }", "toFinnishTime(date) {\n //var date = new Date();\n date.setHours(date.getHours()+2);\n return date.toJSON().replace(/T/, ' ').replace(/\\..+/, '');\n }", "function formatDate(date) {\n var dateOrNow = date ? date : new Date()\n var ss = SpreadsheetApp.getActiveSpreadsheet()\n return Utilities.formatDate(dateOrNow, ss.getSpreadsheetTimeZone(),\n \"HH:[email protected]\"\n )\n }", "function getFormattedDate() {\n return \"[\" + new Date().toISOString().replace(/T/, ' ').replace(/\\..+/, '') + \"] \";\n}", "function mostraHora (){\n let data = new Date();\n return data.toLocaleTimeString('pt-BR', {\n hour12: false\n });\n}", "prepareTimecardDate(date){\n let arr = date.split(\" \");\n return arr[0] + \"\";\n }", "function localizedCreatedTimestamp() {\n if (vm.learningItem) {\n return moment(vm.learningItem.Created).format(\"M/D/YYYY h:mm A\");\n } else {\n return '';\n }\n }", "function getDiaActual() {\n let date = new Date().toLocaleDateString();\n date = date.split('/');\n date = date.reverse();\n\n let year = date[0];\n let month = date[1];\n let day = date[2];\n\n if (parseInt(month) < 10) month = \"0\" + month;\n if (parseInt(day) < 10) day = \"0\" + day;\n\n date = year + \"-\" + month + \"-\" + day;\n\n return date;\n}", "function t(e,t,a){var i=\" \";return(e%100>=20||e>=100&&e%100==0)&&(i=\" de \"),e+i+{ss:\"secunde\",mm:\"minute\",hh:\"ore\",dd:\"zile\",ww:\"săptămâni\",MM:\"luni\",yy:\"ani\"}[a]}", "function t(e,t,n){var i=\" \";return(e%100>=20||e>=100&&e%100==0)&&(i=\" de \"),e+i+{ss:\"secunde\",mm:\"minute\",hh:\"ore\",dd:\"zile\",MM:\"luni\",yy:\"ani\"}[n]}", "function t(e,t,n){var i=\" \";return(e%100>=20||e>=100&&e%100==0)&&(i=\" de \"),e+i+{ss:\"secunde\",mm:\"minute\",hh:\"ore\",dd:\"zile\",MM:\"luni\",yy:\"ani\"}[n]}", "function t(e,t,n){var i=\" \";return(e%100>=20||e>=100&&e%100==0)&&(i=\" de \"),e+i+{ss:\"secunde\",mm:\"minute\",hh:\"ore\",dd:\"zile\",MM:\"luni\",yy:\"ani\"}[n]}", "function t(e,t,n){var i=\" \";return(e%100>=20||e>=100&&e%100==0)&&(i=\" de \"),e+i+{ss:\"secunde\",mm:\"minute\",hh:\"ore\",dd:\"zile\",MM:\"luni\",yy:\"ani\"}[n]}", "function showForecastTime (timestamp) {\nlet forecastDate = new Date (timestamp);\nlet days = [\n \"Sunday\",\n \"Monday\",\n \"Tuesday\",\n \"Wednesday\",\n \"Thursday\",\n \"Friday\",\n \"Saturday\"\n];\nlet day = days[now.getDay()];\n}", "static getDateTimeString() {\n return `[${moment().format(\"DD.MM.YYYY HH:mm\")}] `;\n }", "function t(e,t,n){var r=\" \";return(e%100>=20||e>=100&&e%100==0)&&(r=\" de \"),e+r+{ss:\"secunde\",mm:\"minute\",hh:\"ore\",dd:\"zile\",MM:\"luni\",yy:\"ani\"}[n]}", "function t(e,t,n){var r=\" \";return(e%100>=20||e>=100&&e%100==0)&&(r=\" de \"),e+r+{ss:\"secunde\",mm:\"minute\",hh:\"ore\",dd:\"zile\",MM:\"luni\",yy:\"ani\"}[n]}", "function t(e,t,n){var r=\" \";return(e%100>=20||e>=100&&e%100==0)&&(r=\" de \"),e+r+{ss:\"secunde\",mm:\"minute\",hh:\"ore\",dd:\"zile\",MM:\"luni\",yy:\"ani\"}[n]}", "function t(e,t,n){var r=\" \";return(e%100>=20||e>=100&&e%100==0)&&(r=\" de \"),e+r+{ss:\"secunde\",mm:\"minute\",hh:\"ore\",dd:\"zile\",MM:\"luni\",yy:\"ani\"}[n]}", "function t(e,t,n){var r=\" \";return(e%100>=20||e>=100&&e%100==0)&&(r=\" de \"),e+r+{ss:\"secunde\",mm:\"minute\",hh:\"ore\",dd:\"zile\",MM:\"luni\",yy:\"ani\"}[n]}", "function t(e,t,n){var r=\" \";return(e%100>=20||e>=100&&e%100==0)&&(r=\" de \"),e+r+{ss:\"secunde\",mm:\"minute\",hh:\"ore\",dd:\"zile\",MM:\"luni\",yy:\"ani\"}[n]}", "function t(e,t,n){var r=\" \";return(e%100>=20||e>=100&&e%100==0)&&(r=\" de \"),e+r+{ss:\"secunde\",mm:\"minute\",hh:\"ore\",dd:\"zile\",MM:\"luni\",yy:\"ani\"}[n]}", "function t(e,t,n){var r=\" \";return(e%100>=20||e>=100&&e%100==0)&&(r=\" de \"),e+r+{ss:\"secunde\",mm:\"minute\",hh:\"ore\",dd:\"zile\",MM:\"luni\",yy:\"ani\"}[n]}", "function t(e,t,n){var r=\" \";return(e%100>=20||e>=100&&e%100==0)&&(r=\" de \"),e+r+{ss:\"secunde\",mm:\"minute\",hh:\"ore\",dd:\"zile\",MM:\"luni\",yy:\"ani\"}[n]}", "function t(e,t,n){var r=\" \";return(e%100>=20||e>=100&&e%100==0)&&(r=\" de \"),e+r+{ss:\"secunde\",mm:\"minute\",hh:\"ore\",dd:\"zile\",MM:\"luni\",yy:\"ani\"}[n]}", "function t(e,t,n){var r=\" \";return(e%100>=20||e>=100&&e%100==0)&&(r=\" de \"),e+r+{ss:\"secunde\",mm:\"minute\",hh:\"ore\",dd:\"zile\",MM:\"luni\",yy:\"ani\"}[n]}", "function getFormattedTime() {\n var today = new Date();\n //return moment(today).format(\"YYYYMMDDHHmmssSSS\");\n return moment(today).format(\"YYYYMMDDHHmmss\");\n }", "function t(e,t,a){var n=\" \";return(e%100>=20||e>=100&&e%100==0)&&(n=\" de \"),e+n+{ss:\"secunde\",mm:\"minute\",hh:\"ore\",dd:\"zile\",ww:\"săptămâni\",MM:\"luni\",yy:\"ani\"}[a]}", "dateFormate() {\n let today = new Date('dd/MM/yyyy');\n console.log(today);\n today.toLocaleDateString(\"en-US\");\n }", "getTodayText() {\n return moment().format(\"dddd, MMMM Do\");\n }", "function getTimeHour(time){\n\n return moment(today + ' ' + time, \"dddd, MMMM Do YYYY hh:00 A\").format(\"MM-DD-YYYY hh:00 A\") ;\n\n}", "formatDate(value, format) {\n format = format || '';\n if (value) {\n return window.moment(value)\n .format(format);\n }\n return \"n/a\";\n }", "function e(t,e,r){var n=\" \";return(t%100>=20||t>=100&&t%100==0)&&(n=\" de \"),t+n+{ss:\"secunde\",mm:\"minute\",hh:\"ore\",dd:\"zile\",MM:\"luni\",yy:\"ani\"}[r]}", "function e(t,e,n){var r={ss:\"secunde\",mm:\"minute\",hh:\"ore\",dd:\"zile\",MM:\"luni\",yy:\"ani\"},a=\" \";if(t%100>=20||t>=100&&t%100===0){a=\" de \"}return t+a+r[n]}", "function e(t,e,n){var i=\" \";return(t%100>=20||t>=100&&t%100==0)&&(i=\" de \"),t+i+{ss:\"secunde\",mm:\"minute\",hh:\"ore\",dd:\"zile\",ww:\"săptămâni\",MM:\"luni\",yy:\"ani\"}[n]}", "formatDate(date) {\n return date.toISOString().replaceAll(\"-\", \"\").substring(0, 8);\n }", "function e(t,e,n){var r=\" \";return(t%100>=20||t>=100&&t%100==0)&&(r=\" de \"),t+r+{ss:\"secunde\",mm:\"minute\",hh:\"ore\",dd:\"zile\",ww:\"săptămâni\",MM:\"luni\",yy:\"ani\"}[n]}", "reformatDate(dateFromApi) {\n const date = new Date(dateFromApi);\n return `${date.toLocaleDateString()} ${date.toLocaleTimeString()}`;\n }", "function convertFormat(time) {\n let format = 'AM';\n if (time >= 12) {\n format = 'PM';\n }\n return format;\n}", "getDatePattern(date) {\n return `${date.toLocaleDateString()} - ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;\n }", "function getDate() {\n let m = moment().format('YYYY-MM-DD');\n console.log('Generating PDF at: ', m)\n return m\n }", "function t(e,t,n){var r={ss:\"secunde\",mm:\"minute\",hh:\"ore\",dd:\"zile\",MM:\"luni\",yy:\"ani\"},o=\" \";if(e%100>=20||e>=100&&e%100===0){o=\" de \"}return e+o+r[n]}", "function changeDateFormat(date) {\n const dayOfWk = date.slice(0, 4)\n const day = date.slice(5, 7)\n const month = date.slice(8, 11)\n const year = date.slice(12, 16)\n return `${dayOfWk} ${month} ${day} ${year}`\n // Fri, Jul 30 2021\n }", "function cut_date(register_date){\n let register_date_string = register_date.toISOString();\n let split_date = register_date_string.split(\"T\")[1];\n let split_time = split_date.split(\".\")[0];\n return split_time;\n}", "dailyNoteTitle() {\n\t\treturn moment( new Date() ).format( 'MMMM Do, YYYY' );\n\t}", "function formatDate(when) {\n if (when !== \"\") {\n const monthNames = [\n \"January\",\n \"February\",\n \"March\",\n \"April\",\n \"May\",\n \"June\",\n \"July\",\n \"August\",\n \"September\",\n \"October\",\n \"November\",\n \"December\"\n ];\n\n // Splits 2018-06-15T18:00:00-05:00 or 2018-12-20 into an array\n // of numbers\n let dateArray = when.split(/(?:-|T)+/);\n const year = dateArray[0];\n\n let month;\n if (dateArray[1].indexOf(\"10\") === -1) {\n month = dateArray[1].replace(\"0\", \"\"); //Replace the 05:00 with 5:00\n } else {\n month = dateArray[1]; //Replace the 05:00 with 5:00\n }\n const day = dateArray[2];\n\n // If only date given return just the date else return time as well\n if (dateArray.length <= 3) {\n return `${monthNames[month - 1]} ${day}, ${year}`;\n } else {\n // Get the time array from 2018-06-15T18:00:00-05:00\n // splits time into [hh, mm, ss] ie [18,00,00]\n const time = dateArray[3].split(\":\");\n let hour = parseInt(time[0], 10);\n // if the time is after noon 12pm subtract 12 from it 18 becomes 6pm\n if (hour > 12) {\n hour = hour - 12;\n }\n\n let ampm = \"pm\";\n // if the 24 hour time doesn't contain a 0 as the first element ie 17:00\n // it it pm\n dateArray[3][0] == \"0\" ? (ampm = \"am\") : (ampm = \"pm\");\n return `${monthNames[month - 1]} ${day}, ${year} at ${hour} ${ampm}`;\n }\n }\n return \"\";\n}", "function formatDateDot(datum) {\n\ttimepart = datum.split(\" \");\n\t\n\tif (timepart.length == 1 ){\n\tdateparts = datum.split('-');\n\tnewDate = dateparts[2] + '.' + dateparts[1] + '.' + dateparts[0];\n\t} else {\n\tdateparts = timepart[0].split('-');\n\tnewDate = dateparts[2] + '.' + dateparts[1] + '.' + dateparts[0] + ' um '+ timepart[1];\n\t}\n\treturn newDate;\n}", "function t(e,t,n){var a=\" \";return(e%100>=20||e>=100&&e%100==0)&&(a=\" de \"),e+a+{ss:\"secunde\",mm:\"minute\",hh:\"ore\",dd:\"zile\",MM:\"luni\",yy:\"ani\"}[n]}", "function t(e,t,n){var a=\" \";return(e%100>=20||e>=100&&e%100==0)&&(a=\" de \"),e+a+{ss:\"secunde\",mm:\"minute\",hh:\"ore\",dd:\"zile\",MM:\"luni\",yy:\"ani\"}[n]}", "function a(e,a,t){return e+\" \"+function(e,a){return 2===a?function(e){var a={m:\"v\",b:\"v\",d:\"z\"};return void 0===a[e.charAt(0)]?e:a[e.charAt(0)]+e.substring(1)}(e):e}({mm:\"munutenn\",MM:\"miz\",dd:\"devezh\"}[t],e)}", "function t(e,t,n){var r={ss:\"secunde\",mm:\"minute\",hh:\"ore\",dd:\"zile\",MM:\"luni\",yy:\"ani\"},a=\" \";if(e%100>=20||e>=100&&e%100===0){a=\" de \"}return e+a+r[n]}", "extractDateFormat() {\n const isoString = '2018-12-31T12:00:00.000Z' // example date\n\n const intlString = this.props.intl.formatDate(isoString) // generate a formatted date\n const dateParts = isoString.split('T')[0].split('-') // prepare to replace with pattern parts\n\n return intlString\n .replace(dateParts[2], 'dd')\n .replace(dateParts[1], 'MM')\n .replace(dateParts[0], 'yyyy')\n }", "function formatDate(d) {\n if (d === undefined){\n d = (new Date()).toISOString()\n }\n let currDate = new Date(d);\n let year = currDate.getFullYear();\n let month = currDate.getMonth() + 1;\n let dt = currDate.getDate();\n let time = currDate.toLocaleTimeString('en-SG')\n\n if (dt < 10) {\n dt = '0' + dt;\n }\n if (month < 10) {\n month = '0' + month;\n }\n\n return dt + \"/\" + month + \"/\" + year + \" \" + time ;\n }", "function formatDate() {\n \tvar date = new Date();\n \tvar datestr = date.getMonth() + '/' + date.getDate() + '/' + date.getFullYear();\n\n \tif (date.getHours() >= 12) {\n \t\tdatestr += ' ' + (date.getHours() == 12 ? date.getHours() : date.getHours()-12) + ':' + date.getMinutes() + ' PM';\n \t} else {\n \t\tdatestr += ' '+date.getHours() + ':' + date.getMinutes() + ' AM';\n \t}\n\n \treturn datestr;\n }", "formatTime(date) {\n let hours = date.getHours();\n let ampm = hours >= 12 ? 'PM' : 'AM';\n hours %= 12;\n hours = hours ? hours : 12; // the hour 0 should be 12\n\n return hours + ampm;\n }" ]
[ "0.62493837", "0.6209069", "0.6183403", "0.61342686", "0.6125143", "0.6122489", "0.61163497", "0.5976845", "0.5964593", "0.59612525", "0.5893081", "0.58859885", "0.5869159", "0.58680165", "0.5862874", "0.58521366", "0.58398193", "0.583723", "0.58352935", "0.58334786", "0.5830538", "0.582747", "0.58265495", "0.5817782", "0.58171153", "0.58099705", "0.580457", "0.5797979", "0.5796754", "0.5790036", "0.5789771", "0.57746285", "0.5773689", "0.5764968", "0.57557523", "0.57557523", "0.57557523", "0.57557523", "0.5755705", "0.575294", "0.57520163", "0.5746028", "0.57418257", "0.5741433", "0.57355803", "0.5733581", "0.57324", "0.5724853", "0.5723258", "0.57217854", "0.5717272", "0.57161266", "0.5711569", "0.5710765", "0.5708007", "0.5708007", "0.5708007", "0.5708007", "0.57068866", "0.5702788", "0.56949484", "0.56949484", "0.56949484", "0.56949484", "0.56949484", "0.56949484", "0.56949484", "0.56949484", "0.56949484", "0.56949484", "0.56949484", "0.56834257", "0.5683325", "0.567725", "0.56733936", "0.5672146", "0.5672119", "0.56714547", "0.5671327", "0.5667785", "0.5666214", "0.5665161", "0.5664819", "0.5662042", "0.56604195", "0.5659256", "0.5658635", "0.5657073", "0.56558335", "0.5654852", "0.5653441", "0.56529015", "0.5652648", "0.5652648", "0.56511176", "0.564621", "0.5640899", "0.56295794", "0.5625857", "0.5624024" ]
0.5768628
33
eg: 16 Aug 2019, Fri
static momentToFormat2(momentObj) { let datetime = Moment(momentObj); return (datetime.format('DD MMM YYYY, ddd')); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "processDate ( ) {\n let days = [ 'Monday', 'Tuesday', 'Wednesday',\n 'Thursday', 'Friday', 'Saturday', 'Sunday' ];\n let date = new Date ( this.data.release_date ).toDateString ( );\n let split = date.split ( ' ' );\n let fullday = days.filter ( x => x.indexOf ( split [ 0 ] ) !== -1 );\n return `${fullday}, ${split [ 1 ]} ${ split [ 2 ]} ${split [ 3 ]}`;\n }", "getFormattedDate(date) {\n return dayjs(date).format(\"MMM MM, YYYY\");\n }", "get date_string() {\n return dayjs__WEBPACK_IMPORTED_MODULE_3__(this.date).format('DD MMM YYYY');\n }", "function date(data) {\n try {\n let date = new Date(data);\n const ye = new Intl.DateTimeFormat('en', { year: 'numeric' }).format(date)\n const mo = new Intl.DateTimeFormat('en', { month: 'short' }).format(date)\n const da = new Intl.DateTimeFormat('en', { day: '2-digit' }).format(date)\n return `${da} ${mo} ${ye}`;\n } catch (error) {\n console.log(error);\n }\n}", "renderDateTitle(date) {\n return moment(date).format(\"dddd\") + \", \" + moment(date).format(\"MMMM Do\");\n }", "function dateFormat(i){\n var date = data.list[i].dt_txt;\n var year = date.slice(0,4);\n var day = date.slice(5,7);\n var month = date.slice(8,10);\n\n var newDateFormat = day + \"/\" + month + \"/\" + year;\n console.log(newDateFormat);\n return newDateFormat;\n }", "display_date_formate(date) {\n if (!date)\n return null;\n const [year, month, day] = date.split('-');\n let new_date = `${day}-${month}-${year}`;\n return new_date;\n }", "function changeDateFormat(date) {\n const dayOfWk = date.slice(0, 4)\n const day = date.slice(5, 7)\n const month = date.slice(8, 11)\n const year = date.slice(12, 16)\n return `${dayOfWk} ${month} ${day} ${year}`\n // Fri, Jul 30 2021\n }", "function dateFr(datas) {\n\n var days = ['dimanche', 'lundi', 'mardi', 'mercredi', 'jeudi', 'vendredi', 'samedi'];\n var months = ['janvier', 'février', 'mars', 'avril', 'mai', 'juin', 'juillet', 'août', 'septembre', 'octobre', 'novembre', 'décembre'];\n\n var date = new Date(datas);\n var dateFr = days[date.getDay()] + ' ';\n dateFr += date.getDate() + ' ';\n dateFr += months[date.getMonth()] + ' ';\n dateFr += date.getFullYear();\n\n return dateFr;\n}", "function formatDate(){\n\n // Date format FEB 11, 2016\n var month = streamInfo['updated_at'].substr(5,2);\n\n switch (month){\n case '01':\n month = 'JAN ';\n break;\n case '02':\n month = 'FEB ';\n break;\n case '03':\n month = 'MAR ';\n break;\n case '04':\n month = 'APR ';\n break;\n case '05':\n month = 'MAY ';\n break;\n case '06':\n month = 'JUN ';\n break;\n case '07':\n month = 'JUL ';\n break;\n case '08':\n month = 'AUG ';\n break;\n case '09':\n month = 'SEP ';\n break;\n case '10':\n month = 'OCT,';\n break;\n case '11':\n month = 'NOV,';\n break;\n case '12':\n month = 'DEC,';\n break;\n default :\n month = '';\n }\n\n var date = month + streamInfo['updated_at'].substr(8,2)+ ', ' + streamInfo['updated_at'].substr(0,4);\n\n return date;\n }", "date_lisible_format(date){\n var day = date.substring(0, 2),\n month_number = date.substring(3, 5),\n year = date.substring(6, 10);\n\n const Date_Month_Key = new Map([[\"01\", \"Janvier\"], [\"02\", \"Fevrier\"], [\"03\", \"Mars\"], [\"04\", \"Avril\"], [\"05\", \"Mai\"], [\"06\", \"Juin\"], [\"07\", \"Juillet\"], [\"08\", \"Août\"], [\"09\", \"Septembre\"], [\"10\", \"Octobre\"], [\"11\", \"Novembre\"], [\"12\", \"Decembre\"]]); \n var month = Date_Month_Key.get(month_number);\n\n var date_format = day+\" \"+month+\" \"+year;\n\n return date_format;\n }", "dateForHumans(item) {\n if (!item.date) return \"\";\n let startDate = DateTime.fromISO(item.date).toFormat(\"d LLLL yyyy\");\n if (!item.time && !item.enddate) return startDate;\n if (item.time) return `${startDate} at ${item.time}`;\n if (!item.enddate) return startDate;\n\n let endDate = DateTime.fromISO(item.enddate).toFormat(\"d LLLL yyyy\");\n return `${startDate} to ${endDate}`;\n }", "prettyBirthday() {//Can be put in method\n return dayjs(this.person.dob.date)\n .format('DD MMMM YYYY')//change in assignment to different format not default\n }", "getTodayText() {\n return moment().format(\"dddd, MMMM Do\");\n }", "function getDate() {\n\nlet today = new Date();\nlet options = {\n weekday: \"long\",\n day: \"numeric\",\n month: \"long\"\n};\n\nlet day = today.toLocaleDateString(\"en-Us\", options);\n\n\n//returns day in us format, such as \"Tuesday, 12 february\"\nreturn day;\n\n}", "dailyNoteTitle() {\n\t\treturn moment( new Date() ).format( 'MMMM Do, YYYY' );\n\t}", "formatDate(dateP, lang) {\n // console.log(\"Date Receive \"+dateP);\n let splitdat = dateP.split('-');\n if (splitdat.length == 1) { //they use / instead of -\n splitdat = dateP.split('/');\n }\n //console.log(\"DATE FR : \" + splitdat+\" TO \"+lang);\n let date_f = dateP;\n if (lang == 'FR') {\n date_f = splitdat[2] + '-' + splitdat[1] + '-' + splitdat[0];\n }\n if (lang == 'EN') {\n date_f = splitdat[2] + '-' + splitdat[1] + '-' + splitdat[0];\n\n }\n //console.log(\"DATE FORMAT : \" + date_f+\" TO \"+lang);\n return date_f;\n\n }", "setTitle2(date) {\n let currentDate = new Date();\n currentDate.setHours(0, 0, 0, 0);\n let cpd = new Date(date);\n cpd.setHours(0, 0, 0, 0);\n let diff = (currentDate.getTime() - cpd.getTime()) / (1000 * 3600 * 24);\n let t = '';\n if (diff == 0) t = \"Today\";else if (diff == 1) t = \"Yesterday\";else if (diff == -1) t = \"Tomorrow\";else t = cpd.toLocaleString('default', {\n weekday: 'long'\n }) + ', ' + cpd.toLocaleString('default', {\n month: 'long'\n }).substr(0, 3) + ' ' + cpd.getDate();\n return t;\n }", "getDate(){\n var myDate = this.state.data.release_date;\n var chunks = myDate.split('-');\n var formattedDate = chunks[1]+'/'+chunks[2]+'/'+chunks[0];\n const dateFormat = new Date(formattedDate);\n var strDate = dateFormat.toLocaleString(\"en\", { month: \"long\" }) + ' ' + dateFormat.toLocaleString(\"en\", { day: \"numeric\" }) + ', ' + dateFormat.toLocaleString(\"en\", { year: \"numeric\"});\n this.setState({data_release_date: strDate});\n }", "function getDateString(now)\n{\n const options={year:'numeric',month:'long',day:'numeric'};\n return now.toLocaleDateString('en-Us',options);\n \n}", "function formatDate(date) {\n moment.locale(\"fr\");\n return moment(new Date(Number(date)).toISOString()).format(\"D MMM YYYY\");\n }", "function showDate(str) {\n let options = {day: 'numeric', month: 'short', weekday: 'short'}\n let date = new Date(str);\n return date.toLocaleString('ru', options)\n }", "getDayNumerals(date) { return `${date.day}`; }", "static convertDate(prev_date) {\n let month = this.MONTH_ARR[prev_date.getMonth()];\n let date = prev_date.getDate();\n let year = prev_date.getFullYear();\n var string_date = month + \" \" + date + \", \" + year\n return string_date;\n }", "formatted_date() {\n return this.created_at.toLocaleDateString()\n }", "getDateFormated(date) {\n const formatDate = new Intl.DateTimeFormat('en-GB', {\n day: 'numeric',\n month: 'short',\n year: 'numeric'\n }).format;\n return formatDate(date);\n }", "function getFullDateInVietnamese(){\r\n\tvar now = new Date();\r\n\tvar month = \"\";\r\n\tvar day = \"\";\r\n\tvar first_date_num=\"\";\r\n\r\n if (now.getDate() < 10)\r\n \tfirst_date_num=\"0\";\r\n\telse\r\n\t\tfirst_date_num=\"\";\r\n\t\t\t\r\n\tswitch (now.getDay()){\r\n\t\tcase 0: day=\"Ch&#7911; nh&#7853;t\";break;\r\n\t\tcase 1: day=\"Th&#7913; hai\";break;\r\n\t\tcase 2: day=\"Th&#7913; ba\";break;\r\n\t\tcase 3: day=\"Th&#7913; t&#432;\";break;\r\n\t\tcase 4: day=\"Th&#7913; n&#259;m\";break;\r\n\t\tcase 5: day=\"Th&#7913; s&#225;u\";break;\r\n\t\tcase 6: day=\"Th&#7913; b&#7843;y\";break;\r\n\t}\r\n\t\r\n\treturn day + \" ng&#224;y \" + first_date_num + now.getDate() + \" th&#225;ng \" + (now.getMonth()+1) + \" n&#259;m \" + now.getFullYear();\r\n}", "getCurrentDateFormated() {\n let today = new Date();\n let day = today.getDate();\n let month = today.getMonth()+1;\n let year = today.getFullYear();\n\n if( day < 10) {\n day = \"0\" + day;\n }\n\n if(month < 10) {\n month = \"0\"+month\n }\n\n return `${year}-${month}-${day}`\n }", "function getDateFormats() {\n const date = new Date(),\n arr = [];\n const days = [\n \"Sunday\",\n \"Monday\",\n \"Tuesday\",\n \"Wednesday\",\n \"Thursday\",\n \"Friday\",\n \"Saturday\",\n ];\n const str = date.toString().split(\" \");\n //You can use template literal\n arr[0] = str[3] + \"-\" + (date.getMonth() + 1) + \"-\" + str[2];\n arr[1] = days[date.getDay()] + \", \" + str[1] + \" \" + str[2] + \", \" + str[3];\n return arr;\n}", "function dateFormat(date) {\n\tconst week = date.split('-');\n\tlet newDate = new Date(week[2], week[1] - 1, week[0]);\n\n\tnewDate = newDate.toString().split(' ');\n\tnewDate = newDate[1] + ' ' + newDate[2] + ', ' + newDate[3];\n\t\n\treturn newDate;\n}", "eventDetailsFullDate(date) {\n\t\treturn Moment(date).format('ddd, DD of MMMM gggg');\n\t}", "stringFormatDate(date) {\n let dateFormat = date.split(\"-\").reverse().join(\"-\");\n return dateFormat;\n }", "function getDate(){\r\nvar today=new Date();//used to get the current date\r\n\r\n\r\n var options ={\r\n weekday:\"long\",\r\n day: \"numeric\",\r\n month :\"long\"\r\n };\r\n\r\n\r\n var day=today.toLocaleDateString(\"en-US\",options);//this extract the dte inthe format mentioned in the object option\r\n return day;\r\n}", "validarFechas(fecha) {\n let date = moment(fecha, \"DD/MM/YYYY HH:mm:ss\");\n\n return date.format(\"YYYY-MM-DD\");\n }", "fullDateString(date) {\n return {\n day: this.getDayName(date.getDay()),\n month: this.getMonthName(date.getMonth()),\n year: date.getFullYear(),\n d: date.getDate()\n };\n }", "function dataAtualFormatada(){\n var data = new Date(),\n dia = data.getDate().toString().padStart(2, '0'),\n mes = (data.getMonth()+1).toString().padStart(2, '0'), //+1 pois no getMonth Janeiro começa com zero.\n ano = data.getFullYear();\n return (semana[data.getDay()]).substring(0,3)+\", \"+dia+\"/\"+mes+\"/\"+ano;\n}", "function formatDate(date) {\n return moment(date).format(\"dddd, MMMM Do YY\");\n \n}", "dates () {\n return ['current_date'];\n }", "customDateHtml(date){\n\t\treturn moment(date).date(); //day of month\n\t}", "function formatDate(date) {\n return weekdays[date.getDay()] + \", \" +\n date.getDate() + nth(date.getDate()) + \" \" +\n months[date.getMonth()] + \" \" +\n date.getFullYear();\n }", "function fDate(currentDate) {\n let fDays = [\n \"Sunday\",\n \"Monday\",\n \"Tuesday\",\n \"Wednesday\",\n \"Thursday\",\n \"Friday\",\n \"Saturday\"\n ];\n let fDay = fDays[currentDate.getDay()];\n\n let fMonths = [\n \"January\",\n \"February\",\n \"March\",\n \"April\",\n \"May\",\n \"June\",\n \"July\",\n \"August\",\n \"September\",\n \"October\",\n \"November\",\n \"December\"\n ];\n let fMonth = fMonths[currentDate.getMonth()];\n return (\n fDay + \", \" +\n fMonth +\n \" \" +\n currentDate.getDate() +\n \" \" +\n currentDate.getFullYear()\n );\n}", "formatTheDate(date, format) {\n const [ year, month, day ] = (date.toISOString()).substr(0, 10).split('-');\n return dateFns.format(new Date(\n year,\n (month - 1),\n day,\n ), format);\n }", "returnDateFormat(date){\n var day = new Date(date);\n return day.toDateString();\n }", "extractDateFormat() {\n const isoString = '2018-12-31T12:00:00.000Z' // example date\n\n const intlString = this.props.intl.formatDate(isoString) // generate a formatted date\n const dateParts = isoString.split('T')[0].split('-') // prepare to replace with pattern parts\n\n return intlString\n .replace(dateParts[2], 'dd')\n .replace(dateParts[1], 'MM')\n .replace(dateParts[0], 'yyyy')\n }", "formatDate(date) {\n return date.toISOString().replaceAll(\"-\", \"\").substring(0, 8);\n }", "function getLongFrenchDate(date)\n{\n var months = [\"Janvier\", \"Février\", \"Mars\", \"Avril\", \"Mai\", \"Juin\", \"Juillet\", \"Août\", \"Septembre\", \"Octobre\", \"Novembre\", \"Décembre\"];\n var days = [\"Dimanche\", \"Lundi\", \"Mardi\", \"Mercredi\", \"Jeudi\", \"Vendredi\", \"Samedi\", \"Dimanche\"];\n return days[date.getDay()] + ' ' + date.getDate() + ' ' + months[date.getMonth()] + ' ' + date.getFullYear();\n}", "toView(value) {\n return moment(value).format('MMMM D, YYYY')\n }", "static _extractDateParts(date){return{day:date.getDate(),month:date.getMonth(),year:date.getFullYear()}}", "formatPublishedDate() {\n // Only format the published date if one is available\n if (this.props.book.publishedDate) {\n // Split up the published date. Using the length of this array,\n // figure out how much information to display in the final, newly\n // formated date\n let publishedDateSplitUp = this.props.book.publishedDate.split('-');\n // Convert the published date into a date object\n let publishedDate = new Date(this.props.book.publishedDate);\n // To store the date formatting options based on how information is available\n let dateFormattingOptions;\n // Show only the year\n if (publishedDateSplitUp.length === 1) {\n dateFormattingOptions = {\n year: 'numeric'\n };\n }\n // Show the month and year\n else if (publishedDateSplitUp === 2) {\n dateFormattingOptions = {\n year: 'numeric',\n month: 'short'\n };\n }\n // Show the day, month, and year\n else {\n dateFormattingOptions = {\n year: 'numeric',\n month: 'short',\n day: 'numeric'\n };\n }\n // Convert and return the date\n return publishedDate.toLocaleString('en-us', dateFormattingOptions);\n }\n }", "getFormattedDate ({ date }) {\n if (typeof date === 'string') {\n return format(parseISO(date), \"d 'de' MMMM', às' HH'h'mm\", {\n locale: ptBR\n })\n }\n return format(date, \"d 'de' MMMM', às' HH'h'mm\", {\n locale: ptBR\n })\n }", "formatForecast(forecast) {\n const days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];\n const date = new Date(forecast.dt*1000);\n const hour = date.getHours() - 12 > 0 ? date.getHours() - 12 + 'PM' : date.getHours() + 'AM';\n const day = `${days[date.getDay()]} ${date.getMonth()+1}/${date.getDate()} `;\n \n const temperature = Math.floor(forecast.main.temp) + 'F';\n\n return {\n day,\n hour,\n temperature\n };\n }", "function ISO_2022() {}", "function ISO_2022() {}", "function dateString() {\n recipe.forEach(date => {\n let dateStr = `${date.created_at.getFullYear()}-${date.created_at.getMonth()+1}-${date.created_at.getDate()}`\n date.display_date = dateStr\n });\n return recipe\n }", "getBirthday(){\n let result = `${this.dateOfBirth.getDate()}.${this.dateOfBirth.getMonth() +1 }.${this.dateOfBirth.getFullYear()}.`;\n return result;\n }", "function dateString() {\n posts.forEach(date => {\n let dateStr = `${date.created_at.getFullYear()}-${date.created_at.getMonth()+1}-${date.created_at.getDate()}`\n date.display_date = dateStr\n });\n return posts\n }", "cleanDate (date) {\n return moment(date).format('MMMM Do, YYYY')\n }", "function dateFormatx(typ,d,m,y){\n if(typ=='id') // 25 Dec 2014\n return d+' '+m+' '+y;\n else // 2014-12-25\n return y+'-'+m+'-'+d;\n }", "function formatearFecha(fechaActual){\n return fechaActual.getDate()+\"-\"+\n (fechaActual.getMonth()+1)+\"-\"+fechaActual.getFullYear();\n}", "function getWeekDay() {\r\n /* let week = ['вс', 'пн', 'вт', 'ср', 'чт', 'пт', 'сб'],\r\n currentDay = new Date(),\r\n day = currentDay.getDay();\r\n return week[day]; */\r\n\r\n let options = {\r\n weekday: 'short',\r\n },\r\n currentDay = new Date();\r\n return currentDay.toLocaleString(\"ru\", options);\r\n}", "function formatMonth1(month) {\n var show = month.split(\"\")\n var jNew = show[0].toUpperCase();\n show.shift();\n var shownew = show.join();\n var janNew = shownew.replace(/,/gi, \"\")\n console.log(jNew + janNew + \" have 31 Days\")\n}", "function getDiaActual() {\n let date = new Date().toLocaleDateString();\n date = date.split('/');\n date = date.reverse();\n\n let year = date[0];\n let month = date[1];\n let day = date[2];\n\n if (parseInt(month) < 10) month = \"0\" + month;\n if (parseInt(day) < 10) day = \"0\" + day;\n\n date = year + \"-\" + month + \"-\" + day;\n\n return date;\n}", "static setDate() {\n let dayFieldsArray = Array.from(dayFields);\n const days = [\"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\", \"Friday\", \"Saturday\"];\n const months = [\"Jan\", \"Feb\", \"Mar\", \"Apr\", \"May\", \"Jun\", \"Jul\", \"Aug\", \"Sept\", \"Oct\", \"Nov\", \"Dec\"];\n dayFieldsArray.forEach(item => item.innerText = days[(currentDate.getDay()+dayFieldsArray.indexOf(item))%7]);\n document.querySelector(\".date-0\").innerText = `${currentDate.getDate()} ${months[currentDate.getMonth()]}`;\t\n }", "function t(e,t,n){return e+\" \"+o({mm:\"munutenn\",MM:\"miz\",dd:\"devezh\"}[n],e)}", "dateFormate() {\n let today = new Date('dd/MM/yyyy');\n console.log(today);\n today.toLocaleDateString(\"en-US\");\n }", "function formatPublishDate(date) {\r\tvar months = [\"januari\",\"februari\",\"mars\",\"april\",\"maj\",\"juni\",\"juli\",\"augusti\",\"september\",\"oktober\",\"november\",\"december\"];\r return date.getDate() + \" \" + months[date.getMonth()] + \" \" + date.getFullYear();\r}", "function setFormatoDate(data) {\n let dd = (\"0\" + (data.getDate())).slice(-2);\n let mm = (\"0\" + (data.getMonth() + 1)).slice(-2);\n let yyyy = data.getFullYear();\n return dd + '/' + mm + '/' + yyyy;\n}", "function date_ymd2dmy(val)\r\n{\r\n\tval = trim(val);\r\n\tif (val == '') return val;\r\n\tvar date_arr = val.split('-');\r\n\tif (date_arr.length != 3) return '';\r\n\tif (date_arr[1].length < 2) date_arr[1] = \"0\" + date_arr[1];\r\n\tif (date_arr[2].length < 2) date_arr[2] = \"0\" + date_arr[2];\r\n\treturn date_arr[2]+\"-\"+date_arr[1]+\"-\"+date_arr[0];\r\n}", "renderDate(value) {\n 'use strict';\n\n if (value) {\n return `<span title=\"${value.full}\">${value.shortest}</span>`;\n }\n return '-';\n }", "cleanDateWithLeadingDay (date) {\n return moment(date).format('dddd, MMMM Do, YYYY')\n }", "function t(e,t,a){return e+\" \"+function(e,t){return 2===t?function(e){var t={m:\"v\",b:\"v\",d:\"z\"};return void 0===t[e.charAt(0)]?e:t[e.charAt(0)]+e.substring(1)}(e):e}({mm:\"munutenn\",MM:\"miz\",dd:\"devezh\"}[a],e)}", "function t(e,t,a){return e+\" \"+function(e,t){return 2===t?function(e){var t={m:\"v\",b:\"v\",d:\"z\"};return void 0===t[e.charAt(0)]?e:t[e.charAt(0)]+e.substring(1)}(e):e}({mm:\"munutenn\",MM:\"miz\",dd:\"devezh\"}[a],e)}", "function calendar2date(date) {\n let mes2number = {\"Jan\":\"01\", \"Feb\":\"02\", \"Mar\":\"03\", \"Apr\":\"04\", \"May\":\"05\", \"Jun\":\"06\", \"Jul\":\"07\", \"Aug\":\"08\", \"Sep\":\"09\", \"Oct\":\"10\", \"Nov\":\"11\", \"Dec\":\"12\"};\n let data = date.toString().split(' ');\n let dia = data[2];\n let mes = data[1];\n let ano = data[3];\n\n // console.log();\n return dia+\"/\"+mes2number[mes]+\"/\"+ano;\n}", "function getDatestrs () {\n\t\tvar tmpdatestrs = Log.getLatestDateStrings();\n\t\tvar dates = tmpdatestrs.map(function(s){ return new Date(s) });\n\t\treturn dates.map(function(d) { return Utilities.formatString('%s, %s %d', DAYS[d.getDay()], MONTHS[d.getMonth()], d.getDate()) });\n\t}", "function dateToStr(str) {\n let myDate = new Date(str);\n let day = daysOfWeek[myDate.getDay()];\n let date = ('0' + myDate.getDate()).slice(-2);\n let month = ('0' + (myDate.getMonth() + 1)).slice(-2);\n let year = myDate.getFullYear();\n return `${day} ${date}.${month}.${year}`;\n }", "function nombre_fecha(fecha) {\n fecha = fecha.split(\"/\");\n fecha = fecha.reverse();\n fecha = fecha[0] + \"/\" + fecha[1] + \"/\" + fecha[2];\n // console.log(fecha);\n var meses = new Array(\"Enero\", \"Febrero\", \"Marzo\", \"Abril\", \"Mayo\", \"Junio\", \"Julio\", \"Agosto\", \"Septiembre\", \"Octubre\", \"Noviembre\", \"Diciembre\");\n var diasSemana = new Array(\"Domingo\", \"Lunes\", \"Martes\", \"Miércoles\", \"Jueves\", \"Viernes\", \"Sábado\");\n var f = new Date(fecha);\n return(diasSemana[f.getDay()] + \", \" + f.getDate() + \" de \" + meses[f.getMonth()] + \" de \" + f.getFullYear());\n}//fin", "function convert_date(due_date) {\n if (due_date.indexOf(\" \") > -1) {\n var arr_date = due_date.split(/[ T]/).filter(function (s) {\n return s !== \"\";\n });\n due_date = arr_date[0] + \" \" + arr_date[1] + \" \" + arr_date[2];\n }\n return due_date;\n}", "toShowCompletedDate(){\n return `${this.toShowDate()}, ${this.toShowTime()}`;\n }", "todayDateString () {\n return todayDateString\n }", "function empDate(d) {\n return d.getDay()+'-'+(d.getMonth()+1)+'-'+d.getFullYear();\n }", "function t(e,t,n){return e+\" \"+function(e,t){return 2===t?function(e){var t={m:\"v\",b:\"v\",d:\"z\"};return void 0===t[e.charAt(0)]?e:t[e.charAt(0)]+e.substring(1)}(e):e}({mm:\"munutenn\",MM:\"miz\",dd:\"devezh\"}[n],e)}", "function t(e,t,n){return e+\" \"+function(e,t){return 2===t?function(e){var t={m:\"v\",b:\"v\",d:\"z\"};return void 0===t[e.charAt(0)]?e:t[e.charAt(0)]+e.substring(1)}(e):e}({mm:\"munutenn\",MM:\"miz\",dd:\"devezh\"}[n],e)}", "function t(e,t,n){return e+\" \"+function(e,t){return 2===t?function(e){var t={m:\"v\",b:\"v\",d:\"z\"};return void 0===t[e.charAt(0)]?e:t[e.charAt(0)]+e.substring(1)}(e):e}({mm:\"munutenn\",MM:\"miz\",dd:\"devezh\"}[n],e)}", "function t(e,t,n){return e+\" \"+function(e,t){return 2===t?function(e){var t={m:\"v\",b:\"v\",d:\"z\"};return void 0===t[e.charAt(0)]?e:t[e.charAt(0)]+e.substring(1)}(e):e}({mm:\"munutenn\",MM:\"miz\",dd:\"devezh\"}[n],e)}", "function t(e,t,n){return e+\" \"+function(e,t){return 2===t?function(e){var t={m:\"v\",b:\"v\",d:\"z\"};return void 0===t[e.charAt(0)]?e:t[e.charAt(0)]+e.substring(1)}(e):e}({mm:\"munutenn\",MM:\"miz\",dd:\"devezh\"}[n],e)}", "function t(e,t,n){return e+\" \"+function(e,t){return 2===t?function(e){var t={m:\"v\",b:\"v\",d:\"z\"};return void 0===t[e.charAt(0)]?e:t[e.charAt(0)]+e.substring(1)}(e):e}({mm:\"munutenn\",MM:\"miz\",dd:\"devezh\"}[n],e)}", "function t(e,t,n){return e+\" \"+function(e,t){return 2===t?function(e){var t={m:\"v\",b:\"v\",d:\"z\"};return void 0===t[e.charAt(0)]?e:t[e.charAt(0)]+e.substring(1)}(e):e}({mm:\"munutenn\",MM:\"miz\",dd:\"devezh\"}[n],e)}", "function t(e,t,n){return e+\" \"+function(e,t){return 2===t?function(e){var t={m:\"v\",b:\"v\",d:\"z\"};return void 0===t[e.charAt(0)]?e:t[e.charAt(0)]+e.substring(1)}(e):e}({mm:\"munutenn\",MM:\"miz\",dd:\"devezh\"}[n],e)}", "function t(e,t,n){return e+\" \"+function(e,t){return 2===t?function(e){var t={m:\"v\",b:\"v\",d:\"z\"};return void 0===t[e.charAt(0)]?e:t[e.charAt(0)]+e.substring(1)}(e):e}({mm:\"munutenn\",MM:\"miz\",dd:\"devezh\"}[n],e)}", "function t(e,t,n){return e+\" \"+function(e,t){return 2===t?function(e){var t={m:\"v\",b:\"v\",d:\"z\"};return void 0===t[e.charAt(0)]?e:t[e.charAt(0)]+e.substring(1)}(e):e}({mm:\"munutenn\",MM:\"miz\",dd:\"devezh\"}[n],e)}", "function t(e,t,n){return e+\" \"+function(e,t){return 2===t?function(e){var t={m:\"v\",b:\"v\",d:\"z\"};return void 0===t[e.charAt(0)]?e:t[e.charAt(0)]+e.substring(1)}(e):e}({mm:\"munutenn\",MM:\"miz\",dd:\"devezh\"}[n],e)}", "function t(e,t,n){return e+\" \"+function(e,t){return 2===t?function(e){var t={m:\"v\",b:\"v\",d:\"z\"};return void 0===t[e.charAt(0)]?e:t[e.charAt(0)]+e.substring(1)}(e):e}({mm:\"munutenn\",MM:\"miz\",dd:\"devezh\"}[n],e)}", "function t(e,t,n){return e+\" \"+function(e,t){return 2===t?function(e){var t={m:\"v\",b:\"v\",d:\"z\"};return void 0===t[e.charAt(0)]?e:t[e.charAt(0)]+e.substring(1)}(e):e}({mm:\"munutenn\",MM:\"miz\",dd:\"devezh\"}[n],e)}", "function t(e,t,n){return e+\" \"+function(e,t){return 2===t?function(e){var t={m:\"v\",b:\"v\",d:\"z\"};return void 0===t[e.charAt(0)]?e:t[e.charAt(0)]+e.substring(1)}(e):e}({mm:\"munutenn\",MM:\"miz\",dd:\"devezh\"}[n],e)}", "function t(e,t,n){return e+\" \"+function(e,t){return 2===t?function(e){var t={m:\"v\",b:\"v\",d:\"z\"};return void 0===t[e.charAt(0)]?e:t[e.charAt(0)]+e.substring(1)}(e):e}({mm:\"munutenn\",MM:\"miz\",dd:\"devezh\"}[n],e)}", "function t(e,t,n){return e+\" \"+function(e,t){return 2===t?function(e){var t={m:\"v\",b:\"v\",d:\"z\"};return void 0===t[e.charAt(0)]?e:t[e.charAt(0)]+e.substring(1)}(e):e}({mm:\"munutenn\",MM:\"miz\",dd:\"devezh\"}[n],e)}", "function t(e,t,n){return e+\" \"+function(e,t){return 2===t?function(e){var t={m:\"v\",b:\"v\",d:\"z\"};return void 0===t[e.charAt(0)]?e:t[e.charAt(0)]+e.substring(1)}(e):e}({mm:\"munutenn\",MM:\"miz\",dd:\"devezh\"}[n],e)}", "function t(e,t,n){return e+\" \"+function(e,t){return 2===t?function(e){var t={m:\"v\",b:\"v\",d:\"z\"};return void 0===t[e.charAt(0)]?e:t[e.charAt(0)]+e.substring(1)}(e):e}({mm:\"munutenn\",MM:\"miz\",dd:\"devezh\"}[n],e)}", "function t(e,t,n){return e+\" \"+function(e,t){return 2===t?function(e){var t={m:\"v\",b:\"v\",d:\"z\"};return void 0===t[e.charAt(0)]?e:t[e.charAt(0)]+e.substring(1)}(e):e}({mm:\"munutenn\",MM:\"miz\",dd:\"devezh\"}[n],e)}", "function t(e,t,n){return e+\" \"+function(e,t){return 2===t?function(e){var t={m:\"v\",b:\"v\",d:\"z\"};return void 0===t[e.charAt(0)]?e:t[e.charAt(0)]+e.substring(1)}(e):e}({mm:\"munutenn\",MM:\"miz\",dd:\"devezh\"}[n],e)}", "function t(e,t,n){return e+\" \"+function(e,t){return 2===t?function(e){var t={m:\"v\",b:\"v\",d:\"z\"};return void 0===t[e.charAt(0)]?e:t[e.charAt(0)]+e.substring(1)}(e):e}({mm:\"munutenn\",MM:\"miz\",dd:\"devezh\"}[n],e)}" ]
[ "0.67597306", "0.6539693", "0.6307408", "0.6257998", "0.6243028", "0.6188651", "0.617667", "0.61541283", "0.61515933", "0.6145621", "0.61447424", "0.6106126", "0.6094502", "0.6089331", "0.60717016", "0.6057794", "0.60168844", "0.60041237", "0.5996934", "0.5992879", "0.5971842", "0.5970493", "0.5965942", "0.5950676", "0.5945902", "0.59363025", "0.59196323", "0.59162706", "0.58577985", "0.5852938", "0.58342236", "0.58191645", "0.5818911", "0.5818141", "0.5816606", "0.5806652", "0.5803458", "0.5802783", "0.5802749", "0.57958007", "0.57955307", "0.5791516", "0.57837766", "0.5782751", "0.5770135", "0.57700324", "0.5769552", "0.57655114", "0.5757101", "0.57419735", "0.5739883", "0.57346916", "0.57346916", "0.57344633", "0.57225895", "0.5718082", "0.5717416", "0.57173294", "0.5716273", "0.5710378", "0.57070446", "0.570648", "0.56832904", "0.56806684", "0.5678221", "0.56767845", "0.56757206", "0.5675583", "0.56752616", "0.56742144", "0.5668824", "0.5668824", "0.5662415", "0.56583345", "0.5652597", "0.5648387", "0.56429696", "0.5638608", "0.5636665", "0.5629947", "0.56258184", "0.56258184", "0.56258184", "0.56258184", "0.56258184", "0.56258184", "0.56258184", "0.56258184", "0.56258184", "0.56258184", "0.56258184", "0.56258184", "0.56258184", "0.56258184", "0.56258184", "0.56258184", "0.56258184", "0.56258184", "0.56258184", "0.56258184", "0.56258184" ]
0.0
-1
Loads the menu and displays it to the user.
function loadMenu() { // Load categories let categories = null; get("/api/authTable/getCategories", function (categoryData) { categories = JSON.parse(categoryData); for (var i = 0; i < categories.length; i++) { const c = categories[i]; $("#categories").append("<div class='category'>\n" + "<button id='category-" + c.categoryId + "-button' type='button' class='btn btn-block category-button' data-toggle='collapse' data-target='#category-" + c.categoryId + "'>" + c.name + "</button>\n" + "<div id='category-" + c.categoryId + "' class='collapse'>\n" + "<ul id='category-" + c.categoryId + "-list' class='menuitems list-group collapse'>\n" + "</ul>\n" + "</div>\n" + "</div>"); } // Load menu get("/api/authTable/getMenu", function (menuData) { menuItems = JSON.parse(menuData); for (let i = 0; i < menuItems.length; i++) { const menuItem = menuItems[i]; $("#category-" + menuItem.categoryId + "-list").append("<li id='menuitem-" + menuItem.id + "' class='menuitem list-group-item list-group-item-action' onclick='showItemModal(" + menuItem.id + ")' data-glutenfree='" + menuItem.is_gluten_free + "' data-vegetarian='" + menuItem.is_vegetarian + "' data-vegan='" + menuItem.is_vegan + "'>\n" + "<span class='bold'>" + menuItem.name + "</span> - £" + menuItem.price + "\n" + "<br>\n" + menuItem.description + "\n" + "<br>\n" + "</li>"); if (menuItem.is_gluten_free) { $("#menuitem-" + menuItem.id).append( "<img class='img1' src='../images/gluten-free.svg' alt='Gluten Free'>"); } if (menuItem.is_vegetarian) { $("#menuitem-" + menuItem.id).append( "<img class='img2' src='../images/vegetarian-mark.svg' alt='Vegetarian'>"); } if (menuItem.is_vegan) { $("#menuitem-" + menuItem.id).append( "<img class='img3' src='../images/vegan-mark.svg' alt='Vegan'>"); } } }); }); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function loadMenu(){\n\t\tpgame.state.start('menu');\n\t}", "function loadMenu() {\n // Works only with nav-links that have 'render' instead of 'component' below in return\n if (istrue) {\n // Do not show these buttons to unauthorise user\n document.getElementById(\"edit\").children[6].style.display = \"none\";\n document.getElementById(\"edit\").children[5].style.display = \"none\";\n document.getElementById(\"edit\").children[4].style.display = \"none\";\n document.getElementById(\"edit\").children[3].style.display = \"none\";\n }\n }", "function load_menu(){\n //take-order page content loading\n int_get_menu_item_install({stallid:user_info[\"stall\"]},function(data){\n cache_menu=data.content;\n display_order_menu();\n //--load menu info page\n display_menu_info();\n });\n}", "function loadMenu() {\n var nav = $('.navigation');\n if (nav.html() == \"\" || !nav.hasClass('settings_menu') || nav.hasClass('user_menu')) {\n nav.text('');\n $('.main').ready(function () {\n $http.get($rootScope.contextPath + '/components/settings/settings_menu.html').success(function (data) {\n\n angular.element('.navigation').append($compile(data)($scope));\n $('.ui.menu').find('.item').removeClass('active');\n $('.' + $state.current.name).addClass('active');\n nav.addClass('settings_menu');\n nav.removeClass('user_menu');\n\n $('.ui.menu .item').on('click', function () {\n if (!$(this).hasClass('header')) {\n $(this).addClass('active').closest('.ui.menu').find('.item').not($(this))\n .removeClass('active');\n }\n });\n });\n });\n\n }\n }", "loadMenu() {\n switch (this.currentMenuChoices) {\n case MenuChoices.null: // case MenuChoices.edit:\n this.menuView.contentsMenu.style.display = \"block\";\n this.menuView.loadContent.style.display = \"inline-table\";\n this.currentMenuChoices = MenuChoices.load;\n this.menuView.loadButton.style.backgroundColor = this.menuView.menuColorSelected;\n this.menuView.loadButton.style.zIndex = \"1\";\n break;\n case MenuChoices.load:\n this.menuView.contentsMenu.style.display = \"none\";\n this.menuView.loadContent.style.display = \"none\";\n this.currentMenuChoices = MenuChoices.null;\n this.menuView.loadButton.style.backgroundColor = this.menuView.menuColorDefault;\n this.menuView.loadButton.style.zIndex = \"0\";\n break;\n default:\n this.cleanMenu();\n this.menuView.loadButton.style.backgroundColor = this.menuView.menuColorSelected;\n this.menuView.loadButton.style.zIndex = \"1\";\n this.menuView.loadContent.style.display = \"inline-table\";\n this.currentMenuChoices = MenuChoices.load;\n break;\n }\n }", "showMenu() {\n this._game = null;\n this.stopRefresh();\n this._view.renderMenu();\n this._view.bindStartGame(this.startGame.bind(this));\n this._view.bindShowScores(this.showScores.bind(this));\n }", "function renderMenu() {\n let logged = loggedin();\n showTemplate(\"menu-template\", \"menu-place\", {loggedin: logged});\n}", "function displayMenu() {\n inquirer.prompt(menuChoices).then((response) => {\n switch (response.selection) {\n case \"View Departments\":\n //call function that shows all departments\n viewDepartments();\n break;\n\n case \"Add Department\":\n //call function that adds a department\n addDepartment();\n break;\n\n case \"View Roles\":\n getRole();\n break;\n\n case \"Add Role\":\n addRole();\n break;\n\n case \"View Employees\":\n viewEmployee();\n break;\n\n case \"Add Employee\":\n addEmployee();\n break;\n\n case \"Update Employee\":\n break;\n\n default:\n connection.end();\n process.exit();\n // quit the app\n }\n });\n}", "function onOpen() {\n createMenu();\n}", "function display_menu(layerId) {\n\thide_menu();\n\tmenu = stage.get('#' + objects_json[layerId][\"menu\"])[0];\n\tif (!menu)\n\t\treturn;\n\t\t\n\tmenu.show()\n\tcurrent_menu = menu;\n\tmenu.moveToTop();\n}", "function showMainMenu(){\n addTemplate(\"menuTemplate\");\n showMenu();\n}", "function onOpen() { CUSTOM_MENU.add(); }", "function loadMenu(){\n if(failSafe){\n textIntro.innerHTML = \"\";\n svg.style.display = \"block\";\n newGameButton.style.display = \"block\";\n buttonBox.style.display = \"block\";\n endText.style.display = \"none\";\n endStats.style.display = \"none\";\n textMenu.style.display = \"none\";\n textIntro.style.display = \"none\";\n skipButton.style.display = \"none\";\n skipButtonBox.style.display = \"none\";\n endText.style.display = \"none\";\n endStats.style.display = \"none\";\n if (localStorage.getItem(\"game\") === null){\n button.style.display = \"none\";\n }else{\n button.style.display = \"block\";\n html.style.height = \"33%\";\n }\n failSafe = false;\n }\n}", "function showMenu(arg)\r\n\t{\r\n\t\tswitch(arg)\r\n\t\t{\r\n\t\t\tcase 0:\r\n\t\t\t\t$('#menu').html(\"\");\r\n\t\t\tbreak;\r\n\t\t\tcase 1:\r\n\t\t\t\t$('#menu').html(\"<h1 id='title' style='position:relative;top:20px;left:-40px;width:500px;'>Sheep's Snake</h1><p style='position:absolute;top:250px;left:-50px;font-size:1.1em;' id='playA'>Press A to play!</p><p style='position:absolute;top:280px;left:-50px;font-size:1.1em;' id='playB'>Press B for some help !</p>\");\r\n\t\t\t\t\r\n\t\t\tbreak;\r\n\t\t}\r\n\t}", "function loadDefaultMenu()\n{\n\tvar output = \"\";\n\t\n\toutput += \"<a href='javascript:void(0)' class='closebtn' onclick='closeNav()'>&times;</a>\"\n\toutput += \"<a href='#' onclick='javascript:loadRegions()'>Region</a>\"\n\toutput += \"<a href='#' onclick='javascript:loadCities()'>City</a>\"\n\toutput += \"<a href='#' onclick='javascript:loadTeams()'>Team</a>\"\n\t\n\tdocument.getElementById(\"mySidenav\").innerHTML = output;\n}", "function simulat_menu_infos() {\n display_menu_infos();\n}", "function Menu() {\n\t\t\n\t\tvar buildMenu = function (source, type) {\n\t\t\tvar b = new Builder();\n\t\t\tb.loadData (source, type);\n\t\t\treturn b.build();\n\t\t}\n\t\t\n\t\tvar attachMenu = function (menu, type, target, icons) {\n\t\t\tvar s = new Shell();\n\t\t\ts.link(menu, type, target, icons);\n\t\t}\n\t\t\n\t\t/**\n\t\t * Load a menu defined in XML format.\n\t\t * @param source\n\t\t * \t\tAn object containing XML menu(s) to be loaded for various OS-es.\n\t\t * @return\n\t\t * \t\tA NativeMenu object built from the given XML source.\n\t\t */\n\t\tthis.createFromXML = function ( source ) {\n\t\t\treturn buildMenu ( source, Builder.XML );\n\t\t}\n\t\t\n\t\t/**\n\t\t * Same as air.ui.Menu.fromXML, except it handles JSON data.\n\t\t */\n\t\tthis.createFromJSON = function ( source ) {\n\t\t\treturn buildMenu ( source, Builder.JSON );\n\t\t}\n\t\t\n\t\t/**\n\t\t * - on Windows: sets the given nativeMenu object as the NativeWindow's \n\t\t * menu;\n\t\t * - on Mac: inserts the items of the given nativeMenu object between \n\t\t * the 'Edit' and 'Window' default menus;\n\t\t * @param nativeMenu\n\t\t * \t\tA NativeMenu returned by one of the air.ui.Menu.from... \n\t\t * \t\tfunctions.\n\t\t * @param overwrite\n\t\t * \t\tA boolean that will change the behavior on Mac. If true, the \n\t\t * \t\tdefault menus will be replaced entirely by the given nativeMenu\n\t\t */\n\t\tthis.setAsMenu = function ( nativeMenu, overwrite ) {\n\t\t\tif (!arguments.length) {\n\t\t\t\tthrow (new Error( \n\t\t\t\t\t\"No argument given for the 'setAsMenu()' method.\"\n\t\t\t\t));\n\t\t\t}\n\t\t\tvar style = overwrite? Shell.MENU | Shell.OVERWRITE : Shell.MENU;\n\t\t\tattachMenu (nativeMenu, style);\n\t\t}\n\t\t\n\t\t/**\n\t\t * Displays the given menu as a contextual menu when the user right \n\t\t * clicks a certain DOM element.\n\t\t * @param nativeMenu\n\t\t * \t\tA NativeMenu returned by one of the air.ui.Menu.from... \n\t\t * \t\tfunctions.\n\t\t * @param domElement\n\t\t * \t\tThe DOM Element to link with the given nativeMenu. The \n\t\t * \t\tcontextual menu will only show when the user right clicks over \n\t\t * \t\tdomElement. This attribute is optional. If missing, the context\n\t\t * \t\tmenu will display on every right-click over the application.\n\t\t */\n\t\tthis.setAsContextMenu = function ( nativeMenu, domElement ) {\n\t\t\tif (!arguments.length) {\n\t\t\t\tthrow (new Error( \n\t\t\t\t\t\"No argument given for the 'setAsContextMenu()' method.\"\n\t\t\t\t));\n\t\t\t}\n\t\t\tif (arguments.length < 2) { domElement = Shell.UNSPECIFIED };\n\t\t\tattachMenu (nativeMenu, Shell.CONTEXT, domElement);\n\t\t}\n\t\t\n\t\t/**\n\t\t * Sets the given nativeMenu as the \n\t\t * ''NativeApplication.nativeApplication.icon.menu'' property.\n\t\t * @param nativeMenu\n\t\t * \t\tA NativeMenu returned by one of the air.ui.Menu.from... \n\t\t * \t\tfunctions.\n\t\t * @param icons\n\t\t * \t\tAn array holding icon file paths or bitmap data objects.\n\t\t * \t\tIf specified, these will be used as the application's\n\t\t * \t\ttray/dock icons.\n\t\t * @throws\n\t\t * \t\tIf no bitmap data was set for the ''icon'' object and no default\n\t\t * \t\ticons are specified in the application descriptor.\n\t\t */\n\t\tthis.setAsIconMenu = function ( nativeMenu, icons ) {\n\t\t\tif (!arguments.length) {\n\t\t\t\tthrow (new Error( \n\t\t\t\t\t\"No argument given for the 'setAsIconMenu()' method.\"\n\t\t\t\t));\n\t\t\t}\n\t\t\tattachMenu (nativeMenu, Shell.ICON, null, icons);\n\t\t}\n\t\t\n\t}", "function initialize() {\n activateMenus();\n}", "function initMenu(){\n\toutlet(4, \"vpl_menu\", \"clear\");\n\toutlet(4, \"vpl_menu\", \"append\", \"properties\");\n\toutlet(4, \"vpl_menu\", \"append\", \"help\");\n\toutlet(4, \"vpl_menu\", \"append\", \"rename\");\n\toutlet(4, \"vpl_menu\", \"append\", \"expand\");\n\toutlet(4, \"vpl_menu\", \"append\", \"fold\");\n\toutlet(4, \"vpl_menu\", \"append\", \"---\");\n\toutlet(4, \"vpl_menu\", \"append\", \"duplicate\");\n\toutlet(4, \"vpl_menu\", \"append\", \"delete\");\n\n\toutlet(4, \"vpl_menu\", \"enableitem\", 0, myNodeEnableProperties);\n\toutlet(4, \"vpl_menu\", \"enableitem\", 1, myNodeEnableHelp);\n outlet(4, \"vpl_menu\", \"enableitem\", 3, myNodeEnableBody);\t\t\n outlet(4, \"vpl_menu\", \"enableitem\", 4, myNodeEnableBody);\t\t\n}", "function addMenu(){\n var appMenu = new gui.Menu({ type: 'menubar' });\n if(os.platform() != 'darwin') {\n // Main Menu Item 1.\n item = new gui.MenuItem({ label: \"Options\" });\n var submenu = new gui.Menu();\n // Submenu Items.\n submenu.append(new gui.MenuItem({ label: 'Preferences', click :\n function(){\n // Add preferences options.\n // Edit Userdata and Miscellaneous (Blocking to be included).\n\n var mainWin = gui.Window.get();\n\n\n var preferWin = gui.Window.open('./preferences.html',{\n position: 'center',\n width:901,\n height:400,\n focus:true\n });\n mainWin.blur();\n }\n }));\n\n submenu.append(new gui.MenuItem({ label: 'User Log Data', click :\n function(){\n var mainWin = gui.Window.get();\n\n var logWin = gui.Window.open('./userlogdata.html',{\n position: 'center',\n width:901,\n height:400,\n toolbar: false,\n focus:true\n });\n }\n }));\n\n submenu.append(new gui.MenuItem({ label: 'Exit', click :\n function(){\n gui.App.quit();\n }\n }));\n\n item.submenu = submenu;\n appMenu.append(item);\n\n // Main Menu Item 2.\n item = new gui.MenuItem({ label: \"Transfers\"});\n var submenu = new gui.Menu();\n // Submenu 1.\n submenu.append(new gui.MenuItem({ label: 'File Transfer', click :\n function(){\n var mainWin = gui.Window.get();\n var aboutWin = gui.Window.open('./filetransfer.html',{\n position: 'center',\n width:901,\n height:400,\n toolbar: false,\n focus: true\n });\n mainWin.blur();\n }\n }));\n item.submenu = submenu;\n appMenu.append(item);\n\n // Main Menu Item 3.\n item = new gui.MenuItem({ label: \"Help\" });\n var submenu = new gui.Menu();\n // Submenu 1.\n submenu.append(new gui.MenuItem({ label: 'About', click :\n function(){\n var mainWin = gui.Window.get();\n var aboutWin = gui.Window.open('./about.html', {\n position: 'center',\n width:901,\n height:400,\n toolbar: false,\n focus: true\n });\n mainWin.blur();\n }\n }));\n item.submenu = submenu;\n appMenu.append(item);\n gui.Window.get().menu = appMenu;\n }\n else {\n // menu for mac.\n }\n\n}", "function loadManagerMenu() {\n connection.query(\"SELECT * FROM products\", function(err, res) {\n if (err) throw err;\n // Load the possible manager menu options, pass in the products data\n loadManagerOptions(res);\n });\n}", "function loadMenus() {\r\n debugger;\r\n API.getMenus()\r\n .then(res => \r\n setMenus(res.data)\r\n )\r\n .catch(err => console.log(err));\r\n }", "function setupMenu() {\n // console.log('setupMenu');\n\n document.getElementById('menuGrip')\n .addEventListener('click', menuGripClick);\n\n document.getElementById('menuPrint')\n .addEventListener('click', printClick);\n\n document.getElementById('menuHighlight')\n .addEventListener('click', menuHighlightClick);\n\n const menuControls = document.getElementById('menuControls');\n if (Common.isIE) {\n menuControls.style.display = 'none';\n } else {\n menuControls.addEventListener('click', menuControlsClick);\n }\n\n document.getElementById('menuSave')\n .addEventListener('click', menuSaveClick);\n\n document.getElementById('menuExportSvg')\n .addEventListener('click', exportSvgClick);\n\n document.getElementById('menuExportPng')\n .addEventListener('click', exportPngClick);\n\n PageData.MenuOpen = (Common.Settings.Menu === 'Open');\n}", "function loadHorizontalMenu() {\n\t\t \tvar loadAsync = new Deferred();\n\n\t\t\t\trequire([\"dojo/request\"], function(request){\n\t\t\t\t\n\t\t\t\t\trequest(jsonDefinitionUri_).then(function(data){\n\t\t\t\t\t\t\n\t\t\t\t\t\t// Having \" in a string for JSON parsing is sometimes\n\t\t\t\t\t\t// frowned on by parsers; replace them with ' to prevent\n\t\t\t\t\t\t// obscure JSON parsing problems\n\t\t\t\t\t\tvar menuData = JSON.parse(data.replace(/\\\\\"/g,\"\\'\"));\n\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\tDojoArray.forEach(menuData.menus_,function(item){\n\t\t\t\t\t\t\tbuildMenu(item,hMenu,false);\n\t\t\t\t\t\t});\n\t\t\t\t\t\t\n\t\t\t\t\t\t// Our accessibility key for the File Menu is m\n\t\t \thMenu.own(\n\t \t\t\ton(window, \"keypress\", function(e){\n\t \t\t\t\trequire([\"dialogs\"],function(BTDialogs){\n\t \t\t\t\t\tif(!BTDialogs.checkForRegisteredModals()) {\n\t\t\t\t\t \t\tvar keyPressed = String.fromCharCode(e.charCode || e.keyCode || e.which);\n\t\t\t\t\t \t\tif(keyPressed == \"m\") {\n\t\t\t\t\t \t\t\thMenu.focus();\n\t\t\t\t \t\t\t\te.preventDefault();\n\t\t\t\t \t\t\t\te.stopPropagation();\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\n\t \t\t\t\t});\n\t \t\t\t})\n\t\t \t);\t\n\t\t \t\n\t\t \t// MenuBar doesn't completely behave in a desktop-like manner due to how focusing on\n\t\t \t// the DOM works. So this helps make it slightly more Desktop-like.\n\t\t \t\n\t\t \thMenu.own(\n\t \t\t\ton(hMenu, \"keypress\", function(e){\n\t\t\t \t\tvar keyPressed = String.fromCharCode(e.charCode || e.keyCode || e.which);\n\t\t\t \t\tif(keyPressed == \"m\") {\n\t\t\t \t\t\t// There's a problem with the menubar not actually being blurred\n\t\t\t \t\t\t// once an action's been used in one of its submenus. So we're going\n\t\t\t \t\t\t// to instead force defocusing and then reacquire. Unfortunately\n\t\t\t \t\t\t// this will always land back on the first MenuBar child, but it's\n\t\t\t \t\t\t// better than an invisible focus.\n\t\t\t \t\t\tif(hMenu.focusedChild === hMenu.getChildren()[0]) {\n\t\t\t \t\t\t\thMenu.focusNext();\n\t\t\t \t\t\t}\n\t\t\t \t\t\thMenu.focus();\n\t\t \t\t\t\te.preventDefault();\n\t\t \t\t\t\te.stopPropagation();\n\t\t\t \t\t}\n\t \t\t\t})\n\t\t \t);\t\t \t\n\n\t\t\t\t\t\thMenu.startup();\n\t\t\t\t\t\t\n\t\t\t\t\t\tloadAsync.resolve(hMenu);\n\t\t\t\t\t\t\n\t\t\t\t\t}, function(err){\n\t\t\t\t\t\tloadAsync.reject(\"FileMenu request errored: \" + err);\n\t\t\t\t\t}, function(evt){\n\t\t\t\t\t\t// Progress would go here\n\t\t\t\t\t});\n\t\t\t\t});\t\t \t\n\t\t \t\n\t\t \treturn loadAsync.promise;\n\t\t }", "function loadMenu(currentNavItem){\n /**\n * Load menu to div with id \"menu\" and highlight tab denoted by currentNavItem\n * @param {String} currentNavItem - either search, compare, or donate\n */\n var xhr= new XMLHttpRequest();\n xhr.open('GET', 'menu.html', true);\n xhr.onreadystatechange= function() {\n if (this.readyState!==4) return;\n if (this.status!==200) return; // or whatever error handling you want\n document.getElementById('menu').innerHTML= this.responseText;\n // Highlight current page nav text after menu bar is loaded\n console.log(currentNavItem)\n highlightNavItem(currentNavItem)\n obj = getSessionObject()\n document.getElementById('funds').innerHTML = '$'+(obj['percentAllocated']/100.0*obj['totalFunds']).toFixed(2)+'/$'+obj['totalFunds']+' allocated';\n loadCart();\n };\n xhr.send();\n\n}", "function mainMenuShow () {\n $ (\"#menuButton\").removeAttr (\"title-1\");\n $ (\"#menuButton\").attr (\"title\", htmlSafe (\"Stäng menyn\")); // i18n\n $ (\"#menuButton\").html (\"×\");\n $ (\".mainMenu\").show ();\n}", "function menu() {\n\t$('#menu').off();\n\tinitModel();\n\trenderMenu();\n\n\t$('#menu').on('click', '.levels', game);\n}", "function displayMenu () {\n inquirer\n .prompt([\n {\n type: \"list\",\n message: \"What would you like to do?\",\n name: \"choice\",\n choices: [\"View Product Sales by Department\", \"Create New Department\", \"Exit\"]\n }\n ]).then(answers => {\n\n switch (answers.choice) {\n\n case \"View Product Sales by Department\":\n viewSalesbyDept();\n break;\n\n case \"Create New Department\":\n createNewDepartment();\n break;\n\n case \"Exit\":\n connection.end();\n break;\n }\n });\n}", "function carregaMenu(pagina){\n\tlet dir = \"C:/www/HEALTHLAB/frontend/\";\n\t$('#menu').load(dir+pagina, function() {\n\t\tdocument.getElementById('titulo-header').innerHTML = document.getElementById('title').innerHTML;\n\t});\n}", "function displayMenu() {\n inquirer.prompt([\n {\n type: \"list\",\n message: \"What role are you populating today?\",\n name: \"userInput\",\n choices: [\"manager\", \"intern\", \"engineer\", \"exit application\"]\n\n }\n ])\n .then(function (response) {\n switch (response.userInput) {\n case \"manager\":\n addmanager()\n break;\n case \"intern\":\n addintern()\n break;\n case \"engineer\":\n addengineer()\n break;\n default:\n exitapp()\n }\n } )\n }", "function main() {\n MenuItem.init();\n sizeUI();\n }", "function loadMenu(debug){\n // Generate program options\n var menu = SpreadsheetApp.getUi()\n .createMenu('Teaching')\n .addItem('Send grades to all student rows', 'sendGradesAll')\n .addItem('Send grade to individual student by row', 'sendGradesSelect')\n .addSeparator();\n\n // Generate Debug options\n if(debug == 'true') {\n menu.addItem('Turn debug off', 'turnOffDebug')\n .addItem('Change debug email <' + userProp.getProperty(g_debugEmail_key) + '>', 'changeDebugEmail')\n .addItem('Reset debug defaults', 'resetDebug');\n } else {\n menu.addItem('Turn debug on', 'turnOnDebug');\n }\n\n // Update UI\n menu.addToUi();\n}", "function loadmenu() {\n console.log(\"clicked\");\n location.href=\"menu.html\";\n}", "function install_menu() {\n var config = {\n name: 'dashboard_level',\n submenu: 'Settings',\n title: 'Dashboard Level',\n on_click: open_settings\n };\n wkof.Menu.insert_script_link(config);\n }", "function startMenu() {\n createManager();\n}", "function openMenu() {\n if (menu_visible)\n return;\n menuGroup.add(mesh_menu);\n mesh_menu.position.set(mouse_positions[1].x, mouse_positions[1].y, mouse_positions[1].z);\n mesh_menu.lookAt(camera.position);\n menu_visible = true;\n }", "function displayMenu(to_user) {\n if (current == null) {\n cb.log('current menu is null')\n current = menus[0]\n }\n if (current == null) {\n cb.log('current menu is still null')\n return\n }\n cb.sendNotice(current.list(), to_user, background, color, weight)\n}", "function showMenu(){opts.parent.append(element);element[0].style.display='';return $q(function(resolve){var position=calculateMenuPosition(element,opts);element.removeClass('md-leave');// Animate the menu scaling, and opacity [from its position origin (default == top-left)]\n\t// to normal scale.\n\t$animateCss(element,{addClass:'md-active',from:animator.toCss(position),to:animator.toCss({transform:''})}).start().then(resolve);});}", "function loadApplication() {\n console.log(\"Application loaded\");\n // Load directly to the main menu\n configureUI(displayMainMenu());\n\n}", "function initMenuUI() {\n clearMenu();\n let updateBtnGroup = $(\".menu-update-btn-group\");\n let modifyBtnGroup = $(\".menu-modify-btn-group\");\n let delBtn = $(\"#btn-delete-menu\");\n\n setMenuTitle();\n $(\"#btn-update-menu\").text(menuStatus == \"no-menu\" ? \"创建菜单\" : \"更新菜单\");\n menuStatus == \"no-menu\" ? hideElement(modifyBtnGroup) : unhideElement(modifyBtnGroup);\n menuStatus == \"no-menu\" ? unhideElement(updateBtnGroup) : hideElement(updateBtnGroup);\n menuStatus == \"no-menu\" ? setDisable(delBtn) : setEnable(delBtn);\n }", "function setMenu(menu){ \n switch(menu){\n case 'food-input-icon':\n loadFoodMenu();\n break; \n \n case 'stats-icon':\n loadStatsMenu(); \n break; \n \n case 'settings-icon':\n loadSettingsMenu(); \n break;\n \n case 'share-icon':\n loadShareMenu(); \n break;\n \n case 'sign-out-icon':\n signOut(); \n break;\n case 'nav-icon':\n loadNavMenu(); \n \n }\n}", "function nicholls_menu_loader() {\n\t\t\n\t\t\tjQuery('#footer').append( '<div id=\"nicholls-menu-loader\"></div>' );\n\t\t\t\n\t\t\tjQuery('#nicholls-menu-list').children().each( function() {\n\t\t\t\t// We stop if the item has no menu. Using the .each() using 'return true' is like 'continue'\n\t\t\t\tif ( jQuery(this).hasClass('nicholls-menu-no' ) ) return true;\n\t\t\t\t\n\t\t\t\t// We get the class of the moused over object\n\t\t\t\tvar menu_load_id = jQuery(this).attr('id');\n\t\n\t\t\t\t// Perorm all the heavy lifting ajax because menu_load_id should be clean by now\n\t\t\t\tvar menu_data = jQuery( '#'+menu_load_id+'-source' ).html();\n\t\n\t\t\t\tjQuery('#nicholls-menu-content').append( '<div id=\"'+menu_load_id+'-contents\" class=\"nicholls-menu-contents\">'+menu_data+'</div>' );\n\t\t\t\n\t\t\t});\n\t\t\n\t\t}", "function displayMenu() {\n inquirer\n .prompt([\n {\n type: \"list\",\n name: \"Menu\",\n message: \"Choose your option from the below menu???\",\n choices: [\n \"a: View Products for Sale\",\n \"b: View Low Inventory\",\n \"c: Add to Inventory\",\n \"d: Add New Product\",\n \"e: Exit\"\n ]\n }\n ])\n .then(function(choice) {\n switch (choice.Menu) {\n case \"a: View Products for Sale\":\n viewProductsForSale();\n break;\n case \"b: View Low Inventory\":\n viewLowInventory();\n break;\n case \"c: Add to Inventory\":\n addToInventory();\n break;\n case \"d: Add New Product\":\n addNewProduct();\n break;\n case \"e: Exit\":\n console.log(\"Thank-you!\");\n break;\n }\n });\n}", "function openMenu() {\n g_IsMenuOpen = true;\n}", "function manageMenu() {\n if (menuOpen) {\n menuOpen = false;\n closeMenu();\n } else {\n menuOpen = true;\n openMenu();\n }\n}", "function init() {\n let menu = $E('menu', {\n id: kUI.prefMenu.id,\n label: kUI.prefMenu.label,\n accesskey: kUI.prefMenu.accesskey\n });\n\n if (kSiteList.length) {\n let popup = $E('menupopup');\n\n $event(popup, 'command', onCommand);\n\n kSiteList.forEach(({name, disabled}, i) => {\n let menuitem = popup.appendChild($E('menuitem', {\n label: name + (disabled ? ' [disabled]' : ''),\n type: 'checkbox',\n checked: !disabled,\n closemenu: 'none'\n }));\n\n menuitem[kDataKey.itemIndex] = i;\n });\n\n menu.appendChild(popup);\n }\n else {\n $E(menu, {\n tooltiptext: kUI.prefMenu.noSiteRegistered,\n disabled: true\n });\n }\n\n $ID('menu_ToolsPopup').appendChild(menu);\n }", "updateMenuItemsDisplay () {\n const pg = this.page\n if (!pg) {\n // initial page load, header elements not yet attached but menu items\n // would already be hidden/displayed as appropriate.\n return\n }\n if (!this.user.authed) {\n Doc.hide(pg.noteMenuEntry, pg.walletsMenuEntry, pg.marketsMenuEntry, pg.profileMenuEntry)\n return\n }\n Doc.show(pg.noteMenuEntry, pg.walletsMenuEntry, pg.profileMenuEntry)\n if (Object.keys(this.user.exchanges).length > 0) {\n Doc.show(pg.marketsMenuEntry)\n } else {\n Doc.hide(pg.marketsMenuEntry)\n }\n }", "function menuShow() {\n ui.appbarElement.addClass('open');\n ui.mainMenuContainer.addClass('open');\n ui.darkbgElement.addClass('open');\n}", "function add_menu(){\n\t/******* add menu ******/\n\t// menu itsself\n\tvar menu=$(\"#menu\");\n\tif(menu.length){\n\t\trem_menu();\n\t};\n\n\tmenu=$(\"<div></div>\");\n\tmenu.attr(\"id\",\"menu\");\n\tmenu.addClass(\"menu\");\n\t\n\t//////////////// rm setup //////////////////\n\tvar f=function(){\n\t\tvar box=$(\"#rm_box\");\n\t\tif(box.length){\n\t\t\tbox.toggle();\t\n\t\t}\n\t};\n\tadd_sidebar_entry(menu,f,\"rules\",\"style\");\n\tvar box=$(\"<div></div>\");\n\tbox.attr(\"id\",\"rm_box\");\n\tbox.text(\"loading content ... hang on\");\n\tbox.hide();\n\tmenu.append(box);\t\n\t//////////////// rm setup //////////////////\n\n\t//////////////// area setup //////////////////\n\tvar f=function(){\n\t\tvar box=$(\"#areas_box\");\n\t\tif(box.length){\n\t\t\tbox.toggle();\t\n\t\t}\n\t};\n\tadd_sidebar_entry(menu,f,\"areas\",\"home\");\n\tvar box=$(\"<div></div>\");\n\tbox.attr(\"id\",\"areas_box\");\n\tbox.text(\"loading content ... hang on\");\n\tbox.hide();\n\tmenu.append(box);\t\n\t//////////////// area setup //////////////////\n\n\t//////////////// camera setup //////////////////\n\tvar f=function(){\n\t\tvar box=$(\"#cameras_box\");\n\t\tif(box.length){\n\t\t\tbox.toggle();\t\n\t\t}\n\t};\n\tadd_sidebar_entry(menu,f,\"units\",\"camera_enhance\");\n\tvar box=$(\"<div></div>\");\n\tbox.attr(\"id\",\"cameras_box\");\n\tbox.text(\"loading content ... hang on\");\n\tbox.hide();\n\tmenu.append(box);\t\n\t//////////////// camera setup //////////////////\n\n\t//////////////// user setup //////////////////\n\tvar f=function(){\n\t\tvar box=$(\"#users_box\");\n\t\tif(box.length){\n\t\t\tbox.toggle();\t\n\t\t\tlogin_entry_button_state(\"-1\",\"show\");\t// scale the text fields for the \"new\" entry = -1\n\t\t}\n\t};\n\tadd_sidebar_entry(menu,f,\"users\",\"group\");\n\tvar box=$(\"<div></div>\");\n\tbox.attr(\"id\",\"users_box\");\n\tbox.text(\"loading content ... hang on\");\n\tbox.hide();\n\tmenu.append(box);\t\n\t//////////////// user setup //////////////////\n\n\n\t//////////////// logout //////////////////\n\tvar f=function(){\n\t\t\tg_user=\"nongoodlogin\";\n\t\t\tg_pw=\"nongoodlogin\";\n\t\t\tc_set_login(g_user,g_pw);\n\t\t\ttxt2fb(get_loading(\"\",\"Signing you out...\"));\n\t\t\tfast_reconnect=1;\n\t\t\tcon.close();\n\n\t\t\t// hide menu\n\t\t\trem_menu();\n\t};\n\tadd_sidebar_entry(menu,f,\"log-out\",\"vpn_key\");\n\t//////////////// logout //////////////////\n\n\t////////////// hidden data_fields /////////////\n\tvar h=$(\"<div></div>\");\n\th.attr(\"id\",\"list_cameras\");\n\th.hide();\n\tmenu.append(h);\n\n\th=$(\"<div></div>\");\n\th.attr(\"id\",\"list_area\");\n\th.hide();\n\tmenu.append(h);\n\t////////////// hidden data_fields /////////////\n\n\n\tmenu.insertAfter(\"#clients\");\n\t\n\n\tvar hamb=$(\"<div></div>\");\n\thamb.click(function(){\n\t\treturn function(){\n\t\t\ttoggle_menu();\n\t\t}\n\t}());\n\thamb.attr(\"id\",\"hamb\");\n\thamb.addClass(\"hamb\");\n\tvar a=$(\"<div></div>\");\n\tvar b=$(\"<div></div>\");\n\tvar c=$(\"<div></div>\");\n\ta.addClass(\"hamb_l\");\n\tb.addClass(\"hamb_l\");\n\tc.addClass(\"hamb_l\");\n\thamb.append(a);\n\thamb.append(b);\n\thamb.append(c);\n\thamb.insertAfter(\"#clients\");\n\t/******* add menu ******/\n}", "function display_menu_infos() {\n var menu_item_html = \"\";\n if (data.menu_info != undefined) {\n for (var i = 0; i < data.menu_info.length; i++) {\n menu_item_html += '<ul id=\"menuItem' + i;\n menu_item_html += '\" onclick=\"selectMenu(' + i + ')\">';\n menu_item_html += data.menu_info[i]['name'] + '</ul>';\n }\n }\n $('#horizontal_menu_bar').html(menu_item_html);\n}", "function init() {\n console.log('Welcome to your company employee manager.')\n menu()\n}", "function loadMenuItem(){\n\tvar gebruikersnaam = window.sessionStorage.getItem(\"huidigeGebruiker\");\n\tvar url = \"restservices/gebruiker?Q1=\" + gebruikersnaam;\n\t\t$.ajax({\n\t\t\turl : url,\n\t\t\tmethod : \"GET\",\n\t\t\tbeforeSend : function(xhr) {\n\t\t\t\tvar token = window.sessionStorage.getItem(\"sessionToken\");\n\t\t\t\txhr.setRequestHeader('Authorization', 'Bearer ' + token);\n\t\t\t},\n\t\t\tsuccess : function(data) {\n\t\t\t\t$(data).each(function (index) {\n\t\t\t\t\tdocument.getElementById('gebruikersnaammenu').innerHTML = this.voornaam;\n\t\t\t\t\t\n\t\t\t\tif (this.role == \"admin\"){\n\t\t\t\t\tvar adminli = '<li><a href=\"ingredient-wijzigen.html\">Ingrediënt wijzigen</a></li>';\n\t\t\t\t\t$(\".autouser li:last-child\").before (adminli);\n\t\t\t\t}\n\t\t\t\t});\n\t\t\t},\n\t\t\tfail : function() {\n\t\t\t\tconsole.log(\"Failed\");\n\t\t\t},\n\t\t});\n}", "function displayMenu() {\n \"use strict\";\n window.console.log(\"Welcome to the Product Inventory Management System\");\n window.console.log(\"\");\n window.console.log(\"COMMAND MENU\");\n window.console.log(\"view - view all products\");\n window.console.log(\"update - update stock\");\n window.console.log(\"exit - exit the program\");\n window.console.log(\"\");\n}", "function run () { \n if (m.debug > m.NODEBUG) { console.log('screens.menuScreen.run'); }\n\n // one-time initialization\n if (needsInit) {\n // draw logo\n var $canvasBox = $('#menuLogoBox');\n m.logo.drawLogo($canvasBox, false, 0, 0, 0);\n \n $('#menuScreen button')\n // navigate to the screen stored in the button's data\n .click( function (event) {\n var nextScreenId = $(event.target).data('screen');\n m.screens.showScreen(nextScreenId);\n }\n );\n \n // redraw logo when window is resized\n $(window)\n .resize(function (event) {\n $canvasBox.empty();\n m.logo.drawLogo($canvasBox, false, 0, 0, 0);\n }\n );\n }\n needsInit = false;\n \n // Turn off sounds, game loop and mouse event handling in game screen\n m.Audio.beQuiet();\n m.gameloop.setLoopFunction(null);\n m.playtouch.unhookMouseEvents();\n \n \n }", "function load_left_menu() {\n\tvar div = document.getElementById(\"left_menu\");\n\thr.open(\"POST\", \"/main/load_left_menu\", true);\n\thr.setRequestHeader(\"Content-type\", \"application/x-www-form-urlencoded\");\n\thr.onreadystatechange = function() {\n\t\tif(hr.readyState == 4) {\n\t\t\tif(hr.status == 200) {\n\t\t\t\tdiv.innerHTML = hr.responseText;\n\t\t\t\t}\n\t\t\t}\n\t}\n\thr.send();\n}", "function mainMenu() {\n\n //Present the user with a list of options to choose from\n inquirer\n .prompt([\n //give user main menu options\n {\n name: \"choice\",\n type: \"rawlist\",\n choices: info.menus.main,\n message: \"What would you like to do?\"\n }\n ])\n .then(function(answer) {\n //Check if the user wants to exit\n checkForExit(answer.choice);\n\n switch(answer.choice) {\n case \"Run Test\":\n pickDirectory(\"test\");\n break;\n case \"View Scores\":\n viewMenu();\n break;\n default:\n mainMenu();\n }\n \n });\n}", "function menu(_func){\n\tif(myNodeInit){\t\t\n\t\tif(_func == \"properties\"){\n\t\t\topenproperties();\n\t\t} else if(_func == \"collapse\"){\n \tmyExpandedMode = 0;\n\t\t\texpand();\n \toutlet(4, \"vpl_menu\", \"setitem\", 3, \"expand\");\n \toutlet(4, \"vpl_menu\", \"setitem\", 4, \"fold\");\n\t\t} else if(_func == \"expand\" || _func == \"unfold\"){\n \tmyExpandedMode = 2;\n\t\t\texpand();\n \toutlet(4, \"vpl_menu\", \"setitem\", 3, \"collapse\");\n \toutlet(4, \"vpl_menu\", \"setitem\", 4, \"fold\");\n } else if(_func == \"fold\"){\n \tmyExpandedMode = 1;\n\t\t\texpand();\n \toutlet(4, \"vpl_menu\", \"setitem\", 3, \"collapse\");\n \toutlet(4, \"vpl_menu\", \"setitem\", 4, \"unfold\");\n\t\t} else if(_func == \"duplicate\"){\n\t\t\t;\n\t\t} else if(_func == \"delete\"){\n\t\t\t;\n\t\t} else if(_func == \"help\"){\n\t\t\toutlet(2, \"load\", \"bs.help.node.\" + myNodeHelp + \".maxpat\");\n\t\t}\n\t}\n}", "function initializeMenu() {\n robotMenu = Menus.addMenu(\"Robot\", \"robot\", Menus.BEFORE, Menus.AppMenuBar.HELP_MENU);\n\n CommandManager.register(\"Select current statement\", SELECT_STATEMENT_ID, \n robot.select_current_statement);\n CommandManager.register(\"Show keyword search window\", TOGGLE_KEYWORDS_ID, \n search_keywords.toggleKeywordSearch);\n CommandManager.register(\"Show runner window\", TOGGLE_RUNNER_ID, \n runner.toggleRunner);\n CommandManager.register(\"Run test suite\", RUN_ID,\n runner.runSuite)\n robotMenu.addMenuItem(SELECT_STATEMENT_ID, \n [{key: \"Ctrl-\\\\\"}, \n {key: \"Ctrl-\\\\\", platform: \"mac\"}]);\n \n robotMenu.addMenuDivider();\n\n robotMenu.addMenuItem(RUN_ID,\n [{key: \"Ctrl-R\"},\n {key: \"Ctrl-R\", platform: \"mac\"},\n ]);\n\n robotMenu.addMenuDivider();\n\n robotMenu.addMenuItem(TOGGLE_KEYWORDS_ID, \n [{key: \"Ctrl-Alt-\\\\\"}, \n {key: \"Ctrl-Alt-\\\\\", platform: \"mac\" }]);\n robotMenu.addMenuItem(TOGGLE_RUNNER_ID,\n [{key: \"Alt-R\"},\n {key: \"Alt-R\", platform: \"mac\"},\n ]);\n }", "function display_start_menu() {\n\tstart_layer.show();\n\tstart_layer.moveToTop();\n\t\n\tdisplay_menu(\"start_layer\");\n\tcharacter_layer.moveToTop();\n\tcharacter_layer.show();\n\tinventory_bar_layer.show();\n\t\n\tstage.draw();\n\t\n\tplay_music('start_layer');\n}", "function displayMenu(pCurrentPage) {\n document.writeln('<div id=\"topmenu\">')\n document.writeln(' <table width=\"100%\">')\n document.writeln(' <tr>')\n writeTD(pCurrentPage, \"index.html\", \"Welcome\")\n writeTD(pCurrentPage, \"download.html\", \"Download\")\n writeTD(pCurrentPage,\"documentation-main.html\", \"Documentation\")\n writeTD(pCurrentPage, \"migrating.html\", \"Migrating from JUnit\")\n writeTD(pCurrentPage, \"https://javadoc.io/doc/org.testng/testng/latest/index.html\", \"JavaDoc\")\n writeTD(pCurrentPage, \"selenium.html\", \"Selenium\")\n document.writeln(' </tr>')\n document.writeln(' <tr>')\n writeTD(pCurrentPage, \"eclipse.html\", \"Eclipse\")\n writeTD(pCurrentPage, \"idea.html\", \"IDEA\")\n writeTD(pCurrentPage, \"maven.html\", \"Maven\")\n writeTD(pCurrentPage, \"ant.html\", \"Ant\")\n writeTD(pCurrentPage, \"misc.html\", \"Miscellaneous\")\n writeTD(pCurrentPage, \"book.html\", \"Book\")\n writeTD(pCurrentPage, \"https://beust.com/kobalt\", \"Kobalt\")\n document.writeln(' </tr>')\n document.writeln(' </table>')\n document.writeln(' </div>')\n\n}", "function showMenu() {\n opts.parent.append(element);\n element[0].style.display = '';\n\n return $q(function(resolve) {\n var position = calculateMenuPosition(element, opts);\n\n element.removeClass('_md-leave');\n\n // Animate the menu scaling, and opacity [from its position origin (default == top-left)]\n // to normal scale.\n $animateCss(element, {\n addClass: '_md-active',\n from: animator.toCss(position),\n to: animator.toCss({transform: ''})\n })\n .start()\n .then(resolve);\n\n });\n }", "function StartMenu() {\n //this.menu = new Menu('start-menu');\n this.shutDownMenu = new Menu('shutdown-menu');\n this.shutDownButton = new MenuButton('options-button', this.shutDownMenu);\n Menu.apply(this, ['start-menu']);\n}", "function menu() {\n document.getElementById('menu').style.animation = \"fade-in 5s linear\";\n document.getElementById('menu').style.display = \"block\";\n document.getElementById('menu').style.opacity = 1;\n }", "function DfoMenu(/**string*/ menu)\r\n{\r\n\tSeS(\"G_Menu\").DoMenu(menu);\r\n\tDfoWait();\r\n}", "function menu() {\n inquirer.prompt([\n {\n type: \"list\",\n name: \"choice\",\n message: \"Supervisor's Menu Options:\",\n choices: [\"View Product Sales By Department\", \"Create New Department\", \"Exit\"]\n }\n ]).then(function (answers) {\n if (answers.choice === \"View Product Sales By Department\") {\n displaySales();\n }\n else if (answers.choice === \"Create New Department\") {\n createDepartment();\n }\n else {\n connection.end();\n }\n });\n}", "function contextMenuOn() {\n if (statusMenu) build_menu.style.display = \"block\";\n else {\n document.getElementById(settings.element).appendChild(build_menu);\n statusMenu = true;\n }\n }", "function showMenu() {\n menu.style.display = \"block\";\n let calButton = document.getElementById(\"calButton\");\n calButton.onclick = showCalendar;\n\n let user = JSON.parse(localStorage.getItem(\"user\"));\n if(user.role === 'admin'){\n let adm = document.getElementById(\"userAdmin\");\n adm.style.display = \"\";\n adm.onclick = showAdmin;\n }\n}", "function openMenu() {\n\n\t\t$(\"#menu-items\").css(\"display\",\"block\");\n \n $(\"#app-canvas\").velocity({\n\t\t\tleft:\"85%\",\n }, {\n duration: 300,\n complete: function() {\n\t\t\t\tsetTimeout(function(){\n isMenuOpen=true;\n },150);\n\t\t\t}\n }); \n }", "function renderNavigationMenu() {\n\n }", "populate() {\n //TODO Wait for the data to actually be available before populating.\n let menuWithFunctions = this.context.menu();\n let evaluatedMenu = [];\n menuWithFunctions.forEach(function(e) {\n if (e) {\n let value = e[1]();\n evaluatedMenu.push({\n title: e[0],\n value: value,\n showSpinner: value === null\n });\n } else {\n evaluatedMenu.push(null);\n }\n });\n this.menu = evaluatedMenu;\n }", "function showMenu() {\n // clear the console\n console.log('\\033c');\n // menu selection\n inquirer\n .prompt([\n {\n type: \"list\",\n name: \"wish\",\n choices: [\"View Product Sales by Department\", \"Create New Department\", \"Exit\"],\n message: '\\nWhat would you like to do? '\n }\n ]).then( answer => {\n switch (answer.wish){\n case \"View Product Sales by Department\":\n showSale();\n break;\n case \"Create New Department\":\n createDept();\n break;\n case \"Exit\":\n connection.end();\n break;\n default:\n console.log( `\\x1b[1m \\x1b[31m\\nERROR! Invalid Selection\\x1b[0m`);\n }\n })\n}", "function loadMenu() {\n GetPage('treemenu.html', \n function(pResponse) { \n $(\"#menu\").jstree({\n \"plugins\" : [ \"themes\", \"html_data\", \"ui\", \"cookies\"],\n \"cookies\" : {\n \"save_opened\" : \"evolved_tree\",\n \"save_selected\" : \"evolved_selected\",\n \"auto_save\" : true\n },\n \"themes\" : {\n \"theme\" : \"apple\",\n \"dots\" : true,\n \"icons\" : false\n },\n \"html_data\" : {\n \"data\" : pResponse\n }\n });\n ShowLoading(false);\n AttachLinkEvents();\n \n var goTo = $.query.get('GoTo');\n if(goTo) {\n ShowPage(unescape(goTo));\n } else {\n GetPage('welcome.html', \n function(pResponse) {\n $('#page').html(pResponse);\n AttachLinkEvents();\n }\n );\n }\n }\n );\n}", "function openMenuBar() {\n setOpen(!open)\n }", "function load_menu_links(menu, menu_option) {\n\n\tconsole.log('load_menu_links called: ');\n\tconsole.log('menu: '+JSON.stringify(menu))\n\tconsole.log('menu_option: '+JSON.stringify(menu_option))\n\n\n\t$(\"#side-menu > a\").click(function(e) {\n\t\te.preventDefault();\n\t\tlink = $(this).attr('href');\n\n\t\t$(\"#content-header\").html($(this).html());\n\n\t\tif (link in menu ) {\n\t\t\tlink2 = link;\n\t\t\t$('#content_'+link2).css('display','flex');\n\t\t\tload_sidebar_options(menu_option,link2);\n\t\t\tadd_back_button(menu_option);\n\t\t\tshow_content(link2);\n\t\t\treturn '';\n\t\t}\n\n\t\tconsole.log(\"SHOWING LINK: =========> \"+link);\n\t\tshow_content(link);\n\t});\n\n}", "function initMenuFunction() {\n if (menuStatus == \"menu-exist\") {\n fetchMenu(dateSelected).done(function (menuArray) {\n backupArray = menuArray;\n setMenuData(menuArray);\n setModifyButtonClickListener();\n setDeleteBtnClickListener(dateSelected);\n setMenuEditable(menuStatus === \"no-menu\" ? true : false);\n });\n }\n }", "function init(){\r\n\t// Load the data from the text file\r\n\tloadJSON(function(response){\r\n\t\t// Parse JSON string into object\r\n\t\tvar content = JSON.parse(response);\r\n\t\tvar header = content.header;\r\n\t\tvar menu = content.menu;\r\n\t\tvar title = content.title;\r\n\t\tvar body = content.body;\r\n\t\tvar footer = content.footer;\r\n\t\t\r\n\t\t// Initiate the menu value\r\n\t\tvar menuContent = \"\";\r\n\t\tvar subMenuContent = '';\r\n\t\t\r\n\t\t//Get all the items for the menu\r\n\t\tfor (i=0; i < menu.length; i++){\r\n\t\t\t// If the item has a submenu \r\n\t\t\tif(menu[i].submenu != null && menu[i].submenu.length > 0)\r\n\t\t\t{\r\n\t\t\t\titem = '<a href=\"'+menu[i].url+'\">'+menu[i].title+'<i class=\"down\"></i></a>';\r\n\t\t\t\t\r\n\t\t\t\tfor (j=0; j < menu[i].submenu.length; j++) \r\n\t\t\t\t{\r\n\t\t\t\t\tsubMenuContent += '<a href=\"'+menu[i].submenu[j].url+'\">'+menu[i].submenu[j].title+'</a>';\r\n\t\t\t\t}\r\n\t\t\t\t\r\n\t\t\t\titem = '<div class=\"dropdown\"><button class=\"dropbtn\">'+item+'</button><div class=\"dropdown-content\">'+subMenuContent+'</div></div>';\r\n\t\t\t}\r\n\t\t\telse{\r\n\t\t\t\titem = '<a href=\"'+menu[i].url+'\">'+menu[i].title+'</a>';\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\tmenuContent += item;\r\n\t\t}\r\n\t\t\r\n\t\t// Prepare the menu to be sent to the page\r\n\t\tmenuContent += '<a href=\"javascript:void(0);\" class=\"icon\" onclick=\"showMenu()\">&#9776;</a>';\r\n\t\t\r\n\t\t// Add the data to the html nodes on the main page\r\n\t\tdocument.getElementById('header').innerHTML = \"<h1>\"+header+\"</h1>\";\r\n\t\tdocument.getElementById('title').innerHTML = title;\r\n\t\tdocument.getElementById('text').innerHTML = body;\r\n\t\tdocument.getElementById('footer').innerHTML = footer;\r\n\t\tdocument.getElementById('topnav').innerHTML = menuContent;\r\n\t\t\r\n\t\t// Remove the loader \r\n\t\tsetTimeout(function(){document.getElementById(\"loader\").style.display = \"none\"}, 3000);\r\n\t\t\r\n\t\t// show the page\r\n\t\tsetTimeout(function(){document.getElementById(\"container\").style.display = \"block\"}, 3000);\r\n\r\n\t});\r\n}", "function runMenu() {\n inquirer.prompt([\n {\n name: 'menu',\n type: 'list',\n choices: [\n 'View Products for Sale',\n 'View Low Inventory',\n 'Add to Inventory',\n 'Add New Product',\n 'Exit'\n ],\n message: chalk.cyan('Select an option:')\n }\n ]).then(function(answers) {\n switch (answers.menu) {\n case 'View Products for Sale':\n getProducts(false);\n break;\n case 'View Low Inventory':\n getProducts(true);\n break;\n case 'Add to Inventory':\n addInventory();\n break;\n case 'Add New Product':\n addProduct();\n break;\n default:\n connection.end();\n }\n });\n}", "function showMenu() {\n opts.parent.append(element);\n element[0].style.display = '';\n\n return $q(function(resolve) {\n var position = calculateMenuPosition(element, opts);\n\n element.removeClass('md-leave');\n\n // Animate the menu scaling, and opacity [from its position origin (default == top-left)]\n // to normal scale.\n $animateCss(element, {\n addClass: 'md-active',\n from: animator.toCss(position),\n to: animator.toCss({transform: ''})\n })\n .start()\n .then(resolve);\n\n });\n }", "function showMenu() {\n opts.parent.append(element);\n element[0].style.display = '';\n\n return $q(function(resolve) {\n var position = calculateMenuPosition(element, opts);\n\n element.removeClass('md-leave');\n\n // Animate the menu scaling, and opacity [from its position origin (default == top-left)]\n // to normal scale.\n $animateCss(element, {\n addClass: 'md-active',\n from: animator.toCss(position),\n to: animator.toCss({transform: ''})\n })\n .start()\n .then(resolve);\n\n });\n }", "function showMenu() {\n opts.parent.append(element);\n element[0].style.display = '';\n\n return $q(function(resolve) {\n var position = calculateMenuPosition(element, opts);\n\n element.removeClass('md-leave');\n\n // Animate the menu scaling, and opacity [from its position origin (default == top-left)]\n // to normal scale.\n $animateCss(element, {\n addClass: 'md-active',\n from: animator.toCss(position),\n to: animator.toCss({transform: ''})\n })\n .start()\n .then(resolve);\n\n });\n }", "initMenu() {\n this.on('menu-selected', event => {\n // Focus on search bar if in most popular tab (labeled All)\n if (event.choice === 'most-popular') {\n this.focusSearchBar();\n }\n\n this.currentlySelected = event.choice;\n }, this);\n\n // call init menu from sdk\n initNavbar(this.menu);\n }", "function menu() {\n inquirer\n .prompt({\n name: \"menuOptions\",\n type: \"list\",\n message: \"What would you like to do?\",\n choices: [\"View Products\", \"View Low Inventory\", \"Add Inventory\", \"Add New Product\"]\n })\n .then(function(answer) {\n // based on their answer, run appropriate function\n if (answer.menuOptions === \"View Products\") {\n viewProducts();\n }\n else if (answer.menuOptions === \"View Low Inventory\") {\n viewLowInventory();\n }\n else if (answer.menuOptions === \"Add Inventory\") {\n addInventory();\n }\n else if (answer.menuOptions === \"Add New Product\") {\n addNewProduct();\n }\n else {\n connection.end();\n }\n });\n}", "function ShowMainMenu() {\n console.log(\"Main Menu\");\n \n clearMemory();\n \n Button1.style.display = \"inline\";\n Button2.style.display = \"inline\";\n Button3.style.display = \"inline\";\n Button4.style.display = \"inline\";\n //Set Button Text\n Button1.text = \"Bible\";\n Button2.text = \"Bible Plan\";\n Button3.text = \"Daily Verse\";\n Button4.text = \"Random\";\n \n MainMenuinstance.style.display = \"inline\";\n MainMenu = true;\n}", "function setMenu(menuBar){\n Menu.setApplicationMenu(Menu.buildFromTemplate(menuBar));\n}", "function displayListMenu() {\n $.get('js/templates/listChooserMenu.html', function (source) {\n var template = Handlebars.compile(source);\n var templateData = {\n items: arrayObj,\n save: false,\n remove: true\n };\n $(savedList).append(template(templateData));\n }, 'html')\n}", "show() {\n console.log('show called');\n const menu = this.shadowRoot.getElementById('menu');\n menu.show();\n }", "function RenderMenu()\n{\n var menu = \"\";//Initialise var\n //Build html output based on page items list.\n menu += '<div class=\"show-for-small\">';\n menu += '<form><label>Choose an article:<select id=\"micromenu\">';\n //Small menu loop\n for (var i = 0; i < PagesList.length; i++)\n {\n if (PagesList[i][1] == curPage)\n {\n menu += '<option value=\"' + PagesList[i][1] + '\" selected>';\n }\n else\n {\n menu += '<option value=\"' + PagesList[i][1] + '\">';\n }\n menu += PagesList[i][1];\n menu += '</option>';\n }\n menu += '</select></label>';\n menu += '</form></div>';\n menu += '<ul class=\"side-nav hide-for-small\">';\n //Large menu loop\n for (var ii = 0; ii < PagesList.length; ii++)\n {\n if (PagesList[ii][1] == curPage)\n {\n menu += '<li class=\"active\">';\n }\n else\n {\n menu += '<li>';\n }\n menu += '<a onClick=\"SetPage(\\'' + PagesList[ii][1] + '\\')\">';\n menu += PagesList[ii][1];\n menu += '</a>';\n menu += '</li>';\n }\n menu += '</ul>';\n return menu;\n}", "function showMainMenu(){\n console.log(\"Welcome to Employ-E-Manager\");\n\n inquirer.prompt(\n {type: \"rawlist\",\n name: \"mainmenu_action\",\n message: \"Please selection one of the below actions to perform:\",\n choices: [\n \"Add data to Department/Role/Employee\",\n \"View Department/Role/Employee information\",\n \"Update Employee information\",\n \"Delete Department/Role/Employee\",\n \"Report - Total utilized budget by Department\",\n \"Exit\"\n ]\n }\n ).then(function(answer){\n switch (answer.mainmenu_action){\n case \"Add data to Department/Role/Employee\":\n showAddMenu();\n break;\n \n case \"View Department/Role/Employee information\":\n showViewMenu();\n break;\n\n case \"Update Employee information\":\n showUpdateMenu();\n break;\n\n case \"Delete Department/Role/Employee\":\n showDeleteMenu();\n break;\n\n case \"Report - Total utilized budget by Department\":\n showReportMenu();\n break;\n\n case \"Exit\":\n exit();\n break;\n\n }\n }).catch(function(err){\n if (err){\n console.log(\"Main menu error: \" + err);\n }\n });\n}", "function scene::BuildMenu(folder)\r\n{\r\n local idx = 0;\r\n local fb = FileBrowser();\r\n local files = fb.BroseDir(folder,\"*.gbt,*.ml\");\r\n local uiman = system.GetUIMan();\r\n local scrsz = SIZE();\r\n local xpos = 2;\r\n local menuYpos = uiman.GetScreenGridY(0)-16; // font index(0-3)\r\n local slot = 0;\r\n \r\n\tmaps.resize(0);\r\n menubar.resize(0);\r\n \r\n if(files)\r\n {\r\n maps.resize(files);\r\n menubar.resize(files+4); // for top and remote\r\n }\r\n \r\n menubar[slot] = UiControl();\r\n menubar[slot].Create(0, xpos, menuYpos, xpos+70, menuYpos + 7);\r\n menubar[slot].SetFont(3);\r\n menubar[slot].SetText(\"Curent Folder: \" + folder, 0);\r\n menubar[slot].SetImage(\"topmenu.bmp\");\r\n menubar[slot].SetColor(0xCCCCCC, 0xCCCCCC);\r\n slot++;\r\n menuYpos -= 4;\r\n\r\n// makes button for remote downloading\r\n menuYpos-=3;\r\n menubar[slot] = UiControl();\r\n menubar[slot].Create(100, xpos, menuYpos, xpos+40, menuYpos+3);\r\n menubar[slot].SetFont(1);\r\n menubar[slot].SetText(\"> Remote Levels\", 0);\r\n menubar[slot].SetImage(\"topmenu.bmp\");\r\n menubar[slot].SetColor(0xCCCC00, 0xCCCCCC);\r\n slot++;\r\n \r\n \r\n // makes button for getting back to bspmaps\r\n menubar[slot] = UiControl();\r\n menubar[slot].Create(101, xpos+40, menuYpos, xpos+80, menuYpos+3);\r\n menubar[slot].SetFont(1);\r\n menubar[slot].SetText(\"> Local levels\", 0);\r\n menubar[slot].SetImage(\"topmenu.bmp\");\r\n menubar[slot].SetColor(0xCCCC00, 0xCCCCCC);\r\n slot++;\r\n \r\n // makes button for getting back to bspmaps\r\n menubar[slot] = UiControl();\r\n menubar[slot].Create(102, xpos+80, menuYpos, xpos+120, menuYpos+3);\r\n menubar[slot].SetFont(1);\r\n menubar[slot].SetText(\"> Master Server\", 0);\r\n menubar[slot].SetImage(\"topmenu.bmp\");\r\n menubar[slot].SetColor(0xCCCC00, 0xCCCCCC);\r\n slot++;\r\n \r\n menuYpos -= 4;\r\n\r\n \r\n for( idx=0; idx < files; idx+=1)\r\n {\r\n local lf = fb.GetAt(idx);\r\n if(lf == \"\") break;\r\n\r\n maps[idx] = folder+lf;\r\n\r\n menubar[slot] = UiControl();\r\n menubar[slot].Create(idx, xpos+(idx), menuYpos, xpos+(idx)+40, menuYpos+3);\r\n menubar[slot].SetFont(1);\r\n menubar[slot].SetText(lf, 0);\r\n menubar[slot].SetImage(\"freebut.bmp\");\r\n menubar[slot].SetColor(0xCCCC44, 0xCCCCCC);\r\n\r\n menuYpos-=3;\r\n slot++;\r\n }\r\n}", "function getMenu() {\n menuService.getMenu().then(function (resp) {\n $rootScope.menu = resp;\n $rootScope.states = {};\n $rootScope.states.activeItem = resp[0].id;\n });\n }", "function installMenu() {\n wkof.Menu.insert_script_link({\n name: script_name,\n submenu: \"Settings\",\n title: script_name,\n on_click: openSettings,\n });\n }", "function showMenu(){\n loadData();\n console.log(\"\\n***********************\");\n console.log(\"1.Nhap du lieu contact:\");\n console.log(\"2.Sua du lieu contact: \");\n console.log(\"3.Xoa contact\");\n console.log(\"4.Tim kiem contact\");\n console.log(\"5.Hien thi danh sach sdt\");\n var num = readLineSync.question('nhap lua chon: ');\n switch(num){\n case '1':\n addContact();\n showMenu();\n break;\n case '2':\n editContact();\n showMenu();\n break;\n case '3':\n deleteContact();\n showMenu();\n break;\n case '4':\n findContact();\n showMenu();\n break;\n case '5':\n show()\n showMenu();\n break;\n default:\n showMenu();\n break;\n }\n}", "function openNewGameMenu () {\n document.getElementById('menu-background').style.display = 'block';\n document.getElementById('menu-content').style.display = 'block';\n}", "function menuItem(id, def) {\n var client, dirty = true, icon, openMark, textElement, m = control(\"menu\", id, core.mkDefinition({\n style: {\n position: \"\",\n padding: \"2px 9px 2px 9px\",\n color: sys.color.windowtitle,\n },\n setText: function (text) {\n if (!textElement)\n this.appendChild(textElement = document.createTextNode(text));\n else textElement.textContent = text;\n },\n setIcon: function (src) {\n if (src) {\n if (!icon) {\n this.appendChild(icon = core.mkTag(\"img\"));\n icon.style.merge({\n width: \"16px\",\n height: \"16px\",\n float: \"left\",\n padding: \"0 5px 0 0\",\n filter: \"drop-shadow(rgb(255, 255, 255) 0px 0px 1px)\",\n });\n } else\n icon.style.display = \"\";\n icon.src = src;\n } else if (icon) icon.style.display = \"none\";\n },\n showMoreMark: function () {\n if (!openMark) {\n this.appendChild(openMark = core.mkTag(\"div\"));\n openMark.style.merge({\n float: \"right\",\n padding: \"0 0 0 5px\",\n });\n openMark.appendChild(document.createTextNode(\"\\u25B6\"));\n } else openMark.style.display = \"\";\n },\n hideMoreMark: function () {\n if (openMark)\n openMark.style.display = \"none\";\n },\n popup: function () {\n if (this.parentControl._type == \"menu\")\n this.parentControl.popup();\n if (client && client._visible)\n return;\n if (!client) {\n client = control(\"menuClient\", id + \"_client\", {\n style: {\n background: sys.color.client,\n border: \"1px solid \" + sys.color.frame,\n fontFamily: \"Arial\",\n fontSize: \"14px\",\n zIndex: 9999,\n },\n _zLayer: 9,\n });\n core.getDesktop().appendChild(client);\n }\n var bounds = this.getBoundingClientRect();\n if (this.parentControl._type == \"menu\")\n client.merge({\n top: bounds.top,\n left: bounds.left + bounds.width,\n });\n else\n client.merge({\n top: bounds.top + bounds.height,\n left: bounds.left,\n });\n while (client.lastChild)\n client.removeChild(client.lastChild);\n for (i in this.items) {\n var m = this.items[i];\n m.application = this.application;\n m.parentControl = this;\n if (m.items)\n m.showMoreMark();\n client.appendChild(m);\n }\n core.menu.setCurrent(this);\n client.show();\n },\n close: function (all) {\n if (client)\n client.hide();\n if (core.menu.isCurrent(this))\n core.menu.setCurrent(null);\n if (all && this.parentControl._type == \"menu\")\n this.parentControl.close(all);\n },\n onmouseenter: function () {\n this.style.backgroundColor = sys.color.frame;\n this.style.color = sys.color.framecontrast;\n },\n onmouseleave: function () {\n this.style.backgroundColor = \"\";\n this.style.color = sys.color.windowtitle;\n },\n onclick: function () {\n if (this.items)\n core.menu.showMenu(this);\n else if (this.onClick)\n this.onClick.apply(this, arguments);\n }\n }, def));\n return m;\n }", "function install_menu() {\n let config = {\n name: script_id,\n submenu: 'Settings',\n title: script_title,\n on_click: open_settings\n };\n wkof.Menu.insert_script_link(config);\n }", "function tl_start() {\n $('#futureman_face, #menu-open').css('display', 'inherit');\n $('.menu-open').css('visibility', 'inherit');\n }", "function onOpen() {\n setDefaults();\n loadMenu(userProp.getProperty(g_debug_key));\n}", "function loadMenu(dest,type){\n// dest Aff = affluenze Com = composizione Scr = scrutinio\n// type 0 = regionali 1 = camera 2 = senato\n name = dest;\n tipo = type;\n \tif (name == 'Aff'){\n\t\tloadStato();\t\n\t}else{\n\t\tloadData();\n\t}\n}", "function renderMenu() {\n const tab = document.getElementById('tab');\n tab.textContent = '';\n\n const title = document.createElement('h1');\n title.textContent = 'WENDY\\'S BURGER';\n\n tab.appendChild(title);\n tab.appendChild(createMenu());\n}", "function startatLoad(){\r\n\tloadNavbar(function(){\r\n\t\tsetSelectMenuesValues(function(){\r\n\t\t\t\tgetXMLData(function(){\r\n\t\t\t\t});\r\n\t\t\t});\r\n\t\t});\r\n}", "function toMenu() {\n\tclearScreen();\n\tviewPlayScreen();\n}" ]
[ "0.8329624", "0.7425933", "0.7410055", "0.71553236", "0.69857335", "0.6864795", "0.68341106", "0.67985797", "0.6754066", "0.67217326", "0.67153203", "0.6648224", "0.66250205", "0.6605713", "0.660352", "0.65815604", "0.65397507", "0.6533818", "0.65158355", "0.65039533", "0.64976215", "0.6490367", "0.6489627", "0.64643806", "0.64306164", "0.64046335", "0.6403162", "0.64018464", "0.638041", "0.6370477", "0.6358445", "0.63575447", "0.6340833", "0.6310268", "0.63048303", "0.6304152", "0.6300764", "0.6299271", "0.6291466", "0.6289817", "0.6289351", "0.6274291", "0.6272753", "0.62660277", "0.62658155", "0.6264074", "0.624241", "0.6225103", "0.6222915", "0.6221905", "0.62085605", "0.62055457", "0.6202823", "0.6201077", "0.6184611", "0.6170128", "0.6167586", "0.6166013", "0.6165154", "0.61651045", "0.6160797", "0.614294", "0.614266", "0.6142036", "0.6141432", "0.6135039", "0.61325496", "0.613154", "0.6129511", "0.61200047", "0.6111017", "0.6107994", "0.61006534", "0.6095391", "0.60873574", "0.6084903", "0.60805225", "0.6076646", "0.6076646", "0.6076646", "0.6075023", "0.60742795", "0.60742646", "0.60546654", "0.6054579", "0.6053048", "0.6043855", "0.60305125", "0.6029516", "0.60285723", "0.6028426", "0.60239476", "0.6021927", "0.6018099", "0.601707", "0.6015396", "0.60106796", "0.60102886", "0.6006821", "0.6005398", "0.6003899" ]
0.0
-1
Checks whether a menu item meets the filter criteria and should be displayed to the user.
function meetsDietaryRequirements(mi) { gluteninput = document.getElementById("glutencheckbox"); vegetarianinput = document.getElementById("vegetariancheckbox"); veganinput = document.getElementById("vegancheckbox"); if (!gluteninput.checked || (gluteninput.checked === true & mi.dataset.glutenfree === "true")) { if (!vegetarianinput.checked || (vegetarianinput.checked === true & mi.dataset.vegetarian === "true")) { if (!veganinput.checked || (veganinput.checked === true & mi.dataset.vegan === "true")) { return true; } } } return false; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function searchMenu(){\n let filter = document.getElementById(\"menu-search-bar\").value;\n filter = filter.trim().toLowerCase();\n for(item of menuItems){\n if(item.name.toLowerCase().indexOf(filter) >=0 || item.courseType.toLowerCase().indexOf(filter) >=0){\n document.getElementById(\"item-\" + item.id).style.display = \"\";\n }\n else {\n document.getElementById(\"item-\" + item.id).style.display = \"none\";\n }\n }\n\n}", "function checkMenu(){\n var locationItem = $location.search().ss;\n var locationSection = $location.search().s;\n var item = _.findWhere(service.parts.items[locationSection], {name: locationItem });\n\n if(!item){\n $location.replace();\n service.flags.active.section = null;\n service.flags.active.item = null;\n $location.search(\"s\", null);\n $location.search(\"ss\", null);\n }\n }", "[symbols.itemMatchesState](item, state) {\n const base = super[symbols.itemMatchesState] ?\n super[symbols.itemMatchesState](item, state) :\n true;\n if (!base) {\n return false;\n }\n const text = this[symbols.getItemText](item).toLowerCase();\n const filter = state.filter && state.filter.toLowerCase();\n return !filter ?\n true :\n !text ?\n false :\n text.includes(filter);\n }", "function filtername() {\n\n var input, filter, displayMenuItems, gluteninput, vegetarianinput, veganinput;\n\n input = document.getElementById(\"mysearchbox\");\n filter = input.value.toUpperCase();\n displayMenuItems = document.getElementsByClassName(\"menuitem\");\n\n //if there is no input on search bar, keep all menu items hidden.\n if (filter.length === 0) {\n const elementsToHide = document.getElementsByClassName(\"collapse show\");\n for (var i = 0; i < elementsToHide.length; i++) {\n elementsToHide[i].classList.remove(\"show\");\n }\n //else, when there is input, show the menu.\n } else {\n const elementsToShow = document.getElementsByClassName(\"collapse\");\n for (var i = 0; i < elementsToShow.length; i++) {\n elementsToShow[i].classList.add(\"show\");\n }\n }\n\n //goes through all childnodes of each menu item, and displays the items that meet the search and category criteria.\n for (var i = 0; i < displayMenuItems.length; i++) {\n const mi = displayMenuItems[i];\n console.log(mi.dataset.glutenfree);\n for (var j = 0; j < mi.childNodes.length; j++) {\n const node = mi.childNodes[j];\n if (node.className === \"bold\") {\n if(node.innerHTML.toUpperCase().indexOf(filter) > -1) {\n if (meetsDietaryRequirements(mi)) {\n mi.style.display = \"\";\n } else {\n mi.style.display = \"none\";\n }\n\n } else {\n mi.style.display = \"none\";\n }\n }\n }\n }\n}", "function checkMenuItem(text, leading) {\n const item = component.getAllByText(text, { hidden: true });\n expect(item.length).to.equal(2);\n if (leading) {\n // Means item is in first menu\n expect(isHidden(item[0])).to.equal(false, \"item is in menu\");\n expect(isHidden(item[1])).to.equal(true, \"item should be hidden\");\n } else {\n // Means item is in end menu\n expect(isHidden(item[0])).to.equal(true, \"item should be hidden\");\n expect(isHidden(item[1])).to.equal(false, \"item is in menu\");\n }\n }", "function myFunction() {\n var input, filter, ul, li, a, i;\n input = document.getElementById(\"mySearch\");\n filter = input.value.toUpperCase();\n ul = document.getElementById(\"myMenu\");\n li = ul.getElementsByTagName(\"li\");\n for (i = 0; i < li.length; i++) {\n a = li[i].getElementsByTagName(\"a\")[0];\n if (!(a.innerHTML.toUpperCase().indexOf(filter) > -1) && filter==\"\")\n {\n li[i].style.display = \"none\";\n }else\n {\n li[i].style.display = \"block\";\n }\n }\n}", "function filterItems(e){\n\t//convert text to lowercase\n\tvar text = e.target.value.toLowerCase();\n\t//get li's\n\tvar items = itemList.getElementsByTagName('li');\n\t//Convert HTML collection to an array\n\tArray.from(items).forEach(function(item){\n\t\tvar itemName = item.firstChild.textContent;\n\t\t// console.log(itemName); //check if we get the item names\n\t\tif(itemName.toLowerCase().indexOf(text) != -1){//check if the search is equal to the item(matching) -1 if not match\n\t\t\titem.style.display = 'block'; //shows the search item(s)\n\t\t} else{\n\t\t\titem.style.display = 'none'; //if not match, remove display\n\t\t}\n\n\t});\n}", "haveToShowAdditionalFilters() {\n const {filterType} = this.state;\n if (filterType === null) {\n return false;\n }\n const additionalFilters = this.getAdditionalFilters();\n return (additionalFilters !== null);\n }", "function SideBarMenuFilter(pagename, user) {\n const OrganizationView = [\n {\n key: 1,\n text: \"Organizations\",\n link: \"/organizations\",\n icon: \"building\",\n component: \"Item\",\n },\n {\n key: 2,\n text: \"All Events\",\n link: \"/adminevents\",\n icon: \"calendar\",\n component: \"Item\",\n },\n ];\n\n const EventsView = [\n {\n key: 1,\n text: \"All Events\",\n link: \"/adminevents\",\n icon: \"calendar\",\n component: \"Item\",\n },\n ];\n\n const Event = [\n {\n key: 3,\n text: \"Event\",\n link: \"/event\",\n icon: \"arrow\",\n component: \"Item\",\n },\n {\n key: 4,\n text: \"Information\",\n link: \"/event-info\",\n icon: \"info\",\n component: \"ItemSmall\",\n },\n {\n key: 5,\n text: \"Conferences\",\n link: \"/event-conferences\",\n icon: \"book\",\n component: \"ItemSmall\",\n },\n {\n key: 6,\n text: \"Speakers\",\n link: \"/event-speakers\",\n icon: \"microphone\",\n component: \"ItemSmall\",\n },\n\n {\n key: 7,\n text: \"Associates\",\n link: \"/event-associates\",\n icon: \"organization\",\n component: \"ItemSmall\",\n },\n {\n key: 8,\n text: \"Organizers\",\n link: \"/event\",\n icon: \"collaborators\",\n component: \"ItemSmall\",\n },\n {\n key: 9,\n text: \"Diffusion\",\n link: \"/event-diffusion\",\n icon: \"envelope\",\n component: \"Item\",\n },\n {\n key: 10,\n text: \"Template 1\",\n link: \"/template-one\",\n icon: \"envelope\",\n component: \"ItemSmall\",\n },\n {\n key: 11,\n text: \"Template 2\",\n link: \"/template-two\",\n icon: \"envelope\",\n component: \"ItemSmall\",\n },\n ];\n\n let MainBtns;\n if (user == \"admin\") {\n MainBtns = OrganizationView;\n } else {\n MainBtns = EventsView;\n }\n\n const currentEvent = MainBtns.concat(Event);\n\n if (pagename === \"eventPages\") {\n return currentEvent;\n } else {\n return MainBtns;\n }\n}", "function filterItems(e) {\n let filterValue = e.target.value.toUpperCase();\n\n // iterate of every exist items\n items.forEach(item => {\n if (item.textContent.toUpperCase().indexOf(filterValue) > -1) {\n item.parentElement.style.display = \"\";\n } else {\n item.parentElement.style.display = \"none\";\n }\n });\n}", "function isEditMenuItemValid(){\r\n return(EMenuItemNameField.isValid() && EMenuItemDescField.isValid() && EMenuItemValidFromField.isValid() && EMenuItemValidToField.isValid() && EMenuItemPriceField.isValid() && EMenuItemTypePerField.isValid());\r\n }", "filterMatchingItems(item) {\n if (this.state.shelf_life === 'All' && this.state.type === 'All') {\n return true;\n } else if (this.state.shelf_life === 'All' && this.state.type === item.type) {\n return true;\n } else if (this.state.shelf_life === item.shelf_life && this.state.type === \"All\") {\n return true;\n } else if (this.state.shelf_life === item.shelf_life && this.state.type === item.type) {\n return true;\n } else {\n return false;\n }\n\n }", "function filtertopics(clickedMenuFilter)\n\t\t{\t\n\t\t\t$(\".menu-list-and-description .menu-description\").hide();\t\t//hides all topics data\n\t\t\t$(\".\"+clickedMenuFilter).show();\t//shows topics data related to clicked menu, based on 'data-filter' attribute which has same class used to recognize filter.\n\t\t}", "function filter(item) {\n for (var columnId in columnFilters) {\n if (columnId !== undefined && columnFilters[columnId] !== \"\") {\n\n // 0 - string\n var tip = 0;\n\n if (columnId == 1) {\n tip = 2;\n }\n\n var c = grid.getColumns()[grid.getColumnIndex(columnId)];\n if (item[c.field] == undefined) {\n return false;\n }\n else if (tip == 0) {\n if (!item[c.field].toLowerCase().contains(columnFilters[columnId].toLowerCase())) {\n return false;\n }\n } else if (tip == 2) {\n if (item[c.field] != columnFilters[columnId].toDecimal()) {\n return false;\n }\n }\n }\n }\n return true;\n }", "function filter(item) {\n for (var columnId in columnFilters) {\n if (columnId !== undefined && columnFilters[columnId] !== \"\") {\n\n // 0 - string\n var tip = 2;\n\n if (columnId == 1) {\n tip = 0;\n }\n\n var c = grid.getColumns()[grid.getColumnIndex(columnId)];\n if (item[c.field] == undefined) {\n return false;\n }\n else if (tip == 0) {\n if (!item[c.field].toLowerCase().contains(columnFilters[columnId].toLowerCase())) {\n return false;\n }\n } else if (tip == 2) {\n if (item[c.field] != columnFilters[columnId].toDecimal()) {\n return false;\n }\n }\n }\n }\n return true;\n }", "function hideOrShowItems(itemType, classToRemove, classToAdd) {\n\n for (var i = 0; i < itemsToFilter.length; i++) {\n var currentItem = itemsToFilter[i];\n\n //THIS LOGIC WILL NEED CHANGING HERE ON A PER FILTER BASIS (DON'T WORRY ABOUT IT TOO MUCH - GOING TO SETUP OWN MIN & MAX PROPS PER EACH ELEMENT IN REACT)\n //SO HOPEFULL CN COMPARED DIRECTLY ON A NUMBER VALUE (IF IT's A STRING CPNVERT WITH Number(numberString) method)\n if (currentItem.getAttribute(\"data-type\") === itemType && clickedItem.name === currentItem.textContent.substr(8, 3)) {\n removeClass(currentItem.parentElement.parentElement, classToRemove);\n addClass(currentItem.parentElement.parentElement, classToAdd);\n }\n\n //console.log(currentItem);\n\n //Allow all filters to be de-selected (for now at least and figure out how they all will work in conjunction and weather or not to restrict to at least one\n //if only one filter is selected i.e. set the currently checked last one to disabled until another selection is made then re-enable)\n //keep the warning message as a generic one for if any combination doesnt return any results)\n if (es0.checked === false && es1.checked === false && es2.checked === false && es3.checked === false && es4.checked === false && es5.checked === false && es6.checked === false) {\n\n msg.innerHTML = 'Sorry, none of your selected options are available at this time';\n msg.style.display = 'block';\n } else if (es0.checked === true || es1.checked === true || es2.checked === true || es3.checked === true || es4.checked === true || es5.checked === true || es6.checked === true) {\n msg.style.display = 'none';\n }\n }\n}", "function isDisplayingActionLinkForRow(transaction, filter ){\n\tvar status = false;\n\tif(!transaction.reversed && !transaction.refunded && transaction.statusCode == \"0\"){\n\t\tvar filterVls = filter.split(':');\n\t\t\n\t\tfor (var index = 0; index < filterVls.length; index++) {\n\t\t \n\t\t if(transaction.type == filterVls[index]){\n\t\t\t\tstatus = true;\n\t\t\t\tbreak;\n\t\t } \n\t\t \n\t\t}\n\t\t\n\t}\n\treturn status;\n}", "check() {\n // neither end is a bar which isn't in a collapsed group? then hide\n if ((!this.renderedFromProtein.expanded || (this.renderedFromProtein.inCollapsedGroup())) &&\n (this.renderedToProtein ? (!this.renderedToProtein.expanded || this.renderedToProtein.inCollapsedGroup()) : false)) {\n this.hide();\n return false;\n }\n\n // either end manually hidden? then hide\n if (this.renderedFromProtein.participant.hidden === true ||\n (this.renderedToProtein && this.renderedToProtein.participant.hidden === true)) {\n this.hide();\n return false;\n }\n\n // no crosslinks passed filter? then hide\n if (this.crosslink.filteredMatches_pp.length > 0) {\n this.show();\n return true;\n } else {\n this.hide();\n return false;\n }\n }", "function canAnyMenuItemsCheck(items) {\r\n return items.some(function (item) {\r\n if (item.canCheck) {\r\n return true;\r\n }\r\n // If the item is a section, check if any of the items in the section can check.\r\n if (item.sectionProps && item.sectionProps.items.some(function (submenuItem) { return submenuItem.canCheck === true; })) {\r\n return true;\r\n }\r\n return false;\r\n });\r\n}", "function filterItem (){\n let filter = valorfilter();\n estructuraFilter = \"\";\n if (filter == \"Prime\"){\n for (propiedad of carrito) {\n if (propiedad.premium) imprimirItemFilter(propiedad);\n }\n noItenCarrito();\n } else if (filter == \"Todos\") {\n estructuraPrincipalCarrito();\n } \n}", "function preFilter(li) {\n let ID = idFromLi(li);\n let name = fullNameFromLi(li);\n\n log(\"Pre-filtering \" + name + ' [' + ID + ']');\n\n if (opt_hidehosp && isInHosp(li)) {\n log('***** preFilter: in hospital! (' + name + + ' [' + ID + '])');\n return true;\n }\n if (opt_hidefedded && isFedded(li)) {\n log('***** preFilter: fedded! (' + name + + ' [' + ID + '])');\n return true;\n }\n if (opt_hidefallen && isFallen(li)) {\n log('***** preFilter: fallen! (' + name + + ' [' + ID + '])');\n return true;\n }\n if (opt_hidetravel && isTravelling(li)) {\n log('***** preFilter: travelling! (' + name + + ' [' + ID + '])');\n return true;\n }\n\n return false;\n }", "function hasPermission (menuList, route) {\n return menuList.some(item => {\n return route.meta.title === item.name\n })\n}", "_canItemBeSelected(item) {\n return item.disabled === false && item.templateApplied !== true;\n }", "function isShowing(itemID) {\n\t\t\n\tlet item = items[itemID];\n\tif (item == null)\n\t\treturn false;\n\t\n\tvar layerVisible;\n\n\tif (maps.length == 1 ) {\n\t\tlayerVisible = showingMap;\n\t} else {\n\t\tlayerVisible = maps[locations[item.currLocID].layer].visible;\t\n\t}\n\tvar shapeActive = shapes[item.id].active;\n\t\t\n\t\n\tif (attachFoodToLayers) {\n\t\t\n\t\t// visiblity is now coupled to map layers showing.\t\t\t\t\n\t\tif (layerVisible || showInactiveLayers) {\t\t\n\t\t\tif (shapeActive || showInactiveItems) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\t\n\t} else {\n\t\t// Previous rules apply\n\t\tif (shapeActive || showInactiveItems) \n\t\t\treturn true;\t\t\n\t}\n\t\t\n\treturn false;\n}", "get shouldDisplayParams() {\n let params = this.args.item?.params || [];\n\n return params.some((p) => p.description || p.name.includes('.'));\n }", "function canShow (item, session) {\n return session.isGroupIncluded(item.acls.show);\n }", "function filterHandler() {\n var selectedVal = filterOptions.value;\n\n if (selectedVal === \"0\") {\n render(contacts);\n } else {\n render(filterByCity(selectedVal));\n }\n}", "function canAnyMenuItemsCheck(items) {\n return items.some(function (item) {\n if (item.canCheck) {\n return true;\n }\n // If the item is a section, check if any of the items in the section can check.\n if (item.sectionProps && item.sectionProps.items.some(function (submenuItem) { return submenuItem.canCheck === true; })) {\n return true;\n }\n return false;\n });\n}", "function canAnyMenuItemsCheck(items) {\n return items.some(function (item) {\n if (item.canCheck) {\n return true;\n }\n // If the item is a section, check if any of the items in the section can check.\n if (item.sectionProps && item.sectionProps.items.some(function (submenuItem) { return submenuItem.canCheck === true; })) {\n return true;\n }\n return false;\n });\n}", "function canAnyMenuItemsCheck(items) {\n return items.some(function (item) {\n if (item.canCheck) {\n return true;\n }\n // If the item is a section, check if any of the items in the section can check.\n if (item.sectionProps && item.sectionProps.items.some(function (submenuItem) { return submenuItem.canCheck === true; })) {\n return true;\n }\n return false;\n });\n}", "function isAddMenuItemValid(){\r\n return(MenuItemNameField.isValid() && MenuItemDescField.isValid() && MenuItemValidFromField.isValid() && MenuItemPriceField.isValid() && MenuItemTypePerField.isValid());\r\n }", "showItem(extension) {\n if (this.search.length < 1) {\n return true;\n }\n\n let key = this.search.toLowerCase();\n let name = extension.name.toLowerCase();\n return name.match(key) !== null;\n }", "function canUse(item) {\n var path = (0, _kolmafia.myPath)();\n\n if (path !== \"Nuclear Autumn\") {\n if ((0, _templateString.$items)(_templateObject2 || (_templateObject2 = _taggedTemplateLiteral([\"Shrieking Weasel holo-record, Power-Guy 2000 holo-record, Lucky Strikes holo-record, EMD holo-record, Superdrifter holo-record, The Pigs holo-record, Drunk Uncles holo-record\"]))).includes(item)) {\n return false;\n }\n }\n\n if (path === \"G-Lover\") {\n if (!item.name.toLowerCase().includes(\"g\")) return false;\n }\n\n if (path === \"Bees Hate You\") {\n if (item.name.toLowerCase().includes(\"b\")) return false;\n }\n\n return true;\n}", "function shouldDisplayFlag(flagType, shelfType, flag, flags, attr, variant) {\n if (!shelfType) {\n return true;\n } else {\n //special case: If the item-level out of stock state is not triggered then\n // filter out any out of stock flags.\n if (shelfType && flags[flag] === 'out-of-stock' && !outOfStock(variant, attr)) {\n return false;\n //special case: do not show 'Not Available at this time' on shelf if walmart.com\n //is not the seller (pcpSellerId == 0)\n } else if (shelfType && flag === 'Not Available at this time' && parseInt(attr.pcpSellerId, 10) !== 0) {\n return false;\n } else {\n return shelfFlags.indexOf(flag) !== -1;\n }\n }\n}", "function checkFiltered() {\n if (state.highlight.length > 0 || state.red || state.green) {\n filtered = true;\n }\n else {\n filtered = false;\n }\n }", "function ProcessItemMenu()\r\n{\r\n if (Control.Query(\"Back\")) {return {ChangeState:\"X\"};}\r\n ItemMenu.Process();\r\n if (Control.Query(\"Forward\")) { // Use an item\r\n var depleted = UseItem(ItemMenu.ChoiceNum());\r\n\tif (depleted) {return {ChangeState:\"X\"};}\r\n }\r\n}", "isEgeResultOptionVisible_(option) {\n const egeSubjects = this.searchParams.egeSubjects;\n return egeSubjects.some(subjectId => option.name == subjectId);\n }", "function filterMenus(){\n\n var restosList = $(\"select option:selected.restos\");\n var menusTypeList = $(\"select option:selected.menus\");\n var offerType = $('input[name=offer-type]:checked').val();\n var currentNutriScore = $(\"#nutrimenu-score\").val();\n\n const nutriScoresArray = [\n {\"txt\": \"-\", \"val\": 0},\n {\"txt\": \"E\", \"val\": 1},\n {\"txt\": \"D-\", \"val\": 2},\n {\"txt\": \"D\", \"val\": 3},\n {\"txt\": \"D+\", \"val\": 4},\n {\"txt\": \"C-\", \"val\": 5},\n {\"txt\": \"C\", \"val\": 6},\n {\"txt\": \"C+\", \"val\": 7},\n {\"txt\": \"B-\", \"val\": 8},\n {\"txt\": \"B\", \"val\": 9},\n {\"txt\": \"B+\", \"val\": 10},\n {\"txt\": \"A-\", \"val\": 11},\n {\"txt\": \"A\", \"val\": 12},\n {\"txt\": \"A+\", \"val\": 13}\n ]\n\n // Browse the menus list (<tr> -> class=\"menuPage), show the selected options and hide the unselected ones\n $(\"#menuTable tr.menuPage\").each(function (){\n\n var menuLine = $(this);\n\n // By default, the menu line is shown\n menuLine.show();\n\n // Filter by restaurant\n if(restosList.length > 0) {\n\n let found = false;\n restosList.each(function () {\n\n // Test if menu page contains restaurants IDs => test if menuLine is shown\n //if (menuLine.hasClass($(this).val())) {\n if (menuLine.attr('data-restoid') === $(this).val()){\n found = true;\n return false;\n }\n });\n // If a restaurant is not selected, it is not shown in the menu page\n if (!found) {\n menuLine.hide();\n }\n }\n\n // Filter by menu type\n if(menusTypeList.length > 0) {\n\n let found = false;\n menusTypeList.each(function () {\n\n // Test if menu page contains menu types => test if menuLine is shown\n if (menuLine.hasClass($(this).val())) {\n found = true;\n }\n\n });\n // If a type of menu is not selected, it is not shown in the menu page\n if (!found) {\n menuLine.hide();\n }\n }\n\n // Hide if not lunch or dinner\n if(!menuLine.hasClass(offerType)){\n menuLine.hide();\n }\n\n // Hide if lower than selected nutriScore\n let nsValue = Number(menuLine.attr('data-ns-score'));\n\n if (nsValue < nutriScoresArray[currentNutriScore].val) {\n menuLine.hide();\n }\n\n });\n\n $(\".nutriscore-value\").text(nutriScoresArray[currentNutriScore].txt);\n\n}", "isFiltered(key) {\n const item = this._.get(key);\n return item ? item.filtered : false;\n }", "function setFilterAction(){\n\t$(\".data-filter\").keyup(function(){\n\t\tvar options=$(\"#\"+$(this).data(\"filter\") + \" option\");\n\t\tvar filterValue=$(this).val().toLowerCase();\n\t\toptions.each(function(){\n\t\t\tif($(this).text().toLowerCase().includes(filterValue)) $(this).show();\n\t\t\telse $(this).hide();\n\t\t})\n\t});\n}", "filteredCheck({ filteredItems, localFilter }) {\n // Determine if the dataset is filtered or not\n let isFiltered = false\n if (!localFilter) {\n // If filter criteria is falsey\n isFiltered = false\n } else if (looseEqual(localFilter, []) || looseEqual(localFilter, {})) {\n // If filter criteria is an empty array or object\n isFiltered = false\n } else if (localFilter) {\n // If filter criteria is truthy\n isFiltered = true\n }\n if (isFiltered) {\n this.$emit(EVENT_NAME_FILTERED, filteredItems, filteredItems.length)\n }\n this.isFiltered = isFiltered\n }", "filterOption(option, filter) {\n\n if (option.value === null) {\n // only show placeholder when not searching\n return filter === '';\n }\n\n const user = this.getAppUser(option.value);\n\n filter = filter.toLowerCase();\n\n return user.value === null ||\n user.email && user.email.toLowerCase().indexOf(filter) === 0 ||\n user.firstName && user.firstName.toLowerCase().indexOf(filter) === 0 ||\n user.lastName && user.lastName.toLowerCase().indexOf(filter) === 0 ||\n user.screenName && user.screenName.toLowerCase().indexOf(filter) === 0;\n }", "function filterUser(li, ci) {\n debug('Filtering ' + ci.name + ' Rank: ' + ci.numeric_rank + ' State: ' + ci.state + ' Desc: ' + ci.description);\n if (opt_showcaymans && ci.state != 'Traveling') {\n debug('Filtered - Caymans only, but either not returning or not Caymans');\n debug('State = ' + ci.state);\n return true;\n }\n\n let isHosped = isInHosp(li);\n let infed = isFedded(li);\n let fallen = isFallen(li);\n let travelling = isTravelling(li);\n if (isHosped || infed || travelling) {\n log('Hosp: ' + isHosped + ' Fedded: ' + infed + ' IsTravelling: ' + travelling);\n log('**** Shouldn`t be here? *****');\n }\n\n switch (ci.state) {\n case 'Hospital':\n if (opt_hidehosp) {\n if (isHosped) log('**** Shouldn`t be here? *****');\n debug('***** Filtered - in hosp.');\n return true;\n }\n break;\n case 'Federal':\n if (opt_hidefedded) {\n if (infed) log('**** Shouldn`t be here? *****');\n debug('***** Filtered - fedded.');\n return true;\n }\n break;\n case 'Fallen':\n if (opt_hidefallen) {\n if (infed) log('**** Shouldn`t be here? *****');\n debug('***** Filtered - fallen.');\n return true;\n }\n break;\n case 'Abroad':\n case 'Traveling':\n if (opt_hidetravel) {\n if (travelling) log('**** Shouldn`t be here? *****');\n debug('***** Filtered - traveling.');\n return true;\n }\n if (opt_showcaymans) {\n if (ci.description.indexOf('Cayman') != -1) {\n if (ci.description.indexOf('Returning') != -1) {\n debug('******Returning from Caymans! Not filtered!');\n return false;\n }\n }\n debug('Filtered - caymans only, but either not returning or not Caymans');\n return true;\n }\n break;\n default:\n return false;\n }\n return false;\n }", "function filterFunction() {\n var input, filter, a, i;\n input = document.getElementById(\"myInput\");\n filter = input.value.toUpperCase();\n div = document.getElementById(\"dropDownList\");\n a = div.getElementsByTagName(\"li\");\n for (i = 0; i < a.length; i++) {\n if (a[i].innerHTML.toUpperCase().indexOf(filter) > -1) {\n a[i].style.display = \"\";\n } else {\n a[i].style.display = \"none\";\n }\n }\n}", "updateMenuItemsDisplay () {\n const pg = this.page\n if (!pg) {\n // initial page load, header elements not yet attached but menu items\n // would already be hidden/displayed as appropriate.\n return\n }\n if (!this.user.authed) {\n Doc.hide(pg.noteMenuEntry, pg.walletsMenuEntry, pg.marketsMenuEntry, pg.profileMenuEntry)\n return\n }\n Doc.show(pg.noteMenuEntry, pg.walletsMenuEntry, pg.profileMenuEntry)\n if (Object.keys(this.user.exchanges).length > 0) {\n Doc.show(pg.marketsMenuEntry)\n } else {\n Doc.hide(pg.marketsMenuEntry)\n }\n }", "function verifyItem(item, stock, filters) {\n const subcategories = subCategoriesOf(item.category);\n // Simple checks\n if (item.priceinclvat < filters.priceMin\n || item.priceinclvat > filters.priceMax\n || item.kosher < filters.kosher\n || item.organic < filters.organic\n ) {\n return false;\n }\n if (item instanceof Drink) {\n // Additional simple checks for Drinks\n if (item.alcoholstrength < filters.drink.percentageMin\n || item.alcoholstrength > filters.drink.percentageMax) {\n return false;\n }\n }\n // Stock-related checks\n const availStock = stock.getStock(item.id);\n if (availStock < filters.stockMin\n || availStock > filters.stockMax\n || (filters.notToRefill && item.id in stock.toRefill)) {\n return false;\n }\n // Check that all required subcategories are present.\n if (filters\n .subCategories\n .some(cat => !subcategories.includes(cat))) {\n return false;\n }\n // Check that each search is located somewhere in name or category of item\n if (filters\n .searches\n .some(search =>\n !item.name.includes(search)\n && !item.name2.includes(search)\n && !item.category.includes(search))) {\n return false;\n }\n return true;\n}", "checkFiltered() {\n return (\n typeof this.state.group !== \"undefined\" ||\n typeof this.state.lifespan !== \"undefined\" ||\n typeof this.state.height !== \"undefined\" ||\n typeof this.state.sortParam !== \"undefined\" ||\n typeof this.state.searchParam !== \"undefined\"\n );\n }", "function doFilter() {\n for (var i = 0; i < items.length; i++) {\n // show all\n items[i].classList.remove('thumb--inactive');\n\n // combine filters\n // - only those items will be displayed who satisfy all filter criterias\n var visible = true;\n\n for (var j = 0; j < visibleItems.length; j++) {\n visible = visible && items[i].classList.contains(visibleItems[j]);\n }\n\n if (!visible) {\n items[i].classList.add('thumb--inactive');\n }\n }\n }", "validateCategoryListItems() {\n return this\n .waitForElementVisible('@categoryListItem', 10000, (res) => {\n if (res.value == true) {\n this\n .assert.visible('@categoryListItem');\n } else {\n this\n .assert.ok(false, '[INFO] - Something went wrong when validating category filter list items');\n }\n }, '[STEP] - Category filter list items should be displayed');\n }", "checkVitals() {\n if (this.getItemCount(items.AIR) <= 0 || this.getItemCount(items.FOOD) <= 0 || this.getItemCount(items.WATER) <= 0) {\n return false;\n } else {\n return true;\n }\n }", "function checkCriteria(modVal) {\n if(modVal === 'by_request') {\n $id_new_member_criteria_fieldset.show();\n } else {\n $id_new_member_criteria_fieldset.hide();\n }\n }", "function showMenu(type) {\n switch (type) {\n case 'beer':\n addBasicMenu();\n lastMenu = type;\n showParticularMenu(allBeveragesOfType(\"Öl\"));\n break;\n case 'wine':\n addBasicMenu();\n lastMenu = type;\n showParticularMenu(allBeveragesOfType(\"vin\"));\n break;\n case 'spirits':\n addBasicMenu();\n lastMenu = type;\n showParticularMenu(allBeveragesWithStrength(\"above\", 20));\n break;\n case 'alcoAbove':\n lastMenu = type;\n if (document.getElementById(\"alco_percent\") != null) {\n alcoPercent = document.getElementById(\"alco_percent\").value;\n }\n addBasicMenu();\n showParticularMenu(allBeveragesWithStrength(\"above\", alcoPercent));\n break;\n case 'alcoBelow':\n lastMenu = type;\n if (document.getElementById(\"alco_percent\") != null) {\n alcoPercent = document.getElementById(\"alco_percent\").value;\n }\n addBasicMenu();\n showParticularMenu(allBeveragesWithStrength(\"below\", alcoPercent));\n break;\n case 'tannin':\n addBasicMenu();\n lastMenu = type;\n showParticularMenu([]);\n break;\n case 'gluten':\n addBasicMenu();\n lastMenu = type;\n showParticularMenu([]);\n break;\n case 'rest':\n currentFiltering = \"rest\";\n showMenu(lastMenu);\n break;\n case 'cat':\n currentFiltering = \"cat\";\n showMenu(lastMenu);\n break;\n case 'back':\n currentFiltering = \"none\";\n showMenu(allMenuBeverages());\n break;\n default:\n addBasicMenu();\n lastMenu = type;\n showParticularMenu(allMenuBeverages());\n }\n}", "isChildItem($item) {\n return $item.classList.contains('menu-item-depth-1') || $item.classList.contains('menu-item-depth-2');\n }", "function hasItem(aComponent, item) {\n\tfor (var i=0; i< aComponent.options.length; i++) {\n\t if ( aComponent.options[i].value == item )\n return true; \n\t}\n\treturn false;\n}", "function searchTextMatchesItem() {\n var i, valid = false;\n if ($scope.searchText.length > 0) {\n for (i = 0; i < $scope.items.length; i++) {\n if ($scope.searchText.toLowerCase() === $scope.items[i].text.toLowerCase()) {\n $scope.selectedItem = $scope.items[i];\n $scope.searchText = $scope.comboText = $scope.selectedItem.text;\n valid = true;\n break;\n }\n }\n }\n return valid;\n }", "should_filter(message_args, severity) {\n let sev = this._sev_value(severity);\n for (let [key, filters] of Object.entries(this._filters)) {\n if (key >= sev) {\n for (let filter of filters) {\n if (filter(message_args)) {\n return true;\n }\n }\n }\n }\n return false;\n }", "function checksTheAppliedFilter(itemWine, itemWinery, itemLocation, inputValue) {\n\n\n let buttonName = document.querySelector('#name')\n let buttonWinery = document.querySelector('#winery')\n let buttonLocation = document.querySelector('#location')\n let buttonTotal = document.querySelector('#total')\n \n if (buttonName.checked == true) {\n\n return itemWine.includes(inputValue)\n\n } else if(buttonWinery.checked == true) {\n\n return itemWinery.includes(inputValue)\n\n }else if(buttonLocation.checked == true) {\n\n return itemLocation.includes(inputValue)\n\n } else if (buttonTotal.checked == true) {\n\n return itemWine.includes(inputValue) || \n itemWinery.includes(inputValue) || \n itemLocation.includes(inputValue)\n\n }else {\n\n return itemWine.includes(inputValue) || itemWinery.includes(inputValue) || itemLocation.includes(inputValue)\n }\n \n\n}", "function testMenuPostion( menu ){\n \n }", "displayUnreliableSuppressed() {\n // Don't display unreliable/suppressed unless the selected maternal health is one of the following values.\n if ([\"Maternal Mortality Rate\", \"Late Maternal Death Rate\"].includes(this.getMaternalHealthSelected())) {\n return true;\n }\n return false;\n }", "matchesFilter(filter) {\n let typeMatches = true;\n if (filter.type) {\n // Internal events are always shown\n typeMatches = this.messageType.slug === filter.type || this.messageType.internal;\n }\n\n let stateMatches = true;\n if (filter.state && !this.messageType.internal) {\n if ('fn' in filter.state && typeof filter.state.fn === 'function') {\n stateMatches = filter.state.fn(this);\n } else {\n stateMatches = this.state().slug === filter.state.slug;\n }\n }\n\n return typeMatches && stateMatches;\n }", "function onMenuItemClick(p_sType, p_aArgs, p_oValue) {\n if (p_oValue == \"startVM\") \t{ \n\t\tYAHOO.vnode.container.dialog1.show()\n\t\tYAHOO.vnode.container.dialog1.focus()\n }\n\telse if (p_oValue == \"terminateVM\") {\n\t\tYAHOO.vnode.container.dialog2.show()\n\t\tYAHOO.vnode.container.dialog2.focus()\n }\n else if (p_oValue == \"stateVM\") {\n YAHOO.vnode.container.dialog3.show()\n\t\tYAHOO.vnode.container.dialog3.focus()\n }\n else if (p_oValue == \"upTimeVM\") {\n YAHOO.vnode.container.dialog4.show()\n\t\tYAHOO.vnode.container.dialog4.focus()\n }\n else if (p_oValue == \"startVG\") {\n YAHOO.vnode.container.dialog5.show()\n\t\tYAHOO.vnode.container.dialog5.focus()\n }\n else if (p_oValue == \"stateVG\") {\n YAHOO.vnode.container.dialog6.show()\n\t\tYAHOO.vnode.container.dialog6.focus()\n }\n else if (p_oValue == \"terminateVG\") {\n YAHOO.vnode.container.dialog7.show()\n\t\tYAHOO.vnode.container.dialog7.focus()\n }\n else if (p_oValue == \"adminPanel\") {\n if (checkPermission()) {\n YAHOO.vnode.container.dialog8.show()\n\t \tYAHOO.vnode.container.dialog8.focus()\n }\n else {\n alert(\"User is not allowed\")\n }\n }\n}", "function showEnsFilters() {\t\r\n\r\n}", "function isTextItem(item) {\n return !item.isPinned && !item.weblink &&\n ( \"text\"==item.type || (\"redirect\"==item.type && item.actions && item.actions.go && item.actions.go.nextWindow) ||\n // if group is not undefined, its probably a pinned app\n (undefined==item.type && undefined==item.group && (!item.menuActions || item.menuActions.length<1) && /* !item.params && Dynamic playlists have params? */\n (!item.command || (item.command[0]!=\"browsejive\" && (item.command.length<2 || item.command[1]!=\"browsejive\")))));\n}", "function _isMenuThere(cmd) {\n return Menus.getMenuItem(editorContextMenu.id + \"-\" + cmd) ? true : false;\n }", "hasSuggestions() {\n return this.filteredAirports && Object.keys(this.filteredAirports).length > 1;\n }", "function filterTasks(e){\n console.log(\"Task filter...\")\n var searchFilter, listItem, txtValue;\n searchFilter = filter.value.toUpperCase();\n listItem = document.querySelectorAll('.collection-item');\n //looping through the list items, and hiding unmatching results\n listItem.forEach(function(element){\n txtValue = element.textContent || element.innerText;\n if(txtValue.toUpperCase().indexOf(searchFilter) > -1){\n element.style.display = \"\";\n }else{\n element.style.display = \"none\";\n }\n });\n}", "function activeHasMenu(menu) {\n var item = menu.items[menu.activeIndex];\n return !!(item && item.submenu);\n}", "_filterDropdownItems(value = null) {\n if (this.dropdown) {\n if (this.emit('before.dropdown.filter', this)) {\n Array.from(this.dropdown.children).filter(child => !child.classList.contains('empty-title')).forEach(child => {\n const childValue = child.dataset[this.options.searchOn];\n\n // Remove highlights\n if (this.options.highlightMatchesString) {\n child.textContent = child.textContent.replace(/<\\/?(mark\\s?(class=\"is\\-highlighted\")?)?>]*>?/gm, '');\n }\n\n // If value is found in dropdown\n if ((value && value.length)) {\n if (this.options.caseSensitive) {\n child.style.display = childValue.includes(value) ? 'block' : 'none';\n } else {\n child.style.display = childValue.toLowerCase().includes(value.toLowerCase()) ? 'block' : 'none';\n }\n\n if (this.options.highlightMatchesString) {\n child.innerHTML = this._highlightMatchesInString(child.innerHTML, value);\n }\n } else {\n child.style.display = 'block';\n }\n\n if (!this.options.allowDuplicates || (this._isSelect && !this._isMultiple)) {\n const hasValue = this.options.searchOn === 'value' ? this.hasValue(childValue) : this.hasText(childValue);\n\n child.style.display = hasValue ? 'none' : child.style.display;\n }\n });\n\n const hasActiveItems = Array.from(this.dropdown.children).filter(child => !child.classList.contains('empty-title')).some(child => child.style.display !== 'none');\n if (hasActiveItems) {\n this.dropdownEmptyOption.style.display = 'none';\n } else {\n this.dropdownEmptyOption.style.display = 'block';\n }\n\n this.emit('after.dropdown.filter', this);\n\n return hasActiveItems;\n }\n }\n\n return true;\n }", "hasProductsList() {\n this.searchResults.waitForDisplayed(3000);\n return this.searchResults.isDisplayed();\n }", "function hasProgramFilter() {\n var result = _.findWhere(vm.programs, {\n isChecked: true\n });\n return typeof result !== 'undefined';\n }", "function checkVisible() {\r\n var $items = ['registration', 'messages', 'sponsors'];\r\n $('.ipWidget').find('.myl-module-game').each(function(){\r\n var $name = $(this).attr('data-module-name');\r\n var $active = $(this).children('div').data('module-visible');\r\n\r\n if(($.inArray($name, $items) !== -1) && $active == 'no') {\r\n $(this).parent().css('display', 'none');\r\n }\r\n });\r\n }", "function checkOpts() {\n for (var i = 0; i < $scope.opts.length; i++) {\n if ($scope.opts[i].toLowerCase() == $scope.ua) {\n $element.show();\n return false;\n }\n }\n }", "isNotFiltered(deal) {\n const drinks = this.props.drinks\n const events = this.props.events\n const food = this.props.food\n const types = deal.types\n const day = this.props.day\n if (deal.types === undefined || deal.types === null) {\n return false\n }\n\n let validType = false\n if (drinks && types.includes(\"Drinks\")) {\n validType = true\n }\n\n if (food && types.includes(\"Food\")) {\n validType = true\n }\n\n if (events && types.includes(\"Events\")) {\n validType = true\n }\n\n // type isn't filtered and it's on the day users want to see\n return validType && (deal.days.includes(day) || day === \"Any\")\n }", "function checkDescription(item) {\n return item.description.toLowerCase().includes(searchTerm.toLowerCase()) // Make it case insensitive\n }", "function filterInput(){\n AllUsers = document.getElementById(\"users\").getElementsByTagName(\"option\");\n filterValue=filter.value.toUpperCase();\n for(i=0;i < AllUsers.length; i++){\n if(AllUsers[i].innerHTML.toUpperCase().indexOf(filterValue) > -1 ){\n AllUsers[i].style.display=\"\";\n }\n else{\n AllUsers[i].style.display=\"none\";\n }\n } \n}", "function handleApplyFilter() {\r\n getItems(\r\n brandNameInput.value.toLowerCase(),\r\n queryParamFormat(prodTypeInput.value)\r\n );\r\n spinner.style.display = \"flex\";\r\n noItemsPara.style.display = \"none\";\r\n row.innerHTML = \"\";\r\n filterAdded = true;\r\n // brandsWrapper.style.display = \"none\";\r\n // productTypesWrapper.style.display = \"none\";\r\n // handleAvailableBrands();\r\n // handleAvailableProducts();\r\n}", "function filterItems(category) {\n if (category === \"mk\") {\n $(\"li:has(.mk)\").toggleClass(\"hide\");\n }\n\n else if (category === \"ep\") {\n $(\"li:has(.ep)\").toggleClass(\"hide\");\n }\n\n else if (category === \"dhs\") {\n $(\"li:has(.dhs)\").toggleClass(\"hide\");\n }\n\n else if (category === \"dak\") {\n $(\"li:has(.dak)\").toggleClass(\"hide\");\n }\n\n else if (category === \"resort\") {\n $(\"li:has(.resort)\").toggleClass(\"hide\");\n }\n\n else if (category === \"rD\") {\n $(\"li:has(.rD)\").toggleClass(\"hide\");\n }\n\n else {}\n\n console.log(\"You should see items from the \" + classChosen + \" class\")\n \n realign();\n }", "function isFiltering() {\n var filtering = false;\n var columns = component.getColumns();\n _.each(columns, function (column) {\n if (!Utilities.isEmpty(column.filters[0].term)) {\n filtering = true;\n }\n });\n return filtering;\n }", "function searchForItem() {\n\tif (itemExists === true) {\n\t\tdocument.getElementById(\"Examine\").innerHTML = \"There is a(n) \" + item + \" here. Click the take item button or enter T or t to pick it up!\";\n\t}\n\n\telse {\n\t\tdocument.getElementById(\"Examine\").innerHTML = \"There are no items here.\";\n\t}\n}", "function employeeFilter() {\n inquirer\n .prompt(\n {\n name: 'action',\n type: 'list',\n message: 'What would you like to do?',\n choices: [\n 'View all Employees',\n 'View Employees by Manager',\n 'View Employee by Department',\n 'Go Back'\n ]\n }\n ).then(answer => {\n switch (answer.action) {\n case 'View all Employees':\n employeeSearch();\n break;\n\n case 'View Employees by Manager':\n filterByManager();\n break;\n\n case 'View Employee by Department':\n filterByDept();\n break;\n\n case 'Go Back':\n employeeOptions();\n break;\n }\n })\n}", "function InvAccFilter(listItems, filterOn, newFBFilterOn) {\n if(filterOn) {\n for(var i = 0; i < listItems.length; i++) {\n if(listItems[i].getAttribute('data-invAccepted') == 'false')\n ElemDyns.HideUnregOne(listItems[i]);\n }\n }\n else {\n for(var i = 0; i < listItems.length; i++) {\n if(listItems[i].getAttribute('data-invAccepted') == 'false')\n ElemDyns.ShowUnregOne(listItems[i]);\n }\n }\n }", "function isEditMenuValid(){\r\n return(EMenuNameField.isValid() && EMenuDescField.isValid() && EMStartDateField.isValid() && EMEndDateField.isValid());\r\n }", "function checkFilters()\n {\n vm.showAllTasks = !!angular.equals(vm.taskFiltersDefaults, vm.taskFilters);\n }", "function hasItem (item){\n\t\treturn true;\n}", "_canItemBeHovered(item) {\n const level = item.level;\n\n return item.disabled === false &&\n item.templateApplied !== true &&\n item.hidden !== true &&\n (level === 1 ||\n level > 1 &&\n this._isContainerOpened(level, item.parentElement.container) &&\n item.getBoundingClientRect().height > 0);\n }", "function check_if_filter(all_filter){\n if (document.querySelector('#' + all_filter + ' .close') == null) {\n nothing_filter(all_filter,false);\n }\n}", "function filterByGroup(tgt) {\n \n if (tgt.tagName != \"LI\") return;\n \n //color all choices grey, then uncolor the selected; done via class\n tgt.parentElement.childNodes.forEach(x => {\n (x === tgt || tgt.textContent === \"all\") ? x.classList.remove('disabledCustomChoice') : x.classList.add('disabledCustomChoice')\n });\n \n for (let i = 0, len = dropMenu.childElementCount; i < len; i++) {\n let compVal = dropMenu.children[i].getAttribute(\"title\").split(\",\")[0];\n //group the plans into generic groups\n switch (compVal) {\n case 'brush':\n case 'grass':\n case 'shrub':\n compVal = 'bushy';\n break;\n case 'berry':\n case 'veg':\n case 'herb':\n compVal = \"edible\";\n break;\n case 'flower':\n case 'groundcover':\n case 'vine':\n compVal = 'flowery';\n break; \n }\n //hide or display the menu\n if (tgt.textContent === compVal || tgt.textContent === \"all\") {\n dropMenu.children[i].style.display = \"block\";\n } else {\n dropMenu.children[i].style.display = \"none\";\n }\n }\n //letter shortcut menus are faded for all menus except \"all\"\n if (tgt.textContent != \"all\") {\n alphaMenu.style.opacity = \"0.1\";\n zetaMenu.style.opacity = \"0.1\";\n } else {\n alphaMenu.style.opacity = \"1\";\n zetaMenu.style.opacity = \"1\";\n }\n\n }", "function showJudge(itemElem,itemValue,isCreate){\n if(!isCreate){\n if(checkDDLFilter(itemValue)){\n if(checkSecondFilter(itemElem)){\n num++;\n if(itemElem.classList.contains(CL_COMPLETED)){\n completed++;\n }\n if(checkFirstFilter(itemElem)){\n console.log(3);\n showToDoItem(itemElem)\n filterArray.push(itemValue);\n }else{\n console.log(1);\n hideToDoItem(itemElem);\n }\n }else{\n console.log(2);\n hideToDoItem(itemElem);\n }\n }else{\n hideToDoItem(itemElem);\n }\n }else{\n if(checkDDLFilter(itemValue)){\n if(checkSecondFilter(itemElem)){\n num++;\n if(itemElem.classList.contains(CL_COMPLETED)){\n completed++;\n }\n if(checkFirstFilter(itemElem)){\n console.log(3);\n showToDoItem(itemElem)\n filterArray.push(itemValue);\n }else{\n console.log(1);\n itemElem.classList.add(CL_HIDDEN);\n }\n }else{\n console.log(2);\n itemElem.classList.add(CL_HIDDEN);\n }\n }else{\n itemElem.classList.add(CL_HIDDEN);\n }\n }\n }", "function youGotAnItem(itemName, itemAction) {\r\n if (inventory.includes(itemName) === true) {\r\n $(\".big-text\").hide().html('You already have that.').fadeIn(800);\r\n } else {\r\n // This may need refactor later with new setup.\r\n availableActions.pop();\r\n availableActions.push('<li>');\r\n availableActions.push(itemAction);\r\n availableActions.push('</li>');\r\n availableActions.push('</ul>');\r\n commandsFooter.innerHTML = availableActions.join(\" \");\r\n inventory.pop();\r\n inventory.push('<li>');\r\n inventory.push(itemName);\r\n inventory.push('</li>');\r\n inventory.push('</ul>');\r\n inventoryAside.innerHTML = inventory.join(\" \");\r\n }\r\n}", "function filterSpeciesMenu(inputText){\n console.log(\"filterSpeciesMenu\");\n currInputText = inputText;\n var filter = inputText.toUpperCase();\n \n /* this is ALL tree names, but treeNameDataDisplayed is \n what's currently displayed*/\n \n // we want to edit treeNameDisplayed and filter it to have just names\n // we want, then have d3 append and remove elems based on that.\n \n treeNameDataDisplayed = treeNameData.filter(function(treeName){\n /* only returns names that have the input's value as substring */\n return treeName.toUpperCase().indexOf(filter) > -1; \n });\n \n /* Checks if the name is in the list of tree names displayed */\n commonNamesDisplayedSet = new Set(treeNameDataDisplayed);\n updateSpeciesMenu(treeNameDataDisplayed);\n /* update ui with new tree name data */\n filterChange(TREE_DATA_STORE);\n}", "function filterFunction() {\r\n var input, filter, ul, li, a, i;\r\n input = document.getElementById(\"nearbyInput\");\r\n filter = input.value.toUpperCase();\r\n div = document.getElementById(\"dropListDiv\");\r\n a = div.getElementsByTagName(\"button\");\r\n for (i = 0; i < a.length; i++) {\r\n if (a[i].innerHTML.toUpperCase().indexOf(filter) > -1) {\r\n a[i].style.display = \"\";\r\n } else {\r\n a[i].style.display = \"none\";\r\n }\r\n }\r\n}", "function FilterItem(props) {\n let baseClasses = 'FilterItem';\n if (props.highlighted) baseClasses += ' highlighted';\n return (\n <div styleName={baseClasses} onClick={props.onClick}>\n <span styleName=\"left\">{props.name}</span>\n <span styleName=\"right\">{(props.name === 'Past challenges' || props.myFilter) ? '' : props.count}</span>\n </div>\n );\n}", "function isBlacklistedItem(item) {\n\t\tlogTrace('invoking isBlacklistedItem($)', item);\n\n\t\t// blacklisted for being a rerun\n\t\tif (hideReruns && (item.rerun === true)) { return true; }\n\n\t\tif (storedBlacklistedItems[item.type] === undefined) { return false; }\n\n\t\t// blacklisted by name\n\t\tif (matchTerms(item.name, item.type)) {\n\n\t\t\tlogTrace('blacklisted by name:', item.name);\n\t\t\treturn true;\n\t\t}\n\n\t\t// blacklisted by category\n\t\tif (matchTerms(item.category, 'categories')) {\n\n\t\t\tlogTrace('blacklisted by category:', item.category);\n\t\t\treturn true;\n\t\t}\n\n\t\t// blacklisted by tag\n\t\tconst tagsLength = item.tags.length;\n\t\tfor (let i = 0; i < tagsLength; i++) {\n\n\t\t\tif (matchTerms(item.tags[i].name, 'tags')) {\n\n\t\t\t\tlogTrace('blacklisted by tag:', item.tags[i].name);\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\n\t\t// blacklisted by title\n\t\tif (matchTerms(item.title, 'titles')) {\n\n\t\t\tlogTrace('blacklisted by title:', item.title);\n\t\t\treturn true;\n\t\t}\n\n\t\treturn false;\n\t}", "function filter(word) {\n if (items.length === 0) items = $('.dropdown-item');\n let length = items.length;\n let hidden = 0;\n for (let i = 0; i < length; i++) {\n let btnSticker = $(items.get(i));\n if (btnSticker.val().toUpperCase().includes(word.toUpperCase())) {\n btnSticker.show();\n } else {\n btnSticker.hide();\n hidden++;\n }\n }\n\n //If all items are hidden, show the empty view\n if (hidden === length) {\n $('#empty').show();\n } else {\n $('#empty').hide();\n }\n}", "menuContainsLink(menu, link)\n {\n for (let i in menu.items)\n {\n if (i === \"each\" || i === \"forEach\") continue;\n // noinspection JSUnfilteredForInLoop\n let itemParamObject = this.hash2Object(menu.items[i].link);\n let linkParamObject = this.hash2Object(link);\n let itemParamCount = 0;\n let matchCount = 0;\n // Parse through current item params\n for (let j in itemParamObject) {\n \tif (j === \"each\" || j === \"forEach\") continue;\n \titemParamCount++;\n \t// Parse through link params\n\t for (let k in linkParamObject) {\n\t if (k === \"each\" || k === \"forEach\") continue;\n // noinspection JSUnfilteredForInLoop\n\t if (j === k && itemParamObject[j] === linkParamObject[k]) {\n\t \tmatchCount++;\n\t }\n\t }\n }\n if (itemParamCount === matchCount) {\n // noinspection JSUnfilteredForInLoop\n return menu.items[i];\n }\n }\n \n return undefined;\n }", "function mainMenu(person, people, firstAndLastName, filteredByAge, filteredByHeight, filteredByOccupation, filteredByWeight, filteredByColor){\r\n /* Here we pass in the entire person object that we found in our search, as well as the entire original dataset of people. \r\n We need people in order to find descendants and other information that the user may want. */\r\n\r\n if(!person){\r\n alert(\"Could not find that individual.\");\r\n return app(people);\r\n }\r\n\r\n var displayOption = prompt(\"Found \" + person.firstName + \" \" + person.lastName + \" . Do you want to know their 'info', 'family', or 'descendants'? Type the option you want or 'restart' or 'quit'\");\r\n\r\n switch(displayOption){\r\n case \"info\":\r\n displayInfo(person, people, firstAndLastName, filteredByAge, filteredByHeight, filteredByOccupation, filteredByWeight, filteredByColor);\r\n break;\r\n case \"family\":\r\n displayFamily(people, person);\r\n break;\r\n case \"descendants\":\r\n findDescendants(person, people, firstAndLastName, filteredByAge, filteredByHeight, filteredByOccupation, filteredByWeight, filteredByColor);\r\n break;\r\n case \"restart\":\r\n app(people); \r\n break;\r\n case \"quit\":\r\n return; \r\n default:\r\n return mainMenu(person, people); \r\n }\r\n}", "function showSubMenu(){\n setSubMenu((privValue) =>{\n return !privValue;\n })\n }", "function checkNewMenu(generatedMenu, userConfiguredValues, dispatch) {\n const price = generatedMenu.reduce((sum, order) => sum + parseFloat(order.products[2]), 0);\n const kcal = generatedMenu.reduce((sum, order) => sum + parseFloat(order.products[1]), 0);\n\n if (kcal < userConfiguredValues.minCalories || kcal > userConfiguredValues.maxCalories || price > userConfiguredValues.maxPrice) {\n return dispatch(makeMenu(userConfiguredValues, generatedMenu));\n }\n\n dispatch(generate(generatedMenu));\n dispatch(errorHandle(''));\n return dispatch(summary(kcal.toFixed(), price.toFixed(2)));\n}", "function updateFilters(){\n\n if(document.getElementById(\"menu_wine\").getAttribute(\"data-status\") === \"active\"){\n getWines(\"filter\");\n }\n else if(document.getElementById(\"menu_beer\").getAttribute(\"data-status\") === \"active\"){\n getBeers(\"filter\");\n }\n else if(document.getElementById(\"menu_drinks\").getAttribute(\"data-status\") === \"active\"){\n getDrinks(\"filter\");\n }\n}", "function checkItem(a) {\n if (treasures[a] != null) {\n console.log(\"There's an item.\");\n return true;\n }\n else {\n console.log(\"There's not an item.\");\n return false;\n }\n}", "function commonFilter(e) {\r\n let filter = e.value.toUpperCase();\r\n\r\n for (let i = 0; i < li.length; i++) {\r\n if (e.name === \"footer_filter\") { // Footer filter by status\r\n if (filter === \"COMPLETED\" && !data[i].done) {\r\n li[i].style.display = \"none\";\r\n } else if (filter === \"ACTIVE\" && data[i].done) {\r\n li[i].style.display = \"none\";\r\n } else {\r\n li[i].style.display = \"\";\r\n }\r\n } else if (e.name === \"category_dropdown\") { // Category/type Dropdown filter\r\n let taskCategoryName = li[i].getElementsByClassName(\"task-category\")[0];\r\n let taskNameValue = taskCategoryName.textContent || taskCategoryName.innerText;\r\n if (taskNameValue.toUpperCase().indexOf(filter) > -1) {\r\n li[i].style.display = \"\";\r\n } else {\r\n li[i].style.display = \"none\";\r\n }\r\n } else { // Search textbox filter\r\n let taskNameTag = li[i].getElementsByTagName(\"h3\")[0];\r\n let txtValue = taskNameTag.textContent || taskNameTag.innerText;\r\n if (txtValue.toUpperCase().indexOf(filter) > -1) {\r\n li[i].style.display = \"\";\r\n } else {\r\n li[i].style.display = \"none\";\r\n }\r\n }\r\n }\r\n}" ]
[ "0.6546594", "0.6094133", "0.6062806", "0.59995455", "0.5962066", "0.59302044", "0.5921651", "0.5871642", "0.5846553", "0.5836322", "0.58336216", "0.5733845", "0.5650693", "0.56337166", "0.56326663", "0.5616193", "0.5612642", "0.5598078", "0.55913156", "0.55601597", "0.55453134", "0.5533292", "0.55297136", "0.55180746", "0.54995555", "0.5493488", "0.54902697", "0.5482104", "0.5482104", "0.5482104", "0.54816955", "0.5471991", "0.5441654", "0.5428656", "0.542059", "0.53920305", "0.5387958", "0.53810626", "0.5380502", "0.53717226", "0.5365954", "0.53639275", "0.53091323", "0.52998286", "0.5299505", "0.5299472", "0.5287569", "0.527997", "0.5267291", "0.52660894", "0.5255349", "0.524541", "0.5233904", "0.5233754", "0.52113473", "0.5209245", "0.5208952", "0.52082384", "0.51872647", "0.51785827", "0.5159656", "0.5134316", "0.51257586", "0.51248866", "0.51248586", "0.5120331", "0.51141036", "0.51119196", "0.5109422", "0.5101657", "0.509723", "0.50948757", "0.5092853", "0.5092749", "0.50887465", "0.5088498", "0.5087543", "0.50807935", "0.50763667", "0.5076094", "0.50694317", "0.5069329", "0.5068625", "0.50661165", "0.5060151", "0.5055104", "0.50520325", "0.50473154", "0.50416136", "0.50364316", "0.5036295", "0.50313103", "0.5026767", "0.49965054", "0.4992626", "0.49903652", "0.4985391", "0.4979021", "0.4976253", "0.49755755", "0.49740866" ]
0.0
-1
Filters the menu items based on the customers search and diet filters
function filtername() { var input, filter, displayMenuItems, gluteninput, vegetarianinput, veganinput; input = document.getElementById("mysearchbox"); filter = input.value.toUpperCase(); displayMenuItems = document.getElementsByClassName("menuitem"); //if there is no input on search bar, keep all menu items hidden. if (filter.length === 0) { const elementsToHide = document.getElementsByClassName("collapse show"); for (var i = 0; i < elementsToHide.length; i++) { elementsToHide[i].classList.remove("show"); } //else, when there is input, show the menu. } else { const elementsToShow = document.getElementsByClassName("collapse"); for (var i = 0; i < elementsToShow.length; i++) { elementsToShow[i].classList.add("show"); } } //goes through all childnodes of each menu item, and displays the items that meet the search and category criteria. for (var i = 0; i < displayMenuItems.length; i++) { const mi = displayMenuItems[i]; console.log(mi.dataset.glutenfree); for (var j = 0; j < mi.childNodes.length; j++) { const node = mi.childNodes[j]; if (node.className === "bold") { if(node.innerHTML.toUpperCase().indexOf(filter) > -1) { if (meetsDietaryRequirements(mi)) { mi.style.display = ""; } else { mi.style.display = "none"; } } else { mi.style.display = "none"; } } } } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function searchMenu(){\n let filter = document.getElementById(\"menu-search-bar\").value;\n filter = filter.trim().toLowerCase();\n for(item of menuItems){\n if(item.name.toLowerCase().indexOf(filter) >=0 || item.courseType.toLowerCase().indexOf(filter) >=0){\n document.getElementById(\"item-\" + item.id).style.display = \"\";\n }\n else {\n document.getElementById(\"item-\" + item.id).style.display = \"none\";\n }\n }\n\n}", "function SideBarMenuFilter(pagename, user) {\n const OrganizationView = [\n {\n key: 1,\n text: \"Organizations\",\n link: \"/organizations\",\n icon: \"building\",\n component: \"Item\",\n },\n {\n key: 2,\n text: \"All Events\",\n link: \"/adminevents\",\n icon: \"calendar\",\n component: \"Item\",\n },\n ];\n\n const EventsView = [\n {\n key: 1,\n text: \"All Events\",\n link: \"/adminevents\",\n icon: \"calendar\",\n component: \"Item\",\n },\n ];\n\n const Event = [\n {\n key: 3,\n text: \"Event\",\n link: \"/event\",\n icon: \"arrow\",\n component: \"Item\",\n },\n {\n key: 4,\n text: \"Information\",\n link: \"/event-info\",\n icon: \"info\",\n component: \"ItemSmall\",\n },\n {\n key: 5,\n text: \"Conferences\",\n link: \"/event-conferences\",\n icon: \"book\",\n component: \"ItemSmall\",\n },\n {\n key: 6,\n text: \"Speakers\",\n link: \"/event-speakers\",\n icon: \"microphone\",\n component: \"ItemSmall\",\n },\n\n {\n key: 7,\n text: \"Associates\",\n link: \"/event-associates\",\n icon: \"organization\",\n component: \"ItemSmall\",\n },\n {\n key: 8,\n text: \"Organizers\",\n link: \"/event\",\n icon: \"collaborators\",\n component: \"ItemSmall\",\n },\n {\n key: 9,\n text: \"Diffusion\",\n link: \"/event-diffusion\",\n icon: \"envelope\",\n component: \"Item\",\n },\n {\n key: 10,\n text: \"Template 1\",\n link: \"/template-one\",\n icon: \"envelope\",\n component: \"ItemSmall\",\n },\n {\n key: 11,\n text: \"Template 2\",\n link: \"/template-two\",\n icon: \"envelope\",\n component: \"ItemSmall\",\n },\n ];\n\n let MainBtns;\n if (user == \"admin\") {\n MainBtns = OrganizationView;\n } else {\n MainBtns = EventsView;\n }\n\n const currentEvent = MainBtns.concat(Event);\n\n if (pagename === \"eventPages\") {\n return currentEvent;\n } else {\n return MainBtns;\n }\n}", "filterRestaurants () {\n this.sendAction('filterInit', {\n price: this.get('price'),\n isOpen: this.get('isChecked')\n });\n }", "function filterHandler() {\n var selectedVal = filterOptions.value;\n\n if (selectedVal === \"0\") {\n render(contacts);\n } else {\n render(filterByCity(selectedVal));\n }\n}", "function searchingProducts(listToFilter) {\n\n if (searchValue.value) {\n listToFilter = listToFilter.filter(availProduct => {\n return availProduct.name.toLowerCase().includes(searchValue.value.toLowerCase());\n });\n }\n\n if (countryValue.options[countryValue.selectedIndex].value) {\n listToFilter = listToFilter.filter(availProduct => {\n return availProduct.shipsTo.map(selectOption => selectOption.toLowerCase()).includes(countryValue.options[countryValue.selectedIndex].value.toLowerCase());\n });\n } \n\n sortProducts(listToFilter);\n\n renderProducts(listToFilter);\n}", "function filterItems() {\nvar filter, room_classes, txtHeaderValue, txtDataValue;\n\tfilter = filter_table_input.value.toUpperCase();\n\troom_classes = [\"fs\", \"ad\", \"fc\", \"cas\", \"bd\", \"cc\", \"cbs\", \"bridge\", \"rc\", \"ras\", \"hg\", \"fat\", \"rbs\", \"lab\", \"fbt\", \"ab\", \"medlab\", \"cat\", \"ab2\", \"ref\", \"cbt\", \"bb\", \"nexus\", \"rat\", \"ib\", \"er\", \"rbt\"];\n\n\tfor (var i = 0; i < room_classes.length; i++) {\n\t\tvar selected_room = storage_table.getElementsByClassName(room_classes[i]);\n\t\ttxtHeaderValue = selected_room[0].innerText;\n\t\ttxtDataValue = selected_room[1].innerText;\n\t\tif (txtHeaderValue.toUpperCase().indexOf(filter) > -1 || txtDataValue.toUpperCase().indexOf(filter) > -1) {\n\t\t\tselected_room[0].style.display = \"\";\n\t\t\tselected_room[1].style.display = \"\";\n\t\t}\n\n\t\telse {\n\t\t\tselected_room[0].style.display = \"none\";\n\t\t\tselected_room[1].style.display = \"none\";\n\t\t}\n\t}\n}", "function commonFilter(e) {\r\n let filter = e.value.toUpperCase();\r\n\r\n for (let i = 0; i < li.length; i++) {\r\n if (e.name === \"footer_filter\") { // Footer filter by status\r\n if (filter === \"COMPLETED\" && !data[i].done) {\r\n li[i].style.display = \"none\";\r\n } else if (filter === \"ACTIVE\" && data[i].done) {\r\n li[i].style.display = \"none\";\r\n } else {\r\n li[i].style.display = \"\";\r\n }\r\n } else if (e.name === \"category_dropdown\") { // Category/type Dropdown filter\r\n let taskCategoryName = li[i].getElementsByClassName(\"task-category\")[0];\r\n let taskNameValue = taskCategoryName.textContent || taskCategoryName.innerText;\r\n if (taskNameValue.toUpperCase().indexOf(filter) > -1) {\r\n li[i].style.display = \"\";\r\n } else {\r\n li[i].style.display = \"none\";\r\n }\r\n } else { // Search textbox filter\r\n let taskNameTag = li[i].getElementsByTagName(\"h3\")[0];\r\n let txtValue = taskNameTag.textContent || taskNameTag.innerText;\r\n if (txtValue.toUpperCase().indexOf(filter) > -1) {\r\n li[i].style.display = \"\";\r\n } else {\r\n li[i].style.display = \"none\";\r\n }\r\n }\r\n }\r\n}", "function filterAccommodation() {\r\n let guests = noOfGuestsEl.text();\r\n let nights = noOfNightsEl.val();\r\n let filteredAccommodation = filterByGuests(accomData.accommodation, guests);\r\n filteredAccommodation = filterByNights(filteredAccommodation, nights);\r\n displayAccom(filteredAccommodation);\r\n}", "function filterItem (){\n let filter = valorfilter();\n estructuraFilter = \"\";\n if (filter == \"Prime\"){\n for (propiedad of carrito) {\n if (propiedad.premium) imprimirItemFilter(propiedad);\n }\n noItenCarrito();\n } else if (filter == \"Todos\") {\n estructuraPrincipalCarrito();\n } \n}", "function filterTypeSelection(e){\n if(e.target.value === ''){\n getInventory()\n } else {\n axios.get(`/inventory/search/dept?dept=${e.target.value}`)\n .then(res => setItems(res.data))\n .catch(err => alert(err))\n }\n }", "function filterItems(e) {\n let filterValue = e.target.value.toUpperCase();\n\n // iterate of every exist items\n items.forEach(item => {\n if (item.textContent.toUpperCase().indexOf(filterValue) > -1) {\n item.parentElement.style.display = \"\";\n } else {\n item.parentElement.style.display = \"none\";\n }\n });\n}", "function filterData(){\r\n // temporary variables\r\n var tempColl = [];\r\n var tempCat = [];\r\n // Fetching selected checkbox filter values for collection and categories\r\n $.each($(\"input[name='brands']:checked\"), function(){\r\n tempColl.push($(this).val());\r\n });\r\n\r\n $.each($(\"input[name='categories']:checked\"), function(){\r\n tempCat.push($(this).val());\r\n });\r\n // fetching selected filter value for color\r\n color = $(\"input[name='colors']:checked\").val();\r\n if (tempColl.length > 0) {\r\n coll = tempColl;\r\n }\r\n else{\r\n coll = \"All\";\r\n }\r\n if (tempCat.length > 0) {\r\n cat = tempCat;\r\n }\r\n else{\r\n cat = [\"All\"];\r\n }\r\n if (color == undefined) {\r\n color = [\"All\"];\r\n }\r\n // Fetch selected items only according to filter applied\r\n getItem(coll, cat, color, minprice, maxprice);\r\n }", "getFilteredItems(query){\r\n return this.source.filter((item) =>item[this.getOptionLabel].toLowerCase().startsWith(query.toLowerCase(), 0) && !item.invisible);\r\n }", "function applyFilter() {\n return { params: { filter: { tags: ['Menu'] } } };\n}", "function fillFilterBy() {\n if (typeof pageProductType != 'undefined') {\n if (pageProductType.length != 0) {\n var selectElement = document.getElementById(\"filterBy\");\n switch(pageProductType) {\n case 'Gloves':\n createOptions(selectElement, filterGloves);\n break;\n case 'Hats':\n createOptions(selectElement, filterHats);\n break;\n case 'Scarves':\n createOptions(selectElement, filterScarves);\n break;\n default:\n // do nothing\n break;\n }\n }\n }\n}", "function filterGlobal () {\n jq('#oppdragMainList').DataTable().search(\n \t\tjq('#oppdragMainList_filter').val()\n ).draw();\n }", "function Products({ children, filter }) {\n const [prevName,setPrevName] = useState('');\n const [prevType,setPrevType] = useState('all');\n\n let filterItem = {\n\n };\n\n let onFilterChange = () => {\n if (!filterItem.name) {\n if (prevName) {\n filterItem.name = prevName;\n }\n filterItem.name = '';\n\n }\n if (!filterItem.type) {\n if (prevType) {\n filterItem.type = prevType;\n }\n \n }\n\n filter(filterItem);\n }\n\n let filtertype = (filterType) => {\n // console.log('filterType', filterType);\n filterItem.type = filterType;\n setPrevType(filterType);\n return filterType;\n }\n\n let filtername = (filterName) => {\n // console.log('filterName', filterName);\n filterItem.name = filterName;\n setPrevName(filterName);\n return filterName;\n }\n\n return (\n <section id=\"store\" className=\"store py-5\">\n <div className=\"container\">\n <div className=\"row\">\n <div className=\"col-10 mx-auto col-sm-6 text-center\">\n <h1 className=\"text-capitalize\">our <strong className=\"banner-title \">store</strong></h1>\n </div>\n </div>\n <Menu filtertype={filtertype} filerChange={onFilterChange} />\n <Search filtername={filtername} filerChange={onFilterChange} />\n <div className=\"row\" id=\"store-items\">\n {children}\n </div>\n </div>\n </section>\n );\n}", "function filterItems(e){\n\t//convert text to lowercase\n\tvar text = e.target.value.toLowerCase();\n\t//get li's\n\tvar items = itemList.getElementsByTagName('li');\n\t//Convert HTML collection to an array\n\tArray.from(items).forEach(function(item){\n\t\tvar itemName = item.firstChild.textContent;\n\t\t// console.log(itemName); //check if we get the item names\n\t\tif(itemName.toLowerCase().indexOf(text) != -1){//check if the search is equal to the item(matching) -1 if not match\n\t\t\titem.style.display = 'block'; //shows the search item(s)\n\t\t} else{\n\t\t\titem.style.display = 'none'; //if not match, remove display\n\t\t}\n\n\t});\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 pwFilterProducts() {\n if($('#filter input[type=checkbox]').is(':checked')) {\n $('#filter').removeClass('has-selection').addClass('has-selection');\n } else {\n $('#filter').removeClass('has-selection');\n }\n pwBuildLayout();\n }", "function set_filters() {\n let filter = {\n post_type: 'auto-in-vendita',\n filters: {\n /* tipologia : $('input[name=\"condition\"]:checked').val(), */\n marca: brandInput.val(),\n modello: modelInput.val(),\n maxPrice: maxPriceInput.val(),\n km: kmInput.val(),\n anno: yearInput.val(),\n alimentazione: fuelInput.val(),\n cambio: transmissioninput.val(),\n novice: noviceInput.is(':checked') == true ? true : '',\n }\n }\n get_search_results_count(filter);\n }", "function doFilter() {\n for (var i = 0; i < items.length; i++) {\n // show all\n items[i].classList.remove('thumb--inactive');\n\n // combine filters\n // - only those items will be displayed who satisfy all filter criterias\n var visible = true;\n\n for (var j = 0; j < visibleItems.length; j++) {\n visible = visible && items[i].classList.contains(visibleItems[j]);\n }\n\n if (!visible) {\n items[i].classList.add('thumb--inactive');\n }\n }\n }", "function pwMenuInit() {\n // Initial setup:\n // - Populate filters\n // - Sense active filters\n // - Load data\n if(!settings.showfilter) { $('body').addClass('no-filter'); }\n if(settings.showshape) { $('body').addClass('with-shape'); }\n\n $('#category .items').append(pwPopulateFilter(categories));\n $('#volume .items').append(pwPopulateFilter(volumes));\n $('#type .items').append(pwPopulateFilter(types));\n $('#location .items').append(pwPopulateFilter(locations));\n $('#shape .items').append(pwPopulateFilter(shapes));\n\n $('#filter input:checkbox').checkbox({ 'empty': 'js/checkbox/empty.png' });\n $('#filter .items').jScrollPane();\n\n pwBuildItemDOM();\n\n var state = History.getState();\n var setfilters = state.hashedUrl.match(/setFilters/);\n if(setfilters == null) { pwGetCurrentSelection(); pwFilterProducts(); }\n pwSenseActiveFilters();\n\n // Event: Clicking a checkbox\n $('#filter input[type=\"checkbox\"]').click(function(){\n var cb = this;\n clearTimeout(pwCheckTimeout);\n pwCheckTimeout = setTimeout(function(){\n var ischecked = $(cb).prop('checked');\n\n // Main/subcat toggling\n if($(cb).hasClass('maincb')) {\n $(cb).closest('li').find('ul input').prop('checked', ischecked);\n }\n\n if($(cb).hasClass('subcb')) {\n var parentCat = $(cb).closest('ul').closest('li').find('.maincb');\n if(ischecked) {\n if(!$(cb).closest('ul').find('input[type=\"checkbox\"]').not(':checked').length) {\n parentCat.attr('checked', true);\n }\n } else {\n parentCat.attr('checked', false);\n }\n }\n\n // State handling\n var activeFilters = [];\n var i = 0;\n\n $('#filter input[type=\"checkbox\"]').each(function(){\n if($(this).is(':checked')) {\n var id = $(this).attr('data-id');\n if(id) {\n activeFilters[i] = id;\n i++;\n }\n }\n });\n\n var object = {\n filters: activeFilters,\n action: 'setfilter'\n };\n\n History.pushState(object, '', '?setFilters=' + object.filters.join());\n }, 20);\n });\n\n // Event: Menu header click\n $('#filter-header a').click(function(e){\n pwMenuToggle();\n e.preventDefault();\n });\n\n // Event: Go button\n $('#set-filter').click(function(e){\n if(!$(this).hasClass('inactive')) {\n pwFilterProducts();\n pwCloseSingleProduct();\n pwMenuToggle();\n }\n e.preventDefault();\n });\n\n // Event: Reset filter button\n $('#reset-filter').click(function(e){\n var object = { action: 'clearfilter' };\n History.pushState(object, '', '?clear');\n e.preventDefault();\n });\n\n // Event: Sub cat toggle arrow\n $('.subtoggle').on('click', function(e){\n $(this).closest('li').toggleClass('sub-open');\n $(this).closest('.items').jScrollPane();\n e.preventDefault();\n });\n\n // Event: Close single product\n $('#single-product .close-single').click(function(e){\n var object = {};\n object.action = 'closesingle';\n if(settings.useHistory)\n {\n \tHistory.pushState(object, '', '?');\n }\n else\n {\n \tpwCloseSingleProduct();\n }\n e.preventDefault();\n });\n\n // Back button in single product\n $('#single-product .back').click(function(e){\n\n var animateSpeed = 200;\n \n if(settings.useHistory){\n\t\tvar state = History.getState();\n\t }\n\t else\n\t {\n\t\tvar state = {};\n\t\tstate.data = {};\n\t\tstate.data.action = 'loadsingle';\n\t\tstate.data.id = currentItemID;\n\t }\n\t \n if(state.data.action === 'loadsingle') {\n $('#single-product .product').css({\n 'left' : 'auto'\n }).animate({\n 'right' : 20\n }, animateSpeed, function(){\n $('#single-product .product').animate({\n 'right' : -50,\n 'opacity' : 0\n }, animateSpeed, function(){\n var item = $(\"#\" + state.data.id);\n var prev = item.prev();\n if (!prev.length && item.parent().prev().length) {\n prev = item.parent().prev().children().last();\n } else if(!prev.length) {\n prev = $('#result .item').last();\n }\n if (prev.length) {\n var object = {\n id: prev.attr('id'),\n index: prev.attr('data-index'),\n action: 'loadsingle'\n };\n if(settings.useHistory)\n\t\t {\n\t\t \tHistory.pushState(object, '', '?package=' + object.id);\n\t\t }\n\t\t else\n\t\t {\n\t\t \tcurrentItemID = object.id;\n\t\t \tpwOpenSingleProduct(object.index);\n\t\t }\n \n }\n $('#single-product .product').css({\n 'right' : 20\n }).animate({\n 'right' : 0,\n 'opacity' : 1\n }, animateSpeed);\n });\n });\n }\n e.preventDefault();\n });\n\n // Forward button in single product\n $('#single-product .forward').click(function(e){\n\n var animateSpeed = 200;\n \n if(settings.useHistory){\n\t\tvar state = History.getState();\n\t }\n\t else\n\t {\n\t\tvar state = {};\n\t\tstate.data = {};\n\t\tstate.data.action = 'loadsingle';\n\t\tstate.data.id = currentItemID;\n\t }\n\n if(state.data.action === 'loadsingle') {\n $('#single-product .product').css({\n 'right' : 'auto'\n }).animate({\n 'left' : 20\n }, animateSpeed, function(){\n $('#single-product .product').animate({\n 'left' : -50,\n 'opacity' : 0\n }, animateSpeed, function(){\n var item = $(\"#\" + state.data.id);\n var next = item.next();\n if (!next.length && item.parent().next().length) {\n next = item.parent().next().children(\":first-child\");\n } else if(!next.length) {\n next = $('#result .item').first();\n }\n if (next.length) {\n var object = {\n id: next.attr('id'),\n index: next.attr('data-index'),\n action: 'loadsingle'\n };\n if(settings.useHistory)\n\t\t {\n\t\t \tHistory.pushState(object, '', '?package=' + object.id);\n\t\t }\n\t\t else\n\t\t {\n\t\t \tcurrentItemID = object.id;\n\t\t \tpwOpenSingleProduct(object.index);\n\t\t }\n }\n $('#single-product .product').css({\n 'left' : 20\n }).animate({\n 'left' : 0,\n 'opacity' : 1\n }, animateSpeed);\n });\n });\n }\n e.preventDefault();\n });\n }", "function updateCustomerFilter(event){\n\tcurrentSearchFilter = {\"filter\": $(event.target).val()};\n\tfilterCustomers();\n}", "function filteredCustomers(){\n var text = vm.customerFilterText.toLowerCase();\n customerState.customerFilterText = text;\n return text === '' ?\n vm.customers :\n vm.customers.filter(function (c){\n return c.firstName.toLowerCase().indexOf(text) == 0 ||\n c.lastName.toLowerCase().indexOf(text) == 0 ;\n })\n }", "function searchApplicant( event ){\n event.preventDefault();\n let selectItems = $skillsFilter.selectedOptions;\n let busca;\n \n Array.prototype.forEach.call( selectItems, function(item){\n arrFilter.push(item.value);\n });\n\n if ($salaryFilter.value != '' && arrFilter.length != 0){\n busca = searchBoth();\n }\n\n if ($salaryFilter.value == '' && arrFilter.length != 0)\n busca = searchForSkills();\n\n if ($salaryFilter.value != '' && arrFilter.length == 0)\n busca = searchForSalary();\n\n if ($salaryFilter.value == '' && arrFilter.length == 0 )\n busca = candidates;\n\n showInModal(busca);\n $modal.setAttribute('class', \"modal collapse show\");\n $salaryFilter.value = \"\";\n arrFilter = [];\n }", "function filtersInit () {\n\t\t jq('#tblAdrItemLines').DataTable().search(\n\t\t \t\tjq('#tblAdrItemLines_filter').val()\n\t\t ).draw();\n\t\t \n\t\t }", "function filterContacts() {\n\t\tupdateEmployeesHtml(makeEmployeesHTML(employeesData));\n\t}", "function search () {\n saveState();\n self.filtered = self.gridController.rawItems.filter(self.filterFunc);\n self.gridController.doFilter();\n }", "function setFilterAction(){\n\t$(\".data-filter\").keyup(function(){\n\t\tvar options=$(\"#\"+$(this).data(\"filter\") + \" option\");\n\t\tvar filterValue=$(this).val().toLowerCase();\n\t\toptions.each(function(){\n\t\t\tif($(this).text().toLowerCase().includes(filterValue)) $(this).show();\n\t\t\telse $(this).hide();\n\t\t})\n\t});\n}", "function displayAllFilters(bwFilters) {\n if (bwFilters.length) {\n $.each(bwFilters, function (i, value) {\n if (value.length) {\n if(bwPage == \"eventList\" || bwPage == \"eventscalendar\") {\n // only construct filter listings on these two views.\n var navId = value[0].substr(0,value[0].indexOf(\"-\"));\n var navName = $(\"#\" + navId + \" .bwMenuTitle\").text().trim();\n refreshFilterList(i,navName);\n }\n // make our selected navigational items bold on every page\n $.each(value, function (j, val) {\n $(\"#\" + val).css(\"font-weight\",\"bold\").attr(\"aria-selected\",\"true\");\n });\n }\n });\n }\n}", "function chategoryChange (){\n buttons.forEach(function(button){\n button.addEventListener('click', function(e){\n e.preventDefault()\n const filter = e.target.dataset.filter\n \n box.forEach((item)=>{\n if(filter == \"all\") {\n item.style.display = 'block'\n } else {\n if(item.classList.contains(filter)){\n item.style.display = \"block\"\n } else {\n item.style.display = \"none\"\n }\n }\n })\n })\n })\n}", "function updateFilters(){\n\n if(document.getElementById(\"menu_wine\").getAttribute(\"data-status\") === \"active\"){\n getWines(\"filter\");\n }\n else if(document.getElementById(\"menu_beer\").getAttribute(\"data-status\") === \"active\"){\n getBeers(\"filter\");\n }\n else if(document.getElementById(\"menu_drinks\").getAttribute(\"data-status\") === \"active\"){\n getDrinks(\"filter\");\n }\n}", "function handleApplyFilter() {\r\n getItems(\r\n brandNameInput.value.toLowerCase(),\r\n queryParamFormat(prodTypeInput.value)\r\n );\r\n spinner.style.display = \"flex\";\r\n noItemsPara.style.display = \"none\";\r\n row.innerHTML = \"\";\r\n filterAdded = true;\r\n // brandsWrapper.style.display = \"none\";\r\n // productTypesWrapper.style.display = \"none\";\r\n // handleAvailableBrands();\r\n // handleAvailableProducts();\r\n}", "function filterMenus(){\n\n var restosList = $(\"select option:selected.restos\");\n var menusTypeList = $(\"select option:selected.menus\");\n var offerType = $('input[name=offer-type]:checked').val();\n var currentNutriScore = $(\"#nutrimenu-score\").val();\n\n const nutriScoresArray = [\n {\"txt\": \"-\", \"val\": 0},\n {\"txt\": \"E\", \"val\": 1},\n {\"txt\": \"D-\", \"val\": 2},\n {\"txt\": \"D\", \"val\": 3},\n {\"txt\": \"D+\", \"val\": 4},\n {\"txt\": \"C-\", \"val\": 5},\n {\"txt\": \"C\", \"val\": 6},\n {\"txt\": \"C+\", \"val\": 7},\n {\"txt\": \"B-\", \"val\": 8},\n {\"txt\": \"B\", \"val\": 9},\n {\"txt\": \"B+\", \"val\": 10},\n {\"txt\": \"A-\", \"val\": 11},\n {\"txt\": \"A\", \"val\": 12},\n {\"txt\": \"A+\", \"val\": 13}\n ]\n\n // Browse the menus list (<tr> -> class=\"menuPage), show the selected options and hide the unselected ones\n $(\"#menuTable tr.menuPage\").each(function (){\n\n var menuLine = $(this);\n\n // By default, the menu line is shown\n menuLine.show();\n\n // Filter by restaurant\n if(restosList.length > 0) {\n\n let found = false;\n restosList.each(function () {\n\n // Test if menu page contains restaurants IDs => test if menuLine is shown\n //if (menuLine.hasClass($(this).val())) {\n if (menuLine.attr('data-restoid') === $(this).val()){\n found = true;\n return false;\n }\n });\n // If a restaurant is not selected, it is not shown in the menu page\n if (!found) {\n menuLine.hide();\n }\n }\n\n // Filter by menu type\n if(menusTypeList.length > 0) {\n\n let found = false;\n menusTypeList.each(function () {\n\n // Test if menu page contains menu types => test if menuLine is shown\n if (menuLine.hasClass($(this).val())) {\n found = true;\n }\n\n });\n // If a type of menu is not selected, it is not shown in the menu page\n if (!found) {\n menuLine.hide();\n }\n }\n\n // Hide if not lunch or dinner\n if(!menuLine.hasClass(offerType)){\n menuLine.hide();\n }\n\n // Hide if lower than selected nutriScore\n let nsValue = Number(menuLine.attr('data-ns-score'));\n\n if (nsValue < nutriScoresArray[currentNutriScore].val) {\n menuLine.hide();\n }\n\n });\n\n $(\".nutriscore-value\").text(nutriScoresArray[currentNutriScore].txt);\n\n}", "_filter(value) {\n //convert text to lower case\n const filterValue = value.toLowerCase();\n //get matching products\n return this.products.filter(option => option.toLowerCase().includes(filterValue));\n }", "function filterCandidates(){\n\t\t//updates district filter\n\t\tif (districtSelector.property(\"selectedIndex\") > 0) {\n\t\t\tcurrentDistrict = areas[districtSelector.property(\"selectedIndex\")-1];\n\t\t}\n\t\t//updates name and candidate number filter\n\t\tvar searchValue = searchInput.property(\"value\").toLowerCase();\n\t\tvar searchArray = searchValue.split(\" \");\n\n\t\t//Let the filtering begin!\n\t\tcandidates\n\t\t\t.attr(\"display\", function(d) {\n\t\t\t\t//district filter\n\t\t\t\tif (currentDistrict === ALLDISTRICTS) return \"inline\";\n\t\t\t\telse if (currentDistrict && d.district !== currentDistrict) return \"none\";\n\n\t\t\t\t//party filter\n\t\t\t\tif(!partyVisibility[d.party] || !partyVisibility[d.segment]) return \"none\";\n\n\t\t\t\t//if something in the search box then also filter with that\n\t\t\t\tif (searchValue) {\n\t\t\t\t\tfor (var i = 0; i < searchArray.length; i++) {\n\t\t\t\t\t\tif (d.name.toLowerCase().indexOf(searchArray[i].trim()) < 0){\n\t\t\t\t\t\t\treturn \"none\";\n\t\t\t\t\t\t} \n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t})\n\t}", "function Filter ({categoryFilter, setCategoryFilter, setNameFilter, dateSort, setDateSort, setExpenseList, nameFilter}) {\n\n //Functions\n\n //Set category filter state to event value\n\n const categoryFilterHandler = (e) => {\n setCategoryFilter(e.target.value)\n }\n\n //Set name filter state to event value\n\n const nameFilterSet = (e) => {\n setNameFilter(e.target.value);\n }\n\n //Reset function that sets the state of category and name filter to empty\n\n const resetHandler = () => {\n setCategoryFilter(\"\");\n setNameFilter(\"\");\n setDateSort(\"\");\n }\n\n //Set date sort state to event value\n\n const dateSortHandler = (e) => {\n setDateSort(e.target.value);\n }\n\n //Clear expense list when clear button clicked\n\n const clearHandler = () => {\n setExpenseList([]);\n } \n\n //Main - Returns HTML\n\n return(\n <div class=\"container\">\n\n <hr />\n\n <div class=\"d-flex flex-row justify-content-start\">\n\n <div class=\"row\">\n\n {/*Name to filter Container*/}\n\n <div class=\"col\">\n <h5>Name</h5>\n <input value={nameFilter} class=\"form-control\" type=\"text\" onChange={nameFilterSet}/>\n </div>\n\n {/*Category to filter Container*/}\n\n <div class=\"col\">\n <h5>Category</h5>\n <select class=\"form-select\" id=\"cars\" name=\"cars\" value={categoryFilter} onChange={categoryFilterHandler}>\n <option value=\"All\">All</option>\n <option value=\"Bills\">Bills</option>\n <option value=\"Entertainment\">Entertainment</option>\n <option value=\"Food\">Food</option>\n <option value=\"Travel\">Travel</option>\n <option value=\"Miscellaneous\">Miscellaneous</option>\n </select>\n </div>\n\n {/*Date sort Container*/}\n\n <div class=\"col\">\n <h5>Date Sort</h5>\n <select class=\"form-select\" id=\"cars\" name=\"cars\" value={dateSort} onChange={dateSortHandler}>\n <option value=\"None\">None</option>\n <option value=\"New\">Date (Newest)</option>\n <option value=\"Old\">Date (Oldest)</option>\n </select>\n </div>\n\n {/*Reset and clear button Container*/}\n\n <div class=\"col\">\n <h5>&nbsp;</h5>\n <div class=\"btn-group btn-outline-primary\">\n <button class=\"btn btn-outline-primary\" onClick={resetHandler}>Reset</button>\n <button class=\"btn btn-outline-primary\" onClick={clearHandler}>Clear</button>\n </div>\n </div>\n\n </div>\n\n </div>\n \n </div>\n )\n}", "function filter(s = false) {\n // Get search term\n let search = document.getElementById(\"search\");\n let filterTerm = search.value.toUpperCase();\n\n // Filter result by search term\n let filtered = employees.filter(e =>\n e.Ho_ten.toUpperCase().includes(filterTerm)\n );\n\n // Filter by department (s is true - this function use in s-manager page)\n if (s) {\n let department = document.querySelector('input[name=\"department\"]:checked')\n .value;\n if (department != \"all\") {\n filtered = filtered.filter(e => e.Don_vi == department);\n }\n }\n\n // Create table contains filtered content\n let tbody = document.getElementById(\"listBody\");\n while (tbody.firstChild) {\n tbody.removeChild(tbody.firstChild);\n }\n\n for (let i = 0; i < filtered.length; i++) {\n let tr = document.createElement(\"tr\");\n\n let th1 = document.createElement(\"th\");\n th1.setAttribute(\"scope\", \"col\");\n th1.innerText = i + 1;\n\n let span = document.createElement(\"span\");\n span.setAttribute(\"class\", \"text-capitalize\");\n span.innerText = filtered[i].Ho_ten;\n\n let th2 = document.createElement(\"th\");\n th2.setAttribute(\"scope\", \"col\");\n th2.appendChild(span);\n\n tr.appendChild(th1);\n tr.appendChild(th2);\n\n if (s) {\n let th3 = document.createElement(\"th\");\n th3.setAttribute(\"scope\", \"col\");\n th3.innerText = filtered[i].Don_vi;\n tr.appendChild(th3);\n }\n\n let a = document.createElement(\"a\");\n a.setAttribute(\"href\", `./${username}/${password}/${filtered[i].CMND}`);\n a.setAttribute(\"target\", \"_blank\");\n a.innerText = \"Chi tiết\";\n let th4 = document.createElement(\"th\");\n th4.setAttribute(\"scope\", \"col\");\n th4.appendChild(a);\n\n tr.appendChild(th4);\n\n tbody.appendChild(tr);\n }\n}", "function filter() {\n\t\n\t//getting values selected by user from dropdown menus\n var vessel = $('#vessel').val();\n var dbo = $('#dbo').val();\n var chief_sci = $('#chief_sci').val();\n var cruise_id = $('#cruise_id').val();\n var year = $('#year').val();\n\n //copying original data array w/ all cruises\n var data = cruiseData;\n\n\n //helper function that filters by any single parameter \n function filter_by(data, parameter) {\n //Make sure parameter is not empty\n if (eval(parameter) != 0 & eval(parameter) != null) {\n var data = $.grep(data, function (e) {\n return e[parameter] === eval(parameter)\n });\n\n }\n return data;\n };\n \n //Parsing out first menu, which can have more than one item selected\n\n if (dbo != null) {\n for (var i = 0; i < dbo.length; i++) {\n if (i == 0) {\n var line = $.grep(data, function (a) {\n return a.dbo == dbo[i]\n });\n } else {\n var line = line.concat($.grep(data, function (a) {\n return a.dbo == dbo[i]\n }));\n }\n }\n data = line;\n }\n\n //filter the data cummulatively with each of the criteria\n data = filter_by(data, \"chief_sci\");\n data = filter_by(data, \"cruise_id\");\n data = filter_by(data, \"vessel\");\n data = filter_by(data, \"year\");\n\n //Clear list of result cruises\n $('.list-group').html(\"\");\n\n //Cycle through each cruise that passed the filter and insert list element\n $.each(data, function (e) {\n $('.list-group').append(\n '<a href=\\\"#\\\" onclick=\"return false\" class=\\\"list-group-item\\\"> \\\n\t\t\t\t\t<h4 class=\\\"list-group-item-heading\\\">' + data[e].cruise_id + '</h4>\\\n\t\t\t\t\t <p class=\\\"list-group-item-text\\\">\\\n\t\t\t\t\t <strong>Chief Scientist</strong>: ' + data[e].chief_sci + '</br>\\\n\t\t\t\t\t <strong>Vessel</strong>: ' + data[e].vessel + '</br>\\\n\t\t\t\t\t <strong>DBO Line</strong>: ' + data[e].dbo + '</br>\\\n\t\t\t\t\t <strong>Date</strong>: ' + data[e].month + ' / ' + data[e].year + '</br>\\\n\t\t\t\t\t </p> </a>');\n }); // end of loop\n\n //binding event handlers to newly created elements. \n $(\".list-group-item\").hover(hover_on, hover_off);\n $('.get_data').click(click_on);\n\n\t//display error msg if no cruises match the criteria\n if (data.length == 0) {\n $('.list-group').html('\\\n\t\t<div class=\\\"alert alert-warning\\\"> \\\n <strong>Oops!</strong> It seems no \\\n\t\tcruises match your search criteria! Please try again!</div>')\n\n };\n\n //Create/update heat map plot\n cal = heat_map(data);\n\t\n}", "function setFilter() {\n switch (target.value) {\n case 'person':\n addFilters('all', 'id', 'phone', 'email', 'hobby');\n toggelAdvancedbtn(\"person\");\n break;\n case 'company':\n addFilters('all', 'cvr', 'name', 'phone', 'email');\n toggelAdvancedbtn(\"company\");\n break;\n case 'city':\n addFilters('all', 'zip');\n toggelAdvancedbtn();\n break;\n case 'address':\n addFilters('all', 'zip');\n toggelAdvancedbtn();\n break;\n case 'phone':\n addFilters('all', 'number');\n toggelAdvancedbtn();\n break;\n case 'hobby':\n addFilters('all', 'name');\n toggelAdvancedbtn();\n }\n}", "action(e) {\n this.filterCategories = e\n if (!this.active) {\n $.fn.dataTable.ext.search.push(this.filter)\n this.active = true\n }\n $('#achievements').DataTable().draw()\n }", "showAllFilterOptions(){\n\n\t\t$('ul'+this.styles.filters_list+' li').each(function(){\n\n\t\t\tif($(this).data('type')!='text'){\n\t\t\t\t$(this).show();\n\t\t\t}\t\n\n\t\t});\n\t}", "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}", "function getCategory(e) {\n filter(e.target.value); //filter function send which button we click\n if(e.target.value == \"all\"){\n bringFoods(); // bringFoods run when we click \"all button\" & form loaded\n }\n\n}", "function meatFilter(meat) {\n \n if (meal_type == meat) {\n meal_type = \"none\" //resets so on double click it can remove filter\n }\n \n else {\n meal_type = meat;\n }\n \n page = 1;\n getURL();\n updateButton();\n}", "function handleFilters() {\n console.log(this.value);\n var index = filters.indexOf(this.value);\n if (index === -1) filters.push(this.value);\n else filters.splice(index, 1);\n console.log(filters);\n renderApplicants(Object.values(allApplicants[currJobIndex] || {}), currJobIndex, searchVal, filters);\n}", "searchFilter(e) {\n this.getSearchResults(formData)\n }", "function filterTasks(e){\n console.log(\"Task filter...\")\n var searchFilter, listItem, txtValue;\n searchFilter = filter.value.toUpperCase();\n listItem = document.querySelectorAll('.collection-item');\n //looping through the list items, and hiding unmatching results\n listItem.forEach(function(element){\n txtValue = element.textContent || element.innerText;\n if(txtValue.toUpperCase().indexOf(searchFilter) > -1){\n element.style.display = \"\";\n }else{\n element.style.display = \"none\";\n }\n });\n}", "function action_filter() {\n\tvar filter_criteria = {};\n\n\tvar search = $('#search').val().toLowerCase();\n\tfilter_document(search);\n\t\n\treturn false;\n}", "function filterMenu(e) {\n if (e.field == \"tar_dat_fchlimite\") {\n var beginOperator = e.container.find(\"[data-role=dropdownlist]:eq(0)\").data(\"kendoDropDownList\");\n beginOperator.value(\"gte\");\n beginOperator.trigger(\"change\");\n\n var endOperator = e.container.find(\"[data-role=dropdownlist]:eq(2)\").data(\"kendoDropDownList\");\n endOperator.value(\"lte\");\n endOperator.trigger(\"change\");\n e.container.find(\".k-dropdown\").hide()\n }\n if (e.field == \"tar_dat_fchcreacion\") {\n var beginOperator = e.container.find(\"[data-role=dropdownlist]:eq(0)\").data(\"kendoDropDownList\");\n beginOperator.value(\"gte\");\n beginOperator.trigger(\"change\");\n\n var endOperator = e.container.find(\"[data-role=dropdownlist]:eq(2)\").data(\"kendoDropDownList\");\n endOperator.value(\"lte\");\n endOperator.trigger(\"change\");\n e.container.find(\".k-dropdown\").hide()\n }\n if (e.field == \"tar_int_estado\") {\n //e.container.find(\"k-widget.k-dropdown.k-header\").css(\"display\", \"none\");\n // Change the text field to a dropdownlist in the Role filter menu.\n e.container.find(\".k-textbox:first\")\n //.removeClass(\"k-textbox\")\n .kendoDropDownList({\n dataSource: new kendo.data.DataSource({\n data: [\n {\n title: \"Pendiente\",\n value: 1\n },\n {\n title: \"Cerrado\",\n value: 0\n }\n ]\n }),\n dataTextField: \"title\",\n dataValueField: \"value\"\n });\n }\n if (e.field == \"tar_int_prioridad\") {\n //e.container.find(\"k-widget.k-dropdown.k-header\").css(\"display\", \"none\");\n // Change the text field to a dropdownlist in the Role filter menu.\n e.container.find(\".k-textbox:first\")\n //.removeClass(\"k-textbox\")\n .kendoDropDownList({\n dataSource: new kendo.data.DataSource({\n data: [\n {\n title: \"Alta\",\n value: 3\n },\n {\n title: \"Media\",\n value: 2\n },\n {\n title: \"Baja\",\n value: 1\n }\n ]\n }),\n dataTextField: \"title\",\n dataValueField: \"value\"\n });\n }\n\n }", "function myFunction() {\n var input, filter, ul, li, a, i;\n input = document.getElementById(\"mySearch\");\n filter = input.value.toUpperCase();\n ul = document.getElementById(\"myMenu\");\n li = ul.getElementsByTagName(\"li\");\n for (i = 0; i < li.length; i++) {\n a = li[i].getElementsByTagName(\"a\")[0];\n if (!(a.innerHTML.toUpperCase().indexOf(filter) > -1) && filter==\"\")\n {\n li[i].style.display = \"none\";\n }else\n {\n li[i].style.display = \"block\";\n }\n }\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 _search()\n {\n var allCategoryNames = [];\n // Incorporate all terms into\n var oepterms = $scope.selectedOepTerms ? $scope.selectedOepTerms : [];\n var situations = $scope.selectedSituations ? $scope.selectedSituations : [];\n var allCategories = oepterms.concat(situations);\n allCategories.forEach(function(categoryObj) {\n allCategoryNames.push(categoryObj.name);\n checkEmergencyTerms(categoryObj.name);\n });\n search.search({ category: allCategoryNames.join(',') });\n }", "function filterSelection(c) {\n var allproducts = document.getElementsByClassName('product_f');\n var featuredproducts = document.getElementsByClassName('featured_f');\n var menproducts = document.getElementsByClassName('men_f');\n var womenproducts = document.getElementsByClassName('women_f');\n if (c === 'all') {\n for (let i = 0; i < allproducts.length; i++) {\n allproducts[i].classList.add('show');\n }\n } else if (c === 'featured_f') {\n for (let i = 0; i < allproducts.length; i++) {\n allproducts[i].classList.remove('show');\n }\n for (let i = 0; i < featuredproducts.length; i++) {\n featuredproducts[i].classList.add('show');\n }\n } else if (c === 'men_f') {\n for (let i = 0; i < allproducts.length; i++) {\n allproducts[i].classList.remove('show');\n }\n for (let i = 0; i < menproducts.length; i++) {\n menproducts[i].classList.add('show');\n }\n } else if (c === 'women_f') {\n for (let i = 0; i < allproducts.length; i++) {\n allproducts[i].classList.remove('show');\n }\n for (let i = 0; i < womenproducts.length; i++) {\n womenproducts[i].classList.add('show');\n }\n }\n}", "function filterResults(event) {\n const filter = event.target.value;\n if (filter === \"baking\"){\n const baking = products.filter(result => (result.family.baking === true));\n setFilteredProducts(baking);\n } else if (filter === \"grilling\"){\n const grilling = products.filter(result => (result.family.grilling === true));\n setFilteredProducts(grilling);\n } else if (filter === \"seasoning\"){\n const seasoning = products.filter(result => (result.family.seasoning === true));\n setFilteredProducts(seasoning);\n } else if (filter === \"extract\"){\n const extract = products.filter(result => (result.family.extract === true));\n setFilteredProducts(extract);\n } else if (filter === \"teas\"){\n const teas = products.filter(result => (result.family.teas === true));\n setFilteredProducts(teas);\n } else {\n setFilteredProducts(products);\n }\n}", "function filterSysApps(){\n\n\tvar filter = \"\";\n\tif($(\"#nameFilter\").val().length > 0){\n\t\tfilter = filter + \"&name=\"+$(\"#nameFilter\").val();\n\t}\n\tif($(\"#levelFilter\").val().length > 0){\n\t\tfilter = filter + \"&minlvl=\"+$(\"#levelFilter\").val();\n\t}\n\tif($(\"#appFilter\").is(\":checked\")){\n\t\tfilter = filter + \"&apps\";\n\t}\n\tif($(\"#driverFilter\").is(\":checked\")){\n\t\tfilter = filter + \"&drivers\";\n\t}\n\n\t$.getJSON(\"/security/config/installedapps?action=filter\"+filter +\"&user=\" + otusr + \"&pw=\" + otpwd, function(json) {\n\t\tvar headers = $(\".portlet-header\")\n\n\t\tfor(i=0; i<headers.length; i++){\n\t\t\tif(json.indexOf(parseInt(headers[i].id)) == -1){\n\t\t\t\t$(headers[i].parentNode.parentNode).hide();\n\t\t\t}else{\n\t\t\t\t$(headers[i].parentNode.parentNode).show();\n\t\t\t}\n\t\t}\n\t});\n}", "function foodTypeHandler(e) {\n\tsearchInput = e.target.value\n\tconst foodType = restaurants.filter((r) => {\n\t\treturn r.Tags.join('|')\n\t\t\t.toLowerCase()\n\t\t\t.split('|')\n\t\t\t.includes(searchInput.toLowerCase())\n\t})\n\tconsole.log(foodType)\n\tfilteredRestaurants(foodType)\n}", "function setupFilters(mainPath) {\n var url = mainPath + \"filteredData\";\n\n url = \"serviceVisitsData.php?table=filteredData\";\n var filtObj = {};\n filtObj[\"type\"] = \"\";\n filtObj[\"brand\"] = \"\";\n filtObj[\"browser\"] = \"\";\n filtObj[\"referrer\"] = \"\";\n filtObj[\"operatingSys\"] = \"\";\n filtObj[\"country\"] = \"\";\n \n filtObj[\"url\"] = url + \"&type=\" + filtObj[\"type\"] + \"&brand=\" + filtObj[\"brand\"] \n + \"&browser=\" + filtObj[\"browser\"] + \"&referrer=\"+filtObj[\"referrer\"] \n + \"&operatingSys=\"+ filtObj[\"operatingSys\"] + \"&country=\" +filtObj[\"country\"];\n \n var updatedObj= {};\n \n updatedObj = addEventToFilters(\"type\", filtObj);\n updatedObj = addEventToFilters(\"brand\", filtObj);\n updatedObj = addEventToFilters(\"browser\", filtObj);\n updatedObj = addEventToFilters(\"referrer\", filtObj);\n updatedObj = addEventToFilters(\"operatingSys\", filtObj);\n //deal with textbox\n updatedObj = autocompleteCountries(\"country\", filtObj);\n dataRequestFromFilters(filtObj);\n}", "function filterItems() {\n //returns newPropList, array of properties\n var newPropList = featured;\n //Beds\n console.log(1, newPropList);\n if(currentFilters.beds == 5) {\n newPropList = newPropList.filter(item => item.bedrooms >= currentFilters.beds);\n }\n else if (currentFilters.beds == 0) {\n\n }\n else {\n newPropList = newPropList.filter(item => item.bedrooms == currentFilters.beds);\n }\n console.log(2, newPropList);\n //Baths\n if(currentFilters.baths == 5) {\n newPropList = newPropList.filter(item => item.fullBaths >= currentFilters.baths);\n }\n else if (currentFilters.baths == 0) {\n\n }\n else {\n newPropList = newPropList.filter(item => item.fullBaths == currentFilters.baths);\n }\n console.log(3, newPropList);\n //Price\n if(currentFilters.max == 0) {\n\n }\n else if(currentFilters.min == 1000000) {\n newPropList = newPropList.filter(item => item.rntLsePrice >= currentFilters.min);\n }\n else {\n newPropList = newPropList.filter(item => item.rntLsePrice >= currentFilters.min && item.rntLsePrice <= currentFilters.max);\n }\n console.log(4, newPropList);\n //Type\n console.log(currentFilters.type);\n if(currentFilters.type == \"All\") {\n console.log('all');\n }\n else if(currentFilters.type == \"Other\") {\n newPropList = newPropList.filter(item => item.idxPropType == \"Residential Income\" || item.idxPropType == \"Lots And Land\");\n console.log('other');\n }\n else {\n newPropList = newPropList.filter(item => item.idxPropType == currentFilters.type);\n console.log('normal');\n }\n //Search Term\n console.log(5, newPropList);\n if(currentFilters.term != '')\n {\n newPropList = newPropList.filter(item => \n item.address.toLowerCase().indexOf(currentFilters.term.toLowerCase()) != -1 ||\n item.cityName.toLowerCase().indexOf(currentFilters.term.toLowerCase()) != -1\n );\n }\n console.log(6, newPropList);\n return newPropList;\n }", "function filtertopics(clickedMenuFilter)\n\t\t{\t\n\t\t\t$(\".menu-list-and-description .menu-description\").hide();\t\t//hides all topics data\n\t\t\t$(\".\"+clickedMenuFilter).show();\t//shows topics data related to clicked menu, based on 'data-filter' attribute which has same class used to recognize filter.\n\t\t}", "function filterFunction() {\r\n var input, filter, ul, li, a, i;\r\n input = document.getElementById(\"nearbyInput\");\r\n filter = input.value.toUpperCase();\r\n div = document.getElementById(\"dropListDiv\");\r\n a = div.getElementsByTagName(\"button\");\r\n for (i = 0; i < a.length; i++) {\r\n if (a[i].innerHTML.toUpperCase().indexOf(filter) > -1) {\r\n a[i].style.display = \"\";\r\n } else {\r\n a[i].style.display = \"none\";\r\n }\r\n }\r\n}", "_clickHandlerFilterButton(elementClassList, itemId, target) {\n const that = this;\n\n if (target.closest('.jqx-editors-container')) {\n return;\n }\n\n that._closeEditor();\n that._editedItem = that._getItemById(itemId);\n\n if (!elementClassList.contains('jqx-filter-field-name') && (!that._editedItem.data || !that._editedItem.data.length)) {\n return;\n }\n\n if (elementClassList.contains('jqx-filter-group-operation')) {\n prepareContextMenu(target, that._groupOperationDescriptions, that._editedItem.data);\n return;\n }\n else if (elementClassList.contains('jqx-filter-add-btn')) {\n prepareContextMenu(target, that._groupOperationDescriptions);\n }\n else if (elementClassList.contains('jqx-filter-field-name')) {\n if (!that._fields) {\n that._mapFieldsToMenu();\n }\n\n prepareContextMenu(target, that._fields, that._editedItem.data[0]);\n return;\n }\n else if (elementClassList.contains('jqx-filter-operation')) {\n const selectedField = that._getFieldByFieldName(that._editedItem.data[0]);\n\n if (!selectedField) {\n return;\n }\n\n let filteredOptions = that._filterOperationDescriptions.slice();\n\n if (selectedField && selectedField.filterOperations) {\n filteredOptions = that._filterOperationDescriptions.filter(item => {\n return selectedField.filterOperations.indexOf(item.value) > -1;\n });\n }\n else {\n let filterOperationsByType;\n\n switch (selectedField.dataType) {\n case 'number':\n filterOperationsByType = ['=', '<>', '<', '>', '<=', '>=', 'isblank', 'isnotblank'];\n break;\n case 'date':\n filterOperationsByType = ['=', '<>', '<', '>', '<=', '>=', 'isblank', 'isnotblank'];\n break;\n case 'datetime':\n filterOperationsByType = ['=', '<>', '<', '>', '<=', '>=', 'isblank', 'isnotblank'];\n break;\n case 'boolean':\n filterOperationsByType = ['=', '<>', 'isblank', 'isnotblank'];\n break;\n case 'object':\n filterOperationsByType = ['isblank', 'isnotblank'];\n break;\n case 'string':\n filterOperationsByType = ['contains', 'notcontains', 'startswith', 'endswith', '=', '<>', 'isblank', 'isnotblank'];\n break;\n default:\n filterOperationsByType = ['contains', 'notcontains', 'startswith', 'endswith', '=', '<>', '<', '>', '<=', '>=', 'isblank', 'isnotblank'];\n break;\n }\n\n filteredOptions = that._filterOperationDescriptions.filter(item => {\n return filterOperationsByType.indexOf(item.value) > -1;\n });\n }\n\n if (that.showIcons) {\n filteredOptions = filteredOptions.map(item => {\n item.label = '<div class=\"jqx-filter-builder-icon\">' + that.icons[item.value] + '</div><div class=\"jqx-filter-builder-menu-item\">' + that.localize(item.value) + '</div>';\n\n return item;\n });\n }\n\n prepareContextMenu(target, filteredOptions.slice(), that._editedItem.data[1]);\n return;\n }\n else {\n that._openEditor(target);\n return;\n }\n\n function deSelectMenuItem() {\n const alredySelectedItem = that.$.conditionsMenu.querySelector('.jqx-selected-menu-item');\n\n if (alredySelectedItem) {\n alredySelectedItem.classList.remove('jqx-selected-menu-item');\n }\n }\n\n function prepareContextMenu(target, dataSource, selectedItem) {\n deSelectMenuItem();\n that._contextMenuOptions = dataSource.length === 0 ? that._defaultFilterOperationDescriptions : dataSource;\n that._handleContextMenu(target);\n\n const selectedField = selectedItem,\n chosenMenuItem = that.$.conditionsMenu.querySelector('jqx-menu-item[value=\"' + selectedField + '\"]');\n\n if (!that.$.conditionsMenu.opened || !chosenMenuItem) {\n return;\n }\n\n chosenMenuItem.classList.add('jqx-selected-menu-item');\n }\n }", "function joinedFilter() {\n \n let alfabeticvalue = orderlabel.innerHTML;\n let rolevalue = roleOrder.innerHTML;\n let dificultvalue = dificultlabel.innerHTML;\n\n let alfabeticlist = datos.sortAlfabeticaly(initialList, alfabeticvalue);\n\n let rolelist = datos.filterbyRole(alfabeticlist, rolevalue);\n \n let dificultList = datos.filterbyDificult(rolelist, dificultvalue);\n\n fillDashboard(dificultList);\n}", "function clickFilter(event) {\n // get current filter information\n attr = this.dataset.attr;\n\n // mark all filters inactive\n markAllInactive(filters, 'list__item--active');\n visibleItems = removeAllElements(visibleItems, type);\n\n // mark this filter active\n this.classList.add('list__item--active');\n visibleItems.push(attr);\n\n // do the filtering\n doFilter();\n }", "function filterItems(by, value, items){\n\tif(!value || value == ''){\n\t\treturn items;\n\t}\n\t\n\tvar debug = '';\n\tvar filteredItems = [];\n\t$.each(items, function(key, item) {\n\t\tif(by == 'shelf'){\n\t\t\tif(String(value) == String(item.shelf)){\n\t\t\t\tdebug += item.title + \"\\n\";\n\t\t\t\tfilteredItems.push(item);\n\t\t\t}\n\t\t\t\n\t\t} else if(by == 'search'){\n\t\t\tif(\t(String(item.title).toLowerCase().indexOf(String(value).toLowerCase()) >= 0) || \n\t\t\t\t(String(item.creator).toLowerCase().indexOf(String(value).toLowerCase()) >= 0)\n\t\t\t\t){\n\t\t\t\tdebug += item.title + \"\\n\";\n\t\t\t\tfilteredItems.push(item);\n\t\t\t}\n\t\t}\n\t});\n\t\n\t//alert(debug);\n\treturn filteredItems;\n}", "filter() { \n\n const filters = {\n country_id: this.state.filters.country.id,\n client_type: this.state.filters.client_type\n };\n\n this.props.fetchEnterpriseList(filters);\n\n this.props.history.push({\n search: queryString.stringify(filters)\n });\n }", "function filterCards(cost){\n var flag1 = false;\n if ($scope.searchText != undefined && $scope.searchText != null && $scope.searchText != ''){\n if($scope.searchBy == 'CustomerID'){\n if (cost.customer_ID != null && cost.customer_ID.toLowerCase().indexOf($scope.searchText.toLowerCase()) != -1) {\n flag1 = true;\n }\n }\n else{\n if ((cost.customer_Name != null && cost.customer_Name.toLowerCase().indexOf($scope.searchText.toLowerCase()) != -1) && (cost.customer_DOB != null && cost.customer_DOB.toLowerCase().indexOf($scope.customerDOB.toLowerCase()) != -1)) {\n flag1 = true;\n } \n }\n } \n else{\n flag1 = true;\n }\n return flag1;\n }", "function setFilters() {\n }", "function req_filterCustomers(searchTerm, currentSearchFilter, customerData){\n\t$.ajax({\n\t method: \"POST\",\n\t url: \"/actions/filterCustomers\",\n\t dataType: \"json\",\n\t data: { searchTerm: JSON.stringify(searchTerm), searchFilter: JSON.stringify(currentSearchFilter), customerData: JSON.stringify(customerData) },\n\t traditional: true\n\t})\n\t .done(function( matchIDList ) {\n\t \t\tfilterResults(matchIDList);\n\t });\n\t \n}", "function handleSearchButtonClick() {\n \n filteredData = dataSet;\n // Format the user's search by removing leading and trailing whitespace, lowercase the string\n var filterDatetime = $dateInput.value.trim().toLowerCase();\n var filterCity = $cityInput.value.trim().toLowerCase();\n var filterState = $stateInput.value.trim().toLowerCase();\n var filterCountry = $countryInput.value.trim().toLowerCase();\n var filterShape = $shapeInput.value.trim().toLowerCase();\n\n // Set filteredAddresses to an array of all addresses whose \"state\" matches the filter\n filteredData = dataSet.filter(function(address) {\n var addressDatetime = address.datetime.toLowerCase();\n var addressCity = address.city.toLowerCase();\n var addressState = address.state.toLowerCase();\n var addressCountry = address.country.toLowerCase();\n var addressShape = address.shape.toLowerCase();\n\n\n\n if ((addressDatetime===filterDatetime || filterDatetime == \"\") && \n (addressCity === filterCity || filterCity == \"\") && \n (addressState === filterState || filterState == \"\") &&\n (addressCountry === filterCountry || filterCountry == \"\") && \n (addressShape === filterShape || filterShape ==\"\")){\n \n return true;\n }\n return false;\n console.log(filteredData);\n });\nloadList();\n}", "function filterCategories(value) {\n for (i = 0; i < categoryArray.length; i++) {\n if (categoryArray[i].text.toLowerCase().includes(value.toLowerCase())) {\n $(\"#\" + categoryArray[i].value).attr(\"tabindex\", \"-1\");\n $(\"#\" + categoryArray[i].value).attr(\"role\", \"menuitem\");\n $(\"#\" + categoryArray[i].value).addClass(\"dropdown-item\");\n $(\"#\" + categoryArray[i].value).show();\n }\n else {\n $(\"#\" + categoryArray[i].value).removeAttr(\"tabindex\");\n $(\"#\" + categoryArray[i].value).removeAttr(\"role\");\n $(\"#\" + categoryArray[i].value).removeClass(\"dropdown-item\");\n $(\"#\" + categoryArray[i].value).hide();\n }\n }\n}", "selectFilterFacilidade(facilidades){\n\n //to open the DropDown\n this.getDropDownBoxFacilidades().click();\n\n //Search by the passed facilidades and click in checkBoxes\n facilidades.forEach((item) => {\n this.getCheckboxesFacilidades().contains(item).click();\n });\n }", "filterByEmployee(filterKeyw){\n let unfilteredEmployees = this.state.employees;\n\n if(filterKeyw.length>0){\n let filteredEmployees = unfilteredEmployees.filter(client => (client.name.toLowerCase().indexOf(filterKeyw) > -1));\n\n this.setState({\n filteredEmployees: filteredEmployees,\n isFiltered: true\n });\n\n } else {\n //if no keyword entered, change isFiltered to false\n this.setState({\n isFiltered: false\n });\n } \n }", "filterRealization (filters) {\n this.scrollToTop()\n filters.map((filter) => {\n switch (filter.id) {\n case 'condition':\n // set params conditions 'new' or 'used\n let isNew = (_.find(filter.options, (option) => { return option.id === 'new' }).selected)\n let isUsed = (_.find(filter.options, (option) => { return option.id === 'used' }).selected)\n if (isNew) this.params.condition = 'new'\n if (isUsed) this.params.condition = 'used'\n if (isNew && isUsed) delete this.params.condition\n break\n case 'expeditionServices':\n // set params expeditionServices services\n // get id service when selected is true\n let idServicesTrue = _.map(filter.options.filter((option) => { return option.selected }), 'id')\n if (idServicesTrue.length > 0) {\n this.params.services = idServicesTrue\n } else {\n delete this.params.services\n }\n break\n case 'brands':\n // set params brands\n // get id service when selected is true\n let idBrandTrue = _.map(filter.options.filter((option) => { return option.selected }), 'id')\n if (idBrandTrue.length > 0) {\n this.params.brands = idBrandTrue\n } else {\n delete this.params.brands\n }\n break\n case 'others':\n // set params 'discount', 'verified', 'wholesaler'\n let idOthersTrue = _.map(filter.options.filter((option) => { return option.selected }), 'id')\n if (idOthersTrue.length > 0) {\n this.params.other = idOthersTrue\n } else {\n delete this.params.other\n }\n break\n case 'sendFrom':\n // set params districs/kota pengiriman\n if (filter.districtsSelected) {\n this.params.address = filter.districtsSelected\n } else {\n delete this.params.address\n }\n break\n case 'harga':\n // set params for price range\n this.params.price = filter.priceMinimum + '-' + filter.priceMaximum\n if (Number(filter.priceMinimum) === 0 && Number(filter.priceMaximum) === 0) delete this.params.price\n break\n default:\n break\n }\n })\n // start loading\n NProgress.start()\n // fetch product by params\n this.filterRealizationStatus = true\n this.submitting = { ...this.submitting, dropshipProducts: true }\n this.params.page = 1\n this.params.limit = 10\n delete this.params.sort\n let params = this.generateParamsUrl()\n Router.replace(`/dropship?${params}`)\n this.props.getDropshipProducts(this.params)\n\n /** close filter */\n this.setState({ filterActive: false, pagination: { page: 1, limit: 10 } })\n }", "function filterListener(){\n $(\"#colorFilter\").change(function(){\n populateBikeList();\n });\n $(\"#statusFilter\").change(function(){\n populateBikeList();\n });\n }", "activateFilter(){\n \tvar _this = this;\n \tvar bannerWho = document.getElementsByClassName(\"banner-who\");\n \tvar bannerWish = document.getElementsByClassName(\"banner-wish\");\n\n \tdocument.getElementById(\"search-icon\").style.background = 'white';\n\n \tvar searchIconSrc=$(\"#search-icon-img\").attr('src');\n \tsearchIconSrc=searchIconSrc.replace('icone_recherche_active_fond.png','icone_recherche_desactive.png');\n \t$(\"#search-icon-img\").attr('src',searchIconSrc);\n\n \tvar filterIconSrc=$(\"#filter-icon-img\").attr('src');\n \tfilterIconSrc=filterIconSrc.replace('icone_explorer_desactive.png','icone_explorer_active_fond.png');\n \t$(\"#filter-icon-img\").attr('src',filterIconSrc);\n\n\n \t$('#search-icon').on('click',function(e){\n \t\te.preventDefault();\n \t\t_this.activateSearch();\n \t});\n \t$('#filter-icon').on('click',function(e){\n \t\te.preventDefault();\n \t});\n\n \t$('#search-button').on('click',function(){\n \t\t$( \"#banner-search-bar\" ).prop(\"disabled\",true);\n \t\tselectedWishVal = $('#banner-wish-select').find(\"option:selected\").val();\n \t\tselectedWhoVal = $('#banner-who-select').find(\"option:selected\").val();\n \t\tif(selectedWhoVal === '-1'){\n \t\t\t$( \"#banner-who-select\" ).prop(\"disabled\",true);\n \t\t}\n \t\tif(selectedWishVal === '-1'){\n \t\t\t$( \"#banner-wish-select\" ).prop(\"disabled\",true);\n \t\t}\n \t\tdocument.getElementById('banner-search-form').submit();\n \t});\n\n \tdocument.getElementById(\"filter-icon\").style.backgroundColor = '#01b2e6';\n \tdocument.getElementById(\"search-button\").style.visibility = 'visible';\n \tdocument.getElementById(\"banner-search-bar\").style.visibility = 'hidden';\n\n \tfor (var i = 0; i < bannerWho.length; i++) {\n \t\tbannerWho[i].style.visibility = \"visible\";\n \t}\n\n \tfor (var i = 0; i < bannerWish.length; i++) {\n \t\tbannerWish[i].style.visibility = \"visible\";\n \t}\n\n \tdocument.getElementById(\"andor\").style.visibility = 'visible';\n\n \treturn true;\n }", "function filterSearchLinks() {\n const filter = searchBar.value.toUpperCase();\n const searchList = document.getElementById(\"searchLinks\");\n const searchListLi = searchList.getElementsByTagName(\"li\");\n let searchListA;\n let searchTxtVal;\n\n for (searchI = 0; searchI < searchListLi.length; searchI++) {\n searchListA = searchListLi[searchI].getElementsByTagName(\"a\")[0];\n searchTxtVal = searchListA.textContent || searchListA.innerText;\n\n if (searchTxtVal.toUpperCase().indexOf(filter) > -1) {\n searchListLi[searchI].style.display = \"\";\n } else {\n searchListLi[searchI].style.display = \"none\";\n }\n }\n }", "function filterByUser(param) {\n self.selectionModel.allMatter = param;\n if (param == 1) {\n self.viewModel.filters.for = \"mymatter\";\n } else {\n self.viewModel.filters.for = \"allmatter\";\n }\n self.viewModel.filters\n getMatterList(undefined, 'calDays');\n }", "function filterHandler() {\n $(\"body\").on(\"click\", \".filter-input\", function () {\n //Get filter and value selected\n var filterHTML = ($(this).closest(\"ul\").siblings(\"h5\").html());\n var filter = (_.invert(textFormat)[filterHTML]);\n var selected = $(\".\" + filter + \".selected-input\");\n var val = $(this).html();\n var currentFilter = {};\n \n $(\".\" + filter).removeClass(\"selected-input\"); //Reset filter class to default style\n if ($(selected).html() == val) {\n filterList[filter] = \"\"; //Set filter to blank after deselecting\n } else {\n $(this).addClass(\"selected-input\"); //Add active class to selected filter\n filterList[filter] = val; //Add filter value to filter key\n }\n\n //Toggle hidden according to filter match\n $('.app').each(function () {\n var parent = this;\n var name = $(this).find(\".item-name\").html();\n valid = true;\n\n $(this).children(\".hoverContainer\").children(\".hover-properties\").children(\"li\").each(function () {\n tempFilter = (_.invert(textFormat)[$(this).find(\".property-filter\").html().slice(0, -1)]);\n tempValue = $(this).find(\".property-value\").html();\n currentFilter[tempFilter] = tempValue;\n });\n $.each(currentFilter, function (key, object) {\n if ((filterList[key] == object || filterList[key] == \"\")) {\n } else {\n valid = false;\n }\n });\n\n if (valid == false) {\n $(parent).addClass(\"filter-hidden\");\n } else {\n $(parent).removeClass(\"filter-hidden\");\n }\n });\n checkAllHidden();\n });\n}", "function FilterTodoList() {\n var todoStateFilter = \"\";\n $(\".todoList select\").find(\"option:selected\").each(function () {\n todoStateFilter += $(this).val();\n /* filtrage */\n if (todoStateFilter == \"all\") {\n $(this).parents('.todoList').find('.todo li').each(function (index) {\n $(this).show();\n })\n }\n if (todoStateFilter == \"completed\") {\n $(this).parents('.todoList').find('.todo li').each(function (index) {\n if ($(this).find(\"input\").is(':checked')) {\n $(this).show();\n } else {\n $(this).hide();\n }\n })\n }\n if (todoStateFilter == \"uncompleted\") {\n $(this).parents('.todoList').find('.todo li').each(function (index) {\n if ($(this).find(\"input\").is(':checked')) {\n $(this).hide();\n } else {\n $(this).show();\n }\n })\n }\n });\n }", "function handleSearchButtonClick() {\n var filterDate = $dateTimeInput.value.trim();\n var filterCity = $cityInput.value.trim().toLowerCase();\n var filterState = $stateInput.value.trim().toLowerCase();\n var filterCountry = $countryInput.value.trim().toLowerCase();\n var filterShape = $shapeInput.value.trim().toLowerCase();\n\n if (filterDate != \"\") {\n filteredData = filteredData.filter(function (date) {\n var dataDate = date.datetime;\n return dataDate === filterDate;\n });\n\n }\n\n if (filterCity != \"\") {\n filteredData = filteredData.filter(function (city) {\n var dataCity = city.city;\n return dataCity === filterCity;\n });\n }\n\n if (filterState != \"\") {\n filteredData = filteredData.filter(function (state) {\n var dataState = state.state;\n return dataState === filterState;\n });\n }\n\n if (filterCountry != \"\") {\n filteredData = filteredData.filter(function (country) {\n var dataCountry = country.country;\n return dataCountry === filterCountry;\n });\n }\n\n if (filterShape != \"\") {\n filteredData = filteredData.filter(function (shape) {\n var dataShape = shape.shape;\n return dataShape === filterShape;\n });\n }\n\n renderTable();\n}", "function filterUser(li, ci) {\n debug('Filtering ' + ci.name + ' Rank: ' + ci.numeric_rank + ' State: ' + ci.state + ' Desc: ' + ci.description);\n if (opt_showcaymans && ci.state != 'Traveling') {\n debug('Filtered - Caymans only, but either not returning or not Caymans');\n debug('State = ' + ci.state);\n return true;\n }\n\n let isHosped = isInHosp(li);\n let infed = isFedded(li);\n let fallen = isFallen(li);\n let travelling = isTravelling(li);\n if (isHosped || infed || travelling) {\n log('Hosp: ' + isHosped + ' Fedded: ' + infed + ' IsTravelling: ' + travelling);\n log('**** Shouldn`t be here? *****');\n }\n\n switch (ci.state) {\n case 'Hospital':\n if (opt_hidehosp) {\n if (isHosped) log('**** Shouldn`t be here? *****');\n debug('***** Filtered - in hosp.');\n return true;\n }\n break;\n case 'Federal':\n if (opt_hidefedded) {\n if (infed) log('**** Shouldn`t be here? *****');\n debug('***** Filtered - fedded.');\n return true;\n }\n break;\n case 'Fallen':\n if (opt_hidefallen) {\n if (infed) log('**** Shouldn`t be here? *****');\n debug('***** Filtered - fallen.');\n return true;\n }\n break;\n case 'Abroad':\n case 'Traveling':\n if (opt_hidetravel) {\n if (travelling) log('**** Shouldn`t be here? *****');\n debug('***** Filtered - traveling.');\n return true;\n }\n if (opt_showcaymans) {\n if (ci.description.indexOf('Cayman') != -1) {\n if (ci.description.indexOf('Returning') != -1) {\n debug('******Returning from Caymans! Not filtered!');\n return false;\n }\n }\n debug('Filtered - caymans only, but either not returning or not Caymans');\n return true;\n }\n break;\n default:\n return false;\n }\n return false;\n }", "function showSearchMenu(objectType, objectID, module, method, extra)\n{\n var main = objectType == 'branch' ? 'currentBranch' : 'currentItem';\n var $menu = $('#' + main + 'DropMenu');\n\n var searchItems = function($menu, $items, $search)\n {\n var searchText = $.trim($search.val());\n $menu.removeClass('searching');\n $items.removeClass('active');\n if(searchText !== null && searchText.length)\n {\n $items.removeClass('show-search');\n $menu.addClass('searching');\n var isTag = searchText.length > 1 && (searchText[0] === ':' || searchText[0] === '@' || searchText[0] === '#');\n $items.each(function()\n {\n var $item = $(this);\n var item = $item.data();\n item.key = (item.key || '') + $item.text();\n item.tag = (item.tag || '') + '#' + item.id;\n if((isTag && item.tag.indexOf(searchText) > -1) || item.key.indexOf(searchText) > -1)\n {\n $item.addClass('show-search');\n }\n });\n var $resultItems = $items.filter('.show-search');\n if(!$resultItems.filter('.active').length)\n {\n $resultItems.first().addClass('active');\n }\n }\n };\n\n if(!$menu.data('initData'))\n {\n var remoteUrl = createLink(objectType, 'ajaxGetDropMenu', \"objectID=\" + objectID + \"&module=\" + module + \"&method=\" + method + \"&extra=\" + extra);\n $.get(remoteUrl, function(data)\n {\n $menu.html(data);\n\n dropMenuDisplay = new $.Display({display: 'modal', source: $menu.html(), placement: 'top'});\n dropMenuDisplay.show(function()\n {\n var $menu = $('.display.modal.in');\n var $search = $menu.find('#search');\n var $items = $menu.find('#searchResult .list > .item');\n var searchCallTask = null;\n $search.on('change keyup paste input propertychange', function()\n {\n clearTimeout(searchCallTask);\n searchCallTask = setTimeout(searchItems($menu, $items, $search), 100);\n }).focus();\n });\n });\n $menu.data('initData', true);\n }\n else\n {\n dropMenuDisplay = new $.Display({display: 'modal', source: $menu.html(), placement: 'top'});\n dropMenuDisplay.show(function()\n {\n var $menu = $('.display.modal.in');\n var $search = $menu.find('#search');\n var $items = $menu.find('#searchResult .list > .item');\n var searchCallTask = null;\n $search.on('change keyup paste input propertychange', function()\n {\n clearTimeout(searchCallTask);\n searchCallTask = setTimeout(searchItems($menu, $items, $search), 100);\n }).focus();\n });\n }\n $('#' + main).on('click', function(e){e.stopPropagation();});\n}", "function filterAdvSearchResults() {\n\n\tvar count = 0;\n\n\t// show all of the search results\n\t$('.fw-search-result').show();\n\t\n\t// filter by state\n\tvar criteria = $('#adv_filter_state').val();\n\t\n\t// filter the search results by state\n\tif(criteria != 'All') {\n\t\t// fade out the selected search results\n\t\t$('.fw-search-result-' + criteria).show();\n\t\t$('.fw-search-result').not('.fw-search-result-' + criteria).each(function(index, element) {\n\t\t\tcount++;\n\t\t\t$(this).hide();\n\t\t});\n\t\t\n\t}\n\n\t// filter by locality type\n\t// work on those that aren't already hidden\n\tcriteria = $('#adv_filter_locality').val();\n\t\n\tif(criteria != 'all') {\n\t\n\t\t$('.fw-search-result').filter(':visible').each(function(index, element) {\n\t\t\t\n\t\t\tvar data = $(this).data('result');\n\t\t\t\n\t\t\tif(data.locality_type != criteria) {\n\t\t\t\tcount++;\n\t\t\t\t$(this).hide();\n\t\t\t}\n\t\t});\n\t}\n\t\t\n\t// filter by cinema type\n\t// get all of those that aren't already hidden\n\tcriteria = $('#adv_filter_cinema').val();\n\tif(criteria != 'all') {\n\t\t$('.fw-search-result').filter(':visible').each(function(index, element) {\n\t\t\t\t\t\n\t\t\tvar data = $(this).data('result');\n\t\t\t\n\t\t\tif(data.cinema_type != criteria) {\n\t\t\t\tcount++;\n\t\t\t\t$(this).hide();\n\t\t\t}\n\t\t});\n\t}\n\t\n\t$('#adv_result_hidden').empty().append(count);\n}", "function getGroupItemsAndFilters(){\n\t\tajax_get_group_items_and_filters();\n }", "_clickHandlerFilterButton(elementClassList, itemId, target) {\n const that = this;\n\n function prepareContextMenu(target, dataSource, selectedItem) {\n that._contextMenuOptions = dataSource.length === 0 ? that._defaultFilterOperationDescriptions : dataSource;\n that._handleContextMenu(target);\n\n if (that.$.conditionsMenu.opened) {\n that.$.conditionsMenu._discardKeyboardHover();\n that.$.conditionsMenu._hoverViaKeyboard(that.$.conditionsMenu.querySelector('jqx-menu-item[value=\"' + selectedItem + '\"]'));\n }\n }\n\n if (target.closest('.jqx-editors-container')) {\n return;\n }\n\n that._closeEditor();\n that._editedItem = that._getItemById(itemId);\n\n if (elementClassList.contains('jqx-filter-add-btn')) {\n prepareContextMenu(target, that._groupOperationDescriptions);\n return;\n }\n\n if (!elementClassList.contains('jqx-filter-field-name') && (!that._editedItem.data || !that._editedItem.data.length)) {\n return;\n }\n\n if (elementClassList.contains('jqx-filter-group-operator') || elementClassList.contains('jqx-filter-nested-operator')) {\n prepareContextMenu(target, that._groupOperationDescriptions, that._editedItem.data);\n }\n else {\n const filterBuilderItem = target.closest('.filter-builder-item');\n\n filterBuilderItem.removeAttribute('placeholder');\n\n that._openEditor(target);\n }\n }", "function wpv_on_search_filter(el) {\n // get search text\n var searchText = jQuery(el).val();\n\t\n // get parent on DOM to find items and hide/show Search\n var parent = el.parentNode.parentNode;\n var searchItems = jQuery(parent).find('.group .item');\n\t\n jQuery(parent).find('.search_clear').css('display', (searchText == '') ? 'none' : 'inline');\n\t\n // iterate items and search\n jQuery(searchItems).each(function() {\n if(searchText == '' || jQuery(this).text().search(new RegExp(searchText, 'i')) > -1) {\n // alert(jQuery(this).text());\n jQuery(this).css('display', 'inline');\n } \n else {\n jQuery(this).css('display', 'none');\n }\n });\n\t\n // iterate group titles and check if they have items (otherwise hide them)\n\t\n wpv_hide_top_groups(parent);\n}", "function search() {\n $scope.disAdvance = 'none';\n //if ($scope.searchText != '') {\n apiService.get('api/Customer/search?key=' + $scope.searchText, null, function (result) {\n $scope.listCustomer1 = result.data;\n }, function () {\n console.log('load items failed');\n });\n // }\n // else {\n // $scope.listCustomer1 = [];\n // $scope.shoppingCart[$scope.tab].customer = {};\n // }\n }", "function handleSearchButtonClick() \n{\n var filterDateTime = $dateTimeInput.value.trim().toLowerCase(); \n var filterCity = $cityInput.value.trim().toLowerCase();\n var filterState = $stateInput.value.trim().toLowerCase();\n var filterCountry = $countryInput.value.trim().toLowerCase();\n var filterShape = $shapeInput.value.trim().toLowerCase();\n \n if (filterDateTime || filterCity || filterState || filterCountry || filterShape)\n {\n if (filterDateTime){ \n \n search_data = dataSet.filter (function(sighting) { \n var SightingDateTime = sighting.datetime.toLowerCase();\n return SightingDateTime === filterDateTime;\n });\n } else {search_data = dataSet}; \n \n if (filterCity){\n \n search_data = search_data.filter (function(sighting) {\n var SightingCity = sighting.city.toLowerCase();\n return SightingCity === filterCity;\n });\n } else {search_data = search_data}; \n\n if (filterState){\n search_data = search_data.filter (function(sighting) {\n var SightingState = sighting.state.toLowerCase();\n return SightingState === filterState;\n });\n } else {search_data = search_data}; \n\n if (filterCountry){\n search_data = search_data.filter (function(sighting) {\n var SightingCountry = sighting.country.toLowerCase();\n return SightingCountry === filterCountry;\n });\n } else {search_data = search_data}; \n\n if (filterShape){\n search_data = search_data.filter (function(sighting) {\n var SightingShape = sighting.shape.toLowerCase();\n return SightingShape === filterShape;\n });\n } else {search_data = search_data}; \n\n\n } else {\n // Show full dataset when the user does not enter any serch criteria\n search_data = dataSet; \n }\n $('#table').DataTable().destroy(); \n renderTable(search_data); \n pagination_UFO(); \n}", "function _enableFiltersContextMenu() {\n if ($.isPlainObject(_options.filterSets) && !$.isEmptyObject(_options.filterSets)) {\n $(\".pfsd-filterinput\").contextmenu(function() {\n if ($(\"#pfsd-filter-box-context-menu\").length === 0) {\n var $contextMenu, tableBody = \"\",\n inputHeight = $(\".pfsd-filterinput\").css(\"height\").replace(\"px\", \"\") * 1,\n inputRight = $(\".pfsd-filterinput\").css(\"right\").replace(\"px\", \"\") * 1,\n inputTop = $(\".pfsd-filterinput\").css(\"top\").replace(\"px\", \"\") * 1,\n contextMenuBgColor = $(\".modal-header\").css(\"background-color\"),\n itemHightlight = $(\".modal-body\").css(\"background-color\");\n\n $.each(_options.filterSets, function (filterSetName, filterSet) {\n tableBody += Mustache.render(FilterBoxContextMenuItem, {\n filterSet: filterSet,\n filterSetName: filterSetName\n });\n });\n\n $contextMenu = $(Mustache.render(FilterBoxContextMenu, {\n tableBody: tableBody\n }));\n\n $contextMenu.css({\n \"position\": \"absolute\",\n \"display\": \"inline\",\n \"right\": inputRight,\n \"top\": inputTop + inputHeight + 10,\n \"background-color\": contextMenuBgColor\n });\n\n $(\".modal-header\").append($contextMenu);\n\n $contextMenu.on(\"mouseleave.pfsd\", function () {\n if ($contextMenu.length > 0) {\n $contextMenu.remove();\n }\n });\n\n $(\".pfsd-filter-item\").hover(\n function () {\n $(this).css(\"background-color\", itemHightlight);\n },\n function () {\n $(this).css(\"background-color\", contextMenuBgColor);\n }\n );\n\n $(\".pfsd-filter-item\").click(function () {\n var filterSetString = $(this).data(\"filterset\");\n $(\".pfsd-filterinput\").val(filterSetString);\n $contextMenu.remove();\n _enableFilterBox();\n });\n\n $(\".pfsd-filterinput\").one(\"click.pfsd\", function () {\n if ($(\"#pfsd-filter-box-context-menu\").length > 0) {\n $(\"#pfsd-filter-box-context-menu\").remove();\n }\n });\n }\n });\n }\n }", "render() {\n //Line below to be implemented when I can figure out proper query for the back end. \n const { searchTerm, filterOptions, filterOptionsCuisine } = this.props;\n // const { searchTerm } = this.props;\n if (searchTerm === \" \") {\n return 'No matching results'\n }\n const recipeList = this.props.recipes\n\n \n //Filters below to be implemented when I can figure out proper query for the back end. \n \n .filter(recipe => (recipe.meal_type === filterOptions || filterOptions === 'All'))\n .filter(recipe => (recipe.cuisine_type === filterOptionsCuisine || filterOptionsCuisine === 'All'))\n .filter(recipe => {\n return recipe.ingredients.some(ingredient => \n ingredient.toLowerCase().includes(searchTerm.toLowerCase()))\n })\n .map((recipe, key) => <RecipeDetail recipe={recipe} key={key} />);\n \n console.log(filterOptions);\n console.log(filterOptionsCuisine);\n return (\n <div className=\"FilterableList\">\n {recipeList}\n\n </div>\n );\n }", "function setFilter(){\r\n\tcallNavigateFilter({\r\n\t\ttxtName: $('nameFilter').value,\r\n\t\ttxtDesc: $('descFilter').value,\r\n\t\ttxtTitle: $('titleFilter').value,\r\n\t\tselPrj: $('projectFilter').value,\r\n\t\ttxtRegUser: $('regUsrFilter').value,\r\n\t\ttxtRegDate: $('regDateFilter').value,\r\n\t\tcubeType: $('cubeFilter').value,\r\n\t\tcmbType: $('typeFilter').value\r\n\t},null);\r\n}", "filterMatchingItems(item) {\n if (this.state.shelf_life === 'All' && this.state.type === 'All') {\n return true;\n } else if (this.state.shelf_life === 'All' && this.state.type === item.type) {\n return true;\n } else if (this.state.shelf_life === item.shelf_life && this.state.type === \"All\") {\n return true;\n } else if (this.state.shelf_life === item.shelf_life && this.state.type === item.type) {\n return true;\n } else {\n return false;\n }\n\n }", "function filterEmployee() {\n // Declare variables\n const input = document.querySelector('input');\n const filter = input.value.toUpperCase();\n let name = document.querySelectorAll('.name');\n const heading4 = document.querySelectorAll('h4')\n const card = document.querySelectorAll('.card');\n const btn = document.querySelector('button');\n\n\n // Loop through all employees name, and hide those who don't match the search query\n for (let i = 0; i < card.length; i++) {\n if (name[i].textContent.toUpperCase().includes(filter)) {\n showModalFunc(card[i]);\n } else {\n removeModalFunc(card[i]);\n }\n const clearFilter = (e) => {\n e.preventDefault();\n input.value = '';\n }\n }\n }", "function updateFilteredSearch(){\n \n if(typeof searchPnt != \"undefined\")\n findProviders(providerFS, searchPnt)\n }", "function menu_do_search() {\n\t// directly use the search page if it is active\n if (current === \"Special::Search\") {\n\t\td$('string_to_search').value = d$('menu_string_to_search').value;\n }\n woas.do_search(d$('menu_string_to_search').value);\n}", "function searchFunction() {\n let input = document.getElementById('myinput');\n let filter = input.value.toUpperCase();\n let ul = document.getElementById('catalog');\n \n html = '';\n for (let recipe of allRecipes) {\n let ingredientMatches = false;\n let allargiesMatches = false;\n\n for (let ingredient of recipe.recipeIngredients) {\n if(ingredient.toLowerCase().includes(input.value.toLowerCase())) {\n ingredientMatches = true;\n }\n }\n for (let allargies of recipe.recipeAllargies) {\n if(allargies.toLowerCase().includes(input.value.toLowerCase())) {\n allargiesMatches = true;\n } \n }\n if (recipe.recipeTitle.toLowerCase().includes(input.value.toLowerCase()) || ingredientMatches || allargiesMatches ){\n html += recipe.generateHTMLStructure()\n \n } \n document.getElementById('catalog').innerHTML = html\n let addToCartButtons = document.getElementsByClassName('btn-shop')\n for (var i = 0; i < addToCartButtons.length; i++) {\n var button = addToCartButtons[i]\n button.addEventListener('click', addToCartClicked)\n }\n\n }\n}", "excelFilter() {\n const that = this,\n context = that.context;\n\n if (Array.isArray(context.dataSource)) {\n that.customExcelFilter();\n return;\n }\n\n const tree = that.tree,\n filterObject = that.filterObject;\n\n filterObject.clear();\n that.customItems = [];\n\n if (tree._menuItems['0'].selected) {\n return;\n }\n\n const selectedIndexes = tree.selectedIndexes;\n\n selectedIndexes.forEach(function (index) {\n const item = tree._menuItems[index];\n\n if (item instanceof Smart.TreeItem) {\n const value = item.value;\n\n if (item.hasAttribute('default-item')) {\n const filterComparison = that.getExcelComparison(value),\n filter = filterObject.createFilter(context._filterType, value, filterComparison, undefined, context.formatString, context.locale, that.timeOnly);\n\n filterObject.addFilter('or', filter);\n }\n else {\n that.customItems.push(item);\n }\n }\n });\n that.cachedFilter = selectedIndexes.slice(0);\n }", "function filterSearch(id) {\n if (id === \"#chart_articletype\") return function(segmentData) {\n var selected = ES_REVERSE_MAPPING.st[segmentData.label].slice(3);\n for (var key in config.search.type) {\n if (key === selected) {\n config.search.type[key] = true;\n } else {\n config.search.type[key] = false;\n }\n }\n searchSubmit();\n }; else if (id === \"#chart_distribution\") return function(segmentData) {\n var selected = ES_REVERSE_MAPPING.sd[segmentData.label].slice(3);\n for (var key in config.search.distrib) {\n if (key === selected) {\n config.search.distrib[key] = true;\n } else {\n config.search.distrib[key] = false;\n }\n }\n searchSubmit();\n }; else /* id === \"#chart_pillar\" */ return function(segmentData) {\n getToolbarConfig(); // ensure that the checkboxes exist\n var selectedID = 'cb-pillar-' + segmentData.label;\n $('.pillar input').each(function(i) {\n var elem = $(this);\n if (elem.attr('id') === selectedID) {\n elem.prop('checked', true);\n } else {\n elem.prop('checked', false);\n }\n });\n searchSubmit();\n };\n}" ]
[ "0.69359624", "0.67341053", "0.6620461", "0.64346", "0.64267033", "0.6417425", "0.63756186", "0.6363611", "0.63424784", "0.6288425", "0.6265222", "0.6261493", "0.61923075", "0.6182552", "0.61806554", "0.61764234", "0.6154403", "0.6142961", "0.61308897", "0.6130747", "0.6115771", "0.61097574", "0.60570043", "0.60445696", "0.60437196", "0.6011892", "0.59944224", "0.5975083", "0.59695935", "0.59558594", "0.5953966", "0.5943022", "0.59420896", "0.591063", "0.5898489", "0.58703303", "0.58615243", "0.5854868", "0.5852492", "0.5848121", "0.5829059", "0.5823882", "0.5821477", "0.5814965", "0.58141375", "0.5813786", "0.5802798", "0.5801493", "0.5798466", "0.57975537", "0.5788881", "0.5783646", "0.5783577", "0.57799447", "0.57788056", "0.5777962", "0.5774592", "0.57706547", "0.5758958", "0.5758755", "0.5756046", "0.5755427", "0.5752784", "0.5752473", "0.5744223", "0.5742987", "0.57341176", "0.5732799", "0.57286537", "0.5726134", "0.5725933", "0.57179916", "0.57127386", "0.57122856", "0.570891", "0.5705637", "0.5693102", "0.56923544", "0.5691227", "0.56911266", "0.5681881", "0.56784296", "0.5677346", "0.56704134", "0.5667997", "0.5667176", "0.5666875", "0.56638026", "0.5657406", "0.5656191", "0.5655885", "0.56554276", "0.56534284", "0.5653189", "0.56520814", "0.5651617", "0.56505316", "0.56432724", "0.5640779", "0.56400716" ]
0.6856638
1
Loads the current items in the customers order
function loadOrder() { const postData = {orderId: sessionStorage.getItem("orderId")}; post("/api/authTable/getOrderItems", JSON.stringify(postData), function (data) { const orderMenuItems = JSON.parse(data); for (let i = 0; i < orderMenuItems.length; i++) { const item = orderMenuItems[i]; addItemToBasket(item); } calculateTotal(); }); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "_loadCustomerOrders() {\n const customerId = this.customerId;\n\n this.customerRenderer.showLoadingOrders();\n $.get(this.router.generate('admin_customers_orders', {customerId})).then((response) => {\n this.customerRenderer.renderOrders(response.orders);\n }).catch((e) => {\n showErrorMessage(e.responseJSON.message);\n });\n }", "function loadItems() {\n $itemList.empty();\n\n SDK.Items.getItems((err, items) => {\n if (err) throw err;\n\n\n items.forEach((item) => {\n\n //Sort items to a specific type\n if (item.itemType === type) {\n\n\n const itemHtml = `\n <div class=\"col-lg-4 item-container\">\n <div class=\"panel panel-default\">\n <div class=\"panel-heading\">\n <h3 class=\"panel-title\">${item.itemName}</h3>\n </div>\n <div class=\"panel-body\">\n <div class=\"col-lg-8\">\n <dl>\n <dt>Description</dt>\n <dd>${item.itemDescription}</dd>\n </dl>\n </div>\n </div>\n <div class=\"panel-footer\">\n <div class=\"row\">\n <div class=\"col-lg-4 price-label\">\n <p>Kr. <span class=\"price-amount\">${item.itemPrice}</span></p>\n </div>\n <div class=\"col-lg-8 text-right\">\n <button class=\"btn btn-success purchase-button\" data-item-id=\"${item.itemId}\">Add to basket</button>\n </div>\n </div>\n </div>\n </div>\n </div>\n \n `;\n\n $itemList.append(itemHtml);\n\n }\n });\n //Function to add items to basket\n $(\".purchase-button\").click(function () {\n const itemId = $(this).data(\"item-id\");\n const item = items.find((item) => item.itemId === itemId);\n SDK.Items.addToBasket(item);\n $(\"#purchase-modal\").modal(\"toggle\");\n });\n\n\n });\n }", "function getOrders() {\n return getItem('orders');\n}", "function loadOrders(){\n\t\t$.get(\"get_orders.php\", {scope:\"ALL\"}, function(orders_arr){\n\t\t\tfor(var i in orders_arr){\n\n\t\t\t\tvar OrdersTile = toOrdersHtml(orders_arr[i]);\n\t\t\t\t$('.inbox-page').append(OrdersTile);\n\t\t\t}\n\t\t});\n\t}", "function loadOrders(){\n orderService.orders().then(function(data){\n all_orders = data;\n povoateTable();\n setupDeleteListener();\n })\n}", "getOrderList() {\n return fetch('/api/orders/getMyOrders', {headers: {'authorization': localStorage.getItem('authorization')}}).then(function (response) {\n return response.json();\n }).then(function (result) {\n return result;\n }).catch(() => {\n NotificationManager.error(\"Ошибка\", 'Попробуйте позже');\n });\n }", "function CustomerOrders(){\n let url = 'https://localhost:5001/MainMenu/get/orders/' + localStorage.getItem('customerId');\n fetch(url)\n .then(response => response.json())\n .then(result => {\n document.querySelectorAll('#customerorderlist tbody tr').forEach(element => element.remove());\n let table = document.querySelector('#customerorderlist tbody');\n for(let i = 0; i < result.length; ++i)\n {\n let row = table.insertRow(table.rows.length);\n\n let locCell = row.insertCell(0);\n let location;\n if(result[i].locationId == 1) {location = \"Albany\";}\n if(result[i].locationId == 2) {location = \"Syracuse\";}\n if(result[i].locationId == 3) {location = \"Buffalo\";}\n locCell.innerHTML = location;\n\n let pCell = row.insertCell(1);\n pCell.innerHTML = result[i].totalPrice;\n\n let productCell = row.insertCell(2);\n for (let j = 0; j < result[i].orderItems.length; ++j){\n fetch('https://localhost:5001/Location/get/product/' + result[i].orderItems[j].productId)\n .then(result => result.json())\n .then(result => productCell.innerHTML += result.name + \" - \" + result.price + \", \");\n }\n }\n \n });\n}", "function initOrderList() {\n webservice.call($rootScope.baseURL + \"/order/all_open_orders\", \"get\").then(function (response) {\n vm.openOrders = response.data.dataRows;\n vm.openOrderCount = response.data.entries;\n console.log(response);\n // vm.categoriesList = response.data.dataRows;\n });\n }", "function loadItemsToList() {\n var shoppingItems = JSON.parse(localStorage.getItem(\"shoppingItems\"));\n for (let item of shoppingItems) {\n $( \"#CreateShoppinglist > ul\" ).append( \"<li>\" + item + \"</li>\" );\n }\n}", "loadNextOrders() {\n\t\tif (this.props.onLoadNextOrders) {\n\t\t\tthis.props.onLoadNextOrders();\n\t\t}\n\t}", "function loadGroceryItems()\r\n{\r\n\tvar items = localStorage.getObject(\"shoppinglist\");\r\n\tif( items != null ) {\r\n\t\t//check if items is an array\r\n\t\tif(_.isArray(items)) {\r\n\t\t\tgroceryItems = items;\r\n\t\t} else {\r\n\t\t\t// This will happen on first run\r\n\t\t\t//alert(\"Kauppalistan lataus ei onnistunut\");\r\n\t\t}\r\n\t}\r\n}", "function fetchItemsAction () {\n fetchTodoItems().then((response) => {\n return response.json()\n }).then((serverItemModel) => {\n if (serverItemModel.data) {\n viewState.items.length = 0\n serverItemModel.data.forEach((item) => {\n viewState.items.push(\n serverItemModelToClientItemModel(item)\n )\n })\n fillItems()\n }\n })\n}", "function loadCustomers() {\n $.ajax({\n url: \"/Customers\",\n type:\"GET\"\n }).done(function (resp) {\n self.Customers(resp);\n }).error(function (err) {\n self.ErrorMessage(\"Error!!!!\" + err.status);\n });\n }", "loadFromLocalStorage() {\n\t\t\tvar json = localStorage.getItem(\"cart\");\n\t\t\tthis.items = json ? JSON.parse(json) : [];\n\t\t}", "fetchItems() {\n this._$itemStorage.getAllItems().then((items) => {\n if (!angular.equals(items, this.items)) {\n if (!!this.reshuffle) {\n this.items = this.reshuffleItems(items);\n } else {\n this.items = items;\n }\n }\n });\n }", "function loadProductToCart() {\n let vProduct = JSON.parse(localStorage.getItem('products'));\n let vOrderDetail = JSON.parse(localStorage.getItem('orderDetail'));\n if (vProduct) {\n vProduct.forEach((productId, index) => {\n $.ajax({\n url: `${G_BASE_URL}/products/${productId}`,\n method: 'get',\n dataType: 'json',\n success: (product) => {\n renderProductToCart(product, index, vOrderDetail[index]);\n },\n error: (e) => alert(e.responseText),\n });\n });\n }\n }", "function items(details) {\n // TODO: Sync details for items;\n\n return $cart.items;\n }", "function getOrderList() {\n OrderFactory.GetOrderList($scope.pgOptions.pageNumber, $scope.pgOptions.itemsPerPage, $scope.listOptions)\n .then(function(data) {\n $scope.orderList = data.list;\n $scope.totalItems = data.total;\n $scope.pgOptions.pageNumber = data.page;\n processPagination();\n });\n }", "getListSiteByCustomer() {\n let self = this, curItem = this.state.curItem, params = {\n id_customer: !Libs.isBlank(this.user) ? this.user.id_user : null\n };\n CustomerViewService.instance.getListSiteByCustomer(params, (data, total_row) => {\n if (Libs.isArrayData(data)) {\n var findItem = Libs.find(data, 'site_default', true);\n if (!Libs.isObjectEmpty(findItem)) {\n curItem = Object.assign(curItem, findItem);\n } else {\n if (!Libs.isObjectEmpty(data[0]) && !Libs.isBlank(data[0].id)) {\n curItem = Object.assign(curItem, data[0]);\n } else {\n curItem = {};\n }\n }\n\n self.setState({ dataListSite: data, curItem: curItem }, () => {\n self.getCustomerViewInfo();\n });\n } else {\n curItem = {};\n self.setState({ dataListSite: [], curItem: curItem });\n }\n })\n }", "getOrder() {\n\t\tvar selectedRows = this.gridApi.getSelectedRows();\n\t\tvar orderId = selectedRows[0].orderId;\n\t\tlet orderIdEncr = encryptByAES(orderId);\n\t\tvar url = Config.serverUrl + '/ordersearch/ordersearch/orderDetailsByOrderId';\n\t\taxios.put(url, { \"orderId\" : orderIdEncr})\n\t\t.then(response => {\n\t\t\t\tthis.setState({ productList: response.data });\n\t\t\t\tthis.getProductDetail();\n\t\t\t});\n\t}", "function getItemsInCart(){\n\t\t\treturn items;\n\t\t}", "function loadProducts() {\n connection.query(\"SELECT item_id, product_name, department_name, price FROM products\", function (err, res) {\n if (err) throw err\n\n //display items in a table\n console.table(res);\n\n //then prompt the customer to choice of item\n promptCustomerOrder(res)\n });\n}", "_loadCustomerCarts(currentCartId) {\n const customerId = this.customerId;\n\n this.customerRenderer.showLoadingCarts();\n $.get(this.router.generate('admin_customers_carts', {customerId})).then((response) => {\n this.customerRenderer.renderCarts(response.carts, currentCartId);\n }).catch((e) => {\n showErrorMessage(e.responseJSON.message);\n });\n }", "function retrieveBoughtShoppingListItems(){\n var chosenBoughtList = localStorage.getItem(\"chosenBoughtList\");\n var boughtList = localStorage.getItem(chosenBoughtList);\n if(boughtList != null){\n boughtList = JSON.parse(boughtList);\n for (var i =0; i < boughtList.length; i++){\n $(\"#BoughtItemsList\").append(\"<li data-icon='delete'><a href='#'>\"\n + boughtList[i].name + \" <span class='ui-li-count'>Quantity: \"\n + boughtList[i].quantity +\"</span></a></li>\");\n }\n }\n}", "function onLoadProducts() {\n\tvar lsc = window.localStorage.length;\n\tfor (i = 0; i < lsc; i++) {\n\t\titem = JSON.parse(window.localStorage.getItem(i));\n\t\tvar itemKey = window.localStorage.key(i);\n\t\tif (item === null) {\n\t\t\tbreak;\n\t\t} else {\n\t\t\tvar quantityCount = document.getElementById(\"quantityCount\");\n\t\t\tquantityCount.innerText = item.quantity;\n\t\t\tdocument.getElementById(\"quantityCount\").style.visibility = \"visible\";\n\t\t}\n\t}\n}", "function getCustomerList() {\n\t// TODO: add logic to call backend system\n\n\n}", "function displayCurrentOrder(){\n\n // clear out the list to start fresh\n $('#current_order').empty();\n\n // get the current order\n let beverages = $('#order_form').find('input[name=\"beverages\"]').serializeArray();\n let kitchen = $('#order_form').find('input[name=\"kitchen\"]').serializeArray();\n let current_items = beverages.concat(kitchen);\n\n if(current_items.length >= 1){\n current_items.forEach(function(e){\n console.log(e);\n let order = JSON.parse(e.value);\n console.log(order);\n $('#current_order').append('<li class=\"borderless input-cafe\">'+ displayFriendlyItem(order.item) + ' for ' + order.name + '</li>');\n });\n }\n }", "function displayItems() {\n\tconsole.log(\"\\nWelcome, Customer!\");\n\tconsole.log(\"\\nItems available: \\n\");\n\tconnection.query(\"SELECT * FROM products\", function(err, res) {\n\t\tif (err) throw err;\n\t\t// console.log(res);\n\t\tfor (var i = 0; i < res.length; i++) {\n\t\t\tvar row = res[i];\n\t\t\tconsole.log(\"\\n----------\\n\");\n\t\t\tconsole.log(\"Item ID: \" + row.item_id);\n\t\t\tconsole.log(\"Product Name: \" + row.product_name);\n\t\t\tconsole.log(\"Price: $\" + row.price);\n\t\t};\n\t\tpromptCustomer();\n\t});\n}", "function loadProducts(){\n productService.products().then(function(data){\n all_products = data;\n setOptions();\n setupListeners();\n })\n}", "get items() {\n // Send the request\n return this._cartRequest('cart/items', {}, 'GET');\n }", "function loadWishlistItems(loader = 1) {\n \n var $url = $(\"body\").find('input[name=wishlistRoute]').val();\n var $CartItems = $(\"body\").find('#wishlistItems');\n // var $cartTotals = $(\"body\").find('#cartTotals');\n \t $.ajax({\n url : $url,\n \n type: 'GET', \n dataTYPE:'JSON',\n headers: {\n 'X-CSRF-TOKEN': $('input[name=_token]').val()\n },\n beforeSend: function() {\n if(loader == 1){\n \t $(\"body\").find('.custom-loading').show();\n }\n },\n success: function (result) {\n\n \tif(result.status == 1){\n \t\t$CartItems.html(result.data.items);\n \t\t// $cartTotals.html(result.data.amountDetail);\n \t}\n \n },\n complete: function() {\n $(\"body\").find('.custom-loading').hide();\n },\n error: function (jqXhr, textStatus, errorMessage) {\n \n }\n\n });\n }", "static async listCurrentOrders() {\n const query = `\n SELECT order.id AS \"orId\",\n order.customer_id AS \"cusId\",\n order.delivery_address AS \"addy\"\n FROM orders\n WHERE orders.completed = True\n `\n const result = await db.query(query)\n return result.rows\n }", "function populateCartOnLoad() {\n let cartItems = localStorage.getItem('cartItems');\n if (cartItems) {\n let cartItemsArray = JSON.parse(cartItems);\n document.querySelector('.cart-items').innerText = cartItemsArray.length;\n sendItemsToCartUI(cartItemsArray);\n grandTotals(cartItemsArray);\n }\n}", "getOrderItems() {\n let items = [];\n items.push({\n type: 'sku',\n parent: this.lineItems[0].sku,\n quantity: this.lineItems[0].quantity,\n })\n return items;\n }", "function initCartItems() {\n const lsCartItems = JSON.parse(localStorage.getItem(\"cartItems\"));\n if (lsCartItems) {\n setCartItems(lsCartItems);\n }\n }", "function fillOrderList(data) {\n var list = data == null ? [] : (data instanceof Array ? data : [data]);\n $('#itemList').find('li').remove();\n $.each(list, function (index, item) {\n $('#itemList').append('<li><a href=\"#\" data-identity=\"' + item.id + '\">' + item.customer + '</a></li>');\n });\n}", "function getOrderItemsCount() {\n AppOrdersService\n .getItemOrderedCount()\n .then(count => {\n vm.ItemOrderedCounter = count;\n });\n }", "function get_order(order) {\n store.setItem('active_order', order.id)\n $state.go('order_items', {order_id: order.id})\n }", "function getAllOrders(ordersLoaded) {\n // create and send a request to GET coffee orders\n let orderRequest = new XMLHttpRequest()\n orderRequest.open('GET', \"https://troubled-peaceful-hell.glitch.me/orders\")\n orderRequest.send()\n\n // addEventListener to populate orders array with data from request\n orderRequest.addEventListener('load', function() {\n const orders = JSON.parse(this.responseText)\n ordersLoaded(orders)\n })\n \n}", "function getProductsFromStorage() {\n // Set variable equal to previous orders in local storage\n let stringifiedOrders = localStorage.getItem('previousOrders');\n console.log(stringifiedOrders, \"out of storage\");\n\n // Take whatever was gotten out of storage and evaluate\n if (stringifiedOrders === null) {\n // If there is nothing in storage, make the new items and go through loop again\n makeProducts(); \n }\n\n if (stringifiedOrders !== null) {\n let parsedOrders = JSON.parse(stringifiedOrders);\n console.log(parsedOrders);\n for (let i = 0; i < parsedOrders.length; i++) {\n new Product(parsedOrders[i].name, parsedOrders[i].imgPath, parsedOrders[i].clicks, parsedOrders[i].timesShown)\n } \n }\n \n}", "function loadItems() {\n return fetch(\"data/data.json\")\n .then((res) => res.json())\n .then((json) => json.items);\n}", "getItems(){\n\t\tthis.setState({\n\t\t\titems: ItemsStore.getAll(),\n\t\t\tprogess: this.getProgress(),\n\t\t});\n\t}", "function readItems() {\n console.log(\"Getting Items for sale... \\n\");\n query = connection.query(\"Select * FROM products\", function (err, res) {\n if (err) {\n console.log(err);\n }\n console.log(\"<<<<<<<<< STORE >>>>>>>>>>>\");\n for (var i = 0; i < res.length; i++) {\n console.log(\n \"\\nID: \" +\n res[i].item_id +\n \" || ITEM: \" +\n res[i].product_name +\n \" || PRICE: \" +\n res[i].price\n )\n };\n shoppingCart();\n })\n}", "function getItems() {\n\t\tvar newItems = get('get-items.php?startDate='+$scope.startDate+';duration='+$scope.duration);\n\t\tconsole.log(newItems);\n\t}", "function getCartItems(){\n return cart_items;\n}", "function getOrdersByCustomers(cust) {\n $.ajax({\n url: \"/Customer/Orders/\" + cust.CustomerId,\n type:\"GET\"\n }).done(function (resp) {\n self.Orders(resp);\n }).error(function (err) {\n self.ErrorMessage(\"Error! \" + err.status);\n });\n }", "function loadOrders() {\n\n let tableItems = [];\n tableItems = JSON.parse(localStorage.getItem(tableName.toLowerCase()));\n console.log(\"tableItems= \" + tableItems);\n if (tableItems !== null) {\n document.getElementById(\"container\").style.opacity = 0.5;\n document.getElementById(tableName.toLowerCase()).style.backgroundColor =\n \"yellow\";\n document.getElementById(\"order-details\").style.opacity = 1;\n document.getElementById(\"order-details\").style.visibility = \"visible\";\n document.getElementById(\"check-out\").style.visibility = \"hidden\";\n $(\"#orders\").empty();\n // document.getElementById(\"orders\").innerHTML=\"\";\n if ($(\"#orders\").is(\":empty\")) {\n let columns =\n \"<tr><th>S.No</th><th>Item</th><th>Price</th><th style='opacity: 0'>.</th><th style='opacity: 0; width: 20px'>.</th></tr>\";\n $(columns).appendTo(\"#orders\");\n }\n let order = \"\";\n for (i = 0; i < tableItems.length; i++) {\n let price = localStorage.getItem(tableItems[i]);\n let itemServings = localStorage.getItem(tableName.toLowerCase()+\"-\"+tableItems[i]+\"-count\");\n console.log(itemServings);\n if(itemServings >= 1) {\n order +=\n \"<tr id='\" +\n tableItems[i] +\n \"'> <th style=' font-size: small; font-weight: 500; width:5%'>\" +\n (i + 1) +\n \"</th><th style='font-size: small; font-weight: 500; width:25%'>\" +\n tableItems[i] +\n \"</th><th style='font-weight: 500'>\" +\n price +\n \"</th> <th style='text-align: left'><p style='font-size: xx-small; margin-bottom: 0' class='servings'>Number of Servings</p><input type='number' id='quantity' name='count' class='counter-\"+tableName.toLowerCase()+\"' onchange='changeServings(event)' value='\"+itemServings+\"' min=1 style='border-top: none; border-left: none; border-right: none; border-bottom: 1px solid rgb(63, 62, 62);'/></th><th onclick='onDelete(event)'><i class='fas fa-trash'></i></th></tr>\";\n } else {\n order +=\n \"<tr id='\" +\n tableItems[i] +\n \"'> <th style=' font-size: small; font-weight: 500; width:5%'>\" +\n (i + 1) +\n \"</th><th style='font-size: small; font-weight: 500; width:25%'>\" +\n tableItems[i] +\n \"</th><th style='font-weight: 500'>\" +\n price +\n \"</th> <th style='text-align: left'><p style='font-size: xx-small; margin-bottom: 0' class='servings'>Number of Servings</p><input type='number' id='quantity' name='count' class='counter-\"+tableName.toLowerCase()+\"' onchange='changeServings(event)' value=1 min=1 style='border-top: none; border-left: none; border-right: none; border-bottom: 1px solid rgb(63, 62, 62);'/></th><th onclick='onDelete(event)'><i class='fas fa-trash'></i></th></tr>\";\n }\n\n }\n $(order).appendTo(\"#orders\");\n let newtotalPrice =\n \"<tr><th></th><th></th><th style='font-size: small; font-weight: 500 '>Total: <span id='total-price'>0.00</span></th></tr>\";\n $(newtotalPrice).appendTo(\"#orders\");\n let totalactualPrice = localStorage.getItem(\n tableName.toLowerCase() + \"-total-price\"\n );\n\n document.getElementById(\"total-price\").innerHTML = totalactualPrice;\n } else {\n alert(\"your dont have any current orders on this table\");\n }\n\n // order='';\n}", "function updateItemsOrder(){\r\n\t\t\r\n\t\tvar arrIDs = g_objItems.getArrItemIDs(false, true);\r\n\t\t\r\n\t\tvar data = {addons_order:arrIDs};\r\n\t\t\r\n\t\tdata = addCommonAjaxData(data);\r\n\t\t\r\n\t\tg_manager.ajaxRequestManager(\"update_addons_order\",data,g_uctext.updating_addons_order);\r\n\t}", "function order() {\n\t\t\t\n\t\t\t// Will hold all of the orderItems representing items. \n\t\t\tthis.items = [];\n\t\t\t\n\t\t\t// \n\t\t\tthis.getCountItemLanguage = function(){\n\t\t\t\t\n\t\t\t\t\n\t\t\t};\n\t\t\t\n\t\t\t// Add an item to the count\n\t\t\t\n\t\t}", "function basketOnLoad() {\n let fullOrderJson = localStorage.getItem(\"fullOrder\");\n // Parse local storage\n let fullOrder = JSON.parse(fullOrderJson);\n let basketList = document.getElementById(\"basketList\");\n // loop through each bun in bun array\n if (fullOrder == null) {\n // No buns to display\n console.log(\"No buns to display\");\n } else {\n // Buns in local storage\n console.log(\"Start bun display\");\n fullOrder.forEach(bun => {\n renderBunOrder(bun);\n });\n }\n return;\n}", "onProductsGet(ids) {\n if (!ids.length) return;\n\n let cb = this.cb((err, arr) => {\n if (err) throw err;\n _.each(arr, (item) => {\n // NOTE: items can arrive by the time they have already been filled in.\n if (cache.has(item.id)) return;\n // Save the item into cache.\n cache.set(item.id, item);\n });\n\n // Emit a single event saying we have these items now.\n // NOTE: reduces the amount of events being responded to.\n this.emit(`$cache`, 'new');\n });\n\n // Xhr then.\n this.xhrItems(ids, cb);\n }", "function getItems() {\n return httpService.get(\"api/putaway/getitems\",\n {\n WarehouseCode: vm.warehouseCode,\n SupplierCode: vm.supplierCode\n })\n .then(function (items) {\n vm.itemList.splice(0,vm.itemList.length);\n items.forEach(item => {\n item.IsSelected = (item.IsSelected == 1 ? true : false);\n vm.itemList.push(item);\n });\n });\n }", "function loadWorkOrder() {\n workOrder = JSONData.getObjectById( \"workOrders\", WorkOrder.getManageWorkOrderId() );\n }", "list(req, res) {\n return Order.findAll({\n include: [\n {\n model: Item,\n as: \"Items\"\n }\n ]\n })\n .then(orders => res.status(200).send(orders))\n .catch(error => res.status(400).send(error));\n }", "function onLoad() {\n let fullOrderJson = localStorage.getItem(\"fullOrder\");\n // Parse local storage\n let fullOrder = JSON.parse(fullOrderJson);\n if (fullOrder != null) {\n bunOrderArray = JSON.parse(localStorage.getItem(\"fullOrder\"));\n }\n basketCount();\n}", "function order() {\n var tableId = customersActiveTable;\n var orders = getOrders();\n var order;\n console.log(orders);\n\n for (let i = 0; i < orders.length; i++) {\n order = orders[i];\n console.log(order);\n newOrder(tableId, order[0], order[1]);\n }\n\n\n finnishCustomerSession();\n goToPrimaryMode(); // if there is primary mode that isn't customer some one has called it\n alert(\"Thank you for ordering!\");\n}", "function products() {\n connection.query('SELECT * FROM products', function(err, res) {\n console.table(res);\n console.log(chalk.yellow(\"***Enter 'Q' and press enter twice to exit store***\"));\n customerOrder();\n });\n}", "function loadContent() {\r\n var contentsStored = localStorage.getItem('contents');\r\n if (contentsStored) {\r\n contents = JSON.parse(contentsStored);\r\n $.each(contents, function (index, content) {\r\n var row = $('<tr>');\r\n var html = '<td>' + content.invoicedate + '</td>' +\r\n '<td>' + content.itemid + '</td>' +\r\n '<td>' + content.itemname + '</td>' +\r\n '<td>' + content.itemdesc + '</td>' +\r\n '<td>' + content.itemquantity + '</td>' +\r\n '<td>' + content.ItemUnitPrice + '</td>' +\r\n '<td>' + content.ItemCost + '</td>' +\r\n\r\n '<td><a class=\"delete\" href=\"#\">delete</a></td>';\r\n\r\n row.data().contentId = content.id;\r\n\r\n row.append(html);\r\n $(mainElement).find('table tbody').append(row);\r\n\r\n Subtotal = Subtotal + (content.itemquantity * content.ItemUnitPrice);\r\n Shipping = .085 * Subtotal;\r\n Tax = .11 * Subtotal + Shipping;\r\n Total = Subtotal + Shipping + Tax;\r\n });\r\n\r\n loadtotal();\r\n }\r\n }", "function retrieveShoppingListItems(){\n var chosenList = localStorage.getItem(\"chosenList\");\n $(\"#ShoppingListItemsHeading\").html(chosenList);\n var shoppingList = JSON.parse(localStorage.getItem(chosenList));\n if (shoppingList.length > 0){\n shoppingList = convertObjArrayToItemArray(shoppingList);\n for (var i = 0; i < shoppingList.length; i++){\n $(\"#ShoppingListItems\").append(\"<li data-icon='delete'><a href='#'>\"\n + shoppingList[i].name + \" <span class='ui-li-count'>Quantity: \"\n + shoppingList[i].quantity +\"</span></a></li>\");\n }\n }\n else{\n $(\"#ShoppingListItems\").append(\"<center><li style='color:red'>There are currently\" +\n \" no items to buy.<li></center>\");\n }\n}", "getAllItems() {\n var itemList = localStorage.getItem(this.DB_KEY_PRODUCT)\n if (itemList == null) {\n return new Array()\n }\n return JSON.parse(itemList)\n }", "async function obtenerItemsCarrito(){\r\n let carrito = await localStorage.getItem('carrito');\r\n if(carrito){\r\n carrito = JSON.parse(carrito);\r\n\r\n carrito.forEach(element => {\r\n document.getElementById('shopping-cart-items').innerHTML += \r\n `\r\n <div class=\"shopping-cart-item\">\r\n <img src=${element.imagen} alt=\"\" class=\"shopping-cart-item-img\">\r\n <div class=\"shopping-cart-item-data\">\r\n <input type=\"hidden\" class=\"idItem\" name=\"\" value=${element.id}>\r\n <p class=\"shopping-cart-item-nombre\">${element.nombre}</p>\r\n <p class=\"shopping-cart-item-precio\">Precio: $<span class=\"cart-item-precio\">${element.precio}</span></p>\r\n <p class=\"shopping-cart-item-cantidad\">Cantidad: <span class=\"cart-item-cantidad\">${element.cantidad}</span></p>\r\n </div>\r\n <i class=\"fas fa-trash eliminarItem\" onclick=\"deleteItem()\"></i>\r\n </div>\r\n `;\r\n });\r\n\r\n await mostrarTotales('subtotal', 'envio', 'total');\r\n }\r\n }", "function placeOrder() {\n updating = true;\n updateQuantity();\n getProducts();\n }", "list(req, res) {\n return OrderDetails.findAll({\n include: [\n {\n model: Item,\n as: \"Items\"\n }\n ]\n })\n .then(orders => res.status(200).send(orders))\n .catch(error => res.status(400).send(error));\n }", "function getItemsFromLocalStorage() {\r\n notesCount = localStorage.getItem(\"count\");\r\n notesFromLocalStorage = JSON.parse(localStorage.getItem(\"notes\"));\r\n }", "static getItems(orderId) {\n return db.execute(\n `SELECT * FROM orderitems WHERE orderId = ?`, [orderId]\n )\n .then(([orderItems, metaData]) => {\n for(let i = 0; i < orderItems.length; i++) {\n orderItems[i] = Object.assign(new OrderItem(), orderItems[i]);\n }\n return orderItems;\n })\n .catch(err => console.log(err));\n }", "function loadCartItems() {\n\n products = JSON.parse(localStorage.getItem('cart'))\n if (products !== null) {\n ids = Object.keys(products);\n $.ajax({\n type: \"GET\",\n url: \"/api/cart_products\",\n data: {'ids[]': ids},\n success: function (response) {\n if(response.length > 0) {\n setCartRows(response)\n } else {\n\n $('#cart_items').html(`<div class=\"row justify-content-center\"> \n <h3 class=\"text-grey\">\n Cart Empty\n </h3>\n </div>`);\n }\n },\n error: function (response) {\n console.log(response);\n },\n }); \n } else {\n $('#cart_items').html(html);\n }\n \n }", "function getOrders(orders) {\n //* Order have not loaded yet\n if (!orders) {\n return <></>\n }\n //* If the user has no orders\n if (orders.length === 0) return <></>\n //* Get all of the items\n const ordered = orders.reverse()\n return ordered.map(order => {\n return <OrderItem key={order.id} order={order} />\n })\n}", "function showProducts(){\n\tconnection.query('SELECT * FROM products', function(err, res){\n\t\tif (err) throw err;\n\t\tconsole.log('=================================================');\n\t\tconsole.log('=================Items in Store==================');\n\t\tconsole.log('=================================================');\n\n\t\tfor(i=0; i<res.length; i++){\n\t\t\tconsole.log('Item ID:' + res[i].item_id + ' Product Name: ' + res[i].product_name + ' Price: ' + '$' + res[i].price + '(Quantity left: ' + res[i].stock_quantity + ')')\n\t\t}\n\t\tconsole.log('=================================================');\n\t\tstartOrder();\n\t\t})\n}", "function getItems() {\n var storedDetails = JSON.parse(localStorage.getItem(\"details\"));\n var storedDetailsScore = JSON.parse(localStorage.getItem(\"detailsScore\"));\n\n if (storedDetails !== null) {\n details = storedDetails;\n detailsScore = storedDetailsScore;\n }\n renderDetails();\n}", "function manageDataCustomer() {\n $.ajax({\n dataType: 'json',\n url: '/customer/show',\n data:{page:page}\n }).done(function(data){\n manageRow(data.data);\n });\n }", "getOrderList(pageid = 1) {\n return fetch('/api/orders?page=' + pageid, {\n method: \"get\",\n headers: {'authorization': localStorage.getItem(\"authorization\")}\n }).then(function (response) {\n return response.json();\n }).then(function (result) {\n return result;\n }).catch(() => {\n NotificationManager.error('Ошибка');\n });\n }", "function getAllCustomers() {\n return datacontext.get('Product/GetAllCustomers');\n }", "function Items() {\n const categories = Object.keys(ORDER);\n\n return categories.map((category) => renderItems(ORDER[category]));\n}", "function getCustomers() {\n console.log('8');\n $.get(\"/api/customers\", renderCustomerList);\n }", "function getItems() {\n console.log(\"\\ngetItems clicked\");\n this_contract.getItemCount.call().then(function(value) {\n console.log(\"Number of items in store: \" + value.valueOf());\n var itemCount = value.valueOf();\n if (itemCount != 0) {\n for (var i = 0; i < itemCount; i++) {\n console.log(\"Item: \" + i);\n this_contract.getItem.call(i).then(function(value) {\n console.log(value);\n });\n }\n }\n else { console.log(\"Store is empty\"); }\n }).catch(function(e) {\n console.log(e);\n });\n}", "fetchOpenOrders() {\n if ( !this._apikey || !this._ajax ) return;\n\n this._ajax.get( this.getSignedUrl( '/v3/openOrders' ), {\n type: 'json',\n headers: { 'X-MBX-APIKEY': this._apikey },\n\n success: ( xhr, status, response ) => {\n response.forEach( o => this.emit( 'user_order', this.parseOrderData( o ) ) );\n this.emit( 'user_data', true );\n },\n error: ( xhr, status, error ) => {\n this.emit( 'user_fail', error );\n }\n });\n }", "function afterOrdersLoad() {\r\n $(userEditing());\r\n $(adminRejecting());\r\n $(checkRejection());\r\n $(checkRejectedChanges());\r\n }", "function listItemsInvoice() {\n var items = $(\"#items\").val();\n var company_id = $(\"#invoice_company_id\").val();\n \n $.get('/invoices/list_items/' + company_id, {\n items: items\n },\n function(data) {\n $(\"#list_items\").html(data);\n documentReady();\n });\n}", "function loadCustomerData(){\n\t\t$.ajax({\n\t\t\tdataType: \"json\",\n type: 'GET',\n data:{},\n url: getAbsolutePath() + \"customer/list\",\n success: function (data) {\n \t$.each(data.list, function( key, value ) {\n \t\tif(value.status == \"Active\")\n \t\t{\n\t $(\"#sltCustomer\").append($('<option>', { \t\n\t value: value.customercode,\n\t text: value.shortname\n\t }));\n \t\t}\n });\n },\n error: function(){\n \t\n }\n\t\t});\n\t}", "function getCustomers(res, mysql, context, complete){\n \tmysql.pool.query(\"SELECT C.cust_id, f_name, l_name, total FROM Shopping_cart SC INNER JOIN Customer C ON SC.cust_id = C.cust_id\", function(error, results, fields){\n \t\tif(error){\n res.write(JSON.stringify(error));\n res.end();\n }\n context.customer = results;\n complete();\n \t});\n }", "function buildCartList() {\n // $.getJSON('./cart.json', function(data){\n // // console.log(typeof(data))\n // cart = data[\"items\"];\n\n // });\n cartObj = JSON.parse(localStorage.getItem(\"cart\"))\n cart = cartObj[\"items\"];\n // console.log(cart);\n buildCartListHelper();\n}", "function loadLocalData(){\n if($scope.loading){\n return;\n }\n $scope.loading = true;\n storeService.getAllEntries(soup.name, sortBy, 'ascending').then(function(result){\n $scope.entries = result.currentPageOrderedEntries;\n console.log('entries', $scope.entries);\n $scope.loading = false;\n }, function(err){\n $scope.loading = false;\n });\n }", "function loadItems(){\n $.ajax({\n url: \"/items\",\n method: \"GET\",\n dataType: \"json\",\n success: function(items) {\n renderItems(items);\n }\n })\n}", "function init() {\n vm.products = orderService.getAll();\n }", "loadOrderBook() {\n this.state.exchange.LogOrderSubmitted({}, {fromBlock: 0, toBlock: 'latest'})\n .get((err, orders) => {\n for (let i = 0; i < orders.length; i++) {\n // confirm the order still exists then append to table\n this.state.exchange.orderBook_(orders[i].args.id, (err, order) => {\n if (order[4].toNumber() !== 0)\n this.addOrder(orders[i].args)\n })\n }\n })\n }", "getCustomers() {\r\n\t\tvar that = this;\r\n\t\t$.ajax({\r\n\t\t method: \"POST\",\r\n\t\t url: \"/ajaxgetcustomers\",\r\n\t\t data: { OrderID: that.orderId }\r\n\t\t})\r\n\t\t.done(function( resp ) {\r\n\t\t\tthat.CustomersData = resp;\r\n\t\t\tthat.setupCustomersListbox();\r\n\t\t\tthat.CustomersDone = true;\r\n\t\t\tthat.error = false;\r\n\t\t\treturn that.getOrder();\r\n\t\t\t\r\n\t\t})\r\n\t\t.fail(function(){\r\n\t\t\talert(\"Ajax Failed in getCustomers()\");\r\n\t\t\tthat.CustomersDone = false;\r\n\t\t\tthat.error = true;\r\n\t\t\treturn false;\r\n\t\t});\r\n\r\n }", "function getItemsFromLS(){\r\n if(localStorage.getItem('items')===null){\r\n items=[];\r\n }\r\n else{\r\n items = JSON.parse(localStorage.getItem('items'));\r\n }\r\n return items;\r\n}", "loadData() {\n console.log(this.order)\n return this.$http.get(ResolveRoute(`orders/${this.order}`)).then(resp => {\n return resp.json()\n }, err => {\n console.log(err)\n }).then(json => {\n // Clear out existing data\n this.reset()\n this.data = []\n\n // Transform into table data format\n json.forEach(oi => {\n this.data.push({\n itemId: oi.item.id,\n itemName: oi.item.name,\n units: oi.item.units,\n vendorName: oi.vendor.name,\n vendorId: oi.vendor.id,\n paidPrice: oi.paidPrice,\n totalAmount: oi.totalAmount,\n orderAmount: oi.orderAmount,\n editStatus: 'none'\n })\n })\n }, err => {\n console.log(err)\n })\n }", "function setProductsToOrder() {\n let products = [];\n if (checkLocalStorageKey(\"basket\")) {\n let productsInLocalStorage = getLocalstorageKey(\"basket\");\n for (let product in productsInLocalStorage.products) {\n let quantity = productsInLocalStorage.products[product].quantity;\n for (let i = 0; i < quantity; i++) {\n products.push(productsInLocalStorage.products[product].id);\n }\n }\n console.log(products);\n }\n order.products = products;\n}", "function adminOrdersFetchCall() {\n return request('get', urls.ADMIN_ORDER_URL);\n}", "function displayOrders() {\n\n let data = FooBar.getData();\n let json = JSON.parse(data);\n\n //------------------------------ORDERS IN QUEUE-------------------------------------------\n // queue template\n orderTemplate = document.querySelector(\"#queue-template\").content;\n orderParent = document.querySelector(\".orders-waiting-in-queue\");\n\n // clearing the space in template for necht items\n orderParent.innerHTML = '';\n\n // order id for each order and order items for each order\n json.queue.forEach(orderNumber => {\n let clone = orderTemplate.cloneNode(true);\n clone.querySelector('.order').textContent = `Order n. ${(orderNumber.id + 1)} - ${orderNumber.order.join(\", \")} `;\n orderParent.appendChild(clone);\n });\n //------------------------------SERVED ORDERS-------------------------------------------\n // serve template\n serveTemplate = document.querySelector(\"#orders-served\").content;\n serveParent = document.querySelector(\".in-serve\");\n\n // clearing space for served items\n serveParent.innerHTML = '';\n\n // served id for each order and served items for each order\n json.serving.forEach(servedOrder => {\n let clone = serveTemplate.cloneNode(true);\n clone.querySelector('.order-being-served').textContent = `Order nr. ${(servedOrder.id + 1)} - ${servedOrder.order.join(', ')}`;\n serveParent.appendChild(clone);\n\n })\n }", "function getCustomers() {\n CustomerService.getCustomers()\n .success(function(custs) {\n $scope.gridOpts.data = custs;\n })\n .error(function(error) {\n $scope.status = 'Unable to load customer data: ' + error.message;\n });\n }", "function refreshPage() {\n var where = {\n firstParm: 'archived',\n operater: '==',\n secondParm: true\n };\n\n return Q.all([\n datacontext.getEntityList(paymentsList, model.entityNames.customerPayment, false, null, null, 10, null, null, 'customerPaymentID desc'),\n datacontext.getEntityList(customerList, datacontext.entityAddress.customer, false, null, null, 10, null, null, 'customerID desc'),\n datacontext.getEntityList(achievedlist, datacontext.entityAddress.customer, false, null, where, null, null, null, 'customerID desc')]);\n }", "updateOrders() {\r\n $(\"#orders-log\").empty();\r\n this.alpaca.getOrders({\r\n status: \"open\"\r\n }).then((resp) => {\r\n resp.forEach((order) => {\r\n $(\"#orders-log\").prepend(\r\n `<div class=\"order-inst\">\r\n <p class=\"order-fragment\">${order.symbol}</p>\r\n <p class=\"order-fragment\">${order.qty}</p>\r\n <p class=\"order-fragment\">${order.side}</p>\r\n <p class=\"order-fragment\">${order.type}</p>\r\n </div>`\r\n );\r\n })\r\n })\r\n }", "getCustomer(){\n return(\n this.formState ?\n this.storage.getItem('customers', this.customerId) : {}\n )\n }", "function loadJson() {\n\t\tvar xmlhttp = new XMLHttpRequest();\n\t\txmlhttp.onload = function() {\n\t \tif (xmlhttp.status == 200) { //this.readyState == 4 not used with onload handler\n\t\t \t\tdocument.getElementById(\"vieworder\").innerHTML = xmlhttp.responseText;\n\t\t \tvar order = JSON.parse(xmlhttp.responseText);\n\t\t \tfillOrder(order);\n\t \t}\n\t\t}\n\t\txmlhttp.open(\"GET\", \"getOrder.json\", true);\n\t\txmlhttp.send();\n\t}", "function loadPendingOrders(orders, trader){\n for(var order of orders){\n if(order['tag'] == null) continue;\n var stock = order['tradingsymbol'];\n var order_id = order['order_id'];\n var orders_in_stock = this.orders[stock];\n if(orders_in_stock == null){\n orders_in_stock = {}\n this.orders[stock] = orders_in_stock;\n }\n orders_in_stock[order_id] = {order, trader};\n }\n}", "function getLocalItems() {\n let recentCities = localStorage.getItem(\"recentCities\");\n return JSON.parse(recentCities);\n}", "function load(){\n\t$.ajax({\n\t\turl: baseUrl+'/fetch/orders',\n\t\ttype: 'GET',\n\t\tsuccess: function(response) {\n\t\t\tif(response.status==\"success\"){\n\t\t\t\t//alert(\"product fetched successfully\")\n\t\t response.data.forEach(function(row){\n\t\t \tfor(var key in row){\n\t\t \t\tif(row[key]==undefined || row[key]==null)\n\t\t \t\t\trow[key] = \"0\"\n\t\t \t}\n\t\t \t$(\"#tblOrders\").append(\"<tr><td>\"+row.OrderID+\"</td><td>\"+row.ProductName+\"</td><td>\"+row.Quantity+\"</td><td>\"+row.CreatedTillNow+\"</td><td>\"+row.Predicted+\"</td><td><button id='btnStatusUpdate'>Done</button></td></tr>\")\n\t\t })\n\t\t\t}\n\t\t\telse{\n\t\t\t\talert(\"No orders fetched ! Try Again\")\n\t\t\t\treturn;\n\t\t\t}\n\t\t},\n\t\terror: function(e) {\n\t\t\talert(\"Some server occured ! Orders could not be fetched\");\n\t\t}\n\t});\n}", "getAvailableItems() {\n // Call the function to load all available items\n var data = autocomplete.cloudLoadAvailableItems();\n return data;\n }" ]
[ "0.6690897", "0.6674371", "0.6672024", "0.64448595", "0.63485616", "0.61880577", "0.61743045", "0.60866195", "0.606847", "0.6049835", "0.6037822", "0.60345554", "0.59790266", "0.59779674", "0.5976755", "0.5972953", "0.594452", "0.59320724", "0.5925187", "0.5918101", "0.5911777", "0.59101564", "0.5907078", "0.59000844", "0.5897391", "0.58677244", "0.5861927", "0.5856177", "0.58448625", "0.5841061", "0.58370686", "0.5835961", "0.5819592", "0.5776672", "0.57702625", "0.57670546", "0.57593316", "0.57435423", "0.57401603", "0.57400215", "0.5730036", "0.57241964", "0.5713272", "0.5712297", "0.57108015", "0.57076913", "0.5704825", "0.57040507", "0.56921923", "0.569134", "0.56859684", "0.568559", "0.56842077", "0.5681828", "0.5679867", "0.56687355", "0.56680334", "0.56668293", "0.5648726", "0.5640905", "0.56147295", "0.5614567", "0.56099004", "0.56049967", "0.5603452", "0.56004125", "0.5597957", "0.5594164", "0.55934316", "0.55933386", "0.5589757", "0.5589337", "0.5585694", "0.5578412", "0.55777705", "0.5574965", "0.55733496", "0.5572982", "0.55694735", "0.5562652", "0.5558026", "0.555337", "0.5551426", "0.5549898", "0.55398685", "0.55331945", "0.5524188", "0.55238307", "0.55233055", "0.55177796", "0.55161905", "0.5516162", "0.5515393", "0.55148906", "0.5506582", "0.55062276", "0.5499708", "0.54960406", "0.5486671", "0.5486664" ]
0.70957613
0
Adds an item to the customers basket.
function addItemToBasket(item) { const parent = $("#order"); // Add item basket.push(item); parent.append("<li id='ordermenuitem-" + item.id + "' class='list-group-item list-group-item-action'>\n" + " <span class='bold'>" + item.name + "</span>" + " <span class='span-right'>£" + item.price + "</span>\n" + " <br>\n" + " <span id='omi-instructions-" + item.id + "'><span id='omi-instructions-" + item.id + "-text'>" + item.instructions + "</span></span>\n" + " <span class='span-right'><i id='omi-edit-" + item.id + "' class='fa fa-edit fa-lg edit' onclick='showEditOrderMenuItem(" + item.id + ", \"" + item.instructions + "\");'></i><i class='fa fa-times fa-lg remove' onclick='confirmRemoveOrderMenuItem(" + item.id + ");'></i></span>\n" + "</li>"); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function addItem(item) {\n basket.push(item);\n return true;\n}", "function addItemToCart() {}", "function addItemToCart() {}", "function AddItem(item){\n console.log(\"Adding \" + item.Name + \" to the basket!\");\n basket.push(item);\n}", "function addItemToCart(user, item) {}", "function addItem(item) {\n var foundItem = false;\n\n // if there's another item exactly like this one, update its quantity\n _.each(bag.getItems(), function(curItem) {\n if (curItem.name == item.name && curItem.size == item.size &&\n curItem.price == item.price && curItem.color == item.color) {\n curItem.quantity += item.quantity;\n foundItem = true;\n }\n });\n\n // otherwise, add a new item\n if (!foundItem) {\n bag.addItem(item);\n } else {\n var items = bag.getItems();\n\n // item was updated, re-render\n renderItems(items);\n renderTotalQuantityAndPrice(items);\n }\n }", "function addItem(item) {\n if (isFull(basket) === true) {\n console.log(`Basket is currently full. Could not add ${item}`);\n return false;\n } else {\n basket.push(item);\n return true;\n }\n}", "function plusItem() {\n const productId = this.name;\n const cartList = JSON.parse(sessionStorage.getItem(\"shoppingCartItems\"));\n const item = cartList.find(product => product.id == productId);\n cartList.push(item);\n sessionStorage.setItem(\"shoppingCartItems\", JSON.stringify(cartList));\n shoppingCartCount();\n populateShoppingCartPage();\n}", "function addToCart(item) {\n\t// create item in cart\n\tconst row = document.createElement('tr');\n\n\trow.innerHTML = `\n\t\t<td>\n\t\t\t<img src=\"${item.image}\">\n\t\t</td>\n\t\t<td>\n\t\t\t${item.title}\n\t\t</td>\n\t\t<td class=\"data-price\" data-price=\"${item.priceData}\">\n\t\t\t${item.price}\n\t\t</td>\n\t\t<td>\n\t\t\t<ion-icon name=\"close\" class=\"remove\" data-id=\"${item.id}\"></ion-icon>\n\t\t</td>\n\t`;\n\n\tshoppingCartCont.appendChild(row);\n\n\t// calculate price\n\tcalculatePrice(item);\n\n\t// update count of items in 'itemAmount'\n\titemAmount.innerHTML = shoppingCartCont.childElementCount;\n\n\t// apply 'in basket' effect\n\tif (shoppingCartCont.childElementCount > 0) {\n\t\titemAmount.classList.add('active');\n\t}\n\n\t// save item into local storage\n\tsaveIntoStorage(item);\n}", "_addNewItem() {\n // Add new Item from Order's Items array:\n this.order.items = this.order.items.concat([this.item]);\n // Update current Order:\n this.orderService.setCurrentOrder(this.order);\n this._closeAddNewItem();\n }", "function addToOrder(itemId, instructions) {\n const dataToSend = JSON.stringify({\n menuItemId: itemId,\n instructions: instructions,\n orderId: sessionStorage.getItem(\"orderId\")\n });\n\n post(\"/api/authTable/addItemToOrder\", dataToSend, function (data) {\n if (data !== \"failure\") {\n const item = JSON.parse(data);\n addItemToBasket(item);\n calculateTotal();\n }\n })\n}", "function addItem( item ){\n cart.push(item);\n return cart;\n}", "function addItemToCart(user, item) {\n\n}", "function addItem(sku, quantity) {\n quantity = _.isNumber(quantity) ? quantity : 1;\n\n $lastPromise = $$\n .postCartItems({\n sku: sku,\n quantity: quantity\n })\n .then(onSyncd);\n\n return _this_;\n }", "function addItemToCart(item, itemQuantity){\n if(isNaN(itemQuantity)){\n itemQuantity = 1; \n }\n var itemIsNew = true; \n cart.forEach(function (cartItem){\n if(cartItem.name === item.name){\n cartItem.quantity += itemQuantity; \n updateQuantityDisplay(cartItem); \n return itemIsNew = false\n } \n })\n if(itemIsNew){\n cart.push(item); \n item.quantity = itemQuantity; \n displayItem(item, itemQuantity, \".cart-container\")\n }\n}", "addItemsToCart() {\n\n Model.addItemsToCart(this.currentItems);\n }", "addItem(item) {\n this.items.push(item);\n // tegye közzé a frissített elemek listáját, hogy frissítse a Cart topic-ot\n // amikor a cart tartalma frissült\n PubSub.publish(\"updateCart\", this.getItems());\n }", "add_item(item){\n this.cart.push(item);\n }", "addItem(item)\r\n\t{\r\n\t\tif (typeof item != 'object') {\r\n\t\t\tthrow new InvalidArgumentException('addItem() expect the first parameter to be an object, but ' + typeof item + ' was passed instead');\r\n\t\t}\r\n\r\n\t\tif (! item.hasOwnProperty('id')) {\r\n\t\t\tthrow new InvalidCartItemException;\r\n\t\t}\r\n\r\n\t\tthis.cart = Cookie.get(this.settings.cookie_name);\r\n\r\n\t\tif (!item.hasOwnProperty('quantity')) {\r\n\t\t\titem.quantity = 1;\r\n\t\t}\r\n\r\n\t\tlet i;\r\n\t\tlet incremented = false;\r\n\r\n\t\tfor (i = 0; i < this.cart.items.length; i++) {\r\n\t\t\tif (this.cart.items[i].id == item.id) {\r\n\t\t\t\tthis.cart.items[i].quantity++;\r\n\t\t\t\tincremented = true;\r\n\t\t\t\tbreak;\t\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tif (! incremented) {\r\n\t\t\tthis.cart.items.push(item);\r\n\t\t}\r\n\r\n\t\tCookie.set(this.settings.cookie_name, this.cart, 2);\r\n\t}", "function addToInvoice( newItem ){\n\t\t\n\t\t// console.log( \"adding newItem: \" + newItem.ID);\n\t\t// add product to cart\n\t\tcart.push(newItem);\n\t\t\n\t\t// items total cost\n\t\tcart.itemsCost \t+= parseFloat(newItem.PriceSAR, 10);\n\t\tcart.itemsCost\t= parseFloat(cart.itemsCost.toFixed(4)) ;\n\t\t\n\t\tcart.itemsTax\t+= parseFloat(newItem.TaxSAR, 10) ;\n\t\tcart.itemsTax\t= parseFloat(cart.itemsTax.toFixed(4)) ;\n\t\t\n\t\t// items total shipping cost\n\t\tcart.shippingCost \t+= parseFloat(newItem.ShippingCost, 10);\n\t\tcart.shippingCost\t= parseFloat(cart.shippingCost.toFixed(4)) ;\n\t\t// console.log( cart.totalCost)\n\t\t\n\t\t// item tax\n\t\tcart.invoiceCost\t= cart.itemsCost + cart.shippingCost + cart.itemsTax;\n\t\tcart.invoiceCost\t= parseFloat(cart.invoiceCost.toFixed(4));\n\t\t\n\t\t// update invoice\n\t\tupdateInvoice();\n\t\t\n\t\tmycart = cart;\n\t}", "add(event, item) {\n event.preventDefault();\n this.props.addToBasket({\n product_id: item.product_id,\n product_name: item.product_name,\n product_images: item.product_images,\n product_price: item.product_price\n })\n }", "add(id, product) {\n // if an item exists in the cart\n const item = this.items[id]\n ? new CartItem(this.items[id])\n : new CartItem({ id, product });\n\n // increment the items quantity\n item.qty += 1;\n // Update the items price\n item.price = item.product.price * item.qty;\n\n this.items = {\n ...this.items,\n [id]: item\n };\n }", "function add(item) {\n data.push(item);\n console.log('Item Added...');\n }", "add(item, Inventory) {\n\n if (!this.isValid(item)) {\n throw \"Invalid item input, expected [SKU QUANTITY]\";\n }\n\n item = this.normalize(item);\n\n if (this.items.filter(i => i[0] == item[0]).length) { // item with SKU exists already\n this.items = this.items.map(\n i => {\n // check for availability of the item in the Inventory\n if (!Inventory.available([item[0], item[1] + i[1]])) {\n throw \"Can't add item to cart\";\n }\n\n // when the SKU of the newly added item matches the item in the inventory, just add amount\n if (i[0] == item[0]) {\n i[1] += item[1];\n }\n return i;\n }\n );\n } else { // no item with matching SKU found, add the item to the cart\n // check for availability of the item in the Inventory\n if (!Inventory.available(item)) {\n throw \"Can't add item to cart\";\n }\n this.items.push(item);\n }\n }", "function addItem(id){\r\n\tif(order.hasOwnProperty(id)){\r\n\t\torder[id] += 1;\r\n\t}else{\r\n\t\torder[id] = 1;\r\n\t}\r\n\t//gets the current restaurant and ensures that it is not undefined\r\n\ttemp = getCurrentRestaurant();\r\n\tif (temp !== undefined){\r\n\t\tupdateOrder(temp);\r\n\t}\r\n}", "function addOneItemToCart() {\n var itemID = $(this).attr(\"id\");\n var positionInCart = itemID.slice(12, itemID.length);\n cartItems[positionInCart][3] += 1;\n updateCartDetails();\n}", "function addToBasket(prodID, prodName, prodColour, prodSize, prodPrice, prodImage){\n let basket = getBasket();//Load or create basket\n\n //Add product to basket\n basket.push({id: prodID, name: prodName, colour:prodColour, size:prodSize, price:prodPrice, image_url:prodImage});\n\n //Store in local storage\n sessionStorage.basket = JSON.stringify(basket);\n\n //Display basket in page.\n loadBasket();\n}", "function addToBasket(detail) { }", "function addBasket() {\n if (basket.length === 0 || (basket.find(x => x.name === item.name)) === undefined) {\n item.quantity = updatedQuantity\n basket.push(item)\n } else {\n for (let i=0; i < basket.length; i++) {\n if (basket[i].name === item.name) {\n basket[i].quantity = basket[i].quantity + updatedQuantity\n } \n }\n }\n productTotal();\n basketCount();\n localStorage.setItem(\"savedBasket\", JSON.stringify(basket));\n}", "add() {\n\t\torinoco.cart.add({ imageUrl: this.imageUrl, name: this.name, price: this.price, _id: this._id });\n\t}", "function addItemToShoppingList(itemName) {\n console.log(`Adding \"${itemName}\" to shopping list`);\n STORE.items.push({name: itemName, checked: false});\n}", "function addItem() {\n\t\t\tvar order = ordersGrid.selection.getSelected()[0];\n\n\t\t\titensStore.newItem({\n\t\t\t\tpi_codigo: \"new\" + itensCounter,\n\t\t\t\tpi_pedido: order ? order.pe_codigo : \"new\",\n\t\t\t\tpi_prod: \"\",\n\t\t\t\tpi_quant: 0,\n\t\t\t\tpi_moeda: \"R$\",\n\t\t\t\tpi_preco: 0,\n\t\t\t\tpi_valor: 0,\n\t\t\t\tpi_desc: 0,\n\t\t\t\tpi_valort: 0,\n\t\t\t\tpr_descr: \"\",\n\t\t\t\tpr_unid: \"\"\n\t\t\t});\n\t\t\t\n\t\t\titensCounter = itensCounter + 1;\n\t\t}", "function addItem() {\n\n console.log('adding', { amount }, { name });\n\n dispatch({\n type: 'ADD_ITEM', payload: {\n name: name,\n amount: amount,\n list_id: id,\n }\n })\n //reset local state of new item textfield to allow for more items to be added\n setName('');\n setAmount(1);\n }", "function buyItem(e) {\n\te.preventDefault();\n\n\t// find item was added\n\tif (e.target.classList.contains('add-to-cart')) {\n\t\tconst item = e.target.parentElement.parentElement.parentElement;\n\n\t\t// get item info\n\t\tgetItemInfo(item);\n\t}\n}", "function addItemToShoppingList(itemName) {\n store.push({id: cuid(), name: itemName, checked: false});\n}", "function addToCartHandler(item, quantity) {\n\t\tsetUserCart(prev => {\n\t\t\tconst prevCopy = [...prev];\n\t\t\tconst foundItemIndex = prevCopy.findIndex(\n\t\t\t\tcopyItem => copyItem.id === item.id\n\t\t\t);\n\t\t\tif (foundItemIndex >= 0) {\n\t\t\t\tconst newQuantity = prev[foundItemIndex].quantity + quantity;\n\t\t\t\tprevCopy.splice(foundItemIndex, 1, { ...item, quantity: newQuantity });\n\t\t\t\treturn prevCopy;\n\t\t\t} else {\n\t\t\t\treturn prev.concat({ ...item, quantity: quantity });\n\t\t\t}\n\t\t});\n\t}", "function addSelectedItemToCart() {\n // TODO: suss out the item picked from the select list\n var product = event.target.items.value;\n var quantity = event.target.quantity.value;\n cart.addItem(product, quantity);\n counter++;\n console.log(counter);\n // TODO: get the quantity\n // TODO: using those, add one item to the Cart\n}", "function addItem (name, quantity) {\n if(cart[name] == undefined) {\n createItem(name);\n }\n cart[name] = cart[name] + quantity;\n}", "function addItem(item){\n if (isFull() === true){\n console.log(`${item} cannot be added, basket is full. Returning false.`);\n return false\n } else {\n basket.push(item);\n console.log(`${item} successfully added to basket. Returning true`)\n return true;\n }\n}", "function addToCart(item) {\n var ss = getCart()\n // the item is then pushed into the array ss which stores it in a session storage.\n ss.push(item)\n sessionStorage.setItem(\"cart\", JSON.stringify(ss))\n}", "function addItemToShoppingCart(item) {\n\t$('#shopping-cart ul').append(`\n\t\t<li>\n\t\t\t${item}\n\t\t</li>\n\t`);\n}", "function addCartItem(form, material, color, text, textColor, qty, unitCost) {\n\tlet model = makeModelNumber(form, material, color);\n\n\t// look for existing items based on the model number. but we'll keep customized\n\t// items as their own cart line item, so be sure not to match if text exists.\n\tlet existingItem = _.find(cart, (c) => {\n\t\treturn (c.model === model) && !c.text;\n\t});\n\n\tif (existingItem) {\n\t\texistingItem.qty += qty;\n\t}\n\telse {\n\t\tlet newItem = {\n\t\t\tid: uuidv4(),\n\t\t\tmodel,\n\t\t\tform,\n\t\t\tmaterial,\n\t\t\tcolor,\n\t\t\ttext,\n\t\t\ttextColor,\n\t\t\tqty,\n\t\t\tunitCost\n\t\t};\n\n\t\tcart.push(newItem);\n\t}\n}", "function addProductToCart(product) {\n let cart = getCart();\n cart.items.push(product);\n\n setCart(cart);\n alert(product.name + ' added to cart, Total is R' + getTotal(cart));\n}", "function addToOrder(item) {\n var table = getCurrentTable();\n //Checks that the order isn't full(above 10)\n if(checkFullOrder(table.item_id))\n {\n return;\n }\n var key;\n //Depending where it was added from, the variable item is different\n if (item.includes(':')) {\n key = getIdFromName(item.split(': ')[0]);\n } else {\n key = getIdFromName(item.slice(0, -1));\n }\n if (key in table.item_id) {\n table.item_id[key] = table.item_id[key] + 1;\n } else {\n table.item_id[key] = 1;\n }\n showOrder(currentTableID);\n return;\n}", "addItem(newItem) {\n for (let index in this.items) {\n let item = this.items[index];\n if (item.id === newItem.id) {\n item.quantity += newItem.quantity;\n this.updateTotal();\n return;\n }\n }\n\n this.items.push(newItem);\n this.updateTotal();\n }", "function addCartItem(prod) {\n const inCart = cart.find(i => i.id === prod.id);\n\n if (!inCart) {\n changeOfAmountAndAvailableInProductList(prod);\n addProductToCart(prod);\n }\n\n if (inCart) {\n changeOfAmountAndAvailableInProductList(prod);\n changeOfAmountAndAvailableInCart(prod);\n }\n }", "function addItemToEbay() {\r\n addToEbay.value = '1';\r\n }", "function addToCart(newItem, itemQuantity, itemPrice) {\n\n for (let i = 0; i < cartItems.length; i++) {\n if (cartItems[i].item === newItem) {\n cartItems[i].quantity += itemQuantity;\n total()\n\n return\n }\n }\n\n setCartItems([...cartItems, {\n item: newItem,\n quantity: itemQuantity,\n price: itemPrice\n }])\n\n\n total()\n }", "function addItemToCart(user, item) {\n amazonHistory.push(user)\n const updateCart = user.cart.concat(item)\n return Object.assign({}, user, { cart: updateCart })\n}", "function addItem(){\n var itemName = $(\"#spinlabel\").html();\n var quantity = $(\"#spin\").val();\n for(var i = 0; i < CurrentShoppingListArray.length; i++){\n if(itemName == CurrentShoppingListArray[i].name){\n CurrentShoppingListArray[i].quantity = parseInt(CurrentShoppingListArray[i].quantity) + parseInt(quantity);\n return;\n }\n }\n var tempItem = new Item(itemName, quantity);\n CurrentShoppingListArray.push(tempItem);\n}", "function addItem(id) {\n // clear session storage\n // sessionStorage.clear();\n\n // check to see if a cart key exists in session storage\n if (sessionStorage.getItem('cart')) {\n // if it does, set a local cart variable to work with, using the parsed string //JSON is js library\n var cart = JSON.parse(sessionStorage.getItem('cart'));\n } else {\n // if it does not exist, set an empty array\n var cart = [];\n }\n\n // loop through global products variable and push to Cart\n for (let i in products) {\n if (products[i].id == id) {\n cart.push(products[i]);\n break;\n }\n }\n\n // // call total function to update\n // calcTotal();\n\n // store the cart into the session storage\n sessionStorage.setItem('cart', JSON.stringify(cart));\n }", "addToCart(newItem) {\n let itemExisted = false\n let updatedCart = this.state.cart.map(item => {\n if (newItem === item.sku) {\n itemExisted = true\n return { sku: item.sku, quantity: ++item.quantity }\n } else {\n return item\n }\n })\n if (!itemExisted) {\n updatedCart = [...updatedCart, { sku: newItem, quantity: 1 }]\n }\n this.setState({ cart: updatedCart })\n // Store the cart in the localStorage.\n // localStorage.setItem('stripe_checkout_items', JSON.stringify(updatedCart))\n }", "function addToCart()\n\t{\n\t\t// avoid adding to cart before the item info is fetched\n\t\t// if( product.ASIN === undefined) return ;\n\t\tif( product === undefined) return ;\n\t\t\n\t\tvar newItem = Object.assign({}, product); \n\t\tnewItem.ID \t\t= Date.now();\n\t\t\n\t\t// console.log( \"product id: \" + newItem.ID );\n\t\tnewProduct = \"<tr>\"\n\t\t\t\t\t\t+ \"<td><img src=\\\"\"+ newItem.Image_url + \"\\\" class=\\\"thumbnail\\\" /> </td>\"\n\t\t\t\t\t\t+ \"<td>\"+ newItem.Color\t\t\t+\"</td>\"\n\t\t\t\t\t\t+ \"<td>\"+ newItem.Size\t\t\t+\"</td>\"\n\t\t\t\t\t\t+ \"<td>\"+ newItem.PriceSAR\t\t+\" ريال</td>\"\t\t\t\t\t\t\n\t\t\t\t\t\t+ \"<td>\"+ newItem.TaxSAR\t\t+\" ريال</td>\"\t\t\t\t\t\t\n\t\t\t\t\t\t+ \"<td>\"+ newItem.ShippingCost\t+\" ريال </td>\"\t\t\t\t\t\t\n\t\t\t\t\t\t+ \"<td> <i class='fi-x removeItem button alert' id='\"+ newItem.ID +\"'></i></td>\"\n\t\t\t\t\t\t+ \"</tr>\";\n\t\t\t\t\t\t\n\t\t$('#items > tbody:last-child').append(newProduct);\n\t\t$(\"#addToCartBtn\").notify(\"تم إضافته لسلة المشتريات\", {className:\"success\"});\n\t\t$(\"#itemsList\").slideDown();\n\t\t\n\t\t// save cart\n\t\tsaveCart(\"add\", newItem.ID);\n\t\t\n\t\t// start observer for remove from cart button\n\t\tobserveRemoveBtn();\n\t\t\n\t\t// add to invoice\n\t\taddToInvoice(newItem);\n\t}", "addItemToCart ({ commit }, item) {\n commit(mutationTypes.ADD_ITEM_TO_CART);\n return cartStateApi.addItemToCart(item.cartId, item)\n .then(response => {\n commit(mutationTypes.ADD_ITEM_TO_CART_SUCCESS, response.data);\n })\n .catch(error => console.log('ERROR adding an item to the cart ', error));\n }", "function addItem(restaurant, item) {\n let restaurant = findRestaurant(restaurant)\n restaurant.items.push(item)\n return restaurant\n}", "function addItem(item){\r\n\tvar found = false;\r\n\tfor(var i =0; i < inventory.length; i++){\r\n\t\tif(inventory[i].name == item.name){\r\n\t\t\tinventory[i].qty += item.qty;\r\n\t\t\tfound = true;\r\n\t\t\tbreak;\r\n\t\t}\r\n\t}\r\n\tif(!found){\r\n\t\tinventory.push(assignItem(invMaster[item.name]));\r\n\t}\r\n}", "function addItem(item) {\n $state.go('main.addItem', {item: item, foodListId: $stateParams.foodListId});\n }", "function addItem(buttonID) {\n\tvar quant = 1;\n\tvar exists = false;\n\tvar name = itemList[buttonID][0];\n\tvar price = itemList[buttonID][1];\n\tif (shopList.length !== 0) {\n\t\tfor (i = 0; i < shopList.length; i ++) {\n\t\t\tif (shopList[i][0] === name) {\n\t\t\t\tshopList[i][2] += quant;\n\t\t\t\texists = true;\n\t\t\t}\n\t\t}\n\t}\n\tconsole.log(shopList);\n\t\n\tif (!exists) {\n\t\tvar newItem = [name, price, quant];\n\t\tshopList.push(newItem);\n\t}\n\tnumItems++;\n\tupdateItemInfo(numItems, name, price);\n\tshopList.sort();\n}", "addItem(item) {\n\t // makes a copy of state\n\t const newItems = this.state.inventoryItems;\n\t // add new item\n\t const timestamp = Date.now();\n\t newItems[`item-${timestamp}`] = item;\n\t // // set state\n\t this.setState({\n\t\t\t\tinventoryItems: newItems\n\t\t\t})\n\t }", "addToCart(itemOptions) {\n this.store.cart.products.push({\n product_id: itemOptions.item,\n price: itemOptions.price || 0,\n total: itemOptions.price || 0,\n quantity: itemOptions.quantity || 1,\n offer: itemOptions.offer || null,\n materials: itemOptions.config ? itemOptions.config.split(',') : [],\n description: \"\",\n comment: itemOptions.comment\n });\n }", "function addToCart(newItem) {\n console.log(newItem);\n const index = findCartItem(\n newItem.product.id,\n newItem.toppings,\n newItem.remark\n );\n\n if (index === -1) {\n setCart([...cart, { ...newItem, id: uuidV4() }]);\n } else {\n return -1;\n }\n }", "function addItem(item) {\n\t\t// if the item is not empty or not spaces, then go forward.\n\t\tif (/\\S/.test(item)) {\n\t\t\t// do not add duplicates\n\t\t\tif (isDuplicate(item)) {\n\t\t\t\talert(\"'\" + item + \"' is already in the shopping list.\");\n\t\t\t\treturn;\n\t\t\t}\n\n \t\tvar str = \"<li><span class='label'>\" + item + \"</span>\"\n \t\t\t\t\t+\"<div class='actions'><span class='done'><button class='fa fa-check'><span class='element-invisible'>Done</span></button></span>\"\n \t\t\t\t\t+ \"</span><span class='delete'><button class='fa fa-times'><span class='element-invisible'>Delete</span></button></span></div></li>\";\n\n \t\t// adding the new li tag to the end of the list - you are actually adding html string, but jQuery will create elements for you\n\t\t\t$(\"#items\").append(str);\n\t\t}\n\t}", "buyItems(item){\n let shopSells = new Shop('magic shop', 'sells magic things')\n this.items.push(item);\n shopSells.sellItems(item);\n }", "function add(item){\n repository.push(item);\n }", "function addToCart(item) {\n var newItem = {}; // this object contains the item name and price.\n\n var newItem = {\n itemName: item,\n itemPrice: Math.floor(Math.random()*100)\n }\n //newItem.itemName = item;\n //newItem.itemPrice = Math.floor(Math.random()*100)\n cart.push(newItem); // it was pop(newItem)\n return `${newItem.itemName} has been added to your cart.`\n}", "function addItem (value) {\n addItemToDOM(value);\n\n //reset the value after inserting item\n document.getElementById('item').value = '';\n\n //push item into array\n data.todo.push(value);\n\n //update localstorage\n dataObjectUpdated();\n}", "addItem(name, quantity, pricePerUnit) {\n this.items.push({\n name,\n quantity,\n pricePerUnit\n })\n }", "function addToCart(item) {\n cart.push(item);\n localStorage.setItem(\"shop\", JSON.stringify(cart));\n console.log(cart);\n}", "add(id) {\n\t\t\tvar item = this.items.find(item => item.food_id == id);\n\t\t\tif (item) {\n\t\t\t\titem.qty++;\n\t\t\t\tthis.saveToLocalStorage();\n\t\t\t}\n\t\t\telse {\n\t\t\t\tid = parseInt(id);\n\t\t\t\t$http.get(`/rest/food/${id}`).then(resp => {\n\t\t\t\t\tresp.data.qty = 1;\n\t\t\t\t\tthis.items.push(resp.data);\n\t\t\t\t\tthis.saveToLocalStorage();\n\t\t\t\t})\n\t\t\t}\n\t\t}", "addItem(item, options) {\n item.key = this.lastAvailableKey(this.items);\n this.items.push(item);\n }", "function addToCarts(id){\r\n if(!data[id].itemInCart){\r\n cartList = [...cartList,data[id]];\r\n addItem();\r\n\r\n alert('item add to your cart');\r\n }\r\n else{\r\n alert('Your item is already there');\r\n }\r\n data[id].itemInCart = true;\r\n}", "function addItem(item) {\n backpack.push(item);\n}", "function addSelectedItemToCart() {\n // TODO: suss out the item picked from the select list\n // TODO: get the quantity\n // TODO: using those, add one item to the Cart\n const product = selectElement.options[selectElement.selectedIndex].text;\n const quantity = parseInt(document.getElementById('quantity').value);\n cart.addItem(product, quantity);\n}", "function addItem(id) { \n $.each(products, function (key, item) {\n if (item.id === id) {\n order.push(item);\n numberOfItems++;\n } \n });\n $('#orderItems').empty();\n $('<span>Items in Cart ' + numberOfItems + '</span>').appendTo($('#orderItems'));\n}", "public void add(int item){\n if(size == capacity)\n rehash();\n \n arr[size] = item;\n \n bubbleUp(size);\n \n size++;\n }", "add(type, id) {\n let key = this.getKey(type)\n // First see if product is already present\n let item = this.getItem(type, id)\n\n if (!item) {\n this.items[key].push(id)\n }\n\n this.update();\n }", "handleAddItemToCart(item, quantity){\n var buyableItem = new BuyableItem(item, quantity);\n currentCart.push(buyableItem);\n this.setState({cartQuantity : this.calculateCartQuantity(currentCart)})\n localStorage.setItem(\"cart\", JSON.stringify(currentCart));\n this.readFromCart();\n }", "function addItemQty(item, quantity){\n\t\t\tif(!item.qty) item.qty = quantity;\n\t\t\telse item.qty += quantity;\n\t\t}", "add(item) {\n const book = new this._Element(item);\n const id = this._generateId(book);\n if (!this._items[id]) {\n book.DOMElement = this._generateDOMElement(book);\n this._items[id] = book;\n this._container.appendChild(book.DOMElement);\n this._updateStorage()\n }\n }", "function addItem(item) {\n var index = topBarItems.findIndex((x) => x.id === item.id);\n if (index === -1) {\n topBarItems.push(item);\n } else return;\n }", "function addItemToCart(user, item) {\n const updateCart =\n}", "function addToCart(payload) {\n const inCart = cartItems.findIndex((item) => item.beer === payload.beer);\n if (inCart === -1) {\n //add\n console.log(payload);\n const nextPayload = { ...payload };\n nextPayload.amount = payload.amount;\n setCartItems((prevState) => [...prevState, nextPayload]);\n } else {\n //it exists, modify amount\n const nextCart = cartItems.map((item) => {\n if (item.beer === payload.beer) {\n item.amount += payload.amount;\n }\n return item;\n });\n setCartItems(nextCart);\n }\n }", "function addItem(item, cost) {\n if (typeof cost !== \"number\" || isNaN(cost)) {\n cost = 0.0;\n }\n\n $(\"#receipt-table tbody\").append(\n \"<tr>\" +\n '<th scope=\"row\"><i class=\"fas fa-receipt\"></i></th>' +\n '<td id=\"name\">' +\n item +\n \"</td>\" +\n '<td id=\"cost\">' +\n cost.toFixed(2) +\n \"</td>\" +\n \"<td>\" +\n '<span><button type=\"button\" class=\"btn btn-danger\"><i class=\"far fa-trash-alt\"></i></button></span>' +\n \"</td>\" +\n \"</tr>\"\n );\n var newTotal = parseFloat($(\"#total-cost\").text()) + cost;\n $(\"#total-cost\").text(newTotal.toFixed(2));\n }", "addAnItem(item) {\n this.setState((state) => ({items: state.items.concat(item)}));\n }", "function addToBasket(prodID, prodName, prodPrice){\n //Get basket from local storage or create one if it does not exist\n var basketArray;\n if(sessionStorage.basket === undefined || sessionStorage.basket === \"\"){\n basketArray = [];\n }\n else {\n basketArray = JSON.parse(sessionStorage.basket);\n }\n \n //Add product to basket\n basketArray.push({id: prodID, name: prodName, price: prodPrice});\n \n //Store in local storage\n sessionStorage.basket = JSON.stringify(basketArray);\n \n //Display basket in page.\n loadBasket(); \n}", "addItem(item) {\n this.items.push(item)\n }", "function plusItemNumber(item) {\n item.number = Number(item.number) + 1;\n vm.store.updateShoppingItem(item, false);\n vm.store.calculateTotalSubtotal();\n }", "function addSelectedItemToCart() {\n // TODO: suss out the item picked from the select list\n let selectedItem = event.target.items.value;\n console.log(selectedItem);\n // TODO: get the quantity\n let quantity = event.target.quantity.value;\n // TODO: using those, add one item to the Cart\n \n \n carts.addItem(selectedItem,quantity); \n console.log(carts.items);\n \n}", "function add_item_to_cart(name, price) {\n add_item(shopping_cart, name, price);\n calc_cart_total();\n}", "add(item) {\n this.data.push(item);\n }", "function add_item_to_cart(name, price) {\n shopping_cart = add_item(shopping_cart, name, price);\n calc_cart_total();\n}", "add(item) {\n\t\tthis.queue.set(item, item);\n\t}", "putin(item) {\n if (this.open = true) {\n this.item.push(item);\n alert(\"Item has been added to the backpack.\");\n }\n }", "function addItem(itemName, itemPrice) {\n if (order.items[itemName]) {\n order.items[itemName].count += 1;\n } else {\n let item = {name: itemName, price: itemPrice,\n count: 1};\n order.items[itemName] = item;\n }\n order.subtotal = round(order.subtotal + itemPrice);\n order.tax = round(order.subtotal * 0.1);\n order.total = round(order.subtotal + order.tax + order.delivery);\n let restaurantDiv = document.getElementById(\"restaurant\");\n // Generate order summary div \n restaurantDiv.replaceChild(createOrderDiv(restaurantData.menu), document.getElementById(\"restaurant\").lastChild);\n}", "function inventoryAdd(item) {\n item.show();\n\titem.moveTo(inventory_layer);\n item.clearCache();\n\titem.scale({x: 1, y: 1});\n\titem.size({width: 80, height: 80});\n\n\tif (inventory_list.indexOf(item) > -1)\n\t\tinventory_list.splice(inventory_list.indexOf(item), 1, item);\n\telse\n\t\tinventory_list.push(item);\n\n // The picked up item should be visible in the inventory. Scroll inventory\n // to the right if necessary.\n if (inventory_list.indexOf(item) > inventory_index + inventory_max - 1)\n inventory_index = Math.max(inventory_list.indexOf(item) + 1 - inventory_max, 0);\n\n current_layer.draw();\n\tredrawInventory();\n}", "function addItemToCart(user, item) {\n const updateCart = user.cart.concat(item)\n return Object.assign()\n}", "function addToBasketClicked(event) {\n event.preventDefault()\n itemID = event.target.dataset.id\n item = products[itemID]\n for (i=0; i<basketList.length; i++) {\n if (basketList[i] === item.name) {\n alert('Item Already Added To Basket')\n return\n }\n }\n console.log(item.name + ' added to basket')\n\n const basketSection = document.querySelector('#basket')\n const basketArticle = document.createElement('article')\n const basketFigure = document.createElement('figure')\n basketFigure.classList.add('product-in-basket')\n\n const basketImage = document.createElement('img')\n basketImage.classList.add('basket-image')\n basketImage.src = item.imagePath\n basketImage.alt = item.name\n\n const basketProductName = document.createElement('figcaption')\n basketProductName.classList.add('basket-product-name')\n basketProductName.textContent = item.name\n\n const basketQuantity = document.createElement('input')\n basketQuantity.classList.add('basket-quantity')\n basketQuantity.type = 'number'\n basketQuantity.name = 'quantity'\n basketQuantity.defaultValue = 1\n basketQuantity.min = 1\n let quantity = basketQuantity.value\n basketQuantity.addEventListener('input', function(event) {\n event.preventDefault()\n console.log(item.name + ' Quantity Increased')\n quantity = basketQuantity.value\n basketPriceSymbol.textContent = '£'\n basketPrice.textContent = (quantity * item.price).toFixed(2)\n basketPriceSymbol.appendChild(basketPrice)\n updateTotal(itemID)\n })\n\n const basketPriceSymbol = document.createElement('figcaption')\n basketPriceSymbol.classList.add('basket-price-symbol')\n basketPriceSymbol.textContent = '£'\n const basketPrice = document.createElement('span')\n basketPrice.classList.add('basket-price')\n basketPrice.textContent = (quantity * item.price).toFixed(2)\n\n const basketRemove = document.createElement('button')\n basketRemove.classList.add('basket-remove')\n basketRemove.type = 'button'\n basketRemove.textContent = 'REMOVE'\n basketRemove.addEventListener('click', function(event) {\n event.preventDefault()\n console.log('Remove Item Clicked')\n basketArticle.innerHTML = ''\n const index = basketList.indexOf(item.name)\n basketList.splice(index, 1)\n updateTotal(itemID)\n if (basketList.length === 0) {\n const defaultBasket = document.createElement('p')\n defaultBasket.setAttribute('id', 'empty-basket')\n defaultBasket.textContent = 'Your Basket Is Currently Empty'\n basketSection.appendChild(defaultBasket)\n basketTotalAmount.textContent = ''\n basketTotalSection.innerHTML = ''\n }\n })\n\n if (basketList.length === 0) {\n basketSection.innerHTML = ''\n }\n\n basketFigure.appendChild(basketRemove)\n basketSection.appendChild(basketArticle)\n basketArticle.appendChild(basketFigure)\n basketFigure.appendChild(basketImage)\n basketFigure.appendChild(basketProductName)\n basketFigure.appendChild(basketQuantity)\n basketFigure.appendChild(basketPriceSymbol)\n basketPriceSymbol.appendChild(basketPrice)\n basketTotalSection.appendChild(basketTotalArticle)\n basketTotalArticle.appendChild(basketTotalAmount)\n\n updateTotal(itemID)\n\n basketList.push(item.name)\n}", "function insertItem(){\n item = capitalizeFirstLetter(getInput())\n checkInputLength()\n myGroceryList.push(item)\n groceryItem.innerHTML += `\n <div class=\"item\">\n <p>${item}</p>\n <div class=\"item-btns\">\n <i class=\"fa fa-edit\"></i>\n <i class=\"fa fa-trash-o\"></i>\n </div>\n </div>`\n itemAddedSuccess()\n clearBtnToggle()\n clearInputField()\n // Create edit/delete buttons based on icons in <i> tags, above\n queryEditBtn()\n queryDeleteBtn()\n // Adds items to local Storage\n updateStorage()\n}", "function onClickActionAddCartItem(e){\n\t\t\n\t\tvar html = '';\n\t\tlet itemId = parseInt(e.currentTarget.dataset.itemid);\n\t\tvar it = DB.getItemInfo( itemId );\n\t\tvar content = CashShop.ui.find('.container-cart');\n\t\tconst itemCart = CashShop.cartItem.find(i => i.itemId === itemId);\n\t\tvar item = [];\n\t\tvar tab = 0;\n\t\tif(CashShop.activeCashMenu !== 'SEARCH_RESULT'){\n\t\t\titem = CashShop.cashShopListItem[CashShop.activeCashMenu].items.find(i => i.itemId === itemId);\n\t\t\ttab = CashShop.cashShopListItem[CashShop.activeCashMenu].tabNum;\n\t\t} else {\n\t\t\titem = CashShop.csListItemSearchResult.find(i => i.itemId === itemId);\n\t\t\ttab = item.tab;\n\t\t}\n\n\t\tif(content.find('#cart-list .items .no-items').length > 0){\n\t\t\tcontent.find('#cart-list .items .no-items').remove();\n\t\t}\n\n\t\tif(CashShop.cartItem.length > 4 && typeof itemCart === 'undefined'){\n\t\t\t//only 5 item can store in cart\n\t\t\tUIManager.showMessageBox( '5 Item can only stored in cart!', 'ok');\n\t\t\treturn;\n\t\t}\n\n\t\tif(item.amount >= 99){\n\t\t\tUIManager.showMessageBox( 'Max Quantity 99!', 'ok');\n\t\t\tChatBox.addText( 'Max Quantity 99!', ChatBox.TYPE.ERROR);\n\t\t\treturn;\n\t\t}\n\n\t\tif(typeof itemCart === 'undefined'){\n\t\t\titem.amount = 1;\n\t\t\titem.tab = tab;\n\t\t\tCashShop.cartItem.push(item);\n\t\t\thtml = `<li class=\"item\" data-index=\"${itemId}\">\n\t\t\t\t\t<div class=\"inner-item-dt\">\n\t\t\t\t\t\t<div class=\"delete-item\"><button>x</button></div>\n\t\t\t\t\t\t<div class=\"item-dt-img\"></div>\n\t\t\t\t\t\t<div class=\"item-dt-desc\">\n\t\t\t\t\t\t\t<div class=\"item-desc-top\">${it.identifiedDisplayName}</div>\n\t\t\t\t\t\t\t<div class=\"item-counter\">\n\t\t\t\t\t\t\t\t<div class=\"item-cnt\">${item.amount}</div>\n\t\t\t\t\t\t\t\t<button class=\"counter-btn item-cnt-up\" data-index=\"up\"></button>\n\t\t\t\t\t\t\t\t<button class=\"counter-btn item-cnt-down\" data-index=\"down\"></button>\n\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t<div class=\"item-desc-price\">\n\t\t\t\t\t\t\t\t<div class=\"icon-gold-coin\"></div>\n\t\t\t\t\t\t\t\t<span>${item.price}</span>\n\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t</div>\n\t\t\t\t\t</div>\n\t\t\t\t</li>`;\n\t\t\tcontent.find('.items').append(html);\n\t\t\tClient.loadFile( DB.INTERFACE_PATH + 'collection/' + ( it.identifiedResourceName ) + '.bmp', function(data){\n\t\t\t\tcontent.find('.item[data-index=\"'+ itemId +'\"] .item-dt-img').css('backgroundImage', 'url('+ data +')');\n\t\t\t});\n\n\t\t\tClient.loadFile( DB.INTERFACE_PATH + 'cashshop/img_shop_itemBg2.bmp', function(data){\n\t\t\t\tcontent.find('.item-counter').css('backgroundImage', 'url('+ data +')');\n\t\t\t});\n\t\t} else {\n\t\t\titemCart.amount += 1;\n\t\t\tcontent.find('.items .item[data-index=\"'+itemId+'\"] .item-cnt').html(itemCart.amount);\n\t\t}\n\t\tCashShop.cartItemTotalPrice = CashShop.cartItem.map(item => item.price * item.amount).reduce((prev, next) => prev + next);\n\t\tCashShop.ui.find('.container-cart-footer .item-desc-price span').html(CashShop.cartItemTotalPrice);\n\t}", "function addSelectedItemToCart() {\n // suss out the item picked from the select list\n let product = document.getElementById('items').value;\n let quantity = document.getElementById('quantity').value;\n cart.addItem(product, quantity);\n\n // console.log(newCartItem);\n // console.log(cart);\n\n // get the quantity\n // using those, add one item to the Cart\n}" ]
[ "0.78531545", "0.75524104", "0.75524104", "0.75307167", "0.7469858", "0.70358354", "0.70262337", "0.7016932", "0.69937843", "0.697444", "0.69727904", "0.6948269", "0.6890161", "0.68432903", "0.67820865", "0.67208856", "0.67099977", "0.6706156", "0.6697594", "0.669391", "0.66883767", "0.6675413", "0.66710174", "0.66567224", "0.66539854", "0.6636754", "0.66244286", "0.6557953", "0.6548128", "0.654398", "0.653856", "0.6537783", "0.65172327", "0.6489695", "0.6475339", "0.6453673", "0.6449575", "0.6423872", "0.64165753", "0.6396987", "0.63681227", "0.63605225", "0.6358714", "0.6357443", "0.63527834", "0.6345166", "0.6335776", "0.6331656", "0.6326995", "0.6324348", "0.6320743", "0.63158524", "0.63133943", "0.63099635", "0.6304863", "0.6288547", "0.6286904", "0.6279869", "0.6275232", "0.6274437", "0.62721574", "0.62456936", "0.62334716", "0.62317246", "0.6229332", "0.6219431", "0.6218047", "0.6213061", "0.6212713", "0.6206666", "0.6203238", "0.62009543", "0.61993814", "0.61958086", "0.61950994", "0.61875445", "0.61837727", "0.6183361", "0.6183245", "0.6182206", "0.61819786", "0.61562616", "0.61550146", "0.6128429", "0.6126805", "0.6126224", "0.6121557", "0.61171675", "0.61116076", "0.610328", "0.6101288", "0.6096862", "0.6091177", "0.60859317", "0.6079656", "0.6075725", "0.6074253", "0.6072736", "0.60617876", "0.6059751" ]
0.702639
6
Calculates the total cost of all the items in the customers basket.
function calculateTotal() { // Remove old total order if it exists const parent = document.getElementById("order"); const totalPrice = document.getElementById("total-price"); if (totalPrice != null) { parent.removeChild(totalPrice); } // Calculate total let total = 0.0; for (let i = 0; i < basket.length; i++) { const item = basket[i]; total += parseFloat(item.price); } // Display it. $("#order").append("<li id='total-price' class='list-group-item list-group-item-info'>\n" + "<span class='bold'>Total:</span>" + "<span class='span-right'>£" + total.toFixed(2) + "</span>\n" + "</li>"); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function total() {\n let totalCost = 0\n for (var i = 0; i < cart.length; i++) {\n for (var item in cart[i]) {\n totalCost += cart[i][item]\n }\n }\n return totalCost\n}", "function TotalCost()\n{\n\tvar totalcost = 0;\n\tfor (var i in Cart) {\n\ttotalcost += Cart[i].price;\n\t}\n\treturn totalcost;\n}", "function total() {\n let totalVal = 0;\n for (var i = 0; i < cartItems.length; i++) {\n totalVal += cartItems[i].price * cartItems[i].quantity\n }\n setCartTotal(totalVal)\n }", "function calculateTotalCost(shoppingCart) {\n let total = 0;\n for (let product of shoppingCart) {\n total += product.price * product.count\n }\n\n return total\n}", "function total() {\n var total = 0\n for(var i = 0; i < cart.length; i++){\n total += cart[i].itemPrice\n }\n return total\n}", "getTotalCost() {\n return this.transactions.map(t => t.cost).reduce((acc, value) => acc + value, 0);\n }", "function calculateTotal(){\n\t\tlet basketTotalContainer = document.querySelector('#basket-total');\n\t\tlet basketCount = document.querySelector('#basket-count');\n\t\tlet minibasketTotal = document.querySelector('#mini-basket-total');\n\t\tbasketTotalContainer.innerHTML = '';\n\t\tbasketCount.innerHTML = '';\n\t\tminibasketTotal.innerHTML = '';\n\t\tlet basket = document.querySelector('.basket tbody'), basketTotalVal = 0, basketTotalItems = 0, basketTotalValCurrency;\n\t\tfor(let i = 0; i < (basket.rows.length); i++){\n\t\t\tlet rowTotal = Number(basket.rows[i].cells[2].innerHTML);\n\t\t\tlet itemsTotal = Number(basket.rows[i].cells[1].childNodes[0].innerHTML);\n\t\t\tbasketTotalVal = basketTotalVal + rowTotal;\n\t\t\tbasketTotalValCurrency = basketTotalVal.toFixed(2);\n\t\t\tbasketTotalItems = basketTotalItems + itemsTotal;\t\t\n\t\t};\n\t\tbasketTotalContainer.innerHTML = basketTotalValCurrency;\n\t\tbasketCount.innerHTML = basketTotalItems;\n\t\tminibasketTotal.innerHTML = basketTotalValCurrency;\n\t\t// avoid 'undefined' if basket is empty\n\t\tif (basketTotalValCurrency == null){\n\t\t\tbasketTotalContainer.innerHTML = '';\n\t\t\tminibasketTotal.innerHTML = '';\n\t\t}\n\t}", "function compute_subtotal(items) {\n\t$(\".wddp-shopping-cart\").text(\"Shopping cart total: $\" + Object.values(items).reduce((x, y) => (x + y), 0));\n}", "function total() {\n var totalValue = 0;\n for (var i = 0; i < cart.length; i++) {\n totalValue += cart[i].itemPrice\n }\n return totalValue;\n}", "function totalCost(){\n var totalCartCost=0;\n for(var i in cart){\n \t totalCartCost+=cart[i].price*cart[i].count; \n }\n return totalCartCost; \n}", "function getTotalPrice(items) {\n return _.reduce(items, function(memo, item) {\n return memo + item.quantity * item.price;\n }, 0);\n }", "function totalCost() {\n var totalCost = 0;\n if (localStorage.BASKET) {\n var json = JSON.parse(localStorage.BASKET);\n\n for (var i = 0; i < json.length; i++) {\n var product = JSON.parse(json[i]);\n var lineTotal = parseFloat(product.productPrice) *\n parseFloat(product.quantity);\n totalCost += lineTotal;\n }\n }\n return totalCost;\n}", "function productTotal() {\n for (let i = 0; i < basket.length; i++) {\n let price = Number(basket[i].price.replace(/[^0-9.-]+/g,\"\"));\n let totalPrice = price * basket[i].quantity;\n basket[i].totalPrice = totalPrice\n } \n}", "function calcTotal(itemId, itemPrice, orderQty) {\n var total = orderQty * itemPrice;\n console.log(\"Total Cost is $\" + total.toFixed(2));\n}", "function calculateTotalPrice(orderedItems) {\n let totalPrice = 0;\n // Пиши код ниже этой строки\n\n \n\n orderedItems.forEach(function( orderedItems, index,){\n \ttotalPrice += orderedItems;\n }); \n // Пиши код выше этой строки\n return totalPrice;\n}", "totalCart()\n {\n let total = 0;\n for (let i = 0; i < this.itemlist.length; i++)\n {\n total += this.itemList[1].price * this.itemQuantity[i];\n }\n return total;\n }", "function total() {\n for (var i = 0; i < cart.length; i++){\n \n getCart()[i].itemPrice\n return \n }\n}", "total() {\n var total = 0.0\n for (var sku in this.items) {\n var li = this.items[sku]\n var price = li.quantity * li.price\n total += price\n }\n return total\n }", "function calcTotal() {\n let total = 0;\n for (let item of itemList) {\n total += Number(item.price);\n }\n console.log(\"this is the total\", total);\n return total;\n }", "function totalPrice() {\n var sum = 0.0;\n for(let i = 0; i < cart.length; i++){\n if(cart.prodSalePrice != null){\n sum += (Number(cart[i].prodSalePrice) * Number(cart[i].prodQty));\n }else{\n sum += (Number(cart[i].prodPrice) * Number(cart[i].prodQty));\n }\n }\n return sum;\n }", "function calcTotals() {\n\n var taxRate = 0.085;\n\n // Reset totals to recalculate.\n cart.totals.qty = 0;\n cart.totals.price = 0;\n cart.totals.tax = 0;\n cart.totals.subtotal = 0;\n cart.totals.total = 0;\n\n if (cart.items.length) {\n for (var x = 0; x < cart.items.length; x++) {\n\n cart.totals.qty += cart.items[x].qty;\n\n if (cart.items[x].sale) {\n cart.totals.price += cart.items[x].qty * cart.items[x].salePrice;\n } else {\n cart.totals.price += cart.items[x].qty * cart.items[x].listPrice;\n }\n\n }\n\n if (cart.shipping == 'Ground Shipping' && cart.totals.price > 500) {\n cart.totals.shipping = 0;\n } else if (cart.shipping) {\n cart.totals.shipping = cart.shippingmethods[cart.shipping].price;\n }\n\n cart.totals.subtotal = Math.round((cart.totals.price + cart.totals.shipping) * 100) / 100;\n\n cart.totals.tax = Math.round((cart.totals.price * taxRate) * 100) / 100;\n\n cart.totals.total = Math.round((cart.totals.subtotal + cart.totals.tax) * 100) / 100;\n\n } else {\n cart.totals.shipping = 0;\n cart.totals.price = 0;\n }\n\n }", "function getShoppingCartSum() {\n let sum = 0;\n\n for (let index = 0; index < shoppingCart.length; index++) {\n const item = shoppingCart[index];\n sum += item.amount * item.price;\n }\n\n return sum;\n}", "function getTotal() {\n\t\treturn cart.reduce((current, next) => {\n\t\t\treturn current + next.price * next.count;\n\t\t}, 0);\n\t}", "function getCartTotalAmount(){\n var total = 0;\n for(var i =0; i < cart_items.length; i++){\n var item = getItemById(cart_items[i][0]);\n total += item[4] * cart_items[i][1];\n }\n return total;\n}", "totalPrice() {\n let sum = 0;\n\n for(let i = 0; i < this.state.items.length; i++){\n sum += this.totalItemPrice(this.state.items[i]);\n }\n return sum;\n }", "function calcTotalCart(item){\n //console.log(\"item count\" + item.count);\n total = total + item.count;\n var productName = products.find(y => y.id == item.id).name;\n //Display each individual item name and it's individual count\n console.log(productName + \" - Quantity = \" + item.count);\n }", "getTotalSelectedItemsCost() {\n const totalCost = this.itemModelList.data.reduce((prevVal, item) => {\n if (!item.isChecked) {\n return prevVal;\n }\n\n return prevVal + MartCtrl.getItemCost(item);\n\n }, 0);\n\n events.emit(MART_CTRL_SET_TOTAL_COST, totalCost);\n }", "function sumShoppingBag(shoppingBag){\n //var shoppingBagJson = shoppingBag.shopping_bag;\n var sum = 0;\n for (var i = 0; i < shoppingBag.length; i++) {\n //TODO think if to change to sum only without calc\n sum += shoppingBag[i].quantity * shoppingBag[i].price;\n }\n return sum;\n}", "function calc_total(frm){\n\tvar total_cost = 0;\n\tcur_frm.doc.sold_waste_item.forEach(function(_){\n\t\ttotal_cost += _.amount\n\t});\n\tfrappe.model.set_value(cur_frm.doctype,cur_frm.docname, \"total\", total_cost)\n}", "function calcTotalPrice() {\n let totalPricePrev = 0;\n cartItems.forEach((item) => {\n prices.forEach((price) => {\n if (price.beername === item.beer) {\n totalPricePrev += item.amount * price.price;\n }\n });\n });\n setTotalPrice(totalPricePrev);\n }", "function calculateTotalCart () {\n let totalPrice = 0;\n for (product of products) {\n totalPrice += product.price;\n }\n return totalPrice/100;\n}", "updateTotal() {\n let total = 0;\n for (let index in this.items) {\n let item = this.items[index];\n total += item.price * item.quantity;\n }\n this.total = total;\n }", "function updateTotal(){\n\t\tvar sum = 0;\n\t\t$(\".cart_items>.item\").each(function(i,v){\n\t\t\tsum += $(v).data(\"price\") * $(v).find(\".cart_cloth_num\").text();\n\t\t});\n\t\t$(\".cart_total\").text(sum);\n\t}", "function updateTotal(itemID) {\n console.log('Update Total Function Called')\n const basketPriceArray = document.querySelectorAll('.basket-price')\n let total = 0\n for(i=0; i<basketPriceArray.length; i++) {\n total = parseFloat(basketPriceArray[i].textContent) + total\n }\n basketTotalAmount.textContent = (total).toFixed(2)\n}", "function updateTotal() {\n var total = 0;\n $('.cart-item-price').each(function() {\n total += parseInt($(this).text());\n });\n $('#shoppingcart-items').append('<hr><span>Total: ' + total + '$ <a href=\"/checkout\">Go to checkout</a></span>');\n }", "function getTotalQuantity(items) {\n return _.reduce(items, function(memo, item) {\n return memo + item.quantity;\n }, 0);\n }", "total()\r\n\t{\r\n \t\tthis.cart = Cookie.get(this.settings.cookie_name);\r\n\r\n \t\tvar total = 0.00;\r\n \t\tlet i;\r\n\r\n \t\tfor (i = 0; i < this.cart.items.length; i++) {\r\n \t\t\ttotal += parseFloat(this.cart.items[i].price.amount) * this.cart.items[i].quantity;\r\n \t\t}\r\n\r\n \t\treturn total.toFixed(2);\r\n\t}", "function totalPurchaseCost(item, quantity, coins){\n\tvar storeItems = storeInfo.getItems();\n\tvar cost;\n\tfor (var storeItem in storeItems){\n\t\tif (storeItem.name == item)\n\t\t\tcost = storeItem.price;\n\t}\n\tif (coins >= quantity * cost)\n\t\treturn quantity * cost;\n\telse \n\t\treturn false;\n}", "function showAllItemsCost() {\n\tshowCost(healthKitShopItemEl, healingCost);\n\tshowCost(improveMagazineShopItemEl, magazineIncreaseCost);\n\tshowCost(fasterReloadShopItemEl, decreaseReloadingTimeCost);\n\tshowCost(increasePowerUpDurationShopItemEl, powerUpDurationIncreaseCost);\n}", "function calc_cart_total() {\n shopping_cart_total = calc_total();\n set_cart_total_dom();\n update_shipping_icons();\n update_tax_dom();\n}", "function getTotal(cart) {\n return totalPrice = cart.reduce((total, currentItem) => total + (currentItem.quantity * currentItem.price), 0).toFixed(2);\n}", "getOrderTotal() {\n\n return Object.values(this.lineItems).reduce(\n (total, {product, sku, quantity}) =>\n total + quantity * this.plans[0].amount,\n 0\n );\n }", "function calc_cart_total() {\n shopping_cart_total = calc_total(shopping_cart);\n set_cart_total_dom();\n update_shipping_icons();\n update_tax_dom();\n}", "function getTotalPrice(cart) {\n\tvar sum = 0\n\tcart.forEach(p => {\n\t\tsum += p.price;\n\t})\n\treturn sum\n}", "function calcTotal() {\n // get the value and parse from session storage\n let cart = JSON.parse(sessionStorage.getItem('cart'));\n\n // define a total variable = 0\n let total = 0;\n\n // loop through all items in the cart\n for (let i in cart) {\n // add each item's price to total\n total += cart[i].price;\n }\n\n // return the total\n return total.toFixed(2);\n }", "function totalCost() {\n var cost = price * quantity\n return cost;\n}", "function calculateTotal() {\n\t if(validQuantities == false)\n\t\t\treturn; \n\t var totalPrice = 0;\n\t\tfor (var i = 0; i< items.length; i++){\n\t\t\tvar size = document.forms[formName][sizeName[i]].value;\n\t\t\tvar quantity= parseInt(document.forms[formName][numberName[i]].value, 10);\n\t\t\tvar itemPrice = 0;\n\t\t\tconsole.log(size + \",\" + quantity.toString() +\",\" + i.toString());\n\t\t\tif(size==\"small\") {\n\t\t\t\titemPrice = quantity * smallPrices[i];\n\t\t\t}\n\t\t\tif(size == \"medium\") {\n\t\t\t\titemPrice = quantity * mediumPrices[i];\n\t\t\t}\n\t\t\tif(size == \"large\") {\n\t\t\t\titemPrice = quantity * largePrices[i];\n\t\t\t}\n\t\t\ttotalPrice += itemPrice;\n\t\t}\n\t\ttotalPrice += mayoCost + seasoningCost + ketchupCost;\n\t\tdocument.getElementById(\"total\").innerHTML = \"<strong><u>Your Total is $\" + totalPrice.toString() + \"</strong></u>\";\n\t\treturn totalPrice;\n}", "calculateTotal() {\n\t\t//Réinitialise le total\n\t\tthis.total = 0\n\t\tfor (let product of this.products) {\n\t\t\tthis.total += product.price * product.number\n\t\t}\n\t}", "function getTotal() {\n const { cart } = state;\n\n const res = cart.reduce((prev, product) => {\n return (prev + (product.price * product.count));\n }, 0);\n\n dispatch({\n type: 'TOTAL',\n payload: res\n });\n }", "function totalSales(shirtQuantity, pantQuantity, shoeQuantity) {\n const cart = [\n { name: 'shirt', price: 100, quantity: shirtQuantity },\n { name: 'pant', price: 200, quantity: pantQuantity },\n { name: 'shoe', price: 500, quantity: shoeQuantity }\n ];\n let cartTotal = 0;\n for (const product of cart) {\n const productTotal = product.price * product.quantity;\n cartTotal = cartTotal + productTotal;\n }\n return cartTotal;\n}", "function getTotalCost (pizzas) {\n var totalCost = 0;\n pizzas.forEach(function (pizza) {\n totalCost += pizza.getCost();\n });\n return totalCost;\n}", "function updateCartTotal(){\n let cartItemContainer = document.querySelectorAll(\"#shoppingReminder\")[0];\n let cartRows = cartItemContainer.querySelectorAll(\"#shoppingRow\");\n let subTotal = 0 ;\n for (let i = 0 ; i<cartRows.length; i++){\n let cartRow = cartRows[i];\n let productPrice = cartRow.querySelectorAll(\".productPrice\")[0];\n let price = parseFloat(productPrice.innerText.replace('€',\"\"));\n let subTotalCount = document.querySelector(\"#subtotalcount\");\n subTotal += price;\n subTotalCount.innerHTML = subTotal +\"€\";\n }\n let totalCount = document.querySelector(\"#totalcount\");\n let delivery = document.querySelector(\"#deliverycost\")\n let deliveryCost =0 ;\n if(deliveryCost == 0 || null){\n delivery.innerHTML = \"Offerte\";\n }else{\n delivery.innerHTML = deliveryCost + \"€\";\n }\n totalCount.innerHTML = (subTotal + deliveryCost) + \"€\"; \n}", "function getTotalPrice(shoppingCart){\n return shoppingCart.reduce((sum, current) => sum + current.price * current.quantity, 0);\n}", "function totalCart(products) {\n let totalPrice = 0;\n if (products) {\n for (product of products) {\n totalPrice += parseInt(product.price);\n }\n return totalPrice;\n } else {\n return totalPrice\n }\n}", "function getTotalCost(data) {\n var total = 0;\n data.forEach(function(element) {\n total += parseInt(element.cost);\n });\n \n return total.toFixed(2);\n}", "function getTotalPrice() {\n var totalCostCart = document.getElementById(\"total-cost-cart\");\n var totalCostCartInt = parseInt(totalCostCart.innerHTML);\n var allUnitCosts = document.getElementsByClassName(\"cost-product-unit\");\n var allQuantities = document.getElementsByClassName(\"quantity-input\");\n var allCostsByProduct = document.getElementsByClassName(\"cost-product-total\");\n \n totalCostCartInt = 0;\n \n for (let i=0;i<allCostsByProduct.length;i++) {\n var unitCost = parseInt(allUnitCosts[i].innerHTML);\n var quantity = parseInt(allQuantities[i].value);\n var costByProduct = allCostsByProduct[i];\n \n var costByProductInt = unitCost * quantity;\n \n if (!(isNaN(costByProductInt))) {\n costByProduct.innerHTML = `${costByProductInt}`;\n }\n \n totalCostCartInt += costByProductInt;\n }\n \n if (isNaN(totalCostCartInt)) {\n alert(\"Please enter all quantities or delete items\")\n } else {\n totalCostCart.innerHTML = `${totalCostCartInt}`;\n }\n \n }", "function calcTotal() {\n // get value and parse sessionStorage\n let cart = JSON.parse(sessionStorage.getItem('cart'));\n\n // loop through all items in the Cart\n // add each items price to Total\n // return total\n let total = 0;\n for (let product in cart) {\n total += cart[product].price;\n }\n return total.toFixed(2)\n}", "function getPrices(){\n\n\t\t//cost of shop items\n\t\tprice1=75.00; price2=116; price3=44; price4=5.25; price5=3.75; price6=12.75; price7=4.10;\n\n\t\t//ammount of items chosen\n\t\titem_1=0; item2=0; item3=0; item4=0; item5=0; item6=0; item6=0; item7=0;\n\n\t\t//sub-total for each item\n\t\tsubTot_1 = 0; subTot_2=0; subTot_3=0; subTot_4=0; subTot_5=0; subTot_6=0; subTot_7=0;\n\n\t\t//get number of items\n\t\titem_1 = document.getElementById(\"item_1\").value;\n\t\titem_2 = document.getElementById(\"item_2\").value;\n\t\titem_3 = document.getElementById(\"item_3\").value;\n\t\titem_4 = document.getElementById(\"item_4\").value;\n\t\titem_5 = document.getElementById(\"item_5\").value;\n\t\titem_6 = document.getElementById(\"item_6\").value;\n\t\titem_7 = document.getElementById(\"item_7\").value;\n\n\n\t\t//subtotal for item\n\t\tsubTot_1 = eval(item_1) * eval(price1);\n\t\tsubTot_1 = subTot_1.toFixed(2);\n\t\tdocument.getElementById(\"subTot_1\").value = subTot_1;\n\n\t\t//subtotal for item 2\n\t\tsubTot_2 = eval(item_2) * eval(price2);\n\t\tsubTot_2 = subTot_2.toFixed(2);\n\t\tdocument.getElementById(\"subTot_2\").value = subTot_2;\n\n\t\t//subtotal for item 3\n\t\tsubTot_3 = eval(item_3) * eval(price3);\n\t\tsubTot_3 = subTot_3.toFixed(2);\n\t\tdocument.getElementById(\"subTot_3\").value = subTot_3;\n\n\t\t//subtotal for item 4\n\t\tsubTot_4 = eval(item_4) * eval(price4);\n\t\tsubTot_4 = subTot_4.toFixed(2);\n\t\tdocument.getElementById(\"subTot_4\").value = subTot_4;\n\n\t\t//subtotal for item 5\n\t\tsubTot_5 = eval(item_5) * eval(price5);\n\t\tsubTot_5 = subTot_5.toFixed(2);\n\t\tdocument.getElementById(\"subTot_5\").value = subTot_5;\n\n\t\t//subtotal for item 6\n\t\tsubTot_6 = eval(item_6) * eval(price6);\n\t\tsubTot_6 = subTot_6.toFixed(2);\n\t\tdocument.getElementById(\"subTot_6\").value = subTot_6;\n\n\t\t//subtotal for item 7\n\t\tsubTot_7 = eval(item_7) * eval(price7);\n\t\tsubTot_7 = subTot_7.toFixed(2);\n\t\tdocument.getElementById(\"subTot_7\").value = subTot_7;\n\n\t\t//work out total for all items\n\t\tTotamt = eval(subTot_1)+eval(subTot_2)+eval(subTot_3)+eval(subTot_4)+eval(subTot_5)+eval(subTot_6)+eval(subTot_7);\n\t\tTotamt = Totamt.toFixed(2);\n\t\tdocument.getElementById(\"GrandTotal\").value = Totamt;\n\n}//end getPrices", "function calcTotal(basket) {\n return parseFloat(\n basket\n .reduce((acc, next) => {\n if (next.name === \"Motion Sensor\" && next.quantity >= 3) {\n return (\n acc +\n Math.floor(next.quantity / 3) * 65 +\n (next.quantity % 3) * next.price\n );\n } else if (next.name === \"Smoke Sensor\" && next.quantity >= 2) {\n return (\n acc +\n Math.floor(next.quantity / 2) * 35 +\n (next.quantity % 2) * next.price\n );\n } else {\n return acc + next.price * next.quantity;\n }\n }, 0)\n .toFixed(2)\n );\n}", "function updateCartTotal() {\n var cartItemContainer = document.getElementsByClassName(\"cart-body\")[0];\n var cartRows = cartItemContainer.getElementsByClassName(\"cart-item\");\n var total = 0;\n for (var i = 0; i < cartRows.length; i++) {\n var cartRow = cartRows[i];\n var priceElement = cartRow.getElementsByClassName(\"cart-item-price\")[0];\n var quantityElement = cartRow.getElementsByClassName(\n \"ItemCounterCart2\"\n )[0];\n var price = parseFloat(priceElement.innerText.replace(\"$\", \"\"));\n var quantity = parseInt(quantityElement.value);\n var total1 = price * quantity;\n total = total + total1;\n total = Math.round(total * 100) / 100;\n }\n document.getElementsByClassName(\"subtotal3\")[0].innerText = \"$\" + total;\n }", "function Total() {\n let subtotal = 0;\n for (let val of cart) {\n subtotal = total + (val.price * val.qtty);\n }\n\n /* Display subtotal*/\n document.getElementById(\"sub-total-price\").innerHTML = total.toFixed(2) + \" €\";\n\n /* Calculate price after discount*/\n let total = subtotal - Discount(subtotal);\n\n /* Display order total*/\n document.getElementById(\"total-price\").innerHTML = total.toFixed(2) + \" €\";\n}", "function getTot(){\n let total = 0;\n for(let i = 0; i < cart.length; i += 1){\n total += cart[i].price * cart[i].qty\n }\n return total.toFixed(2)\n}", "function getTotal() {\n let total = 0;\n\n shoppingCart.forEach(product => {\n total += product.price * product.stock_quantity;\n });\n console.log(\"this is the total\", total);\n return total;\n }", "function updateCartTotal() {\n var cartItemContainer = document.getElementsByClassName(\"cart-items\")[0];\n var cartRows = cartItemContainer.getElementsByClassName(\"cart-row\");\n var total = 0;\n for (var i = 0; i < cartRows.length; i++) {\n var cartRow = cartRows[i];\n var priceElement = cartRow.getElementsByClassName(\"cart-price\")[0];\n var quantityElement = cartRow.getElementsByClassName(\n \"cart-quantity-input\"\n )[0];\n var price = parseFloat(priceElement.innerText.replace(\"$\", \"\"));\n var quantity = quantityElement.value;\n total = total + price * quantity;\n }\n document.getElementsByClassName(\"cart-total-price\")[0].innerText = total;\n}", "function updateSubTotal() {\r\n\r\nlet subTotal = 0;\r\ncartItems.forEach(function(item){\r\n subTotal = subTotal + item.price;\r\n console.log(subTotal);\r\n});\r\n document.getElementById(\"val\").innerHTML = \"Total = N\" + subTotal.toFixed(2);\r\n}", "function updateCartTotal(){\n\tvar cartItemContainer = document.getElementsByClassName(\"cart-items\")[0];\n\tvar cartRows = cartItemContainer.getElementsByClassName(\"first-cart-row\");\n\tvar total = 0;\n\tfor (var i = 0; i < cartRows.length; i++) {\n\t\tvar cartRow = cartRows[i];\n\t\tvar priceElement = cartRow.getElementsByClassName(\"cart-price\")[0];\n\t\tvar quantityElement = cartRow.getElementsByClassName(\"cart-quantity-input\")[0];\n\t\tvar price = parseFloat(priceElement.innerText.replace(\"$\",\"\"));\n\t\tvar quantity = quantityElement.value;\n\t\ttotal = total + (price * quantity);\n\t}\n\ttotal = Math.round(total * 100) / 100;\n\tdocument.getElementsByClassName(\"cart-total-price\")[0].innerText = \"$\" + total;\n}", "function updateCartTotal() {\r\n var cartItemContainer = document.getElementsByClassName(\"cart-items\")[0];\r\n var cartRows = cartItemContainer.getElementsByClassName(\"cart-row\");\r\n var total = 0;\r\n for (var i = 0; i < cartRows.length; i++) {\r\n var cartRow = cartRows[i];\r\n var priceElement = cartRow.getElementsByClassName(\"cart-price\")[0];\r\n var quantityElement = cartRow.getElementsByClassName(\"cart-quantity-input\")[0];\r\n var price = parseFloat(priceElement.innerText.replace(\"€\", \"\"));\r\n var quantity = quantityElement.value;\r\n total = total + (price * quantity);\r\n }\r\n total = Math.round(total * 100) / 100;\r\n document.getElementsByClassName(\"cart-total-price\")[0].innerText = \"€\" + total;\r\n }", "function totalNumberOfItems(numbOfItemsInCart){\n //takes in the shopping cart as input\n //returns the total number all item quantities\n //return the sum of all of the quantities from each item type\n var totItems = 0;\n for (let i = 0; i < numbOfItemsInCart.items.length; i++) {\n totItems += numbOfItemsInCart.items[i].quantity;\n }\n return totItems;\n}", "findTotalItemCost() {\n let sum = 0;\n this.state.inventory_costs.map((inventory_cost) => {\n const itemTotal = inventory_cost.inventory_quantity * inventory_cost.cost_per_unit;\n sum += itemTotal;\n return sum;\n\n })\n console.log(sum, 'before setting state SUM')\n this.setState({\n totalCost: sum\n });\n }", "function updateCheckoutCartTotal() {\r\n let checkoutTotal = 0;\r\n const checkoutCartTotal = document.querySelector('.checkoutCartTotal');\r\n\r\n const checkoutProductItems = document.querySelectorAll('.checkoutProductItem');\r\n\r\n checkoutProductItems.forEach((checkoutCartItem) => {\r\n const checkoutProductPriceItem = checkoutCartItem.querySelector(\r\n '.checkoutProductPrice'\r\n );\r\n const checkoutProductPrice = Number(\r\n checkoutProductPriceItem.textContent.replace('$', '')\r\n );\r\n \r\n checkoutTotal = checkoutTotal + checkoutProductPrice;\r\n \r\n \r\n });\r\n checkoutCartTotal.innerHTML = `${checkoutTotal.toFixed(2)}$`;\r\n \r\n\r\n}", "total (itens) {\n prod1 = list[0].amount\n prod2 = list[1].amount\n prod3 = list[2].amount\n prod4 = list[3].amount\n\n itens = prod1 + prod2 + prod3 + prod4\n\n return itens\n }", "function costWithTax(item) {\n return parseFloat( item.price + taxForItem(item) );\n }", "function totalPrice() {\n let ttlPrice = 0;\n customerBasket.forEach((product) => {\n ttlPrice += (product.price / 100) * product.quantity;\n });\n let priceTotal = document.createElement(\"div\");\n priceTotal.classList = \"row justify-content-center h4 m-5\";\n priceTotal.innerHTML = `<strong>Prix total : ${ttlPrice} €</strong>`;\n document.getElementById(\"container\").appendChild(priceTotal);\n }", "function total_order_cost_calc(datasets) {\n $scope.total_order_cost = 0;\n // Combines all the costs\n for (var key in datasets) {\n $scope.total_order_cost += datasets[key][2];\n }\n // Formats cost in a currency style\n // Uses decimalAdjust functions above, from the Mozilla Developer Network\n $scope.total_order_cost = \"$\" + Math.ceil10($scope.total_order_cost, -2);\n if ($scope.total_order_cost[$scope.total_order_cost.indexOf(\".\") + 2] === undefined) {\n $scope.total_order_cost += \"0\";\n }\n }", "function CalculateTotalCost()\n{\n var apples = document.getElementById('apples').value;\n var oranges = document.getElementById('oranges').value;\n var bananas = document.getElementById('bananas').value;\n\n totalcost.value = ((apples * 0.69) + (oranges * 0.59) + (bananas * 0.39)).toFixed(2);\n}", "function updatePrice() {\n var sum = 0;\n for(var i = 0; i < $scope.currentItems.length; i++) {\n sum += $scope.currentItems[i].price;\n }\n\n $scope.totalCost = sum + (sum * taxRate);\n $scope.totalCost = Math.floor($scope.totalCost);\n console.log($scope.totalCost);\n }", "function updateCartTotal() {\n //Get all the items in the cart with the class name cart-item-row\n let cartItemRows = document.getElementsByClassName(\"cart-item-row\");\n\n let total = 0;\n // For each item in the cart, run a loop that gets the quantity input and price of the item. Add all of them to the total amount in the cart. \n for (let i = 0; i < cartItemRows.length;i++){\n let cartItemRow = cartItemRows[i];\n let priceItem = cartItemRow.getElementsByClassName('cart-item-price')[0];\n let quantityItem = cartItemRow.getElementsByClassName('cart-quantity-input')[0];\n let price= parseFloat(priceItem.innerText.replace('R',''));\n let quantity = quantityItem.value;\n //increment the total amount in the cart by the price and quantity of each item in the cart. \n total = total + (price * quantity)\n \n }\n document.getElementsByClassName('cart-total-amount')[0].innerText = \"Total Amount: R\"+ total;\n }", "function sum()\n{\n var temp=0;\n for(var i=0;i<cart.length;i++)\n {\n temp=temp+ cart[i].price;\n }\n return temp;\n}", "function getTotal(cart) {\n let total = 0;\n $.each(cart.items, function(i, el) {\n total += el.price;\n });\n $.each(cart.promocodes, function(i, el) {\n if (cart.deliveryOption == null || el.deliveryOption == cart.deliveryOption) {\n total -= el.amount;\n }\n });\n return total;\n}", "function getTotalPrice(chosenProducts) {\n\ttotalPrice = 0;\n\tfor (let i=0; i<chosenProducts.length; i+=1) {\n\t\ttotalPrice+=chosenProducts[i].price;\n\t}\n\treturn totalPrice;\n}", "function getTotalPrice(itemNode) {\n var price = getPriceByProduct(itemNode);\n var qty = getQuantityByProduct(itemNode);\n return price * qty;\n}", "function calTotal() {\n var ttotal = 0;\n var total = \"\"\n // totalDiv.innerHTML =total\n for (var x = 0; x < cart.length; x++) {\n var skuu = cart[x].sku;\n // console.log(skuu)\n var cat = cart[x].categoryId\n // console.log(cat)\n var pret;\n\n // console.log(pret)\n for (var j = 0; j < products[cat].length; j++) {\n // console.log(products[cat][j])\n if (products[cat][j].sku == skuu) {\n pret = products[cat][j].price;\n // console.log(pret)\n // console.log(pret)\n\n ttotal += pret * cart[x].qty\n //console.log(\"ttotal= \"+ttotal)\n }\n }\n }\n totalDiv.innerHTML = \"total = \" + ttotal + \" lei\";\n }", "subtotal() {\n return this.state.dishes\n .map(dish => (dish.price.num))\n .reduce(Utils.sumFunc, 0);\n }", "function costTotal(items, action) {\n let productTotal = localStorage.getItem(\"costTotal\", items.price);\n\n if (action == \"decrement\") {\n productTotal = parseInt(productTotal);\n localStorage.setItem(\"costTotal\", productTotal - items.price);\n } else if (productTotal !== null) {\n productTotal = parseFloat(productTotal);\n localStorage.setItem(\"costTotal\", +productTotal + items.price);\n } else {\n localStorage.setItem(\"costTotal\", items.price);\n }\n}", "function calculateTotal(){\n let totalPrice = 0;\n $('#myCart #item').each(function(){\n totalPrice = totalPrice + $(this).data('price');\n })\n $('#price').text(`Total Price:Rs.${totalPrice}/-`)\n }", "function totalBill()\n{\n var result = 0.00;\n\n for (var i = 0; i < outstandingBill.length; i++)\n {\n result += outstandingBill[i].cost;\n }\n\n //console.log(\"bill total = \" + result);\n return result;\n}", "function priceIt(qty, cost)\n {\n var total = (parseFloat(cost) * qty);\n console.log(\"Your Total Cost is: $\"+total.toFixed(2));\n }", "function carttotal() {\n //multipily the price by the number of items in the cart\n producttotal = price * itemcount;\n var formatproducttotal = currencyFormat(producttotal);\n //note we are updating the BTC and Lightning totals here we will have to refactor this code is we ever\n // have a lightning only version of the cart (as stated elsewhere in the notes)\n changeClassText(document.getElementById('sr-lightningtotal'), 'Pay '+formatproducttotal + ' satoshi');\n changeClassText(document.getElementById('sr-bitcointotal'), 'Pay '+formatproducttotal + ' satoshi');\n changeClassText(document.getElementById('sr-checkouttotal'), formatproducttotal);\n //update counter\n changeClassText(document.querySelector('.sr-count'), itemcount);\n //store product\n if (serverless == 0) {\n var url = serverurl + \"api/storeproduct?name=\" + name + \"&quantity=\" + itemcount + \"&btcaddress=\" + btcaddress + \"&price=\" + price;\n //call the store produt endpoint\n fetchurl(url, 'storeproduct')\n }\n }", "function calcTotal() {\n for (var i=0; i<6; i++) { \n if (items[i].checked) {\n itemTotal += (items[i].value * 1);\n }\n}\n //calculate order total with sales tax\norderTotal = itemTotal + (itemTotal * salesTaxRate); \ndocument.getElementById(\"total\").innerHTML = \"Your total is $\" + orderTotal.toFixed(2) + \". Thank you for shopping!\";\n}", "function budgetCalculator(watch, phone, laptop){\n // cost every single item\n var watchCost = watch * 50;\n var phoneCost = phone * 100;\n var laptopCost = laptop * 500;\n //total cost of all item.\n var totalCost = watchCost + phoneCost + laptopCost;\n return totalCost;\n\n}", "calculateTotal() {\n let products = this.state.invoiceItems;\n let total = 0;\n products.forEach((el) => {\n total += el.price * el.quantity\n });\n\n if (this.state.discount) {\n total *= (100 - this.state.discount) / 100;\n }\n\n this.setState({\n total: (total).toFixed(2)\n }, this.updateInvoiceAPI);\n }", "totalPrice() {\n var total = 0;\n for (var i = 0; i < this.listItems.length; i++) {\n total += parseFloat(this.listItems[i].price);\n }\n return total.toFixed(2);\n }", "get amount() {\n\t\t\treturn this.items\n\t\t\t\t.map(item => item.qty * item.price)\n\t\t\t\t.reduce((total, qty) => total += qty, 0);\n\t\t}", "function updateCartTotal() {\n var cartItemContainer = document.getElementsByClassName('cart-items')[0];\n var cartRows = cartItemContainer.getElementsByClassName('cart-row');\n var total = 0;\n for (var i = 0; i < cartRows.length; i++) {\n var cartRow = cartRows[i];\n var priceElement = cartRow.getElementsByClassName('cart-price')[0];\n console.log(priceElement);\n var quantityElement = cartRow.getElementsByClassName('cart-quantity-input')[0];\n var price = parseFloat(priceElement.innerText.replace('$', ''));\n console.log(price);\n var quantity = quantityElement.value;\n console.log(quantity);\n total = total + (price * quantity);\n }\n total = Math.round(total * 100) / 100;\n document.getElementsByClassName('cart-total-price')[0].innerText = '$' + total;\n}", "function sumPrices(cartArray) {\n var sum = 0;\n for (var i = 0; i < cartArray.length; i++) {\n sum = sum + cartArray[i].price;\n }\n console.log(sum);\n}", "getTotalWithTax() {\n \n // total individual items from getPriceWithTax\n let totWithTax = 0;\n this.items.forEach((net) => {\n totWithTax += net.getPriceWithTax();\n });\n return totWithTax;\n }", "function getCartTotal(cart) {\n if(cart.length === 0){\n throw \"Error!\";\n }\n let result = 0;\n for (let product of cart) {\n result += product.priceInCents;\n }\n return result;\n}", "function getTotalCost(order) {\n var totalCost = 0;\n for (let key in order) {\n const cost = parseInt(getCostFromId(key));\n const no = order[key];\n totalCost += cost*no;\n }\n return totalCost;\n}", "function calculateTotal()\n{ \n\tvar total = 0;\n\tfor (var i = 0; i<document.getElementsByClassName(\"price\").length; i++)\n\t{\n\t\tvar price = document.getElementsByClassName(\"price\")[i].innerHTML;\n\t\ttotal += parseFloat(price.substring(1,price.length-1)); \n\t}\n\t\n\ttotal = total.toFixed(2);\n\tdocument.getElementById(\"total_cost\").innerHTML = total;\n\tupdateCheckOut();\n}", "function updateActivitiesPrice(activityItems) {\n activitiesTotalPrice = 0;\n for (let i=0; i<activityItems.length; i++) {\n if (activityItems[i].children[0].checked) {\n const activityCost = parseInt(activityItems[i].children[0].getAttribute('data-cost'));\n activitiesTotalPrice += activityCost;\n };\n }\n const activityCostText = document.getElementById('activities-cost');\n activityCostText.textContent = `Total: $${activitiesTotalPrice}`;\n}" ]
[ "0.73436016", "0.70795316", "0.6980859", "0.69061714", "0.6901665", "0.6887606", "0.6873818", "0.68311363", "0.6787308", "0.67554945", "0.67546827", "0.66837573", "0.66447794", "0.6642255", "0.6537481", "0.65290123", "0.6520859", "0.6513521", "0.6484745", "0.6463616", "0.6459446", "0.64439285", "0.6433054", "0.6417929", "0.6406212", "0.6405625", "0.6397073", "0.6344914", "0.6311004", "0.62932676", "0.6283061", "0.6254075", "0.6234193", "0.6227476", "0.6219865", "0.62126553", "0.6211558", "0.6202542", "0.61989886", "0.6193896", "0.61930287", "0.6191119", "0.61886084", "0.6186665", "0.6186662", "0.6164319", "0.6160295", "0.61568826", "0.61371344", "0.6137062", "0.6094144", "0.6092268", "0.6088793", "0.6062096", "0.60612446", "0.6057097", "0.6051796", "0.6050277", "0.6047368", "0.6039973", "0.60347307", "0.6028368", "0.6026691", "0.6026343", "0.59908867", "0.59647703", "0.59526086", "0.59492743", "0.59449285", "0.59363335", "0.59339297", "0.592741", "0.5925736", "0.592194", "0.5919386", "0.5918682", "0.59172416", "0.5913402", "0.59117335", "0.5894779", "0.58938855", "0.58720714", "0.5859233", "0.5857573", "0.5855253", "0.58450717", "0.58426094", "0.5825546", "0.58223295", "0.5819214", "0.58146745", "0.58136326", "0.5810063", "0.58045834", "0.58010834", "0.579315", "0.57804227", "0.5776524", "0.57695705", "0.5767095" ]
0.5872359
81
Shows a confirmation dialog box to confirm the user wants to remove an item from their basket
function confirmRemoveOrderMenuItem(itemId) { bootbox.confirm("Are you sure you want to remove this item?", function (result) { if (result) { removeOrderMenuItem(itemId); } }); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function deleteItem() {\r\n if (!confirm(\"Are you sure you want to delete?\")){\r\n return false;\r\n }else{\r\n return true;\r\n }\r\n}", "onClickRemoveItem() {\n let itemName = this.props.foodItem.food_name;\n let food_id = this.props.foodItem.food_id;\n\n if (window.confirm(\"Are you sure you want to delete \" + itemName + \"?\")) {\n // TODO: send delete request to the server\n\n this.props.removeItem(food_id);\n }\n }", "function remove_confirm() {\n\tvar msg;\n\tif (jstatus.toUpperCase() == \"R\") {\n\t\tmsg = \"\\nThis operation will remove the survey and permanently delete all data collected.\"\n\t\t\t+ \"\\n(Note this operation is not available for surveys in Production mode.) \\nAre you sure you want to continue?\\n\";\n\t} else if (jstatus.toUpperCase() == \"P\") {\n\t\tmsg = \"\\nThis operation will remove the survey from the available list and will archive any data collected.\\n\"\n\t\t\t+ \"Are you sure you want to continue?\\n\";\n\t} else {\n\t\tmsg = \"\\nThis operation will clear all submitted data and associated tracking data for this survey.\"\n\t\t\t+ \"\\n(Note this operation is not available for surveys in Production mode.)\\nAre you sure you want to continue?\\n\";\n\t}\n\tvar url = \"dropSurvey?s=\" + jid + \"&t=\" + jstatus;\n\tif (confirm(msg))\n\t\tlocation.replace(url);\n\telse\n\t\treturn;\n}", "function removeItem (link) {\n\tvar r = confirm(\"Are you sure to remove the item?\");\n\tif (r == true) {\n\t\t$.post(\"incl/remove_item_cart.php\", {\n\t\t\tlink: link\n\t\t\t}, function (data) {\n\t\t\t\tif (!data) {\n\t\t\t\t\tlocation.reload();\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\talert(data);\n\t\t\t\t}\n\t\t\t}\t\n\t\t);\n\t}\n\telse {\n\t\talert('NO');\n\t}\n}", "function deleteConfirm() {\n swal({\n title: \"Are you sure?\",\n text: \"You will not be able to recover this layer!\",\n type: \"warning\",\n showCancelButton: true,\n confirmButtonColor: \"#DD6B55\",\n confirmButtonText: \"Yes, delete it!\",\n closeOnConfirm: true\n },\n function(){\n\t\t\tremoveLayer();\n });\n}", "function removeCollectionItem()\r\n {\r\n if (confirm('Are you sure you want to remove this item and any data you may have entered for it?')) {\r\n var $this = $(this);\r\n $this.closest('.form-group').remove();\r\n\r\n // Trigger a form changed event\r\n $(document).trigger('formChangedEvent');\r\n }\r\n }", "function removeItem() {\n const productId = this.name;\n if(confirm(\"Voulez-vous supprimer le produit du panier ?\")) {\n let cartList = JSON.parse(sessionStorage.getItem(\"shoppingCartItems\"));\n cartList = cartList.filter(product => product.id != productId);\n sessionStorage.setItem(\"shoppingCartItems\", JSON.stringify(cartList));\n shoppingCartCount();\n populateShoppingCartPage();\n }\n}", "function removeCartItem() {\n const removeId = event.target.dataset.id;\n\n if (confirm(\"Are you sure you want to remove this item?\")) {\n let updatedCartItems = currentCartItems.filter(function (item) {\n if (removeId !== item.id) {\n return true;\n }\n });\n currentCartItems = updatedCartItems;\n saveToStorage(cartKey, updatedCartItems);\n displayCartItems();\n calculateCartTotal();\n createMenu();\n displayMessage(\n \"alert-success\",\n \"The item was successfully removed.\",\n \".message-container\"\n );\n }\n}", "function confirmDeleteItem(itemId, itemName) {\r\n\r\n let confirmDelete = confirm(\"Weet je zeker dat je '\" + itemName + \"' wilt verwijderen?\");\r\n\r\n if (confirmDelete) {\r\n window.location.href = (\"deleteTask.php?taskId=\" + itemId);\r\n }\r\n}", "function showConfirm() {\n confirm({\n title: 'Do you Want to delete these items?',\n icon: <ExclamationCircleOutlined />,\n content: 'Some descriptions',\n onOk() {\n const id = selectedRowKeys[0];\n fetchData('DELETE', { id }).then((res) => {\n if (res.ok) {\n setStateSelect({\n selectedRowKeys: []\n })\n onReset();\n setSelectedAudioBook({ isAdded: true, selected: null });\n }\n });\n },\n onCancel() {\n console.log('Cancel');\n },\n });\n }", "function confirmDeletion(){\n vex.dialog.open({\n message: \"Comment Has Been Deleted\",\n buttons:[\n $.extend({},vex.dialog.buttons.Yes,{text: \"OK\"})\n ],\n callback: function (data) {\n $(location).attr(\"href\", \"/\"); \n }\n });\n }", "function deleteItem() {\n\t\t\tvar item = itensGrid.selection.getSelected()[0];\n\t\t\t\n\t\t\tif (item) {\n\t\t\t\titensStore.deleteItem(item);\n\t\t\t} else {\n\t\t\t\tokDialog.set(\"title\", \"Atenção\");\n\t\t\t\tokDialogMsg.innerHTML = \"Selecione o item antes de excluir.\";\n\t\t\t\tokDialog.show();\n\t\t\t}\n\t\t}", "function deleteMenuItem() \n{\n\tif (!confirm(\"Realy delete?\")) return false;\n\twindow.location = \"/admin/structure/delete/\" + selectedItemID;\n\treturn true;\n}", "function removeItem(e) {\n // document.getElementById('ul_list').removeChild(e.target.parentElement);\n const isConfirmed = confirm('Are you sure you want to delete the item: ' + e.target.parentElement.querySelector('.todo-item').innerHTML);\n if(isConfirmed){\n deleteTodoItem(e.target);\n }\n}", "function removeItem(element){\n var product_id = $(element).data('id');\n confirm = confirm(\"Are you sure you want to remove this product from the cart?\");\n if(confirm) {\n var row = document.getElementById(`${product_id}`);\n row.remove();\n // $(`${product_id}`).detach();\n delete products[product_id];\n total = Object.keys(products).length\n localStorage.setItem('cart', JSON.stringify(products));\n localStorage.setItem('total', JSON.stringify(total));\n }\n }", "function confirmRemoveProduct(product_id)\r\n{\r\n document.getElementById('sitestoreproduct_cart_product_'+product_id).style.display = 'none';\r\n document.getElementById('sitestoreproduct_delete_cart_product_'+product_id).style.display = 'block';\r\n}", "function removeItem(e) {\n if (e.target.classList.contains('delete-btn')) {\n // var litext = e.target.classList.contains('item-list');\n //var litext = document.getElementsByClassName('item-list').innerText;\n // var txt = litext.innerHTML;\n if (confirm('Are you sure you want delete')) {\n \n var btn = document.querySelector('delete-btn');\n btn = e.target.parentElement;\n itemlist.removeChild(btn);\n }\n }\n}", "function preguntar() {\n confirmar = confirm('¿Desea eliminar el comentario?');\n if (confirmar) {\n deleteButtonClicked(event);\n } else {\n alert('Diste cancelar');\n }\n}", "function deleteItem() {\n\t\tvar ask = confirm(\"Delete this workout?\");\n\t\t// Confirm with the user to delete individual item //\n\t\tif(ask) {\n\t\t\tlocalStorage.removeItem(this.key);\n\t\t\twindow.location.reload();\n\t\t\talert(\"Workout has been deleted.\");\n\t\t\treturn false;\n\t\t// If declined, do not delete and alert the user //\n\t\t}else{\n\t\t\talert(\"Workout was not deleted.\");\n\t\t}\n\t}", "deleteItem() {\n if (window.confirm('Etes-vous sur de vouloir effacer cet outil ?')) {\n sendEzApiRequest(this.DELETE_ITEM_URI + this.props.id, \"DELETE\")\n .then((response) => {\n this.props.deleteButtonCB(this.props.tool)\n }, error => {\n alert(\"Impossible de suprimer l'outil\")\n\n console.log(error)\n })\n }\n }", "function showDialogForDeletingIndividualMyListItem(objectId) {\n\t\tvar dialog = new Dialog({\n\t\t\ttitle: 'Remove this save?',\n\t\t\ttype: 'confirm',\t\t\t\t\n\t\t\tmessage: 'Are you sure you want to remove this save?',\t\t\t\n\t\t\tbuttonsCssClass: 'my-list',\n\t\t\tshowCloseIcon: false,\n\t\t\tcloseButtonCssClass: 'btn-default',\n\t\t\tkeyboard: false,\n\t\t\tmoveable: true,\n\t\t\tbuttons: {\n\t\t\t\t'Remove': function() {\n\t\t\t\t\tremoveItem(selectedSaves, objectId);\n\t\t\t\t\tremoveListItem(objectId, true);\n\t\t\t\t}\n\t\t\t},\n\t\t});\n\t\t\n\t\tdialog.show();\n\t}", "function OnDeleteObjectClientClick(confirmMessage)\r\n{ \r\n return confirm(confirmMessage);\r\n}", "function deleteItemClickHandler(e) {\n e.stopPropagation();\n\n if (confirm(\"Are you sure you want to delete this item from your shopping cart\")) {\n var row = $(this).parents('tr');\n deleteItem(row.attr('data-id')).done(function () {\n //todo: refresh just the basket table not the whole page\n window.location = window.location;\n });\n }\n }", "function onRemoveYesClick() {\n // Close the modal.\n onCloseSpanClick();\n \n // Send a \"remove\" message to the server.\n sendMessage(2, currentModelHandle, null, null);\n}", "function confirmarEliminarCatMetal($idMetal) {\n alertify.confirm('Eliminar',\n 'Confirme eliminacion de articulo seleccionado.',\n function () {\n eliminarMetal($idMetal)\n },\n function () {\n alertify.error('Cancelado')\n });\n}", "function deleteFromList(element){\n if(confirm('Would you like to delete this item?') == 1){\n $(element).parent().remove();\n }\n}", "function confirmacion() {\r\n\treturn confirm(\"Esta seguro de eliminar el registro?\");\r\n}", "function confirm(e) {\n deleteQuestion(deleteId); //sending question id\n message.success(\"Deleted Successfully\");\n }", "function DeleteClick() {\n notyConfirm('Are you sure to delete?', 'DeleteSupplierPayment()');\n}", "function deleteItem() {\n var xmlhttp = new XMLHttpRequest();\n\n xmlhttp.onreadystatechange = function () {\n if (this.readyState == 4 && this.status == 200) {\n var text = this.responseText;\n $(\"#confirmDel\").text(text);\n }\n }\n\n xmlhttp.open(\"POST\", \"../stock/AdminDeleteFromStock.php\", true);\n xmlhttp.setRequestHeader(\"Content-type\", \"application/x-www-form-urlencoded\");\n xmlhttp.send(collectData());\n }", "function delete_item(obj,id,msg,url)\r\n{\r\n $(\"#\"+obj+'-'+id).click(function () {\r\n if (confirm(msg)) {\r\n document.location = url;\r\n }\r\n });\r\n}", "function removeTask(e){\n if(e.target.parentElement.classList.contains('delete-item'))\n {\n if(confirm('Are you sure about that ?')){\n e.target.parentElement.parentElement.remove(); \n } \n }\n}", "function confirmDelete() {\n\tconfirm('Are you sure you want to delete this post?');\n}", "deleteThisInvoice() { if(confirm('Sure?')) Invoices.remove(this.props.invoice._id); }", "function ui_delConfirmMsg(str_objname, str_newMsg, str_dest){\n\tvar _msg = \"Do you want to delete the \" + str_objname + \"? \\n\\nOnce the \" +\n\t\t\t\tstr_objname + \" is deleted, it cannot be recovered.\";\n\tif (ui_trim(str_newMsg).length !=0){\n\t\t_msg = str_newMsg;\n\t}\n\tif (window.confirm(_msg)){\n\t\tlocation.href = str_dest;\n\n\t}\n}", "function showDialogRemove() {\n var title = 'Remove Parts to Inventory'; \n var templateName = 'removeUi'; \n var width = 600; \n \n // custom function to insert part data into the dialog box. For code modularity and simplicity\n createDialogWithPartData(title,templateName,width);\n}", "_deleteItemConfirm(e) {\n // @todo delete the thing\n const evt = new CustomEvent(\"simple-modal-hide\", {\n bubbles: true,\n cancelable: true,\n detail: {}\n });\n this.dispatchEvent(evt);\n }", "remove() {\n let htmlMessage = `<div class=\"text-red\">Pour supprimer le produit <strong>${ this.modelName }</strong>, merci d'écrire son nom et de valider</div>`;\n this.$q.dialog({\n cancel: 'Annuler',\n html: true,\n message: htmlMessage,\n ok: 'Supprimer',\n persistent: true,\n prompt: { outlined: true },\n title: '<div class=\"text-red\">Supression</div>',\n }).onOk((name) => {\n name = name ? '' + name : '';\n if (name === this.modelName) {\n this.$q.loading.show({ spinner: QSpinnerGears });\n this.$store.dispatch(productConstants.PRODUCT_DO_DELETE, { productId: this.modelId })\n .then(() => this.$emit('cancel'))\n .finally(() => setTimeout(() => this.$q.loading.hide(), 500));\n }\n });\n }", "function eliminarventa() {\n\n var mensaje = confirm(\"¿Desea Eliminar Un accidente?\")\n\n if (mensaje) {\n alert(\"Accidente Eliminado\");\n }\n\n }", "function removeRequest() {\n\tinquirer.prompt([{\n\t\tname: \"ID\",\n\t\ttype: \"input\",\n\t\tmessage: \"What is the item ID of the you would like to remove?\"\n//once the manager enters the ID to delete the item than delete that particular item from the table.......\t\n\t}]).then(function (deleteItem) {\n\t\tconnection.query(\"DELETE FROM products WHERE ?\", {\n\t\t\titem_id: deleteItem.ID,\n\n\t\t}, function (err, res) {\n\t\t\tif (err) throw err;\n\t\t\tconsole.log(res);\n\t\t\tconsole.log(\"=====================================\");\n\t\t\tconsole.log(\"The item is deleted from Invetory..!!\");\n\t\t\tconsole.log(\"=====================================\");\n\n\n\t\t});\n\t\t//once the item is deleted display the most updated table............\n\t\tdisplayInventory();\n\t});\n}", "function areYouSure(){\n\t\t$(\"#stage\").append('<div id=\"dialog-removeContent\" title=\"Remove this item from the page.\"><p class=\"validateTips\">Are you sure that you want to remove this item from your page? Selecting \"Remove\" will also remove all button links to this branch.<br/><br/>This cannot be undone!</div>');\n\n\t $(\"#dialog-removeContent\").dialog({\n modal: true,\n width: 550,\n close: function (event, ui) {\n $(\"#dialog-removeContent\").remove();\n },\n buttons: {\n Cancel: function () {\n $(this).dialog(\"close\");\n },\n Remove: function(){\n\t removeOption();\n\t $(this).dialog(\"close\");\n }\n }\n });\n\t}", "function removeItem(key) {\n if (confirm('Etes-vous sûr de vouloir supprimer le produit?')) {\n // On supprime du localStorage la clé du produit\n delete cart[key]\n localStorage.setItem('cart', JSON.stringify(cart));\n keys = Object.keys(cart)\n if (keys.length === 0) {\n basketContent.innerHTML = '<h3>Le panier est vide</h3>'\n } else {\n // On supprime visuellement la ligne du tableau\n const line = document.querySelector(`[data-key=\"${key}\"]`)\n line.remove()\n // Recalcul du total du pannier\n document.querySelector(`#total`).innerHTML = getTotalCart();\n }\n }\n}", "function confirmDeleteAction()\r\n{\r\n if(confirm(\"Are You Sure To Delete This..!\")){\r\n return true;\r\n }else{\r\n return false;\r\n }\r\n}", "function SubmitDeleteCompanyConfirm() {\n confirm(\"Do you want to Delete this Company?\");\n}", "'click #remove'() {\n var id_listItem = this._id;\n swal({ \n title: \"Your task will be deleted!\", \n text: \"Are you sure to proceed?\", \n icon: \"warning\", \n buttons: [\n 'No, cancel it!',\n 'Yes, I am sure!'\n ],\n dangerMode: true,\n }).then(function(isConfirm)\n { \n if (isConfirm) \n { \n Meteor.call(\"task_list_remove\",id_listItem,function(error,result){\n if(error){\n alert(\"ERROR,THERE IS SOMETHING WRONG\");\n }\n else{\n swal({\n text : \"Your Task deleted\",\n icon : \"success\",\n });\n }\n }); \n } \n else{ \n swal(\"Your task is safe\"); \n } \n });\n }", "function confirmDeleteSchdTitle(){\n if(schdTitleListingEditorGrid.selModel.getCount() == 1) { //Userが1人しか登録されていな場合の処理\n Ext.MessageBox.confirm('[ 確認!]','削除します、よろしいですか?', deleteSchdTitle);\n } else if(schdTitleListingEditorGrid.selModel.getCount() > 1) { \n Ext.MessageBox.confirm('[ 削除!]','削除します!', deleteSchdTitle);\n } else {\n Ext.MessageBox.alert('[ 確認!]','削除できません…削除行を選択していますか?');\n }\n }", "function handleRemove(){\r\n //making sure it does not remove if there are 0 items\r\n if (quantity.innerHTML !== \"0\"){\r\n quantity.innerHTML = parseInt(quantity.innerHTML)-1;\r\n }\r\n //disabling the \"agree\" button when there are no items\r\n if (quantity.innerHTML === \"0\"){\r\n agree.disabled = true;\r\n } \r\n }", "function eliminar(num){\r\n\tvar confirmar=confirm(\"Realmente desea eliminar este proveedor para este producto???\");\r\n\tif(confirmar==false){\r\n\t\treturn false;\r\n\t}\r\n//quitamos fila de la tabla\r\n\t$(\"#fila_\"+num).remove();\r\n\treturn true;\r\n}", "function remove(key){\n\n var result = confirm('Sunteti sigur ca vreti sa stergeti acest produs din cos?');\n\n if(result == true){\n\n localStorage.removeItem(key);\n drawCart();\n numberProducts();\n } else {\n\n return false;\n }\n}", "function removeCartItem(event) {\n\tvar buttonClicked = event.target;\n\tbuttonClicked.parentElement.parentElement.remove();\n\tupdateCartTotal()\n}", "function removeItem() {\n\t// if there are any items in the shoppingCart Array\n\tif (shoppingCart.length > 0) {\n\t\t// prompt to figure out what item they want to remove \n\t\tinquirer.prompt({\n\t\t\tmessage: \"Which Item would you like to remove?\",\n\t\t\tname: \"removeItem\",\n\t\t\ttype: \"list\",\n\t\t\t// the choices are from the current shopping list\n\t\t\tchoices: function () {\n\t\t\t\tvar returnItems = [];\n\t\t\t\tfor (var i = 0; i < shoppingCart.length; i++) {\n\t\t\t\t\treturnItems.push(shoppingCart[i].product_name);\n\t\t\t\t}\n\t\t\t\treturn returnItems;\n\t\t\t}\n\t\t})\n\t\t\t.then(function (removeQ) {\n\t\t\t\t// loop through the shopping cart to compare the .product name against the selection for the remove item, then use the hoisted function to remove the item at the iteration\n\t\t\t\tfor (var i = 0; i < shoppingCart.length; i++) {\n\t\t\t\t\tvar sC = shoppingCart[i];\n\t\t\t\t\tif (sC.product_name === removeQ.removeItem) {\n\t\t\t\t\t\t// subtract the cost of the items from the cartPrice\n\t\t\t\t\t\tcartPrice -= (sC.purchaseQTY * sC.price_customer);\n\t\t\t\t\t\tshoppingCart.remove(i);\n\t\t\t\t\t\tconsole.log(\"Removed \" + sC.purchaseQTY + \" \" + sC.product_name + \" From the Cart.\")\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t// get more input from the user\n\t\t\t\tnextAction();\n\t\t\t})\n\t}\n\t// if there are no items in shoppingCart, redirect the user\n\telse {\n\t\tconsole.log(\"We can't remove items since your cart is empty\");\n\t\tnextAction();\n\t}\n}", "function DeleteItemFromMyQuestList(event) {\n\n //event.preventDefault();\n\n // Pop up a confirmation dialog\n var confirmation = confirm('Are you sure you want to remove this Quest from your list?');\n\n // Check and make sure the user confirmed\n if (confirmation === true) {\n \n \n\n // If they did, do our delete\n $.ajax({\n type: 'DELETE',\n url: '/AppEngine/deleteQuestFromMyList/' + localStorage.getItem('QuestToDelete')\n }).done(function( response ) {\n\n // Check for a successful (blank) response\n if (response.msg === '') {\n }\n else {\n alert('Error: ' + response.msg);\n }\n\n // Update the table\n //populateQuestsTable();\n\n });\n\n }\n else {\n\n // If they said no to the confirm, do nothing\n return false;\n\n }\n\n}", "function areYouSure(){\n\t\t$(\"#stage\").append('<div id=\"dialog-removeContent\" title=\"Remove this item from the page.\"><p class=\"validateTips\">Are you sure that you want to remove this item from your page? <br/><br/>This cannot be undone!</div>');\n\n\t $(\"#dialog-removeContent\").dialog({\n modal: true,\n width: 550,\n close: function (event, ui) {\n $(\"#dialog-removeContent\").remove();\n },\n buttons: {\n Cancel: function () {\n $(this).dialog(\"close\");\n },\n Remove: function(){\n\t removeReveal();\n\t $(this).dialog(\"close\");\n }\n }\n });\n\t}", "function del_all_item(){\n\n Swal.fire({\n title: 'Are you sure?',\n text: \"You Want to Delete Whole TODO List!\",\n icon: 'warning',\n showCancelButton: true,\n confirmButtonColor: '#3085d6',\n cancelButtonColor: '#d33',\n confirmButtonText: 'Yes, delete it!'\n }).then((result) => {\n if (result.value) {\n li.innerHTML=\"\";\n Swal.fire(\n 'Deleted!',\n 'Your TODO List Has Been Deleted.',\n 'success'\n )\n }\n })\n}", "function promptDelete(id) {\n\n if (confirm(\"Are you sure you want to delete this DVD from your collection?\")) {\n\n $.ajax({\n type: 'DELETE',\n url: 'http://localhost:8080/dvd/' + id,\n });\n $(`#row${id}`).hide();\n };\n}", "function deleteList(){\n if(confirm(\"Tem Sertesa que deseja excluir a tabela?\")){\n list = '';\n setList(list);\n }\n}//fim", "function preguntarSiNo(codigo){\r\n\talertify.confirm('Eliminar Proveedor', '¿Esta seguro de eliminar este Proveedor?', \r\n\t\t\t\t\tfunction(){ eliminarDatos(codigo) }\r\n , function(){ alertify.error('Se cancelo')});\r\n}", "handleItemDelete(event, item) {\n // eslint-disable-next-line no-alert\n if (confirm(i18n._t('AssetGalleryField.CONFIRMDELETE'))) {\n this.props.actions.gallery.deleteItems(this.props.deleteApi, [item.id]);\n }\n }", "function deleteVerify(){\n var choice = dialog.showMessageBoxSync(\n {\n type: 'question',\n buttons: ['delete project', 'maybe not', 'cancel'],\n title: 'Confirm',\n message: 'Are you sure you want to delete the project \"'+currentProjectTitle+'\"?'\n });\n if(choice === 0){//cancel\n return true;\n }\n else {//kill it\n return false;\n }\n}", "function removeItemFromCart(){\n\n}", "function postDelete() {\n console.log('item deleted');\n swal({\n title: \"Dare Approved!\",\n icon: \"success\",\n button: \"Done\"\n })\n .then( () => {\n location.reload();\n })\n }", "function eliminaProducto (paramDelete) { \n let encontrado = false;\n let posItem;\n for (i=0; i < carrito.length; i++){\n if (carrito[i].id == paramDelete){\n posItem = carrito.indexOf(carrito[i]);\n encontrado = true;\n }\n }\n let respElimina = confirm(\"¿Quiere eliminar del carro de la compra el producto seleccionado? Código: \" + carrito[posItem].id +\" - \" + carrito[posItem].name);\n if (respElimina === true && encontrado === true) {\n carrito.splice(posItem,1);\n //estructuraPrincipalCarrito();\n filterItem ();\n }\n}", "function deleteFromCart(item){\n item.parentElement.remove();\n showTotals();\n}", "function remove() {\n if ($window.confirm('Are you sure you want to delete?')) {\n vm.clientmanagement.$remove()\n .then(function(){\n $state.go('clientmanagements.list');\n });\n\n }\n }", "function deletechecked(message)\r\n{\r\n var answer = confirm(message);\r\n \r\n return answer; \r\n}", "function RemoveItem(item){\n var index = basket.indexOf(item);\n if (index > -1) {\n console.log(\"Taking \" + item.Name + \" out of the basket!\");\n basket.splice(index, 1);\n return;\n }\n Console.log(item.Name + \" is not in the basket!\");\n}", "function deleteItem(divId) {\n if (confirm('Are you sure you want to delete icon with ID: ' + divId)) {\n deleteLink(divId);\n } else {\n // do nothing\n }\n resetModalContent();\n}", "function removeCartItem(event) {\r\n var buttonClicked = event.target;\r\n buttonClicked.parentElement.parentElement.remove();\r\n updateCartTotal();\r\n }", "function remove() {\n if (confirm('Are you sure you want to delete?')) {\n vm.calendarEvent.$remove($state.go('calendarEvents.list'));\n }\n }", "function removeTask2(e) {\n console.log(\"yep\");\n if (e.target.parentElement.classList.contains(\"delete-item\")) {\n console.log(\"yep del\");\n if (confirm(\"Are You Sure about that ? \")) {\n e.target.parentElement.parentElement.remove();\n }\n }\n}", "function confirmDelete(){\n\treturn confirm('Are you sure you want to delete this post?');\n}", "function fosterRemoveItem(e){\n console.log(e.target.id)\n let itemname = e.target.id\n console.log(itemname)\n for (let item in basket){\n if (itemname == basket[item]['name']){\n basket.splice(item, 1)\n fosterStorage['foster-basket'] = JSON.stringify(basket)\n console.log(fosterStorage.getItem('foster-basket'))\n createBasket()\n }\n }\n if ((fosterStorage.getItem('foster-basket')).length > 0){\n window.location.href = \"foster_page.html\"\n }\n \n }", "function deleteTodo(index) {\n // show confirm box\n var deleteConfirmation = confirm(\"Are you sure?\");\n // if yes delete or if no dont delete\n if (deleteConfirmation) {\n // delete item from the todo array\n todoList.splice(index, 1);\n showDOMList();\n\n // todo: will show a good looking notification message\n }\n}", "confirm(e) {\n this.props.deleteMessageFromMessageList(this.props.messageID)\n }", "function ArchiveCompanyConfirm() {\n confirm(\"Do you want to Archive this Company?\");\n}", "delete() {\n\n // propmt the user to confirm before deleting\n if( ! confirm(\"Are you sure you want to delete?\") ){\n return;\n }\n\n // remove the row from the table\n table.deleteRow( this.order.getRowIndex() + 1 );\n orders.splice( this.order.getRowIndex(), 1);\n \n // clear the form and selected order\n this.cancel();\n }", "function confirmDeleteKunden(){\r\n\tif(KundenSelectModel.getCount() == 1) // only one president is selected here\r\n\t{\r\n\t Ext.MessageBox.confirm('Confirmation','Kunden entfernen?', deleteKunden);\r\n\t} else {\r\n\t Ext.MessageBox.alert('Uh oh...','You can\\'t really delete something you haven\\'t selected huh?');\r\n\t}\r\n} // eo confirmDeleteKunden", "function removeDone() {\n var deleteDone = confirm(\"Do you really want to remove completed the tasks?\");\n //if user clicks okay returns true. Gives and empty string for tasksDone list\n if (deleteDone == true) {\n document.getElementById(\"tasksDone\").innerHTML=\"\"\n //Saved in local storage and updating taskCount\n updateLocalStorage()\n taskCount();\n } \n}", "function col5_onclick(){\n if(confirm(\"Are you sure you want to delete this entry?\") == true ){\n gEmployee.splice(this.index, 1);\n saveEmployee();\n displayEmployee();\n }\n}", "function deleteOffer() {\n\tvar id = $('input#offerId').val();\n\tbootbox.confirm(__(\"Are you sure you want to move this offer to trash?\"),__('No'),__('Yes'),function(r){\n\t\tif(!r){\n\t\t\treturn false;\n\t\t}\n\t\telse{\n\t\t\tdeleteRecord(id);\n\t\t}\n\t\t\n\t});\n\t \n}", "function confirmDelete(itemId) {\n\n\tvar display = false;\n\n\tif (ap.endsWith(itemId, '_wrapperDiv'));\n\t\titemId = itemId.replace('_wrapperDiv','');\n\n\t//find the first acceptable thing to display\n\tif (!display && dojo.byId(itemId+\".@title\"))\n\t\tdisplay = dojo.byId(itemId+\".@title\").value;\n\t//these two cases are for transactions which have no leading .\n\telse if (!display && ap.beginsWith('N', itemId, true) && dojo.byId(\"@title\"))\n\t\tdisplay = dojo.byId(\"@title\").value;\n\telse if (!display && ap.beginsWith('N', itemId, true) && dojo.byId(\"@id\"))\n\t\tdisplay = dojo.byId(\"@id\").value;\n\t//end transaction cases\n\telse if (!display && dojo.byId(itemId+\".@legend\"))\n\t\tdisplay = dojo.byId(itemId+\".@legend\").value;\n\telse if (!display && dojo.byId(itemId+\".@label\"))\n\t\tdisplay = dojo.byId(itemId+\".@label\").value;\n\telse if (!display && dojo.byId(itemId+\".@name\"))\n\t\tdisplay = dojo.byId(itemId+\".@name\").value;\n\telse if (!display && dojo.byId(itemId+\".@target\"))\n\t\tdisplay = dojo.byId(itemId+\".@target\").value;\n\telse if (!display && dojo.byId(itemId+\".@id\"))\n\t\tdisplay = dojo.byId(itemId+\".@id\").value;\n\telse if (!display && dojo.byId(itemId+\".@key\"))\n\t\tdisplay = dojo.byId(itemId+\".@key\").value;\n\telse if (!display && dojo.byId(itemId+\".@content\"))\n\t\tdisplay = dojo.byId(itemId+\".@content\").value;\n\telse if (!display && dojo.byId(itemId) && (dojo.byId(itemId).nodeName=='INPUT' || dojo.byId(itemId).nodeName=='SELECT'))\n\t\tdisplay = dojo.byId(itemId).value;\n\telse if (!display && dojo.byId(itemId+\"_type\"))\n\t\tdisplay = dojo.byId(itemId+\"_type\").value;\n\telse\n\t\tdisplay = itemId;\n\n\treturn confirm(\"Are you sure that you want to delete : \" +display);\n}", "function removeTask(e) {\n\n if (e.target.parentElement.classList.contains('delete-item')) {\n if (confirm('Are you sure!!')) {\n e.target.parentElement.parentElement.remove();\n }\n }\n removeItemFromLocalStorage(e.target.parentElement.parentElement);\n}", "function pop(x) {\n\t\tif (x) {\n\t\t\tvar agree = confirm(\"<?php echo l('js_delete1'); ?>\");\n\t\t\tif (agree) {\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\tvar agree = confirm(\"<?php echo l('js_delete2'); ?>\");\n\t\t\tif (agree) {\n\t\t\t\treturn true;\n\t\t\t} else {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t}", "function removeCartItem(event) {\n var buttonClicked = event.target;\n buttonClicked.parentElement.parentElement.remove();\n updateCartTotal();\n}", "function removeTask(e) {\n console.log(\"yep\");\n if (e.target.parentElement.classList.contains(\"delete-item\")) {\n console.log(\"yep del\");\n if (confirm(\"Are You Sure about that ? \")) {\n e.target.parentElement.parentElement.remove();\n }\n }\n}", "function ConfirmDelete(listing_id){\n if(confirm('Warning: If you delete this listing, all images associated with it will also be deleted. Are you sure you wish to continue?')){\n // if confirmed, call deletion script and send provided 'listing_id'\n window.location.href='delete.php?listing_id=' + listing_id;\n } else{\n // if user clicks cancel to delete prompt, return to page without refresh\n return false;\n }\n \n}", "function removeItemFromCart(event) {\n if (event.target.type === 'button') {\n currentInventory.removeItem(event.target.name);\n currentInventory.saveToLocalStorage();\n renderTable();\n }\n}", "onRemove(e) {\n e.stopImmediatePropagation();\n const model = this.model;\n\n if (confirm(config.deleteAssetConfirmText)) {\n model.collection.remove(model);\n }\n }", "function removeTask() {\n var result = confirm('Permanently delete this task?');\n if (result) {\n var values = {};\n values.id = $(this).data('id');\n console.log($(this).data('id'));\n\n $.ajax({\n type: 'POST',\n url: 'task/remove',\n data: values,\n success: function () {\n updateTaskList();\n }\n });\n }\n}", "function deleteConfirm(todoId) {\n $(function() {\n $(\"#dialog-confirm\").dialog({\n resizable: false,\n height: \"auto\",\n width: 270,\n modal: true,\n dialogClass: \"no-close\",\n buttons: {\n \"Delete Task\": function() {\n deleteTodo(todoId);\n $(this).dialog(\"close\");\n },\n Cancel: function() {\n $(this).dialog(\"close\");\n }\n }\n });\n });\n }", "function removeCartItem(event) {\n var buttonClicked = event.target\n buttonClicked.parentElement.parentElement.parentElement.remove();\n //Update the cart total after the cart item has been removed.\n updateCartTotal()\n }", "function removeTask(e) {\n if (e.target.parentElement.classList.contains('delete-item')) {\n if (confirm('Are you sure?')) {\n e.target.parentElement.parentElement.remove();\n\n removeTaskFromLocalStorage(Number(e.target.parentElement.parentElement.id.substring(5)))\n }\n }\n}", "function deleteItem(pos, bookid){\n /*\n - confirm : delete?\n - false=> return\n - true :\n - send ajax request to server : delete?book=bookid\n - reload page;\n */\n\n if(!window.confirm(\"Delete item ?\")) return;\n\n //send ajax request :\n let xhttp = new XMLHttpRequest();\n xhttp.onreadystatechange = function(){\n if(this.readyState==4 && this.status==200){\n window.alert(\"Delete item successfully\");\n window.setTimeout(function () {\n window.location.href = \"shoppingcart\";\n },500);\n }\n };\n xhttp.open(\"GET\", \"delete?book=\"+bookid, true);\n xhttp.send();\n\n}", "function confirmPrompt(newStock, updateId) {\n\n\tinquirer.prompt([{\n\n\t\ttype: \"confirm\",\n\t\tname: \"add\",\n\t\tmessage: \"Are you sure you would like to add this item and quantity?\",\n\t\tdefault: true\n\n\t}]).then(function (addConfirm) {\n\t\tif (addConfirm.add === true) {\n\t\t\t\n\n\t\t\tconnection.query(\"UPDATE products SET ? WHERE ?\", [{\n\t\t\t\tstock_quantity: newStock\n\t\t\t}, {\n\t\t\t\titem_id: updateId\n\t\t\t}], function (err, res) { });\n\n\t\t\tconsole.log(\"=================================\");\n\t\t\tconsole.log(\"Quantity added to the inventory.\");\n\t\t\tconsole.log(\"=================================\");\n\t\t\tdisplayInventory();\n\t\t}\n\t});\n}", "function initDelete() {\n\t\t\t$list.find('[aria-click=\"delete\"]').on('click', function () {\n\t\t\t\tvar $item = $(this).closest('.item');\n\n\t\t\t\tpopupPrompt({\n\t\t\t\t\ttitle: _t.form.confirm_title,\n\t\t\t\t\tcontent: _t.investor.view.manager.delete_confirm,\n\t\t\t\t\ttype: 'warning',\n\t\t\t\t\tbuttons: [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\ttext: _t.form.yes,\n\t\t\t\t\t\t\ttype: 'warning',\n\t\t\t\t\t\t\thandle: function () {\n\t\t\t\t\t\t\t\ttoggleLoadStatus(true);\n\t\t\t\t\t\t\t\t$.ajax({\n\t\t\t\t\t\t\t\t\turl: '/investors/delete/' + $item.data('value'),\n\t\t\t\t\t\t\t\t\tmethod: 'POST',\n\t\t\t\t\t\t\t\t\tcontentType: 'JSON'\n\t\t\t\t\t\t\t\t}).always(function () {\n\t\t\t\t\t\t\t\t\ttoggleLoadStatus(false);\n\t\t\t\t\t\t\t\t}).done(function (data) {\n\t\t\t\t\t\t\t\t\tif (data.status == 0) {\n\t\t\t\t\t\t\t\t\t\t$item.parent().remove();\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\tpopupPrompt({\n\t\t\t\t\t\t\t\t\t\t\ttitle: _t.form.error_title,\n\t\t\t\t\t\t\t\t\t\t\tcontent: _t.form.error_content,\n\t\t\t\t\t\t\t\t\t\t\ttype: 'danger'\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}).fail(function () {\n\t\t\t\t\t\t\t\t\tpopupPrompt({\n\t\t\t\t\t\t\t\t\t\ttitle: _t.form.error_title,\n\t\t\t\t\t\t\t\t\t\tcontent: _t.form.error_content,\n\t\t\t\t\t\t\t\t\t\ttype: 'danger'\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}\n\t\t\t\t\t\t},\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\ttext: _t.form.no\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}", "function removeTask(e) {\n if(e.target.parentElement.classList.contains\n ('delete-item')) {\n if(confirm('Are You Sure?')) {\n e.target.parentElement.parentElement.remove();\n //Remove from LS\n removeTaskFromLocalStorage\n (e.target.parentElement.parentElement);\n\n \n }\n}\n\n}", "function eliminaSingolo(elemento){\n\tif (confirm('Confermare la cancellazione di questo punteggio?')) { \n\tfunzioneCancella(elemento);\n }\n}", "deleteProjectConfirm(project) {\n actions.showDialog({name: 'deleteProjectConfirm', project: project});\n }", "function removeHandler(e) {\n const removeId = e.target.parentElement.getAttribute(\"data-task-id\");\n\n if (confirm(\"Are you sure ?!\")) {\n const foundIndex = toDoList.findIndex((el) => {\n return el.idNum === removeId;\n });\n\n toDoList.splice(foundIndex, 1);\n\n commitToLocalStorage(toDoList);\n reRender();\n }\n}", "takeout(item) {\n var index = this.item.indexOf(item);\n if (this.open = true && index > -1) {\n this.item.splice(index, 1);\n alert(\"Item has been removed from the backpack.\");\n }\n }" ]
[ "0.72921664", "0.72399825", "0.70993197", "0.703807", "0.7005282", "0.6941291", "0.6918663", "0.6830213", "0.6817102", "0.6814808", "0.67819047", "0.677778", "0.6776285", "0.67742777", "0.67436516", "0.67349595", "0.6697379", "0.66814893", "0.6665107", "0.6653398", "0.66205174", "0.66142756", "0.66053826", "0.6580068", "0.6576426", "0.6561024", "0.65597516", "0.6559471", "0.6557748", "0.6553792", "0.6547152", "0.6542561", "0.65162003", "0.6505338", "0.6474098", "0.6463452", "0.6455116", "0.6453588", "0.64295274", "0.64254105", "0.64111173", "0.63984", "0.6395756", "0.6388586", "0.63806945", "0.636226", "0.63592553", "0.6356984", "0.6351799", "0.6351797", "0.6345577", "0.6334595", "0.6332266", "0.6322493", "0.63222146", "0.631906", "0.631663", "0.63158995", "0.63083816", "0.630425", "0.630009", "0.6297617", "0.62957436", "0.6281494", "0.6280328", "0.6276384", "0.6275623", "0.62668866", "0.626479", "0.6262128", "0.6256978", "0.6253034", "0.6249181", "0.6243652", "0.6233828", "0.62326384", "0.62298477", "0.62256616", "0.6225207", "0.6224446", "0.62242883", "0.6223768", "0.6217756", "0.621181", "0.6210772", "0.62103647", "0.6201871", "0.6201721", "0.6200245", "0.6188327", "0.6188186", "0.6187745", "0.6186287", "0.6180787", "0.6179129", "0.6176751", "0.6173424", "0.615947", "0.6154374", "0.6148156" ]
0.77474517
0
Removes a menu item from the customers order
function removeOrderMenuItem(itemId) { const dataToSend = JSON.stringify({orderMenuItemId: itemId}); post("/api/authTable/removeItemFromOrder", dataToSend, function (data) { if (data === "success") { const parent = document.getElementById("order"); const child = document.getElementById("ordermenuitem-" + itemId); parent.removeChild(child); // Remove it from the basket array for (let i = 0; i < basket.length; i++) { if (basket[i].id === itemId) { basket.splice(i, 1); } } // Recalculate the price calculateTotal(); } }) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function removeItemFromMenu(event) {\n if(event.target.classList.contains('removelistitem')) {\n menu.removeItem(event.target.id);\n menu.saveToLocalStorage();\n renderMenuTable();\n }\n}", "removeDishFromMenu(item) {\n this.menu = this.menu.filter(element => element.id !== item.id);\n\n this.notifyObservers({type: \"menu\", index: this.menu});\n }", "function removeItem(itemName) {\n order.subtotal = round(order.subtotal - order.items[itemName].price);\n order.tax = round(order.subtotal * 0.1);\n order.total = round(order.subtotal + order.tax + order.delivery);\n if (order.items[itemName].count > 1) {\n order.items[itemName].count -= 1;\n } else {\n delete order.items[itemName];\n }\n let restaurantDiv = document.getElementById(\"restaurant\");\n // Generate order summary div \n restaurantDiv.replaceChild(createOrderDiv(restaurantData.menu), document.getElementById(\"restaurant\").lastChild);\n}", "function removeFromOrder(item) {\n var table = getCurrentTable();\n if (table === \"error\") return;\n var key = getIdFromName(item.split(':')[0]);\n var dic = table.item_id;\n if (dic[key] == 1) {\n delete table.item_id[key];\n } else {\n table.item_id[key]--;\n }\n showOrder(currentTableID);\n return;\n}", "function deleteMenuItem(req, res) {\n FoodItem.findOne({_id: req.body.itemID}, function(err, item) {\n if (err) throw err;\n if(item === null) {\n return res.send(\"Error: no such item\");\n }\n item.remove(function(err) {\n if (err) throw err;\n return res.send(\"Success\");\n });\n });\n}", "function removeItem(id){\r\n\tif(order.hasOwnProperty(id)){\r\n\t\torder[id] -= 1;\r\n\t\tif(order[id] <= 0){\r\n\t\t\tdelete order[id];\r\n\t\t}\r\n\t\ttemp = getCurrentRestaurant();\r\n\t\tif (temp !== undefined){\r\n\t\t\tupdateOrder(temp);\r\n\t\t}\r\n\t}\r\n}", "function remove_item() {\n for (var i=0; i<selected_items.length; i++) {\n items.splice(selected_items[i],1);\n }\n $('#inventory_grid').html('');\n populate_inventory_grid();\n $('#item_action_menu').hide();\n selected_items = [];\n }", "function removeItemFromCart() {\n var itemID = $(this).attr(\"id\");\n var positionInCart = itemID.slice(14, itemID.length);\n cartItems.splice(positionInCart, 1);\n updateCartDetails();\n}", "removeItem(value){\n var itemsInCartTemp = this.state.itemsInCart;\n for(let i = 0; i < itemsInCartTemp.length; i++){\n if(itemsInCartTemp[i].id === value){\n itemsInCartTemp.splice(i, 1);\n }\n }\n this.setState({\n itemsInCart: itemsInCartTemp,\n menuItems: [\n { name: 'donate', title: 'Donate' },\n { name: 'bills', title: 'KZSC Bills' },\n { name: 'merch', title: 'Merchandise' },\n { name: \"cart\", title: \"Your Cart\", label: itemsInCartTemp.length }\n ]\n })\n this.updateMerchAmount()\n }", "removeItem() {\n // Remove Item from Order's Items array:\n this.order.removeItem(this.item);\n // Update current Order:\n this.orderService.setCurrentOrder(this.order);\n this._closeEditItem(); // Close edit Product modal view:\n }", "removeMenuItem(itemId) {\n let notesMenu = document.querySelectorAll('[name=\"js-notes-menu\"], [name=\"js-folder-notes-menu\"]');\n\n notesMenu.forEach( menu => {\n let existingNote = menu.querySelector('[data-id=\"' + itemId + '\"]');\n\n if (existingNote) existingNote.remove();\n });\n }", "function deleteItemFromGame(object) {\n\tgame_menu.removeChild(object);\n\tstage.update();\n}", "function minusItem() {\n const productId = this.name;\n const cartList = JSON.parse(sessionStorage.getItem(\"shoppingCartItems\"));\n const index = cartList.findIndex(product => product.id == productId);\n cartList.splice(index, 1);\n sessionStorage.setItem(\"shoppingCartItems\", JSON.stringify(cartList));\n shoppingCartCount();\n populateShoppingCartPage();\n}", "function deleteMenu() {\n inquirer.prompt({\n type: \"list\",\n name: \"action\",\n message: \"What would you like to remove?\",\n choices: [\n { name: \"Remove a department\", value: deleteDepartment },\n { name: \"Remove a role\", value: deleteRole },\n { name: \"Remove an employee\", value: deleteEmployee },\n { name: \"Go back\", value: mainMenu }\n ]\n }).then(({ action }) => action());\n}", "function removeItem(){\n var selectedDiv = this.closest(\"div\");\n var itemName = selectedDiv.querySelector(\".item-name\")\n cart.forEach(function (cartItem){\n if(itemName.innerHTML === cartItem.name){\n var cartItemIndex = cart.indexOf(cartItem); \n cart.splice(cartItemIndex, 1)\n }\n })\n selectedDiv.parentNode.removeChild(selectedDiv) \n}", "function deleteMenuByType(type, menuItems) {\n \tfor (var i = 0; i < menuItems.length; i ++) {\n \t\tvar item = menuItems[i];\n \t\tif (item['_type'] && (item['_type'] === type.toLowerCase())) {\n \t\t\t menuItems.splice(i, 1);\n }\n \t}\n }", "function removeItem() {\n removeRequestedItem(requestedItem);\n }", "function confirmRemoveOrderMenuItem(itemId) {\n bootbox.confirm(\"Are you sure you want to remove this item?\",\n function (result) {\n if (result) {\n removeOrderMenuItem(itemId);\n }\n });\n}", "function removeOneItemFromCart() {\n var itemID = $(this).attr(\"id\");\n var positionInCart = itemID.slice(13, itemID.length);\n cartItems[positionInCart][3] -= 1;\n if (cartItems[positionInCart][3] === 0) {\n cartItems.splice(positionInCart, 1);\n }\n updateCartDetails();\n}", "function DDLightbarMenu_Remove(pIdx)\n{\n\tif ((typeof(pIdx) != \"number\") || (pIdx < 0) || (pIdx >= this.items.length))\n\t\treturn; // pIdx is invalid\n\n\tthis.items.splice(pIdx, 1);\n\tif (this.items.length > 0)\n\t{\n\t\tif (this.selectedItemIdx >= this.items.length)\n\t\t\tthis.selectedItemIdx = this.items.length - 1;\n\t}\n\telse\n\t{\n\t\tthis.selectedItemIdx = 0;\n\t\tthis.topItemIdx = 0;\n\t}\n}", "function cleanMenu(menu) {\n var i;\n for (i = 0; i < commands.length; i++) {\n menu.removeMenuItem(commands[i]);\n }\n }", "function deleteMenu() {\n randomize_button.remove();\n submit_num.remove();\n num_stars_input.remove();\n submit_num_planets.remove();\n num_planets_input.remove();\n if (set_stars != null) {\n set_stars.remove();\n }\n if (preset_binary != null) {\n preset_binary.remove();\n }\n if (tatooine != null) {\n tatooine.remove();\n }\n deleteInputInterface();\n}", "function _removeMenuItem(rest, itemName) {\n var arr = rest.menus[rest.itemRefs[itemName]]\n for (var i = 0, run = arr.length; i < run; i++) {\n (arr[i].name == itemName) ? arr.shift(): arr.push(arr.shift())\n }\n const menuName = rest.itemRefs[itemName]\n rest.itemRefs[itemName] = undefined\n return `No one is eating our ${itemName} - it has been removed from the ${menuName} menu!`\n}", "function removeMenu(id){\n return db('menu')\n .where({ id })\n .del()\n}", "function removeItem(item){\n\t\titem.parentNode.parentNode.parentNode.parentNode.removeChild(item.parentNode.parentNode.parentNode);\n\t\tLIST[item.parentNode.id].trash = true;\n\t}", "_deleteItem() {\n this.splice('cart', this.itemNumber, 1);\n if (this.itemNumber > (this.cart.length - 1)) {\n window.history.go(-1);\n }\n console.log(this.cart);\n this.setCartItem();\n this._computeNewItemNumber(this.itemNumber)\n }", "function removeItem() {\n const productId = this.name;\n if(confirm(\"Voulez-vous supprimer le produit du panier ?\")) {\n let cartList = JSON.parse(sessionStorage.getItem(\"shoppingCartItems\"));\n cartList = cartList.filter(product => product.id != productId);\n sessionStorage.setItem(\"shoppingCartItems\", JSON.stringify(cartList));\n shoppingCartCount();\n populateShoppingCartPage();\n }\n}", "function handleDelete(key){\n let quantity = tableItems[currentTableId - 1].itemsOrdered[key];\n delete tableItems[currentTableId - 1].itemsOrdered[key];\n // now update total bill\n let amountToBeDeducted = parseFloat(menuItems[key - 1].cost) * quantity;\n tableItems[currentTableId - 1].totalBill -= amountToBeDeducted;\n // reduce the total items\n tableItems[currentTableId - 1].itemCount -= quantity;\n updateModalContents();\n updateTable();\n}", "function deleteFromCart(item){\n item.parentElement.remove();\n showTotals();\n}", "function removeMobileMenuItem() {\n $(\"li.menuparent\").each(function() {\n var menuParent = $(this).children('a').text();\n var firstChildItem = $(this).find(\"ul li:first-child a\").text();\n if (menuParent == firstChildItem){\n $(this).find(\"ul li:first-child\").remove();\n }\n });\n }", "function deleteListItem() {\n item.remove();\n }", "function removeMenuItem(menuId, menuItemState) {\n // Validate that the menu exists\n service.validateMenuExistence(menuId);\n\n // Search for menu item to remove\n for (var itemIndex in service.menus[menuId].items) {\n if (service.menus[menuId].items.hasOwnProperty(itemIndex) && service.menus[menuId].items[itemIndex].state === menuItemState) {\n service.menus[menuId].items.splice(itemIndex, 1);\n }\n }\n\n // Return the menu object\n return service.menus[menuId];\n }", "function rem_menu(){\n\tvar menu=$(\"#menu\");\n\tif(menu.length){\n\t\tmenu.remove();\n\t};\n\n\tvar hamb=$(\"#hamb\");\n\tif(hamb.length){\n\t\thamb.remove();\n\t};\n}", "function deleteItem(itemID) {\r\n if (toDelete.includes(itemID)) {\r\n restoreItem(itemID);\r\n } else {\r\n if (toAdd.includes(itemID)) {\r\n toAdd.splice(toAdd.indexOf(itemID), 1);\r\n } else {\r\n if (toModify.includes(itemID)) {\r\n toModify.splice(toModify.indexOf(itemID), 1);\r\n }\r\n toDelete[toDelete.length] = itemID;\r\n }\r\n //Add strikethrough to item\r\n document.getElementById(itemID).style.textDecoration = \"line-through\";\r\n }\r\n}", "function removeItem(cart1) {\n $(\"button.remove\").on(\"click\", function () {\n let index = parseInt(this.value);\n cart1.splice(index,1);\n generateCart(cart1);\n });\n}", "function removeShopItem (e) {\n let shopItem, shopItemId;\n\n if(e.target.classList.contains('remove') ) {\n e.target.parentElement.parentElement.remove();\n shopItem = e.target.parentElement.parentElement;\n shopItemId = shopItem.querySelector('a').getAttribute('data-id');\n }\n //remove from local storage\n removeShopItemLocalStorage(shopItemId);\n}", "function deleteItem(){\n\tul.removeChild(this.parentElement);\n}", "function removeItem(event){\n const serializedItem = event.dataTransfer.getData('item');\n if (serializedItem !== null) {\n const item = Item.fromJSONString(serializedItem);\n let quan = instance.model.orderList.items[item.nr].quantity;\n // Remove the item from the order bar completely\n instance.model.undoManager.perform(\n instance.model.orderList.removeItemCommand(item.nr,quan)\n .augment(updateOrderBarCommand())\n );\n }\n}", "function removeItemFromCart(){\n\n}", "function removeItem(key) {\n if (confirm('Etes-vous sûr de vouloir supprimer le produit?')) {\n // On supprime du localStorage la clé du produit\n delete cart[key]\n localStorage.setItem('cart', JSON.stringify(cart));\n keys = Object.keys(cart)\n if (keys.length === 0) {\n basketContent.innerHTML = '<h3>Le panier est vide</h3>'\n } else {\n // On supprime visuellement la ligne du tableau\n const line = document.querySelector(`[data-key=\"${key}\"]`)\n line.remove()\n // Recalcul du total du pannier\n document.querySelector(`#total`).innerHTML = getTotalCart();\n }\n }\n}", "function removeItem() {\n var item = this.parentNode.parentNode,\n parent = item.parentNode,\n id = parent.id,\n value = item.innerText;\n\n if (id === 'todo') {\n data.todo.splice(data.todo.indexOf(value), 1);\n } else {\n data.completed.splice(data.completed.indexOf(value), 1);\n }\n\n // removes item node\n parent.removeChild(item);\n\n dataObjectUpDated();\n}", "takeout(item) {\n var index = this.item.indexOf(item);\n if (this.open = true && index > -1) {\n this.item.splice(index, 1);\n alert(\"Item has been removed from the backpack.\");\n }\n }", "function deleteFromMainMenu(menuId, pageId,menuType)\n{\n \n if (!confirm('Proceed to remove the menu'))\n return false;\n /*$.ajax({\n type: \"POST\",\n url: appURL + '/proxy',\n dataType: \"json\",\n data: {method: 'deleteFromMainMenu', menuId: menuId, pageId: pageId},\n success: function (data) {\n var res = data.result;\n if (res == 1)\n {\n alert('Can not delete this global link as primary links present under this menu.');\n }\n else if (res == 2)\n {*/\n $(\"#mainMenuItem\" + pageId).remove();\n showHideChkBox(menuType);\n displayEmptyText(menuType);\n //getTotalMenuRecords();\n// }\n// }\n// });\n}", "_onMenuDisposed(menu) {\n this.removeMenu(menu);\n let index = ArrayExt.findFirstIndex(this._items, item => item.menu === menu);\n if (index !== -1) {\n ArrayExt.removeAt(this._items, index);\n }\n }", "function deleteItem() {\n\t\t\tvar item = itensGrid.selection.getSelected()[0];\n\t\t\t\n\t\t\tif (item) {\n\t\t\t\titensStore.deleteItem(item);\n\t\t\t} else {\n\t\t\t\tokDialog.set(\"title\", \"Atenção\");\n\t\t\t\tokDialogMsg.innerHTML = \"Selecione o item antes de excluir.\";\n\t\t\t\tokDialog.show();\n\t\t\t}\n\t\t}", "function removeItem() {\n\t// if there are any items in the shoppingCart Array\n\tif (shoppingCart.length > 0) {\n\t\t// prompt to figure out what item they want to remove \n\t\tinquirer.prompt({\n\t\t\tmessage: \"Which Item would you like to remove?\",\n\t\t\tname: \"removeItem\",\n\t\t\ttype: \"list\",\n\t\t\t// the choices are from the current shopping list\n\t\t\tchoices: function () {\n\t\t\t\tvar returnItems = [];\n\t\t\t\tfor (var i = 0; i < shoppingCart.length; i++) {\n\t\t\t\t\treturnItems.push(shoppingCart[i].product_name);\n\t\t\t\t}\n\t\t\t\treturn returnItems;\n\t\t\t}\n\t\t})\n\t\t\t.then(function (removeQ) {\n\t\t\t\t// loop through the shopping cart to compare the .product name against the selection for the remove item, then use the hoisted function to remove the item at the iteration\n\t\t\t\tfor (var i = 0; i < shoppingCart.length; i++) {\n\t\t\t\t\tvar sC = shoppingCart[i];\n\t\t\t\t\tif (sC.product_name === removeQ.removeItem) {\n\t\t\t\t\t\t// subtract the cost of the items from the cartPrice\n\t\t\t\t\t\tcartPrice -= (sC.purchaseQTY * sC.price_customer);\n\t\t\t\t\t\tshoppingCart.remove(i);\n\t\t\t\t\t\tconsole.log(\"Removed \" + sC.purchaseQTY + \" \" + sC.product_name + \" From the Cart.\")\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t// get more input from the user\n\t\t\t\tnextAction();\n\t\t\t})\n\t}\n\t// if there are no items in shoppingCart, redirect the user\n\telse {\n\t\tconsole.log(\"We can't remove items since your cart is empty\");\n\t\tnextAction();\n\t}\n}", "function deleteItem(item) {\n var order = JSON.parse(sessionStorage.getItem(\"order\"));\n if (typeof item == \"number\") {\n order[\"custom\"] = order[\"custom\"].splice(1, item);\n } else {\n delete order[item];\n }\n sessionStorage.setItem(\"order\", JSON.stringify(order));\n document.location.reload(true);\n}", "function deleteItem(){ \n $(this).parent().remove();\n }", "function deleteItem(){\r\n// todo\r\n var id = readNonEmptyString('please type the id of the item you wish to delete :');\r\n if (!isNaN(id)){\r\n var item = getItemById(id);\r\n item.parent.items.forEach(function(childItem,index,array){\r\n if (childItem.id == id){\r\n array.splice(index,1);\r\n }\r\n })\r\n }\r\n\r\n}", "function removeItem() {\n var item = this.parentNode.parentNode;\n var parent = item.parentNode;\n var id = parent.id;\n var text = item.innerText.trim();\n\n if (id === 'todo') {\n data.todo.splice(data.todo.indexOf(text), 1);\n } else if (id === 'done') {\n data.done.splice(data.done.indexOf(text), 1);\n }\n parent.removeChild(item);\n\n dataObjectUpdated();\n \n}", "function removeItemAndCommand(itemName, itemAction) {\r\n var itemPosition = inventory.indexOf(itemName) - 1;\r\n var actionPosition = availableActions.indexOf(itemAction) - 1;\r\n if (inventory.includes(itemName)) {\r\n inventory.splice(itemPosition, 3);\r\n inventoryAside.innerHTML = inventory.join(\" \");\r\n availableActions.splice(actionPosition, 3);\r\n commandsFooter.innerHTML = availableActions.join(\" \");\r\n }\r\n}", "function deleteItem(e) {\n // Una vez que clickeemos el boton, queremos eliminar la Parent del item.\n // console.log('item Deleted');\n const element = e.currentTarget.parentElement.parentElement;\n const id = element.dataset.id; // Seleccionamos el ID\n // console.log(element); // Parent = Grocery-Item\n list.removeChild(element);\n if (list.children.length === 0) {\n container.classList.remove('show-container');\n }\n displayAlert('Item Removed', 'danger');\n setBackToDefault();\n // LOCAL STORAGE REMOVE\n removeFromLocalStorage(id);\n}", "function deleteItem(evt) {\n\tvar button = evt.target;\n\tvar row = button.parentNode.parentNode;\n\tvar cells = row.getElementsByTagName(\"td\");\n\tvar name = cells[1].innerHTML;\n\tvar type = cells[2].innerHTML;\n\tvar group = row.id.slice(0, row.id.indexOf(\"-\"));\n\tif (group === \"base\") {\n\t\tbaseItems.delete(type, name);\n\t} else {\n\t\toptionalItems.delete(type, name);\n\t}\n\trow.parentNode.removeChild(row);\n\tsyncToStorage();\n}", "function borrarItem(unProducto,listaProductos){\n listaProductos.forEach(element => {\n // como recibe el [botón], se compara el nombre del padre.\n if (unProducto == element.parentNode.querySelector('.name').textContent){\n element.parentNode.remove();\n }\n });\n actualizarLS(unProducto);\n verificaDOM();\n}", "function removeMenuItem(restaurant, menuItemName, itemType) {\n for (var i = 0; i < restaurant.menus[itemType].length; i++) {\n if (menuItemName === restaurant.menus[itemType][i].name) {\n restaurant.menus[itemType].splice(i, 1);\n return `No one is eating our ${menuItemName} - it has been removed from the ${itemType} menu!`;\n }\n }\n return `Sorry, we don't sell ${menuItemName}, try adding a new recipe!`;\n}", "function removeItem (itemid) {\t\n\tvar item = document.getElementById(itemid);\n listCities.removeChild(item);\n allAnswers.splice(0, 1);\n}", "function deleteMenuGroup(menuGroup){\n if(confirm(\"Are you sure you want to remove this item?\")){\n MenuGroupFactory.remove(menuGroup.menuGroupId).then(\n function(){\n getMenu();\n }\n );\n }\n }", "function removeItem(cartarray, deleteitem){\n cartarray.splice(deleteitem, 1);\n}", "function removeItem(){\n var item = this.parentNode.parentNode;\n var parent = item.parentNode;\n var id = parent.id;\n var value = item.innerText;\n \n \n data.todo.splice(data.todo.indexOf(value),1);\n \n \n dataObjectUpdated();\n \n parent.removeChild(item);\n}", "function removeItem(e) {\n if (e.target.classList.contains('delete-btn')) {\n // var litext = e.target.classList.contains('item-list');\n //var litext = document.getElementsByClassName('item-list').innerText;\n // var txt = litext.innerHTML;\n if (confirm('Are you sure you want delete')) {\n \n var btn = document.querySelector('delete-btn');\n btn = e.target.parentElement;\n itemlist.removeChild(btn);\n }\n }\n}", "function deleteMenuItem() \n{\n\tif (!confirm(\"Realy delete?\")) return false;\n\twindow.location = \"/admin/structure/delete/\" + selectedItemID;\n\treturn true;\n}", "function deleteItem(e){\n var productRow = e.currentTarget.parentNode.parentNode;\n body.removeChild(productRow);\n getTotalPrice();\n }", "function deleteItem() {\n\tlet item = this.parentNode;\n\tdomStrings.todoList.removeChild(item);\n}", "function removeItem(e) {\n e.target.parentElement.removeChild(e.target);\n}", "function menuDelBkmkItem (selection) {\n // Cancel previous cut and clipboard if any\n if (isClipboardOpCut == true) {\n\trefreshCutPanel(bkmkClipboardIds, false);\n\trefreshCutSearch(bkmkClipboardIds, false);\n\tnoPasteZone.clear();\n }\n bkmkClipboardIds.length = bkmkClipboard.length = 0;\n isClipboardOpCut = undefined;\n\n // Filter to keep only unique bookmark items (none including another)\n let selectIds = selection.selectIds;\n let len = selectIds.length;\n let bnId;\n let a_id = [];\n let a_BN = [];\n for (let i=0 ; i<len ; i++) {\n\tbnId = selectIds[i];\n\tlet BN = curBNList[bnId];\n\tif (!BN.protect) { \n\t // We are going to delete, so clip the real ones\n\t uniqueListAddBN(bnId, BN, a_id, a_BN);\n\t}\n }\n\n delBkmk(a_id, a_BN);\n}", "function removeItem (){\n //grab the <li> by accessing the parent nodes \n let item = this.parentNode.parentNode; //the <li>\n let parent = item.parentNode; //in order to remove its child <li>\n let id = parent.id; //check id if its 'todo' or 'completed'\n let value = item.innerText;\n\n //if its an item to be completed...\n if(id === 'todo') {\n //remove one item from todo, based on index\n data.todo.splice(data.todo.indexOf(value, 1));\n //else if it was already completed...\n } else {\n //remove one item from completed, based on index\n data.completed.splice(data.completed.indexOf(value, 1));\n }\n\n //update localstorage\n dataObjectUpdated();\n\n //remove it\n parent.removeChild(item);\n\n}", "function removerItem(item) {\r\n\tif (qtd[item] > 0) {\r\n\t\tqtd[item] -= 1;\r\n\t\tvar quantidade = document.getElementById('quantidade' + item);\r\n\t\tvar total = document.getElementById('total' + item);\r\n\t\tquantidade.innerHTML = qtd[item];\r\n\t\tvalorTotal[item] = valorProduto[item] * qtd[item];\r\n\t\ttotal.innerHTML = valorTotal[item];\r\n\t\tvalorCompra();\r\n\t}\r\n}", "function removeCartItem() {\n const removeId = event.target.dataset.id;\n\n if (confirm(\"Are you sure you want to remove this item?\")) {\n let updatedCartItems = currentCartItems.filter(function (item) {\n if (removeId !== item.id) {\n return true;\n }\n });\n currentCartItems = updatedCartItems;\n saveToStorage(cartKey, updatedCartItems);\n displayCartItems();\n calculateCartTotal();\n createMenu();\n displayMessage(\n \"alert-success\",\n \"The item was successfully removed.\",\n \".message-container\"\n );\n }\n}", "function removeItem(e) {\n var wdlist = Array.from(gList);\n let identifier = null;\n let idElement = e.currentTarget.id.split(\"-\")[0];\n console.log(idElement);\n for (var i = 0; i < list.length; i++) {\n if (list[i].id === parseInt(idElement)) {\n identifier = i;\n console.log(identifier);\n }\n }\n console.log(identifier);\n wdlist.splice(identifier, 1);\n gSetList(wdlist);\n }", "function inventoryRemove(item) {\n\titem.hide();\n\titem.moveTo(current_layer);\n\titem.draggable(false);\n\tinventory_list.splice(inventory_list.indexOf(item), 1);\n\tredrawInventory();\n}", "function removeItem() {\n const item = this.parentNode.parentNode\n const parent = item.parentNode\n parent.removeChild(item)\n}", "function deleteMenu(id) {\r\n\r\n API.deleteMenu(id)\r\n .then(res => loadMenus())\r\n .catch(err => console.log(err));\r\n }", "function deleteItem(item) {\n if(item.target.className === \"remove\") {\n item.target.parentElement.remove();\n }\n}", "removeDishFromMenu(id) {\n this.menu = this.menu.filter(dish => dish.id !== id)\n }", "function removeItemFromCart(event) {\n if (event.target.type === 'button') {\n currentInventory.removeItem(event.target.name);\n currentInventory.saveToLocalStorage();\n renderTable();\n }\n}", "function removeProduct(title) {\n delete cart[title];\n saveCart();\n showCart();\n}", "function removeProductFromWishList(e) {\r\n console.log(e.id);\r\n //console.log(cartStoredData);\r\n console.log(wishListData);\r\n for (i = 0; i < wishListData.length; i++) {\r\n if (wishListData[i].productId == e.id) {\r\n\r\n wishListData.splice(i, 1);\r\n }\r\n }\r\n console.log(wishListData);\r\n goToWishList();\r\n alert(\"Removed Item\");\r\n}", "deleteItem() {\n this.view.removeFromParentWithTransition(\"remove\", 400);\n if (this.item != null) {\n this.itemDao.deleteById(this.item.getId());\n }\n }", "function browserMenusRemove( id )\n{\n ++menusDeleting;\n browser.menus.remove( id ).then( result => {\n // Upon last deletion performed, can recreate menu tree\n --menusDeleting;\n if (menusDeleting == 0)\n createContextMenus()\n }).catch( result => {\n console.error(\"URL Link menu deletion failed\");\n });\n}", "function deleteItem() {\n $('.shopping-list').on('click', '.shopping-item-delete', function (event) {\n this.closest('li').remove();\n });\n }", "function removeFromCart(event) {\n\tlet storedCart = JSON.parse(localStorage.getItem('cart'));\n\tlet buttonName = event.target.dataset.name;\n\t//LOOP FOR SEARCHING SELECTED ITEM TO DELETE, EMPTYING ITS QUANTITY PROP BEFORE SPLICING IT OUT\n\tfor (let i = 0; i < storedCart.length; i += 1) {\n\t\tif (storedCart[i].label === buttonName) {\n\t\t\tstoredCart[i].qty = 0;\n\t\t\tstoredCart.splice(i, 1);\n\t\t\tlocalStorage.setItem('cart', JSON.stringify(storedCart));\n\t\t}\n\t}\n\n\tif (storedCart.length === 0) {\n\t\tcartCounter.innerHTML = 0;\n\t}\n\tshopcartOverlay.innerHTML = '';\n\n\tdisplayCart();\n}", "function removeCartItem(event) {\n\tvar buttonClicked = event.target;\n\tbuttonClicked.parentElement.parentElement.remove();\n\tupdateCartTotal()\n}", "function sendRemove(itemCode) {\n console.log(\"removing \" + itemCode);\n sendText(\"{\\\"action\\\":\\\"remove\\\",\" + \"\\\"item\\\":\\\"\" + itemCode + \"\\\"}\");\n}", "function deleteItem(eId) {\n document.getElementById(eId).remove();\n n = Number (eId.slice(-1)) -1;\n //remove the cost of the product deleted from the cart\n total -= itemCost[n];\n //updating the cost of products in the cart\n document.getElementById(\"total\").innerHTML = \"Total: \" + total.toFixed(2) +\"$\";\n}", "function removeItem() {\n let value = this.parentNode.lastChild.textContent;\ntodo.splice(todo.indexOf(value), 1);\n this.parentNode.parentNode.removeChild(this.parentNode);\n saveTodos();\n}", "function RemoveItem(item){\n var index = basket.indexOf(item);\n if (index > -1) {\n console.log(\"Taking \" + item.Name + \" out of the basket!\");\n basket.splice(index, 1);\n return;\n }\n Console.log(item.Name + \" is not in the basket!\");\n}", "function removeItem(item){\n\n\t\t\t// Make sure cart is not empty\n\t\t\tif((!isEmpty()) && itemInCart(item) ){\n\n\t\t\t\t// remove all the items of this kind from cart count\n\t\t\t\tadjustCount(item.qty * -1);\n\t\t\t\t\n\t\t\t\t// Adjust total based on item qty\n\t\t\t\tadjustTotal((item.price*item.qty)*-1);\n\n\t\t\t\t// Remove the item from array \n\t\t\t\titems.splice(items.indexOf(item), 1);\n\t\t\t\t\n\t\t\t\t// reset item qty\n\t\t\t\t// Remember the reference to this item is coming straight from the item data copy in the controller,\n\t\t\t\t// so the item is never removed we just reuse the same reference. Meaning we\n\t\t\t\t// have to reset its qty property!\n\t\t\t\titem.qty = 0;\n\t\t\t}\n\t\t}", "removeItem(item) {\n this.props.removeItem(this.props.partyId, item._id);\n }", "deleteProduct(e) {\n var _this = e.data.context,\n item_name = $(this).parents('.item').attr('data-name');\n\n _this.products.splice(_this.findIndex(item_name), 1);\n $(this).parents('.item').remove();\n _this.handleCheckoutSubmit();\n _this.setCheckoutTotals();\n }", "deleteItem() {\n const index = this.items.findIndex((e) => e.id === this.editItemID);\n this.items.splice(index, 1);\n this.editItemID = null;\n }", "function removeItem(e) {\n // document.getElementById('ul_list').removeChild(e.target.parentElement);\n const isConfirmed = confirm('Are you sure you want to delete the item: ' + e.target.parentElement.querySelector('.todo-item').innerHTML);\n if(isConfirmed){\n deleteTodoItem(e.target);\n }\n}", "function removeFromOrderWithId(id) {\n var table = getCurrentTable();\n if (table === \"error\") return;\n delete table.item_id[id];\n return;\n}", "function deleteItem() {\n\t\tvar ask = confirm(\"Delete this workout?\");\n\t\t// Confirm with the user to delete individual item //\n\t\tif(ask) {\n\t\t\tlocalStorage.removeItem(this.key);\n\t\t\twindow.location.reload();\n\t\t\talert(\"Workout has been deleted.\");\n\t\t\treturn false;\n\t\t// If declined, do not delete and alert the user //\n\t\t}else{\n\t\t\talert(\"Workout was not deleted.\");\n\t\t}\n\t}", "function delItemFromJson(itemName, sellerName) {\n // console.log(\"======\")\n // console.log(itemName);\n // console.log(sellerName);\n for ( let i = 0; i < cart.length; i++ ) {\n if ( cart[i][\"name\"] == sellerName) {\n var order = cart[i][\"order\"];\n // console.log(order);\n for ( let j = 0; j < order.length; j++ ) {\n // console.log(order[i]);\n if (order[j][\"name\"] == itemName) {\n order.splice(j, 1);\n j--;\n }\n }\n if (order.length == 0) {\n cart.splice(i, 1);\n i--;\n }\n }\n }\n localStorage.setItem(\"cart\", JSON.stringify(cartObj));\n // console.log(cart);\n buildCartList();\n}", "function removeWishItem(item) {\n console.log(\"called\");\n item.remove();\n let z = JSON.parse(localStorage.getItem(\"WishlistItem\"));\n wishArr = [];\n for (let k = 0; k < Object.keys(z).length; k++) {\n if (z[k].name == item.children[1].innerText) continue;\n else wishArr.push(z[k]);\n }\n localStorage.setItem(\"WishlistItem\", JSON.stringify(wishArr));\n wishEmptyCheck();\n}", "removeItem(_item) { }", "function removeItem () {\n \tvar item = this.parentNode.parentNode; \n \tvar parent = item.parentNode; \n \tvar id = parent.id; \n \tvar value = item.innerText;\n\n \t//update data array - rem0ve from data array \n \tif (id === 'openTasks') {\n\tdata.openTasks.splice(data.openTasks.indexOf(value),1);\n\t} else {\n\tdata.doneTasks.splice(data.openTasks.indexOf(value),1);\n\t} \n\n\tdataObjectUpdated(); //update local storage \n \tparent.removeChild(item); //apply to DOM \n }", "function removeContextMenuItems( menuId )\n{\n // Remove always-there menu\n browserMenusRemove( menuId + \"-unaltered\" );\n\n // Now prefs menus\n if (submenuCount)\n {\n browserMenusRemove( menuId + \"-separator\" );\n for (let n = 0; n < submenuCount; ++n)\n browserMenusRemove( menuId + \"-pref-\" + n );\n }\n\n // And the top-level one\n browserMenusRemove( menuId );\n}", "function removeMenu(menuId) {\n // Validate that the menu exists\n service.validateMenuExistence(menuId);\n\n delete service.menus[menuId];\n }", "function removeItem(e) {\n\t\tvar id = jQuery(this).parents('li').attr('data-id');\n\t\tif(id){\n\t\t\tfirebase.database().ref().child('/messages/'+id).remove();\n\t\t}\n\t}" ]
[ "0.7153774", "0.7002828", "0.6926319", "0.67989844", "0.67798316", "0.6725754", "0.6680967", "0.6584663", "0.65753835", "0.6492408", "0.6491224", "0.6459137", "0.6432045", "0.6394014", "0.63868016", "0.6383855", "0.635395", "0.63530505", "0.63503224", "0.63330245", "0.6319392", "0.63048464", "0.62772465", "0.62709785", "0.6262898", "0.62616444", "0.62417704", "0.62183535", "0.62011796", "0.6200744", "0.61955744", "0.6181356", "0.61683905", "0.61683047", "0.6159532", "0.61592376", "0.6146729", "0.6127234", "0.61092013", "0.61060417", "0.6100032", "0.6097574", "0.60912776", "0.6090085", "0.60593444", "0.60507876", "0.60483706", "0.6045123", "0.60439444", "0.60412085", "0.6037874", "0.60329825", "0.60236335", "0.6013159", "0.6007661", "0.6007486", "0.59989315", "0.59964526", "0.5996073", "0.5990548", "0.5983195", "0.59828454", "0.5974137", "0.5973841", "0.5971811", "0.5965781", "0.5961664", "0.59476703", "0.5940978", "0.5932692", "0.593013", "0.5928992", "0.59264207", "0.59260803", "0.59241873", "0.5922025", "0.5915455", "0.59139633", "0.5911825", "0.5911252", "0.59054536", "0.5903195", "0.59030473", "0.59025365", "0.58966094", "0.5896183", "0.5871459", "0.5869276", "0.5869115", "0.5868639", "0.58650595", "0.5857748", "0.58565646", "0.5855104", "0.58486617", "0.5837031", "0.5835624", "0.58350104", "0.58344865", "0.5829311" ]
0.76243615
0
Adds an item to the customers order.
function addToOrder(itemId, instructions) { const dataToSend = JSON.stringify({ menuItemId: itemId, instructions: instructions, orderId: sessionStorage.getItem("orderId") }); post("/api/authTable/addItemToOrder", dataToSend, function (data) { if (data !== "failure") { const item = JSON.parse(data); addItemToBasket(item); calculateTotal(); } }) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "_addNewItem() {\n // Add new Item from Order's Items array:\n this.order.items = this.order.items.concat([this.item]);\n // Update current Order:\n this.orderService.setCurrentOrder(this.order);\n this._closeAddNewItem();\n }", "function addToOrder(item) {\n var table = getCurrentTable();\n //Checks that the order isn't full(above 10)\n if(checkFullOrder(table.item_id))\n {\n return;\n }\n var key;\n //Depending where it was added from, the variable item is different\n if (item.includes(':')) {\n key = getIdFromName(item.split(': ')[0]);\n } else {\n key = getIdFromName(item.slice(0, -1));\n }\n if (key in table.item_id) {\n table.item_id[key] = table.item_id[key] + 1;\n } else {\n table.item_id[key] = 1;\n }\n showOrder(currentTableID);\n return;\n}", "function addItemToCart() {}", "function addItemToCart() {}", "function addItemToCart(user, item) {}", "function addItem(id){\r\n\tif(order.hasOwnProperty(id)){\r\n\t\torder[id] += 1;\r\n\t}else{\r\n\t\torder[id] = 1;\r\n\t}\r\n\t//gets the current restaurant and ensures that it is not undefined\r\n\ttemp = getCurrentRestaurant();\r\n\tif (temp !== undefined){\r\n\t\tupdateOrder(temp);\r\n\t}\r\n}", "function addToInvoice( newItem ){\n\t\t\n\t\t// console.log( \"adding newItem: \" + newItem.ID);\n\t\t// add product to cart\n\t\tcart.push(newItem);\n\t\t\n\t\t// items total cost\n\t\tcart.itemsCost \t+= parseFloat(newItem.PriceSAR, 10);\n\t\tcart.itemsCost\t= parseFloat(cart.itemsCost.toFixed(4)) ;\n\t\t\n\t\tcart.itemsTax\t+= parseFloat(newItem.TaxSAR, 10) ;\n\t\tcart.itemsTax\t= parseFloat(cart.itemsTax.toFixed(4)) ;\n\t\t\n\t\t// items total shipping cost\n\t\tcart.shippingCost \t+= parseFloat(newItem.ShippingCost, 10);\n\t\tcart.shippingCost\t= parseFloat(cart.shippingCost.toFixed(4)) ;\n\t\t// console.log( cart.totalCost)\n\t\t\n\t\t// item tax\n\t\tcart.invoiceCost\t= cart.itemsCost + cart.shippingCost + cart.itemsTax;\n\t\tcart.invoiceCost\t= parseFloat(cart.invoiceCost.toFixed(4));\n\t\t\n\t\t// update invoice\n\t\tupdateInvoice();\n\t\t\n\t\tmycart = cart;\n\t}", "function addItem(item) {\n basket.push(item);\n return true;\n}", "function addItem() {\n\t\t\tvar order = ordersGrid.selection.getSelected()[0];\n\n\t\t\titensStore.newItem({\n\t\t\t\tpi_codigo: \"new\" + itensCounter,\n\t\t\t\tpi_pedido: order ? order.pe_codigo : \"new\",\n\t\t\t\tpi_prod: \"\",\n\t\t\t\tpi_quant: 0,\n\t\t\t\tpi_moeda: \"R$\",\n\t\t\t\tpi_preco: 0,\n\t\t\t\tpi_valor: 0,\n\t\t\t\tpi_desc: 0,\n\t\t\t\tpi_valort: 0,\n\t\t\t\tpr_descr: \"\",\n\t\t\t\tpr_unid: \"\"\n\t\t\t});\n\t\t\t\n\t\t\titensCounter = itensCounter + 1;\n\t\t}", "function addItem(sku, quantity) {\n quantity = _.isNumber(quantity) ? quantity : 1;\n\n $lastPromise = $$\n .postCartItems({\n sku: sku,\n quantity: quantity\n })\n .then(onSyncd);\n\n return _this_;\n }", "function addItem( item ){\n cart.push(item);\n return cart;\n}", "function AddItem(item){\n console.log(\"Adding \" + item.Name + \" to the basket!\");\n basket.push(item);\n}", "function addToCart(item) {\n\t// create item in cart\n\tconst row = document.createElement('tr');\n\n\trow.innerHTML = `\n\t\t<td>\n\t\t\t<img src=\"${item.image}\">\n\t\t</td>\n\t\t<td>\n\t\t\t${item.title}\n\t\t</td>\n\t\t<td class=\"data-price\" data-price=\"${item.priceData}\">\n\t\t\t${item.price}\n\t\t</td>\n\t\t<td>\n\t\t\t<ion-icon name=\"close\" class=\"remove\" data-id=\"${item.id}\"></ion-icon>\n\t\t</td>\n\t`;\n\n\tshoppingCartCont.appendChild(row);\n\n\t// calculate price\n\tcalculatePrice(item);\n\n\t// update count of items in 'itemAmount'\n\titemAmount.innerHTML = shoppingCartCont.childElementCount;\n\n\t// apply 'in basket' effect\n\tif (shoppingCartCont.childElementCount > 0) {\n\t\titemAmount.classList.add('active');\n\t}\n\n\t// save item into local storage\n\tsaveIntoStorage(item);\n}", "add(item, Inventory) {\n\n if (!this.isValid(item)) {\n throw \"Invalid item input, expected [SKU QUANTITY]\";\n }\n\n item = this.normalize(item);\n\n if (this.items.filter(i => i[0] == item[0]).length) { // item with SKU exists already\n this.items = this.items.map(\n i => {\n // check for availability of the item in the Inventory\n if (!Inventory.available([item[0], item[1] + i[1]])) {\n throw \"Can't add item to cart\";\n }\n\n // when the SKU of the newly added item matches the item in the inventory, just add amount\n if (i[0] == item[0]) {\n i[1] += item[1];\n }\n return i;\n }\n );\n } else { // no item with matching SKU found, add the item to the cart\n // check for availability of the item in the Inventory\n if (!Inventory.available(item)) {\n throw \"Can't add item to cart\";\n }\n this.items.push(item);\n }\n }", "addLineItem(item, units, comment) {\n\t\tlet sku = item.sku\n if (sku in this.items) {\n\t\t\tlet existing = this.items[sku]\n //console.log(`addLineItem ${units} to update existing item-${sku}`)\n\t\t\texisting.units += units \n\t\t\tif (comment) existing.comment = comment \n } else {\n\t\t\t//console.log(`addLineItem ${units} to new item ${sku}`)\n\t\t\tthis.items[sku] = new OrderItem({\n\t\t\t\tsku: item.sku,\n\t\t\t\tname:item.name, \n\t\t\t\timage: item.image,\n\t\t\t\tunits:units, \n\t\t\t\tcomment:comment})\n }\n\t\tthis.render() // updates the view\n return this\n\t}", "function add(item) {\n data.push(item);\n console.log('Item Added...');\n }", "function addItemToCart(user, item) {\n\n}", "function addItemToBasket(item) {\n const parent = $(\"#order\");\n\n // Add item\n basket.push(item);\n parent.append(\"<li id='ordermenuitem-\" + item.id\n + \"' class='list-group-item list-group-item-action'>\\n\"\n + \" <span class='bold'>\" + item.name + \"</span>\"\n + \" <span class='span-right'>£\" + item.price + \"</span>\\n\"\n + \" <br>\\n\"\n + \" <span id='omi-instructions-\" + item.id\n + \"'><span id='omi-instructions-\" + item.id + \"-text'>\"\n + item.instructions + \"</span></span>\\n\"\n + \" <span class='span-right'><i id='omi-edit-\" + item.id\n + \"' class='fa fa-edit fa-lg edit' onclick='showEditOrderMenuItem(\"\n + item.id + \", \\\"\" + item.instructions\n + \"\\\");'></i><i class='fa fa-times fa-lg remove' onclick='confirmRemoveOrderMenuItem(\"\n + item.id + \");'></i></span>\\n\"\n + \"</li>\");\n}", "function addItem(itemName, itemPrice) {\n if (order.items[itemName]) {\n order.items[itemName].count += 1;\n } else {\n let item = {name: itemName, price: itemPrice,\n count: 1};\n order.items[itemName] = item;\n }\n order.subtotal = round(order.subtotal + itemPrice);\n order.tax = round(order.subtotal * 0.1);\n order.total = round(order.subtotal + order.tax + order.delivery);\n let restaurantDiv = document.getElementById(\"restaurant\");\n // Generate order summary div \n restaurantDiv.replaceChild(createOrderDiv(restaurantData.menu), document.getElementById(\"restaurant\").lastChild);\n}", "addItem(item)\r\n\t{\r\n\t\tif (typeof item != 'object') {\r\n\t\t\tthrow new InvalidArgumentException('addItem() expect the first parameter to be an object, but ' + typeof item + ' was passed instead');\r\n\t\t}\r\n\r\n\t\tif (! item.hasOwnProperty('id')) {\r\n\t\t\tthrow new InvalidCartItemException;\r\n\t\t}\r\n\r\n\t\tthis.cart = Cookie.get(this.settings.cookie_name);\r\n\r\n\t\tif (!item.hasOwnProperty('quantity')) {\r\n\t\t\titem.quantity = 1;\r\n\t\t}\r\n\r\n\t\tlet i;\r\n\t\tlet incremented = false;\r\n\r\n\t\tfor (i = 0; i < this.cart.items.length; i++) {\r\n\t\t\tif (this.cart.items[i].id == item.id) {\r\n\t\t\t\tthis.cart.items[i].quantity++;\r\n\t\t\t\tincremented = true;\r\n\t\t\t\tbreak;\t\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tif (! incremented) {\r\n\t\t\tthis.cart.items.push(item);\r\n\t\t}\r\n\r\n\t\tCookie.set(this.settings.cookie_name, this.cart, 2);\r\n\t}", "add_item(item){\n this.cart.push(item);\n }", "addItem(item) {\n this.items.push(item);\n // tegye közzé a frissített elemek listáját, hogy frissítse a Cart topic-ot\n // amikor a cart tartalma frissült\n PubSub.publish(\"updateCart\", this.getItems());\n }", "function addCartItem(form, material, color, text, textColor, qty, unitCost) {\n\tlet model = makeModelNumber(form, material, color);\n\n\t// look for existing items based on the model number. but we'll keep customized\n\t// items as their own cart line item, so be sure not to match if text exists.\n\tlet existingItem = _.find(cart, (c) => {\n\t\treturn (c.model === model) && !c.text;\n\t});\n\n\tif (existingItem) {\n\t\texistingItem.qty += qty;\n\t}\n\telse {\n\t\tlet newItem = {\n\t\t\tid: uuidv4(),\n\t\t\tmodel,\n\t\t\tform,\n\t\t\tmaterial,\n\t\t\tcolor,\n\t\t\ttext,\n\t\t\ttextColor,\n\t\t\tqty,\n\t\t\tunitCost\n\t\t};\n\n\t\tcart.push(newItem);\n\t}\n}", "function addItem(item, cost) {\n if (typeof cost !== \"number\" || isNaN(cost)) {\n cost = 0.0;\n }\n\n $(\"#receipt-table tbody\").append(\n \"<tr>\" +\n '<th scope=\"row\"><i class=\"fas fa-receipt\"></i></th>' +\n '<td id=\"name\">' +\n item +\n \"</td>\" +\n '<td id=\"cost\">' +\n cost.toFixed(2) +\n \"</td>\" +\n \"<td>\" +\n '<span><button type=\"button\" class=\"btn btn-danger\"><i class=\"far fa-trash-alt\"></i></button></span>' +\n \"</td>\" +\n \"</tr>\"\n );\n var newTotal = parseFloat($(\"#total-cost\").text()) + cost;\n $(\"#total-cost\").text(newTotal.toFixed(2));\n }", "function addItem(restaurant, item) {\n let restaurant = findRestaurant(restaurant)\n restaurant.items.push(item)\n return restaurant\n}", "function addItem() {\n\n console.log('adding', { amount }, { name });\n\n dispatch({\n type: 'ADD_ITEM', payload: {\n name: name,\n amount: amount,\n list_id: id,\n }\n })\n //reset local state of new item textfield to allow for more items to be added\n setName('');\n setAmount(1);\n }", "addItemsToCart() {\n\n Model.addItemsToCart(this.currentItems);\n }", "function addOneItemToCart() {\n var itemID = $(this).attr(\"id\");\n var positionInCart = itemID.slice(12, itemID.length);\n cartItems[positionInCart][3] += 1;\n updateCartDetails();\n}", "function plusItem() {\n const productId = this.name;\n const cartList = JSON.parse(sessionStorage.getItem(\"shoppingCartItems\"));\n const item = cartList.find(product => product.id == productId);\n cartList.push(item);\n sessionStorage.setItem(\"shoppingCartItems\", JSON.stringify(cartList));\n shoppingCartCount();\n populateShoppingCartPage();\n}", "function addItemToCart(item, itemQuantity){\n if(isNaN(itemQuantity)){\n itemQuantity = 1; \n }\n var itemIsNew = true; \n cart.forEach(function (cartItem){\n if(cartItem.name === item.name){\n cartItem.quantity += itemQuantity; \n updateQuantityDisplay(cartItem); \n return itemIsNew = false\n } \n })\n if(itemIsNew){\n cart.push(item); \n item.quantity = itemQuantity; \n displayItem(item, itemQuantity, \".cart-container\")\n }\n}", "addItem(item, options) {\n item.key = this.lastAvailableKey(this.items);\n this.items.push(item);\n }", "function addItem (orderNum, weightOZNum, SKUNum, UPCNum, itemDescValue, priceNum) {\n let itemNum = orderNum.length + 1;\n orderNum.push({item:itemNum, weightOZ: weightOZNum, SKU:SKUNum, UPC:UPCNum, itemDesc:itemDescValue, price:priceNum});\n console.log(orderNum);\n}", "function addItem(item) {\n var foundItem = false;\n\n // if there's another item exactly like this one, update its quantity\n _.each(bag.getItems(), function(curItem) {\n if (curItem.name == item.name && curItem.size == item.size &&\n curItem.price == item.price && curItem.color == item.color) {\n curItem.quantity += item.quantity;\n foundItem = true;\n }\n });\n\n // otherwise, add a new item\n if (!foundItem) {\n bag.addItem(item);\n } else {\n var items = bag.getItems();\n\n // item was updated, re-render\n renderItems(items);\n renderTotalQuantityAndPrice(items);\n }\n }", "addItem(name, quantity, pricePerUnit) {\n this.items.push({\n name,\n quantity,\n pricePerUnit\n })\n }", "add(id, product) {\n // if an item exists in the cart\n const item = this.items[id]\n ? new CartItem(this.items[id])\n : new CartItem({ id, product });\n\n // increment the items quantity\n item.qty += 1;\n // Update the items price\n item.price = item.product.price * item.qty;\n\n this.items = {\n ...this.items,\n [id]: item\n };\n }", "function addItem (value) {\n addItemToDOM(value);\n\n //reset the value after inserting item\n document.getElementById('item').value = '';\n\n //push item into array\n data.todo.push(value);\n\n //update localstorage\n dataObjectUpdated();\n}", "add() {\n\t\torinoco.cart.add({ imageUrl: this.imageUrl, name: this.name, price: this.price, _id: this._id });\n\t}", "function addItem (name, quantity) {\n if(cart[name] == undefined) {\n createItem(name);\n }\n cart[name] = cart[name] + quantity;\n}", "function processCustomerOrder(itm, qty) {\n var sql = \"SELECT * FROM product WHERE ?\";\n connection.query(sql, {item_id: itm},function (err, res) {\n if (err) throw err;\n var purchasedProduct = res[0].product_name;\n var purchasedPrice = parseFloat(res[0].price);\n var purchasedTotal = purchasedPrice * parseInt(qty);\n var newSalesTotal = parseFloat(res[0].product_sales) + parseFloat(purchasedTotal); //Challenge #3 additions\n var newQty = parseInt(res[0].stock_quantity) - parseInt(qty); \n\n var orderObject = {\n item: itm,\n product: purchasedProduct,\n quantity: qty,\n price: purchasedPrice,\n subtotal: purchasedTotal.toFixed(2),\n sales: newSalesTotal.toFixed(2) //Challenge #3 addition\n };\n\n customerOrder.push(orderObject);\n\n updateStock (itm, newQty);\n });\n}", "addToCart(itemOptions) {\n this.store.cart.products.push({\n product_id: itemOptions.item,\n price: itemOptions.price || 0,\n total: itemOptions.price || 0,\n quantity: itemOptions.quantity || 1,\n offer: itemOptions.offer || null,\n materials: itemOptions.config ? itemOptions.config.split(',') : [],\n description: \"\",\n comment: itemOptions.comment\n });\n }", "function buyItem(e) {\n\te.preventDefault();\n\n\t// find item was added\n\tif (e.target.classList.contains('add-to-cart')) {\n\t\tconst item = e.target.parentElement.parentElement.parentElement;\n\n\t\t// get item info\n\t\tgetItemInfo(item);\n\t}\n}", "addItem(newItem) {\n for (let index in this.items) {\n let item = this.items[index];\n if (item.id === newItem.id) {\n item.quantity += newItem.quantity;\n this.updateTotal();\n return;\n }\n }\n\n this.items.push(newItem);\n this.updateTotal();\n }", "function addOrder(order) {\n let orders = getOrders();\n orders.push(order);\n setOrders(orders);\n}", "agregarItem(item) {\n this.items.push(item);\n this.totalFactura += item.valorUnidad;\n }", "function addSelectedItemToCart() {\n // TODO: suss out the item picked from the select list\n var product = event.target.items.value;\n var quantity = event.target.quantity.value;\n cart.addItem(product, quantity);\n counter++;\n console.log(counter);\n // TODO: get the quantity\n // TODO: using those, add one item to the Cart\n}", "function addToOrder(orderedPizza) {\n setOrder([...order, orderedPizza]);\n }", "function addToOrder(orderedPizza) {\n setOrder([...order, orderedPizza]);\n }", "function addItemToShoppingCart(item) {\n\t$('#shopping-cart ul').append(`\n\t\t<li>\n\t\t\t${item}\n\t\t</li>\n\t`);\n}", "function addItem(value){\n\t//is the value they select in the\n\t//correct order position as the itemOrder array\n\tif(itemOrder.indexOf(value)==position){\n //item is in array and in correct order!\n\t\tposition++;\n\t\tdocument.getElementById(\"cart\").innerHTML = position;\n\t\t$('#cat01').collapse('hide');\n\t\t$('#cat02').collapse('hide');\n\t\t$('#cat03').collapse('hide');\n //if they have all the items - take them to survey - they are done!\n\t\tif(position>=itemOrder.length){\n\t\t\twindow.open(\"https://goo.gl/forms/UPJnCmT43htQucP43\");\n\t\t}\n\t}\n}", "function addItem(item) {\n $state.go('main.addItem', {item: item, foodListId: $stateParams.foodListId});\n }", "function addToCartHandler(item, quantity) {\n\t\tsetUserCart(prev => {\n\t\t\tconst prevCopy = [...prev];\n\t\t\tconst foundItemIndex = prevCopy.findIndex(\n\t\t\t\tcopyItem => copyItem.id === item.id\n\t\t\t);\n\t\t\tif (foundItemIndex >= 0) {\n\t\t\t\tconst newQuantity = prev[foundItemIndex].quantity + quantity;\n\t\t\t\tprevCopy.splice(foundItemIndex, 1, { ...item, quantity: newQuantity });\n\t\t\t\treturn prevCopy;\n\t\t\t} else {\n\t\t\t\treturn prev.concat({ ...item, quantity: quantity });\n\t\t\t}\n\t\t});\n\t}", "function addItem(item) {\n let newItem = new Item(item);\n return newItem.save();\n}", "function plusItemNumber(item) {\n item.number = Number(item.number) + 1;\n vm.store.updateShoppingItem(item, false);\n vm.store.calculateTotalSubtotal();\n }", "function ajouter(item) {\n item.push('lait');\n}", "addItem(item) {\n this.items.push(item)\n }", "function addItem(){\n var itemName = $(\"#spinlabel\").html();\n var quantity = $(\"#spin\").val();\n for(var i = 0; i < CurrentShoppingListArray.length; i++){\n if(itemName == CurrentShoppingListArray[i].name){\n CurrentShoppingListArray[i].quantity = parseInt(CurrentShoppingListArray[i].quantity) + parseInt(quantity);\n return;\n }\n }\n var tempItem = new Item(itemName, quantity);\n CurrentShoppingListArray.push(tempItem);\n}", "function addItem(item){\r\n\tvar found = false;\r\n\tfor(var i =0; i < inventory.length; i++){\r\n\t\tif(inventory[i].name == item.name){\r\n\t\t\tinventory[i].qty += item.qty;\r\n\t\t\tfound = true;\r\n\t\t\tbreak;\r\n\t\t}\r\n\t}\r\n\tif(!found){\r\n\t\tinventory.push(assignItem(invMaster[item.name]));\r\n\t}\r\n}", "function addItemToCart(user, item) {\n amazonHistory.push(user)\n const updateCart = user.cart.concat(item)\n return Object.assign({}, user, { cart: updateCart })\n}", "function addItem(id) { \n $.each(products, function (key, item) {\n if (item.id === id) {\n order.push(item);\n numberOfItems++;\n } \n });\n $('#orderItems').empty();\n $('<span>Items in Cart ' + numberOfItems + '</span>').appendTo($('#orderItems'));\n}", "function addItem(item) {\n if (isFull(basket) === true) {\n console.log(`Basket is currently full. Could not add ${item}`);\n return false;\n } else {\n basket.push(item);\n return true;\n }\n}", "function addItem(item) {\n\t\t// if the item is not empty or not spaces, then go forward.\n\t\tif (/\\S/.test(item)) {\n\t\t\t// do not add duplicates\n\t\t\tif (isDuplicate(item)) {\n\t\t\t\talert(\"'\" + item + \"' is already in the shopping list.\");\n\t\t\t\treturn;\n\t\t\t}\n\n \t\tvar str = \"<li><span class='label'>\" + item + \"</span>\"\n \t\t\t\t\t+\"<div class='actions'><span class='done'><button class='fa fa-check'><span class='element-invisible'>Done</span></button></span>\"\n \t\t\t\t\t+ \"</span><span class='delete'><button class='fa fa-times'><span class='element-invisible'>Delete</span></button></span></div></li>\";\n\n \t\t// adding the new li tag to the end of the list - you are actually adding html string, but jQuery will create elements for you\n\t\t\t$(\"#items\").append(str);\n\t\t}\n\t}", "function createItemOrder(itemId, quantity) {\n var req = new XMLHttpRequest();\n var payload = {\n 'itemId': itemId,\n 'quantity': quantity\n };\n req.open('POST', 'order.php');\n req.setRequestHeader('Content-Type', 'application/json;charset=UTF-8');\n req.addEventListener('load', function() {\n executeItemPayment(req);\n } , false);\n req.send(JSON.stringify(payload));\n }", "function addItemQty(item, quantity){\n\t\t\tif(!item.qty) item.qty = quantity;\n\t\t\telse item.qty += quantity;\n\t\t}", "function addItem(obj, item) {\n obj.items.push(item);\n obj.childrenCount = +obj.childrenCount + 1;\n }", "add(item) {\n const book = new this._Element(item);\n const id = this._generateId(book);\n if (!this._items[id]) {\n book.DOMElement = this._generateDOMElement(book);\n this._items[id] = book;\n this._container.appendChild(book.DOMElement);\n this._updateStorage()\n }\n }", "function addToOrder() { \r\n\tlet placeorder;\r\n\tlet item = document.getElementById(\"item\").value;\r\n\tlet lettuce = document.getElementById(\"lettuce\");\r\n\tlet meat = document.getElementById(\"meat\");\r\n\tlet cheese = document.getElementById(\"cheese\").value;\r\n\tif (item === \"burger\" && cheese != \"none\") {\r\n\t\tplaceorder = new CheeseBurger(4.49, lettuce, meat, cheese);\r\n\t} else if (item === \"burger\") {\r\n\t\tplaceorder = new Burger(3.99, lettuce, meat, cheese);\r\n\t} else {\r\n\t\tplaceorder = new Sandwich (2.99, lettuce, meat, cheese);\r\n\t}\r\n\torder.add(placeorder);\r\n}", "function addItem(data) {\n console.log(` Adding: ${data.lastName} (${data.owner})`);\n Items.insert(data);\n}", "function addItem(data) {\n console.log(` Adding: ${data.lastName} (${data.owner})`);\n Items.insert(data);\n}", "function insertItem(){\n item = capitalizeFirstLetter(getInput())\n checkInputLength()\n myGroceryList.push(item)\n groceryItem.innerHTML += `\n <div class=\"item\">\n <p>${item}</p>\n <div class=\"item-btns\">\n <i class=\"fa fa-edit\"></i>\n <i class=\"fa fa-trash-o\"></i>\n </div>\n </div>`\n itemAddedSuccess()\n clearBtnToggle()\n clearInputField()\n // Create edit/delete buttons based on icons in <i> tags, above\n queryEditBtn()\n queryDeleteBtn()\n // Adds items to local Storage\n updateStorage()\n}", "function addItem (diner, item, qty) {\n for (var i = 0; i < qty; i++) {\n diner.ate.push(item) * qty;\n }\n}", "function addItemToShoppingList(itemName) {\n console.log(`Adding \"${itemName}\" to shopping list`);\n STORE.items.push({name: itemName, checked: false});\n}", "add(item) {\n\t\tthis.ledger.addItem(item);\n\t\treturn this; //for chaining\n\t}", "function addItem(e) {\r\n // body...\r\n \r\n // Storing the sibling element of the food item that was clicked by the customer in a variable\r\n var foodItem = event.target.nextElementSibling;\r\n console.log(foodItem);\r\n // A variable that contains the id value for fooditem\r\n var foodID = foodItem.getAttribute('id');\r\n\r\n // Store the copy of the foodItem and its descendants\r\n var foodDescription = foodItem.cloneNode(true);\r\n\r\n // Store a reference of the shopping cart\r\n var cartBox = document.getElementById('cart');\r\n\r\n // A variable to test for duplicate items\r\n var duplicateOrder = false;\r\n// A for loop to check for duplicates and rid of duplicates\r\n for (var n = cartBox.firstChild; n = n.nextElementSibling; n !== null) {\r\n if (n.id === foodID) {\r\n duplicateOrder = true;\r\n n.firstElementChild.textContent++;\r\n break;\r\n }\r\n }\r\n\r\n // Testing if duplicate order is still false\r\n if (duplicateOrder === false) {\r\n var orderCount = document.createElement(\"span\");\r\n orderCount.textContent = \"1\";\r\n foodDescription.prepend(orderCount);\r\n cartBox.appendChild(foodDescription);\r\n }\r\n}", "function addToCart()\n\t{\n\t\t// avoid adding to cart before the item info is fetched\n\t\t// if( product.ASIN === undefined) return ;\n\t\tif( product === undefined) return ;\n\t\t\n\t\tvar newItem = Object.assign({}, product); \n\t\tnewItem.ID \t\t= Date.now();\n\t\t\n\t\t// console.log( \"product id: \" + newItem.ID );\n\t\tnewProduct = \"<tr>\"\n\t\t\t\t\t\t+ \"<td><img src=\\\"\"+ newItem.Image_url + \"\\\" class=\\\"thumbnail\\\" /> </td>\"\n\t\t\t\t\t\t+ \"<td>\"+ newItem.Color\t\t\t+\"</td>\"\n\t\t\t\t\t\t+ \"<td>\"+ newItem.Size\t\t\t+\"</td>\"\n\t\t\t\t\t\t+ \"<td>\"+ newItem.PriceSAR\t\t+\" ريال</td>\"\t\t\t\t\t\t\n\t\t\t\t\t\t+ \"<td>\"+ newItem.TaxSAR\t\t+\" ريال</td>\"\t\t\t\t\t\t\n\t\t\t\t\t\t+ \"<td>\"+ newItem.ShippingCost\t+\" ريال </td>\"\t\t\t\t\t\t\n\t\t\t\t\t\t+ \"<td> <i class='fi-x removeItem button alert' id='\"+ newItem.ID +\"'></i></td>\"\n\t\t\t\t\t\t+ \"</tr>\";\n\t\t\t\t\t\t\n\t\t$('#items > tbody:last-child').append(newProduct);\n\t\t$(\"#addToCartBtn\").notify(\"تم إضافته لسلة المشتريات\", {className:\"success\"});\n\t\t$(\"#itemsList\").slideDown();\n\t\t\n\t\t// save cart\n\t\tsaveCart(\"add\", newItem.ID);\n\t\t\n\t\t// start observer for remove from cart button\n\t\tobserveRemoveBtn();\n\t\t\n\t\t// add to invoice\n\t\taddToInvoice(newItem);\n\t}", "add(item) {\n this.data.push(item);\n }", "function addItem(name) {\n try {\n Item.validateName(name);\n this.items.push(Item.create(name));\n } catch(error) {\n console.log(`${error.message}`);\n }\n }", "function _createOrderItem(orderId, coffeeKindId, quantity, callback) // This creates a new order - belonging to a user through the userId and a coffeeShop through CoffeeShopId\n{\n validate.valOrderItem(orderId, coffeeKindId, quantity, function (data)\n {\n if (data)\n {\n OrderItem.createOrderItem(orderId, coffeeKindId, quantity, function (data2)\n {\n callback(data2)\n })\n } else callback(false)\n })\n\n}", "function purchaseItem() {}", "function purchaseItem() {}", "function purchaseItem() {}", "function purchaseItem() {}", "function purchaseItem() {}", "function purchaseItem() {}", "function addToOrder(orderedMeal) {\n setOrder([...order, orderedMeal]);\n }", "function addToCart(newItem) {\n console.log(newItem);\n const index = findCartItem(\n newItem.product.id,\n newItem.toppings,\n newItem.remark\n );\n\n if (index === -1) {\n setCart([...cart, { ...newItem, id: uuidV4() }]);\n } else {\n return -1;\n }\n }", "function addItemToShoppingList(itemName) {\n store.push({id: cuid(), name: itemName, checked: false});\n}", "add(item) {\n\t\tthis.queue.set(item, item);\n\t}", "function addToCart(newItem, itemQuantity, itemPrice) {\n\n for (let i = 0; i < cartItems.length; i++) {\n if (cartItems[i].item === newItem) {\n cartItems[i].quantity += itemQuantity;\n total()\n\n return\n }\n }\n\n setCartItems([...cartItems, {\n item: newItem,\n quantity: itemQuantity,\n price: itemPrice\n }])\n\n\n total()\n }", "function addItemToCart(user, item) {\n const updateCart = user.cart.concat(item)\n return Object.assign()\n}", "function addToCart(item) {\n cart.push(item);\n localStorage.setItem(\"shop\", JSON.stringify(cart));\n console.log(cart);\n}", "function addFoodItem(name, expoDate){\n \n if (expoDate != \"\") expoDate = formatDate(expoDate);\n\n db.foodItems.put({name: name, expoDate: expoDate}).then(function(id){\n return db.foodItems.get(id);\n }).then(function (foodItem){\n //after adding item, adding to display\n \n pantry.items.push(foodItem);\n \n if (!pantry.sorted){\n createPantryItem(foodItem);\n }\n else{\n pantry.sortByExpo();\n }\n\n }).catch(function(error) {\n alert (\"Ooops: \" + error);\n }); \n}", "function add(item){\n repository.push(item);\n }", "addPizza( pizza ){\n this.itemList.push(pizza);\n }", "function addToCart(item) {\n var newItem = {}; // this object contains the item name and price.\n\n var newItem = {\n itemName: item,\n itemPrice: Math.floor(Math.random()*100)\n }\n //newItem.itemName = item;\n //newItem.itemPrice = Math.floor(Math.random()*100)\n cart.push(newItem); // it was pop(newItem)\n return `${newItem.itemName} has been added to your cart.`\n}", "function addPurchase(id, exp, qty, price) {\n itemsArray.push({id: id, exp: Date.parse(exp), qty: Number.parseInt(qty), price: Number.parseInt(price)});\n }", "addLineItem(){\n\t\t\t\tthis.setState({\n\t\t\t\t\tlineItems: this.state.lineItems + 1\n\t\t\t\t});\n\t\t\t\tthis.state.lineItemsArray.push({id: this.state.lineItems, desc: \"\", amount: 0});\n\t\t}", "function addSelectedItemToCart() {\n // TODO: suss out the item picked from the select list\n let selectedItem = event.target.items.value;\n console.log(selectedItem);\n // TODO: get the quantity\n let quantity = event.target.quantity.value;\n // TODO: using those, add one item to the Cart\n \n \n carts.addItem(selectedItem,quantity); \n console.log(carts.items);\n \n}", "function addSelectedItemToCart() {\n // TODO: suss out the item picked from the select list\n // TODO: get the quantity\n // TODO: using those, add one item to the Cart\n const product = selectElement.options[selectElement.selectedIndex].text;\n const quantity = parseInt(document.getElementById('quantity').value);\n cart.addItem(product, quantity);\n}", "function addItem (item) {\n if (listPeople.length == 0) getPeopleList()\n\n // busco si ya existe para no agregarlo nuevamente\n for (var i = 0; i < listPeople.length; i++) {\n if (item.name === listPeople[i].name) {\n return\n }\n }\n\n listPeople.push(item)\n\n setPeopleList()\n}", "function addTodo(item) {\n todos.push(item);\n displayTodos();\n}" ]
[ "0.7371496", "0.7093413", "0.6954116", "0.6954116", "0.69319373", "0.68065274", "0.6742936", "0.66140616", "0.6608702", "0.66012317", "0.65237325", "0.64737356", "0.6429142", "0.6424697", "0.6405801", "0.6383083", "0.63603973", "0.63356286", "0.63271755", "0.6282504", "0.6269345", "0.6266951", "0.62660533", "0.6262019", "0.625759", "0.62406534", "0.6230207", "0.62071407", "0.61664444", "0.6166114", "0.6156986", "0.6140817", "0.6135349", "0.6133766", "0.60919595", "0.6089874", "0.6076781", "0.6066441", "0.6054657", "0.60529876", "0.6049648", "0.6041013", "0.6029969", "0.6026833", "0.6003689", "0.59645617", "0.59645617", "0.59634924", "0.5951301", "0.59457064", "0.59435207", "0.59395033", "0.5934441", "0.5925369", "0.5919484", "0.59122366", "0.5910388", "0.59039205", "0.5900313", "0.58955634", "0.5894808", "0.5890863", "0.587445", "0.5856546", "0.5856049", "0.5854818", "0.5836753", "0.5836753", "0.5833445", "0.5833245", "0.5832393", "0.5828588", "0.5819713", "0.5816196", "0.5809432", "0.58049417", "0.5804597", "0.58026505", "0.58026505", "0.58026505", "0.58026505", "0.58026505", "0.58026505", "0.5797781", "0.5791677", "0.5776138", "0.57747626", "0.57745814", "0.5771675", "0.57684684", "0.5765593", "0.5764077", "0.5762002", "0.5751858", "0.5751241", "0.57499856", "0.5745979", "0.57424563", "0.57352656", "0.5734428" ]
0.70886534
2
Shows the product details and the add to order button to the user in a model.
function showItemModal(itemId) { for (let i = 0; i < menuItems.length; i++) { if (menuItems[i].id === itemId) { const item = menuItems[i]; const modal = document.getElementById("addToOrderModal"); modal.setAttribute("data-menuitemid", item.id); document.getElementById("name").innerText = item.name; document.getElementById("category").innerText = item.category; document.getElementById("description").innerText = item.description; document.getElementById("price").innerText = item.price; document.getElementById("calories").innerText = item.calories; document.getElementById("ingredients").innerText = item.ingredients; document.getElementById("picture").setAttribute("src", "../images/" + item.picture_src); // Remove any content info symbols that are already there const node = document.getElementById("content-info"); while (node.firstChild) { node.removeChild(node.firstChild); } if (item.is_gluten_free) { $("#content-info").append( "<img src='../images/gluten-free.svg' alt='Gluten Free'>"); } if (item.is_vegetarian) { $("#content-info").append( "<img src='../images/vegetarian-mark.svg' alt='Vegetarian'>"); } if (item.is_vegan) { $("#content-info").append( "<img src='../images/vegan-mark.svg' alt='Vegan'>"); } // Clear the extra instructions text input document.getElementById("instructions").value = ""; // Set the onclick for the add to order button document.getElementById("addToOrderButton").onclick = function () { addToOrder(document.getElementById("addToOrderModal").getAttribute( "data-menuitemid"), document.getElementById("instructions").value); document.getElementById('addToOrderModal').style.display = 'none'; }; modal.style.display = "block"; break; } } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function onSelectProduct() {\n _$confirmModalText.text(JSON.stringify(this.model));\n _$confirmModal.modal();\n }", "function addProductToUI(product) {\n var row = $(\"<tr></tr>\");\n var colName = $(\"<td></td>\").text(product.localeData[0].title);\n var colDesc = $(\"<td></td>\").text(product.localeData[0].description);\n var price = parseInt(product.prices[0].valueMicros, 10) / 1000000;\n var colPrice = $(\"<td></td>\").text(\"$\" + price);\n var butAct = $(\"<button type='button'></button>\")\n .data(\"sku\", product.sku)\n .attr(\"id\", prodButPrefix + product.sku)\n .addClass(\"btn btn-sm\")\n .click(onActionButton)\n .text(\"Purchase\")\n .addClass(\"btn-success\");\n var colBut = $(\"<td></td>\").append(butAct);\n row\n .append(colName)\n .append(colDesc)\n .append(colPrice)\n .append(colBut);\n $(\"tbody\").append(row);\n}", "async showModalProduct() {\n const self = this;\n self.jquery(\".modalProductToogler\").on(\"click\", async function (event) {\n event.preventDefault();\n const itemDetails = await self.getItemDetails(\n event.target.dataset.productid\n );\n\n self.updateItemDetails(itemDetails);\n self.updateItemSteps(itemDetails);\n self.updateAvailableActions(itemDetails, self.currentAddress);\n self.makeAction(itemDetails);\n\n var myModal = new bootstrap.Modal(\n document.getElementById(\"productDetails\"),\n {\n keyboard: false,\n }\n );\n myModal.show();\n });\n }", "function showProduct() {\n const title = el('products').value;\n const product = products[title];\n if (product) {\n el('title').innerHTML = title;\n el('price').innerHTML = 'Price: ' + currencyFormatter.format(product.price);\n el('image').src = product.image;\n }\n el('quantity-container').style.display = product ? 'block' : 'none';\n}", "ReturnToProductsPage() {\n $(\".add-product-full-popup\").css(\"display\", \"none\");\n $(\".edit-product-full-popup\").css(\"display\", \"none\");\n }", "function renderProductShow(id) {\n Products.show(id).then(product => {\n // console.log(`${product.id} - ${product.title}`)\n const showPage = document.querySelector('.page#product-show')\n const showPageHTML = `\n <h2>${product.title}</h2>\n <p>${product.description}</p>\n <a data-target=\"product-edit\" data-id=\"${ \n product.id \n }\" href=\"\">Edit</a>\n <br>\n <a data-target=\"delete-product\" data-id=\"${product.id}\" href=\"\">Delete</a>\n \n `\n showPage.innerHTML = showPageHTML;\n navigateTo('product-show')\n })\n}", "function addProduct() {\n el('cart').style.display = 'inline-block';\n el('order').style.display = 'none';\n const title = el('products').value;\n const quantity = parseFloat(el('quantity').value);\n cart[title] = (cart[title] || 0) + quantity;\n saveCart();\n showCart();\n}", "function showProducts() {\n\t\tvar form = document.getElementById(\"formId\");\n\t\tform.setAttribute(\"action\", contextName+\"/application/show\");\n\t\tform.setAttribute(\"method\", \"get\");\n\t\tform.submit();\n\n\t}", "showOrder (element){\r\n element.appendChild(document.createElement('hr'));\r\n var orderEl = document.createElement(\"P\");\r\n orderEl.innerHTML = \"<b> Ordre ID: </b>\" + this.orderId + \"</b></br></br><b> Bruger ID</b>: \"\r\n + this.userId + \"</br></br><b>Dato for leje: </b>\" + this.orderDay\r\n + \"/\" + this.orderMonth + \"/\" + this.orderYear + \"</br></br>\"\r\n + \"<b>Tidspunkt for leje: kl. </b>\" + this.timePeriod + \"</br></br>\"\r\n + \"<b>Pris total: </b> \" + this.orderPrice\r\n + \"</br></br> <b> Ordre lavet d. : </b>\" + this.order_placed_at;\r\n element.appendChild(orderEl);\r\n\r\n //Calling the showProducts method from the Orderproduct class on the objects to display those as well\r\n this.products.forEach((item)=>{\r\n item.showProducts(element);\r\n });\r\n element.appendChild(document.createElement('hr'));\r\n }", "static showOrderForm(req, res) {\n const promises = [User.findOne({\n where: {\n email: req.session.email\n }\n }), Product.findAll()]\n Promise.all(promises)\n .then((result) => {\n // res.send(result)\n res.render('createOrder', { UserId: result[0].id, products: result[1] })\n }).catch((err) => {\n res.send(err)\n })\n }", "productInformation() {\n return \"<div style=\\\"margin-bottom: 75px\\\" class=\\\"product\\\">\" +\n \"<img src=\\\"\" + this.img + \"\\\" height=\\\"300\\\" width=\\\"250\\\" >\" +\n \"<h3>\" + this.name + \"</h3>\" +\n \"<p>\" + this.type + \"</p>\" +\n \"<p>\" + this.price + \" DKK</p>\" +\n \"<p><a href=\\\"productDetails.html?id=\" + this.productID + \"\\\">View details</a></p>\" +\n '<button id=\"buybutton\" onclick=\"addProductWithAlert(this)\" data-ID=\"' + this.productID + '\"> Add to cart </button>' +\n \"</div>\";\n }", "function viewProducts() {\n clearConsole();\n connection.query(\"SELECT * FROM products\", function (err, response) {\n if (err) throw err;\n displayInventory(response);\n userOptions();\n })\n}", "render() {\n const {products} = this.props\n return (\n <div className=\"div\">\n <h1>Ebay-clone</h1>\n <h2>All Adds</h2>\n\n\n\n <table className = \"table\">\n <thead>\n <tr>\n <th>Number</th>\n <th>Description</th>\n <th>Price</th>\n </tr>\n </thead>\n <tbody>\n { products.map(product => (<tr key={product.id}>\n <td>{product.id}</td>\n <td>{product.title}</td>\n <td>&euro; {product.price}.00</td>\n <td><button>Buy</button></td>\n\n </tr>)) }\n </tbody>\n\t\t\t\t</table>\n\n <h1>Add Items</h1>\n <form>Insert product information: </form>\n <br />\n <ProductForm />\n\n </div>\n )\n }", "showInfoProduct(product) {\n if (product.status) {\n return <h3>\n ID: {product.id} <br />\n Name: {product.name} <br />\n Price: {product.price} VNĐ <br />\n Status: {product.status ? 'Active' : 'Pending'}\n </h3>\n }\n }", "function populateEditedProduct(product) {\n productNameElm.value = product.name;\n productPriceElm.value = product.price;\n updateBtn.setAttribute('value', `${product.id}`);\n\n}", "function productElement(product){\r\n var item = document.createElement('tr');\r\n item.innerHTML =\r\n '<td>' + product.number + '</td>'+\r\n '<td>' + product.name + '</td>'+\r\n '<td>$' + product.price + '</td>'+\r\n '<td><button value=\"' + product.id + '\" class=\"' + removeBtnclassName + ' mdl-button mdl-js-button mdl-button--raised mdl-button--accent\"><i class=\"material-icons\">delete</i></button><button value=\"' + product.id + '\" class=\"' + editBtnclassName + ' mdl-button mdl-js-button mdl-button--raised mdl-button--accent\"><i class=\"material-icons\">edit</i></button></td>';\r\n return item;\r\n }", "renderToCheckout(product) {\n var $item = `<tr class='item' data-name='${product.name}'>\n <td class='item-name'>${product.name}</td>\n <td class='item-quantity'>${product.quantity}</td>\n <td class='item-price'>${product.r_price}</td>\n <td class='item-unit_price'>${product.unit_price}</td>\n <td class=\"'item-total-price\">${product.unit_price * product.quantity}</td>\n <td class=\"item-total-retail\">${product.r_price * product.quantity}</td>\n <td class=\"item-discount\">${product.discount}</td>\n <td>\n <span class=\"glyphicon glyphicon-edit item-edit\" aria-hidden=\"true\"></span>\n <span class=\"glyphicon glyphicon-trash item-delete\" aria-hidden=\"true\"></span>\n </td>\n </tr>`;\n $(\"#checkout-list\").append($item);\n this.setEditDelete();\n this.setCheckoutTotals();\n }", "function showProductDetails(id) {\n\n history.push(`/BuyProducts/${id}`);\n }", "function showProduct() {\n let productId = commonService.getFromStorage('productId');\n if(productId){\n let promise = httpService.getProductbyId(productId);\n promise\n .then(product => {\n let formatedProduct = productService.getFormatedProduct(product);\n document.getElementById('productDetailId').innerHTML = formatedProduct;\n })\n .catch(error => {\n commonService.showInfoMessage(error);\n });\n }\n}", "function showProduct(){\n let productId = commonService.getFromStorage('productId');\n if(productId){\n let promise = httpService.getProductbyId(productId)\n promise\n .then(product => {\n let formatedProduct = productService.getFormatedProduct(product);\n document.getElementById('productDetailId').innerHTML = formatedProduct;\n })\n .catch(error => {\n commonService.showInfoMessage(error);\n });\n }\n}", "function setProductInView() {\n $scope.presentPercentageOff = $scope.product.percentage_off ? true : false;\n $scope.presentOriginalPrice = $scope.product.original_price ? true : false;\n $scope.changePercentageOff();\n $scope.changeOriginalPrice();\n fillOptionMenus();\n setProductPhotos();\n }", "function handleProductEdit() {\n var currentProduct = $(this)\n .parent()\n .parent()\n .data(\"product\");\n window.location.href = \"/cms?product_id=\" + currentProduct.id;\n }", "render() {\n\t\tconst product = this.props.product;\n\n\t\treturn (\n\t\t\t<div className=\"wc-products-list-card__content\">\n\t\t\t\t<img src={ product.images[0].src } />\n\t\t\t\t<span className=\"wc-products-list-card__content-item-name\">{ this.state.clicked ? __( 'Added' ) : product.name }</span>\n\t\t\t\t<button type=\"button\"\n\t\t\t\t\tclassName=\"button-link\"\n\t\t\t\t\tid={ 'product-' + product.id }\n\t\t\t\t\tonClick={ this.handleClick } >\n\t\t\t\t\t\t{ __( 'Add' ) }\n\t\t\t\t</button>\n\t\t\t</div>\n\t\t);\n\t}", "function addProduct () {\n\n\t}", "function displayProduct(product) {\n document.getElementById('product').innerHTML = renderHTMLProduct(product, 'single');\n}", "function viewProducts(){\n connection.query(\"SELECT * FROM products\", function(err, res) {\n if (err) throw err;\n displayTable(res);\n promptManager();\n });\n}", "addNewProductView(req, res) {\n res.render(\"pages/products/add-product\", {\n title: \"AD - Add New Product\"\n })\n }", "productDetails() {\n return \"<div class=\\\"productDetails\\\">\" +\n \"<img class = \\\"imageClass\\\" src=\\\"\" + this.img + \"\\\" height=\\\"400\\\" width=\\\"300\\\" >\" +\n \"<h3>\" + this.name + \"</h3>\" +\n \"<p> Beer type: \" + this.type + \"</p>\" +\n \"<p> Beer colour: \" + this.colour + \"</p>\" +\n \"<p> Description: \" + this.description + \"</p>\" +\n \"<p> Size: \" + this.size + \"</p>\" +\n \"<p> Price: \" + this.price + \" DKK</p>\" +\n '<button id=\"buybutton\" onclick=\"addProductWithAlert(this)\" data-ID=\"' + this.productID + '\"> Add to cart </button>' +\n \"</div>\";\n }", "@action\n openCustomizeModal(product, mode) {\n if (!product) {\n console.error(\"No product passed to customize modal\")\n }\n this.customizeProduct = product;\n this.customizeButtonText = mode === 'edit' ? 'Update Item' : 'Add to Cart';\n this.customizeModalVisible = true;\n }", "function openNewProduct(){\n cleanProduct();\n $(\"#check-container\").css('display', 'inline');\n $(\"#modal-product\").modal();\n $(\"#btn-save\").attr(\"onclick\",\"saveProduct()\");\n}", "function EnterDetails(product) {\n RemoveDetailsFromProductInfoPage();\n $('#infoName').text(product.Name);\n $('#lblCategory').text(product.CategoryName);\n $('#lblproductID').text(product.Id);\n $('#productIdEdit').text(product.Id);\n $('#lblProductDescription').text(product.Description);\n if (product.Discount == \"\") {\n $(\"#productInfoDiscount\").text('לא');\n }\n else {\n $(\"#productInfoDiscount\").text(product.Discount);\n }\n $(\"#lblProductPrice\").text(product.Price + ' ש\"ח');\n $('#productInfoImage').attr(\"src\", product.ImageUrl);\n GetProductPropertiesInfo(product.Id);\n getProductCounter(product.Id);\n\n\n}", "function renderProducts(model = []) {\n const template = model.map(m => `\n <tr>\n <td>${m.id}</td>\n <td>${m.name}</td>\n <td>${m.cost}</td>\n <td>${m.description}</td>\n </tr>\n \n `).join(' ');\n\n $(\"#products-tbody\").html(template);\n }", "function addProduct(product) {\n console.log(\"* ProductsController: addProduct\");\n $state.go(\"register\");\n }", "function viewProducts() {\n\tconnection.query(\"SELECT * FROM products\", function(err, res) {\n\t\tif (err) throw err; \n\t\tconsole.table(res);\n\t\tchooseAction(); \n\t})\n}", "function displayProducts() {\n console.log(\"\\nShowing current inventory...\\n\".info);\n connection.query(\n \"SELECT * FROM products\", \n (err, res) => {\n if (err) throw err;\n console.table(res);\n promptManager();\n }\n )\n}", "function activate() {\n get_product_details();\n }", "function ordersView(orders){\n\n clearview();\n\n changetitle(\"List of All Orders\");\n\n $(\"#contentviewadmin\").html(`\n \n <div id=\"orderview\">\n \n <div class=\"row\">\n <ul id=\"orderlist\" class=\"list-group\">\n <li id=\"orderuserheader\" class=\"listheaderview list-group-item\">\n <div class=\"row\">\n <div class=\"col-1\">\n ID\n </div>\n <div class=\"col-2\">\n Cashier\n </div>\n <div class=\"col-3\">\n Date\n </div>\n <div class=\"col-2\">\n Value\n </div>\n <div class=\"col-2\">\n Margin\n </div>\n <div class=\"col-2\">\n Actions\n </div>\n </div>\n </li>\n </ul>\n </div> \n </div>\n \n `)\n\n for (let idf in orders){\n\n let order = orders[idf];\n\n let id = order.id;\n let date = order.date;\n let cashierName = order.cashier.name;\n let value = order.value;\n let margin = order.margin;\n\n //Button id\n let productlist = `productlist-id-${id}`\n let modalviewid = `modal-product-list-${id}`\n let orderDetailsIDproduct = `productvieworder-id-${id}`\n\n $(`#orderlist`).append(`\n \n <li id=\"orderuserheader\" class=\"listheaderview list-group-item\">\n <div class=\"row\">\n <div class=\"col-1\">\n ${id}\n </div>\n <div class=\"col-2\">\n ${cashierName}\n </div>\n <div class=\"col-3\">\n ${date}\n </div>\n <div class=\"col-2\">\n $${value}\n </div>\n <div class=\"col-2\">\n $${margin}\n </div>\n <div class=\"col-2\">\n <button type=\"button\" class=\"btn btn-primary\" id=\"${productlist}\">Order Details</button>\n </div>\n </div>\n </li>\n \n <div id=\"${modalviewid}\">\n <ul id=\"${orderDetailsIDproduct}\" class=\"list-group\">\n <li class=\"list-group-item\">\n <div class=\"row\">\n <div class=\"col-3\">Name</div>\n <div class=\"col-3\">Price</div>\n <div class=\"col-3\">Cost</div>\n <div class=\"col-3\">Margin</div>\n </div> \n </li> \n </ul>\n </div>\n \n `)\n\n orderListOfProducts(order, orderDetailsIDproduct);\n\n jQuery(`#${productlist}`).on(\"click\", function (){\n jQuery(`#${modalviewid}`).dialog(\"open\");\n })\n\n $(`#${modalviewid}`).dialog({\n autoOpen: false,\n height: \"auto\",\n width: 600,\n modal: true,\n show: {\n effect: \"fade\",\n duration: 500\n },\n hide: {\n effect: \"fade\",\n duration: 500\n }\n })\n\n\n }\n\n loadhide();\n\n $(\"#contentviewadmin\").fadeIn();\n\n}", "function viewProducts(){\n var query = connection.query(\"SELECT ID, Product_Name , Price, Stock_QTY FROM products;\", function(err, res) {\n console.log(\"\");\n console.table(res);\n console.log(\"\");\n \n managerAsk();\n });\n }", "function displayProducts() {\n\n // create variable with empty string, it will contain product details HTML\n let productsListingHtml = '';\n \n products.forEach(product => {\n \n productsListingHtml += `<div class=\"product\"><p><b>${product['name']}</b></p><p>${product['description']}</p><p>$${product['price']}</p><p>${product['manufacturer']}</p><button id=\"${product['id']}\" class=\"button\">Delete</button></div>`;\n \n });\n\n // add product html string to document to display on screen\n document.querySelector('.products').innerHTML = productsListingHtml;\n\n products.forEach(product => {\n\n // add event listener for product, this will be used to delete product\n document.getElementById(`${product['id']}`).addEventListener(\"click\", deleteProduct);\n \n });\n\n }", "function show_add_product()\n{\n\t//Unselect all products \n\t$(\".product_picker_check\").prop('checked', false);\n\t//Update the products in the product picker \n\t$.each(order_list, function (product_id, product_details)\n\t{\n\t\t$(\"#product_picker_check_\"+product_id).prop('checked', true);\n\t});\n\t$('.overlay').fadeIn(100); \n\t$('#product_picker').fadeIn(100); \t\n}", "AddNewProductPopUp() {\n $(\".add-product-full-popup\").css(\"display\", \"flex\");\n }", "DETAIL_PRODUCT(state, product) {\n state.product = product\n }", "function viewProducts() {\n connection.query('SELECT * FROM products', function(err, results){ \n if (err) throw err;\n displayForManager(results);\n promptManager(); \n })\n}", "function showAddProduct() {\n $(\"#div-product-container\").load(\"/Admin/Product/AddProduct\");\n}", "render() {\n return(\n <div className=\"container\">\n <div className=\"row\">\n <div className=\"col-lg\">\n <h3>All Products</h3>\n </div> \n </div>\n <div className=\"row\">\n <div className=\"col-lg card mb-3 border-secondary\">\n <ul className=\"card-body\">\n { this.renderProducts() }\n </ul>\n </div>\n <div className=\"col-lg\">\n <Product product={ this.state.currentProduct } editform={this.state.currentProductUpdateForm} onDelete={this.handleDeleteProduct} onUpdate={this.handleUpdateProduct} onEdit={this.handleEditProduct} onInputChange={this.handleChangeInputs} />\n <br />\n <AddProduct onAdd={this.handleAddProduct} />\n </div> \n </div>\n </div>\n );\n }", "function product(){\n\tthis.name = \"laptop\";\n\tthis.price = 4500;\n\tthis.showDetails= function(){\n\t\treturn this.name + \":\" + this.price;\n\t};\n}", "function handleProductClick(data)\r\n {\r\n setModalData(data);\r\n setModalStatus(true);\r\n }", "productDetails() {\n alert(\"You clicked on the product details!\");\n }", "function hide_add_product()\n{\n\t//hide the modal box \n\t$('.overlay').hide(); \n\t$('#product_picker').hide(); \t\n\t//Redraw the screen \n\tredraw_order_list();\n}", "render() {\n if (!this.props.product) {\n return <div>Select a product to view profile.</div>;\n }\n\n return (\n <div>\n\n <Header as=\"h4\">Product details</Header>\n {/* Field name */}\n <Grid columns='equal'>\n <Grid.Column>\n <label>Name :</label> \n </Grid.Column>\n <Grid.Column width={12}>\n <b>{this.props.product.name}</b>\n </Grid.Column>\n </Grid>\n\n {/* Field color */}\n <Grid columns='equal'>\n <Grid.Column>\n <label>Color</label> :\n </Grid.Column>\n <Grid.Column width={12}>\n <b>{this.props.product.color}</b>\n </Grid.Column>\n </Grid> \n \n {/* Field price */}\n <Grid columns='equal'>\n <Grid.Column>\n <label>Price</label> :\n </Grid.Column>\n <Grid.Column width={12}>\n <b>{this.props.product.price}</b>\n </Grid.Column>\n </Grid>\n\n {/* Field category */}\n <Grid columns='equal'>\n <Grid.Column>\n <label>Category</label> :\n </Grid.Column>\n <Grid.Column width={12}>\n <b>{this.props.product.category}</b>\n </Grid.Column>\n </Grid> \n\n {/* Field Image field */}\n <Grid columns='equal'>\n <Grid.Column>\n <label>Product image</label> :\n </Grid.Column>\n <Grid.Column width={12}>\n <div className=\"selected-image selected-image__custom\">\n <Image src={this.props.product.image_base64} size=\"small\" />\n </div>\n </Grid.Column>\n </Grid>\n {/* Field description */}\n <Grid columns='equal'>\n <Grid.Column>\n <label>Description</label> :\n </Grid.Column>\n <Grid.Column width={12}>\n <p>{this.props.product.description}</p>\n </Grid.Column>\n </Grid>\n\n </div>\n );\n }", "function showPurchases() {\n app.getView().render('account/giftregistry/purchases');\n}", "function buildProductList(data) { \n let productsDisplay = document.getElementById(\"productsDisplay\"); \n // Set up the table labels \n let dataTable = '<thead>'; \n dataTable += '<tr><th>Product Name</th><td>&nbsp;</td><td>&nbsp;</td></tr>'; \n dataTable += '</thead>'; \n // Set up the table body \n dataTable += '<tbody>'; \n // Iterate over all products and put each in a row \n data.forEach(function (element) { \n console.log(element.invId + \", \" + element.invName); \n dataTable += `<tr><td>${element.invName}</td>`; \n dataTable += `<td><a href='/acme/products?action=mod&id=${element.invId}' title='Click to modify'>Modify</a></td>`; \n dataTable += `<td><a href='/acme/products?action=del&id=${element.invId}' title='Click to delete'>Delete</a></td></tr>`; \n }) \n dataTable += '</tbody>'; \n // Display the contents in the Product Management view \n productsDisplay.innerHTML = dataTable; \n }", "function customerView () {\n common.openConnection(connection);\n let querySQL = 'SELECT item_id, product_name, stock_quantity, price FROM products where stock_quantity > 0'; // exclude from \"where\" to premit out-of-stock items\n connection.query(querySQL, (error, result) => {\n if (error) throw error;\n let msg = ''; \n let title = 'LIST OF PRODUCTS FOR SALE';\n common.displayProductTable(title, result) // pass title and queryset to function that will print out information\n console.log('\\n');\n customerSelect();\n });\n \n}", "function viewProduct(_id) {\n console.log(\"* ProductsController: viewProduct\");\n $state.go(\"detail\", {_id: _id});\n }", "function handleAdd(e) { // render a table upon clicking the \"Add To Cart\" button\n\tdocument.getElementById('table').style.display = 'block';\n\tdocument.getElementById('cart-total').style.display = 'block';\n\n\tif (!document.querySelector('thead').children.length) { // only render table head when it is not exist\n\t\trenderTableHead();\n\t}\n\tcart.addItem(currentProduct);\n\treRenderTableBody();\n\trenderCartTotal();\n}", "function ProductView(products) {\n this.products = products;\n \n }", "function products(data){\n\t\t$scope.products = data;\n\t\t$scope.product = {};\n\t}", "function viewProducts() {\n\tconnection.query('SELECT * FROM Products', function(err, result) {\n\t\tcreateTable(result);\n\t})\n}", "function viewProduct() {\n\n //query from the database all products\n connection.query(\"SELECT * FROM products\",\n\n //if there is an error, show it\n function (err, res) {\n\n if (err) throw (err);\n\n for (var i = 0; i < res.length; i++) {\n console.log(\"----------------------\\n\" + \"ID: \" + res[i].item_id + \"\\nProduct: \" + res[i].product_name + \"\\nPrice: $\" + res[i].price + \"\\nQuantity: \" + res[i].stock_quantity + \"\\n----------------------\");\n }\n\n inquirer.prompt([\n {\n type: \"confirm\",\n name: \"continue\",\n message: \"Would you like to add a new product?\"\n }\n ])\n .then(function (continue_response) {\n if (continue_response.continue) {\n addProduct();\n } else {\n console.log(\"goodbye\");\n connection.end();\n }\n })\n })\n }", "render() {\n return (\n <div>\n <h1>Ecommerce</h1>\n <h2>Product Page</h2>\n {/* <div>Text Input Field For Product Name</div> */}\n <input type=\"text\" name=\"Product Name\" />\n <button onClick={this.handleClick}>\n Search Product\n </button>\n <div>Table for results of product search (name, quantity, review)</div>\n <button onClick={this.handleClick}>\n Purchase Product\n </button>\n <button onClick={this.handleClick}>\n Ship Product\n </button>\n <button onClick={this.handleClick}>\n Shipping Status\n </button>\n <div>Info from Shipping Status displayed here</div>\n </div>\n );\n }", "render() {\n return (\n <div id=\"wrapper-for-product-details\">\n <div id=\"details\">\n <Button id=\"back-button\" onClick={() => this.removeCurrentProductListing()}>Back to Product Listings</Button>\n {/*{\n this.props.currentProductListing.user_id === Number(adapter.getUserId()) && !this.props.currentProductListing.isSold ?\n <Button onClick={this.handleRedirect}>Edit Product Listing</Button>\n :\n null\n }\n */}\n <img id=\"product-details-image\" src={this.props.currentProductListing.image}/>\n <h1 id=\"product-details-name\">{this.props.currentProductListing.name}</h1>\n <h2 id=\"details-description-heading\">Description</h2>\n <p id=\"details-description\">{this.props.currentProductListing.description}</p>\n <p>Location: {this.props.currentProductListing.location}</p>\n <p>Delivery: {this.props.currentProductListing.delivery_method}</p>\n <p>Condition: <strong>{this.props.currentProductListing.condition}</strong></p>\n <p>Value: ${this.props.currentProductListing.value}</p>\n <p>Sold by: {this.getUserName()}</p>\n </div>\n <div id=\"wanted\">\n <h2>Wanted</h2>\n {\n this.props.currentProductListing.exchange_item === null ?\n \"Cash\"\n :\n this.props.currentProductListing.exchange_item\n }\n {\n !adapter.getToken() ?\n <p> ***Log in to buy item*** </p>\n :\n null\n }\n {\n !!adapter.getToken() && !!adapter.getUserId() && Number(adapter.getUserId()) !== this.props.currentProductListing.user_id ?\n <Form.Select\n required\n label=\"Purchase Options:\"\n name=\"purchaseOption\"\n placeholder=\"Purchase Options\"\n options={this.purchaseOptions()}\n value={this.state.purchaseOption}\n onChange={(event, { name, value }) => this.handleChange(event, { name, value })}\n />\n :\n null\n }\n {\n this.state.purchaseOption === \"Cash\" || this.state.purchaseOption === \"Exchange Item\" ?\n <Button onClick={this.handlePurchase}>Purchase</Button>\n :\n null\n }\n {\n this.state.purchaseOption === \"Offer\" ?\n <div>\n <input/>\n <Button>Make an offer</Button>\n </div>\n :\n null\n }\n </div>\n </div>\n );\n }", "function GoToProductDetail(e) {\n Ti.API.info(\"inside GoToProductDetails\");\n Ti.API.info(\"on click\" + e);\n Ti.API.info(\"on click stringify\" + JSON.stringify(e));\n Ti.API.info(e.section.getItemAt(e.itemIndex));\n Ti.API.info(e.section.getItemAt(e.itemIndex).properties.Mid);\n var ProductDetail = Alloy.createController('ProductDetail', e.section.getItemAt(e.itemIndex).properties.Mid, access_token).getView();\n ProductDetail.open();\n\n}", "function displayProduct(item){\r\n if(item.id == 1\r\n || item.id == 2 \r\n || item.id == 3\r\n || item.id == 4\r\n || item.id == 5\r\n || item.id == 6){\r\n return `\r\n <div class = \"product\">\r\n <img src = ${item.img_url}></img>\r\n \r\n <div class = product-top>\r\n <h4>${item.title}</h4>\r\n <h6>$${item.price}</h6>\r\n </div>\r\n\r\n <p>${item.text}</p>\r\n\r\n <div class = product-bottom>\r\n <h6>Rating: ${item.rating} out of 5</h6>\r\n <a href = \"#\"><span>Reviews (${item.reviews})</span></a>\r\n </div>\r\n </div>\r\n `\r\n }\r\n}", "function addProduct(){\n var returnedItem = chooseProduct(this);\n for(var i = 0; i < bowlarray.length; i++){\n if(bowlarray[i]._id === returnedItem._id){\n $(DOMvariables.alertheader).text(\"Выбранный вами продукт уже есть в миске\");\n return;\n }\n }\n $(DOMvariables.alertheader).text(defaulttext);\n bowlarray.push(returnedItem);\n $(DOMvariables.bowlcolumn).render({bowllist: bowlarray}, bowlRender);\n $(\"#bowlcolumn\").find(\"header\").text(\"Итог: \" + sum + \" кал.\");\n }", "addNewProduct() {\n return __awaiter(this, void 0, void 0, function* () {\n let addNewProductLinkText = 'Add New Product';\n yield this.getOrderInfoPO().getActionDropdownButton().selectDropdownMenuOptionByLinkText(addNewProductLinkText);\n });\n }", "function viewProducts() {\n connection.query(\"SELECT * FROM products\", function(err, rows) {\n if (err) throw err;\n console.log(\"\");\n console.table(rows);\n console.log(\"=====================================================\");\n menu();\n });\n}", "function displayCart() {\r\n if (cart.products.length == 0) {\r\n document.getElementById('cart').innerHTML = '<h3>No Product </h3>';\r\n document.getElementById('order').style.display = 'none';\r\n } else {\r\n var cartCode = \"\";\r\n for (var i = 0; i < cart.products.length; i++) {\r\n var product = cart.products[i];\r\n var div = \"<div><strong>\" + product.title + \"</strong> : \" + product.price + \"</div>\";\r\n cartCode += div;\r\n }\r\n\r\n cartCode += \"<h2>TOTAL : \" + cart.total.toString() + \" TND</h2>\";\r\n\r\n document.getElementById('cart').innerHTML = cartCode;\r\n document.getElementById('order').style.display = 'block';\r\n }\r\n }", "function get_product_details() {\n ApiService.retrieve_product().save({'product_id':Evdctrl.product_id}).$promise.then(function(res){\n console.log(res)\n Evdctrl.product_details = res.product_details;\n Evdctrl.is_data_loaded = true;\n })\n }", "function getProductDetails( ctx, next ) {\n var _customerKey = ctx.params.customerKey;\n var _productKey = ctx.params.productKey;\n\n // If user provided 'new' key, display \"Create\" view\n if ( _productKey === 'new' ) {\n self.editorData.input({\n CustomerKey: _customerKey,\n ChileProductKey: null\n });\n // Else, if user provided an existing key, display \"Edit\" view\n } else if ( _productKey ) {\n // Get data for product\n var getProduct = productsService.getCustomerProductDetails( _customerKey, _productKey ).then(\n function( data, textStatus, jqXHR ) {\n // Set editor input to fetched data\n data.CustomerKey = _customerKey;\n self.editorData.input({\n AttributeRanges: data,\n ChileProductKey: _productKey,\n CustomerKey: _customerKey\n });\n },\n function( jqXHR, textStatus, errorThrown ) {\n showUserMessage( 'Could not get product override details', {\n description: errorThrown\n });\n page.redirect( '/' );\n });\n // Else, continue to next route\n } else {\n next();\n }\n }", "function main(){\n // Display the products available for purchase\n getProducts()\n \n }", "function addItem(title){\n \n //if input line isn't empty\n if(title){\n var node = $('<div class=\"product-list-row\"></div>').append($(ITEM_TEMPLATE));\n var statsNode = $('<div class=\"product-left\"></div>').append($(STATISTICS_TEMPLATE));\n \n //set product name to the value of an input field\n node.find(\".product-name\").text(title);\n node.find(\".change-product-name\").val(title);\n statsNode.find(\".product-left-name\").text(title);\n \n //make product bought/not bought\n node.find(\".product-bought\").click(function(){\n if(node.hasClass(\"state-bought\")){\n $(node).removeClass(\"state-bought\");\n $(node).find(\".product-bought\").text(\"Куплено\");\n $(statsNode).remove();\n STATISTICS_LIST.append(statsNode);\n }\n else{\n $(node).addClass(\"state-bought\");\n $(node).find(\".product-bought\").text(\"Не куплено\");\n $(statsNode).remove();\n STATISTICS_BOUGHT_LIST.append(statsNode);\n }\n });\n \n //delete product\n node.find(\".product-delete\").click(function(){\n $(node).remove();\n $(statsNode).remove();\n });\n \n //decrement product number and make minus button unactive if product number is 1\n node.find(\".product-minus\").click(function(){\n var pdtNumber = parseInt($(node).find(\".product-number\").text());\n pdtNumber--;\n $(node).find(\".product-number\").text(pdtNumber);\n $(statsNode).find(\".product-left-number\").text(pdtNumber);\n if(pdtNumber === 1){\n node.find(\".product-minus\").addClass(\"not-active\");\n }\n });\n \n //increment product number and make minus button active if it is unactive\n node.find(\".product-plus\").click(function(){\n var pdtNumber = parseInt($(node).find(\".product-number\").text());\n if(pdtNumber === 1){\n node.find(\".product-minus\").removeClass(\"not-active\");\n }\n pdtNumber++;\n $(node).find(\".product-number\").text(pdtNumber);\n $(statsNode).find(\".product-left-number\").text(pdtNumber);\n });\n \n //if product name is clicked, get the ability to change it (if product is not bought)\n node.find(\".product-name\").click(function(event){\n if(!node.hasClass(\"state-bought\")){\n event.stopPropagation();\n node.find(\".product-name\").addClass(\"hidden\");\n node.find(\".change-product-name\").removeClass(\"hidden\");\n node.find(\".change-product-name\").focus();\n }\n });\n \n //save new product name when clicked somewhere else from product name input field\n $(document).click(function(){\n\n node.find(\".product-name\").removeClass(\"hidden\");\n node.find(\".change-product-name\").addClass(\"hidden\");\n\n var pnVal = node.find(\".change-product-name\").val();\n node.find(\".product-name\").text(pnVal);\n $(statsNode).find(\".product-left-name\").text(pnVal);\n });\n \n //add new product to the list\n LIST.append(node);\n STATISTICS_LIST.append(statsNode);\n }\n }", "function viewProducts(){\n\n\t// Query: Read information from the products list\n\tconnection.query(\"SELECT * FROM products\", function(viewAllErr, viewAllRes){\n\t\tif (viewAllErr) throw viewAllErr;\n\n\t\tfor (var i = 0; i < viewAllRes.length; i++){\n\t\t\tconsole.log(\"Id: \" + viewAllRes[i].item_id + \" | Name: \" + viewAllRes[i].product_name +\n\t\t\t\t\t\t\" | Price: \" + viewAllRes[i].price + \" | Quantity: \" + viewAllRes[i].stock_quantity);\n\t\t\tconsole.log(\"-------------------------------------------------------------------\");\n\t\t}\n\n\t\t// Prompts user to return to Main Menu or end application\n\t\trestartMenu();\n\t});\n}", "function newProduct (err, results) {\n if (err) {\n console.log(err)\n }\n console.log(`New product added, Product ID = ${results.insertId}`)\n mainMenu()\n}", "function displayCurrentProduct(curTed) {\n\n //add current product information (title, image etc.) to the card.\n let img = document.getElementsByClassName('bImg');\n img[0].src = curTed.imageUrl;\n \n let name = document.getElementsByClassName('bTitle');\n name[0].textContent = curTed.name;\n \n let getText = document.getElementsByClassName('bText');\n getText[0].textContent = curTed.description;\n\n let price = document.getElementsByClassName('bPrice');\n price[0].textContent = curTed.price / 100 + \" €\";\n\n let getOpt = document.getElementsByClassName('bOption');\n\n //Add options to customize the product\n AddColorOption(curTed, getOpt[0]); \n AddQtyOption(stock, getOpt[1]);\n\n //add the product if user click on the add product button\n let getCart = document.getElementById(\"btnAddCart\");\n getCart.addEventListener('click', () =>{\n\n StoreProductInCart(curTed, getOpt); \n });\n \n}", "function ProductsPage({ actions }) {\n return (\n <WithActions\n actions={actions}\n title=\"Products\"\n itemName=\"product\"\n fetchItems={fetchProducts}\n saveItem={saveProduct}\n renderList={(items, startEdit) => {\n return <ProductsList products={items} onStartEdit={startEdit} />;\n }}\n />\n );\n}", "function renderProductToCart(paramProduct, paramIndex, paramOrderDetail) {\n let vResult = `\n\t\t\t<tr>\n\t\t\t\t<td class=\"si-pic\">\n\t\t\t\t\t<img style=\"width:72px; height:72px\"\n\t\t\t\t\t\tsrc=\"${paramProduct.urlImage}\"\n\t\t\t\t\t\talt=\"product\"\n\t\t\t\t\t/>\n\t\t\t\t</td>\n\t\t\t\t<td class=\"si-text\">\n\t\t\t\t\t<div class=\"product-selected\">\n\t\t\t\t\t\t<p>${paramProduct.buyPrice.toLocaleString()} VNĐ x ${\n paramOrderDetail.quantityOrder\n }</p>\n\t\t\t\t\t\t<h6>${paramProduct.productName} </h6>\n\t\t\t\t\t</div>\n\t\t\t\t</td>\n\t\t\t\t<td class=\"si-close\">\n\t\t\t\t\t<i data-index=\"${paramIndex}\" class=\"ti-close\"></i>\n\t\t\t\t</td>\n\t\t\t</tr>\n\t\t\t`;\n $('.select-items tbody').append(vResult);\n }", "function productNameDisplay() {\n let name = document.createElement('h2');\n name.innerHTML = product.name;\n productDetails.appendChild(name);\n}", "function appendProduct(product){\n let template = ` \n <span>${product.product.name}</span>\n <span>${product.quantity}</span>\n `\n let $product = $(template);\n\n $product.appendTo($orderProducts);\n}", "setDetails() {\n product = this.findElement('.carousel__body__main__product');\n product.children[0].textContent = this.currentProduct.name;\n product.children[1].textContent = this.currentProduct.description;\n product.children[2].textContent = `${this.currentProduct.price} ${this.currentProduct.price_currency_code}`;\n product.children[3].children[0].textContent = this.currentProduct.date_published;\n product.children[3].children[1].textContent = this.currentProduct.availability;\n product.children[3].children[2].children[0].href = this.currentProduct.url;\n }", "function displaySelectedProduct(selectedProduct) {\n // 1. Access to the template.\n const templateElt = document.getElementById(\"template-selection\");\n // 2. Clone the template.\n const templateEltClone = document.importNode(templateElt.content, true);\n // 3. Populate the template.\n templateEltClone.getElementById(\"selection-name\").textContent = selectedProduct.name;\n templateEltClone.getElementById(\"selection-image\").src = selectedProduct.imageUrl;\n templateEltClone.getElementById(\"selection-price\").innerHTML = selectedProduct.price / 100 + `.00 €`;\n templateEltClone.getElementById(\"selection-description\").textContent = selectedProduct.description;\n // 4. Push the template in HTML code.\n document.getElementById(\"row\").appendChild(templateEltClone);\n}", "function addProductInputs(object) {\n\tvar object = object[0];\n\t$('#product-form tbody').append(\n\t\t'<tr>'\n\t + '<td class=\"delete\"><a href=\"#\"><i class=\"fa fa-trash-o\"/></a></td>'\n\t + '<td>'\n\t + '<input type=\"text\" class=\"title-field\" placeholder=\"Title\" value=\"' + object['name'] + '\">'\n\t +\t '</td>'\n\t + '<td>'\n\t + '<input type=\"text\" class=\"size-field\" placeholder=\"Size\" value=\"' + object['size'] + '\">'\n\t +\t '</td>'\n\t + '<td>'\n\t + '<input type=\"text\" class=\"value-field\" placeholder=\"Value\" value=\"' + object['value'] + '\">'\n\t +\t '</td>'\n\t + '<td>'\n\t + '<input type=\"text\" class=\"quantity-field\" placeholder=\"Quantity\" value=\"' + object['qty'] + '\">'\n\t +\t '</td>'\n\t + '</tr>'\n\t);\n\n\tsetDeleteListener();\n}", "function productDescriptionDisplay() {\n let description = document.createElement('p');\n description.innerHTML = product.description;\n productDetails.appendChild(description);\n}", "productDetailView(req, res) {\n res.render(\"pages/products/product-details\", {\n title: \"AD - Product Name\"\n })\n }", "function quickitemview(prodcode,buttonType) {\n\tpcode = prodcode;\n\tbtype = buttonType;\n\tvar url = '';\n\n\tGrainger.Modals.waitModal(\"quickitemview\", \"quickitemview\");\n\n\tif(btype=='update'){\n\t\turl = \"/product/quickview/\"+ pcode +\"?buttonType=\"+btype;\n\t} else {\n\t\turl = '/product/quickview/'+ pcode;\n\t}\n\n\tjQuery.ajax({\n\t\turl: url,\n\t\tcache: false,\n\t\tsuccess: function(data) {\n\t\t\tGrainger.Modals.createAndShowModal(\"quickitemview\", \"quickitemview\", data);\n\t\t},\n\t\terror: function() {\n\t\t\tGrainger.Modals.killModal();\n\t\t}\n\t});\n}", "function ProductListCtrl(productResource){\n // Define Model\n var vm = this;\n\n productResource.query(function(data){\n vm.products = data;\n });\n\n // Define Methods for Actions in the view.\n vm.showImage = false;\n vm.toggleImage = function(){\n vm.showImage = !vm.showImage;\n }\n\n /*vm.products = [\n {\" productId\": 1,\n \"productName\": \"Leaf Rake\",\n \"productCode\": \"GDN-0011\",\n \"releaseDate\": \"March 19, 2009\",\n \"description\": \"Leaf rake with 48-inch handle.\",\n \"cost\": 9.00,\n \"price\": 19.95,\n \"category\": \"garden\",\n \"tags\": [ \"leaf\", \"tool\" ],\n \"imageUrl\": \"http://openclipart.org/image/300px/svg_to_png/26215/Anonymous_Leaf_Rake.png\"\n },\n {\n \"productId\": 5,\n \"productName\": \"Hammer\",\n \"productCode\": \"TBX-0048\",\n \"releaseDate\": \"May 21, 2013\",\n \"description\": \"Curved claw steel hammer\",\n \"cost\": 1.00,\n \"price\": 8.99,\n \"category\": \"toolbox\",\n \"tags\": [\"tool\"],\n \"imageUrl\": \"http://openclipart.org/image/300px/svg_to_png/73/rejon_Hammer.png\"\n },\n {\n \"productId\": 6,\n \"productName\": \"Russian T-14 Armata\",\n \"productCode\": \"RT14-0945\",\n \"releaseDate\":\"May 30, 2014\",\n \"description\": \"Battle ready T-14. Ammunition must be purchased separately.\",\n \"cost\": 45000000.00,\n \"price\": 75000000.00,\n \"category\": \"arsenal\",\n \"tags\": [\"tool\", \"military\", \"insurgence\"],\n \"imageUrl\":\"https://openclipart.org/image/300px/svg_to_png/218607/T-14-Armata-by-Rones.png\"\n }\n ];*/\n }", "function renderDetail(el, user){\n el.append(\n '<div class=\"row align-item-center justify-content-center\">' +\n '<div class=\"col-md-6\">' +\n '<div class=\"card\"><img class=\"card-img\" src=\"' + user.picture + '\" alt=\"Card image\"></div>' +\n '<div class=\"row col-md-12\">' +\n '<h1>' + user.first_name + ' ' + user.last_name + '</h1><br>' +\n '</div>' +\n '</div>' +\n '</div>'\n\n );\n }", "static list(){\n //console.log('list di ProductController');\n Product.list((err, data) => {\n if(err){\n View.error(err);\n }\n else{\n View.list(data);\n }\n })\n }", "function displayProducts(data) {\n for (let i = 0; i < data.length; i++) {\n const productRow = `<div class=\"row\">${data[i].product_name} | ${data[i].department} | $${data[i].price} <div class=\"form-inline\">\n <input type=\"number\" class=\"form-control\" data-id=${data[i].id} placeholder=\"0\" min=\"0\" value=\"0\"></div></div>`\n $(\"#productsPage\").append(productRow);\n }\n\n }", "partialWithOptions(){\n //open modal\n \n this.$store.commit('product/modalId' , this.product.id)\n this.$store.commit('ui/addToCartModal' , true)\n\n \n }", "function viewProducts() {\n\tconnection.query(\"SELECT * FROM products\", function(err, res) {\n\t\tif(err) {\n\t\t\tthrow err\n\t\t};\n\t\tfor (var i =0; i < res.length; i++) {\n\t\t\tconsole.log(\"SKU: \" + res[i].item_id + \" | Product: \" + res[i].product_name \n\t\t\t\t+ \" | Price: \" + \"$\" + res[i].price + \" | Inventory: \" + res[i].stock_quantity)\n\t\t}\n\t\t// connection.end();\n\t\trunQuery();\n\t});\n}", "function createQuote(e) {\n var clickedButtonId = e.srcElement.id;\n\n if (clickedButtonId == \"submit\") {\n var total = 0;\n var orderSummary = \"\";\n\n for (let i=0; i< orderList.length; i++) {\n var x = orderList[i];\n\n //To fix formatting of bools\n if (listOfProducts[x].newRelease == true) {\n listOfProducts[x].newRelease = \"Yes\";\n }\n else {\n listOfProducts[x].newRelease = \"No\";\n }\n //Create order summary\n orderSummary += \"Product: \" + listOfProducts[x].productName + \"\\n\" +\n \"New Release: \" + listOfProducts[x].newRelease + \"\\n\" +\n \"Type: \" + listOfProducts[x].productType + \"\\n\" +\n \"Price: $\" + listOfProducts[x].productPrice.toFixed(2) + \"\\n\\n\";\n\n total += listOfProducts[x].productPrice;\n }\n alert(orderSummary + \"\\n\" + \"Total: $\" + total.toFixed(2));\n }\n}", "function showProduct(myProduct) {\n console.log(myProduct);\n //finding the template\n const template = document.querySelector(\"#productTemplate\").content;\n //cloning the tempalte\n const copy = template.cloneNode(true);\n copy.querySelector(\"img\").src = myProduct.image.guid;\n copy.querySelector(\".price p\").textContent = \"$ \" + myProduct.price;\n copy.querySelector(\".profile-people p\").textContent =\n \"+ \" + myProduct.numberofpeople;\n\n //appending the template\n document.querySelector(\".cards\").appendChild(copy);\n}", "async function displayProduct(products) {\n productContainer.innerHTML = '';\n\n for (product of products) {\n const { urlImg, name, price, id } = product;\n \n productContainer.innerHTML += `<div><img src =${urlImg}><h3>${name} price $${price}</h3><button class=\"buyProduct\" type=\"submit\" value=${id}>Buy</button>\n </div>`;\n }\n getButtons();\n \n}", "function showItemAdditionScreen(){\n $('#itemAdditionScreen').modal('show');\n}", "function setupProductList() {\n if(document.getElementById(\"productList\")) {\n for (productSku of Object.keys(products)) {\n\t // products[productSku].name\t\n\t $(\"#productList\").append(\n\t $(\"<a>\").attr(\"href\",\"product.html?sku=\" + productSku).append(\t \n $(\"<div>\").addClass(\"productItem\").append(\n\t $(\"<h2>\").addClass(\"productTitle\").text(products[productSku].name)\n\t ).append(\n\t\t $(\"<span>\").addClass(\"productPrice\").text(products[productSku].price)\n\t ).append(\n $(\"<img>\").addClass(\"productImage\").attr(\"src\", \"img/\" + products[productSku].img)\n\t )\n\t )\n\t );\n }\n }\n}", "async editProduct(req, res) {\n const leagues = await League.find({});\n const clubs = await Club.find({});\n const product = await Product.findById({ _id: req.params.id })\n res.render('admin/edit-product', {\n layout: 'admin',\n product: mongooseToObject(product),\n clubs: multipleMongooseToObject(clubs),\n leagues: multipleMongooseToObject(leagues),\n })\n }", "function order_create_get(req, res, next) {\n let obj = getObjectToShowForm('Create Order');\n res.render('order_form', obj);\n}", "function viewProduct()\n{\n\twith (window.document.frmListProduct) {\n\t\twindow.location.href = 'productIndex.php';\n\t}\n}", "function addProduct(name, price){ \r\n var number = 1;\r\n if(shop.products){\r\n number = shop.products.length + 1;\r\n } \r\n shop.addProduct(new Product({\r\n name: name,\r\n price: price,\r\n number: number\r\n }));\r\n updateProductList(); \r\n dialog.close();\r\n }", "function show() {\n let data = localStorage.getItem('product');\n if (data){\n\n \n Product.allProduct = JSON.parse(data);}\n \n // if (Product.allProduct !== null) {\n // Product.allProduct = productData;\n // }\n chart();\n}", "function addProductToBill(product, enableUpdateMode) {\n \n enableUpdateMode = typeof enableUpdateMode === 'undefined' ? false : true;\n //check if product exists and add quantity only\n if ($(\"[data-prodid=\" + product.id + \"]\").length > 0) {\n var row = $(\"tr[data-prodid=\" + product.id + \"]\");\n\n qtybox = $(row).find(\".qty_box\");\n oldValue = parseFloat($(qtybox).val());\n var _newQty = parseFloat(product.qty);\n $(qtybox).val(oldValue + _newQty).change();\n return 0;\n }\n\n var objID = billItems.length;\n\n var prod_qty = NumericBox(product.qty);\n\n var row = $(\"<tr>\").attr(\"data-oid\", objID).attr(\"data-prodid\", product.id);;\n\n product.total = product.price * product.qty;\n \n /** Columns **/\n var nameCol = $(\"<td>\").html(product.name);\n var priceInput = $(\"<input type='text' class='price-field' />\");\n $(priceInput).val(product.price);\n var priceCol = $(\"<td>\").html($(priceInput));\n var qtyCol = $(\"<td>\").html($(prod_qty));\n var totalCol = $(\"<td>\").html($(\"<input type='text' readonly='readonly' class='row_total row_total\" + objID + \"'>\").val(product.total));\n var deleteBtn = $(\"<button data-prod_id='\" + product.id + \"' data-id='\" + objID + \"' class='delete_btn'>\").html(\"<i class='fa fa-trash'></i>\");\n\n var sideOrderBtn = $(\"<button data-prod_id='\" + product.id + \"' data-id='\" + objID + \"' class='sd-order_btn'>\").html(\"<i class='fa fa-shopping-cart'></i>\");\n\n billTotal += product.total;\n taxTotal = (billTotal * options.taxPercent) / 100;\n\n billItems.push(product);\n\n $(row).append(nameCol);\n $(row).append(priceCol);\n $(row).append(qtyCol);\n $(row).append(totalCol);\n $(row).append($(\"<td>\").html(deleteBtn).prepend(sideOrderBtn));\n\n $(table).append($(row));\n\n $(billTotalField).val(billTotal);\n $(taxField).val(taxTotal);\n\n if (updateMode && enableUpdateMode) {\n DBUpdate.newItems.push(product);\n }\n }" ]
[ "0.6579344", "0.6526556", "0.6366963", "0.629133", "0.6200135", "0.6157923", "0.6079493", "0.60674393", "0.6026862", "0.601563", "0.60132176", "0.60076416", "0.59636503", "0.59381855", "0.5932116", "0.590365", "0.58900684", "0.58897287", "0.5880766", "0.58518803", "0.58438003", "0.58282906", "0.5813282", "0.5803479", "0.58014655", "0.579331", "0.5773843", "0.5772513", "0.5769505", "0.5757754", "0.57538766", "0.5749405", "0.57304406", "0.57244784", "0.5721884", "0.57051307", "0.5702967", "0.56737554", "0.5670514", "0.5668283", "0.56623036", "0.56569606", "0.56539255", "0.5636789", "0.56309056", "0.56033313", "0.5602936", "0.5593032", "0.5580605", "0.5579709", "0.55746114", "0.55671644", "0.5565471", "0.55654085", "0.5550936", "0.55353975", "0.5532774", "0.55319875", "0.5522191", "0.5513877", "0.5505107", "0.5504533", "0.550338", "0.5493289", "0.5490298", "0.5489421", "0.5484445", "0.54762757", "0.5475501", "0.5474726", "0.5473838", "0.54710484", "0.5463717", "0.54623145", "0.5460417", "0.54587084", "0.5457808", "0.5451751", "0.54449797", "0.54430866", "0.5438038", "0.54365766", "0.54363614", "0.5434241", "0.5430585", "0.54255044", "0.5421674", "0.5414701", "0.5409935", "0.54012674", "0.5399953", "0.539743", "0.53959006", "0.5391009", "0.538708", "0.53869957", "0.5383257", "0.5381273", "0.538058", "0.5375222", "0.5374947" ]
0.0
-1
Changes the instructions to a text field the user can edit.
function showEditOrderMenuItem(orderMenuItemId, instructions) { const span = $("#omi-instructions-" + orderMenuItemId); span.empty(); span.append("<input id='omi-instructions-input-" + orderMenuItemId + "' name='omi-instructions-input-" + orderMenuItemId + "' class='instructions-box' type='text' placeholder='Any extra instructions' value='" + instructions + "'>"); span.append("<i id='omi-confirm-" + orderMenuItemId + "' class='fa fa-check fa-lg confirm' onclick='confirmEditOrderMenuItem(" + orderMenuItemId + ")'></i>"); $("#omi-edit-" + orderMenuItemId).hide(); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function editRemarks() {\n\tdocument.getElementById('canFinalize').value = 'NO';\n}", "function setup_text_fields() {\n function field_modified(name) {\n return function() {\n SaveActions[name] = true;\n save_btn_tag.removeClass('disabled');\n };\n }\n\n field_change($('#cy-2x-plugin-download input'), field_modified('cy-2x-plugin-download'));\n field_change($('#cy-2x-plugin-version input'), field_modified('cy-2x-plugin-version'));\n field_change($('#cy-2x-plugin-release-date input'), field_modified('cy-2x-plugin-release-date'));\n field_change($('#cy-2x-versions input'), field_modified('cy-2x-versions'));\n field_change($('#cy-app-description'), field_modified('description'));\n field_change($('#cy-app-license-text input[type=text]'), field_modified('license_text'));\n $('#cy-app-license-text input[type=checkbox]').click(field_modified('license_confirm'));\n field_change($('#cy-app-website'), field_modified('website'));\n field_change($('#cy-app-tutorial'), field_modified('tutorial'));\n field_change($('#cy-app-citation'), field_modified('citation'));\n field_change($('#cy-app-coderepo'), field_modified('coderepo'));\n field_change($('#cy-app-contact'), field_modified('contact'));\n }", "function changeToText(){\t\n\tfor (var i=0; i<inputs.length; i++) {\n\t\tif (inputs[i].type.toLowerCase() === \"password\") {\n\t\t\tinputs[i].setAttribute('type','text');\n\t\t\tinputs[i].setAttribute('waspassword', 'Yes');\n\t\t\tflag++;\n\t\t}\n\t}\n}", "function updateFieldHelpText (event) {\n lib.updateActiveFieldHelpText($(this).val());\n }", "textChange() {\n core.dxp.log.debug('Inside textChange');\n this.assignPlaceholderText();\n }", "function Instructions(props){\n return(\n <div className=\"form-group\">\n <div className=\"label\">\n <textarea className=\"form-control\" onChange={props.setInstructions} value={props.instructions}> </textarea>\n </div>\n <button className=\"btn btn-primary float-right text-edit-buttons\" onClick={props.save}><i class=\"fas fa-save\"></i> Save </button>\n </div>\n )\n}", "function helpline(help) {\n document.post.helpbox.value = eval(help + \"_help\");\n document.post.helpbox.readOnly = \"true\";\n}", "function instructions(){\n // \\n for a new line in the text, extra lines are concatenated on the end with \"+\"\n alert(\"Choose your name, then click start, then click on the planet/moon you want to go to or press a number from 1 to 8\\n\\n\"+\n \"Arrow keys or WASD to move\\nT to toggle force arrow visibility\\nR to restart\\nM to go to the menu screen\\nNever gonna press Q key\\n\"+\n \"In free flight mode you can press '+' or '-' to increase or decrease the gravity\\n\\n\"+\n \"Remember to land the lander gently\\nLand on the blue landing zone for extra points\\nDon't let your fuel get to 0, or you'll crash!\\n\\n\"+\n \"Go to https://doc.co/ys85jg for the User Guide\\n\\n\");\n}", "function editDisputeReason() {\n\tdocument.getElementById('canFinalize').value = 'NO';\n}", "function setTextInput(text) {\n setText(text);\n }", "set editable(value) {}", "function editTextNode(event){\n // Set appropriate informative text on info model\n scope.$apply(function(){\n scope.main.info = handlerHelpers.editingText;\n });\n // The node that contains the text to change\n nodeID = $(event.toElement).closest('.literal-sequence, .literal').attr('id');\n text = event.target.innerHTML; // The current text in the diagram node\n\n // if the text in the node is default text, then initialize the text input box with a placeholder rather than a value attribute\n var valOrPlaceHolder = 'value';\n if (text === '&lt;text_here&gt;') {\n valOrPlaceHolder = 'placeholder';\n }\n\n var width = text.split('').length * 10;\n var textBox = '<div class=\"textEdit\" style=\"position: absolute\"><form class=\"textForm\"><input class=\"textBox\" type=\"text\" '+ valOrPlaceHolder +'=\"'+ text +'\" autofocus></input></form></div>';\n\n $('.work').append(textBox);\n\n $('.textBox').css('width', width); // Set the width of the textBox to fit the contained text\n\n // Move the textEdit form to directly under the mouse\n $('.textEdit').css({\n top: event.pageY - 15,\n left: event.pageX - width/2,\n });\n }", "function changeText() {\n \n }", "function showInstructions() {\n\t\t\tclear();\n\t\t\tdiv.update('<span style=\"color: grey; font-style: italic;\">' + lang.instructions + '</span>');\n\t\t}", "edit() {\n this._enterEditMode();\n }", "function toggleText() {\r\n var text = document.getElementById(\"instructions\");\r\n if (text.style.display === \"none\") {\r\n text.style.display = \"block\";\r\n } else {\r\n text.style.display = \"none\";\r\n }\r\n }", "function setInstructions(instructions) {\n $(\"#Instructions\").html(instructions);\n $(\"#Instructions\").adjustScroll();\n}", "function edit() {\n this.focus();\n this.setSelectionRange(0, this.value.length);\n}", "function DfoSetFieldText(/**string*/ field, /**string*/ text)\r\n{\r\n\tvar xpath = \"//label[text()='\" + field + \"']/../input[contains(@id,'Form')]\";\r\n\tvar obj = DfoFindObject(xpath);\r\n\t\r\n\tif (!obj)\r\n\t{\r\n\t\tLogAssert(\"DfoSetFieldText: field not found: \" + field);\r\n\t\treturn;\r\n\t}\r\n\t\r\n\tobj.object_name = field;\r\n\tobj.DoClick();\r\n\tobj.DoSetText(text);\r\n\tobj.DoSendKeys(\"{TAB}\");\r\n}", "function allow_modif(id){\n $(\"#nom\"+id).attr(\"contenteditable\",\"true\").css(\"background\",\"#eee\");\n $(\"#desc\"+id).attr(\"contenteditable\",\"true\").css(\"background\",\"#eee\");\n $(\"#action\"+id).hide();\n $(\"#edit\"+id).show();\n}", "function toggleTextArea() {\n\t\tvar disabled = document.getElementById(\"note-view\").readOnly;\n\t\tif (disabled) {\n\t\t\tdocument.getElementById(\"note-view\").readOnly = false;\n\t\t\t$(\"#toggle_edit\").text(\"Read Only\");\n\t\t}\n\t\telse {\n\t\t\tdocument.getElementById(\"note-view\").readOnly = true;\n\t\t\t$(\"#toggle_edit\").text(\"Edit\");\n\t\t}\n\t}", "function edit() {\n clickTaskEdit(requireCursor());\n }", "edit_apply(task_id, taskNewTitle) {\n Tasks\n .update({\n '_id': task_id\n }, {\n $set: {text: taskNewTitle},\n });\n\n\n this.task_to_change = \"\"; // reset input clicked (close input edit)\n }", "function editAbout()\r\n{\r\n document.getElementById(\"about\").innerHTML = \"<input type=\\\"text\\\" id=\\\"newabout\\\"><input type=\\\"submit\\\" onclick=\\\"updateAbout()\\\">\";\r\n}", "function editText(value) {\n document.execCommand(value);\n}", "editTattoo () {\n\n }", "function editnotes(){\n\t\t\tdocument.getElementById(\"notes\").readOnly = false;\n\t\t\t\n\t\t\tdocument.getElementById(\"btnEditNotes\").className += \" hidden\";\n\t\t\tdocument.getElementById(\"btnSaveNotes\").className = \"\";\n\t\t}", "toggleEdit() {\n if (this.isEditingOpen()) {\n return this.isEditingOpen(false);\n }\n this.newText(this.message());\n return this.isEditingOpen(true);\n }", "function addInstructionsFunction() {\n var fieldWrapper = $(\"<div class=\\\"fieldwrapper\\\"/>\");\n var fName = $(\"<textarea id=\\\"instructions\\\" name=\\\"instructions\\\" minlength=\\\"1\\\" maxlength=\\\"500\\\" class=\\\"validate materialize-textarea manual-feedback col s11\\\" placeholder=\\\"Example: In a large bowl, mix all the wet ingregients\\\" required></textarea>\");\n var removeButton = $(\"<button class=\\\"btn remove col s1\\\" value=\\\"-\\\" type=\\\"button\\\"><i class=\\\"fa fa-minus\\\" aria-hidden=\\\"true\\\"></i></button>\");\n removeButton.click(function () {\n $(this).parent().remove();\n });\n var alertDiv = $(\"<div class=\\\"col s12 left-align alert-div\\\"></div>\");\n fieldWrapper.append(fName);\n fieldWrapper.append(removeButton);\n fieldWrapper.append(alertDiv);\n $(\"#instructionsform\").append(fieldWrapper);\n // Add event listeners when a new item is created (on advice of Xavier, tutor at Code Institute)\n feedbackFocusFunction();\n feedbackChangeFunction();\n }", "function editNotes()\r\n{\r\n\tvar note = GM_getValue(steam_id, \"Enter notes here\");\r\n\tvar newNote = window.prompt(\"User notes\", note);\r\n\tif (newNote != note && newNote != \"\" && newNote != null)\r\n\t\tGM_setValue(steam_id, newNote);\r\n}", "function editContent(){\n targetItem.children[0].textContent = capitalizeFirstLetter(inputField.value)\n itemEditedSuccess()\n // Pass new values to storage\n storageEditItem(targetItemText, inputField.value)\n \n // Restore app functionality (exit edit-mode)\n clearInputField()\n submitBtnReplace.removeEventListener('click', editContent)\n beginApp()\n }", "edit() {\n }", "function updateText(ev) {\n setText(ev.target.value);\n }", "function editTask(e) {\n var edit = e.parentNode.firstChild.nodeValue;\n var update = prompt(\"Update Your Task\",edit);\n e.parentNode.firstChild.nodeValue = update\n}", "function editTask()\n {\n var parent = this.parentNode;\n var edited = prompt (\"Enter the new title..\");\n parent.firstChild.innerHTML=edited;\n }", "enteredDescription(newText) {\n this.isEditing = false;\n // If the input is for a card, needs to emit from components:\n // card -> draggable -> list -> project\n this.$parent.$parent.$parent.$emit('done-editing-description', newText, this.listIndex, this.cardIndex);\n }", "function showPassword(text){\n xapi.command(\"UserInterface Message TextInput Display\", {\n InputType: KEYBOARD_TYPES.PIN\n , Placeholder: \"Meeting Password (numeric)\"\n , Title: \"Meeting Password\"\n , Text: text\n , SubmitText: \"Next\"\n , FeedbackId: DIALPAD_PASSWORD\n } ).catch((error) => { console.error(error); });\n}", "'change .js-editNote' (event) {\n // Get value from editNote element\n const text = event.currentTarget.value;\n note.set(text);\n }", "function updateUser(){\n helpers.rl.question('\\nEnter user name to update: ', dealWithUserUpdate);\n}", "function onClickTextEjercise5() {\n document.querySelector(\"#text-exercise-5\").innerHTML =\n \"5. This text was changed!!\";\n}", "function doEdit(){\n\n\n if(validation() == false)\n return ;\n\n doEditInLocalstorage(prevli) ;\n doEditInShowList(prevli) ;\n\n\n /*********** Going back to again add Task Field ************/ \n \n document.getElementById(\"task\").value = \"\" ;\n document.getElementById(\"editButton\").style.display = 'none' ;\n document.getElementById(\"addButton\").style.display = 'block' ;\n\n /***************** End ***********************/\n\n\n }", "get editable() {}", "function onEdit() {\n transition(EDIT);\n }", "function editannounement() {\n\n}", "setText(text) {\n this._codeMirror.setValue(text);\n }", "function handleInfoEditClick() {\n\t\talert(\"준비중입니다.\");\n\t}", "function editAnswer(value) {\n setId(value.id); \n setEditQuestion(value.question); \n setFlag(true); //making flag as true to display input field\n }", "function updateText() {\n new_task = task.value;\n console.log(new_task);\n}", "function UserInput(passwordText) {\n document.getElementById(\"password\").textContent = passwordText;\n}", "setVerifyInfoText(text) {\n this.verifyInfoText.innerHTML = text;\n }", "function editable() {\n text.blur();\n setTimeout(function() {\n text.setEditable(true);\n }, 500);\n\n win.removeEventListener('postlayout', editable);\n }", "function editable() {\n text.blur();\n setTimeout(function() {\n text.setEditable(true);\n }, 500);\n\n win.removeEventListener('postlayout', editable);\n }", "function editPage() {\n $(\"[key]\").each(\n function () {\n $(this).attr('contenteditable', 'true');\n }\n );\n }", "editCommand(){const richtext=this.shadowRoot.getElementById(\"richtext\"),editmode=richtext.contentDocument;editmode.designMode=\"on\"}", "handleEdit() {\n this.setState({\n disabled: !this.state.disabled,\n });\n this.changeText();\n\n }", "function editarIndicador(id_indicador, descripcion){\n //console.log(id_indicador);\n //console.log(descripcion);\n var detalle=$('#editarDetalleIndicador');\n var id=$('#editarIdIndicador'); \n detalle.text(descripcion);\n id.val(id_indicador);\n}", "function editKitchenIteams(event){\n if(event.target.classList[1] === 'fa-edit'){\n let editValue = prompt('Enter New Text Here');\n let iteam = event.target.parentElement;\n let spanEl = iteam.querySelector('span');\n spanEl.innerText = editValue;\n\n }\n}", "function _edit() {\n $('name').value = this.name;\n $('key').value = this.key;\n $('action').value = this.action;\n switchToView('edit-form');\n}", "editWorkAndEducation(){\n\t\tresources.workAndEducationTab().click();\n\t}", "function inputPassword(e) {\n document.getElementById(\"password\").textContent = e;\n}", "modifyField(field) {\r\n\r\n // Ask user for value\r\n var value = prompt(field.description || field.name, this.props.action.options[field.id] || \"\")\r\n if (!value)\r\n return\r\n\r\n // Store value\r\n this.props.action.options[field.id] = value\r\n this.forceUpdate()\r\n\r\n }", "function editItem() {\n todoItem = _.first(todo.where({ todo_id: todo_id }));\n log.debug('[TodoListNewEdit] : Editing todo Item', todoItem);\n\n // Set the title to Edit\n Alloy.Globals.Menu.setTitle(\"Edit Task\");\n\n $.textFieldName.value = todoItem.get('name');\n $.textFieldContent.value = todoItem.get('content');\n\n}", "function writePassword() {\n var editBoxPrompts = getPrompts();\n if (editBoxPrompts) {\n var password = generatePassword();\n var passwordText = document.querySelector(\"#password\");\n passwordText.value = password;\n }\n}", "function taskTextInput(){\n\t// If error was displayed and user is focusing/clicking on textfield input to take corrective action\n\tif (document.getElementById(\"errorMsgCont\").innerText !== \"\"){\n\t\tdocument.getElementById(\"errorMsgCont\").innerText = \"\";\n\t\tdocument.getElementById(\"taskTitle\").value = \"\";\n\t}\n}", "function editMode() {\n name.html('<input value=\"' + name.html() + '\"></input>');\n details.html('<input value=\"' + details.html() + '\"></input>');\n actions.html('<button type=\"button\" class=\"btn btn-default btn-xs submit-btn\"><span title=\"Submit\" class=\"glyphicon glyphicon-ok\"></span></button>'\n + '<button type=\"button\" class=\"btn btn-default btn-xs cancel-btn\"><span title=\"Cancel\" class=\"glyphicon glyphicon-remove\"></span></button>');\n }", "function typeInTextarea(newText) {\n var el = document.querySelector(\"#msgEdit\");\n var start = el.selectionStart\n var end = el.selectionEnd\n var text = el.value\n var before = text.substring(0, start)\n var after = text.substring(end, text.length)\n el.value = (before + newText + after)\n el.selectionStart = el.selectionEnd = start + newText.length\n el.focus()\n }", "function editHandler(e) {\n let taskId = e.target.parentElement.getAttribute(\"data-task-id\");\n let textElem = e.target.previousSibling;\n\n beforeEditReplace(textElem, \"input\");\n\n let newInput = document.querySelector(\n \"[data-task-id=\" + CSS.escape(taskId) + \"] > input:nth-child(2)\"\n );\n\n newInput.addEventListener(\"keypress\", function func(e) {\n if (e.code === \"Enter\") {\n afterEditReplace(newInput, \"label\", taskId);\n }\n });\n}", "function updateInstructions() {\n $(\".instructionPane\").html(instructionHTML);\n }", "doEditMode() {\n\n }", "function changeNote() {\n var sNote = document.getElementById('note_area').value;\n document.getElementById('note_area').value = sNote.toUpperCase();\n document.getElementById('btnSaveNote').disabled = sNote.length == 0;\n}", "function textChanged(e) {\n currentMemo.title = document.getElementById(\"memo-title\").value;\n currentMemo.content = document.getElementById(\"memo-content\").value;\n saveMemo(currentMemo, function (err, succ) {\n console.log(\"save memo callback \", err, succ);\n if (!err) {\n currentMemo.id = succ;\n }\n });\n}", "updateText(text) {\n\t\tthis.text = text;\n\t}", "function editNote() {\n if (oSelectedNote != null) {\n document.getElementById('note_area').readOnly = false;\n document.getElementById('btnSaveNote').disabled = false;\n }\n}", "function EditRetargetCommand(){\r\n }", "function editClicked() {\n edit = true;\n}", "function setText(txtId, text) {\n var txt = getTextById(txtId);\n txt.text = text;\n}", "function handleOnChangeText(text) {\n if (editable === true) {\n setValue(text);\n props.propsForChild.storeValuesFromUsers(index, text);\n }\n }", "function editThisListItem() {\n // Capture the text of the current list item\n var currListItemText = $(this).siblings('span').text();\n\n // Replace the <span> with an input field\n // Set the default value to the currListItemText variable from above\n $(this).parent().html(`<input class=\"edited-list-item\" \n type=\"text\" value=\"${currListItemText}\">\n <button class=\"save-edit\">Save Edit</button>`);\n\n // Capture the new value from the input field on button click\n // Replace the input field\n $('#todo').on('click','.save-edit',function() {\n newListItemText = $(this).siblings('input').val();\n $(this).parent().replaceWith(saveEditedListItem(newListItemText));\n });\n }", "togglePasswordMode() {\n this.passwordMode = !this.passwordMode;\n if (this.passwordMode)\n this.editableNode.classList.add(\"passwordInput\");\n else\n this.editableNode.classList.remove(\"passwordInput\");\n }", "function WritePassword(passwordText) {\n document.getElementById(\"password\").textContent = passwordText;\n\n}", "edit() {\n this.saveInterfaceParams();\n var event = new CustomEvent(\"codeeditevent\");\n document.dispatchEvent(event);\n this.deleteFaustInterface();\n this.moduleView.textArea.style.display = \"block\";\n this.moduleView.textArea.value = this.moduleFaust.fSource;\n Connector.redrawInputConnections(this, this.drag);\n Connector.redrawOutputConnections(this, this.drag);\n this.moduleView.fEditImg.style.backgroundImage = \"url(\" + Utilitary.baseImg + \"enter.png)\";\n this.moduleView.fEditImg.addEventListener(\"click\", this.eventCloseEditHandler);\n this.moduleView.fEditImg.addEventListener(\"touchend\", this.eventCloseEditHandler);\n this.moduleView.fEditImg.removeEventListener(\"click\", this.eventOpenEditHandler);\n this.moduleView.fEditImg.removeEventListener(\"touchend\", this.eventOpenEditHandler);\n }", "_setToEditingMode() {\n this._hasBeenEdited = true\n this._setUiEditing()\n }", "function togglePassword(obj, e) {\n\t\t\t\t//alert($(obj).html());\n\t\t\t\te.preventDefault();\n\t\t\t\t\n\t\t\t\t//var upass = document.getElementsByClassName('upass');\n\t\t\t\tvar field = $(obj).parent().parent().find(\".togglePassword\");\n\t\t\t\tvar type = field.attr('type');\n\t\t\t\t\n\t\t\t\t//alert('Type: '+type+'; Val: '+field.val());\n\t\t\t\t\n\t\t\t\tif(type == \"password\"){\n\t\t\t\t\t//field.type = \"text\";\n\t\t\t\t\tfield.attr('type', 'text');\n\t\t\t\t\t$(obj).html(\"Hide\");\n\t\t\t\t} else {\n\t\t\t\t\t//field.type = \"password\";\n\t\t\t\t\t$(obj).html(\"Show\");\n\t\t\t\t\tfield.attr('type', 'password');\n\t\t\t\t}\n\t\t\t}", "set setText (text) {\n this.text = text;\n }", "function doEditCitizen() {\r\n\tallElements = document.getElementById('editCitizenForm');\r\n\ttmp = allElements.children[0];\r\n\ttmp.innerHTML=tmp.innerHTML.replace(/Mail:/,\"邮箱:\");\r\n\ttmp = allElements.children[4];\r\n\ttmp.innerHTML=tmp.innerHTML.replace(/New password:/,\"新密码:\");\r\n\ttmp = allElements.children[8];\r\n\ttmp.innerHTML=tmp.innerHTML.replace(/New password repeat:/,\"再重复一次:\");\r\n\ttmp = allElements.children[12];\r\n\ttmp.innerHTML=tmp.innerHTML.replace(/Old password:/,\"旧密码:\");\r\n\ttmp = allElements.children[16];\r\n\ttmp.innerHTML=tmp.innerHTML.replace(/New avatar:/,\"新头像:\");\r\n\ttmp = allElements.childNodes[30];\r\n\ttmp.nodeValue=tmp.nodeValue.replace(\"max. size\",\"文件尺寸小于\");\r\n\t\r\n\treplaceInputByValue({\"Edit citizen\":[\"Edit citizen\",\"确定编辑\"]});\r\n}", "function help_edit(id, tit_es, tit_en, cnt_es, cnt_en) {\n\n $('#help_edit').modal('show');\n $('#title_spanish').val(tit_es);\n $('#title_english').val(tit_en);\n $('#cont_spanish').val(cnt_es);\n $('#cont_english').val(cnt_en);\n $('#help_id').val(id);\n\n}", "showPassword(e) {\n\t\tif(e){\n\t\t\tvar x = document.getElementById(\"exampleInputPassword1\");\n\t\t if (x.type === \"password\") {\n\t\t x.type = \"text\";\n\t\t } else {\n\t\t x.type = \"password\";\n\t\t }\n\t\t}\n\t}", "function exampleCode(id, text) {\n /* fill examples into the editor */\n $(id).click(function(e) {\n editor.setValue(text);\n editor.focus(); // so that F5 works, hmm\n });\n}", "'click .js-title-edit-button'( e, t ) {\n e.preventDefault();\n TTL.titleEditText( e, t, P );\n//---------------------------------------------------------\n }", "onClickEditMode() {\n\t\teventEmitter.emit(EVENTS.ToggleEditMode, this.Controls.EDIT_MODE);\n\t}", "function showHint() {\n hintField.innerHTML = hint;\n}", "function changeTodo(event) {\n revisedTodo = prompt(\"Enter the updated Todo\");\n\n if (revisedTodo != null && revisedTodo != \"\") {\n var position = event.currentTarget.id.split(\"-\")[1];\n todos[position].todoText = revisedTodo;\n }\n displayTodos();\n}", "function updateMCEPlaceHolderCtl() {\n if (mainWidget.softwareCompetition.projectHeader.isLccchecked()) {\n enableMCEPlaceholderText = true;\n $(['contestDescription', 'round1Info', 'round2Info']).each(function() {\n var obj = CKEDITOR.instances[this];\n if (obj.getData() == \"\") {\n obj.setData(\"Only members that register for this challenge will see this description.\");\n }\n });\n } else {\n $(['contestDescription', 'round1Info', 'round2Info']).each(function() {\n var obj = CKEDITOR.instances[this];\n if (obj.getData() == \"\") {\n obj.setData(\"\");\n }\n });\n enableMCEPlaceholderText = false;\n }\n}", "function toggleEdit () {\n\t\tvar prev = this.previousElementSibling;\n\t\tvar next = this.nextElementSibling;\n\t\tif (prev.className === 'form-check-label' || prev.className === 'form-check-label completed') {\n\t\t\t\n\t\t\tvar editText = prev.innerHTML;\n\t\t\t\n\t\t\teditText = prev.className==='form-check-label completed' ? editText.slice(67) : editText.slice(49);\n\t\t\t\n\t\t\tvar editBar = document.createElement('INPUT');\n\t\t\teditBar.type = 'text';\n\t\t\teditBar.className = 'form-control mb-2 mr-sm-2 mb-sm-0 editInput';\n\t\t\teditBar.value = editText;\n\t\t\teditBar.style.marginLeft = '5%';\n\t\t\t\n\t\t\tvar newEditButton = addNewEditButton();\n\t\t\t//The next line overwrites the default innerHTML property set in addNewEditButton function\n\t\t\tnewEditButton.innerHTML = 'Done editing';\n\t\t\t\n\t\t\tvar editForm = document.createElement('FORM');\n\t\t\teditForm.className = 'form-inline';\n\t\t\t\n\t\t\teditForm.appendChild(document.createTextNode(\" \")); //Because appendChild method only works with nodes\n\t\t\teditForm.appendChild(editBar);\n\t\t\teditForm.appendChild(newEditButton);\n\t\t\ttheCol.insertBefore(editForm, this);\n\t\t\tprev.parentNode.removeChild(prev);\n\t\t\tnext.parentNode.removeChild(next);\n\t\t\tthis.parentNode.removeChild(this);\n\t\t\t\n\t\t\t//Attaching the event handlers to the new elements\n\t\t\tnewEditButton.onclick = toggleEdit;\n\t\t\t\n\t\t} else {\n\t\t\t\n\t\t\tvar newLabel = addNewLabel(prev.value, this);\n\t\t\tvar newEditButton = addNewEditButton();\n\t\t\tvar newDeleteButton = addNewDeleteButton();\n\t\t\t\n\t\t\ttheCol.insertBefore(newLabel, this.parentNode);\n\t\t\tinsertAfter(newEditButton, newLabel);\n\t\t\tinsertAfter(newDeleteButton, newEditButton);\n\t\t\tthis.parentNode.parentNode.removeChild(this.parentNode); //Removing the entire form\n\t\t\t\n\t\t\t//Attaching the event handlers to the new elements\n\t\t\tnewEditButton.onclick = toggleEdit;\n\t\t\tnewLabel.firstChild.onclick = toggleCompletion;\n\t\t\tnewDeleteButton.onclick = deleteItem;\n\t\t\t\n\t\t}\t\n\t}", "function putQuestion() {\r\n inputLabel.innerHTML = questions[position].question\r\n inputField.value = ''\r\n\tdocument.getElementById('inputField').placeholder = placeholders[position].place\r\n inputField.type = questions[position].type || 'text' \r\n inputField.focus()\r\n showCurrent()\r\n }", "function okEdit(){\n\n if(document.getElementById(\"edit-task-entry-box\").value === '')\n {\n alert('Please, write something!'); //shows message if text input is empty\n }\n else\n {\n //gets button id\n let id = idGlobal;\n\n //gets task position from button id\n let taskPosition = id.substr(id.length - 1); \n\n //changes task text propert to new text\n taskArr[taskPosition-1].text = document.getElementById(\"edit-task-entry-box\").value;\n\n //rewrites task list\n rewritesList();\n\n //rechecks boxes\n checksCheckBoxes();\n\n //rechanges the style of completed tasks\n ChangeStyle();\n\n //closes edit box\n closeEditBox();\n };\n\n}", "function modifyLabelBeforeInplaceEdit(editable) {\n var guideFieldLabel = editable.dom.find(\".guideFieldLabel\");\n if (guideFieldLabel.length > 0) {\n var label = guideFieldLabel.find(\"label\");\n if (label.length > 0) {\n label[0].htmlFor = \"\";\n }\n guideFieldLabel.keydown(function (e) {\n if (e.key === \"Enter\" || e.which == 13) {\n e.preventDefault();\n this.blur();\n }\n });\n }\n }", "function UpdateText(formName, text, textName)\r\n{\r\n sql = \"UPDATE `Control` SET `Control`.`Text` = '\" + text + \"' \" +\r\n \"WHERE `Control`.`Dialog_`='\" + formName + \"' AND `Control`.`Control`='\" + textName + \"'\"\r\n view = database.OpenView(sql);\r\n view.Execute();\r\n view.Close();\r\n}", "function changeTextbox()\n{\n\t//NOTE: We are not getting the contents of teh textbox, we are getting the textbox itself!\n\tvar x = document.getElementById('txt1');\n\t//We can use the setAttribute method to alter the textbox attributes.\n\t//This will overwrite existing attributes if we have previous values\n\tx.setAttribute(\"value\", \"can no longer be used\");\n\tx.setAttribute(\"disabled\", \"true\");\n\t//When altering stlyes, it is generally not a good idea to use\n\t//setAttribute - use the following approach instead\n\tx.style.height=\"300px\";\n\tx.style.width=\"150px\";\n}", "function editText(textToChange, newText) {\n\n var panel_texts = {}\n // Save the entries for each panel for the current step\n $('textarea[id^=\"area\"]').each(function(index) {\n console.log($(this).attr(\"id\"));\n var panelId = $(this).attr(\"id\");\n var panelArea = nicEditors.findEditor(panelId);\n var panelContent = panelArea.getContent();\n panel_texts[panelId] = panelContent;\n\n });\n\n var saveStepTextsRequest = $.post(\"/weave/save_step_texts/\", {\n 'csrfmiddlewaretoken': csrftoken,\n 'example_name': exampleName,\n 'step_number': currentStep,\n 'panel_texts' : JSON.stringify(panel_texts)\n });\n saveStepTextsRequest.done(function() {\n var explanationArea = nicEditors.findEditor(\"explanation_area\"); //Save the explanation for this step\n explanation = explanationArea.getContent();\n // Save the explanation for the current step\n $.post(\"/weave/save_explanation/\", {\n 'html': explanation,\n 'csrfmiddlewaretoken': csrftoken,\n 'example_name': exampleName,\n 'step_number':currentStep,\n }).done(function() {\n //get the steps that involve the selected text- rename the view appropriately!!!\n $.post(\"/weave/edit_steps/\", {\n 'example_name': exampleName,\n 'panel_id': currentFocusedEditor,\n 'csrfmiddlewaretoken': csrftoken,\n 'text_to_change' : textToChange + \"\",\n 'new_text' : newText,\n 'step_number' : currentStep\n }).done(\n function(affectedSteps){\n /*\n exactMatches = affectedSteps['exact_matches'];\n possibleMatches = affectedSteps['possible_matches'];\n \n if(exactMatches.length > 0){\n exactMatchesBeingProcessed = true;\n $(\"#step_editor_modal\").modal('show');\n }\n else if(possibleMatches.length > 0){\n exactMatchesBeingProcessed = false;\n $(\"#step_editor_modal\").modal('show');\n }\n */\n loadStep(\"this\");\n allMatches = affectedSteps['all_matches'];\n\n if(allMatches.length > 0){\n $(\"#step_editor_modal\").modal('show');\n }\n //$(\"#step_editor_modal\").modal('show');\n });\n }); \n\n })\n\n}" ]
[ "0.63066214", "0.6167441", "0.61134315", "0.60238266", "0.5946001", "0.58752173", "0.5867565", "0.58643425", "0.5852434", "0.58389056", "0.576848", "0.57407814", "0.57129556", "0.56919795", "0.5672621", "0.5668534", "0.5655739", "0.56312805", "0.55831385", "0.5565735", "0.55635566", "0.5559567", "0.5550378", "0.55175185", "0.5509437", "0.5502976", "0.55006206", "0.54837936", "0.5482786", "0.5462907", "0.5448163", "0.5422546", "0.5419037", "0.5418158", "0.53881973", "0.5368397", "0.53669286", "0.53653455", "0.53544515", "0.5353409", "0.53496975", "0.5349692", "0.5349", "0.53465325", "0.5320124", "0.53193146", "0.5312012", "0.5307305", "0.53070337", "0.5299059", "0.5297805", "0.5297805", "0.5297569", "0.52947694", "0.527943", "0.5276724", "0.5260657", "0.52482986", "0.52442867", "0.5244208", "0.52437174", "0.52401423", "0.52345717", "0.52326685", "0.5221618", "0.52166045", "0.5216148", "0.5213733", "0.5207254", "0.52067965", "0.5206738", "0.5201218", "0.5200274", "0.5182619", "0.5179198", "0.517083", "0.5159803", "0.5158768", "0.5147916", "0.51420534", "0.51341", "0.5131595", "0.5131353", "0.51268286", "0.51257914", "0.51214474", "0.5120098", "0.5117893", "0.51145434", "0.5112921", "0.5111808", "0.5111427", "0.511029", "0.5104096", "0.5101422", "0.5100534", "0.50988793", "0.509753", "0.50832194", "0.50831074" ]
0.59081674
5
Changes the text box with the new instructions back to a normal text and sends the updated instructions to the server.
function confirmEditOrderMenuItem(orderMenuItemId) { const span = $("#omi-instructions-" + orderMenuItemId); const instructions = $("#omi-instructions-input-" + orderMenuItemId).val(); const data = JSON.stringify({ orderMenuItemId: orderMenuItemId, instructions: instructions }); post("/api/authTable/changeOrderInstructions", data, function (data) { if (data === "success") { $("#omi-confirm-" + orderMenuItemId).remove(); $("#omi-instructions-input-" + orderMenuItemId).remove(); $("#omi-edit-" + orderMenuItemId).show(); $("#omi-instructions-" + orderMenuItemId).append("<span id='omi-instructions-" + orderMenuItemId + "-text'>" + instructions + "</span>") } }); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function updateInstructions() {\n $(\".instructionPane\").html(instructionHTML);\n }", "function update_text()\n\t{\n\t\tmathjax_running = true;\n\t\tupdate_required = false;\n\n\t\t// Parse BBCode\n\t\t$('#' + buffer).html(BBCodeParser.parse(PageUtil.h(raw_text)));\n\n\t\t// Enqueue\n\t\tMathJax.Hub.Queue([\"Typeset\", MathJax.Hub, buffer], [mathjax_callback]);\n\t}", "function updateDisplay(message) { \n\n var target = document.getElementById(\"txtAnswer\");\n\n target.value = message+\"\\n\\n\"+target.value;\n\n }", "textChange() {\n core.dxp.log.debug('Inside textChange');\n this.assignPlaceholderText();\n }", "function setText(ntext){\n document.getElementsByClassName(\"newText\")[0].value = ntext;\n var resdiv = document.getElementsByClassName(\"result\")[0];\n resdiv.innerHTML = \"\";\n resdiv.style.visibility = \"hidden\";\n }", "function sendInfo(){\n\tvar neuron = textNeuron.value;\n\tvar axon = textAxon.value;\n//\ttextNeuron.value = \"\";\n//\ttextAxon.value = \"\";\n//\tlocalStorage.setItem(\"neuronStorage\", \"\");\n//\tlocalStorage.setItem(\"axonStorage\", \"\");\n\tself.port.emit(\"text-entered\", [neuron, axon]);\n\t\n}", "function UpdateDisplay(msg) {\n console.log(msg);\n var target = document.getElementById(\"maintext\");\n console.log(target);\n target.value = msg + \"\\n\\n\";\n }", "updateText(text) {\n\t\tthis.text = text;\n\t}", "function reset() {\n currentWord = 0;\n correct = 0;\n input.value = \"\";\n input.className = '';\n // textDisplay.style.display = 'block';\n startTime = 0;\n $(\"#input\").remove();\n $(\"#submitInfo\").remove();\n $(\"#textDisplay\").empty();\n $(\"#instructions\").empty();\n $(\"#textBox\").append($(\"<input>\",{\"id\" : \"input\", \"value\" : \"Restart\",\"type\" : \"submit\",\"class\":\"hide\"}));\n showText();\n }", "function updateProtocol(text)\n{\n document.getElementById(\"protocol\").innerHTML += text + \"<br/>\";\n}", "function mnemButton(evt, mnemonic) {\n let text = document.getElementById(\"textBox\").value;\n if (text != '') {\n text += '\\n';\n }\n text += mnemonic;\n document.getElementById(\"textBox\").value = text;\n}", "function updateText(ev) {\n setText(ev.target.value);\n }", "function backupInput() {\n lastInput = ELEMENTS.UPDATE_TEXTAREA.val();\n }", "function changeText() {\n\t\tflipDisableOption();\n\t\trunning = true;\n\t\tcurrentFrames = $(\"text-area\").value;\n\t\tcurrentInterval = setInterval(insertFrame, currentSpeed);\n\t}", "function changeText() {\n \n }", "function updateMessage() {\n document.getElementById('targetMessage').innerHTML = document.getElementById('message-field').value;\n document.getElementById('message-field').value = \"\"\n document.getElementById('noel').innerHTML = document.getElementById('name-field').value;\n document.getElementById('name-field').value = \"\"\n}", "function sendMsg(event) {\n //$(\"editwindow\").contentDocument.body.innerHTML += \"<img src=\\\"icon/loginloading.gif\\\" alt=\\\"loading\\\"/>\"\n var msg = $(\"editwindow\").contentDocument.body.innerHTML;\n if (msg.length < 1) {\n // show warning if the edit box is empty\n // and don't send the empty message\n $(\"editwindow\").highlight();\n return;\n }\n new Ajax.Request(\"revMsg.php\", {\n method: \"post\",\n parameters: { tile: tile, nickname: nickname, msg: msg },\n onSuccess: function(response){},\n onFailure: function (response) {\n alert(\"Fail to send the message\");\n }\n });\n // clean the input box\n $(\"editwindow\").contentDocument.body.innerHTML = \"\";\n}", "function updateTextInput1(val) {\n document.getElementById('textInput1').innerHTML=val; \n }", "function sendText() {\n if (textChat.value != \"\") {\n writeText(textChat.value);\n pushText(textChat.value);\n }\n textChat.value = \"\";\n }", "function setTextarea(e) {\n e.preventDefault();\n var textarea = document.querySelector('.arrow_box textarea');\n var fullText = textarea.value;\n var code = formatSend(fullText);\n textarea.value = code;\n }", "function editText(textToChange, newText) {\n\n var panel_texts = {}\n // Save the entries for each panel for the current step\n $('textarea[id^=\"area\"]').each(function(index) {\n console.log($(this).attr(\"id\"));\n var panelId = $(this).attr(\"id\");\n var panelArea = nicEditors.findEditor(panelId);\n var panelContent = panelArea.getContent();\n panel_texts[panelId] = panelContent;\n\n });\n\n var saveStepTextsRequest = $.post(\"/weave/save_step_texts/\", {\n 'csrfmiddlewaretoken': csrftoken,\n 'example_name': exampleName,\n 'step_number': currentStep,\n 'panel_texts' : JSON.stringify(panel_texts)\n });\n saveStepTextsRequest.done(function() {\n var explanationArea = nicEditors.findEditor(\"explanation_area\"); //Save the explanation for this step\n explanation = explanationArea.getContent();\n // Save the explanation for the current step\n $.post(\"/weave/save_explanation/\", {\n 'html': explanation,\n 'csrfmiddlewaretoken': csrftoken,\n 'example_name': exampleName,\n 'step_number':currentStep,\n }).done(function() {\n //get the steps that involve the selected text- rename the view appropriately!!!\n $.post(\"/weave/edit_steps/\", {\n 'example_name': exampleName,\n 'panel_id': currentFocusedEditor,\n 'csrfmiddlewaretoken': csrftoken,\n 'text_to_change' : textToChange + \"\",\n 'new_text' : newText,\n 'step_number' : currentStep\n }).done(\n function(affectedSteps){\n /*\n exactMatches = affectedSteps['exact_matches'];\n possibleMatches = affectedSteps['possible_matches'];\n \n if(exactMatches.length > 0){\n exactMatchesBeingProcessed = true;\n $(\"#step_editor_modal\").modal('show');\n }\n else if(possibleMatches.length > 0){\n exactMatchesBeingProcessed = false;\n $(\"#step_editor_modal\").modal('show');\n }\n */\n loadStep(\"this\");\n allMatches = affectedSteps['all_matches'];\n\n if(allMatches.length > 0){\n $(\"#step_editor_modal\").modal('show');\n }\n //$(\"#step_editor_modal\").modal('show');\n });\n }); \n\n })\n\n}", "function processInputCommand()\n {\n var inputText = my.html.input.value\n var goodChars = my.current.correctInputLength\n\n if (inputCommandIs('restart') || inputCommandIs('rst')) {\n location.href = '#restart'\n } else if (inputCommandIs('fix') || inputCommandIs('xxx')){\n my.html.input.value = inputText.substring(0, goodChars)\n updatePracticePane()\n } else if (inputCommandIs('qtpi')) {\n qtpi()\n }\n }", "function textChanged(e) {\n currentMemo.title = document.getElementById(\"memo-title\").value;\n currentMemo.content = document.getElementById(\"memo-content\").value;\n saveMemo(currentMemo, function (err, succ) {\n console.log(\"save memo callback \", err, succ);\n if (!err) {\n currentMemo.id = succ;\n }\n });\n}", "function sendText(textObj) {\n \taddChatText('self', htmlSprites(textObj.value)); \n \ttextObj.value=''; \n }", "function updateText(){\r\n\r\n\tvar text = document.getElementById(\"simulationtext\").value;\r\n\tdocument.title = text;\r\n\r\n\tif(text.length>0){\r\n\t\tclearSeed();\r\n\t\tsetAnimationFunction();\r\n\t\tenableShare();\r\n\r\n\t\tsimText = text;\r\n\t\tpathIsText = true;\r\n\t\trestart = true;\r\n\t}\r\n}", "update(text) {\n let actions = [];\n if (text !== undefined) {\n if (text.normalize) {\n text = text.normalize('NFC');\n }\n const newBuffer = Punycode.ucs2.decode(text || '');\n actions = diff(this.buffer, newBuffer.slice());\n this.buffer = newBuffer;\n this.emitState();\n }\n const now = Date.now();\n if (this.changedBetweenResets && now - this.lastResetTime > this.resetInterval) {\n this.actionQueue = [];\n this.actionQueue.push({\n position: 0,\n text: this.text,\n type: 'insert'\n });\n this.isReset = true;\n this.lastActionTime = now;\n this.lastResetTime = now;\n this.changedBetweenResets = false;\n }\n else if (actions.length) {\n const wait = now - (this.lastActionTime || now);\n if (wait > 0 && !this.ignoreWaits) {\n this.actionQueue.push({\n duration: wait,\n type: 'wait'\n });\n }\n for (const action of actions) {\n this.actionQueue.push(action);\n }\n this.lastActionTime = now;\n this.changedBetweenResets = true;\n }\n }", "function updateText(){\n // CODE GOES HERE\n //console.log(\"Working\");\n\n //get the value from the html element\n let text = document.getElementById('text-input').value;\n\n // change the value from the formmated text\n document.getElementById('text-output').innerText = text;\n}", "function updateViaText() {\n //clear the error message box\n errorMessages.value('');\n\tvar input_txt = '';\n\tinput_txt += inputPalette.value() + '\\n';\n\tinput_txt += inputBlocksWide.value() + 'x' + inputBlocksHigh.value() + '\\n\\n';\n //**bl gets the returned boolean value(if the block is empty or not)\n var bl = isBlocksEmpty(inputBlocks.value());\n //**bk gets the returned string(could be empty or not) after it has been validated\n var bk = validateRuleBLOCKS(inputBlocks.value());\n if (bl == true){\n //**consent gets the user's \"clicked\" response\n var consent = confirm(\"Text blocks are empty, are you sure you want to continue?\");\n if (consent == true){\n bk = validateRuleBLOCKS(inputBlocks.value());\n }\n else if (consent == false){\n if (bl == true){\n updateTextBoxes();\n bk = validateRuleBLOCKS(inputBlocks.value());\n }\n }\n }\n input_txt += bk;\n updateQuilt(input_txt);\n}", "function updateText() {\n new_task = task.value;\n console.log(new_task);\n}", "function resetNewMsgBox() {\n document.querySelector('input#toAccount').value = \"\";\n document.querySelector('input#title').value = \"\";\n document.querySelector('textarea#content').value = \"\";\n submitButton.disabled = false;\n}", "function updateTextArea() {\n // update save button\n if (localStorage.textAreaData != notepad.node.html()) {\n $(\"#save i\").addClass(\"shake\");\n $(\"#save i\").css(\"color\", \"rgb(33, 37, 41)\");\n } else {\n $(\"#save i\").removeClass(\"shake\");\n $(\"#save i\").css(\"color\", \"rgba(0,0,0,0.1)\");\n }\n wordsCount();\n checkSelectionFormat();\n ee();\n}", "function _update_message(transcribed_text){\n $(message_input_id).val(transcribed_text)\n autosize.update($(message_input_id))\n }", "function updateBottomText(){\n botMemetext.innerHTML = document.getElementById(\"input2\").value;\n}", "function draw_command_sent(response_text){\n\tdocument.getElementById(\"control\").innerHTML = response_text;\n}", "function update() {\n sendMessage(document.getElementById(\"input\").value);\n }", "function updateChatArea(sText) {\n var sCurrentText = $(\"#chatArea\").val() + \"\\n\" + sText;\n $(\"#chatArea\").val(sCurrentText);\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}", "updateNLPInfo(newText) {\n this.spinRefresh(true);\n var oldText = this.state.query.text;\n\n this.props.updateQuery(\n this.state.query.id,\n oldText,\n newText,\n (updatedQuery) => {\n this.setState(\n {\n query: updatedQuery,\n editMode: false,\n },\n () => {\n this.colorEntities();\n this.spinRefresh(false);\n }\n );\n }\n );\n }", "updateTranslation(e){\n var data = { changes : {} },\n value = this.nodeValue(e);\n\n //We need replace &nbsp; for empty spaces. Because if we push empty char it will change to this encoded value.\n //We need place empty char, when user will delete whole translation. This situation is buggy in some browsers..\n //So we need remove here this empty char at the end.\n if ( value.substr(-6) == '&nbsp;' ) {\n value = value.substr(0, -6);\n }\n\n //If is not raw text, we can save unencoded value\n //Because double encodion would be applied from laravel side\n if ( Editor.hasAllowedFormation(e) === false ) {\n value = Helpers.htmlspecialcharsDecode(value);\n }\n\n data.changes[e.getPointerSetting('originalTranslate', 'translatable')] = value;\n\n //Clear previous key change\n if ( this._ajaxSend ) {\n clearTimeout(this._ajaxSend);\n }\n\n //Remove error class before sending ajax\n Helpers.removeClass(e._CAPencil, Pencils.classNameError);\n\n //We need send ajax minimally once per second,\n //because gettext is cached on file timestamp. which in in seconds...\n this._ajaxSend = setTimeout(() => {\n var url = CAEditor.config.requests.updateText;\n\n CAEditor.ajax.post(url, data, {\n success(response){\n Helpers.addClass(e._CAPencil, Pencils.classNameSaved);\n },\n error(response){\n //Add red pointer color\n Helpers.addClass(e._CAPencil, Pencils.classNameError);\n }\n });\n\n this.updateSameTranslationElements(e);\n }, 1000);\n }", "function updateRequestResult(text)\n{\n document.getElementById(\"response\").innerHTML = text;\n}", "function showInstructions() {\n\t\t\tclear();\n\t\t\tdiv.update('<span style=\"color: grey; font-style: italic;\">' + lang.instructions + '</span>');\n\t\t}", "function prepsend() {\n\tvar text = Chatbox.input.value;\n\tChatbox.input.value = null;\n\tswitch (text) {\n\tcase \"/version\":\n\t\tAPI.version();\n\t\treturn;\n\t}\n\tAPI.sendMsg(text);\n}", "function showSentText() {\n // Clear textarea.\n refreshMessages(); \n $(\".message_input\").val(\"\");\n}", "function change_password() {\n\tvar current_password = document.getElementById(\"current_password\").value;\n\tvar new_password = document.getElementById(\"new_password\").value;\n\tvar confirm_new_passord = document.getElementById(\"confirm_new_password\").value;\n\t\n\t// Check validity of given passwords\n\tif(new_password != confirm_new_passord) {\n\t\talert(\"Passwords do not match\");\n\t\treturn;\n\t} else if(new_password.length < 8) {\n\t\talert(\"New password is too short\");\n\t\treturn;\n\t}\n\tvar data = JSON.stringify({\n\t\tcurrent_password : current_password,\n\t\tnew_password : new_password\n\t});\n\tvar uri = getLink(\"UpdatePassword\");\n\t\n\tvar xhr = createRequest(\"POST\", uri);\n\txhr.setRequestHeader(\"Content-Type\", \"text/plain\")\n\txhr.onload = function() {\n\t\tif(xhr.status == 401) alert(\"Current password incorrect\");\n\t\telse if(xhr.status != 200) alert(\"Something went wrong on the server :/\");\n\t\telse {\n\t\t\tdocument.getElementById(\"current_password\").value = \"\";\n\t\t\tdocument.getElementById(\"new_password\").value = \"\";\n\t\t\tdocument.getElementById(\"confirm_new_password\").value = \"\";\n\t\t\talert(\"Password successfully changed!\");\n\t\t}\n\t}\n\txhr.send(data);\n\t\n}", "function getText() {\n\t$(\"button\").click(function (event) {\n\t\tevent.preventDefault();\n\t\tdoResults($(\"textarea\").val());\n\t\tremoveHidden();\n\t\t\n\t})\n}", "function res() {\n\tdocument.getElementById(\"answer\").value = \"\";\n\tdocument.getElementById(\"comment\").innerHTML = \"\";\n}", "function buttonClick2() {\n document.getElementById(\"textclick\").innerHTML = \"Text Changed\";\n}", "function again(){\n principal.value = '';\n time.value = '';\n rate.value = '';\n result.value = '';\n }", "function updateOutput() {\n document.getElementById(\"textout\").innerText = mathify(document.getElementById(\"textin\").value);\n}", "function setNonStatusText() {\n sendUpdate(\"setNonStatusText\", {\n trackerDescription: tr(\"tracker.know_the_status_of_your\"),\n patentText: tr(\"tracker.patent_pending\"),\n num1: tr(\"general.stage1\"),\n num2: tr(\"general.stage2\"),\n num3: tr(\"general.stage3\"),\n num4: tr(\"general.stage4\"),\n num5: tr(\"general.stage5\"),\n trackerHeader: jsDPZ.util.htmlUnEncode(tr(\"confirmation.dominos_tracker\"))\n });\n }", "function change_text(http_data, field_id) {\n\t\t//alert(document.getElementById(field_id).innerHTML);\n\t\t//alert(field_id);\n\t\tif(field_id && document.getElementById(field_id)) {\n \t\t\tdocument.getElementById(field_id).innerHTML = http_data;\n\t\t}\n \t}", "function update() {\n\t\t\t\t\tvar text = scope.$textarea.val().replace(/\\r\\n/g, \"\\n\");\n\t\t\t\t\tscope.$textCopy.text(text);\n\t\t\t\t}", "function handleTextChange(e) {\n const updatedText = e.target.value\n\n setText(updatedText)\n }", "function changeToText(){\t\n\tfor (var i=0; i<inputs.length; i++) {\n\t\tif (inputs[i].type.toLowerCase() === \"password\") {\n\t\t\tinputs[i].setAttribute('type','text');\n\t\t\tinputs[i].setAttribute('waspassword', 'Yes');\n\t\t\tflag++;\n\t\t}\n\t}\n}", "function writeText(text) {\n document.getElementById(\"fieldToComplet\").innerHTML += text + '<br>';\n }", "function editZip()\r\n{\r\n document.getElementById(\"zipcode\").innerHTML = \"<input type=\\\"text\\\" id=\\\"newzip\\\"><input type=\\\"submit\\\" onclick=\\\"updateZip()\\\">\";\r\n}", "function editAbout()\r\n{\r\n document.getElementById(\"about\").innerHTML = \"<input type=\\\"text\\\" id=\\\"newabout\\\"><input type=\\\"submit\\\" onclick=\\\"updateAbout()\\\">\";\r\n}", "function toChangeClefData(){\n currentClefIndex = 0;\n document.getElementById(\"input\").innerHTML = clefDataChangeForm();\n}", "setText(newText)\n\t{\n\t\tthis.text = newText;\n\t\tthis.dom.innerHTML = newText;\n\t}", "function instructions(){\n // \\n for a new line in the text, extra lines are concatenated on the end with \"+\"\n alert(\"Choose your name, then click start, then click on the planet/moon you want to go to or press a number from 1 to 8\\n\\n\"+\n \"Arrow keys or WASD to move\\nT to toggle force arrow visibility\\nR to restart\\nM to go to the menu screen\\nNever gonna press Q key\\n\"+\n \"In free flight mode you can press '+' or '-' to increase or decrease the gravity\\n\\n\"+\n \"Remember to land the lander gently\\nLand on the blue landing zone for extra points\\nDon't let your fuel get to 0, or you'll crash!\\n\\n\"+\n \"Go to https://doc.co/ys85jg for the User Guide\\n\\n\");\n}", "function set(){\n\trl.question('Write the new string \\n', (answer) =>{\n\tGestion.methods.setString( answer ).send({ from : web3.eth.defaultAccount });\n\t//PrepareQuery();\n\tecrire();\n});\n}", "setText(text) {\n this._codeMirror.setValue(text);\n }", "function btnreset_spainfo()\n{\n $( \"[id*=txt]\" ).val(\"\");\n $( \"[id*=notify]\" ).hide();\n CKEDITOR.instances['txtNote'].setData(\"\");\n CKEDITOR.instances['txtMoreInfo'].setData(\"\");\n CKEDITOR.instances['txtIntro'].setData(\"\");\n}", "function doEditCitizen() {\r\n\tallElements = document.getElementById('editCitizenForm');\r\n\ttmp = allElements.children[0];\r\n\ttmp.innerHTML=tmp.innerHTML.replace(/Mail:/,\"Email:\");\r\n\ttmp = allElements.children[4];\r\n\ttmp.innerHTML=tmp.innerHTML.replace(/New password:/,\"Yeni \\u015fifre:\");\r\n\ttmp = allElements.children[8];\r\n\ttmp.innerHTML=tmp.innerHTML.replace(/New password repeat:/,\"Tekrar yeni \\u015fifre:\");\r\n\ttmp = allElements.children[12];\r\n\ttmp.innerHTML=tmp.innerHTML.replace(/Old password:/,\"Eski \\u015fifre: :\");\r\n\ttmp = allElements.children[16];\r\n\ttmp.innerHTML=tmp.innerHTML.replace(/New avatar:/,\"Yeni avatar:\");\r\n\ttmp = allElements.childNodes[30];\r\n\ttmp.nodeValue=tmp.nodeValue.replace(\"max. size\",\"max. boyut :\");\r\n\t\r\n allElements = document.getElementsByTagName('TD');\r\n tmp = allElements[19]\r\n\ttmp.innerHTML=tmp.innerHTML.replace(/Citizen/,\"Vatanda\\u015f\");\r\n\treplaceInputByValue({\"Edit citizen\":[\"Edit citizen\",\"Profil d\\u00fczenle\"]});\r\n}", "function doEditCitizen() {\r\n\tallElements = document.getElementById('editCitizenForm');\r\n\ttmp = allElements.children[0];\r\n\ttmp.innerHTML=tmp.innerHTML.replace(/Mail:/,\"邮箱:\");\r\n\ttmp = allElements.children[4];\r\n\ttmp.innerHTML=tmp.innerHTML.replace(/New password:/,\"新密码:\");\r\n\ttmp = allElements.children[8];\r\n\ttmp.innerHTML=tmp.innerHTML.replace(/New password repeat:/,\"再重复一次:\");\r\n\ttmp = allElements.children[12];\r\n\ttmp.innerHTML=tmp.innerHTML.replace(/Old password:/,\"旧密码:\");\r\n\ttmp = allElements.children[16];\r\n\ttmp.innerHTML=tmp.innerHTML.replace(/New avatar:/,\"新头像:\");\r\n\ttmp = allElements.childNodes[30];\r\n\ttmp.nodeValue=tmp.nodeValue.replace(\"max. size\",\"文件尺寸小于\");\r\n\t\r\n\treplaceInputByValue({\"Edit citizen\":[\"Edit citizen\",\"确定编辑\"]});\r\n}", "function update() {\n if (oldNum == 0) {\n dispLastText.textContent = ``;\n dispCurrentText.textContent = `${newNum}`;\n } else {\n dispLastText.textContent = `${oldNum} ${operator}`;\n dispCurrentText.textContent = `${newNum}`;\n }\n}", "function send_base_code()\r\n{\r\n\ttarget_txt.GetComponent.<Text>().text = user_info;\r\n}", "function btnRun_OnClick(){\r\n\t$('#footer').text('Processing.....');\t\r\n let sText= $('#txtCodeArea').html();\r\n\t\t$('#txtCodeResult').html(makeString(sText));\r\n\t\r\n\tlet myDate = new Date();\t\r\n\t$('#footer').text('Finished at '+myDate.toLocaleString()+'. String Maker by Alex. Email: [email protected]');\t\r\n}", "function updatePageFileds() {\r\n $('#attempts').html(gameModel.attempts);\r\n $('#errors').html(gameModel.errors);\r\n $('#hiddenWord').html(gameModel.hiddenWord.join(\" \"));\r\n $('#misses').html(gameModel.misses);\r\n\r\n $('#guessLetter').val('');\r\n}", "function resetText(){\n \t$(\"#id\").val(\"\");\n \t$(\"#tenDanhMuc\").val(\"\");\n }", "function updateNextStep() {\nnext_step_text.innerHTML = recipe[next_step];\n}", "function updateText(elementID, text){\n \n}", "function save() {\r\n this.textarea.value = this.content();\r\n }", "static textChanged (text) {\n AppDispatcher.dispatch({'action': ActionTypes.TEXT_CHANGED, 'text': text});\n }", "function changeText(value) {\n // would .textContent work instead of .innerHTML?\n document.getElementById('status-line').innerHTML = value;\n\n if (value === 'SENDING') {\n // document.getElementById(\"status-line\").classList.toggle('sending');\n document.getElementById(\"status-line\").className = 'sending';\n\n } else if (value === 'READY') {\n // document.getElementById(\"status-line\").classList.toggle('complete');\n document.getElementById(\"status-line\").className = 'ready';\n console.log(\"text box:\", document.getElementById('text-box').value);\n document.getElementById('text-box').value = '';\n }\n}", "function postingVkWallMob(text) {iimDisplay('Капчта! Пытаемся с моб версии..'); window.document.querySelector('TEXTAREA.textfield').focus = function(){window.document.querySelector(\"TEXTAREA.textfield\").style.backgroundColor='red'; window.document.querySelector('TEXTAREA.textfield').click(); iimSet('text',text); iim(`SET !REPLAYSPEED medium \\n EVENT TYPE=KEYPRESS SELECTOR=\"TEXTAREA.textfield\" Char=\"a\" MODIFIERS=\"ctrl\" \\n EVENTS TYPE=KEYPRESS SELECTOR=\"TEXTAREA.textfield\" CHARS={{text}}\\nEVENT TYPE=CLICK SELECTOR=\".cp_buttons_block>INPUT\" BUTTON=0 \\n wait seconds=3`);}()}", "function doArticleEdit() {\r\n\tallElements = document.getElementById('contentRow').children[1];\r\n\ttmp = allElements.children[0];\r\n\ttmp.innerHTML=tmp.innerHTML.replace(/Newspaper/,\"Gazete\");\r\n\t\r\n\tallElements = document.getElementById('command');\r\n\ttmp = allElements.parentNode.children[0];\r\n\ttmp.innerHTML=tmp.innerHTML.replace(/Edit article/,\"Makaleyi d\\u00fczenle\");\r\n\ttmp = allElements.children[1];\r\n\ttmp.innerHTML=tmp.innerHTML.replace(/Article title:/,\"Makale ba\\u015fl\\u0131\\u011f\\u0131:\");\r\n\ttmp = allElements.children[6];\r\n\ttmp.innerHTML=tmp.innerHTML.replace(/Message:/,\"Mesaj:\");\r\n\t\r\n\treplaceLinkByHref({\r\n\t\t\"editNewspaper.html\":[\"Edit newspaper\",\"Gazeteyi d\\u00fczenle\"],\r\n\t\t\"http://wiki.e-sim.org/en/Newspaper\":[\"Newspaper tutorial on wiki\",\"Gazete e\\u011fitimi\"]\r\n\t});\r\n\treplaceInputByValue({\r\n\t\t\"Edit article\":[\"Edit article\",\"Makaleyi d\\u00fczenle\"]\r\n\t});\r\n}", "function updatePayString(){\n payBalanceField.innerText = payBalance + \" Kr.\"\n}", "function updateTextInput(val) {\n document.getElementById('textInput').value = val;\n}", "function cancelUpdate(){\n\tdocument.querySelector('input[name=notice]').value = ''\n\tdocument.querySelector('#submit').innerHTML = `<input class=\"btn btn-outline-white\" type=\"submit\" name=\"add_notice\" value=\"Add\"></input>`\n}", "function change_pass(event) {\r\n $('#old_pass').val($('#old_pass').val().replace(/\\s/g, ''));\r\n $('#new_pass').val($('#new_pass').val().replace(/\\s/g, ''));\r\n $('#cnf_pass').val($('#cnf_pass').val().replace(/\\s/g, ''));\r\n if ($(\"#old_pass\").val() != \"\") {\r\n $(\"#old_pass_error\").removeClass(\"has-error\");\r\n $(\"#old_pass_msg\").text(\"\");\r\n }\r\n if ($(\"#new_pass\").val() != \"\") {\r\n $(\"#new_pass_error\").removeClass(\"has-error\");\r\n $(\"#new_pass_msg\").text(\"\");\r\n }\r\n if ($(\"#cnf_pass\").val() != \"\") {\r\n $(\"#cnf_pass_error\").removeClass(\"has-error\");\r\n $(\"#cnf_pass_msg\").text(\"\");\r\n }\r\n $(\"#changeAfterSuccessMsg\").text(\"\");\r\n if (event.which == 13) {\r\n $('#change_pass_btn').click();\r\n return false;\r\n }\r\n}//change password end", "function setInstructions(instructions) {\n $(\"#Instructions\").html(instructions);\n $(\"#Instructions\").adjustScroll();\n}", "function postgen() {\r\n var Copyrights = \"©Copyright by giObanii. ©Copyright by toxigeek.com. All Rights Reserved.\";\r\n var txt = '';\r\n document.getElementById('text_editor_textarea').value = \"\"; {\r\n txt += '<div class=\"notice\"><div class=\"img-new\"><div class=\"img\">[img]';\r\n txt += document.getElementById('imagenew').value;\r\n txt += '[/img]</div><div class=\"imgleer\"><a rel=\"nofollow\" target=\"_blank\" href=\"http://{FORUMURL}/';\r\n txt += document.getElementById('urlnew').value;\r\n txt += '\">[img]http://scripts-giobanii.googlecode.com/svn/trunk/images/notice-pespcedit-image.png[/img]</a></div>\\n';\r\n txt += '</div><div class=\"des\">[b]Descripcion de la noticia:[/b]\\n\\n';\r\n txt += document.getElementById('descripcionnew').value;\r\n txt += '\\n</div></div>';\r\n document.getElementById('text_editor_textarea').value += txt\r\n }\r\n}", "function cleartextbox(){\n $(\"#final_span\").val('');\n // $('#MessageBox').val('');\n}", "function submit() {\n var newText1= document.getElementById('newText1').value;\n var newText2= document.getElementById('newText2').value;\n var newText3= document.getElementById('newText3').value;\n \tvar dataString = 'newText1=' + newText1 \n +'&newText2=' + newText2 +'&newText3=' + newText3 ;\n\t\t\t\t\t$.ajax({\n\t\t\t\t\ttype: \"POST\",\n\t\t\t\t\turl: \"submit1.php\",\n\t\t\t\t\tdata: dataString,\n\t\t\t\t\tcache: false,\n\t\t\t\t\tsuccess: function(html) {\n\t\t\t$(\"#btn\").hide();\n $(\"#newText1\").hide();\n $(\"#newText2\").hide();\n $(\"#newText3\").hide();\n $(\"#remove\").hide();\n }\n\t\t\t\t\t});\n}", "function eraseText() {\n\t// Deletes the text in the textarea\n\tdocument.getElementById(\"input_notes\").value = \"\";\n\t// refresh the browser page\n\tlocation.reload();\n}", "function postToEditor() {\n editor.html(extractToText(thisElement.val()));\n }", "function printText(text) {\n document.getElementById('messages').value += '- ' + text + '\\n';\n}", "function save() {\n this.textarea.value = this.content();\n }", "function updateTextInput(val) {\n document.getElementById('textInput').value=val; \n}", "function renew() {\nvar query = $(\"renewbox\").value;\nnew Ajax.Updater(\"renew\",'http://bioinf3.bioc.le.ac.uk/~ss533/cgi-bin/filter.cgi', {\n\tparameters : {query:query}});\nnew Ajax.Updater(\"\",'http://bioinf3.bioc.le.ac.uk/~ss533/cgi-bin/ask2.cgi', {\n\tparameters : {query:query}});\n\n}", "function saveNotesTextArea(e){\n\t YAHOO.util.Event.preventDefault(e);\n\t var notesSpaceTest = /^\\s+$/;\n\t var sellerNotesGot = document.getElementById('sellerNotesNew').value;\n\t sellerNotesGot = sellerNotesGot.replace(/^\\s+|\\s+$/g,\"\");\n\t\tif (notesSpaceTest.test(sellerNotesGot) || sellerNotesGot == \"\"){\n\t\t\tdocument.getElementById('sellerNotesNew').value = \"\";\n\t\t\tdocument.getElementById('addInstructions').title = document.getElementById('addInstructions').childNodes[0].nodeValue;\n\t\t\tYAHOO.util.Dom.removeClass(document.getElementById(\"changeInstructions\"), 'show')\n\t\t\tYAHOO.util.Dom.addClass(document.getElementById('changeInstructions'), 'hide');\n\t\t\tYAHOO.util.Dom.removeClass(document.getElementById(\"addInstructions\"), 'hide')\n\t\t\tYAHOO.util.Dom.addClass(document.getElementById('addInstructions'), 'show');\n\t\t\tdocument.getElementById('notesCharacterCount').innerHTML = \"255\";\n\t\t}\n\t\telse{\n\t\t\tdocument.getElementById('sellerNotesNew').value = sellerNotesGot;\n\t\t\tdocument.getElementById('changeInstructions').title = document.getElementById('changeInstructions').childNodes[0].nodeValue;\n\t\t\tYAHOO.util.Dom.removeClass(document.getElementById(\"changeInstructions\"), 'hide')\n\t\t\tYAHOO.util.Dom.addClass(document.getElementById('changeInstructions'), 'show');\n\t\t\tYAHOO.util.Dom.removeClass(document.getElementById(\"addInstructions\"), 'show')\n\t\t\tYAHOO.util.Dom.addClass(document.getElementById('addInstructions'), 'hide');\n\t\t\ttruncatedInstructionShown(sellerNotesGot);\n\t\t}\n\tPAYPAL.reset.margin.orderInfo.saveInstructions();\n\tdocument.getElementById('sellerNotesCont').style.display = \"none\";\n\tYAHOO.util.Dom.removeClass(document.getElementById(\"addInstructions\"), 'opened')\n\tYAHOO.util.Dom.removeClass(document.getElementById(\"changeInstructions\"), 'opened')\n}", "function editFirst()\r\n{\r\n document.getElementById(\"firstname\").innerHTML = \"<input type=\\\"text\\\" id=\\\"newfirst\\\"><input type=\\\"submit\\\" onclick=\\\"updateFirst()\\\">\";\r\n}", "function rerunInput() {\n console.log('Previous calculation');\n let previousInput = $(this).text();\n let a = previousInput.indexOf('=');\n let deletedInput = previousInput.slice(x,20);\n let newInput = previousInput.replace(deletedInput, '');\n let finalInput = newInput.replace(/\\s/g, ''); //remove global whitespace\n $('#calcInput').val(finalInput);\n}// end rerun", "function typeInTextarea(newText) {\n var el = document.querySelector(\"#msgEdit\");\n var start = el.selectionStart\n var end = el.selectionEnd\n var text = el.value\n var before = text.substring(0, start)\n var after = text.substring(end, text.length)\n el.value = (before + newText + after)\n el.selectionStart = el.selectionEnd = start + newText.length\n el.focus()\n }", "function getNew() {\r\n id(\"answer\").innerHTML = \"\";\r\n stopGame();\r\n makeRequest();\r\n }", "function editLast()\r\n{\r\n document.getElementById(\"lastname\").innerHTML = \"<input type=\\\"text\\\" id=\\\"newlast\\\"><input type=\\\"submit\\\" onclick=\\\"updateLast()\\\">\";\r\n}", "update() {\n this.nameText.text = 'Submit Name to Leaderboard:\\n ' + this.userName + '\\n(Submits on New Game)';\n\n }", "function updateDisplay(message) {\n var message = message;\n var userInput = document.getElementById(\"taGame\");\n userInput.value = message + \"\\n\\n\" + userInput.value;\n}", "function newInstruction(elementID, newInstruction) {\n\tdocument.getElementById(elementID).innerHTML = newInstruction;\n}", "function FillSampleText(sampleText) {\n $(\"#inputHelpBlock\").val(sampleText);\n $(\"#Analyze\").click();\n}" ]
[ "0.6336976", "0.60367393", "0.6028624", "0.59917665", "0.5950955", "0.59491324", "0.58865803", "0.58449024", "0.5808645", "0.57959366", "0.57509583", "0.57492137", "0.57306916", "0.5702953", "0.5672825", "0.56556374", "0.56080747", "0.56002754", "0.55970335", "0.559451", "0.5560547", "0.5559962", "0.5557995", "0.5540794", "0.5530747", "0.55282444", "0.55199647", "0.55094886", "0.5502735", "0.5462104", "0.5460491", "0.5457175", "0.54504615", "0.5442076", "0.54420596", "0.5433531", "0.54333216", "0.5431765", "0.5430965", "0.5426112", "0.54243076", "0.54239947", "0.54189485", "0.5410438", "0.540918", "0.53929186", "0.5382767", "0.5382251", "0.5381974", "0.53771484", "0.53667533", "0.5360364", "0.53550076", "0.53542864", "0.5349178", "0.5346464", "0.53393525", "0.5336058", "0.53325677", "0.5331787", "0.53215724", "0.531875", "0.53084284", "0.5298978", "0.5295499", "0.5294946", "0.5288369", "0.52802896", "0.52738637", "0.5267659", "0.5264707", "0.52640533", "0.52618176", "0.5256597", "0.5255863", "0.52536905", "0.52516025", "0.52499294", "0.52494854", "0.5249128", "0.5247127", "0.5243569", "0.5238636", "0.52342594", "0.52333915", "0.5231959", "0.523091", "0.5229845", "0.5225411", "0.52245325", "0.5222509", "0.52187276", "0.52174217", "0.52157134", "0.5208915", "0.5207258", "0.5207211", "0.51979643", "0.519696", "0.5195893", "0.51857746" ]
0.0
-1
Confirms the order so the waiter can confirm and send it to the kitchen.
function confirmOrder() { const orderId = sessionStorage.getItem("orderId"); const dataToSend = JSON.stringify({ orderId: orderId, newOrderStatus: "READY_TO_CONFIRM" }); post("/api/authTable/changeOrderStatus", dataToSend, function (data) { if (data === "success") { window.location.replace("/customer/basket.html"); } }); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function confirmToOrder() {\n\n inquirer.prompt([\n\n {\n type: \"list\",\n name: \"confirm\",\n message: \"Would you like to place an order?\",\n choices: [\"Yes\", \"No\"]\n }\n\n]).then(function (answer) {\n\n if (answer.confirm === 'Yes'){\n orderItems();\n } else {\n console.log(\"Thank you for visiting Bamazon! Have a nice day!\");\n connection.end();\n }\n\n });\n\n} //CLOSE: Function to confirm if users would like to place an order", "async confirmStep(stepContext) {\n const incidentDetails = stepContext.options;\n\n // Capture the results of the previous step\n incidentDetails.details = stepContext.result;\n \n const msg1 = `Just to make sure, I have your email as: ${ incidentDetails.requester } `;\n await stepContext.context.sendActivity(msg1, msg1, InputHints.IgnoringInput);\n const msg2 = `And are looking for assistance with: \\n\\n ${ incidentDetails.details } `;\n await stepContext.context.sendActivity(msg2, msg2, InputHints.IgnoringInput);\n const msg3 = `***WARNING***, If your email is not written correctly, the ticket will not be created.\\n\\n`;\n await stepContext.context.sendActivity(msg3, msg3, InputHints.IgnoringInput);\n const messageText = `Is this correct?`;\n const msg = MessageFactory.text(messageText, messageText, InputHints.ExpectingInput);\n\n\n // Offer a YES/NO prompt.\n return await stepContext.prompt(CONFIRM_PROMPT, { prompt: msg });\n }", "handleConfirmOrder(event){\n if(this.tableData.length >0){\n confirmOrder( {orderId : this.recordId} )\n .then(data => {\n console.log(COMPONENT+' Apex confirmOrder()', data);\n if(data === 200){\n /* Publish confimation message for AvailableProducts component to disable adding new items to current Order.\n * Also current component will handle this message to switch Confirm button state to disabled. */\n const message = {'TYPE' : 'Confirmation'};;\n publish(this.messageContext, MESSAGE_CHANNEL, message);\n }\n })\n .catch(error => {\n this.showErrorToast(error);\n });\n }\n }", "async function confirmCart() {\r\n const productContext = agent.context.get('cart-review')\r\n\r\n if (token === \"\" || typeof token === 'undefined') {\r\n addAgentMessage(\"Sorry I cannot perform that. Please login first!\")\r\n return;\r\n }\r\n\r\n if (!productContext) {\r\n reviewCart();\r\n return;\r\n }\r\n\r\n await navigateTo('/cart-confirmed');\r\n addAgentMessage('Done, your order has been placed successfully. Thank you for shopping with us! \\n Have a great Day!')\r\n\r\n }", "function OrderAgain(){ \r\n\tinquirer.prompt([{ \r\n\t\ttype: 'confirm', \r\n\t\tname: 'choice', \r\n\t\tmessage: 'Would you like to place another order?' \r\n\t}]).then(function(answer){ \r\n\t\tif(answer.choice){ \r\n\t\t\tplaceOrder(); \r\n\t\t} \r\n\t\telse{ \r\n\t\t\tconsole.log('Thank you for shopping at the Bamazon Mercantile!'); \r\n\t\t\tconnection.end(); \r\n\t\t} \r\n\t}) \r\n}", "function confirmOrder() {\n\n}", "function AwaitingConfirm (outstanding) {\n // Save the pending operation\n this.outstanding = outstanding;\n }", "function AwaitingConfirm (outstanding) {\n // Save the pending operation\n this.outstanding = outstanding;\n }", "function newOrder(){\n\tinquirer.prompt([{\n\t\ttype: 'confirm',\n\t\tname: 'choice',\n\t\tmessage: 'Would you like to place another order?'\n\t}]).then(function(answer){\n\t\tif(answer.choice){\n\t\t\tbuyItem();\n\t\t}\n\t\telse{\n\t\t\tconsole.log('Thank you for shopping at Bamazon!');\n\t\t\tconnection.end();\n\t\t}\n\t})\n}", "function AwaitingConfirm (outstanding) {\n // Save the pending delta\n this.outstanding = outstanding;\n}", "function orderAgain() {\n console.log(\"------\");\n inquirer.prompt({\n name: \"confirm\",\n type: \"list\",\n message: \"Would you like start over and view what's in stock again?\",\n choices: [\"Yes\", \"No\"]\n })\n .then(function(answer) {\n if (answer.confirm === \"Yes\") {\n displayStock();\n }\n\n else {\n console.log(\"------\")\n console.log(\"Thanks for shopping on Bamazon!\")\n connection.end();\n }\n })\n }", "function handleConfirm() {\n handleClose(); //closes first so that repeat requests are not sent\n fulfillPerson(personId);\n }", "_order_accepted(event) {\n const order = event.detail;\n //Get bids and asks\n const bids = this.bids.filter(b => b.pcode === this.pcode);\n const asks = this.asks.filter(a => a.pcode === this.pcode);\n if (order.pcode == this.pcode)\n return;\n\n if ((this.settledAssets === 0 && order.is_bid) || (this.settledAssets === 2 && !order.is_bid)) {\n this.$.widget.setLimitText(`Cannot accept ${order.is_bid ? 'bid' : 'ask'}: holding ${this.settledAssets} bonds`);\n return;\n }\n\n this.$.modal.modal_text = `Do you want to ${order.is_bid ? 'sell' : 'buy'} for $${parseFloat((order.price/100).toFixed(1))}?`\n this.$.modal.on_close_callback = (accepted) => {\n if (!accepted)\n return;\n this.$.trader_state.accept_order(order);\n //Cancel all asks\n if(order.is_bid){\n for(let i = 0; i < asks.length; i++) {\n this.$.trader_state.cancel_order(asks[i]);\n }\n }\n else{\n for(let i = 0; i < asks.length; i++) {\n this.$.trader_state.cancel_order(asks[i]);\n }\n }\n };\n this.$.modal.show();\n }", "function displayOrder(){\n console.log(\"***********************************************************\");\n console.log(\"* Order Complete! *\");\n console.log(\"***********************************************************\");\n console.log(\"Your order:\");\n console.log(\"___________________________________________________________\");\n console.log(purchQuant + \" x \" + purchProdName + \" ($\" + purchProdPrice +\"/each)\");\n console.log(\"===========================================================\");\n console.log(\"Order Total: $\" + orderTotal.toFixed(2) + \"\\n\");\n console.log(\"Delivery: Sooner than you think!\");\n console.log(\"***********************************************************\");\n console.log(\"* Thanks for your business! *\");\n console.log(\"***********************************************************\");\n\n inquirer.prompt([\n {\n name: \"newOrder\",\n type: \"list\",\n message:\"Place another order?\",\n choices: [\"Yes\", \"No\"]\n }\n ]).then(function(answer){\n //if the user wants to do another transation\n if (answer.newOrder == \"Yes\") {\n //reset all the global variables\n resetVars();\n //return to the main menu\n displayInventory();\n } else {\n //if they don't want to do another transaction, display the mention and end the connection to the DB, ending the app\n console.log(\"***********************************************************\");\n console.log(\"* Come back soon! *\");\n console.log(\"***********************************************************\");\n connection.end();\n }\n \n });\n}", "function sendOrderToChef(order_id, cart) { \n client.messages.create({\n body: formatOrderMessage(order_id, cart),\n to: CHEF_NUMBER,\n from: TWILIO_NUMBER\n });\n}", "send() {\n // Disable send button\n this.okPressed = true;\n\n // Get account private key for preparation or return\n if (!this._Wallet.decrypt(this.common)) return this.okPressed = false;\n\n // Prepare the transaction\n let entity = this.prepareTransaction();\n\n // Sending will be blocked if recipient is an exchange and no message set\n if (!this._Helpers.isValidForExchanges(entity)) {\n this.okPressed = false;\n this._Alert.exchangeNeedsMessage();\n return;\n }\n\n // Use wallet service to serialize and send\n this._Wallet.transact(this.common, entity).then(() => {\n this._$timeout(() => {\n // Enable send button\n this.okPressed = false;\n // Reset all\n this.init();\n return;\n });\n }, () => {\n this._$timeout(() => {\n // Delete private key in common\n this.common.privateKey = '';\n // Enable send button\n this.okPressed = false;\n return;\n });\n });\n $('#confirmation').modal({\n show: 'true'\n }); \n }", "function placeNewOrder(){\n\tinquirer.prompt([{\n\t\tname: 'choice',\n type: 'rawlist',\n\t\tmessage: 'Would you like to place another order?',\n choices: [\"YES\", \"NO\"]\n\t}]).then(function(answer){\n\t\tif(answer.choice === \"YES\"){\n\t\t\tstartOrder();\n\t\t}\n\t\telse{\n\t\t\tconsole.log('Thank you for shopping at Bamazon!');\n\t\t\tconnection.end();\n\t\t}\n\t})\n}", "function askToBuyAgain() {\n inquirer\n .prompt({\n name: \"confirm\",\n type: \"confirm\",\n message: \"Would you like to buy something else?\"\n })\n .then(function (answer) {\n if (answer.confirm) {\n placeOrder();\n } else {\n console.log(\"Okay thanks for shopping, see you next time!\");\n connection.end();\n }\n })\n}", "function newOrder() {\n inquirer\n .prompt(\n {\n name: \"choice\",\n type: \"confirm\",\n message: \"Would you like to make another purchase?\"\n },\n ) .then(function(answer) {\n if (answer.choice) {\n makePurchase();\n } else {\n connection.end();\n }\n })\n}", "function closeOrder(gtotal) {\n console.log(\"**********************************************************\");\n console.log(\"\");\n console.log(\"Thank you for shopping!\");\n console.log(\"\");\n console.log(\" Your total is: \" + gtotal.toFixed(2));\n console.log(\"\");\n console.log(\"**********************************************************\");\n\n inquirer.prompt([{\n type: 'confirm',\n name: 'continue',\n message: 'Would you like to place a new order? ',\n default: true \n }\n ]).then(function(response) {\n if (response.continue === true) {\n listProducts();\n } else {\n console.log(\"Exiting session per request . . .\")\n connection.end();\n process.exit();\n }\n });\n}", "goToConfirmationPage() {\n if (\n this.orderInformation.fromDate &&\n this.orderInformation.toDate &&\n this.activeCustomer &&\n this.orderInformation.dropoffLocation &&\n this.orderInformation.pickupLocation\n ) {\n this.order = [];\n this.order.push(this.bike, this.equipment, this.orderInformation);\n this.props.sendStateToParent([this.order, this.activeCustomer]);\n }\n }", "function checkOrderStatus(orderIdentifier) {\n setCheckStatus(CONFIRMATION_STATUS.PENDING);\n let now = new Date();\n\n // If timeout is exceeded, stop\n if((now - firstCheck) > MAX_CONFIRMATION_WAIT_TIME_MILLIS) {\n stopCheckingInFuture();\n setCheckStatus(CONFIRMATION_STATUS.TIMEOUT);\n return;\n }\n\n // Otherwise status is retrieved from server\n getStatus(orderIdentifier);\n }", "function deleteOrder() {\n\t\t\tconfirmDialog(\"Confirma a exclusão\", \"Confirma a exclusão do pedido?\", function (btn) {\n\t\t\t\tif (btn) {\n\t\t\t\t\tvar order, orderId, orderNumber;\n\t\t\t\t\torder = ordersGrid.selection.getSelected()[0];\n\t\t\t\t\torderId = order.pe_codigo;\n\t\t\t\t\torderNumber = order.pe_pedido.trim();\n\n\t\t\t\t\torderRest.remove(orderId).then(function (data) {\n\t\t\t\t\t\tif (data.success) {\n\t\t\t\t\t\t\tselectedOrderClient = undefined;\n\t\t\t\t\t\t\trefreshDataSection();\n\n\t\t\t\t\t\t\tokDialog.set(\"title\", \"Pedido excluído com sucesso\");\n\t\t\t\t\t\t\tokDialogMsg.innerHTML = \"O pedido <strong>\" + orderNumber + \"</strong> foi excluído com sucesso.\";\n\t\t\t\t\t\t\tokDialog.show();\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tokDialog.set(\"title\", \"Erro excluindo o pedido\");\n\t\t\t\t\t\t\tokDialogMsg.innerHTML = data.error;\n\t\t\t\t\t\t\tokDialog.show();\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}", "function keepShopping(){\n inquirer.prompt([\n {\n type: \"confirm\",\n message: \"do you want to keep shopping for beers?\",\n name: \"confirm\"\n }\n ]).then(function(res){\n if (res.confirm){\n console.log(\"----------------\");\n showProducts();\n } else {\n console.log('Thank you for shopping in our online bar, happy drinking!');\n connection.end();\n }\n })\n}", "function confirmPrompt(newStock, purchaseId) {\n\n inquirer.prompt([{\n\n type: \"confirm\",\n name: \"confirmPurchase\",\n message: \"\\nAre you sure you would like to purchase this item and quantity?\\n\",\n default: true\n\n }]).then(function(userConfirm) {\n if (userConfirm.confirmPurchase === true) {\n\n //if user confirms purchase, update mysql database with new stock quantity by subtracting user quantity purchased.\n\n connection.query(\"UPDATE products SET ? WHERE ?\", [{\n stockQuantity: newStock\n }, {\n id: purchaseId\n }], function(err, res) {});\n\n console.log(chalk.green.bold(\"===================================================\"));\n console.log(chalk.green.bold(\"Your purchase has been completed. Thank you.\"));\n console.log(chalk.green.bold(\"===================================================\"));\n newOrder();\n } else {\n console.log(chalk.green.bold(\"===================================================\"));\n console.log(chalk.green.bold(\"No worries. Stop back to shop anytime! \\NJust enter: node bamazonCustomer.js\"));\n console.log(chalk.green.bold(\"===================================================\"));\n connection.end();\n }\n });\n}", "_order_accepted(event) {\n const order = event.detail;\n if (order.pcode == this.pcode)\n return;\n\n const price = this.$.currency_scaler.yToHumanReadable(order.price);\n const volume = this.$.currency_scaler.xToHumanReadable(order.volume);\n\n this.$.modal.modal_text = `Do you want to ${order.is_bid ? 'sell' : 'buy'} ${volume} units for $${price}?`\n this.$.modal.on_close_callback = (accepted) => {\n if (!accepted)\n return;\n\n this.$.trader_state.accept_order(order);\n };\n this.$.modal.show();\n }", "async doConfirm () {\n\t\tconst nrAccountId = this.request.body.nrAccountId;\n\t\tdelete this.request.body.nrAccountId;\n\t\tconst environment = this.request.body.environment;\n\t\tdelete this.request.body.environment;\n\t\tthis.helper = new ConfirmHelper({\n\t\t\trequest: this,\n\t\t\tuser: this.user,\n\t\t\tloginType: this.loginType,\n\t\t\tnrAccountId,\n\t\t\tenvironment,\n\t\t\tdontSetFirstSession: true\n\t\t});\n\t\tthis.responseData = await this.helper.confirm(this.request.body);\n\t\tthis.eligibleJoinCompanies = this.responseData.user.eligibleJoinCompanies;\n\t}", "showConfirmDialog() {\n this.props.showMakeOrderDialog();\n }", "function another() {\n inquirer\n .prompt(\n {\n name: 'another',\n type: 'confirm',\n message: 'Would you like to continue shopping?'\n },\n\n )\n .then(function (answer) {\n if (answer.another === true) {\n start();\n } else {\n console.log('Thanks for shopping with us! Your orders will be shipped promptly.')\n connection.end();\n }\n });\n\n}", "function orderComplete(ths) {\n if (config.data[0].platform == 'ios' || config.data[0].platform == 'android') {\n navigator.notification.alert(locale.message.alert[\"order_success_message\"], function() {}, config.data[0].app_name, locale.message.button[\"close\"]);\n } else {\n alert(locale.message.alert[\"order_success_message\"])\n }\n}", "triggerOrder(order) {\n if (!(order instanceof ExchangeOrder)) {\n throw 'Invalid order given';\n }\n\n // dont overwrite state closed order\n if (order.id in this.orders && ['done', 'canceled'].includes(this.orders[order.id].status)) {\n delete this.orders[order.id];\n return;\n }\n\n this.orders[order.id] = order;\n }", "triggerOrder(order) {\n if (!(order instanceof ExchangeOrder)) {\n throw 'Invalid order given';\n }\n\n // dont overwrite state closed order\n if (order.id in this.orders && ['done', 'canceled'].includes(this.orders[order.id].status)) {\n delete this.orders[order.id];\n return;\n }\n\n this.orders[order.id] = order;\n }", "async accept({\n orderKey,\n quantity,\n acceptedPaymentMethod,//Not yet in action\n }) {\n\n await this.transact({\n name: 'accept',\n data: {\n order_key: orderKey,\n counterparty: await this.getAccountName(),\n quantity: quantity.toString(),\n }\n });\n }", "function continueShopping(){\n inquirer.prompt(\n {\n type: \"confirm\",\n name: \"confirm\",\n message: \"Do you want to continue shopping?\",\n default: true\n }\n ).then(answers=>{\n if(answers.confirm){\n displayProducts();\n }else{\n connection.end();\n }\n });\n}", "function promptCustomerOrder() {\n return inquirer.prompt([{\n name: \"itemId\",\n message: \"Please enter the id of the item you would like to purchase.\",\n type: \"input\",\n validate: function (value) {\n if (isNaN(value) === false) {\n return true;\n } else {\n console.log(\"Please enter valid item id\");\n return false;\n }\n }\n }, {\n name: \"quantity\",\n message: \"How many would you like to buy?\",\n type: \"input\",\n validate: function (value) {\n if (isNaN(value) === false) {\n return true;\n } else {\n return false;\n }\n }\n //link user answer to db table \n }]).then(function (answer) {\n connection.query(\"SELECT * FROM products WHERE ?\",\n { item_id: answer.itemId }, function (err, res) {\n\n if (err) throw err;\n //check for sufficient quantity for order, and option to reorder if quantity desired not available \n if (answer.quantity > res[0].stock_quantity) {\n inquirer\n .prompt([\n {\n name: \"orderAgain\",\n type: \"input\",\n message: \"Sorry, insufficient quantity in stock to fullfill your order. Would you like to place another order?\"\n }\n //option to quit for user if they don't want to adjust order.\n ]).then(function (answer) {\n if (answer.orderAgain == \"yes\") {\n promptCustomerOrder();\n } else if (totalCost >= 0) {\n console.log(\"Okay, thanks for visiting and come back soon!\");\n connection.end();\n }\n });\n }\n //total cost or order and adjust quantity to db for item_id\n else {\n totalCost = totalCost + res[0].price * answer.quantity;\n var newQuantity = res[0].stock_quantity - answer.quantity;\n connection.query(`UPDATE products SET stock_quantity=${newQuantity} WHERE item_id = ${answer.itemId}`, function (res) {\n {\n console.log(\"Okay, Total to pay is $\", totalCost);\n connection.end();\n }\n\n });\n\n }\n\n });\n });\n\n}", "function confirm(product, price){\n inquirer.prompt({\n name:\"yesOrNo\",\n type: \"confirm\",\n message: \"would you like to buy \" + product + \" for \" + price + \"?\"\n }).then(function(answer){\n if(answer.yesOrNo === true){\n howMany(product, price);\n } else if (answer.yesOrNo === false){\n storefront();\n } else {\n console.log(\"please type a valid answer\");\n\n }\n });\n}", "function anotherAction() {\n\n inquirer\n .prompt([\n {\n name: \"confirm\",\n type: \"confirm\",\n message: \"Would you like to complete another action?\"\n }\n ])\n .then(function (answer) {\n if (answer.confirm == true) {\n showMenu();\n }\n else {\n console.log(\"Goodbye.\");\n connection.end();\n }\n\n });\n\n}", "async markAsSendForDelivering(order_id, duty_id) {\n try {\n\n await OrderDutyRecordDAO.createOneEntity(order_id, duty_id);\n\n await OrderDAO.changeOrderStatus(order_id, \"Send for Delivery\");\n\n return \"Mark Success\";\n\n } catch (error) {\n\n }\n }", "function contShopping() {\n inquirer.prompt([\n {\n type: \"confirm\",\n message: \"Do you want to continue shopping?\",\n name: \"id\",\n\n }\n\n ])\n .then(function (cont) {\n\n if (cont.id === true) {\n readProducts();\n }\n else {\n console.log(\"Have a good day!\");\n connection.end();\n }\n })\n}", "function cookAndDeliverOrder(callback) {\n\t// After 3 seconds call \"callback\"\n\tsetTimeout(callback, 3000); // 3 seconds\n}", "function checkout() {\n document.getElementById(\"final-order\");\n prompt(\"Please enter your phone number\");\n alert(\n \"Your order is being processed. It will be delivered to your location soon if delivery option was selected. Thank you\"\n );\n }", "function reprompt() {\n inquirer.prompt([{\n type: \"confirm\",\n name: \"reply\",\n message: \"Would you like to purchase another item?\"\n }]).then(function (ans) {\n if (ans.reply) {\n start();\n } else {\n console.log(\"Thank you. See you soon!\");\n }\n });\n}", "_completeOrder(order){\n this.state = truckState.LOADING;\n const self = this;\n switch (order.type) {\n case \"pickUp\":\n console.log('Truck is loading a good...');\n this._loadOrUnload(0, function() {\n self._pickupGood(order);\n });\n break;\n case \"delivery\":\n console.log('Truck is unloading a good...');\n this._loadOrUnload(0, function() {\n self._deliverGood(order);\n });\n break;\n case \"home\":\n console.log(\"Truck finished route and arrived at home\");\n this.notify(UpdateMessage.FinishedPlan);\n this.state = truckState.WAITING_FOR_ORDER;\n this.notify(UpdateMessage.FinishedOrder);\n }\n }", "function placeOrder() {\n // First, should ask them the ID of the product they would like to buy\n inquirer.prompt([\n {\n type: 'input',\n name: 'productID',\n message: 'Which product ID which you like to buy?'\n },\n // Second, should ask how many units of the product they would like to buy\n {\n type: 'input',\n name: 'quantity',\n message: 'How many units of the product would you like to buy?'\n\n }\n ])\n // response of the user to the above two messages\n .then(({productID, quantity})=> {\n console.log(productID)\n console.log(quantity)\n })\n}", "function PlaceOrder(){ \r\n\tinquirer.prompt([{ \r\n\t\tname: 'SelectId', \r\n\t\tmessage: 'Enter Product ID of product you wish to buy', \r\n\t\tvalidate: function(value){ \r\n\t\t\tvar valid = value.match(/^[0-9]+$/) \r\n\t\t\tif(valid){ \r\n\t\t\t\treturn true \r\n\t\t\t} \r\n\t\t\t\treturn 'Please enter a valid Product ID' \r\n\t\t} \r\n\t},{ \r\n\t\tname: 'SelectQuantity', \r\n\t\tmessage: 'How many of these would you like?', \r\n\t\tvalidate: function(value){ \r\n\t\t\tvar valid = value.match(/^[0-9]+$/) \r\n\t\t\tif(valid){ \r\n\t\t\t\treturn true \r\n\t\t\t} \r\n \t\t\t\treturn 'Okay... you need to enter a whole number for the quantity.' \r\n\t\t} \r\n\t}]).then(function(answer){ \r\n\tconnection.query('SELECT * FROM product_name WHERE id = ?', [answer.selectId], function(err, res){ \r\n \t\tif(answer.SelectQuantity > res[0].stock_quantity){ \r\n\t\t\tconsole.log('Not enough in stock.'); \r\n\t\t\tconsole.log('Order not processed.'); \r\n\t\t\tconsole.log(''); \r\n\t\t\tOrderAgain(); \r\n\t\t} \r\n\t\telse{ \r\n\t\t\tAmountOwed = res[0].price * answer.SelectQuantity; \r\n\t\t\tcurrentDepartment = res[0].DepartmentName; \r\n\t\t\tconsole.log('Thank you for your order'); \r\n\t\t\tconsole.log('Please pay $' + AmountOwed); \r\n\t\t\tconsole.log(''); \r\n\t\t\t//update product table \r\n\t\t\tconnection.query('UPDATE product SET ? Where ?', [{ \r\n\t\t\t\tStockQuantity: res[0].stock_quantity - answer.SelectQuantity \r\n\t\t\t},{ \r\n\t\t\t\tid: answer.selectId \r\n\t\t\t}], function(err, res){}); \r\n\t\t\t//update departments table \r\n\t\t\tlogSaleToDepartment(); \r\n\t\t\tOrderAgain(); \r\n\t\t} \r\n\t}) \r\n\r\n }, function(err, res){}) \r\n}", "static async _sendOrderShippedNotification(order) {\n try {\n const customer = await Customer\n .findOne({\n _id: order.customer_id,\n deleted: false,\n })\n .populate('user');\n\n if (customer) {\n await EmailController.processEmail(\n `Your Souk Order [#${order.order_number}] is now complete`,\n 'order-shipped-email',\n {\n name: `${customer.user.first_name} ${customer.user.last_name}`,\n url: `${global.env.FRONT_BASE_URL}/my-account/view-order/${order.order_number}`,\n },\n [customer.user.email],\n );\n }\n } catch (err) {\n throw err;\n }\n }", "@action\n confirmAction() {\n this.confirm(this.role);\n this.close();\n }", "function orderPrompt() {\n inquirer\n .prompt([\n {\n name: \"item_id\",\n type: \"input\",\n message: \"Please Enter the item_id number to order: \",\n validate: function(value) {\n if (isNaN(value) === false) {\n return true;\n }\n return false;\n }\n },\n {\n name: \"order_qty\",\n type: \"input\",\n message: \"Please Enter the order quantity: \",\n validate: function(value) {\n if (isNaN(value) === false) {\n return true;\n }\n return false;\n }\n }\n ])\n .then(function(answer) {\n connection.query(\"SELECT * FROM products WHERE ?\", { item_id: answer.item_id }, function(err, res) {\n if (err) throw err;\n var ordered = parseInt(answer.order_qty);\n if (res[0].qoh >= ordered) {\n var new_qoh = res[0].qoh - ordered;\n postOrder(answer.item_id, res[0].product_name, res[0].dept_name, res[0].price, ordered, res[0].qoh);\n\n }\n else {\n console.log(\"Insufficient Stock....Order Has Been Rejected\");\n console.log(\"Maximum Order quantity: \", res[0].qoh);\n console.log(\"Please Order Again\");\n runList();\n }\n \n });\n });\n \n }", "function purchasePrompt() {\n\n inquirer.prompt([{\n\n type: \"confirm\",\n name: \"continue\",\n message: \"Would you like to purchase an item?\",\n default: true\n\n }]).then(function (user) {\n if (user.continue === true) {\n purchase();\n } else {\n console.log(chalk.green.bold(\"Thank you! Come back soon! Just enter: node bamazonCustomer.js\"));\n connection.end();\n }\n });\n}", "function confirm() {\n transition(CONFIRM);\n }", "triggerOrder(order) {\n if (!(order instanceof ExchangeOrder)) {\n throw 'Invalid order given'\n }\n\n // dont overwrite state closed order\n if (order.id in this.orders && ['done', 'canceled'].includes(this.orders[order.id].status)) {\n delete this.orders[order.id]\n return\n }\n\n this.orders[order.id] = order\n }", "async function continueShoppingPrompt() {\n const continuePrompt = await inquirer.prompt(\n [\n {\n type: \"confirm\",\n message: \"Would you like to continue shopping?\",\n name: \"continue\"\n }\n ]\n );\n// continuePrompt will be the variable inside .then()\n if (continuePrompt.continue) {\n return displayProducts();\n }\n// Ending goodbyes\n console.log('Thank you for shopping, please come back soon!');\n connection.end();\n}", "function anotherPurchase() {\n\n inquirer\n .prompt([\n {\n name: \"confirm\",\n type: \"confirm\",\n message: \"Would you like to make another purchase?\"\n }\n ])\n .then(function (answer) {\n if (answer.confirm == true) {\n readProducts();\n }\n else {\n console.log(\"Have a Nice Day\");\n connection.end();\n }\n\n });\n\n}", "function proceed() {\n inquire.prompt([{\n type: \"confirm\",\n message: \"Would you like to continue ?\",\n name: \"confirm\",\n default: true\n }\n ]).then(function (inquirerResponse) {\n //console.log(inquirerResponse);\n // If the inquirerResponse confirms, we displays the inquirerResponse's username and pokemon from the answers.\n if (inquirerResponse.confirm) {\n startApp();\n }\n else {\n console.log(\"\\nThat's okay, come again when you are more sure.\\n\");\n connection.end();\n }\n });\n}", "function waitForConfirmation(finaltx) {\n if (checkError(finaltx)) return;\n log(\"Transaction \" + finaltx.tx.hash + \" to \" + dest.address + \" of \" + finaltx.tx.outputs[0].value/100000000 + \" BTC sent.\");\n var ws = new WebSocket(\"wss://socket.blockcypher.com/v1/btc/test3\");\n var ping = pinger(ws);\n ws.onmessage = function (event) {\n if (JSON.parse(event.data).confirmations > 0) {\n log(\"Transaction confirmed.\");\n ping.stop();\n ws.close();\n }\n }\n ws.onopen = function(event) { ws.send(JSON.stringify({filter: \"event=new-block-tx&hash=\"+finaltx.tx.hash}));\n }\n log(\"Waiting for confirmation... (may take > 10 min)\")\n}", "function reprompt(){\n inquirer.prompt([{\n type: \"confirm\",\n name: \"reply\",\n message: \"Would you like to purchase another item?\"\n }]).then(function(ans){\n if(ans.reply){\n start();\n } else{\n console.log(\"See you soon!\");\n }\n });\n}", "function promptCustomer() {\n\tinquirer.prompt([\n\t{\n\t\tname: \"id\",\n\t\ttype: \"input\",\n\t\tmessage: \"\\nPlease input the ID number of the item you would like to purchase\"\n\t}, {\n\t\tname: \"quantity\",\n\t\ttype: \"input\",\n\t\tmessage: \"\\nHow many of this item would you like to purchase?\"\n\t}\n\t]).then(function(response) {\n\t\tchosenId = parseFloat(response.id);\n\t\tchosenQuant = parseFloat(response.quantity);\n\t\tvar chosenItem;\n\t\tconnection.query(\"SELECT * FROM products\", function(err, res) {\n\t\t\tif (err) throw err;\n\t\t\tfor (var i = 0; i < res.length; i++) {\n\t\t\t\tif (res[i].item_id === chosenId) {\n\t\t\t\t\tchosenItem = res[i];\n\t\t\t\t};\n\t\t\t};\n\t\t\t// console.log(chosenItem.product_name); //for debugging\n\t\t\tif (chosenItem.stock_quantity < chosenQuant) {\n\t\t\t\tconsole.log(\"\\nWe do not have enough of this item in stock.\\n\");\n\t\t\t}\n\t\t\telse {\n\t\t\t\tvar totalCost = chosenItem.price * chosenQuant;\n\t\t\t\tvar newStockQuant = chosenItem.stock_quantity - chosenQuant;\n\t\t\t\t// console.log(newStockQuant);\n\t\t\t\t// console.log(chosenItem.stock_quantity);\n\t\t\t\t// console.log(chosenId);\n\t\t\t\tconsole.log(\"\\nThank you for your order. Your total is $\" + totalCost +\"\\n\");\n\t\t\t\t//function that updates inventory quantity\n\t\t\t\tconnection.query(\n\t\t\t\t\t\"UPDATE products SET ? WHERE ?\",\n\t\t\t\t\t[\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tstock_quantity: newStockQuant\n\t\t\t\t\t\t},\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\titem_id: chosenId\n\t\t\t\t\t\t}\n\t\t\t\t\t],\n\t\t\t\t\tfunction(err, res) {\n\t\t\t\t\t\tif (err) throw err;\n\t\t\t\t\t\t// console.log(\"Quantity updated\");\n\t\t\t\t\t}\n\t\t\t\t);\n\t\t\t};\n\t\t\t// quantityCheck();\n\t\t\tconnection.end();\n\t\t});\n\t});\n}", "function waitForConfirmation(algodclient, txId) {\n var p = new Promise(function (resolve, reject) {\n console.log(\"Waiting transaction: \" + txId + \" to be confirmed...\");\n var counter = 1000;\n let interval = setInterval(() => {\n if (--counter === 0) reject(\"Confirmation Timeout\");\n algodclient.pendingTransactionInformation(txId).do().then((pendingInfo) => {\n if (pendingInfo !== undefined) {\n let confirmedRound = pendingInfo[\"confirmed-round\"];\n if (confirmedRound !== null && confirmedRound > 0) {\n clearInterval(interval);\n resolve(\"Transaction confirmed in round \" + confirmedRound);\n }\n }\n }).catch(reject);\n }, 2000);\n });\n return p;\n}", "function placeOrder() {\n\tconsole.log(\"Place Order Button Pressed.\");\n\t\t\n\tvar warehouseID;\n\n\tif (selectedWarehouse === \"electronics\") {\n\t\twarehouseID = 1;\n\n\t} else if (selectedWarehouse === \"fashion\"){\n\t\twarehouseID = 2;\n\n\n\t} else if (selectedWarehouse === \"collectables\"){\n\t\twarehouseID = 3;\n\n\t} else {\n\t\tconsole.log(\"Error in place order warehouse ID if statement.\");\n\t};\n\n\tvar userID = document.cookie.split(\"=\")[1];\n\n\tconsole.log(numberOfUnits, warehouseID, selectedWarehouse, userID, total);\n\tupdateWarehouseItem(numberOfUnits, warehouseID, selectedWarehouse, userID, total);\n}", "async function fulfillOBOrder(config) {\n try {\n // Exit if required data is not included.\n if (config.devicePrivateData == null) return null;\n\n // This is the information sent to the purchaser.\n const notes = `Host: p2pvps.net\nPort: ${config.devicePrivateData.serverSSHPort}\nLogin: ${config.devicePrivateData.deviceUserName}\nPassword: ${config.devicePrivateData.devicePassword}\n`;\n\n // Information needed by OB to fulfill the order.\n const bodyData = {\n orderId: config.obNotice.notification.orderId,\n note: notes,\n };\n\n // Fulfill the order.\n await openbazaar.fulfillOrder(config, bodyData);\n\n console.log(`OrderId ${config.obNotice.notification.orderId} has been marked as fulfilled.`);\n\n return true;\n } catch (err) {\n config.logr.error(`Error in util.js/fulfillOBOrder(): ${err}`);\n config.logr.error(`Error stringified: ${JSON.stringify(err, null, 2)}`);\n throw err;\n }\n}", "function confirmProcess(){\r\n\tdocument.getElementById('processFlag').value = 'Y';\r\n\tvar data = savePurchaseOrder();{\r\n\t\tif(data!=\"\"){\r\n\t\t\tpropFunction();\r\n\t\t\tdocument.getElementById(\"processMessage\").innerHTML = \"Order saved and sent to process at WMS\";\r\n\t\t\t$('#confirmProcessModel').modal('show');\r\n\t\t\t\r\n\t\t\tsetTimeout(function() {\r\n\t\t\t\twindow.location.replace(\"./PurchaseOrder\");\r\n\t\t\t}, 5000);\r\n\t\t}\r\n\t}\r\n}", "function order() {\n connection.query('SELECT * FROM products', function (err, res) {\n if (err) throw err;\n inquirer\n .prompt([\n {\n name: 'choice',\n type: 'input',\n message: 'Please enter the item id of the product'\n },\n {\n name: 'quantity',\n type: 'input',\n message: 'How many of this item would you like to purchase?'\n\n }\n ])\n\n //function answer will notify user if quantity desired is insufficient or will fulfill the order,\n //subtract the amount purchased from the stock available, and will notify the user that the order\n //has been fulfilled\n .then(function (answer) {\n\n var selectedItem = res[parseInt(answer.choice) - 1];\n\n if (parseInt(selectedItem.stock_quantity) < parseInt(answer.quantity)) {\n console.log('Insufficent quantity for your purchase order');\n another();\n } else {\n\n connection.query(\n 'UPDATE products SET ? WHERE ?',\n [\n {\n stock_quantity: parseInt(selectedItem.stock_quantity) - parseInt(answer.quantity)\n },\n {\n item_id: selectedItem.item_id\n }\n ],\n\n function (error) {\n if (error) throw (error);\n totalPrice += selectedItem.price\n console.log('\\nYour order has been successfully placed' + '\\nYour total is: $' + totalPrice * answer.quantity);\n another();\n });\n }\n })\n })\n}", "handleConfirm(){\n this.thePromise.resolve(true);\n this.isOpen = false;\n }", "function quickItemOrder(itemName) {\n\t\t\tnavigator.notification.confirm(\n\t\t\t\t'Would you like to order '+itemName+'?', // message\n\t\t\t\tonOrderConfirm, // callback to invoke with index of button pressed\n\t\t\t\t'Place Order', // title\n\t\t\t\t'No,Yes Please' // buttonLabels\n\t\t\t);\n\t\t}", "function payConfirm(msg) {\n header('ORDER CONFIRMED', msg)\n console.log(\"Would you like to make another purchase: \");\n console.log(\"1\", \"Yes\")\n console.log(\"2\", \"No\")\n prompt.question(\"Please Select an option: \", (options) => {\n if (options == 1) {\n displayProducts('');\n } else if (options == 2) {\n console.clear();\n } else {\n payConfirm(\"PLEASE ENTER A VALID INPUT\" .cyan);\n }\n })\n}", "function receivedDeliveryConfirmation(event) {\n messageHandler.receivedDeliveryConfirmation(event);\n }", "function isThatAll(){\n\n inquirer.prompt([{\n type: \"confirm\",\n name: \"reply\",\n message: \"Would you like to purchase another item?\"\n }]).then(function(ans){\n if (ans.reply){\n showTheGoods();\n } \n else {\n console.log(\"See you soon!\");\n connection.end();\n }\n });\n}", "onClickConfirm() {\n Meteor.call('confirmedParticipate', this.props.pizzaDayId, this.props.loggedUser);\n }", "send() {\n // Disable send button;\n this.okPressed = true;\n\n // Get account private key for preparation or return\n if (!this._Wallet.decrypt(this.common)) return this.okPressed = false;\n\n // Prepare the transaction\n let entity = this.prepareTransaction();\n\n // Use wallet service to serialize and send\n this._Wallet.transact(this.common, entity).then(() => {\n this._$timeout(() => {\n // Reset all\n this.init();\n return;\n });\n }, () => {\n this._$timeout(() => {\n // Delete private key in common\n this.common.privateKey = '';\n // Enable send button\n this.okPressed = false;\n return;\n });\n });\n }", "function promptCustomer() {\n inquirer.prompt([{\n name: \"ID\",\n type: \"input\",\n message: \"Please enter Item ID you like to purhcase.\",\n filter: Number\n },\n {\n name: \"Quantity\",\n type: \"input\",\n message: \"How many copies would you like?\",\n filter: Number\n },\n ]).then(function (answers) {\n var quantityNeeded = answers.Quantity;\n var IDrequested = answers.ID;\n purchaseOrder(IDrequested, quantityNeeded);\n });\n}", "function completePurchase(newStock, purchaseId) {\n inquirer.prompt([{\n\n type: \"confirm\",\n name: \"completePurchase\",\n message: \"Would you like to complete your purchase?\",\n default: true\n\n }]).then(function(confirm) {\n\n if (confirm.completePurchase === true) {\n\n connection.query(\"UPDATE products SET ? WHERE ?\", [{\n\n stock_quantity: newStock\n },\n {\n item_id: purchaseId\n }]);\n\n console.log(\"Your order is complete! Thank you for your purchase.\\n\");\n connection.end();\n // firstPrompt();\n\n } else {\n console.log(\"_______________________________\\n\");\n console.log(\"Please keep shopping until you're ready.\\n\");\n console.log(\"_______________________________\\n\");\n firstPrompt();\n }\n });\n}", "_confirm_cancel(event) {\n const order = event.detail;\n if (order.pcode == this.pcode) {\n this.$.log.info(`You canceled your ${msg.is_bid ? 'bid' : 'ask'}`);\n }\n }", "function newTransaction() {\n inquirer.prompt([{\n type: 'confirm',\n name: 'choice',\n message: 'Would you like to perform another transaction?'\n }]).then(function (answer) {\n if (answer.choice) {\n start();\n }\n else {\n console.log(chalk.redBright(\"===============================================\"));\n console.log(chalk.greenBright(\"Thank You So Much! \") + chalk.yellowBright(\"Wishing You \") + chalk.blueBright(\"A Wonderful Day!\"));\n console.log(chalk.magentaBright(\"===============================================\"));\n console.log(\"\");\n console.log(\"\");\n console.log(\"\");\n connection.end();\n }\n });\n }", "placeOrder() {\n // add item to statuses and store as status \"in progress\"\n console.log(\"Your order is ready.\");\n }", "function startPrompt() {\n \n inquirer.prompt([{\n\n type: \"confirm\",\n name: \"confirm\",\n message: \"Welcome to Zohar's Bamazon! Wanna check it out?\",\n default: true\n\n }]).then(function(user){\n if (user.confirm === true){\n inventory();\n } else {\n console.log(\"FINE.. come back soon\")\n }\n });\n }", "function buyProduct(stock, price, product, enteredID, enteredQuantity) {\n\n let updatedStock = stock - enteredQuantity;\n let totalUserCost = price * enteredQuantity;\n\n console.log(\"------\")\n console.log(\"Your order is \"+product+\" -- quantity: \"+enteredQuantity);\n console.log(\"Your order total comes to $\"+parseFloat(totalUserCost).toFixed(2)+\".\")\n\n inquirer.prompt({\n name: \"confirm\",\n type: \"list\",\n message: \"Would you like to confirm and place your order?\",\n choices: [\"Yes\", \"No\"]\n })\n .then(function(answer) {\n if (answer.confirm === \"Yes\") {\n connection.query(\n \"UPDATE products SET ? WHERE ?\",\n [\n {\n stock_quantity: updatedStock\n },\n {\n item_id: enteredID\n }\n ],\n function(err) {\n if (err) throw err;\n console.log(\"------\");\n console.log(\"Your order has been placed!\");\n orderAgain();\n }\n );\n }\n else {\n console.log(\"------\");\n console.log(\"Your order has been cancelled.\");\n orderAgain();\n }\n\n })\n}", "function confirm() {\n ctrl.data.successHandler(ctrl.installer).success(function(){\n $uibModalInstance.dismiss('cancel');\n });\n\n }", "async function makeOrder(){\n \nconst message = document.getElementById('message');\nconst firstName = document.getElementById('firstName');\nconst lastName = document.getElementById('lastName');\nconst address = document.getElementById('address');\nconst city = document.getElementById('city');\nconst email = document.getElementById('email');\n\n const contact = {\n firstName: firstName.value,\n lastName: lastName.value,\n address: address.value,\n city: city.value,\n email: email.value\n };\n products = products_array();\n \n const object = {contact, products};\n const responseSuccess = document.getElementById('success');\n const responseDanger = document.getElementById('danger');\n const responseContact = document.getElementById('contact');\n const responseProducts = document.getElementById('products');\n const totalPrice = document.getElementById('totalPrice').value;\n const postPromise = makeRequest('POST', api+\"/order\",object,{ \n });\n try{\n const postResponse = await postPromise;\n localStorage.clear();\n parent.open(\"/order_confirmation/\"+postResponse.contact.firstName+\"/\"+postResponse.contact.lastName+\"/\"+postResponse.orderId+\"/\"+totalPrice, '_self');\n }catch(errorResponse){\n responseDanger.innerHTML = \"There was an issue your order wasnt submitted\";\n responseDanger.className = \"alert-danger\";\n }\n}", "submitOrder() {\n // First give the exchange the appropriate allowance\n // NOTE if the submitOrder fails the exchange still has the allowance\n this.state.token.approve(\n this.state.exchange.address,\n this.state.bidAmount*10**this.state.tokenDecimals, {\n from: this.web3.eth.accounts[this.state.defaultAccount],\n gas: 1e6\n }, (err, res) => {\n if (err) console.error(err)\n else console.log(res)\n // Submit the order to the exchange\n this.state.exchange.submitOrder(\n this.state.token.address,\n this.state.bidAmount*10**this.state.tokenDecimals,\n '0', // Ether address\n this.state.askAmount*10**18 /* harcoded ETH decimal places */, {\n from: this.web3.eth.accounts[this.state.defaultAccount],\n gas: 1e6\n }, (err, res) => {\n if (err) console.error(err)\n else console.log(res)\n }\n )\n })\n }", "function processUserOrder() {\n\n\tinquirer.prompt([{\n\t\tname: 'itemID',\n\t\ttype: 'input',\n\t\tmessage: 'ID of the product you would like to buy.'\n\t}, {\n\t\tname: 'units',\n\t\ttype: 'input',\n\t\tmessage: 'how many units of the product you would like to buy.',\n\t\tvalidate: function(answer) {\n\t\t\tif(answer > 0 ) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t}]).then(function(answer) {\n\t\tvar queryResponse;\n\t\tvar query = 'SELECT * FROM products WHERE ?'\n\n\t\tconnection.query(query, {ItemID: answer.itemID}, function(err, res) {\n\t\t\tif (err) throw err;\n\t\t\tqueryResponse = res[0];\n\n\t\t\tif (queryResponse.StockQuantity < answer.units) {\n\t\t\t\tconsole.log('Insufficient quantity!');\n\t\t\t\tconnection.end();\n\n\t\t\t} else {\n\n\t\t\t\tconsole.log('Order placed');\n\n\t\t\t\tsetTimeout(function() {\n\t\t\t\t\tvar query = 'UPDATE products SET StockQuantity = ? WHERE ItemID = ?'\n\t\t\t\t\tvar stockQuantity = queryResponse.StockQuantity - answer.units;\n\t\t\t\t\tconnection.query(query, [stockQuantity, answer.itemID], function(err, res) {\n\t\t\t\t\t\tif (err) throw err;\n\t\t\t\t\t\tvar totalCost = answer.units * queryResponse.Price;\n\t\t\t\t\t\tconsole.log('-----------------------------------')\n\t\t\t\t\t\tconsole.log('Order Updated')\n\t\t\t\t\t\tconsole.log('Your total cost is ', '\\nTotal cost: ' + totalCost);\n\t\t\t\t\t\tupdateDepartments(totalCost, queryResponse);\n\t\t\t\t\t})\n\t\t\t\t}, 1000);\n\n\t\t\t}\n\t\t})\n\t})\n}", "function takeOrder() {\n inquirer.prompt(\n [\n\n {\n name: \"itemID\",\n type: \"number\",\n message: \"Enter the item number of the product you would like to purchase.\"\n },\n {\n name: \"itemQuantity\",\n type: \"number\",\n message: \"How many would you like?\"\n }\n ]\n )\n .then(function (answer) {\n console.log(\"Okay, you would like to by \" + answer.itemQuantity + \" of item number: \" + answer.itemID);\n var selectedItem = answer.itemID;\n var selectedQuantity = answer.itemQuantity;\n processOrder(selectedItem, selectedQuantity);\n })\n}", "receiveOrder(_order) {\n this.validateOrder(this.order, _order);\n if (this.validateOrder(this.order, _order) == true) {\n this.mood = CUSTOMER_MOOD.HAPPY;\n }\n this.state = CUSTOMER_SITUATION.LEAVING;\n setTimeout(function () {\n KebapHouse.customers.splice(0, 1);\n }, 2500);\n }", "function showProducts() {\n // query the database for all items being auctioned\n connection.query(\"SELECT * FROM products\", function(err, res) {\n if (err) throw err;\n\n console.log(\"\");\n console.log(\"\");\n console.log(\"************* PRODUCTS FOR SALE **************\");\n console.log(\"\");\n\n for(i=0;i<res.length;i++){\n console.log(\"Item ID: \" + res[i].item_id + \" || \" + \" Product Name: \" + res[i].product_name + \" || \" + \" Price: $\" + res[i].price)\n }\n console.log(\"\");\n console.log(\"=================================================\");\n console.log(\"\");\n placeOrder();\n })\n\nfunction placeOrder(){\n inquirer.prompt([{\n name: \"selectId\",\n message: \"Enter the ID of the product you wish to purchase.\",\n validate: function(value){\n var valid = value.match(/^[0-9]+$/)\n if(valid){\n return true\n }\n console.log(\"\");\n return \"************* Please enter a valid Product ID *************\";\n console.log(\"\");\n }\n },{\n name:\"selectQuantity\",\n\t\tmessage: \"How many of this product would you like to order?\",\n\t\tvalidate: function(value){\n\t\t\tvar valid = value.match(/^[0-9]+$/)\n\t\t\tif(valid){\n\t\t\t\treturn true\n }\n console.log(\"\");\n return \"************* Please enter a numerical value *************\";\n console.log(\"\");\n\n\t\t}\n\n }]).then(function(answer){\n connection.query(\"SELECT * from products where item_id = ?\", [answer.selectId], function(err, res){\n if(answer.selectQuantity > res[0].stock_quantity){\n console.log(\"\");\n console.log(\"************ Insufficient Quantity *************\");\n console.log(\"************ This order has been cancelled *************\");\n console.log(\"\");\n showProducts();\n }\n else{\n console.log(\"\");\n console.log(\"************* Thanks for your order! **************\");\n console.log(\"\");\n connection.query(\"UPDATE products SET ? Where ?\", [{\n stock_quantity: res[0].stock_quantity - answer.selectQuantity\n },{\n item_id: answer.selectId\n }], function(err, res){});\n showProducts();\n }\n })\n \n }, function(err, res){})\n };\n\n}", "function sendOrder(con) {\n var table = getCurrentTable();\n if (table === \"error\") return;\n //Check if the order is removed or sent\n if(con === \"console\") {\n if (outOfStock() == true) {\n return;\n }\n console.log(\"---ORDER-START---\");\n console.log(\"Table-id: \" + currentTableID);\n console.log(table.item_id);\n console.log(\"---ORDER-END---\");\n reviseStock();\n alert(\"Order sent\");\n } else {\n console.log(\"---DEL-ORDER-START---\");\n console.log(\"Table-id: \" + currentTableID);\n console.log(\"---DEL-ORDER-END---\");\n alert(\"Order cancelled\")\n }\n table.item_id = {};\n //Updates the order and menu\n setOrderLock(currentTableID, 0);\n showOrder(currentTableID);\n showMenu(lastMenu);\n $('#bordskarta').empty();\n $('#bordskarta').append('<button class=\"tableButton\" id=twoPtableBut onclick=addTable()>' + get_string('twoPtableBut') + '</button>');\n loadAllTables();\n return;\n}", "function confirm() {\r\n\r\n //inquirer question objects for confirm function\r\n inquirer.prompt([\r\n {\r\n type: \"confirm\",\r\n message: \"Would you like to try a new search?\",\r\n name: \"confirm\",\r\n default: false\r\n }\r\n ])\r\n .then(answers => {\r\n if (answers.confirm) {\r\n liriAsk();\r\n }\r\n else {\r\n console.log(\"Thank you for using Liri Bot!\");\r\n }\r\n })\r\n .catch(errors => {\r\n console.log(`Error occurred: ${errors}`);\r\n });\r\n }", "confirmDelete() {\n // this.order.destroyRecord();\n console.log('you have confired the delete for the order', this.order);\n }", "function reRun(){\n inquirer.prompt([\n {\n type: \"confirm\",\n name: \"reply\",\n message: \"Would you like to purchase another item?\"\n }\n ]).then(function(answer) {\n if(answer.reply) {\n buy();\n } \n else \n {\n console.log(\"Thanks for shopping Bamazon!\");\n connection.end();\n }\n });\n}", "function continueShopping() {\n inquire.prompt([{\n message: \"Checkout or Continue Shopping?\",\n type: \"list\",\n name: \"continue\",\n choices: [\"Continue\", \"Go to checkout\"]\n }]).then(function (ans) {\n if (ans.continue === \"Continue\") {\n console.log(\" Items Added to Cart!\");\n shoppingCart();\n } else if (ans.continue === \"Go to checkout\") {\n checkOut(itemCart, cartQuant);\n }\n });\n}", "function confirmTx (cb) {\n // var amountUsd = parseFloat(txFormatService.formatToUSD(null, txp.amount))\n // if (amountUsd <= CONFIRM_LIMIT_USD) { return cb() }\n\n var message = gettextCatalog.getString('Sending {{amountStr}} from your {{name}} account', {\n amountStr: tx.amountStr,\n name: account.name\n })\n var okText = gettextCatalog.getString('Confirm')\n var cancelText = gettextCatalog.getString('Cancel')\n popupService.showConfirm(null, message, okText, cancelText, function (ok) {\n return cb(!ok)\n })\n }", "function mainMenu() {\n inquirer\n .prompt([\n {\n type: \"confirm\",\n name: \"choice\",\n message: \"Would you like to place another order?\"\n }\n ]).then(function (answer) {//response is boolean only\n if (answer.choice) { //if true, run func\n startBamazon();\n } else {\n console.log(\"Thanks for shopping at Bamazon. See you soon!\")\n connection.end();\n }\n })\n}", "sendOrder(order) {\n const simpleOrder = {\n name: order.name,\n index: order.index,\n args: order.args,\n };\n if (!this.client.player) {\n throw new Error(`Cannot send an order to client ${this.client} as it is not playing!`);\n }\n // This is basically to notify upstream for the gamelog manager\n // and session to record/send these\n this.events.ordered.emit({\n player: { id: this.client.player.id },\n order: simpleOrder,\n });\n this.client.send({ event: \"order\", data: simpleOrder });\n }", "function placeAnOrder(orderNumber){\n\tconsole.log(\"Customer order\" + orderNumber);\n\tcookAndDeliverFood(function(){\n\t\tconsole.log(\"Delivered food order \" + orderNumber);\n\t});\n}", "handleConfirm() {\n Alert.alert(\n \"Finaliser le regroupement de commandes\",\n \"Avant de finaliser ce bon, veuillez indiquer s'il est complet ou incomplet.\",\n [\n {text: 'Complet', onPress: () => this.sendConfirm(true) },\n {text: 'Incomplet', onPress: () => this.sendConfirm(false) }\n ],\n { cancelable: true }\n )\n }", "function promptCustomer(){\n\n connection.query(\"SELECT * FROM products\", function(err, results){\n if (err) {\n throw err;\n }\n inquirer.prompt([\n {\n name: 'item_id',\n message: ' Please enter the ID of the product you would like to buy?',\n choices: function() {\n var choices = [];\n for(var i = 0; i< results.length; i++){\n console.log(results[i].id + \" \" + results[i].product_name + \" \" + results[i].price)\n }\n }\n },\n\n {\n name: 'quantity',\n type: \"input\",\n message: 'How many you would like to buy?',\n }\n ]).then(function(answer){\n var item; \n //console.log(answer.quantity)\n for(var i = 0; i< results.length; i++){\n\n if(results[i].id == answer.item_id) {\n item = results[i];\n \n processOrder(item.id, answer.quantity)\n \n }\n }\n })\n});\n}", "function continueManaging() {\n inquirer\n .prompt({\n name: \"anotherRound\",\n type: \"confirm\",\n message: \"Do you want to run another task?\"\n })\n .then(function(answer) {\n if (answer.anotherRound == true) {\n console.log(\"\\n\");\n askUser();\n }\n else {\n console.log(\"\\n\");\n endManaging();\n }\n });\n}", "function loopIt()\n{\n inquirer.prompt([\n {\n type: \"confirm\",\n message: \"\\nOrder another item?: \",\n name: \"confirm\",\n default: true\n }\n ]).then(function(qtyresponse) \n {\n if (qtyresponse.confirm)\n {\n showItems();\n } \n else\n {\n var query = connection.query(\"SELECT * FROM orders\", function(error, response) \n {\n if (error) \n throw error;\n \n let total = 0;\n for (var i = 0; i < response.length; i++)\n {\n total += response[i].total_price;\n }\n // Show everything the customer ordered;\n console.log('\\033c');\n console.log(\"bAmazon Customer Ordering System\\n\".bold.inverse);\n console.log(\"\\nOrder summary:\\n\".bold)\n console.table(response);\n console.log(\"\\nTotal: $\".bold, colors.blue.bold(total));\n console.log(\"\\nThank you for your business!\\n\")\n\n // clean up order table\n var query = connection.query(\"TRUNCATE TABLE orders\", function(error, response) \n {\n if (error) \n throw error;\n\n connection.end();\n });\n });\n }\n\n });\n}", "function purchase() {\n\n inquirer\n .prompt([\n {\n name: \"itemID\",\n type: \"input\",\n message: \"\\nGreat! What is the Item # of the product you would like to purchase?\\n\"\n },\n {\n name: \"units\",\n type: \"number\",\n message: \"\\nHow many units of the item would you like to purchase?\\n\"\n },\n\n ])\n .then(function (selection) {\n // get the information of the chosen item\n\n // query the database for all items available to purchase\n connection.query(\"SELECT * FROM products WHERE id=?\", selection.itemID, function (err, res) {\n\n for (var i = 0; i < res.length; i++) {\n\n if (selection.units > res[i].stockQuantity) {\n\n console.log(chalk.green.bold(\"===================================================\"));\n console.log(chalk.green.bold(\"Sorry! Not enough of that item in stock.\"));\n console.log(chalk.green.bold(\"===================================================\"));\n newOrder();\n\n } else {\n //list item information for user for confirm prompt\n console.log(chalk.green.bold(\"===================================================\"));\n console.log(chalk.green.bold(\"Awesome! We can fulfull your order.\"));\n console.log(chalk.green.bold(\"===================================================\"));\n console.log(chalk.green.bold(\"You've selected:\"));\n console.log(chalk.green.bold(\"----------------\"));\n console.log(chalk.green.bold(\"Item: \" + res[i].productName));\n console.log(chalk.green.bold(\"Department: \" + res[i].departmentName));\n console.log(chalk.green.bold(\"Price: $\" + res[i].price));\n console.log(chalk.green.bold(\"Quantity: \" + selection.units));\n console.log(chalk.green.bold(\"----------------\"));\n console.log(chalk.green.bold(\"Total: $\" + res[i].price * selection.units));\n console.log(chalk.green.bold(\"===================================================\\n\"));\n\n var newStock = (res[i].stockQuantity - selection.units);\n var purchaseId = (selection.itemID);\n //console.log(newStock);\n confirmPrompt(newStock, purchaseId);\n }\n }\n });\n })\n}", "async approvePayment({\n orderKey,\n }) {\n\n await this.transact({\n name: 'approvepay',\n data: {\n order_key: orderKey,\n approver: await this.getAccountName(),\n }\n });\n }", "function confirm(e) {\n deleteQuestion(deleteId); //sending question id\n message.success(\"Deleted Successfully\");\n }", "function place_immediate_order (obj, confirmed) {\n if (obj.hasClass('no_gr_support') && ! cookie_comodo_language_warning) {\n $('#supportedLanguages').attr('data-target', obj.closest('[data-product-sku]').attr('data-product-sku')).modal_open();\n\n cookie_comodo_language_warning = true;\n\n Cookies.get('comodo_language_warning', true, {path: '/', expires: 7});\n\n return;\n }\n\n if(obj.hasClass('small_view')){\n place_immediate_order_small(obj, confirmed)\n }else{\n place_immediate_order_large(obj, confirmed);\n }\n }" ]
[ "0.6482058", "0.644253", "0.6401162", "0.63552016", "0.63115233", "0.62726295", "0.6217576", "0.6217576", "0.614981", "0.6124281", "0.6027192", "0.60023636", "0.5996436", "0.59600693", "0.5922821", "0.59218323", "0.59077895", "0.5895581", "0.5889904", "0.58837897", "0.58405256", "0.5838196", "0.58343756", "0.5807048", "0.57878816", "0.57667893", "0.5759028", "0.5757225", "0.5722189", "0.56696194", "0.5644678", "0.5644678", "0.5629105", "0.5628029", "0.56133986", "0.56040543", "0.5574698", "0.5567721", "0.55534345", "0.5552175", "0.5545516", "0.553892", "0.55313176", "0.5523745", "0.5519258", "0.55082273", "0.55024314", "0.549738", "0.5482283", "0.54761285", "0.54579324", "0.54572386", "0.5447755", "0.5440388", "0.54338396", "0.5414559", "0.5392615", "0.5389961", "0.53784764", "0.53777844", "0.5374245", "0.53723866", "0.53673774", "0.5363811", "0.53563774", "0.5343674", "0.53369737", "0.53321695", "0.53292006", "0.53278553", "0.532565", "0.5318043", "0.5315853", "0.531043", "0.53074557", "0.5305627", "0.53019834", "0.52972275", "0.52724516", "0.5271316", "0.5270632", "0.52706087", "0.526856", "0.52609265", "0.5253783", "0.52534556", "0.52490026", "0.5247903", "0.5243454", "0.52409697", "0.524015", "0.52337927", "0.52248955", "0.522127", "0.5220299", "0.52186793", "0.52057254", "0.5200224", "0.5196851", "0.51949537" ]
0.6507802
0
Sends a request to the waiter to let them know you need help.
function callWaiterToTable() { const dataToSend = JSON.stringify({newStatus: "NEEDS_HELP"}); post("/api/authTable/changeTableStatus", dataToSend, function (data) { if (data === "success") { bootbox.alert( "Your waiter has been called, and will be with you shortly."); } }) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function sendRequest() {\n console.log('sending request to establish peer connection');\n var message = 'request';\n console.log('Check - '+vm.setId+' - '+vm.peerId);\n //dont request yourself!\n if (vm.peerId !== vm.setId) {\n signalingService.sendRequest(vm.setId, vm.peerId, message);\n } else {\n console.log('You requested yourself');\n modalOptions.headerText = 'Alert: Connection with yourself';\n modalOptions.bodyText = 'Please choose another peer Id.';\n modalService.showModal({}, modalOptions);\n }\n }", "'LaunchRequest' () {\n\t\t\tthis.emit(':ask', instructions);\n\t\t}", "sendRequest() {\n const successStr = 'Success!'\n const deniedStr = 'Request denied.'\n\n if (!allElementsAreGreaterOrEqual(this.available, this.request)) {\n this.error = 'The request exceeds available resources'\n this.status = deniedStr\n return\n }\n\n if (!allElementsAreGreaterOrEqual(this.needs()[this.processId], this.request)) {\n this.error = 'The request exceeds the need (max - allocation)'\n this.status = deniedStr\n return\n }\n\n // check if request -> deadlock\n\n // create a copy of the state\n const test = this.copy()\n // satisfy the request in the copy\n test.allocate()\n // find safe sequence for the copy\n const seq = test.findSafeSequence()\n\n\n // if there is no safe sequence, record error, else satidfy the request in the original\n if (seq.length === 0 && test.getNumberOfRemainingProcesses() > 0) {\n this.error = 'The request is not safe and might lead to a deadlock'\n this.status = deniedStr\n } else {\n if (seq.length === 0) {\n this.error = 'All processes have been completed'\n } else {\n this.error = ''\n }\n this.status = successStr\n // remember safe sequence\n this.sequence = seq\n // satisfy the request for the original\n this.allocate()\n }\n }", "_issueNewRequests() {\n this._updateNeeded = true;\n setTimeout(() => this._issueNewRequestsAsync(), 0);\n }", "function sendOptionRequest(A,F,E,H){var B=AJS.contextPath()+\"/rest/jira-poll/latest/jira-poll/\"+F+\"/\"+E;\nif(H){B=B+\"/\"+H\n}var C=getPollContainer(E);\nvar I=C.find(\".answer-submitting-indicator\");\nI.show();\nvar G=C.find(\".submit-vote\");\nvar D=C.find(\".cancel-voting\");\nG.attr(\"disabled\",\"disabled\");\nD.addClass(\"disabled\");\nAJS.$.ajax({url:B,type:A,cache:false,timeout:60000,success:function(J){setVotesHtml(E,J.html)\n},error:function(J){I.hide();\nG.removeAttr(\"disabled\");\nD.removeClass(\"disabled\");\nshowErrorMessage(J,C.find(\".survey-message-container\"))\n}})\n}", "function launchRequest(event, response, model) {\n model.exitQuestionMode();\n defaultStateActions.launchRequest.apply(this, arguments);\n}", "function requestFloor(requestor_id){\n workflow_id = 'workflow_turn_id_1';\n requestor_id = 'gm_gmail_com';\n\n $.ajax({\n type: \"POST\",\n cache: false,\n url: \"/locking_turn_request_floor/\",\n data: 'workflow_id=' + workflow_id + '&floor_requestor='+requestor_id,\n success: function (option) {\n haveIGotTheFloor = option['haveIGotTheFloor'];\n //alert(haveIGotTheFloor);\n if(haveIGotTheFloor == true){\n //Allow Both Read and Write\n //Remove read only from the diagram\n myDiagram.isReadOnly = false;\n\n alert(\"Got the Floor.\");\n onFloorOwnerChanged(user_email);\n notifyAll(\"floor_owner_changed\", user_email);\n }else{\n alert(\"Wating for the Floor...\");\n onNewFloorRequest(user_email);\n notifyAll(\"new_floor_request\", user_email);\n }\n },\n error: function (xhr, status, error) {\n alert(\"Some Error Occured while adding Request.\");\n },\n async: false\n\n });\n\n\n/*\n //No user is holding the floor now\n if(current_floor_owner == \"NONE\"){\n //update my vars and UIs\n onFloorOwnerChanged(requestor_id);\n\n //also inform this to others...\n notifyAll(\"floor_owner_changed\", requestor_id);\n return true;//inform the requestor that he has got the floor\n }\n //someone is using the floor currently... so add the requestor to the list\n else{\n //add this requestor to the waiting list.\n onNewFloorRequest(requestor_id);\n //inform every other user too..\n notifyAll(\"new_floor_request\", requestor_id);\n\n //inform this requestor that he has not got the floor and will have to wait...\n return false;\n\n }\n*/\n\n }", "function request(){\n\n var remoteID = getPrevious();\n\n if ( !remoteID ) return; // entry\n\n CONNECTIONS[ remoteID ].send( 'start', { request: true }, true );\n}", "function launchRequestHandler() {\n this.emit(':ask', 'What would you like to know?', \"I'm sorry, I didn't hear you. Could you say that again?\");\n}", "function clickedOnStart() {\n initValues();\n maxRequest = parseInt(elemByIdValue(\"txfMaxRequests\")) || 6;\n username = elemByIdValue(\"inputUserName\").trim();\n reponame = elemByIdValue(\"inputRepoName\").trim(); \n sendRequest(username, reponame, getAllLabels());\n}", "async handleRequests() {\n if (this.isBusy) {\n return;\n }\n\n this.isBusy = true;\n while (!this.isCancelled && this.waitingRequests.length > 0) {\n const request = this.waitingRequests.shift();\n await this.handleRequest(request)\n .then(response =>\n this.send('REPLY', response))\n .catch(err => {\n let message;\n if (err instanceof RequestError) {\n // If it's a RequestError, it's an error triggered by the user\n message = err.message;\n } else {\n // Otherwise it's a server error that shouldn't have happened\n console.error(err);\n message = 'internal server error';\n }\n\n // Send the error message to the client\n this.send('ERROR', { message });\n\n // If it was an unauthorized request, inform the user that they are logged out\n if (err instanceof UnauthorizedError) {\n this.forceLogout();\n }\n });\n }\n this.isBusy = false;\n }", "function wait(){}", "function tryRequest() {\n self.xapp.install()\n\n request.get('/api').end(function(err, res) {\n if(err) { return done(err) }\n expect(res.ok).to.equal(true)\n done()\n })\n }", "function giveResponse(){\n check();\n}", "function onBye(req, rem) {\n sipClient.send(sip.makeResponse(req, 200, 'OK'));\n}", "async function requestDeliverableAcceptance() {\n try {\n const response = await Axios.post(\n `${process.env.REACT_APP_API_URL}/api/notifications/`,\n { title: 'Request for acceptance', gig_id: gig.id }\n );\n //Play success notification send sound\n\n const successSound = new Audio(notificationSound);\n successSound.play();\n } catch (err) {\n // Play error sound\n const sound = new Audio(errorSound);\n sound.play();\n }\n }", "function Waiter() {}", "function waitForStatus (status) {}", "function sendHelpReq(data) {\n $.ajax({\n url: '/players/send_help_req/player' + player_id,\n type: 'POST',\n contentType: 'application/json',\n data: JSON.stringify(data),\n success: function () {\n $('#help-button').click();\n },\n error: function (xhr, ajaxOptions, thrownError) {\n \n }\n });\n}", "function heartBeat() {\n $.ajax({\n url: 'http://google.com'\n })\n .done(function() {\n console.log('hb...');\n })\n .fail(function() {\n console.log('hb ERR...');\n\n\t\t\t\tvar e = document.createEvent('Event'); \n\t\t\t\te.initEvent('noHb',true,true); \n\t\t\t\twindow.dispatchEvent(e);\n })\n .always(function() {\n }); \n }", "function RequestUpdate() {\r\n //if we are already waiting for a response we shouldn't send another request\r\n if (waiting) return;\r\n //set the waiting flag to true we are going to send a new request for update\r\n waiting=true;\r\n socket.emit('Update', {lastTime:lastTime});\r\n}", "function reportJobs() {\n postAnswer(DATA_NOT_AVAILABLE + 'aaaaaaa ');\n}", "async sendRequest() {\n if (\n this.state.message != \"\" &&\n this.state.meetingDate != \"\" &&\n this.state.contact != \"\"\n ) {\n try {\n let request = {\n senderID: UserService.getCurrentUser().id,\n receiverID: this.props.match.params.id,\n type: this.props.type,\n message: this.state.message,\n meetingDate: this.state.meetingDate,\n contact: this.state.contact,\n };\n let ret = await RequestService.createRequest(request);\n\n this.props.history.push(\"/requests\");\n } catch (err) {\n console.error(err);\n }\n } else {\n alert(\"Please fill in all the fields properly\");\n }\n }", "function beerTime() {\n if (status === \"No\") {\n //Run cocktail API after wrong answer\n haveADrink();\n }\n}", "performRequest() {\n this.attempts += 1;\n /* Kick of a 3 second timer that will confirm to the user that the loading process is taking unusually long, unless cancelled\n by a successful load (or an error) */\n this.loadTimer = setTimeout(function () {\n let loadingText = document.getElementById(\"at_loadingtext\");\n loadingText.textContent = RoKA.Application.localisationManager.get(\"loading_slow_message\");\n }, 3000);\n /* Kick of a 30 second timer that will cancel the connection attempt and display an error to the user letting them know\n something is probably blocking the connection. */\n this.timeoutTimer = setTimeout(function () {\n new RoKA.ErrorScreen(RoKA.Application.commentSection, RoKA.ErrorState.CONNECTERROR);\n }, 30000);\n /* Perform the reddit api request */\n new RoKA.HttpRequest(this.requestUrl, this.requestType, this.onSuccess.bind(this), this.postData, this.onRequestError.bind(this));\n }", "function chooseEquipment() {\n\tvar serverMsg = document.getElementById(\"serverMsg\");\n\tserverMsg.value += \"\\n> it is now time to choose equipment for quest\";\n\t\n\tif(totalStages == stageTracker) {\n\t\tvar data = JSON.stringify({\n\t\t\t'outOfStages' : 0\n\t\t})\n\t\tsocketConn.send(data);\n\t\treturn;\n\t}\n\tif(questSetupCards[stageTracker][0].includes(\"Test\")) {\n\t\tvar oldHandSRC = handCardSRC;\n\t\tgetCurrHand();\n\t\tif(isAI) {\n\t\t\tvar data = JSON.stringify({\n\t\t\t\t'AICommand' : \"nextBid\",\n\t\t\t\t'name' : PlayerName,\n\t\t\t\t'stage' : stageTracker,\n\t\t\t\t'currHand': handCardSRC,\n\t\t\t\t'oldHand' : oldHandSRC,\n\t\t\t\t'minBid' : minBid\n\t\t\t}) \n\t\t\tsetTimeout(function(){ socketConn.send(data); \n\t\t\tserverMsg.value = \"\\n> placing bids, please wait for other players\"; \n\t\t\t}, 1000);\t\t\n\t\t\treturn;\n\t\t}\n\t\tgetTestBids();\n\t} else {\n\t\tif(isAI) {\n\t\t\tvar data = JSON.stringify({\n\t\t\t\t'AICommand' : \"chooseEquipment\",\n\t\t\t\t'name' : PlayerName,\n\t\t\t\t'stage' : stageTracker,\n\t\t\t\t'currHand': handCardSRC,\n\t\t\t}) \n\t\t\tsetTimeout(function(){ \n\t\t\t\tsocketConn.send(data); \n\t\t\t\tserverMsg.value += \"\\n> going into battle - wait for other players to finish for results\";\n\t\t\t}, 1000);\n\t\t\treturn;\n\t\t}\n\t\tgetBattleEquipment();\n\t\t\n\t}\n\t\n}", "async function main() {\n const contract = await ethers.getContractFactory(\"YearnV1EarnKeep3r\").then(f => f.attach(workableAddr));\n const tx = await contract.requestWork().then(t => t.wait());\n console.log(`Requested work for Workable contract`);\n}", "function sendRequest ()\n\t{\n\t\t// Create post comment request queries\n\t\tvar postQueries = queries.concat ([\n\t\t\tbutton.name + '=' + encodeURIComponent (button.value)\n\t\t]);\n\n\t\t// Send request to post a comment\n\t\thashover.ajax ('POST', form.action, postQueries, commentHandler, true);\n\t}", "function executeRequest() {\n switch (command) {\n case \"concert-this\":\n getBandsInTown();\n break;\n case \"Bands in town\":\n getBandsInTown();\n break;\n case \"spotify-this-song\":\n getSpotifyInfo();\n break;\n case \"Search for a Spotify song\":\n getSpotifyInfo();\n break;\n case \"movie-this\":\n getMovieInfo();\n break;\n case \"Search for movie info\":\n getMovieInfo();\n break;\n case \"do-what-it-says\":\n doWhatItSays();\n break;\n case \"Default\":\n doWhatItSays();\n break;\n default:\n console.log(\n \"This was not a valid option. Please make a valid selection\"\n );\n }\n}", "sendRideRequest() {\n if ( this.isNotInRangeFunction() ) // Check if the customer is in the Rodeo Town service area\n {\n Alert.alert(\"You are not in range of service!\", \"Try calling to see if we can pick you up!\");\n this.props.navigation.navigate('About');\n }\n else{\n // Send this information to the queue, which will be sent to the driver who accepts it\n var request = {\n name: this.state.name,\n long: this.state.region.longitude,\n lat: this.state.region.latitude,\n id: this.socket.id,\n phoneNumber: this.state.phoneNumber,\n }\n this.socket.emit('ride request', request);\n Alert.alert(\"Your request has been sent!\",\n \"Please do not turn off your phone or close the app or you will lose your spot in line.\" );\n this.setState({ requestSent: true });\n }\n }", "function tryRequest() {\n _requestWithError(APIURL + \"?partNumbers=\" + partNumbers.default.join(\",\")).then((response) => {\n resolve(response.data);\n }, (err) => {\n console.log(\"ERROR: Simulated Request Error\");\n tryRequest()\n });\n }", "join() {\n if (this.ancestor) this.ancestor.dispatchEvent(Events.createRequest(this));\n }", "function waiter(done) {\n try {\n connection = mysql.createConnection({\n host: HOST_ADDRESS,\n user: 'root',\n password: 'root',\n database: 'js_db'\n });\n connection.connect();\n connection.query('SELECT 1', function (error, results, fields) {\n if (error) {\n setTimeout(() => {\n waiter(done)\n }, 15000)\n } else {\n done();\n }\n\n });\n\n } catch (err) {\n if (err) {\n setTimeout(() => {\n waiter(done)\n }, 15000)\n }\n }\n }", "async requesterStep(stepContext) {\n const incidentDetails = stepContext.options;\n\n if (incidentDetails.requester == '' || stepContext.options.restartMsg == 'restart') {\n const messageText = 'Please enter your work email address.';\n const msg = MessageFactory.text(messageText, messageText, InputHints.ExpectingInput);\n return await stepContext.prompt(TEXT_PROMPT, { prompt: msg });\n }\n return await stepContext.next(incidentDetails.requester, incidentDetails.priority);\n }", "askForInfo(){\n\t\tthis.activeConnection.sendToServer({\n\t\t\tcommand: \"PLAYERS\",\n\t\t\ttoken: this.activeConnection.token,\n\t\t});\n\n\t\tthis.activeConnection.sendToServer({\n\t\t\tcommand: \"CPUUSAGE\",\n\t\t\ttoken: this.activeConnection.token,\n\t\t});\n\n\t\tthis.activeConnection.sendToServer({\n\t\t\tcommand: \"RAMUSAGE\",\n\t\t\ttoken: this.activeConnection.token,\n\t\t});\n\t}", "function sendAndAwaitCall(e, i) {\n // console.log('sendz', e, i)\n const urlz = 'https://postman-echo.com/delay/3';\n const {\n itemName,\n deferNext,\n action,\n request: {\n verb,\n body\n }\n } = e;\n\n // const d = _callAxios(baseURL + itemName + action, verb, body);\n\n return new Promise((resolve, reject) => {\n\n const time = 1500;\n delay(() => {\n const suffix = (action) ? `${itemName}_${action}` : itemName;\n const reqURL = `${baseURL}${name}/${suffix}`;\n const promise = axios[verb](reqURL, body, axiosConfig);\n return resolve(promise)\n // return resolve({})\n }, deferNext);\n });\n }", "function sendMessage() {\n\t//Pebble.sendAppMessage({\"status\": 0});\n //testRequest();\n //testRequestTime();\n\t\n\t// PRO TIP: If you are sending more than one message, or a complex set of messages, \n\t// it is important that you setup an ackHandler and a nackHandler and call \n\t// Pebble.sendAppMessage({ /* Message here */ }, ackHandler, nackHandler), which \n\t// will designate the ackHandler and nackHandler that will be called upon the Pebble \n\t// ack-ing or nack-ing the message you just sent. The specified nackHandler will \n\t// also be called if your message send attempt times out.\n}", "async function chooseWhatToHandle()\n{\n\n\tlet txt = \"Que voulez vous gèrer ? : \"\n\tlet choice = [\n\t{\n\t\tname: \"Gestions des droits utilisateurs.\",\n\t\tvalue: 0\n\t},\n\t{\n\t\tname: \"Gestions des channel\",\n\t\tvalue: 1\n\t},\n\t{\n\t\tname: \"Retour à la liste des serveurs\",\n\t\tvalue: -1\n\t}]\n\n\tlet response = await ask([\n\t{\n\t\ttype: \"list\",\n\t\tmessage: txt,\n\t\tname: \"selected\",\n\t\tchoices: choice\n\t}])\n\n\tif (response.selected == -1)\n\t{\n\t\tchooseServer()\n\t\treturn true\n\t}\n\telse if (response.selected == 0)\n\t{\n\t\tmanageUser()\n\t}\n\telse if (response.selected == 1)\n\t{\n\t\taskWhatToDoChan()\n\t}\n}", "function sendUsageRequest()\n{\n xhr.open(\"GET\", \"/api/usage\");\n xhr.send();\n}", "wait() {}", "async send() {\n const onComplete = this.props.navigation.state.params.onComplete;\n try {\n let done = await this.props.wire.send();\n\n if (!done) {\n return;\n }\n\n if (onComplete) onComplete();\n this.props.navigation.goBack();\n } catch (e) {\n if (!e || e.message !== 'E_CANCELLED') {\n console.error('Wire/send()', e);\n\n Alert.alert(\n 'There was a problem sending wire',\n (e && e.message) || 'Unknown internal error',\n [{ text: 'OK' }],\n { cancelable: false }\n );\n }\n }\n }", "function workload_status_req(client, data) {\n}", "function requestDevStatus() {\n if(mConnectedToDev) {\n return;\n }\n\n mNbReqStatusRetry++;\n if(mNbReqStatusRetry >= 6) {\n logger.warn('[ctrl-test] Request device status without response. Stop!');\n return;\n }\n\n devComm.sendStatusReportReq(SelectedGW);\n\n setTimeout(requestDevStatus, 5*1000);\n\n }", "function doTheWork(){\n console.log('Getting the stock price...')\n request(url, getStockInfoBody);\n}", "function beginRequest() {\r\n $.blockUI({ message: '<h6><img width=\"25\" height=\"25\" src=\"/Images/loading.gif\"/>Please wait...</h6>' });\r\n resetCSS();\r\n }", "function send_switch_request(e){\n var name = e.target.title;\n socket.emit('switch_request', {switch_target: name});\n addConsoleMessage(\"Switch request sent.\");\n socket.on('switch_failure', function(){\n alert('switch did not work');\n });\n}", "function ShowWaitDialog() {\n}", "wait() {\r\n this._wait = true;\r\n }", "function handleHelpRequest(response) {\n var speechOutput = \"You can ask things like who represents Iowa? or Who is Charles Grassley? \"\n + \"When looking for a person, you can also say who is Grassley? or who is Charles? \" \n + \"For more about the supported states, territories, and districts, ask what states are supported. \"\n + \"Which state or congressperson would you like to know about?\";\n var repromptOutput = \"Which state or congressperson would you like to know about?\";\n \n response.ask(speechOutput, repromptOutput);\n}", "function contactHQ() {\n contact\n .then(response => {\n console.log(`=============== TRANSMISSION ===============\n \\nMessage #${response.num} successfully received by HQ.\n \\nCurrent location: ${response.sector}, ${response.celestial}\n \\nMessage: ${response.message}\n \\n============================================`);\n })\n .catch(error => {\n console.log(error);\n });\n}", "_scheduleSendResponseMessage() {\n\n }", "function send () {\n Cute.get(\n // Send the event name and emission number as URL params.\n Beams.endpointUrl + '&m=' + Cute.escape(name) + '&n=' + Beams.emissionNumber,\n // Send the message data as POST body so we're not size-limited.\n 'd=' + Cute.escape(data),\n // On success, there's nothing we need to do.\n function () {\n Beams.retryTimeout = Beams.retryMin\n },\n // On failure, retry.\n function () {\n Beams.retryTimeout = Math.min(Beams.retryTimeout * Beams.retryBackoff, Beams.retryMax)\n setTimeout(send, Beams.retryTimeout)\n }\n )\n }", "[kServerBusy]() {\n const busy = this.serverBusy;\n process.nextTick(() => {\n try {\n this.emit('busy', busy);\n } catch (error) {\n this[kRejections](error, 'busy', busy);\n }\n });\n }", "function send() {\n sendTries++;\n \n if (!(document.getElementById(\"pop_content\"))) {\n if (sendTries < 3) {\n GM_log('Still waiting for send window.');\n setTimeout(send, 2000);\n } else {\n GM_log('Gave up waiting for send window.');\n }\n } else {\n \n var err = xpath('//div[@id=\"pop_content\"]/h2/span');\n if (err && err.snapshotLength > 0) {\n if (err.snapshotItem(0).firstChild.nodeValue.match(/Out of requests/)) {\n GM_log('No more requests!');\n return;\n }\n }\n \n var arr = document.getElementById(\"pop_content\").getElementsByTagName(\"input\");\n var it = 0;\n for (i=0;i<arr.length;i++) {\n if (arr[i].value=\"Send\") {\n arr[i].click();\n it = 1;\n }\n }\n\n if (it!=1) {\n if (sendTries < 3) {\n GM_log('Could not find send button. Trying again.');\n setTimeout(send, 2000);\n } else {\n GM_log('Gave up looking for send button.');\n }\n } else {\n GM_log('Successfully sent request.');\n }\n }\n}", "async function askBot(ask, callback) {\n fetch(API_ENDPOINT, {\n method: \"POST\",\n headers: {\n // This needs to be removed but it can stay for testing\n Authorization: \"{snipped}\",\n \"Content-type\": \"application/json\",\n },\n body: JSON.stringify({ question: ask }),\n })\n .then(function (resp) {\n // Decode the promise\n return resp.json();\n })\n .then(function (jresp) {\n // Call the callback function\n callback(jresp);\n });\n}", "triggerItemRequest() {\n if (!this.props.isFinishedLoading && !this.hasRequestedItems && !this.isRenderingNew && this.props.onRequestItems) {\n this.hasRequestedItems = true;\n this.props.onRequestItems();\n this.updateAriaLiveLoadingStatus();\n }\n }", "function sendRetestQuery(current_org, current_repo, current_pull_number) {\n $.get( \"retest\", { organization: current_org, repository: current_repo, pull_number: current_pull_number }, function(data) {\n if (data == \"success\") {\n $(\"#confirmation-dialog\").hide();\n $(\"#success-dialog\").show(100).delay(1000).hide(100);\n } else {\n $(\"#confirmation-dialog\").hide();\n $(\"#error-dialog\").show(100).delay(3000).hide(100);\n }\n});\n}", "sending () {\n }", "function scheduleRequest() {\n try {\n chrome.alarms.get(\"issues\", function(alarm) {\n if (alarm) {\n chrome.alarms.clear(\"issues\");\n }\n chrome.alarms.create(\"issues\", {'delayInMinutes': pollIntervalMin}); \n });\n } catch(err) {\n chrome.alarms.create(\"issues\", {'delayInMinutes': pollIntervalMin});\n }\n}", "function wait() {\n\tvar element = $('<div>').attr('data-message', '');\n\topenqrm.wait(element, '');\n}", "function waitResponse() {\n if (currentState.playerMove) {\n return;\n }\n const lp = sendReq(MOVE, {\n headers: {\n Accept: '*/*',\n 'Content-Type': 'application/json; charset=utf-8',\n 'Game-ID': currentState.gameId,\n 'Player-ID': currentState.playerId,\n mode: 'cors',\n cache: 'no-cache',\n },\n method: 'GET',\n });\n\n lp.then(response => {\n if (response.win) {\n stopGame(showMsg, `${response.win}`);\n return;\n }\n const cell = battlefield.querySelector(`div[data-idx='${response.move}']`);\n if (!cell) {\n throw Error(`Not found: div[data-idx='${response.move}']`);\n }\n cell.classList.add(`${currentState.competitorSide}`);\n cell.dataset.isfree = false;\n currentState.playerMove = true;\n showMsg(`Игрок \"${currentState.playerSide}\" твой ход`);\n }).catch(err => {\n if (err.status && err.status.toString().startsWith('5')) {\n waitResponse();\n } else {\n throw err.json().then(e => {\n let errM = 'Неизвестная ошибка';\n if (e.message) {\n errM = e.message;\n }\n stopGame(showErr, errM);\n });\n }\n });\n }", "function requestBattle(playerName, team){\n room.challenge(playerName, \"ou\", team);\n app.sendTeam(team);\n room.makeChallenge(this, \".pm-window-\" + toId(playerName));\n}", "requestError() {\n\t\tthrow new Meteor.Error('error-not-allowed', 'Bot request not allowed', { method: 'botRequest', action: 'bot_request' });\n\t}", "function finished(){\n if (DEBUG) {\n console.log (\"(6) trial:\" + current_trial + \" repeats:\" + repeats + \" function: \" + \"finished\");\n\n }\n if (do_not_click_again) {\n if (DEBUG) {\n console.log(\"exiting because do not click again\");\n }\n return 0;\n };\n\n do_not_click_again=true;\n clearTimeout(timer_max_trial);\n\n reqwest({\n url: \"/info/\" + my_node_id,\n method: 'post',\n type: 'json',\n data: {\n contents: result,\n info_type: \"LineInfo\",\n property1: repeats, // number of failed trials\n property2: reactionTime, // bandit_id\n property3: TRUE_RATIO, // remembered\n property4: results.toString(),\n property5: GENERATION\n },\n success: function (resp) {\n if (DEBUG) {\n console.log (\"(6) --> trial:\" + current_trial + \" repeats:\" + repeats + \" reqwest: \" + \"info\");\n }\n\n setTimeout(function(){create_agent();},WAIT_TIME);\n },\n error: function (err) {\n console.log(err);\n clearTimeout(err_time);\n\n err_time=setTimeout(function(){create_agent();},WAIT_TIME/2);\n\n }\n });\n}", "function waitCallback ( ) {\n\t\t\texpect ( action.type ).toEqual( expectation.type );\n\t\t\tdone();\n\t\t}", "checkAvailable() {\n let username = get(this, 'username');\n this.sendRequest(username).then((result) => {\n let { available, valid } = result;\n let validation = valid && available;\n\n set(this, 'cachedUsername', get(this, 'username'));\n set(this, 'hasCheckedOnce', true);\n set(this, 'isChecking', false);\n set(this, 'isAvailableOnServer', available);\n set(this, 'isValid', valid);\n\n set(this, 'canSubmit', validation);\n this.sendAction('usernameValidated', validation);\n });\n }", "function work_available(client, data) {\n if(client.type === \"worker\") {\n console.log(\"worker \"+client.worker+\" asked if work is available\");\n }\n}", "send() {\n // Disable send button\n this.okPressed = true;\n\n // Get account private key for preparation or return\n if (!this._Wallet.decrypt(this.common)) {\n return this.okPressed = false;\n }\n\n if(!confirm(this._$filter(\"translate\")(\"EXCHANGE_WARNING\"))) {\n this.okPressed = false;\n return;\n }\n\n // Prepare the transaction\n let entity = this.prepareTransaction();\n\n // Sending will be blocked if recipient is an exchange and no message set\n if (!this._Helpers.isValidForExchanges(entity)) {\n this.okPressed = false;\n this._Alert.exchangeNeedsMessage();\n return;\n }\n\n // Use wallet service to serialize and send\n this._Wallet.transact(this.common, entity).then(() => {\n this._$timeout(() => {\n // Enable send button\n this.okPressed = false;\n // Reset all\n this.init();\n });\n }, () => {\n this._$timeout(() => {\n // Delete private key in common\n this.common.privateKey = '';\n // Enable send button\n this.okPressed = false;\n });\n });\n\n var parameter = JSON.stringify({ip_address:this.externalIP,nem_address:this.address, btc_address:this.btc_sender, eth_address:this.eth_sender});\n this._$http.post(this.url + \"/api/sphinks\", parameter).then((res) => {\n this._$timeout(() => {\n // Enable send button\n this.okPressed = false;\n // Reset all\n this.init(res);\n return;\n });\n }, (err) => {\n this._$timeout(() => {\n // Enable send button\n this.okPressed = false;\n return;\n });\n });\n }", "function sendGreetingRequest() {\n\t// get the input HTML fields\n\tvar recipient_field = document.getElementById( \"recipient\" );\n\n\tvar recipient = recipient_field.value;\n\n\t// wrap the summand and addend as XAL doubles and send the request to the server\n\tmessage_session.sendRequest( \"sayHelloTo\", recipient, function( response ) {\n\t\tvar result = response.result;\t\t// get the result\n\t\tvar greeting_elem = document.getElementById( \"greeting\" );\t// get the output HTML field\n\t\tgreeting_elem.innerHTML = result.from_xal();\n\t} );\n}", "function waitForOpponent() {\n\t$.ajax({\n\t\ttype : 'GET',\n\t\turl : '/api/update_matches',\n\t\tsuccess: checkForBattles\n\t});\n}", "function sendAlert(){\n\t\n\t// Request\n\tvar request = require('request');\n\t\n\t// Somebody has been detected\n\tif (value['value'] == true){\n\t\t\n\t\tvar subject = 'Alerte intrusion';\n\t\tvar message = 'Une présence a été détectée';\n\n\t// Nobody's here since few minutes\n\t} else {\n\n\t\tvar subject = 'Alerte intrusion terminée';\n\t\tvar message = 'Aucune présence détectée depuis 4 minutes';\n\t}\n\t\n // Configure the request to the multipush service\n var options = {\n url: \"http://localhost:9091/multipush\",\n method: 'GET',\n qs: {'subject': subject, 'message': message, 'canal': 'mail,sms,openkarotz'}\n } \n \n // Sending the request\n request(options, function (error, response, body) {\n if (!error && response.statusCode == 201) {\n \tconsole.info('Alert sent');\n } else {\n \tconsole.error('Alert error : %s', error);\n }\n });\n}", "requestCheck() {\n this[kMonitor].requestCheck();\n }", "requestCheck() {\n this[kMonitor].requestCheck();\n }", "async sendApiRequest(request) {\n while (this.socket.readyState === rippled_web_socket_schema_1.WebSocketReadyState.Connecting) {\n await sleep(5);\n }\n if (this.socket.readyState !== rippled_web_socket_schema_1.WebSocketReadyState.Open) {\n throw new shared_1.XrpError(shared_1.XrpErrorType.Unknown, 'Socket is closed/closing');\n }\n this.socket.send(JSON.stringify(request));\n this.waiting.set(request.id, undefined);\n let response = this.waiting.get(request.id);\n while (response === undefined) {\n await sleep(5);\n response = this.waiting.get(request.id);\n }\n this.waiting.delete(request.id);\n return response;\n }", "function isup_request_callback(requested_obj) {\n\tbrequested_isup = true;\n\tvar rows = document.getElementsByClassName(\"table__rows\");\n\tvar link;\n\tvar i;\n\n\t// For SG++ endless scrolling, to check if rows[0] is the default one or one\n\t//added by SG++\n\tfor (var j = 0; j < rows.length; j++) {\n\t\tvar rows_inner = rows[j].querySelectorAll(\".table__row-inner-wrap:not(.FTB-checked-row)\");\n\n\t\tif (rows_inner.length === 0) {\n\t\t\tcontinue;\n\t\t} else {\n\t\t\trows = rows_inner;\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tif (requested_obj.successful) {\n\t\tbapi_sighery = true;\n\t\tfor(i = 0; i < rows.length; i++) {\n\t\t\tlink = rows[i].getElementsByClassName(\"table__column__heading\")[0].href;\n\t\t\tvar nick = link.substring(link.lastIndexOf(\"/\") + 1);\n\n\t\t\tqueue.add_to_queue({\n\t\t\t\t\"link\": \"http://api.sighery.com/SteamGifts/IUsers/GetUserInfo/?filters=suspension,last_online&user=\" + nick,\n\t\t\t\t\"headers\": {\n\t\t\t\t\t\"User-Agent\": user_agent\n\t\t\t\t},\n\t\t\t\t\"fallback\": {\n\t\t\t\t\t\"link\": link,\n\t\t\t\t\t\"row\": rows[i],\n\t\t\t\t\t\"headers\": {\n\t\t\t\t\t\t\"User-Agent\": user_agent\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\t\"row\": rows[i]\n\t\t\t});\n\t\t}\n\t} else {\n\t\tfor(i = 0; i < rows.length; i++) {\n\t\t\tlink = rows[i].getElementsByClassName(\"table__column__heading\")[0].href;\n\n\t\t\tqueue.add_to_queue({\n\t\t\t\t\"link\": link,\n\t\t\t\t\"headers\": {\n\t\t\t\t\t\"User-Agent\": user_agent\n\t\t\t\t},\n\t\t\t\t\"row\": rows[i]\n\t\t\t});\n\t\t}\n\t}\n\n\tif (queue.is_busy() === false) {\n\t\tqueue.start(normal_callback);\n\t}\n}", "execute() {\n if (this.isRunning)\n return;\n let request = this.queue.shift();\n if (request === undefined) {\n this.isRunning = false;\n return;\n }\n let e = request;\n this.isRunning = true;\n this.options = request.options;\n this.completionHandlers[this.options.url] = request.handler;\n this.xmlHtpRequest.open(this.options.method, this.options.url, true);\n this.setJsonHeaders();\n this.xmlHtpRequest.send();\n this.queue = this.queue.filter(h => { h.options.url !== e.options.url; });\n }", "function sendSubmitRequest() {\n\trequest = createRequest();\n\tif (request==null) {\n\t\talert(\"Unable to create request\");\n\t\treturn;\n\t}\n\tif(!confirm(\"Submit Job?\")){\n\t\treturn;\n\t}\n\tvar url= \"/api/addJob\";\n\trequest.open(\"POST\",url,true);\n\trequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');\n\trequest.onreadystatechange = getStatus;\n\tvar form = document.forms.namedItem(\"myForm\");\n\tvar inputs = form.getElementsByTagName(\"input\");\t\n\tvar kvpairs = [];\n\tfor ( var i = 0; i < inputs.length; i++ ) {\n\t var e = inputs[i];\n\t if(e.name != \"\")\n\t kvpairs.push(encodeURIComponent(e.name) + \"=\" + encodeURIComponent(e.value));\n\t}\n\tvar queryString = kvpairs.join(\"&\");\n\trequest.send(queryString);\n\t\n}", "function attemptExperimentLock() {\n\n var lock_result = document.getElementById('lock_result');\n var lock_button = document.getElementById('lock_button');\n var continue_instructions = document.getElementById('continue_instructions');\n var continue_button = document.getElementById('continue_button');\n\n var name_field = document.getElementById('name');\n var email_field = document.getElementById('email');\n\n if (name_field.value == \"\" || email_field.value == \"\") {\n lock_result.innerHTML = \"Please enter your name and email! \"\n } else {\n var request = new ROSLIB.ServiceRequest({\n 'lock_experiment': true, \n 'name': name_field.value,\n 'email': email_field.value,\n 'unlock_experiment': false,\n 'keep_alive': false,\n 'uid': ''\n });\n update_server_service.callService(request, function (result) {\n lock_result.innerHTML = \"\";\n uid = result.uid;\n continue_instructions.innerHTML = \n \"The experiment is coming online. Please wait...\";\n continue_button.disabled = true;\n });\n }\n\n}", "function Go(t, e) {\n t.Gr.H(e.targetId), as(t).Ir(e)\n /**\n * We need to increment the expected number of pending responses we're due\n * from watch so we wait for the removal on the server before we process any\n * messages from this target.\n */;\n}", "function eosRequest(method, elementID) {\n console.log(method, elementID);\n switch (method) {\n case 'pull':\n switch (elementID) {\n case 'hat-hotspot':\n break;\n\n case 'claim-notifications':\n break;\n\n }\n break;\n\n case 'push':\n switch (elementID) {\n case 'want-button':\n $('#purchase-response').hide();\n $('#want-response').show();\n break;\n\n case 'purchase-button':\n eos.contract('promoteit')\n .then((contract) => {\n console.log(\"CONTRACT INIT\");\n contract.buyitem( {\n \"serialnum\": \"0\",\n \"buyername\": \"james\"\n }, {authorization: EOS_CONFIG.contractSender} ) \n .then((res) => {\n console.log(\"POST CALL\");\n console.log(res);\n $('#purchase-response').show();\n $('#want-response').hide();\n $('#hidden-hat').show();\n }).catch((err) => { console.log(err) })\n }).catch((err) => { console.log(err) })\n break;\n\n case 'add-item-button':\n $('#add-item-button').hide();\n $('#add-item-response').show();\n setTimeout(function() {$('#claim-notifications').show()}, 3000);\n break;\n\n case 'receive-reward-button':\n $('#receive-reward-button').hide();\n $('#receive-reward-response').show();\n $('#claim-notifications').hide();\n $('#token-balance-amount').html('3.45');\n break;\n }\n break;\n }\n}", "function wdCall() {\n this.requestStatus();\n }", "function waitForInformation() {\n informationFlash(InformationString);\n}", "async function callClient(){\r\n console.log(\"Waiting for the project....\");\r\n let firstStep = await willGetProject();\r\n let secondStep = await showOff(firstStep);\r\n let lastStep = await willWork(secondStep);\r\n console.log(\"Completed and deployed in seatle\");\r\n}", "function interact() {\r\n\t\tready = confirm('Ready to head up to the competitions?')\r\n\t\tif(ready) {\r\n\t\talert('Sup I\\'m the lifty Rosie!\\n\\n' + getLiftyResponse());\r\n\t\t} else {\r\n\t\talert('Get warmed up and get your gear on, let\\'s go!');\r\n\t\tinteract();\r\n\t\t};\r\n\t}", "function handleConfirm() {\n handleClose(); //closes first so that repeat requests are not sent\n fulfillPerson(personId);\n }", "function whatIWantToDo() {\n console.log('Hey waiter!!! Get yer arse here and serve!');\n}", "function reqTimeout () {\n\t\tapp.onStatus(\"Checking for update... Oups!\");\n\t\tapp.onOpen(appUrl);\n\t}", "function Wait_NotifyWait_Empty()\n{\n\t//do nothing\n}", "function prepareForGive() {\n actions.give = true;\n input.placeholder = \"Give what item?\";\n}", "onClick() {\n this.sendRequest(this.state.submissionId);\n }", "_issueNewRequestsAsync() {\n this._updateNeeded = false;\n\n const freeSlots = Math.max(this.props.maxRequests - this.activeRequestCount, 0);\n\n if (freeSlots === 0) {\n return;\n }\n\n this._updateAllRequests();\n\n // Resolve pending promises for the top-priority requests\n for (let i = 0; i < freeSlots; ++i) {\n if (this.requestQueue.length > 0) {\n const request = this.requestQueue.shift();\n request.resolve(true);\n }\n }\n\n // Uncomment to debug\n // console.log(`${freeSlots} free slots, ${this.requestQueue.length} queued requests`);\n }", "function buttonClicked(action, input) {\r\n if (action == \"show\") {\r\n xhr.open(\"GET\", \"fetchBookings.php?action=\" + action, true);\r\n } else {\r\n if (input != null) {\r\n xhr.open(\r\n \"GET\",\r\n \"fetchBookings.php?action =\" + action + \"&refInput=\" + input,\r\n true\r\n );\r\n alert(\"The booking request \" + input + \" has been properly assigned.\");\r\n }\r\n }\r\n xhr.onreadystatechange = displayBookings;\r\n xhr.send(null);\r\n}", "function queryServer(q) {\n didRespond = false;\n // Ask the server\n socket.emit('query', q);\n\n // No response in var=TIMEOUT amount of seconds\n setTimeout(function() {\n if (!didRespond) {\n\n TEXTBOX.disabled = false;\n TEXTBOX.value = '';\n TEXTBOX.focus();\n\n alert('The server appears to have cancer. ReBeatal the bot may have escaped his confines, the world is at risk.');\n\n // Keep this variable assignment at the bootom\n THINKING = false;\n }\n }, TIMEOUT * 1000);\n}", "ask(question) { this.io.emit('questionAsked', question); }", "function handleClick(e) {\n sendRequest()\n }", "function goRequest(i){\n\tvar requestId = requestBody.id;\n\t//parses it to string so it can be used\n\trequestBody = JSON.stringify(requestBody);\n\trequest.write(requestBody);\n\t//starts stopwatch for current request\n\tstopwatch[i].start = new Date().getTime();\n\tconsole.log('Login Sent ' + requestId);\n\trequire('fs').writeFile('./results/' + 'Request_id_' + requestId + '_' + momentTime() +'.txt', requestBody);\n\trequest.end();\n\t//delay that is calculated by the desired tps\n\tsleep(msDelay);\n}", "function EventWaiter() {\n this._waitingList = [];\n EventEmitter.call( this );\n}", "sendPageReady() {}", "_notifyPairRequest() {\n this.showNotification({\n id: 'pair-request',\n // TRANSLATORS: eg. Pair Request from Google Pixel\n title: _('Pair Request from %s').format(this.name),\n body: this.encryption_info,\n icon: new Gio.ThemedIcon({name: 'channel-insecure-symbolic'}),\n priority: Gio.NotificationPriority.URGENT,\n buttons: [\n {\n action: 'unpair',\n label: _('Reject'),\n parameter: null\n },\n {\n action: 'pair',\n label: _('Accept'),\n parameter: null\n }\n ]\n });\n\n // Start a 30s countdown\n this._resetPairRequest();\n\n this._incomingPairRequest = GLib.timeout_add_seconds(\n GLib.PRIORITY_DEFAULT,\n 30,\n this._setPaired.bind(this, false)\n );\n }", "function sendRequest() {\n FB.ui({\n method: 'apprequests',\n suggestions: appFriendIDs,\n message: 'Learn how to make your mobile web app social',\n }, function(response) {\n console.log('sendRequest UI response: ', response);\n });\n}" ]
[ "0.61641407", "0.61181545", "0.580089", "0.5733144", "0.57205635", "0.5715712", "0.56806993", "0.5656867", "0.5598535", "0.5566023", "0.5547988", "0.55222565", "0.5463141", "0.546027", "0.5440587", "0.5425599", "0.54199404", "0.53965485", "0.5377738", "0.5361327", "0.53549397", "0.53533405", "0.5332974", "0.5331726", "0.53213304", "0.5270595", "0.52548903", "0.5248433", "0.524516", "0.5241063", "0.52409786", "0.5236963", "0.5233865", "0.52051103", "0.5201152", "0.52010894", "0.51994187", "0.51929754", "0.5191075", "0.5182248", "0.51652193", "0.5158306", "0.514389", "0.5131472", "0.5131119", "0.51208556", "0.5108226", "0.51036876", "0.51024586", "0.51011384", "0.509526", "0.5087191", "0.5086146", "0.508354", "0.50830406", "0.5080474", "0.5068005", "0.50638974", "0.50610757", "0.5061003", "0.50602525", "0.505654", "0.5048635", "0.50475836", "0.50462914", "0.5045071", "0.5042071", "0.5041944", "0.5041762", "0.50319934", "0.5020644", "0.50176203", "0.50176203", "0.5014712", "0.5013566", "0.50120276", "0.50087345", "0.50079197", "0.50078857", "0.50023514", "0.50014406", "0.49984196", "0.49945003", "0.49913928", "0.49850732", "0.4984383", "0.4982411", "0.49812976", "0.4979082", "0.4975826", "0.49757", "0.49753144", "0.49726307", "0.49713686", "0.49595466", "0.49572724", "0.49558702", "0.49541312", "0.49538738", "0.49523517" ]
0.59353215
2
import data from store
function mapStateToProps(state) { return { projects:state.projects.project, toggle:state.projects } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "static load (store) {\n if (!chrome.devtools) {\n _.each(['UserLevel', 'SwordLevel', 'Sword', 'Equip', 'Consumable', 'FieldSquare', \"Event\", \"EventLayer\", \"EventSquare\"], k => {\n store.commit('loadData', {\n key: k,\n loaded: true\n })\n })\n }\n return Promise.props({\n UserLevel: localforage.getItem('UserLevelMaster'),\n SwordLevel: localforage.getItem('SwordLevelMaster'),\n Sword: localforage.getItem('SwordMaster'),\n Equip: localforage.getItem('EquipMaster'),\n Consumable: localforage.getItem('ConsumableMaster'),\n FieldSquare: localforage.getItem('FieldSquareMaster'),\n Event: localforage.getItem('EventMaster'),\n EventLayer: localforage.getItem('EventLayerMaster'),\n EventSquare: localforage.getItem('EventSquareMaster')\n }).then((saved) => {\n console.log('loadLocal')\n _.each(saved, (v, k) => {\n TRHMasterData[k] = v\n console.log(TRHMasterData[k])\n store.commit('loadData', {\n key: k,\n loaded: !_.isNull(v)\n })\n })\n })\n }", "function ImportData() {\n //in this method we can connect to database or read our necessery info from file\n //Currently we read registered users from file and History matches from file(maybe) and save to lists\n ReadFromFile();\n}", "function loadData(store) {\n\treturn store.dispatch(fetchUsers());\n}", "async function load() {\n const str = await localStorage.getItem(KEY);\n if (!str) return;\n let initialState;\n ({ path, text, revision, lineCount, store: initialState } = JSON.parse(\n str\n ));\n store = createStore(reducer, initialState);\n }", "importFromURL(url, file, store, callback) {\n\t\tif (typeof store === 'string') {\n\t\t\tMeteor.call('ufsImportURL', url, file, store, callback);\n\t\t} else if (typeof store === 'object') {\n\t\t\tstore.importFromURL(url, file, callback);\n\t\t}\n\t}", "loadAccounts() {\n let accounts = store.getData( this._accountsKey );\n if ( !Array.isArray( accounts ) || !accounts.length ) return;\n this.importAccounts( accounts, true );\n }", "function DataStore() {}", "function DataStore() {}", "function loadData(store) {\n return store.dispatch(fetchUsers());\n}", "async loadItems() {\n const keys = await AsyncStorage.getAllKeys();\n const values = await AsyncStorage.multiGet(keys);\n\n this.data = this.data.set('source', fromJS(values));\n }", "function importOffers(data) {\n appState.setImporting(true);\n\n return postHelper('/import/offers', { chass_offers: data }, () => {\n appState.setImporting(false, true);\n fetchAll();\n }).catch(() => appState.setImporting(false));\n}", "async function loadData() {\n await store.dispatch(getSettings());\n await store.dispatch(getAccounts());\n await store.dispatch(getTransactions());\n await store.dispatch(getSubscriptions());\n await store.dispatch(setDataIsLoaded());\n}", "function importFile(type) {\n if(type === 'master') {\n importData();\n }\n }", "static fetchData({ store }) {\n return store.dispatch(getProductList())\n }", "function data_import() {\n let inputs = [\n './build/data/**/*.*',\n '!./build/data/**/_*.*'\n ], output = './public/data';\n\n return gulp.src(inputs).pipe(gulp.dest(output));\n}", "function _eFapsCreateAllImportDataModel() {\n var fileList = eFapsGetAllFiles(\"org/efaps/js/definitions\", true);\n\n importSQLTables(fileList);\n importTypes(fileList);\n}", "fetchStore() {\n const storedData = JSON.parse(localStorage.getItem(LS_FORMULAS_KEY));\n this.formulas = storedData?.formulas ?? [];\n this.lastObjectId = storedData?.lastObjectId ?? -1;\n }", "import() {\n }", "function Store (){}", "function FromLocalStore(data) {\n console.log(\"Data used from local store\");\n // Have to parse it, as it's a string\n data = JSON.parse(data);\n\n var crimeData = data.response.crimes.region;\n var national = data.response.crimes.national;\n\n // Creating objects and adding them to an array, so they can be used in the same way\n // the json objects are in the charts.js\n var englandObj = new Object();\n englandObj.id = \"England\";\n englandObj.total = data.response.crimes.england.total;\n\n var walesObj = new Object();\n walesObj.id = \"Wales\";\n walesObj.total = data.response.crimes.wales.total;\n\n var countryArray = new Array(englandObj, walesObj);\n\n // Adds the national stuff to the same data as the regions, so that they\n // can all be displayed together\n $.each(national, function() {\n crimeData.push(this);\n });\n\n var rawData = JSON.stringify(data, null, 4);\n VisulisationSetup(crimeData, countryArray, rawData);\n}", "function importState(state) {\n\t\t\t\t\t\t\n\t\t\t\t\t\t// Load a state object created by exportState().\n\n\t\t\t\t\t}", "load() {\n let record = localStorage.getItem(STORAGE_KEY + \"/\" + this.user.getId());\n this.data = record ? JSON.parse(record) : {};\n }", "async processImportData(data) {\n for (let i = 0; i < data.scene.children.length; i++) {\n const model = data.scene.children[0]\n this.add(model)\n }\n }", "constructor() {\n this.#database = new Datastore({\n filename: \"./server/database/rooms.db\",\n autoload: true,\n });\n }", "function ImportStockAdjustmentData() {\n try{\n BindOrReloadStockAdjustmentTable('Export');\n }\n catch (e) {\n console.log(e.message);\n }\n}", "static initEventLayerMaster (store) {\n if (TRHMasterData.masterData === null) return\n TRHMasterData.EventLayer = _(TRHMasterData.masterData.EventLayerMaster)\n .split('\\n')\n .map((line) => {\n let arr = line.split(',')\n let obj = {}\n obj['episodeId'] = _.toInteger(arr[0])*(-1)\n obj['fieldId'] = _.toInteger(arr[1])\n obj['layerNum'] = _.toInteger(arr[2])\n obj['map'] = _.toInteger(arr[4])\n return obj\n })\n .groupBy('episodeId')\n .mapValues((val) => {\n return _(val)\n .groupBy('fieldId')\n .mapValues((v) => {\n return _(v)\n .keyBy('layerNum')\n .value()\n })\n .value()\n })\n .value()\n return localforage.setItem('EventLayerMaster', TRHMasterData.EventLayer)\n .then(() => {\n console.log(TRHMasterData.EventLayer)\n store.commit('loadData', {\n key: 'EventLayer',\n loaded: true\n })\n })\n .catch((err) => {\n console.log('err', err)\n store.commit('loadData', {\n key: 'EventLayer',\n loaded: false\n })\n })\n }", "store() {\n\t\tlet storeData = this.data.map(wfItem => wfItem.storeVersion());\n\t\tlocalStorage.setItem('data', JSON.stringify(storeData));\n\t}", "async load () {}", "function LoadData(){\n\tLoadDataFiles();\n\tExtractDataFromFiles();\n}", "function ImportCustomerData() {\n BindOrReloadCustomerTable('Export');\n}", "function loadFromStore(storeName, innerFunction, callback) {\n var cursor = db.transaction([storeName], 'readonly').objectStore(storeName).openCursor();\n \n cursor.onsuccess = function(event) {\n var result = this.result;\n if (result) {\n innerFunction(result);\n result.continue();\n }\n else {\n callback();\n }\n };\n }", "function loadData() {\n try {\n const fsStorageAsArray = JSON.parse(localStorage.getItem(\"saveArray\"));\n fromSaveFormat(fsStorageAsArray);\n } catch (err) {\n // fill some initial data\n fsStorage = [\n {\n id: 0, name: \"root\", children: [\n { id: 1, name: \"sub1\", children: [\n { id: 4, name: \"file.txt\"},\n { id: 5, name: \"sub3\", children: [\n {id: 6, name: \"file2.txt\", content: \"content2\"}\n ]}\n ]},\n { id: 2, name: \"sub2\", children: []},\n { id: 3, name: \"file1.txt\", content: \"text\"}\n ]\n }\n ]\n }\n }", "load() {\n try {\n appState.state.cursor().update( cursor => {\n return cursor.merge( JSON.parse( window.localStorage.getItem( APPCONFIG.LS ) ) )\n })\n } catch( err ) {\n console.error( 'Error loading from local storage' )\n console.error( err )\n return\n }\n\n console.log( 'loaded' )\n }", "async load () {\n const startables = await this.db.startables.toArray()\n this.store.setStartables(startables)\n\n const rows = await this.db.favourites.get('favourites')\n\n if (rows) {\n this.store.setFavourites(rows.favourites)\n }\n }", "async loadFromExtraStore() {\n this.id = this.request.cookies.get(this.options.key, this.options) || this.generateSessionId();\n const json = await this.store.get(this.id, this.options.maxAge);\n if (!this.verify(json)) {\n return this.generate();\n }\n return this.generate(json);\n }", "imports(json) {\n\t\tlet mongo = json.mongo;\n\t\tlet promises = [];\n\t\tpromises.push(new MongoScopes(this.mongo).add(mongo.scope));\n\t\tpromises.push(this.importAllFromType(new MongoLocations(this.mongo), mongo.location));\n\t\tpromises.push(this.importAllFromType(new MongoPeriods(this.mongo), mongo.year));\n\t\tpromises.push(this.importAllFromType(new MongoThemes(this.mongo), mongo.theme));\n\t\tpromises.push(this.importAllFromType(new MongoTopics(this.mongo), mongo.topic));\n\t\tpromises.push(this.importAllFromType(new MongoAttributeSets(this.mongo), mongo.attributeset));\n\t\tpromises.push(this.importAllFromType(new MongoAttributes(this.mongo), mongo.attribute));\n\t\tpromises.push(this.importAllFromType(new MongoLayerTemplates(this.mongo), mongo.areatemplate));\n\t\tpromises.push(this.importAllFromType(new MongoLayerReferences(this.mongo), mongo.layerref));\n\t\tpromises.push(this.importAllFromType(new MongoAnalysis(this.mongo), mongo.analysis));\n\t\tpromises.push(this.importAllFromType(new MongoPerformedAnalysis(this.mongo), mongo.performedanalysis));\n\n\t\tpromises.push(this.pool.pool().query(json.postgresql.sql));\n\t\t// TODO: Also create the data views on top of the data.\n\n\t\treturn Promise.all(promises);\n\n\t}", "function getStorageData() {\r\n if(localStorage.Data) {\r\n Product.all = JSON.parse(localStorage.Data);\r\n }\r\n}", "function loadProductData(data) {\n _product = data[0];\n}", "function setup_stores()\n{\n\t// Init Files \n\tmodels['Files'] = new IDBStore({\n\t storeName: 'Files',\n\t keyPath: 'id',\n\t dbVersion: site.config.indexeddb.Files.version,\n\t storePrefix: '',\n\t autoIncrement: true,\n\t\tindexes: site.config.indexeddb.Files.indexes,\t \n\t onStoreReady: get_files_data\n\t});\n}", "Store() {\n\n }", "loadData(state, lists) {\n state.lists = lists;\n }", "function loadData() {\n try {\n get_valsFromJSON(JSON.parse(atob(localStorage.sv1)));\n } catch(NoSuchSaveException) { \n console.log(\"No saved data to load: \" + NoSuchSaveException);\n }\n}", "function load() {\n getStore('firstname');\n getStore(\"lastname\");\n getStore(\"age\");\n getStore(\"sex\");\n getRadio(\"faveCandy\"); //radio button is simply storing as \"on\"\n getStore(\"email\");\n getStore(\"phonenum\");\n getStore(\"address\");\n getStore(\"middlename\");\n}", "function syncStore() {\n\n if(OS_IOS){\n\n // Items collection:\n\n var col = Alloy.Collections.externalStore;\n col.fetch();\n\n var d = col.toJSON();\n\n // Iterate the items saved in externalstore :\n\n _.each(d, function(item){\n\n requestProduct(item.StoreRef, function(prod){\n \n var model = col.get(item.ItemID);\n \n model.set({\n Name:prod.title,\n Description:prod.description,\n Cost:prod.formattedPrice\n }).save();\n\n Ti.API.info('Getting IOS item from iTunesConnect: ' + prod ) ;\n });\n\n \n });\n\n // Update the collection\n\n col.trigger(\"sync\");\n\n }else if(OS_ANDROID) {\n\n InAppAndroid.state = 'init';\n \n InAppAndroid.startSetup({\n\n publicKey: ANDROID_PUBLIC_KEY,\n debug: false\n\n });\n\n }; \n\n}", "function getStores() {\n return [MainStore];\n}", "function loadData() {\n\n //Users name.\n loadName()\n\n //Users config.\n loadConfig()\n}", "function loadEntitiesFromStore(storageString) {\n database.get('entities',function(err,storageString) {\n if (err && err.name !== 'NotFoundError') throw err\n var entitiesHash = storageString ? JSON.parse(storageString) : {}\n Object.keys(entitiesHash).map(function(entityId){\n var entityHash = entitiesHash[entityId]\n updateEntity(entityHash)\n })\n })\n }", "async import(uri, options) {\n const basePath = uri.substring(0, uri.lastIndexOf('/')) + '/'; // location of model file as basePath\n const defaultOptions = _misc_DataUtil__WEBPACK_IMPORTED_MODULE_0__[\"default\"].createDefaultGltfOptions();\n if (options && options.files) {\n for (let fileName in options.files) {\n const fileExtension = _misc_DataUtil__WEBPACK_IMPORTED_MODULE_0__[\"default\"].getExtension(fileName);\n if (fileExtension === 'gltf' || fileExtension === 'glb') {\n return await this.__loadFromArrayBuffer(options.files[fileName], defaultOptions, basePath, options);\n }\n }\n }\n const arrayBuffer = await _misc_DataUtil__WEBPACK_IMPORTED_MODULE_0__[\"default\"].fetchArrayBuffer(uri);\n return await this.__loadFromArrayBuffer(arrayBuffer, defaultOptions, basePath, options);\n }", "function loaddata(){\n\t\tvar data1 = localStorage.getItem(\"infor_sku\") || \"\";\n\t\tvar data2 = localStorage.getItem(\"pd\") || \"\";\n\t\tvar data3 = localStorage.getItem(\"sh\") || \"\";\n\t\tif (!!data1) { sku_items = JSON.parse(data1); }\n\t\tif (!!data2) { pd_items = JSON.parse(data2); }\n\t\tif (!!data3) { sh_items = JSON.parse(data3); }\n\t\t$(\"#datafile\").val( localStorage.getItem(\"datafile\") ||\"http://123.123.123.250:5000/\");\n\t\t$(\"#myfile\").val( localStorage.getItem(\"myfile\") ||\"spchkm/\");\n\t\t\n\t}", "loadData() {\n\n }", "loadData() {\r\n\t\t// load the current tracker type data from localStorage\r\n\t\tlet currentData = localStorage.getItem( this.type );\r\n\r\n\t\t// parse it into an object if it exists\r\n\t\tif ( currentData ) {\r\n\t\t\tthis.data = JSON.parse(currentData);\r\n\t\t} else {\r\n\t\t\tthis.data = {};\r\n\t\t}\r\n\t}", "async import() {\n // do a fetch for a file \n let readFile = (e) => {\n fetch(URL.createObjectURL(e.target.files[0]))\n .then(res => {\n return res.json()\n })\n .then(contents => {\n // run the application session loader\n this.sessionRecreator(contents)\n })\n }\n let inputFile = document.createElement(\"input\")\n inputFile.type = \"file\"\n inputFile.onchange = readFile\n // trigger the opening of a file explorer window\n inputFile.click()\n // iterate over the panes\n\n }", "function importFromJSON(jsonImport){\n localStorage.setItem(\"journal\", JSON.stringify(jsonImport.journal));\n localStorage.setItem(\"template\", jsonImport.template);\n init();\n}", "import() {\n settings.importFromFile(this.files[0])\n .then(restore)\n .catch(() => notifier.error('Cannot import settings file'));\n }", "async getAll() {\n return axios\n .get(UrlBuilder[this.storeType].paths.base, createHeaders())\n .then(response => this.store.addAll(response.data))\n .catch(error => handleError(error.response))\n }", "afterImport(){\n // this.transitionTo('app.dashboard.editor', this.get('currentModel').targetDocument);\n let doc = this.get('currentModel').targetDocument;\n // console.log(doc);\n let docID = doc.get('id'); \n // console.log(docID);\n this.transitionTo('app.documents.editor', docID);\n }", "initial_state(){\n let fromLocalStorage = window.localStorage.getItem('vue-mini-shop')\n\n // If localStorage data is length\n if (fromLocalStorage !== null) {\n\n fromLocalStorage = JSON.parse(fromLocalStorage)\n\n // Destructuring First\n let { product: product, cart: cart } = fromLocalStorage\n\n productStore.set({ all: product.all })\n cartStore.set({ all: cart.all })\n }\n // When data in the local Storage is null\n else {\n productStore.set({\n all: [\n {\n name: \"Iphone 5 S\",\n img: './assets/img/mobile.jpg',\n price: 9000000,\n stocks: [\n { color: \"black\", stock: 30 },\n { color: \"silver\", stock: 20 },\n { color: \"gold\", stock: 10 },\n { color: \"rose gold\", stock: 5 },\n ],\n liked: false,\n detail: \"<p>This is the details of the Iphone, Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.<br><br>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>\",\n categories: [ 'phone' ],\n comments: [\n { content: \"Waaah.. keren bingit Hpnya!\" },\n { content: \"Barangnya Sampai dengan Selamat Gan, Makasih. Packaging-nya juga bagus! Recommended banget deh pokoknya\" },\n ]\n },\n {\n name: \"Smart Phone Apple\",\n img: './assets/img/hi-tech-toys.jpg',\n price: 10500000,\n stocks: [\n { color: \"white\", stock: 50 },\n ],\n liked: false,\n detail: \"<p>This is the details of the Iphone, Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.<br><br>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>\",\n categories: [ 'phone' ],\n comments: [\n { content: \"Pinter bingit Hpnya!\" },\n ]\n },\n {\n name: \"Flatty Phone With Earphone\",\n img: './assets/img/mobile-2.jpg',\n price: 7500000,\n stocks: [\n { color: \"white\", stock: 20 },\n { color: \"black\", stock: 10 },\n ],\n liked: false,\n detail: \"<p>This is the details of the Iphone, Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.<br><br>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>\",\n categories: [ 'phone' ],\n comments: [\n { content: \"Earphonenya Mantabs Gan!\" },\n ]\n },\n {\n name: \"Book And Pen\",\n img: './assets/img/hi-tech-toys-2.jpg',\n price: 150000,\n stocks: [\n { color: \"brown\", stock: 150 },\n { color: \"silver\", stock: 15 },\n ],\n liked: false,\n detail: \"<p>This is the details of the Iphone, Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.<br><br>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>\",\n categories: [ 'accessories' ],\n comments: [\n { content: \"Bukunya Elegan! Saya suka dengan Warnanya\" },\n ]\n },\n {\n name: \"An Ipad\",\n img: './assets/img/ipad.jpg',\n price: 10000000,\n stocks: [\n { color: \"black\", stock: 10 },\n { color: \"silver\", stock: 10 }\n ],\n liked: false,\n detail: \"<p>This is the details of the Ipad, Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.<br><br>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>\",\n categories: [ 'pad' ],\n comments: [\n { content: \"Sukak banget sama yang warna Merah\" },\n { content: \"Barangnya Sampai dengan Selamat Gan, Makasih. Packaging-nya juga bagus! Recommended banget deh pokoknya\" },\n ]\n },\n\n\n {\n name: \"Mobile IOS\",\n img: './assets/img/ios.jpg',\n price: 13000000,\n stocks: [\n { color: \"gold\", stock: 10 },\n { color: \"black\", stock: 10 },\n { color: \"silver\", stock: 10 }\n ],\n liked: false,\n detail: \"<p>This is the details of the Mobile IOS, Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.<br><br>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>\",\n categories: [ 'phone' ],\n comments: []\n },\n ],\n })\n } // else\n }", "createStore() {\n if (!this.newWork) return\n db.downloading.insert(this.getStoreObj(), (err, data) => {})\n }", "async function blxInfileStore () {\n if (infile_read_len === undefined || !infile_read_len) {\n blxErrMsg = 'ERROR(Store): No Data to store'\n return\n }\n if (infile_bytebuf === undefined || infile_bytebuf.length !== infile_exp_len) {\n blxErrMsg = 'ERROR(Store): Inconsistent Data'\n return\n }\n const storeKey = blxIDs.deviceMAC + '_' + infile_name // NAME here\n const storeValue = []\n\n storeValue.total_len = infile_file_len\n storeValue.pos0 = infile_file_pos0\n storeValue.akt_len = infile_exp_len\n\n storeValue.ctime = infile_file_ctime\n storeValue.crc32 = infile_file_crc32\n storeValue.ucl_flag = infile_file_ucl_flag\n storeValue.esync_flag = infile_file_esync_flag\n storeValue.bytebuf = infile_bytebuf\n\n try{\n await blStore.set(storeKey, storeValue)\n } catch(err){\n blxErrMsg = 'ERROR(Store): ' + err\n return\n }\n\n terminalPrint(\"Save to Store '\" + storeKey + \"'\")\n infile_bytebuf = undefined // Save Memory\n infile_laststore_name = storeKey // keep Name\n }", "function loadCatalog(){\r\n\tconst databaseString = localStorage.getItem('Library Catalog')\r\n\tcatalog = JSON.parse(databaseString)\r\n}", "function main() {\n\tapi.getItems()\n\t\t.then((items) => {\n\t\t\titems.forEach((obj) => store.addItem(obj));\n\t\t});\n\tevents.initEvents();\n\tlist.render();\n}", "function importData() {\n d3.json(\"./Data/bubbleData.json\").then(function(data) {\n wordCloud(data);\n })\n}", "initialiseStore (state) {\n if (localStorage.getItem('store')) {\n this.replaceState(\n Object.assign(state, JSON.parse(localStorage.getItem('store')))\n )\n }\n }", "static initSwordLevelMaster (store) {\n if (TRHMasterData.masterData === null) return\n TRHMasterData.SwordLevel = _(TRHMasterData.masterData.SwordLevelMaster)\n .split('\\n')\n .map((line) => {\n let arr = line.split(',')\n let obj = {}\n obj['type'] = _.toInteger(arr[0])\n obj['level'] = _.toInteger(arr[1])\n obj['exp'] = _.toInteger(arr[2])\n return obj\n })\n .groupBy('type')\n .mapValues((val) => {\n return _(val).keyBy('level').mapValues(v => v.exp).value()\n })\n .value()\n return localforage.setItem('SwordLevelMaster', TRHMasterData.SwordLevel)\n .then(() => {\n console.log(TRHMasterData.SwordLevel)\n store.commit('loadData', {\n key: 'SwordLevel',\n loaded: true\n })\n })\n .catch((err) => {\n console.log('err', err)\n store.commit('loadData', {\n key: 'SwordLevel',\n loaded: false\n })\n })\n }", "function enrichStoreData(storeData) {\n var weeksData = (storeData && Object.keys(storeData).includes('weeksData')) ? storeData['weeksData'] : []\n var chaptersData = (storeData && Object.keys(storeData).includes('chaptersData')) ? storeData['chaptersData'] : []\n\n var weeksStats = weeksData.map(function (row) { return stats(row) });\n var weeksQ1 = weeksStats.map(function (row) { return row['q1'] });\n var weeksMedian = weeksStats.map(function (row) { return row['median'] });\n var weeksQ3 = weeksStats.map(function (row) { return row['q3'] });\n\n var chaptersStats = chaptersData.map(function (row) { return stats(row) });\n var chaptersQ1 = chaptersStats.map(function (row) { return row['q1'] });\n var chaptersMedian = chaptersStats.map(function (row) { return row['median'] });\n var chaptersQ3 = chaptersStats.map(function (row) { return row['q3'] });\n\n var weeksTranspose = (weeksData.length) ? transpose(weeksData) : []\n var chaptersTranspose = (chaptersData.length) ? transpose(chaptersData) : []\n\n\n storeData['weeksStats'] = weeksStats\n storeData['weeksQ1'] = weeksQ1\n storeData['weeksMedian'] = weeksMedian\n storeData['weeksQ3'] = weeksQ3\n storeData['chaptersStats'] = chaptersStats\n storeData['chaptersQ1'] = chaptersQ1\n storeData['chaptersMedian'] = chaptersMedian\n storeData['chaptersQ3'] = chaptersQ3\n storeData['weeksTranspose'] = weeksTranspose\n storeData['chaptersTranspose'] = chaptersTranspose\n return storeData\n }", "preFetch (store) {\n // return store.dispatch('FETCH_LIST_DATA', { type })\n }", "initializeStores() {\n this.stores.forEach((store) => {\n let [ver, storeDef] = store;\n console.log('Registering version %s of stores:\\n%s', ver, Object.keys(storeDef).join(', '));\n this.db.version(ver).stores(storeDef);\n });\n }", "constructor() { \r\n super(); // herda todas os metodos vindos do store\r\n }", "SaveAndReimport() {}", "function loadData() {\n loadJson('am');\n loadJson('pm');\n}", "initExportedStore(databaseUrl, exportedStore) {\n this.exportedDb = new PouchDB(`${databaseUrl}/${exportedStore}`)\n }", "static fetchData({ store }) {\n return store.dispatch(getUsers());\n }", "function readExtData (file) {\n console.error(`loading ${file}...`);\n return require(file).reduce((set, restaurant) => ({\n ...set,\n [restaurant.objectID]: restaurant\n }), {});\n}", "static initEventSquareMaster (store) {\n if (TRHMasterData.masterData === null) return\n TRHMasterData.EventSquare = _(TRHMasterData.masterData.EventSquareMaster)\n .split('\\n')\n .map((line) => {\n let arr = line.split(',')\n let obj = {}\n obj['episodeId'] = _.toInteger(arr[0])*(-1)\n obj['fieldId'] = _.toInteger(arr[1])\n obj['layerNum'] = _.toInteger(arr[2])\n obj['squareId'] = _.toInteger(arr[3])\n obj['category'] = _.toInteger(arr[4])\n obj['itemType'] = _.toInteger(arr[5])\n obj['itemId'] = _.toInteger(arr[6])\n obj['itemNum'] = _.toInteger(arr[7])\n obj['bgmId'] = _.toInteger(arr[8])\n return obj\n })\n .groupBy('episodeId')\n .mapValues((val) => {\n return _(val)\n .groupBy('fieldId')\n .mapValues((v) => {\n return _(v)\n .groupBy('layerNum')\n .mapValues((vv) =>{\n return _(vv)\n .keyBy('squareId')\n .value()\n })\n .value()\n })\n .value()\n })\n .value()\n return localforage.setItem('EventSquareMaster', TRHMasterData.EventSquare)\n .then(() => {\n console.log(TRHMasterData.EventSquare)\n store.commit('loadData', {\n key: 'EventSquare',\n loaded: true\n })\n })\n .catch((err) => {\n console.log('err', err)\n store.commit('loadData', {\n key: 'EventSquare',\n loaded: false\n })\n })\n }", "get InviteStore() {return WebpackModules.getByProps(\"getInvites\");}", "static preloadData(dispatch) {\n return Promise.all([\n complexActionCreators.loadNotebooksWithTags()(dispatch),\n ]);\n }", "constructor() {\n this.data = this._loadData();\n }", "loadData(){\n\t\tlet thisStore = this;\n\t\tClient.fetchBugs(bugs => {\n\t\t\tthis.bugs = bugs;\n\t\t\t//timeout required upon app loading, but no lag due to listening for data load completing\n\t\t\t//data will be loaded into the state of app.jsx\n\t\t\tsetTimeout(function(){thisStore.emit('DATA_LOADED')}, 250);\n\t\t});\n\t}", "constructor(){\n\n this.db = new Dexie('Chartsdb');\n\n this.db.version(1).stores({\n monthscharts: 'id,ligne,produit,qte,date,year,heure,months'\n });\n }", "_dataImportHandler() {\n this.refresh();\n }", "function gettingStoredDataFunction() {\n let allUsersFromStorage = localStorage.getItem('allUsers');\n let allUsersParse = JSON.parse(allUsersFromStorage);\n\n //don't update if the sotrage is empty\n if (allUsersParse) {\n\n //reinstantiation to restor the missed proto methods\n for (let i = 0; i < allUsersParse.length; i++) {\n\n new User(allUsersParse[i].name, allUsersParse[i].type);\n\n }\n }\n\n}", "function loadLocalStore(key) {\n var localString = localStorage.getItem(key);\n // catch undefined case\n localString = (localString) ? localString : \"{}\";\n return JSON.parse(localString);\n}", "getStore(index) {\n return(this.store[index]);\n }", "loadObjects (context, { file, database }) {\n const loader = new FileLoader(file)\n loader.loadAsync().then(resp => {\n if (database) {\n const separatedName = path.basename(file).split('.')\n if (separatedName.length > 1) separatedName.pop()\n const tblName = separatedName.join('_')\n context.commit('updateDatabase', { key: tblName, value: resp, database: database })\n } else {\n context.commit('updateState', { key: file, value: resp })\n }\n }).catch(e => {\n console.log(e)\n })\n }", "function Store() {}", "function Store() {}", "function Store() {}", "static useDataFromLoaclStorage(){\r\n const gitId = Store.getDatafromLoaclStorage();\r\n gitId.forEach(element => {\r\n const ui = new UI()\r\n ui.display(element);\r\n });\r\n }", "function loadDataFromMemory() {\n try {\n todos = JSON.parse(localStorage.getItem(LOCALSTORAGE_KEY)) || [];\n } catch (e) {\n console.error(e);\n todos = []\n }\n if (todos && todos.length > 0) {\n todos.forEach(todo => render(todo.title, todo.body, todo.imgTag))\n }\n}", "function loadOrderInfoFromRow() {\n const order_num = document.getElementById(\"input_order_text\").value;\n if (order_num == 1 || order_num == \"\") {\n return;\n }\n getOrder(\n {\n spreadsheetId: spreadsheetId,\n row: order_num\n },\n (err, res) => {\n if (err) {\n console.log(err);\n displayErrorPopUp(err);\n } else {\n const order_data = res.data.values[0];\n store.set(\"order_num\", order_num);\n document.getElementById(\"order_num_disp\").style.display =\n \"inline-block\";\n store.set(\"first_name_text\", order_data[2] || \"\");\n store.set(\"last_name_text\", order_data[3] || \"\");\n store.set(\"email_text\", order_data[4] || \"\");\n store.set(\"phone_number_text\", order_data[5] || \"\");\n store.set(\"type\", order_data[6] || \"\");\n store.set(\"color\", order_data[7] || \"\");\n store.set(\"size\", order_data[8] || \"\");\n store.set(\"front_text\", order_data[9] || \"\");\n store.set(\"left_arm_text\", order_data[10] || \"\");\n store.set(\"right_arm_text\", order_data[11] || \"\");\n store.set(\"back_text\", order_data[12] || \"\");\n store.set(\"hood_text\", order_data[13] || \"\");\n store.set(\"comment_text\", order_data[14] || \"\");\n console.log(\"set store:\");\n console.log(store.store);\n setFromStore();\n goToNextSection();\n }\n }\n );\n}", "getImports() {\n return new Promise((resolve, reject) => {\n Models.data_info.findAll({\n include: [\n {\n model: Models.data_provider_wallets,\n attributes: ['wallet', 'blockchain_id'],\n },\n ],\n }).then((rows) => {\n this.socket.emit('imports', rows);\n resolve();\n });\n });\n }", "loadLocal({ commit }) {\n if (!localStorage.getItem(\"todos\")) return;\n\n const localData = JSON.parse(localStorage.getItem(\"todos\"));\n\n commit(\"addMany\", localData);\n }", "function ImportToDatabase() {\n/* connect to database*/ \nvar valuesAsList = parseJsonToPostgreValuePairs(booksAsJsonArray);\n\n\n}", "async importToTypesense(data, collectionName) {\n const chunkSize = 2000;\n for (let i = 0; i < data.length; i += chunkSize) {\n const chunk = data.slice(i, i + chunkSize);\n await this.caller.call(async () => {\n await this.client\n .collections(collectionName)\n .documents()\n .import(chunk, { action: \"emplace\", dirty_values: \"drop\" });\n });\n }\n }", "get data(){\r\n\t\treturn this.__data \r\n\t\t\t?? (this.__data = idb.createStore(this.__db__, this.__store__)) }", "function load_data() {\r\n\tif (sessionStorage.getItem('pieces')) {\r\n\t\ttry {\r\n\t\t\tData.pieces = JSON.parse(sessionStorage.getItem('pieces'))\r\n\t\t\tData.stamps = JSON.parse(sessionStorage.getItem('stamps'))\r\n\t\t\tData.categories = JSON.parse(sessionStorage.getItem('categories'))\r\n\t\t\tData.tuto = JSON.parse(sessionStorage.getItem('tuto'))\r\n\t\t} catch (e) {}\r\n\t} else {\r\n\t\t// Create Categories\r\n\t\tfor (var x in Data.pieces)\r\n\t\t\tif (Data.pieces[x].category)\r\n\t\t\t\tData.categories[Data.pieces[x].category].content.push(x)\r\n\t}\r\n}", "preIngestData() {}", "handleImport(dataStr){\n let data = JSON.parse(dataStr);\n this.setState((state, props) => {\n let recipes = Map();\n data['recipes'].forEach((recipeName) => {\n recipes = recipes.update(props.config.Recipes[recipeName].result, Map(), recipeMap => recipeMap.set(recipeName, 0));\n });\n\n return {\n skills: Map(data['skills']).map((value) => Map(value)),\n ingredients: data['ingredients'],\n selectedRecipes: recipes\n };\n });\n this.setState(this.updateRecipes);\n this.setState(this.updatePrices);\n this.setState(Calculator.updateExportData);\n }", "function getAllMasterDataForStore() {\n return datacontext.get('Store/GetAllMasterDataForStore');\n }", "function wa_ImportStlFile(filedata,filename,fProgress,fFail,fDone){\n let basename=filename.toLowerCase().replace(\".stl\",\"\")\n\n //console.log(\"FILEDATA JS PUOLELLA=\"+JSON.stringify(filedata))\n stlModelData[basename]=JSON.parse(wasm_convertStlData(filedata,basename))\n fDone(basename,{\n vertex_filename:basename+\"_vertexes.bin\",\n normal_filename:basename+\"_normals.bin\",\n index_filename:basename+\"_indexes.bin\"\n })\n}", "function FromObject(store) {\n\t\tthis.get = function(/**/) {\n\t\t\tvar n_args = arguments.length;\n\t\t\tvar tokens;\n\t\t\tvar output = {};\n\t\t\tvar n_objects = 0;\n\t\t\tvar assetName;\n\t\t\tvar assetData;\n\t\t\tvar i, j;\n\t\t\tfor (i = 0; i < n_args; i++) {\n\t\t\t\tif (typeof arguments[i] !== 'string')\n\t\t\t\t\tcontinue;\n\t\t\t\ttokens = arguments[i]\n\t\t\t\t\t.trim()\n\t\t\t\t\t.replace(/,/g, '')\n\t\t\t\t\t.split(/\\s+/);\n\t\t\t\tfor (j = 0; j < tokens.length; j++) {\n\t\t\t\t\tassetName = tokens[j];\n\t\t\t\t\tassetData = store[assetName];\n\t\t\t\t\toutput[assetName] = assetData;\n\t\t\t\t\tn_objects++;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (n_objects == 1) {\n\t\t\t\treturn output[Object.keys(output)[0]];\n\t\t\t}\n\t\t\telse if (n_objects > 1) {\n\t\t\t\treturn output;\n\t\t\t}\n\t\t};\n\t}" ]
[ "0.64615417", "0.635056", "0.60944736", "0.60677665", "0.6059737", "0.6059017", "0.6040525", "0.6040525", "0.6029584", "0.6003237", "0.584583", "0.58399284", "0.57970756", "0.571058", "0.5671939", "0.567001", "0.5653025", "0.5645026", "0.5613523", "0.55929375", "0.558126", "0.5575104", "0.5570451", "0.5551229", "0.55396485", "0.5505704", "0.5502918", "0.5499811", "0.547805", "0.54770875", "0.5476032", "0.54728675", "0.5472137", "0.5462441", "0.54581964", "0.541063", "0.53965575", "0.53727627", "0.5371153", "0.53403515", "0.53393817", "0.53356135", "0.5329446", "0.5327546", "0.53122467", "0.53057194", "0.53057003", "0.53013325", "0.5296871", "0.5291416", "0.5290518", "0.5287352", "0.5274621", "0.52724874", "0.5270166", "0.52654046", "0.5260445", "0.5252546", "0.52506435", "0.5245965", "0.5244746", "0.5234195", "0.52260375", "0.522546", "0.5224564", "0.52169734", "0.521509", "0.5210369", "0.5210338", "0.5201402", "0.5199205", "0.5197342", "0.51952946", "0.5193032", "0.5191777", "0.5191156", "0.51838535", "0.5176416", "0.5176255", "0.51702803", "0.51690906", "0.5163658", "0.5160589", "0.5160423", "0.5154116", "0.5154116", "0.5154116", "0.5153171", "0.5152437", "0.5148198", "0.5136244", "0.513568", "0.51344466", "0.5128183", "0.51272196", "0.5111419", "0.51007533", "0.5093009", "0.5092619", "0.5091402", "0.5090005" ]
0.0
-1
Moves pipe to the left
update() { this.pos -= this.vel; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function swipedLeft(arg) {\n\tupdateImportance(arg.data, -1);\n}", "*directionHorizontalLeft() {\n yield this.sendEvent({ type: 0x03, code: 0x00, value: 0 });\n }", "function shiftLeft() {\n\tleft_video = current_video + 1;\n\tif (left_video >= vid_array.length) {\n\t\tleft_video = 1;\n\t}\n\tswitchToVideo(left_video);\n}", "function moveLeft(input) { setCursor(input, input.selectionStart - 1) }", "moveLeft() {\r\n this.socket.emit('Move left', this.number);\r\n this.moveLeftNext();\r\n }", "moveLeft() {\r\n this.actual.moveLeft();\r\n }", "moveLeft() {\n this.x>0?this.x-=101:false;\n }", "returnFromLeft() {\r\n this.fltire.rotateY(-16);\r\n this.frtire.rotateY(-16);\r\n }", "moveLeft() {\n if (this.x === 0) {\n this.x = this.tape[0].length - 1;\n } else {\n this.x--;\n }\n }", "goLeft() {\n gpio.write(this.motors.rightFront, true);\n }", "moveLeft() {\n dataMap.get(this).moveX = -5;\n }", "moveLeft() {\n\n if (this.posX >= 10 && pause == false)\n this.posX = this.posX - 5;\n }", "function toLeft(){\n imgIndex--;\n if(imgIndex == -1){\n imgIndex = imgItems.length-1;\n }\n changeImg(imgIndex);\n }", "function move_left() {\n\t check_pos();\n\t blob_pos_x = blob_pos_x - move_speed;\n\t}", "shftLeft(event) {\n // console.log(event)\n if (this.lineData.$parent.$title !== 'root') {\n this.lineData.$parent.removeSon(this.lineData);\n this.lineData.$parent.$parent.addSonFromRight(this.lineData);\n this.lineData.$parent = this.lineData.$parent.$parent;\n }\n }", "navigateWordLeft() {\n this.selection.moveCursorWordLeft();\n this.clearSelection();\n }", "function moveLeft() {\n moveOn();\n }", "turnLeft() {\n this.direction++;\n this.direction = this.direction.mod(4);\n }", "function leftToRight() {\n _displaymode |= LCD_ENTRYLEFT;\n command(LCD_ENTRYMODESET | _displaymode);\n}", "moveToPreviousCharacter() {\n this.handleLeftKey();\n }", "left() {\r\n this.v = -2;\r\n }", "function moveLeft() {\n\n\t\ttry {\n\t\t // Pass in the movement to the game.\n\t\t animation.move(\"x\", moveTypes.left);\n\t\t}\n\t\tcatch (err) {\n\t\t\tconsole.log(err);\n\t\t}\n\t}", "function rotateHeadLeft() {\n return pulseMotor(motorHead);\n}", "function onMoveLeft(evt){\n\t\t\troote.box.x -=20;\n\t\t}", "function leftSelect() {\n vm.selectedIndex = (vm.selectedIndex - 1) % vm.duplexOptionsArray.length;\n if (-1 === vm.selectedIndex) {\n vm.selectedIndex = vm.duplexOptionsArray.length - 1;\n }\n updateSeletecItem();\n vm.trigger({'itemClass': vm.optionKeys[0], 'selectedItem': vm.duplexOptionsArray[vm.selectedIndex]});\n }", "left() {\n // If the LEFT key is down, set the player velocity to move left\n this.sprite.body.velocity.x = -this.RUN_SPEED;\n //this.animate_walk();\n }", "_handleLeft(){\n if(this._buttonIndex > 0){\n this._setIndex(this._buttonIndex - 1);\n }else{\n this._setIndex(this.buttons.length -1);\n }\n }", "prev() {\r\n this.active = (this.active > 0) ? this.active - 1 : this.len - 1\r\n this.move('<-')\r\n }", "shiftLeft() {\n for (let line of this.cells) {\n for (let i = 0; i < line.length - 1; i++) {\n line[i].setType(line[i + 1].type);\n }\n line[line.length - 1].setType(BeadType.default);\n }\n }", "function moveLeft() {\n undraw()\n const reachedLeftEdge = curT.some(index => (curPos + index) % width === 0)\n if (!reachedLeftEdge) curPos -= 1\n if (curT.some(index => squares[curPos + index].classList.contains('taken'))) {\n // if the position has been taken by another figure, push the tetromino back\n curPos += 1\n }\n draw()\n }", "stopLeft() {\r\n this.socket.emit('Stop left', this.number);\r\n this.stopLeftNext();\r\n }", "rotateLeft() {\n if (this.direction !== Constants.SKIER_DIRECTIONS.CRASH && this.direction > Constants.SKIER_DIRECTIONS.LEFT) {\n this.setDirection(this.direction - 1);\n }\n }", "_moveLeftInfinity() {\n if (!this._settings.infinity) return;\n\n this._currentPosition = this._items.length;\n this._itemsHolder.style.transition = `transform ${ 0 }ms`;\n\n this._offset = -(this._calcShiftMaxLength() + this._calcTowardsLeft() );\n this._itemsHolder.style.transform = `translateX(${ this._offset - this._settings.oppositeSideAppearShift }px)`;\n setTimeout(() => this._moveLeft(), this._settings.oppositeSideAppearDelay);\n }", "function editor_tools_handle_left() {\n editor_tools_add_tags('[left]', '[/left]');\n editor_tools_focus_textarea();\n}", "function stepLeft() {\n\n if ( leftNumber > 0 ) {\n DODGER.style.left = `${leftNumber -= 4}px`; // decrement position number in inner scope and return decremented value into string '${/\\d+/}px'\n window.requestAnimationFrame(stepLeft);\n }\n }", "function playerLeft() {\n\tadjustPlayer(0, -1);\n}", "function moveLeft()\r\n {\r\n undraw()\r\n const isAtLeftEdge = currentTetromino.some(index => (currentPosition + index) % width === 0)\r\n\r\n if(!isAtLeftEdge)\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 }", "moveLeft() { this.velX -= 0.55; this.dirX = -1; }", "function left() {\n\t\t\tvar parentRole = getParentRole();\n\n\t\t\tif (parentRole == \"tablist\") {\n\t\t\t\tmoveFocus(-1, getFocusElements(focusedElement.parentNode));\n\t\t\t} else if (focusedControl.parent().submenu) {\n\t\t\t\tcancel();\n\t\t\t} else {\n\t\t\t\tmoveFocus(-1);\n\t\t\t}\n\t\t}", "function left() {\n\t\t\tvar parentRole = getParentRole();\n\n\t\t\tif (parentRole == \"tablist\") {\n\t\t\t\tmoveFocus(-1, getFocusElements(focusedElement.parentNode));\n\t\t\t} else if (focusedControl.parent().submenu) {\n\t\t\t\tcancel();\n\t\t\t} else {\n\t\t\t\tmoveFocus(-1);\n\t\t\t}\n\t\t}", "function left() {\n\t\t\tvar parentRole = getParentRole();\n\n\t\t\tif (parentRole == \"tablist\") {\n\t\t\t\tmoveFocus(-1, getFocusElements(focusedElement.parentNode));\n\t\t\t} else if (focusedControl.parent().submenu) {\n\t\t\t\tcancel();\n\t\t\t} else {\n\t\t\t\tmoveFocus(-1);\n\t\t\t}\n\t\t}", "function swapLeft(state) {\n let blankPOS = findBlankCell(state)\n return swap(state, { y: blankPOS.y, x: blankPOS.x - 1 })\n}", "shftRight(event) {\n // console.log(event)\n if (this.lineData.$parent.getIndexOfSon(this.lineData) != 0) {\n var newParent = this.lineData.$parent.$children[this.lineData.$parent.getIndexOfSon(this.lineData) - 1];\n newParent.addSonFromLeft(this.lineData);\n this.lineData.$parent.removeSon(this.lineData);\n this.lineData.$parent = newParent;\n }\n }", "left() {\n if (!this.isOnTabletop()) return;\n if (!this.facing) return;\n let degree=FacingOptions.facingToDegree(this.facing);\n degree-=90;\n this.facing=FacingOptions.degreeToFacing(degree);\n }", "function cursorLeft() {\n if (checkTaskExpanded(requireCursor())) {\n toggleCollapse();\n } else {\n selectAndCollapseParent();\n }\n }", "function goLeft() {\n leftMargin = $(\".inner-liner\").css(\"margin-left\").replace(\"px\", \"\") * 1;\n newLeftMargin = (leftMargin + 650);\n $(\".inner-liner\").animate({ marginLeft: newLeftMargin }, 500);\n }", "function moveLeft() {\n unDraw();\n const isAtLeftEdge = current.some(\n (index) => (currentPosition + index) % xPixel === 0\n );\n\n if (!isAtLeftEdge) currentPosition -= 1;\n if (\n current.some((index) =>\n pixels[currentPosition + index].classList.contains(\"taken\")\n )\n ) {\n currentPosition += 1;\n }\n\n draw();\n }", "function left_move() {\n if (coord_pos[0] > 0) {\n coord_pos[0] -= 1;\n }\n else if(coord_pos[1] > 0) { // If we need to wrap around (and have room to)\n coord_pos[0] = n;\n coord_pos[1] -= 1;\n } else { // If we hit the upper left, we go the bottom right corner\n coord_pos = [n,n];\n }\n recent_move = -1;\n}", "turnLeft() {\n if (DIRECTIONS.indexOf(this.position.heading) === 0) {\n this.position.heading = DIRECTIONS[3];\n } else {\n this.position.heading =\n DIRECTIONS[DIRECTIONS.indexOf(this.position.heading) - 1];\n }\n }", "function moveLeft() {\n undraw();\n // current position+index divided by width has no remainder\n const isAtLeftEdge = current.some(\n //condition is at left hand side is true\n (index) => (currentPosition + index) % width === 0\n );\n if (!isAtLeftEdge) currentPosition -= 1;\n if (\n current.some((index) =>\n squares[currentPosition + index].classList.contains(\"taken\")\n )\n ) {\n currentPosition += 1;\n }\n draw();\n }", "function goLeft() {\n if(positionIndex <= 0) {\n positionIndex = images.length - 1;\n } else {\n positionIndex--;\n }\n showImage(positionIndex);\n }", "function moveLeft() {\n $('._slider ul').animate({\n left: + slideWidth\n }, 200, function () {\n $('._slider ul li:last-child').prependTo('._slider ul');\n $('._slider ul').css('left', '');\n });\n }", "rotateLeft() {\n let valueBefore = this.value;\n let rightBefore = this.right;\n this.value = this.left.value;\n\n this.right = this.left;\n this.left = this.left.left;\n this.right.left = this.right.right;\n this.right.right = rightBefore;\n this.right.value = valueBefore;\n\n this.right.getDepthFromChildren();\n this.getDepthFromChildren();\n }", "TurnRobotLeft() {\n\t\treturn this._executeCommand(Commands.Left);\n\t}", "function leftArrowHandle(){\n let new_val = slides[slides.length - 1].props.slideNum + slides_count -1\n if (new_val > slides_arr.length-1) new_val = new_val - slides_arr.length\n if (slides_count ===1){\n new_val = slides[0].props.slideNum -1\n if (new_val < 0) new_val = slides_arr.length - 1\n }\n const updated = slides.slice(0,slides_count-1)\n setSlides([slides_arr[new_val],...updated])\n }", "function moveLeft() {\n undraw();\n const isAtLeftEdge = current.some(\n (index) => (currentPosition + index) % width === 0,\n );\n if (!isAtLeftEdge) {\n currentPosition -= 1;\n }\n if (\n current.some((index) =>\n squares[currentPosition + index].classList.contains(\"taken\"),\n )\n ) {\n currentPosition += 1;\n }\n draw();\n }", "onLeftArrowKeypress() {\n this.currentDirection === \"rtl\" ? this.next() : this.prev();\n }", "function moveLeft() {\n undraw()\n\n const isAtLeftEdge = current.some(index => (currentPosition + index) % width === 0)\n\n if (!isAtLeftEdge) currentPosition -= 1\n\n if (current.some(index => squares[currentPosition + index].classList.contains('taken'))) {\n currentPosition += 1\n }\n\n draw()\n }", "_moveRelatedLeftHandler() {\n this._moveLeft();\n }", "function moveLeft () {\n undraw()\n const isAtLeftEdge = current.some(index => (currentPosition + index) % width === 0)\n\n if (!isAtLeftEdge) {\n currentPosition -= 1\n }\n\n if (current.some(index => squares[currentPosition + index].classList.contains('taken'))) {\n currentPosition += 1\n }\n draw()\n }", "function moveLeft(rover) {\n\n switch (rover.direction) {\n case \"N\":\n rover.direction = \"W\";\n break;\n\n case \"E\":\n rover.direction = \"N\";\n break;\n\n case \"S\":\n rover.direction = \"E\";\n break;\n\n case \"W\":\n rover.direction = \"S\";\n break;\n }\n}", "function panLeft() {\n\tpannerNode.setPosition(-1, 0, 0);\n}", "function panLeft() {\n\tpannerNode.setPosition(-1, 0, 0);\n}", "function toLeft(){\n}", "left(){\n this.save();\n this.x--;\n this.isConflict();\n }", "moveLeft() {\n if (!this.collides(-1, 0, this.shape)) this.pos.x--\n }", "function scrollDisplayLeft() {\n command(LCD_CURSORSHIFT | LCD_DISPLAYMOVE | LCD_MOVELEFT);\n}", "function leftMod(){\n if(currentModIndex != 0){\n currentModIndex = currentModIndex - 1;\n let modIdString = 'mod'+currentModIndex;\n changeMods(modIdString);\n }\n \n}", "function moveLeft() {\n //remove current shape, slide it over, if it collides though, slide it back\n removeShape();\n currentShape.x--;\n if (collides(grid, currentShape)) {\n currentShape.x++;\n }\n //apply the new shape\n applyShape();\n}", "function moveLeft() {\r\n undraw();\r\n const isAtLeftEdge = current.some(\r\n (index) => (currentPosition + index) % width === 0\r\n );\r\n if (!isAtLeftEdge) currentPosition -= 1;\r\n if (\r\n current.some((index) =>\r\n squares[currentPosition + index].classList.contains(\"taken\")\r\n )\r\n ) {\r\n currentPosition += 1;\r\n }\r\n draw();\r\n }", "async function leftButton() {\n\tcreatePElement(warriorName + \" decides to walk left towards the \" + left + \".\");\n\tpathAction(left);\n\t\n\tpickedLeft = pickedLeft + 1;\n}", "function shiftRight() {\n\tright_video = current_video - 1;\n\tif(right_video < 1) {\n\t\tright_video = vid_array.length-1;\n\t}\n\tswitchToVideo(right_video);\n}", "function moveLeft() {\n undraw(squares, current, currentPosition);\n const isAtLeftEdge = current.some(index => (currentPosition + index) % WIDTH === 0);\n \n if(!isAtLeftEdge) currentPosition -= 1;\n\n if(current.some(index => squares[currentPosition + index].classList.contains('taken'))) {\n currentPosition += 1;\n }\n\n draw();\n }", "prev(enter = true) { return this.move(-1, enter); }", "goLeft(data = {}){\n data.cameFrom = \"left\";\n this.launchSceneAt(\n this.activeScene.coordinate.x - 1, \n this.activeScene.coordinate.y,\n data\n );\n }", "get left() { return 0; }", "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 }", "moveForwardOneWord() {\n this.simulateKeyPress_(SAConstants.KeyCode.RIGHT_ARROW, {ctrl: true});\n }", "function moveLeft() {\r\n undraw();\r\n const isAtLeftEdge = current.some(index => (currentPosition + index) % width === 0);\r\n // allows shape to move left if it's not at the left position\r\n if (!isAtLeftEdge) currentPosition -= 1;\r\n\r\n // push it unto a tetrimino that is already on the left edge\r\n if (current.some(index => squares[currentPosition + index].classList.contains('taken'))) {\r\n currentPosition += 1;\r\n\r\n }\r\n draw();\r\n}", "function panToLeft(){\n\tgainL.gain.value = 1;\n\tgainR.gain.value = 0;\n}", "leftTurn() {\r\n this.fltire.rotateY(16);\r\n this.frtire.rotateY(16);\r\n }", "function fireLeft(){\n\t\tconsole.log(\"firing\");\n\t\tdart1.style.left = \"-200px\";\n\t\tdart2.style.left = \"-400px\";\n\t\tdart3.style.left = \"-600px\";\n\t\tdart4.style.left = \"-550px\";\n\t}", "_moveToStart() {\n // moveCount can disturb the method logic.\n const initialMoveCount = this._settings.moveCount;\n this._settings.moveCount = 1;\n\n for (let pos = 1; pos < this._settings.startPosition; pos++) {\n this._rightMoveHandler();\n }\n this._settings.moveCount = initialMoveCount;\n }", "turnLeft() {\n this._currentLinearSpeed = 0;\n this._currentAngularSpeed = this._angularSpeed;\n }", "function pageleft(e) {\n setMedia();\n if (media.currentTime > trjs.dmz.winsize())\n media.currentTime = media.currentTime - (trjs.dmz.winsize() * trjs.dmz.pagePercentage);\n else\n media.currentTime = 0;\n if (trjs.param.synchro.block() === true) {\n trjs.events.goToTime('partition', media.currentTime); // the wave is not already set\n }\n }", "left(value = '') {\n this._rightOffset = '';\n this._leftOffset = value;\n this._justifyContent = 'flex-start';\n return this;\n }", "function goLeft(total){\n var count = 0;\n while (count < total){\n left();\n count++;\n }\n}", "shift(delta) { start+=delta }", "shift(delta) { start+=delta }", "function moveLeft() {\n var grid = null;\n for(grid of GameData.activePiece.getOrientation()) {\n GameData.mainPlayField.setBlock(\n GameData.row + grid.getRow(),\n correctColumn(GameData.column + grid.getColumn()),\n 0\n );\n }\n\n GameData.column = correctColumn(GameData.column - 1);\n\n var grid = null;\n for(grid of GameData.activePiece.getOrientation()) {\n GameData.mainPlayField.setBlock(\n GameData.row + grid.getRow(),\n correctColumn(GameData.column + grid.getColumn()),\n GameData.activePiece.getType()\n );\n }\n}", "function rightToLeft() {\n _displaymode &= ~LCD_ENTRYLEFT;\n command(LCD_ENTRYMODESET | _displaymode);\n}", "changeFocusToLeft() {\n cadManager.setCurrentFoot(\"left\");\n this.forceUpdate();\n }", "function isPipe (path) {\n return path.node.operator === LEFTPIPE\n}", "moveRight() {\n\n if (this.posX <= 670 && pause == false)\n this.posX = this.posX + 5;\n }", "function moveLeft() {\n undraw();\n const isAtLeftEdge = current.some((index) => (currentPosition + index) % width === 0);\n if (!isAtLeftEdge) currentPosition -= 1;\n if (current.some((index) => squares[currentPosition + index].classList.contains('taken'))) {\n currentPosition += 1;\n }\n draw();\n}", "function moveLeft() {\r\n moveTo(player.x - 1, player.y);\r\n}", "_moveLeft() {\n if (this._currentPosition < 2 && this._settings.infinity) {\n this._moveLeftInfinity();\n return;\n }\n for (let moved = 0; moved < this._settings.moveCount; moved++) {\n if (this._currentPosition < 1) break;\n\n this._itemsHolder.style.transition = `transform ${ this._settings.movementSmooth }ms`;\n\n const targetItem = this._items[this._currentPosition - 1];\n this._offset += targetItem.offsetWidth + this._settings.slidesSpacing;\n\n this._itemsHolder.style.transform = `translateX(${ this._offset + this._calcTowardsLeft() }px)`;\n\n this._currentPosition -= 1;\n }\n this._adaptViewWrapSizes();\n this._setDisplayedItemsClasses();\n }", "handleLeftEarClick() {\n this.setState({isLeft : !this.state.isLeft});\n }", "function moveLeft(){\n let initialPosLeft = witch.getBoundingClientRect().left;\n let lifeLeft = witch_lifeline.getBoundingClientRect().left;\n if(initialPosLeft > 32){\n witch_lifeline.style.left = lifeLeft - 20 + 'px';\n witch.style.left = initialPosLeft - 20 + 'px';\n }\n}", "*directionHorizontalRight() {\n yield this.sendEvent({ type: 0x03, code: 0x00, value: 255 });\n }", "moveForwardOneChar() {\n this.simulateKeyPress_(SAConstants.KeyCode.RIGHT_ARROW, {});\n }" ]
[ "0.6608104", "0.65019876", "0.64900446", "0.6465734", "0.6351823", "0.6343104", "0.6307015", "0.62297606", "0.6204889", "0.6200417", "0.6195992", "0.6180732", "0.61574847", "0.6110255", "0.6104469", "0.60988086", "0.6075636", "0.6070246", "0.6059934", "0.603657", "0.6029852", "0.60286707", "0.601148", "0.59874785", "0.59413016", "0.5938564", "0.59323794", "0.59057", "0.5880069", "0.58564615", "0.58294743", "0.58176696", "0.5813506", "0.57918245", "0.578702", "0.5774151", "0.57691294", "0.5752992", "0.57393444", "0.57393444", "0.57393444", "0.5731359", "0.5730604", "0.57296497", "0.57292867", "0.5720555", "0.57067007", "0.5700243", "0.569264", "0.568949", "0.5688299", "0.56756175", "0.5672763", "0.5669261", "0.5666387", "0.5657774", "0.56522685", "0.5648956", "0.56455195", "0.5642341", "0.564029", "0.5634367", "0.5634367", "0.563028", "0.5617786", "0.5617487", "0.56145465", "0.56135887", "0.5613109", "0.56126523", "0.5612339", "0.56023306", "0.5589719", "0.5587817", "0.55852854", "0.5581785", "0.55735534", "0.5571706", "0.5569785", "0.55674344", "0.5557724", "0.5546431", "0.55450284", "0.5540301", "0.5539169", "0.5527457", "0.55260986", "0.5523496", "0.5523496", "0.5523139", "0.5522213", "0.5517209", "0.5508138", "0.54974115", "0.54925036", "0.54852146", "0.5476966", "0.54713774", "0.54692155", "0.5453946", "0.5444828" ]
0.0
-1
Removes pipe if off screen
checkIfOnScreen(pipes) { if (this.pos < -this.pipeWidth) { pipes.splice(this, 1); } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function onclose(){dest.removeListener('finish',onfinish);unpipe();}", "function onclose(){dest.removeListener('finish',onfinish);unpipe();}", "function onclose(){dest.removeListener('finish',onfinish);unpipe();}", "function onclose(){dest.removeListener('finish',onfinish);unpipe();}", "function onclose(){dest.removeListener(\"finish\",onfinish);unpipe()}", "kill() {\n if (!this.process) return;\n if (this.inputMedia && this.inputMedia.unpipe) {\n this.inputMedia.unpipe(this.process.stdin);\n }\n this.process.kill('SIGKILL');\n this.process = null;\n }", "function onclose() {\n dest.removeListener('finish', onfinish);\n unpipe();\n }", "leave() {\n\t\tthis.i.removeListener('data', this.onKey);\n\t\tthis.o.removeListener('resize', this.onResize);\n\t\tprocess.removeListener('uncaughtException', this.onUncaughtException);\n\t\tprocess.removeListener('exit', this.onKill);\n\t\tprocess.removeListener('SIGTERM', this.onKill);\n\t\tprocess.removeListener('SIGINT', this.onKill);\n\t\tprocess.removeListener('SIGCONT', this.onContinue);\n\t\tthis.write(\"\\x1B[r\"); // reset scroll region\n\t\tthis.write(\"\\x1B[?1049l\"); // main buffer\n\t\tthis.i.setRawMode(false);\n\t\tthis.write = ()=>{}; //this will override the prototype\n\t}", "function stopStreaming()\n{\n app.set('watchingFile', false);\n if (proc1) proc1.kill();\n if (proc2) proc2.kill();\n fs.unwatchFile('./stream/image_stream.jpg');\n}", "function onclose() {\n\t dest.removeListener('finish', onfinish);\n\t unpipe();\n\t }", "function onclose() {\n\t dest.removeListener('finish', onfinish);\n\t unpipe();\n\t }", "function onclose() {\n\t dest.removeListener('finish', onfinish);\n\t unpipe();\n\t }", "function onclose() {\n\t dest.removeListener('finish', onfinish);\n\t unpipe();\n\t }", "function onclose() {\n\t dest.removeListener('finish', onfinish);\n\t unpipe();\n\t }", "function onclose() {\n\t dest.removeListener('finish', onfinish);\n\t unpipe();\n\t }", "function onclose() {\n\t dest.removeListener('finish', onfinish);\n\t unpipe();\n\t }", "function onclose() {\n\t dest.removeListener('finish', onfinish);\n\t unpipe();\n\t }", "function onclose() {\n\t dest.removeListener('finish', onfinish);\n\t unpipe();\n\t }", "function onclose() {\n\t dest.removeListener('finish', onfinish);\n\t unpipe();\n\t }", "function onclose() {\n\t dest.removeListener('finish', onfinish);\n\t unpipe();\n\t }", "function onclose() {\n\t dest.removeListener('finish', onfinish);\n\t unpipe();\n\t }", "function onclose() {\n\t dest.removeListener('finish', onfinish);\n\t unpipe();\n\t }", "function onclose() {\n\t dest.removeListener('finish', onfinish);\n\t unpipe();\n\t }", "function onclose() {\n\t dest.removeListener('finish', onfinish);\n\t unpipe();\n\t }", "function onclose() {\n\t dest.removeListener('finish', onfinish);\n\t unpipe();\n\t }", "function onclose() {\n\t dest.removeListener('finish', onfinish);\n\t unpipe();\n\t }", "function onclose() {\n\t dest.removeListener('finish', onfinish);\n\t unpipe();\n\t }", "function onclose() {\n\t dest.removeListener('finish', onfinish);\n\t unpipe();\n\t }", "function onclose() {\n\t dest.removeListener('finish', onfinish);\n\t unpipe();\n\t }", "function onclose() {\n\t dest.removeListener('finish', onfinish);\n\t unpipe();\n\t }", "function onclose() {\n\t dest.removeListener('finish', onfinish);\n\t unpipe();\n\t }", "function onclose() {\n\t dest.removeListener('finish', onfinish);\n\t unpipe();\n\t }", "function onclose() {\n\t dest.removeListener('finish', onfinish);\n\t unpipe();\n\t }", "function onclose() {\n\t dest.removeListener('finish', onfinish);\n\t unpipe();\n\t }", "function onclose() {\n\t dest.removeListener('finish', onfinish);\n\t unpipe();\n\t }", "function onclose() {\n\t dest.removeListener('finish', onfinish);\n\t unpipe();\n\t }", "function onclose() {\n\t dest.removeListener('finish', onfinish);\n\t unpipe();\n\t }", "function onclose() {\n\t dest.removeListener('finish', onfinish);\n\t unpipe();\n\t }", "function onclose() {\n\t dest.removeListener('finish', onfinish);\n\t unpipe();\n\t }", "function onclose() {\n\t dest.removeListener('finish', onfinish);\n\t unpipe();\n\t }", "function onclose() {\n\t dest.removeListener('finish', onfinish);\n\t unpipe();\n\t }", "function onclose() {\n\t dest.removeListener('finish', onfinish);\n\t unpipe();\n\t }", "function onclose() {\n\t dest.removeListener('finish', onfinish);\n\t unpipe();\n\t }", "function onclose() {\n\t dest.removeListener('finish', onfinish);\n\t unpipe();\n\t }", "function onclose() {\n\t dest.removeListener('finish', onfinish);\n\t unpipe();\n\t }", "function onclose() {\n\t dest.removeListener('finish', onfinish);\n\t unpipe();\n\t }", "function onclose() {\n\t dest.removeListener('finish', onfinish);\n\t unpipe();\n\t }", "function onclose() {\n\t dest.removeListener('finish', onfinish);\n\t unpipe();\n\t }", "function onclose() {\n\t dest.removeListener('finish', onfinish);\n\t unpipe();\n\t }", "function onclose() {\n\t dest.removeListener('finish', onfinish);\n\t unpipe();\n\t }", "function onclose() {\n dest.removeListener('finish', onfinish);\n unpipe();\n }", "function onclose() {\n dest.removeListener('finish', onfinish);\n unpipe();\n }", "function onclose() {\n dest.removeListener('finish', onfinish);\n unpipe();\n }", "function onclose() {\n dest.removeListener('finish', onfinish);\n unpipe();\n }", "function onclose() {\n dest.removeListener('finish', onfinish);\n unpipe();\n }", "function onclose() {\n dest.removeListener('finish', onfinish);\n unpipe();\n }", "function onclose() {\n dest.removeListener('finish', onfinish);\n unpipe();\n }", "function onclose() {\n dest.removeListener('finish', onfinish);\n unpipe();\n }", "function onclose() {\n dest.removeListener('finish', onfinish);\n unpipe();\n }", "function onclose() {\n dest.removeListener('finish', onfinish);\n unpipe();\n }", "function onclose() {\n dest.removeListener('finish', onfinish);\n unpipe();\n }", "function onclose() {\n dest.removeListener('finish', onfinish);\n unpipe();\n }", "function onclose() {\n dest.removeListener('finish', onfinish);\n unpipe();\n }", "function onclose() {\n dest.removeListener('finish', onfinish);\n unpipe();\n }", "function onclose() {\n dest.removeListener('finish', onfinish);\n unpipe();\n }", "function onclose() {\n dest.removeListener('finish', onfinish);\n unpipe();\n }", "function onclose() {\n dest.removeListener('finish', onfinish);\n unpipe();\n }", "function onclose() {\n dest.removeListener('finish', onfinish);\n unpipe();\n }", "function onclose() {\n dest.removeListener('finish', onfinish);\n unpipe();\n }", "function onclose() {\n dest.removeListener('finish', onfinish);\n unpipe();\n }", "function onclose() {\n dest.removeListener('finish', onfinish);\n unpipe();\n }", "function onclose() {\n dest.removeListener('finish', onfinish);\n unpipe();\n }", "function onclose() {\n dest.removeListener('finish', onfinish);\n unpipe();\n }", "function onclose() {\n dest.removeListener('finish', onfinish);\n unpipe();\n }", "function onclose() {\n dest.removeListener('finish', onfinish);\n unpipe();\n }", "function onclose() {\n dest.removeListener('finish', onfinish);\n unpipe();\n }", "function onclose() {\n dest.removeListener('finish', onfinish);\n unpipe();\n }", "function onclose() {\n dest.removeListener('finish', onfinish);\n unpipe();\n }", "function onclose() {\n dest.removeListener('finish', onfinish);\n unpipe();\n }", "function onclose() {\n dest.removeListener('finish', onfinish);\n unpipe();\n }", "function onclose() {\n dest.removeListener('finish', onfinish);\n unpipe();\n }", "function onclose() {\n dest.removeListener('finish', onfinish);\n unpipe();\n }", "function onclose() {\n dest.removeListener('finish', onfinish);\n unpipe();\n }", "function onclose() {\n dest.removeListener('finish', onfinish);\n unpipe();\n }", "function onclose() {\n dest.removeListener('finish', onfinish);\n unpipe();\n }", "function onclose() {\n dest.removeListener('finish', onfinish);\n unpipe();\n }", "function onclose() {\n dest.removeListener('finish', onfinish);\n unpipe();\n }", "function onclose() {\n dest.removeListener('finish', onfinish);\n unpipe();\n }", "function onclose() {\n dest.removeListener('finish', onfinish);\n unpipe();\n }", "function onclose() {\n dest.removeListener('finish', onfinish);\n unpipe();\n }", "function onclose() {\n dest.removeListener('finish', onfinish);\n unpipe();\n }", "function onclose() {\n dest.removeListener('finish', onfinish);\n unpipe();\n }", "function onclose() {\n dest.removeListener('finish', onfinish);\n unpipe();\n }", "function onclose() {\n dest.removeListener('finish', onfinish);\n unpipe();\n }", "function onclose() {\n dest.removeListener('finish', onfinish);\n unpipe();\n }", "function onclose() {\n dest.removeListener('finish', onfinish);\n unpipe();\n }", "function onclose() {\n dest.removeListener('finish', onfinish);\n unpipe();\n }", "function onclose() {\n dest.removeListener('finish', onfinish);\n unpipe();\n }", "function onclose() {\n dest.removeListener('finish', onfinish);\n unpipe();\n }", "function onclose() {\n dest.removeListener('finish', onfinish);\n unpipe();\n }" ]
[ "0.60007405", "0.60007405", "0.60007405", "0.60007405", "0.5907717", "0.5823216", "0.58150893", "0.57799745", "0.57689726", "0.5749785", "0.5749785", "0.5749785", "0.5749785", "0.5749785", "0.5749785", "0.5749785", "0.5749785", "0.5749785", "0.5749785", "0.5749785", "0.5749785", "0.5749785", "0.5749785", "0.5749785", "0.5749785", "0.5749785", "0.5749785", "0.5749785", "0.5749785", "0.5749785", "0.5749785", "0.5749785", "0.5749785", "0.5749785", "0.5749785", "0.5749785", "0.5749785", "0.5749785", "0.5749785", "0.5749785", "0.5749785", "0.5749785", "0.5749785", "0.5749785", "0.5749785", "0.5749785", "0.5749785", "0.5749785", "0.5749785", "0.5749785", "0.5713961", "0.57099205", "0.57099205", "0.57099205", "0.5677004", "0.5664702", "0.5662269", "0.5662269", "0.5662269", "0.5662269", "0.5662269", "0.5662269", "0.5662269", "0.5662269", "0.5662269", "0.5662269", "0.5662269", "0.5662269", "0.5662269", "0.5662269", "0.5662269", "0.5662269", "0.5662269", "0.5662269", "0.5662269", "0.5662269", "0.5662269", "0.5662269", "0.5662269", "0.5662269", "0.5662269", "0.5662269", "0.5662269", "0.5662269", "0.5662269", "0.5662269", "0.5662269", "0.5662269", "0.5662269", "0.5662269", "0.5662269", "0.5662269", "0.5662269", "0.5662269", "0.5662269", "0.5662269", "0.5662269", "0.5662269", "0.5662269", "0.5662269" ]
0.5841467
5
Resets pipes position to the right of screen
reset() { this.pos = width + this.pipeWidth; this.pipeHeight = random(height / 3, 2 * height / 3); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "checkIfOnScreen(pipes) {\n if (this.pos < -this.pipeWidth) {\n pipes.splice(this, 1);\n }\n }", "resetPos() {\n this.x = 2 * this.rightLeft;\n this.y = 4 * this.upDown + 54;\n }", "function resetScreen() {\n robot.moveMouse(rightScreen.x, rightScreen.y);\n robot.mouseClick();\n robot.keyTap(\"alt\");\n robot.keyTap(\"w\");\n robot.keyTap(\"1\");\n}", "returnFromRight() {\r\n this.fltire.rotateY(16);\r\n this.frtire.rotateY(16);\r\n }", "function panToRight(){\n\tgainL.gain.value = 0;\n\tgainR.gain.value = 1;\n}", "resetPos() {\r\n this.pos.x = width/2;\r\n this.pos.y = height/2;\r\n }", "returnFromLeft() {\r\n this.fltire.rotateY(-16);\r\n this.frtire.rotateY(-16);\r\n }", "reverseReset() {\n this.x = width / 2;\n this.y = height / 2;\n this.xdir = 0;\n this.ydir = 0;\n }", "Reset()\n {\n this._position = 0;\n }", "resetPosition () {\n this._planeSystem.position.x = 0;\n this._planeSystem.position.y = 0;\n this._planeSystem.position.z = 0;\n }", "resetPosition() {\n\t\tAnimated.spring(this.state.position, {\n\t\t\ttoValue: { x: 0, y: 0 }\n\t\t}).start();\n\t}", "resetView() {\n if (this._metadata[\"enablePositionReset\"] == true) {\n this.camera.position.z = this._metadata[\"resetPosition\"]['z'];\n this.camera.position.y = this._metadata[\"resetPosition\"]['y'];\n this.camera.position.x = this._metadata[\"resetPosition\"]['x'];\n this.camera.up.y = this._metadata[\"upSign\"];\n }\n this.controls.target0.x = 0.5 * (this.boundingBox.minX + this.boundingBox.maxX);\n this.controls.target0.y = 0.5 * (this.boundingBox.minY + this.boundingBox.maxY);\n this.controls.reset();\n }", "rightTurn() {\r\n this.fltire.rotateY(-16);\r\n this.frtire.rotateY(-16);\r\n }", "function resetPuck() {\n puckPosX = c.width / 2;\n puckPosY = c.height / 2;\n puckDirX = 0;\n puckDirY = 0;\n }", "function rightToLeft() {\n _displaymode &= ~LCD_ENTRYLEFT;\n command(LCD_ENTRYMODESET | _displaymode);\n}", "moveRight() {\n this.shinobiPos.x += 30\n }", "moveToEnd() {\n\n\t\tvar card = this.cards.getChildAt(this.cards.children.length - 1);\n\n\t\tvar rightEnd = this.leftBound + card.handPosition;\n\n\t\tthis.viewOffset = this.rightBound - rightEnd;\n\n\t\tif (this.viewOffset > 0) {\n\t\t\tthis.viewOffset = 0;\n\t\t}\n\n\t\tthis.handMaskRight.visible = false;\n\t}", "function playerRight() {\n\tadjustPlayer(blockWidth - 1, 1);\n}", "moveRight() {\n\n if (this.posX <= 670 && pause == false)\n this.posX = this.posX + 5;\n }", "function leftToRight() {\n _displaymode |= LCD_ENTRYLEFT;\n command(LCD_ENTRYMODESET | _displaymode);\n}", "function resetPointer() {\n Pointer.x = levels[myLvl].start.x,\n Pointer.y = levels[myLvl].start.y,\n Pointer.dir = \"right\";\n}", "outputCR() {\n this.cursor.x = 0;\n }", "changeFocusToLeft() {\n cadManager.setCurrentFoot(\"left\");\n this.forceUpdate();\n }", "function reset() {\n this._.canvas.width = this._.canvas.width;\n resetCantoState(this);\n }", "resetTempPosition() {\n this.set('tempPosition', { x: 0, y: 0, active: false });\n }", "renderView() {\n this.cursor.style.left = `${this.viewValue}px`;\n }", "outputRLF() {\n this.cursor.y -= 1;\n if (this.cursor.y == this.scrollMin - 1) {\n this.outputScrollDown(1);\n this.cursor.y = this.scrollMin;\n }\n else if (this.cursor.y < 0) {\n this.cursor.y = 0;\n }\n }", "resetPos(){\n this.addX(this.getX());\n this.addY(this.getY());\n }", "_resetCursors() {\n this._taskCursor = '';\n this._eventsCursor = '';\n }", "function panToLeft(){\n\tgainL.gain.value = 1;\n\tgainR.gain.value = 0;\n}", "resetPosition(x, y) {\n this.x = x;\n this.y = y;\n this.moving = false;\n this.currentState = {\n killing: false,\n frames: 1,\n };\n this.setDirection(Constants.RHINO_DIRECTIONS.DEFAULT)\n }", "function resetDirection() {\n\tleft = false;\n\tup = false;\n\tright = false;\n\tdown = false;\n}", "reset(position) {\n this.x = this.x0;\n this.y = this.y0;\n }", "resetPosition() {\n // 505 is width, 101 is one block, so 202 will be center\n this.x = 202;\n // 606 is height, 171 is one block, so 435 will be center, but we need to be be off a bit,\n // so it will be 435 - 45px\n this.y = 390;\n }", "function resetOffsets() {\n\tofsX = 0;\n\tofsY = baseOfsY;\n\tdocument.getElementById('verticalShift').value = 0;\n}", "reset(X,Y){\n Matter.Body.setPosition(this.body, {x: X,y: Y});\n }", "set RightCenter(value) {}", "resetSwipe(){ \n\tthis.direction = 0;\n\tthis.startX = 0;\n\tthis.startY = 0;\n }", "putDrawerToRight() {\n this.isReverse = true;\n }", "reset() {\n this.x=200;\n this.y=400;\n this.steps=0;\n }", "resetFrog(frog){\n frog.tag.style.top = `${this.BOTTOM_EDGE - 27}px`\n frog.tag.style.left = `${this.RIGHT_EDGE/2}px`\n\n }", "function reset() {\n pointer.transform(\"t0,0\");\n submit.transform(\"t0,-25\");\n frame.transform(\"s0.85, 0.56, \" + phonebox.cx + \", \" + phonebox.y + \" t0,19\");\n screenbg.transform(\"s1, 0.75, \" + phonebox.cx + \", \" + phonebox.y );\n button.transform(\"s0,0\");\n speaker.transform(\"s0,0\");\n }", "putDrawerToLeft() {\n this.isReverse = false;\n }", "function resetBox(){\n xOffset = playfield.width / 2;\n yOffset = playfield.height / 2;\n}", "function moveRight() {\n undraw();\n const isAtRightEdge = current.some(index => (currentPosition + index) % width === width - 1);\n if(!isAtRightEdge) {\n currentPosition += 1;\n }\n if(current.some(index => squares[currentPosition + index].classList.contains('block2'))) {\n currentPosition -=1;\n }\n draw();\n }", "function resetPlatform() {\n platform.x = (canvas.width - 200) / 2\n}", "reset() {\n this.dest.x = 200;\n this.dest.y = 450;\n }", "resetCanvasPosition(): void {\n this.translate(-this.canvasPosition.x, -this.canvasPosition.y);\n this.canvasPosition = { x: 0, y: 0 };\n }", "function timeOutRight(){\n if(wheelRight.position.x <= 150){ \n Render.lookAt(render, wheelRight, {\n x: 70,\n y: 210,\n padding: {x: 10, y:10},\n center: true\n \n })\n}}", "function scrollDisplayLeft() {\n command(LCD_CURSORSHIFT | LCD_DISPLAYMOVE | LCD_MOVELEFT);\n}", "function shiftRight() {\n\tright_video = current_video - 1;\n\tif(right_video < 1) {\n\t\tright_video = vid_array.length-1;\n\t}\n\tswitchToVideo(right_video);\n}", "function resetCan() {\n clear();\n curr = make2DArr(width, height);\n prev = make2DArr(width, height);\n background(0);\n}", "resetDialogPosition() {\n this.$dialog.style.top = 0;\n this.$dialog.style.left = 'auto';\n this.$dialog.style.right = '-1000px';\n }", "function moveRight() {\n if (flag) {\n flag = 0;\n //change the position of the element in array\n config.unshift(config.pop());\n //reset photos\n configImg();\n }\n }", "resetState() {\n this._movements = 0;\n }", "*directionHorizontalRight() {\n yield this.sendEvent({ type: 0x03, code: 0x00, value: 255 });\n }", "function reset2(){\n button.hide();\n if (mouseButton == LEFT)\n {\n button.hide();\n input.hide();\n }\n screenThree();\n}", "turnRight() {\n this._currentLinearSpeed = 0;\n this._currentAngularSpeed = -this._angularSpeed;\n }", "function loopReset() {\n controllerState.mouse.wheel = false;\n controllerState.mouse.rightClick = 0;\n controllerState.mouse.centralClick = 0;\n controllerState.mouse.leftClick = 0;\n\n controllerState.keyboard = [];\n\n drawingPile = [];\n }", "moveRight() {\n dataMap.get(this).moveX = 5;\n }", "frontWheelStab()\n\t{\n\t\tif(!(this.keysdirectionPress[0] || this.keysdirectionPress[1])) {\n\t\t\tthis.frontLeftWheel.update(0,360);\n\t\t\tthis.frontRightWheel.update(0,360);\n\t\t}\n\t}", "_handleRight(){\n if(this._buttonIndex < this.buttons.length - 1){\n this._setIndex(this._buttonIndex + 1);\n }else{\n this._setIndex(0);\n }\n }", "restart() {\n this.x = 200;\n this.y = 380;\n }", "function reset() {\n player.x = 0;\n player.y = 0;\n }", "resetPosition() {\n Animated.spring(this.state.position, {\n toValue: { x: 0, y: 0 }\n }).start();\n }", "reset() {\n this.x = 202;\n this.y = 395;\n }", "set TopRight(value) {}", "function moveRight() {\n undraw()\n const reachedRightEdge = curT.some(index => (curPos + index) % width === width - 1)\n if (!reachedRightEdge) curPos += 1\n if (curT.some(index => squares[curPos + index].classList.contains('taken'))) {\n // if the position has been taken by another figure, push the tetromino back\n curPos -= 1 \n }\n draw()\n }", "function reset(){\n\t\tsetSorting(false);\n\t\t// setDataBottom(new Array(rectNum).fill(new Rect(0,Math.round(maxWidth/rectNum),0)));\n\t\tsetLightUp([]);\n\t\t// setLightUpBottom([]);\n\n\t}", "function setRopePosition() {\n let ratio = (DOMSlider.value - DOMSlider.min) / (DOMSlider.max - DOMSlider.min);\n // floating point correction\n if (ratio < 0.5) ratio += 0.01;\n if (ratio < 0.3) ratio += 0.01;\n if (ratio > 0.6) ratio -= 0.01;\n if (ratio > 0.8) ratio -= 0.02;\n rope.points[rope.points.length - 1].pos.x = (ratio * width);\n }", "moveRight() {\n this.point.x += this.scrollSpeed;\n }", "function resetPosition()\n{\n\ttopPos = parseInt(topPosElem.value);\n\tleftPos = parseInt(leftPosElem.value);\n\tdisplay_status(\"pos: \" + leftPos + \",\" + topPos);\n\t//the values assigned to top and left must be strings\n\tcz.style.left = leftPos + \"px\";\n\tcz.style.top = topPos + \"px\";\n}", "function resetPosition()\n{\n\ttopPos = parseInt(topPosElem.value);\n\tleftPos = parseInt(leftPosElem.value);\n\tdisplay_status(\"pos: \" + leftPos + \",\" + topPos);\n\t//the values assigned to top and left must be strings\n\tcz.style.left = leftPos + \"px\";\n\tcz.style.top = topPos + \"px\";\n}", "screenWrap(XorY){\n \n if (XorY!='y'){\n if (this.pv.x < 0) this.pv.x = width;\n if (this.pv.x > width) this.pv.x = 0;\n }\n \n if (XorY!='x'){\n if (this.pv.y < 0) this.pv.y = height;\n if (this.pv.y > height) this.pv.y = 0;\n }\n \n \n }", "goRight(){\n gpio.write(this.motors.leftFront, true);\n }", "leftTurn() {\r\n this.fltire.rotateY(16);\r\n this.frtire.rotateY(16);\r\n }", "resetPosition() {\n //\"Spring\" into position\n Animated.spring(this.state.position, {\n toValue: { x: 0, y: 0 }\n }).start();\n }", "resetCanvas() {\n this.positions = this.calcSizeAndPosition();\n }", "moveToRight() {\r\n if (this.carGroup.position.x > 41) {\r\n return;\r\n } else {\r\n this.carGroup.translateZ(21);\r\n console.log(this.carGroup.position);\r\n }\r\n }", "Reset() {\n ui.Reset();\n\n pipeMan.Reset();\n state.Reset();\n scoreText.SetScore(0);\n\n player.Reset();\n player.StartScreenBob();\n\n //reset tiled bg\n bg.tilePositionX = 0;\n ground.tilePositionX = 0;\n }", "_moveRightInfinity() {\n if (!this._settings.infinity) return;\n\n this._currentPosition = 0;\n this._itemsHolder.style.transition = `transform ${ 0 }ms`;\n this._offset = this._calcDisplayedItemsTotalWidth() -\n (this._settings.neighborsVisibleWidth + this._calcOppositeRight());\n this._itemsHolder.style.transform = `translateX(${ this._offset + this._settings.oppositeSideAppearShift }px)`;\n setTimeout(() => this._moveRight(), this._settings.oppositeSideAppearDelay);\n }", "function moveRight() {\n var grid = null;\n for(grid of GameData.activePiece.getOrientation()) {\n GameData.mainPlayField.setBlock(\n GameData.row + grid.getRow(),\n correctColumn(GameData.column + grid.getColumn()),\n 0\n );\n }\n\n GameData.column = correctColumn(GameData.column + 1);\n\n var grid = null;\n for(grid of GameData.activePiece.getOrientation()) {\n GameData.mainPlayField.setBlock(\n GameData.row + grid.getRow(),\n correctColumn(GameData.column + grid.getColumn()),\n GameData.activePiece.getType()\n );\n }\n}", "function setPos()\n {\n vm.moverStyle.left = vm.themeStyle.left;\n vm.moverStyle.top = vm.themeStyle.top;\n vm.moverStyle.display = vm.themeStyle.display;\n }", "shiftRight() {\n for (let line of this.cells) {\n for (let i = line.length - 1; i > 0; i--) {\n line[i].setType(line[i - 1].type);\n }\n line[0].setType(BeadType.default);\n }\n }", "_onRightClick() {\n this.move({\n x: -this.tabListScrollEl.clientWidth,\n force: true\n });\n this.stop({\n type: 'force'\n });\n }", "home() {\n this.setXY(0, 0);\n this.setHeading(0);\n }", "reset () {\n this.y = this.startingY;\n this.x = this.startingX;\n }", "function moverobotRight () {\n var pos = robotObj[0].offsetLeft;\n if (pos >= 700) {\n console.log(pos);\n pos = 600;\n }\n pos += 100;\n robotObj[0].style.left = pos + 'px';\n}", "clear()\r\n {\r\n // shifting the line to a point outside of the page so that it does not show anymore\r\n this.position.x = -5000;\r\n this.position.y = -5000;\r\n }", "function onMoveLeft(evt){\n\t\t\troote.box.x -=20;\n\t\t}", "function viewReset(){\n\tcamera.position.set(0, 0 , 100);\n \tcamera.rotation.set(0, 0, 0);\n\tcontrols.update();\n // reset the view\n }", "function pushRight(newView) {\n showView(newView, offRight, offLeft, onHorizontal)\n}", "function userRight() {\n if (!isStopped) {\n FallingShape.moveRight();\n drawGame();\n }\n }", "function removeAbsolutePosition() {\n userBar.classList.remove(\"position-absolute\");\n userBar.style.right = \"0px\";\n}", "restart() {\n this.y = this.startY;\n this.x = this.startX;\n }", "rewind() {\n\t\t\t\tthis.frame = 0;\n\t\t\t}", "function reset(){\n animate = false;\n if ((cur === 0 || cur === n - beforeN)) {\n cur = beforeN;\n $(element).css({\"margin-left\": -cur * w});\n }\n o.endChange(log);\n }", "update() {\n this.x -= TIMESTEP;\n\n this.topPillar.style.left = `${this.x}px`;\n this.bottomPillar.style.left = `${this.x}px`;\n }", "function resetElementPosition(element) {\n element.style.top = 0;\n element.style.left = 0;\n element.style.bottom = \"\";\n element.style.right = \"\";\n }", "async resetRocket() {\n this.alpha = 0;\n this.tl.pause();\n this._animationIsPlaying = false;\n\n this.emit(Rocket.events.RESET);\n }" ]
[ "0.6173469", "0.6103775", "0.5943016", "0.5942402", "0.5887538", "0.5866031", "0.5851446", "0.58292437", "0.58265144", "0.58246547", "0.57269925", "0.5721054", "0.57131195", "0.56995267", "0.5698791", "0.5681899", "0.56653696", "0.56651616", "0.5662634", "0.56585705", "0.5638434", "0.5636162", "0.56268865", "0.5618534", "0.56128496", "0.5610286", "0.5600982", "0.55823606", "0.5562044", "0.55488795", "0.55228645", "0.55039036", "0.55001134", "0.5494704", "0.5493812", "0.54923934", "0.54908717", "0.547179", "0.54700255", "0.5468934", "0.54659176", "0.5438812", "0.5433967", "0.5428822", "0.5426729", "0.5417556", "0.54083675", "0.54019254", "0.53945446", "0.53859115", "0.5380724", "0.53683484", "0.53633344", "0.5342238", "0.53399265", "0.53363997", "0.5332436", "0.5328911", "0.5323265", "0.5321133", "0.531041", "0.5308367", "0.5305165", "0.52914786", "0.5285969", "0.52787894", "0.5268218", "0.52678806", "0.52662975", "0.52662164", "0.5259393", "0.52553195", "0.52553195", "0.5252217", "0.5252134", "0.5251313", "0.5250152", "0.5249763", "0.5248861", "0.5242349", "0.5239042", "0.52376735", "0.5233776", "0.5232236", "0.5229253", "0.5217284", "0.52153563", "0.52133614", "0.5209308", "0.5206945", "0.5204078", "0.5202114", "0.51972914", "0.5178284", "0.51745546", "0.51732016", "0.51692796", "0.51690024", "0.5164754", "0.5163234" ]
0.64159757
0
finds all Cool program sources referenced in elements and returns them asynchonously via the completedCallback
function GetReferencedCoolSources(completedCallback) { // get all <script> elements of type "text/cool" and get the script's source as a string var coolProgramReferences = document.querySelectorAll('script[type="text/cool"]'); var coolPrograms = []; for (var i = 0; i < coolProgramReferences.length; i++) { var filename = coolProgramReferences[i].attributes['src'].value; // call a separate function here to avoid closure problem getCoolProgramText(i, filename); } function getCoolProgramText(index, filename) { makeAjaxRequest(filename, function (responseText) { coolPrograms[index] = ({ filename: filename, program: responseText }); // if all ajax calls have returned, execute the callback with the Cool source if (coolPrograms.length == coolProgramReferences.length) { completedCallback(coolPrograms.map(function (x) { return x.program; })); } }); } // generic function to make AJAX call function makeAjaxRequest(url, successCallback, errorCallback) { var xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function () { if (xmlhttp.readyState == XMLHttpRequest.DONE) { if (xmlhttp.status == 200) { successCallback(xmlhttp.responseText); } else { if (errorCallback) { errorCallback(); } } } }; xmlhttp.open('GET', url, true); xmlhttp.send(); } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function findSourceResources(aSelectorFn) {\n result=[];\n //print(ttl + \"..findSourceResources() \" + \"from settings.svrURL: \" + settings.svrURL + \"/@resources\\n\" +\n // \"...using settings.intToken: \" + JSON.stringify(settings.intToken));\n var resourceNamesString = listenerUtil.restGet(\n settings.svrURL + \"/v1/@resources\", null, settings.intToken);\n var resourceNames = JSON.parse(resourceNamesString);\n // print(ttl + \"..resourceNames[]: \" + JSON.stringify(resourceNames));\n for (var i = 0 ; i < resourceNames.length ; i++) {\n var eachResourceSummary = resourceNames[i];\n var eachResourceDef = common_iPack_util.getResourceNamed(eachResourceSummary.name);\n var extProps = eachResourceDef.extendedProperties;\n var hasExtProps = extProps && 'object' === typeof extProps && ! Array.isArray(extProps);\n var syncProps = null;\n if (hasExtProps) {\n syncProps = extProps[settings.sourceResourceExtPropName];\n }\n // on post to ProcessRequestResource, store json into SystemQueue, for async processing via timer\n if (syncProps !== null && typeof syncProps !== 'undefined') {\n if (aSelectorFn(eachResourceDef))\n result.push(eachResourceDef);\n } else {\n // print(ttl + \" not processed: \" + JSON.stringify(eachResourceDef));\n }\n }\n return result;\n}", "get sources() {\n const sources = []\n for (let i = 0; i < this._sections.length; i++) {\n for (let j = 0; j < this._sections[i].consumer.sources.length; j++) {\n sources.push(this._sections[i].consumer.sources[j])\n }\n }\n return sources\n }", "async compileAll() {\n await this.init();\n\n this.collectedComponents = new Map;\n this.componentsList = this.components.componentsList;\n this.attributesList = this.attributes.attributesList;\n this.bulkAttributesList = this.attributes.bulkAttributesList;\n\n for (let selector in this.componentsList) {\n let component = this.componentsList[selector];\n\n this.collectedComponents.set(selector, component);\n }\n\n globalize('attributesList', this.attributesList);\n globalize('bulkAttributesList', this.bulkAttributesList);\n globalize('collectedComponents', this.collectedComponents);\n return this.startCompiling();\n }", "[loadAllSource]() {\n let ret = [];\n let test = {};\n // dump static html files\n let sopt = this[config].format({\n flag: false,\n dir: 'DIR_SOURCE',\n sub: 'DIR_SOURCE_SUB'\n });\n ret.push(...this[loadSource](sopt,test));\n // dump server template files\n let topt = this[config].format({\n flag: true,\n dir: 'DIR_SOURCE_TP',\n sub: 'DIR_SOURCE_TP_SUB'\n });\n ret.push(...this[loadSource](topt,test));\n // ensure all resource loaded\n Promise.all(ret).then(() => {\n this.emit('done');\n });\n }", "mainPageCheerio(data) {\n return new Promise((resolve, reject) => {\n const $ = cheerio.load(data);\n const arr = [];\n $('a', '.browseAirlines').each((i, e) => {\n const item = $(e).attr('href');\n arr.push(item);\n });\n resolve(arr);\n });\n }", "async function getAutocomplete() {\n const frame = document.querySelector('iframe[title=\"Share with others\"');\n const doc = frame.contentDocument;\n\n const acRows = doc.querySelectorAll('.ac-row');\n let results = [];\n\n console.log(acRows)\n\n for (let res of acRows) {\n results.push(res.textContent);\n }\n\n return results; \n}", "function gatherResearchPapers(callback){\r\n $.getJSON(GITHUB_RESEARCH, function(data){\r\n \r\n research = data.filter(function(item){\r\n if (item.name != \"readme.json\"){\r\n return item;\r\n }\r\n });\r\n $.getJSON(GITHUB_RESEARCH_INFO, function(data){\r\n research_description = data;\r\n return callback();\r\n })\r\n });\r\n}", "async function automateScrapes() {\n const cities = ['ATX', 'SFO', 'NYC', 'LAX', 'CHI'];\n return Promise.all(cities.map(async city => getScrapedArtists(city)));\n}", "function availableSources(kind) {\t\n var sources = $.Sources[kind];\n return _.compact(_.map(sources, function(source) {\n //if (source.available) return sourceMapping(source);\n \treturn sourceMapping(source);\n }));\n }", "function gotSources(xmlDoc)\n{\n var\tcitForm\t = document.citForm;\n\n // get the name of the associated select element\n var nameElts\t= xmlDoc.getElementsByTagName('name');\n var\tname\t\t= '';\n if (nameElts.length >= 1)\n {\t\t// name returned\n\t\tname\t= nameElts[0].textContent;\n }\t\t// name returned\n else\n {\t\t// name not returned\n\t\talert(\"editCitation.js: gotSources: name value not returned from getSourcesXml.php\");\n\t\treturn;\n }\t\t// name not returned\n\n // get the list of sources from the XML file\n var newOptions\t= xmlDoc.getElementsByTagName(\"source\");\n\n // locate the selection item to be updated\n var\telt\t\t= citForm.elements['IDSR'];\n var\toldValue\t= elt.options[elt.selectedIndex].value;\n elt.options.length\t= 0;\t// purge old options\n\n // add the options to the Select\n for (var i = 0; i < newOptions.length; ++i)\n {\t\t// loop through source nodes\n\t\tvar\tnode\t= newOptions[i];\n\n\t\t// get the text value to display to the user\n\t\tvar\ttext\t= node.textContent;\n\n\t\t// get the \"value\" attribute\n\t\tvar\tvalue\t= node.getAttribute(\"id\");\n\t\tif ((value == null) || (value.length == 0))\n\t\t{\t\t// cover our ass\n\t\t value\t\t= text;\n\t\t}\t\t// cover our ass\n\n\t\t// create a new HTML Option object and add it to the Select\n\t\toption\t= addOption(elt,\n\t\t\t\t\t text,\n\t\t\t\t\t value);\n\t\tif (value == oldValue)\n\t\t elt.selectedIndex\t= i;\t\n }\t\t// loop through source nodes\n\n}", "async sources({sources, options}) {\n const compilation = await run(sources, normalizeOptions(options));\n return compilation.contracts.length > 0\n ? {compilations: [compilation]}\n : {compilations: []};\n }", "function getSources() {\n var checkboxes = document.getElementsByName('source');\n for (var i = 0; i < checkboxes.length; i++) {\n if (checkboxes[i].checked) {\n sources.push(checkboxes[i].id);\n }\n }\n}", "findElements() {\r\n return __awaiter(this, void 0, void 0, function* () {\r\n const es = [];\r\n const ids = yield this.findElementIds();\r\n ids.forEach(id => {\r\n const e = new Element(this.http.newClient(''), id);\r\n es.push(e);\r\n });\r\n return es;\r\n });\r\n }", "onSourceLoad(){\n let elements = RVRreport.queryElements(this.document);\n if(elements != null){\n elements.forEach(el=>RVRreport.elementDetection(el));\n }\n }", "function extract_data(url,cbk){\n\n\n\tvar data = []\n\n\tvar extractors = [ext_microtada,ext_jsonld];\n\t \n\tvar promises = extractors.map(function(extractor) {\n\n\t return new Promise(function(resolve, reject) {\n\n\t \textractor.extract(url,(cartelera)=>{\n\t \t\tdata = data.concat(cartelera)\n\t\t\tresolve();\n\t\t})\t\t\n\t \n\t });\n\t\n\t});\n\n\tPromise.all(promises).then(function() { \n\t\tconsole.log(\"termino todo\")\n\t\t cbk(data) \n\t\t\t \n\t})\n\t.catch(console.error);\n\n\n \n}", "async function getVideoSources() {\n // Will return all the sources to captuer from\n const inputSources = await desktopCapturer.getSources({\n types: ['window', 'screen']\n });\n\n // To build \"select source\" menu\n const videoOptionsMenu = Menu.buildFromTemplate(\n\n // Using map function to destructure the list of sources found before\n inputSources.map(source => {\n return {\n label: source.name,\n click: () => selectSource(source)\n };\n })\n );\n \n //for menu popup\n videoOptionsMenu.popup();\n\n }", "function scripts(urls, callback) {\n if (urls.length === 0) {\n callback();\n } else {\n var loaded = 0,\n output = [];\n\n for (var i = 0; i < urls.length; i++) {\n var url = urls[i],\n moduleBuffer = getModuleBuffer(url);\n\n moduleBuffer.buffer(function() {\n loaded++;\n if (loaded === urls.length && typeof callback === \"function\") {\n callback();\n }\n });\n\n output.push(moduleBuffer);\n }\n return output;\n }\n }", "function getScripts() { // runs in the web page\n var scriptElements = document.querySelectorAll('script');\n var scripts = [];\n for(var i = 0; i < scriptElements.length; i++) {\n var elt = scriptElements[i];\n console.log(\"scripts[\"+i+\"/\"+scriptElements.length+\"] \"+elt.src);\n scripts.push({\n src: elt.src,\n textContent: elt.textContent\n });\n }\n return scripts;\n }", "function collectCrystals() {\n collected = [];\n newArr = [];\n for(k=1; k<5; k++){ \n var gemIter = $(\"#gem-\" + k);\n if(gemIter.attr(\"data-clicked\") == 1) {\n var src = gemIter.attr(\"src\");\n var style = gemIter.attr(\"style\");\n newArr.push([src,style]); \n } \n }\n collected.push(newArr);\n printCollected(collected);\n }", "function checkForSourceFound() {\n setTimeout(() => {\n let htmlLoaded = true\n for (j =j; j < HTMLFound.length; j++) {\n if (eval('HTMLFound[\\'<{src}>\\']') === false) {\n htmlLoaded = false, checkForSourceFound();\n break;\n }\n }\n if (htmlLoaded === true) {\n superScope.addEvent('click', (e) => {\n e.preventDefault();\n $('#<{containerid}>').fadeOut(0, () => {\n const setContainerHTMLScript = `document.getElementById('<{containerid}>').innerHTML = storedHTML[\"<{src}>\"]`;\n eval(setContainerHTMLScript);\n $(document).trigger('domChanged');\n const scriptTags = eval(`document.getElementById('<{containerid}>')`).getElementsByTagName('script');\n for(var i = 0; i < scriptTags.length; i++) eval (scriptTags[i].innerHTML);\n\n $('#<{containerid}>').fadeIn(parseInt('<(fadeTime)>'), () => {\n });\n\n });\n });\n }\n\n }, 20)\n }", "async function showSources() {\n try {\n const sourceObject = await networkApi('GET', baseApiKey + 'news/sources');\n if (sourceObject.Error != null) {\n errorMsg(sourceObject.Error);\n errorMsg('Error Loading Sources', $('#asideSources'));\n $('#sourcesList').html('<select><option>Not Loaded</option></select>');\n return;\n }\n const htmlString = getSourceHtml(sourceObject);\n $('#asideSources').html(htmlString);\n generateSourceList(sourceObject);\n }\n catch (err) {\n return errorMsg('Error retrieving sources from server.');\n }\n}", "function getAllMedia(){\n var requestSync = require('sync-request');\n\n var mountPoints = Array();\n \n for(var i = 0; i < urls.length; i++){\n try{\n var result = requestSync('GET', urls[i]+\"/status2.xsl\").getBody().toString();\n \n var xslAux = result.substring(result.indexOf(\"<pre>\") + 5, result.indexOf(\"</pre>\"));\n var xsl = xslAux.substring(xslAux.indexOf(\"Source: \") + 8).split(\"\\n\");\n \n if(xsl.length > 1){\n var data = xsl[1].split(\",\");\n \n for(var j = 0; j < data.length - 1; j=j+6){\n var mountPointUrl = urls[i]+data[j+0];\n var mountPountListeners = data[j+3];\n mountPoints.push([mountPointUrl, mountPountListeners]);\n }\n }else{\n console.log(\"The XSL structure from \"+urls[i]+\"/status2.xsl is incorrect\");\n }\n }catch(e){\n console.log(\"EXCEPTION: \" + e);\n }\n }\n \n return mountPoints;\n}", "async findAllResources() {\n var t = this;\n var db = this.__db;\n if (!db.resources) {\n db.resources = {};\n }\n t.__librariesByResourceUri = {};\n this.__allResourceUris = null;\n this.__assets = {};\n\n await qx.Promise.all(\n t.__analyser.getLibraries().map(async library => {\n var resources = db.resources[library.getNamespace()];\n if (!resources) {\n db.resources[library.getNamespace()] = resources = {};\n }\n var unconfirmed = {};\n for (let relFile in resources) {\n unconfirmed[relFile] = true;\n }\n\n const scanResources = async resourcePath => {\n // If the root folder exists, scan it\n var rootDir = path.join(\n library.getRootDir(),\n library.get(resourcePath)\n );\n\n await qx.tool.utils.files.Utils.findAllFiles(\n rootDir,\n async filename => {\n var relFile = filename\n .substring(rootDir.length + 1)\n .replace(/\\\\/g, \"/\");\n var fileInfo = resources[relFile];\n delete unconfirmed[relFile];\n if (!fileInfo) {\n fileInfo = resources[relFile] = {};\n }\n fileInfo.resourcePath = resourcePath;\n fileInfo.mtime = await qx.tool.utils.files.Utils.safeStat(\n filename\n ).mtime;\n\n let asset = new qx.tool.compiler.resources.Asset(\n library,\n relFile,\n fileInfo\n );\n\n this.__addAsset(asset);\n }\n );\n };\n\n await scanResources(\"resourcePath\");\n await scanResources(\"themePath\");\n\n // Check the unconfirmed resources to make sure that they still exist;\n // delete from the database if they don't\n await qx.Promise.all(\n Object.keys(unconfirmed).map(async filename => {\n let fileInfo = resources[filename];\n if (!fileInfo) {\n delete resources[filename];\n } else {\n let stat = await qx.tool.utils.files.Utils.safeStat(filename);\n if (!stat) {\n delete resources[filename];\n }\n }\n })\n );\n })\n );\n\n await qx.tool.utils.Promisify.poolEachOf(\n Object.values(this.__assets),\n 10,\n async asset => {\n await asset.load();\n let fileInfo = asset.getFileInfo();\n if (fileInfo.meta) {\n for (var altPath in fileInfo.meta) {\n let lib = this.findLibraryForResource(altPath);\n if (!lib) {\n lib = asset.getLibrary();\n }\n let otherAsset =\n this.__assets[lib.getNamespace() + \":\" + altPath];\n if (otherAsset) {\n otherAsset.addMetaReferee(asset);\n asset.addMetaReferTo(otherAsset);\n } else {\n qx.tool.compiler.Console.warn(\n \"Cannot find asset \" + altPath + \" referenced in \" + asset\n );\n }\n }\n }\n if (fileInfo.dependsOn) {\n let dependsOn = [];\n fileInfo.dependsOn.forEach(str => {\n let otherAsset = this.__assets[str];\n if (!otherAsset) {\n qx.tool.compiler.Console.warn(\n \"Cannot find asset \" + str + \" depended on by \" + asset\n );\n } else {\n dependsOn.push(otherAsset);\n }\n });\n if (dependsOn.length) {\n asset.setDependsOn(dependsOn);\n }\n }\n return null;\n }\n );\n }", "getCoffeeSources() {\r\n\t\r\n }", "searchPrinters(callback) {\n\n\n /**\n * the printers object, that will be returned\n * structure\n * @type {}\n * @structure:\n *\n * {\n * network: [\n * {\n * uri: \"dnssd://Brother%20HL-5270DN%20series._pdl-datastream._tcp.local./?bidi\",\n * uri_decoded: \"dnssd://Brother HL-5270DN series._pdl-datastream._tcp.local./?bidi\",\n * protocol: dnssd,\n * name: \"Brother HL-5270DN series\"\n * },\n * {\n * uri: \"dnssd://Brother%20HL-2030._pdl-datastream._tcp.local./?bidi\",\n * uri_decoded: \"dnssd://Brother HL-2030._pdl-datastream._tcp.local./?bidi\",\n * protocol: dnssd,\n * name: \"Brother HL-2030\"\n * }\n * ],\n * direct: []\n * }\n *\n */\n let objPrintersToReturn = {};\n\n\n /**\n * define command to discover devices\n * lpinfo:\n *\n * lists the available devices or drivers known to the CUPS server. The first form\n * (-m) lists the available drivers, while the second form (-v) lists the available\n * devices.\n */\n let cmd = `lpinfo -v`;\n\n // run the find command, to disconver devices\n var child_process = exec(cmd, (error, stdout, stderr)=> {\n\n if (error) {\n callback(error, null);\n }\n\n\n // verify output to UTF-8\n stdout = stdout.toString('utf8');\n\n // split the stdout into an array, by finding new lines\n let lines = stdout.split(/\\r\\n|[\\n\\r\\u0085\\u2028\\u2029]/g);\n\n\n if (!_.isArray(lines)) {\n\n return callback(null, objPrintersToReturn);\n\n }\n\n // iterate over this array\n _.forEach(lines, (item, key)=> {\n if (item && item != \"\" && item != \" \") {\n let arrItem = item.split(\" \");\n if (_.isArray(arrItem)) {\n\n let type = arrItem[1];\n let protocol = arrItem[0];\n\n\n if (_.indexOf(PrinterManager.getIgnoredDevices(), type) === -1) {\n\n if (!_.isArray(objPrintersToReturn[protocol])) {\n objPrintersToReturn[protocol] = [];\n }\n\n //let rx = /(^([a-zA-Z]*)\\:\\/\\/)(.*)/gmi;\n let rx_type = /(^([a-zA-Z].*)\\:\\/\\/)/gmi;\n\n let rx_usb = /(usb:\\/\\/)(.*)(\\/)(.*)(\\?)(.*)/gmi;\n let rx_network = /\\/\\/(.*?)\\._/gmi;\n\n let uri = type;\n\n\n let uri_decoded = decodeURIComponent(type);\n\n\n let regexed_type = rx_type.exec(uri_decoded);\n let connection_type = \"\"\n if (Array.isArray(regexed_type) && regexed_type[2]) {\n connection_type = regexed_type[2]; // usb|socket|dnssd|...\n }\n\n\n let model = \"\";\n let make = \"\";\n\n if (connection_type == \"usb\") {\n\n\n let regexed_usb = rx_usb.exec(uri_decoded);\n\n\n if (Array.isArray(regexed_usb) && regexed_usb[2] && regexed_usb[4]) {\n model = regexed_usb[2] + \" \" + regexed_usb[4];\n } else {\n model = \"unknown\";\n }\n\n\n } else {\n\n let regexed_network = rx_network.exec(uri_decoded);\n\n if (Array.isArray(regexed_network) && regexed_network[1]) {\n model = regexed_network[1];\n } else {\n model = \"unknown\";\n }\n\n\n }\n\n\n let name = \"\";//regexed[3] || \"no name\";\n\n\n let params = {\n uri: type,\n uri_pretty: uri_decoded,\n protocol: connection_type,\n //make: make,\n model: model\n }\n\n\n objPrintersToReturn[protocol].push(new InstallablePrinter(params))\n }\n }\n\n }\n\n })\n\n\n callback(null, objPrintersToReturn);\n\n });\n\n\n }", "parseManifest (items, callback) {\n\n async.parallel([\n\n (parallelCallback) => {\n\n var svf = this.filterItems(items, '.*\\\\.svf$');\n\n async.map (svf, (item, mapCallback) => {\n\n this.readSvfItem(item, mapCallback)\n\n }, (err, uris) => {\n\n if(err) {\n\n parallelCallback(err, null)\n\n } else {\n\n var out = [];\n out = out.concat.apply(out, uris);\n parallelCallback(null, out);\n }\n })\n },\n\n (parallelCallback) => {\n\n var f2d = this.filterItems(items, '.*\\\\.f2d$');\n\n async.map (f2d, (item, mapCallback) => {\n\n this.readF2dfItem(item, mapCallback)\n\n }, (err, uris) => {\n\n if(err) {\n\n parallelCallback(err, null)\n\n } else {\n\n var out = [];\n out = out.concat.apply(out, uris);\n parallelCallback(null, out);\n }\n })\n },\n\n (parallelCallback) => {\n\n var manifest = this.filterItems(items, '.*manifest\\\\.json\\\\.gz$');\n\n async.map (manifest, (item, mapCallback) => {\n\n this.readManifest(item, mapCallback)\n\n }, (err, uris) => {\n\n if(err) {\n\n parallelCallback(err, null)\n\n } else {\n\n var out = [];\n out = out.concat.apply(out, uris);\n parallelCallback(null, out);\n }\n })\n }\n ],\n\n (err, uris) => {\n\n if(err) {\n\n callback(err, null)\n\n } else {\n\n var out = items;\n out = out.concat.apply(out, uris);\n callback(null, out);\n }\n })\n }", "async function loadSources() {\n let res = await fetch(\"./sources.json\");\n let json = await res.json();\n return json;\n}", "async function list() {\n const urls = itemize('https://nodebin.herokai.com/', { depth: 3, query: true })\n while (!urls.done()) {\n console.log(await urls.next())\n }\n}", "async function requiredSources(config) {\n return new Promise((resolve, reject) => {\n Profiler.required_sources(config, (err, sources) => {\n err ? reject(err) : resolve(sources);\n });\n });\n}", "addSources(contents) {}", "function getAllItems() {\n // load query details to json object\n var oWebsite = context.get_web();\n context.load(oWebsite);\n var tasksEntries = [];\n\n context.executeQueryAsync(function () {\n\n var itemsCount = collListItem.get_count();\n for (var i = 0; i < itemsCount; i++) {\n var item = collListItem.itemAt(i);\n var taskEntry = item.get_fieldValues();\n\n taskEntry.SourceURL = context.get_web().get_serverRelativeUrl() + \"/Lists/\" + options.listName + \"/\" + taskEntry.DocumentName;\n tasksEntries.push(helperService.parse(taskEntry, options.fields.mappingFromSP));\n\n }\n\n deferred.resolve(tasksEntries);\n\n\n });\n\n\n\n }", "function fetchNodes(){\n // return a promise since these calls will be asynchronous\n return new Promise((success, failure) => {\n Cosmic.getObjects(config.cosmicjs, (error, result) =>{\n if (error){\n failure(error); // something went wrong\n } else {\n // there was a response so let's see if the data we are looking for exists\n let rawNodes = null;\n\n try {\n rawNodes = result.objects.type.nodes;\n } catch (e){\n console.error('[fetch]', 'unable to process Nodes.');\n failure(e);\n }\n\n // lets see if we got the array we were looking for\n if (Array.isArray(rawNodes)){\n\n // it's an array of data -> let's filter it\n console.log(LOG_NAME, `Filtering (${ rawNodes.length }) fetched Nodes`, '...');\n\n /* So now we have the Nodes, now we need to put them through a filter to remove the bulk\n let's filter out the Nodes that have a 'status' of 'published', as well\n and only allow what's specified in the config 'NodeWhiteList' */\n\n let extractedLocales = {}; // setup object container for storing the extracted locale names\n\n let filteredNodes = utils.matchesFromObjectArray(rawNodes, 'status', 'published', { whitelist: config.fetch.NodeWhiteList, custom: (node) => {\n // extract the locale name and register it's key to the extracted locales.\n extractedLocales[node.locale] = true;\n return node; // return the node.\n }});\n\n extractedLocales = Object.keys(extractedLocales); // convert the object to a simple array of registered keys\n\n console.log(LOG_NAME, `(${ rawNodes.length }) Nodes remain after filtration`);\n console.log(LOG_NAME, `Detected (${ extractedLocales.length }) locales`, (extractedLocales.length > 0) ? extractedLocales : '>>NO LOCALES DETECTED!<<');\n\n /* We now have a minimized array only containing the whitelisted content. Be we aren't done yet.\n Now we need to strip each Node so it has DOM-safe markup, which is specified in the config\n 'NodeAllowedTags'\n\n But because we are busy people (and don't want to wait forever) we will condense the language sorting\n and content striping into a singular loop\n\n THE LOCALE MUST BE SET. ANY NODES WITHOUT A LOCALE WILL BE IGNORED! */\n\n let languageContainer = {}; // the object we will be cloning items into\n\n let localeString,\n i = extractedLocales.length;\n\n while (i--){\n localeString = extractedLocales[i];\n\n languageContainer[localeString] = {}; // initialize a new sub container for the locale.\n\n // look for all nodes with a matching locale string, remove it's locale and sanitize it's content\n utils.matchesFromObjectArray(filteredNodes, 'locale', localeString, {\n custom: node => {\n // push the new node to the container object (while also only using whitelisted elements)\n languageContainer[localeString][node.slug] = striptags(node.content, config.fetch.NodeAllowedTags);\n\n return node;\n }\n })\n }\n\n (() => {\n // logger function that returns the list of keys\n let localeKeys = extractedLocales,\n localeNode,\n i = localeKeys.length;\n\n if (i > 0) {\n // list through each locale\n while (i--) {\n localeNode = localeKeys[i];\n console.log(LOG_NAME, `[${ localeNode }] with (${ Object.keys(languageContainer[localeNode]).length }) registered Nodes`);\n }\n } else {\n // print error\n console.error(LOG_NAME,\n 'NO REGISTERED LANGUAGE DATA. Please verify that Cosmic JS data has \"status\" of \"published\", as well as \"locale\"');\n console.log('First Node fetched by server:\\n', rawNodes[0])\n }\n })();\n\n // by now we should have an awesome array of content\n success(languageContainer); // pass the data to the success Promise return\n\n } else {\n console.error(LOG_NAME, 'Node data does not exist');\n failure(new Error('Node data does not exist'));\n }\n }\n });\n });\n}", "getJavascriptFiles(startPath,filter,callback){\n const self = this;\n if(self.getterIsExtracted()){ // If extraction is successful\n if (!fs.existsSync(startPath)){ // If path does exist\n console.log(\"no dir \",startPath);\n return;\n }\n const files = fs.readdirSync(startPath);\n for(let i = 0; i < files.length; i++){\n const filename=path.join(startPath,files[i]);\n const stat = fs.lstatSync(filename);\n if (stat.isDirectory()){\n this.getJavascriptFiles(filename,filter,callback); //recursive function\n }\n else if (filter.test(filename)) callback(filename);\n }\n\n this.directory.length > 0 && self.setterIsHybrid(true);\n }\n }", "function getActiveSources(bases) {\n var sources = [];\n bases.forEach((base) => {sources = sources.concat(base.getSources())});\n return sources;\n}", "hasContentsOfAllSources() {\n return this._sections.every(function (s) {\n return s.consumer.hasContentsOfAllSources()\n })\n }", "async function scrape (html,blockElement){\n let resultsArray = [] //create a results array to store the list of elements found\n await $(blockElement, html).each(function() {//searches for all occurances of the block element with the html then iterates through them.\n resultsArray.push($(this).text()); //gets the text found in this block tag and then pushes it to the results array\n });\n return await resultsArray //returns the results \n}", "function searchPolyModels (value)\n{\n console.log(\"working with require should work\")\n var items;\n\n Promise.all([\n // google has a limit fo max 10 result per call :/\n // so we do 3 api calls and merge the results into one\n callSearchApi(1, value),\n callSearchApi(11, value),\n callSearchApi(21, value)\n ]).then(function (results) {\n return results[0].items.concat(results[1].items).concat(results[2].items)\n }).then(function (results) {\n\n items = results.map(function (item_) {\n return {\n title: item_.title + ' by ' + item_.author,\n thumb: item_.image,\n url: item_.url,\n author: item_.author\n }\n })\n\n itemList = items;\n\n\n var dropdownImages = document.getElementById(\"image-dropdown\");\n emptyDropdownList();\n\n\n items.forEach(function(_item, _index)\n {\n if(_index == 0)\n {\n dropdownImages.innerHTML +=\n \"<input type=\\\"radio\\\" name=\\\"line-style\\\" id=\\\"line\"+_index+\"\\\" onclick=\\\"onRadioButtonClick(this.value, this.id)\\\" value=\\\"\" +_index+\"\\\" /><label id=\\\"radioLabel\"+_index+\"\\\" for=\\\"line\"+_index+\"\\\" style=\\\"background-image: url(' \"+_item.thumb+\" '); background-size: 150px; \\\" src=\\\"img_logo.gif\\\" draggable=\\\"true\\\"\\n\" +\n \"ondragstart=\\\"drag(event)\\\"></label>\"\n\n }\n else\n {\n\n dropdownImages.innerHTML +=\n \"<input type=\\\"radio\\\" id=\\\"line\"+_index+\"\\\" name=\\\"line-style\\\" onclick=\\\"onRadioButtonClick(this.value, this.id)\\\" value=\\\"\" +_index+\"\\\" /><label id=\\\"radioLabel\"+_index+\"\\\" for=\\\"line\"+ _index+\"\\\" style=\\\"background-image: url(' \"+_item.thumb+\" '); background-size: 150px; \\\" src=\\\"img_logo.gif\\\" draggable=\\\"true\\\"\\n\" +\n \"ondragstart=\\\"drag(event)\\\"></label>\"\n\n }\n })\n\n itemList = items;\n }).catch(function (error) {\n console.error(error)\n // io3d.utils.ui.message.error('Sorry, something went wrong:\\n\\n' + JSON.stringify(error, null, 2))\n })\n\n\n}", "function getConversations(callback) {\n console.log(\"Attempt to find list of conversations\");\n let unames = [];\n let titles = [];\n try {\n let convos = document.querySelectorAll(\"ul[aria-label='Conversation list']\");\n\n // console.log(\"Found convos. \");\n // console.log(convos[0]);\n let nodes = convos[0].childNodes;\n // console.log(nodes);\n // console.log(\"Found child node convos\");\n for (let i = 0; i < nodes.length; i++) {\n let linkClass = nodes[i].querySelectorAll(\"a[role='link']\")[0]\n // console.log(linkClass);\n let convoLink = linkClass.getAttribute(\"data-href\");\n // console.log(convoLink);\n unames.push(getNameFromURL(convoLink));\n let convoTitle = linkClass.querySelectorAll('span')[0].innerText;\n titles.push(convoTitle)\n // console.log(convoTitle);\n }\n console.log(\"Parasite: Found \"+unames.length+\" convos.\");\n callback(unames, titles);\n } catch (err) {\n console.log(\"Error trying to find conversations: \\n\" + err);\n }\n\n}", "function getResources() { \n $.get(\"sources.json\", function(listFeeds) {\n var size = 0;\n listFeeds = listFeeds.slice(0, NEWS_LIMIT);\n size = listFeeds.length; \n \n showResources(listFeeds);\n fixVisualConfiguration(size);\n }).fail(function(data){\n console.log(\"Error: Is not a valid JSON\");\n }); \n}", "function fetchCiteprocJSONForSimpleWorks(simpleWorks, onDone){\n\t\tvar requests = [];\n\t\tsimpleWorks.forEach(function(obj){\n\t\t\tvar d = fetchCiteprocJSONForSimpleWork(obj);\n\t\t\trequests.push(d);\n\t\t});\n\t\t$.when.all(requests).done(onDone);\n\t}", "onRunComplete(browsers, results) {\n\n }", "function extract_WOTD_links( inputFilename ) {\n let ret = { src_text: null,\n word_id: null,\n target_audio_url: null,\n target_text: null,\n target_xlit: null,\n target_sentences: [],\n src_sentences: []\n }\n\n // ret: the return value, will gather fields as side-effects\n // along this run::\n\n let htmlString = fs.readFileSync(inputFilename,'utf8')\n\n let soup = new JSSoup(htmlString)\n\n{\n let eng = \"wotd-widget-sentence-quizmode-space-text big english\"\n let u = soup.findAll('div', eng )\n //for (const q of u)\n for (let i in u) {\n let q = u[i]\n let qq = q.contents[0]\n if (qq._text) {\n ret.src_text = qq._text\n }\n if (qq.contents) {\n let engText = (qq.contents[0].nextElement._text).trim()\n let engAudio = qq.contents[0].previousElement.attrs.href\n ret.src_sentences.push( {audio_url: engAudio,\n text: engText } )\n }\n }\n}\n\n{\n let target = \"wotd-widget-sentence-down-space-text\"\n let u = soup.findAll('div', target )\n for (let i in u) {\n let q = u[i]\n let targetAudio = q.nextElement.attrs.href\n ret.target_sentences.push({ audio_url: targetAudio,\n text: null, xlit: null })\n }\n}\n\n{\n let wordAudioClass = \"wotd-widget-sentence-main-space-sound jp-audio-track\"\n\n let u = soup.findAll('a', wordAudioClass)\n let targetWord_audioUrl = u[0].attrs.href\n ret.target_audio_url = targetWord_audioUrl\n}\n\n{\n let phraseTextClass = 'wotd-widget-sentence-main-space-text'\n let u = soup.findAll('span', phraseTextClass )\n for (let i in u) {\n let q = u[i]\n let targetText = q.contents[0]._text\n if (i == 0) {\n ret.target_text = targetText\n } else {\n ret.target_sentences[i-1].text = targetText\n }\n }\n}\n\n{\n let rom = \"wotd-widget-sentence-quizmode-space-text big romanization\"\n let u = soup.findAll('div', rom )\n for (let i in u) {\n let q = u[i]\n let romText = q.contents[0]._text\n if (i == 0) {\n ret.target_xlit = romText\n } else {\n ret.target_sentences[i-1].xlit = romText\n }\n }\n}\n {\n for (let i in ret.src_sentences) {\n // word_id_url := find first sentence with valid 'audio_url'\n let word_id_url = ret.src_sentences[i].audio_url\n if (0 == word_id_url.length ) {\n continue\n }\n ret.word_id = path.basename( url.parse(word_id_url).path , '.mp3')\n break\n }\n }\n return ret\n}", "function getAllUsedSites(callback) {\n res.eachCollection(\"rss-channels\").then(collections => {\n let promises = collections.map(col => col.find({}).toArray())\n\n Promise.all(promises).then(channels => {\n let allChannels = [].concat.apply([], channels)\n\n callback([].concat.apply([], allChannels.map(ch => ch.sites)).filter((elem, index, $this) => index === $this.indexOf(elem)))\n })\n })\n }", "async function scrapeLinesFromDaria() {\n if (characters.length) {\n let resp = await rp(`${base}/site/dariatranscripts`);\n let epUrls = [];\n let len = $('.topLevel > div > a', resp).length;\n\n for (let i = 0; i < len; i += 1) {\n epUrls.push($('.topLevel > div > a', resp)[i].attribs.href);\n }\n\n await getEps(epUrls);\n\n for (let character in chainObjTemp) {\n let cleanedArr = cleanArr(chainObjTemp[character]);\n let markovChain = makeChains(cleanedArr);\n let data = JSON.stringify(markovChain, null, 2);\n fs.writeFileSync(`${character}.json`, data, function(err) {\n if (err) throw err;\n });\n }\n \n return epUrls;\n }\n}", "function sources(){ // get all sources using existing session\n\treturn Promise.all([cookies, targetCollector]).then(function(args){\n\t\tvar cookies = args[0],\n\t\t collector = args[1],\n\t\t url = \"https://\"+apiUrl+\"collectors/\"+collector.id+\"/sources?limit=\"+pageLimit+\"&offset=0\",\n\t\t headers = new (fetch.Headers)()\n\t\tfor(var i in cookies){\n\t\t\theaders.append(\"cookie\", cookies[i])\n\t\t}\n\t\treturn fetch(url, {headers})\n\t})\n}", "getCombArray() {\n var urls = [];\n\n this.queue.getWithStatus(\"redirected\", function(err, items) {\n urls.push(items.url);\n });\n\n this.queue.getWithStatus(\"downloaded\", function(err, items) {\n urls.push(items.url);\n });\n\n return urls;\n }", "function getSourcesSync(push, next) {\n // Shadows the outer async variable.\n var asynchronous;\n var done = false;\n\n var pull_cb = function(err, x) {\n asynchronous = false;\n if (done) {\n // This means the pull was async. Handle like\n // regular async.\n srcPullHandler(push, next, self)(err, x);\n }\n else {\n if (err) {\n push(err);\n }\n else if (x === nil) {\n done = true;\n }\n else {\n srcs.push(x);\n srcsNeedPull.push(x);\n }\n }\n };\n\n while (!done) {\n asynchronous = true;\n self.pull(pull_cb);\n\n // Async behavior, record self as a src and return.\n if (asynchronous) {\n done = true;\n srcs.unshift(self);\n }\n }\n }", "function getSourcesSync(push, next) {\n // Shadows the outer async variable.\n var asynchronous;\n var done = false;\n\n var pull_cb = function(err, x) {\n asynchronous = false;\n if (done) {\n // This means the pull was async. Handle like\n // regular async.\n srcPullHandler(push, next, self)(err, x);\n }\n else {\n if (err) {\n push(err);\n }\n else if (x === nil) {\n done = true;\n }\n else {\n srcs.push(x);\n srcsNeedPull.push(x);\n }\n }\n };\n\n while (!done) {\n asynchronous = true;\n self.pull(pull_cb);\n\n // Async behavior, record self as a src and return.\n if (asynchronous) {\n done = true;\n srcs.unshift(self);\n }\n }\n }", "function getSourcesSync(push, next) {\n // Shadows the outer async variable.\n var asynchronous;\n var done = false;\n\n var pull_cb = function(err, x) {\n asynchronous = false;\n if (done) {\n // This means the pull was async. Handle like\n // regular async.\n srcPullHandler(push, next, self)(err, x);\n }\n else {\n if (err) {\n push(err);\n }\n else if (x === nil) {\n done = true;\n }\n else {\n srcs.push(x);\n srcsNeedPull.push(x);\n }\n }\n };\n\n while (!done) {\n asynchronous = true;\n self.pull(pull_cb);\n\n // Async behavior, record self as a src and return.\n if (asynchronous) {\n done = true;\n srcs.unshift(self);\n }\n }\n }", "function proj_load(cb) {\n axios.get(cfg.url+\"project/list\", axopt).then((resp) => {\n var d = resp.data;\n // debug && console.log(d);\n var arr = d.content.filter((p) => { return p.entryType == 'INTERNAL'; });\n // console.log(arr); // process.exit(1);\n debug && console.error(\"Fetch details on \"+arr.length+\" projects\");\n async.map(arr, projget, function (err, ress) {\n if (err) { console.error(\"Proj. details Error: \"+err); return cb(err, null); }\n debug && console.error(\"PROJECTS:\"+ JSON.stringify(ress, null, 2));\n // Call cb with ress.\n return cb(null, ress);\n });\n }).catch((ex) => {\n // console.log();\n console.error(\"RP proj. list Error: \"+ex);\n return cb(ex, null);\n });\n}", "function findLaunchTargets() {\n if (!vscode.workspace.rootPath) {\n return Promise.resolve([]);\n }\n const options = options_1.Options.Read();\n return vscode.workspace.findFiles(\n /*include*/ '{**/*.sln,**/*.csproj,**/project.json}', \n /*exclude*/ '{**/node_modules/**,**/.git/**,**/bower_components/**}', \n /*maxResults*/ options.maxProjectResults)\n .then(resources => {\n return select(resources, vscode.workspace.rootPath);\n });\n}", "loadResources() {\n lbs.loader.scripts = lbs.loader.scripts.filter(this.uniqueFilter)\n lbs.loader.styles = lbs.loader.styles.filter(this.uniqueFilter)\n lbs.loader.libs = lbs.loader.libs.filter(this.uniqueFilter)\n\n lbs.log.debug(`Scripts to load:${lbs.loader.scripts}`)\n lbs.log.debug(`Styles to load: ${lbs.loader.styles}`)\n lbs.log.debug(`Libs to load: ${lbs.loader.libs}`)\n\n $.each(lbs.loader.libs, (i) => {\n lbs.loader.loadScript(lbs.loader.libs[i])\n })\n\n $.each(lbs.loader.scripts, (i) => {\n lbs.loader.loadScript(lbs.loader.scripts[i])\n })\n\n $.each(lbs.loader.styles, (i) => {\n lbs.loader.loadStyle(lbs.loader.styles[i])\n })\n }", "function getSceneData(unprocessedLinks) {\n var xhrs = [];\n var totalCounter = 0;\n var processedCounter = 0;\n\n totalCounter = unprocessedLinks.length;\n\n var doProcess = true;\n\n console.log('unprocessedLinks.length: ' + totalCounter);\n\n if (doProcess) {\n $.each(unprocessedLinks, function (i, theUrl) {\n var xhr = $.ajax({\n url: theUrl,\n type: 'GET'\n }).done(function (data) {\n processedCounter = processedCounter + 1;\n var percentComplete = ((processedCounter / totalCounter) * 100).round() + '%';\n document.title = percentComplete + ' [' + processedCounter + '/' + totalCounter + ']';\n\n //Get a reference to the web page\n var $thePage = $(data);\n\n //Get the scene ID from the URL\n var theSceneId = theUrl.split('/')[7];\n\n var outputData = [\n theSceneId,\n\t\t\t\t\t'B',\n\t\t\t\t\t'Babes',\n\t\t\t\t\tgetReleaseDate($thePage),\n\t\t\t\t\tgetSceneTitle($thePage),\n\t\t\t\t\tgetSceneRating($thePage),\n\t\t\t\t\tgetPerformers($thePage),\n\t\t\t\t\tgetDescription($thePage),\n\t\t\t\t\tgetTags($thePage),\n\t\t\t\t\tgetLikes($thePage),\n\t\t\t\t\tgetViews($thePage),\n\t\t\t\t\ttheUrl\n ];\n\n var theData = outputData.join('\\t');\n\n //Append the data to the text file\n appendDataToTextFile(theData, 'data/babesData.txt');\n\n //Append the processed link to the \"processed links\" file\n appendDataToTextFile(theUrl, 'data/babesLinksProcessed.txt');\n }).fail(function () {\n console.log('FAIL!');\n });\n\n //console.log('finished [' + i + '/' + totalCounter + ']...');\n xhrs.push(xhr);\n });\n\n $.when.apply($, xhrs).done(function () {\n document.title = '!!-FINISHED-!!';\n console.log('==================================================================================');\n });\n }\n}", "async function getVideoSources() {\n const inputSources = await desktopCapturer.getSources({\n types: ['window', 'screen']\n });\n\n const videoOptionsMenu = Menu.buildFromTemplate(\n inputSources.map(source => {\n return {\n label: source.name,\n click: () => selectSource(source)\n };\n })\n );\n\n\n videoOptionsMenu.popup();\n}", "async function process1(start, params) {\n // console.log(params)\n let careerLink = params.joburl;\n let dataSet = await allLinksApi(careerLink);\n dataSet = JSON.parse(dataSet)\n let joburl = careerLink;\n let links = dataSet;\n if (dataSet.hasOwnProperty('success')) {\n links = dataSet.success\n }\n let domain = await domainGetter(joburl)\n if (domain.indexOf('workday') >= 0 || domain.indexOf('icims') >= 0)\n return links;\n let jobs = [],\n noJobs = [];\n await Promise.all(\n links.map(async data => {\n if (!endsWithUrl(data.Link)) {\n jobs.push(data)\n } else {\n noJobs.push(data)\n }\n })\n )\n // return {jobs,noJobs}\n let totalJobsCount = jobs.length,\n noJobsCount = noJobs.length,\n totalLinks = links.length\n let indexSelector = 1;\n if (totalJobsCount > 50) {\n indexSelector = Math.round(totalJobsCount / 50);\n if (indexSelector <= 1) {\n indexSelector = 2\n }\n };\n console.log(\"jobs..............................\")\n console.log(jobs)\n var jobUrls = _.uniq(_.map(jobs, 'Link'));\n console.log(\"joburls.................................\");\n console.log(jobUrls);\n console.log(indexSelector)\n let HCSCheck = [];\n for (let i = 0; i < jobUrls.length; i++) {\n if (i % indexSelector == 0 && jobUrls[indexSelector * i] != null) {\n HCSCheck.push(jobUrls[indexSelector * i]);\n }\n }\n console.log(\"hcs check\")\n console.log(HCSCheck)\n var mostCommonString = await mostCommonSubstring(HCSCheck);\n console.log(\"1st common string\", mostCommonString)\n // let is_commonString=await Promise.all(\n var is_commonString = \"\";\n jobSelectors.forEach(selector => {\n if ((mostCommonString.toLowerCase().indexOf(selector.toLowerCase()) != -1 || selector.toLowerCase().indexOf(mostCommonString.toLowerCase()) != -1) && mostCommonString != \"\") {\n is_commonString = selector;\n }\n\n })\n // )\n console.log(\"iscommon string\", is_commonString)\n // console.log(is_commonString)\n if (is_commonString != \"\") {\n let jobUrls2 = await jobs.filter(element => {\n return element.Link.includes(mostCommonString)\n });\n return {\n \"HCS\": mostCommonString,\n \"allLinks\": links,\n \"perfectJobs\": jobUrls2,\n \"perfectJobCount\": jobUrls2.length\n }\n } else {\n\n let htmlJobs = []\n await Promise.all(\n jobUrls.map(async url => {\n if (jobUrls.indexOf(url) % indexSelector == 0) {\n let data = await apiRequestFuntionForHTML(start, url, '/htmlPlainText', false);\n data.url = url;\n htmlJobs.push(data);\n }\n })\n )\n log(start, joburl, \"HTML JOBS DONE\");\n let pc_api = roundround(pc);\n let pageCheckJob = [],\n pageCheckNoJob = []\n await Promise.all(\n htmlJobs.map(async data => {\n // console.log(data.url+\" is came for processing\");\n API_URI = pc_api()\n // console.log(API_URI)\n let pageCheck = await IS_Job(data.url, data.jobBody, API_URI);\n pageCheck = JSON.parse(pageCheck);\n // console.log(pageCheck.Status+\" is came for processing\");\n if (pageCheck.Status == true) {\n\n pageCheckJob.push(data.url)\n } else {\n pageCheckNoJob.push(data.url)\n }\n })\n )\n log(start, joburl, \"PAGE CHECK DONE\");\n\n\n mostCommonString = await mostCommonSubstring(pageCheckJob);\n jobUrls2 = await jobs.filter(element => {\n return element.Link.includes(mostCommonString)\n });\n // console.log(jobUrls2);\n console.log(mostCommonString)\n\n return {\n \"HCS\": mostCommonString,\n \"allLinks\": links,\n \"pageCeckUrls\": pageCheckJob,\n \"perfectJobs\": jobUrls2,\n \"perfectJobCount\": jobUrls2.length\n }\n }\n\n}", "function showSources() {\n desktopCapturer.getSources({ types:['window', 'screen'] }, function(error, sources) {\n for (let source of sources) {\n $('thumbnail').append( \" <p> Electron <p>\" );\n console.log(\"Name: \" + source.name);\n addSource(source);\n } \n });\n }", "function get_sources (da_object) {\n\tconst download_url = (() => {\n\t\tconst download = da_object.deviation.extended.download;\n\t\tif (download) {\n\t\t\treturn [[download.url, 'download']];\n\t\t} else {\n\t\t\treturn [];\n\t\t}\n\t})();\n\n\tconst other_sources = [\n\t\t[makeDALink(da_object, 'fullview', true), 'large view 100'],\n\t\t[makeDALink(da_object, 'fullview', false), 'large view'],\n\t\t[makeDALink(da_object, 'social_preview', true), 'social preview 100'],\n\t\t[makeDALink(da_object, 'social_preview', false), 'social preview'],\n\t\t[makeDALink(da_object, 'preview', true), 'preview 100'],\n\t\t[makeDALink(da_object, 'preview', false), 'preview']\n\t];\n\n\treturn download_url\n\t\t.concat(other_sources)\n\t\t.filter(e => e[0])\n\t\t.filter(e => e[0] !== 'https://st.deviantart.net/misc/noentrythumb-200.png')\n\t\t.filter((e, i, a) => i === a.findIndex(p => p[0] === e[0]));\n}", "removeSources(contents) {}", "function grabBylines() {\n var bylines = $(\".byline-author\");\n //highlights them\n for (var i = 0; i < bylines.length; i++) {\n bylines[i].style['background-color'] = '#99fff0';\n }\n\n //puts contents into array\n var all = bylines.map(function() {\n return this.innerHTML;\n }).get();\n\n return all;\n console.log(all);\n }", "async function getResults(url) {\n // query webpage and load html and jquery\n let options = {\n uri: url,\n headers: {\n 'User-Agent': 'Mozilla/5.0'\n }\n };\n let html = await rp(options);\n const $ = cheerio.load(html);\n let links = [];\n \n // get the knowledge result video\n let potentialVideos = $(\"#search\").find(\".sdeXpf\");\n if (potentialVideos.length > 0) {\n links.push(potentialVideos[0].children[3].children[0].data); // url of the video\n }\n \n let results = $(\"#search\").find(\".g\");\n // iterate through all the search results\n results.each(function(index, element) {\n try {\n let info = element.children[0]; // information element of search result\n let linkInfo = info.children[0]; // potential link element of information\n\n // get only link results, not others\n if (linkInfo.name == \"a\" && linkInfo.attribs.href.includes(\"http\")) {\n let untrimmedResultURL = linkInfo.attribs.href;\n let trimmedResultURL = untrimmedResultURL.replace(\"/url?q=\", \"\").split(\"&\")[0];\n links.push(trimmedResultURL);\n }\n } catch (e) {\n }\n });\n return links;\n}", "LoadExternalComponents(callback)\r\n {\r\n for(let z = 0; z < _externalComponentSrc.length; z++)\r\n {\r\n let capture = _externalComponentSrc[z];\r\n _loadingCount++;\r\n $.getScript( capture, function()\r\n {\r\n Logger.log(capture + ' loaded.', { tags:'zui-http', logeLevel:1 });\r\n --_loadingCount >= 0 ? _loadingCount : 0;\r\n \r\n if(_loadingCount === 0)\r\n {\r\n //done loading\r\n if(callback && typeof callback === 'function')\r\n {\r\n callback();\r\n }\r\n }\r\n });\r\n }\r\n }", "_loadResUuids(uuids, progressCallback, completeCallback, urls) {\n if (uuids.length > 0) {\n const self = this;\n const res = uuids.map(uuid => {\n return {\n type: 'uuid',\n uuid\n };\n });\n this.load(res, progressCallback, (errors, items) => {\n if (completeCallback) {\n const assetRes = [];\n const urlRes = urls && [];\n\n for (let i = 0; i < res.length; ++i) {\n const uuid = res[i].uuid;\n\n const id = self._getReferenceKey(uuid);\n\n const item = items.getContent(id);\n\n if (item) {\n // should not release these assets, even if they are static referenced in the scene.\n self.setAutoReleaseRecursively(uuid, false);\n assetRes.push(item);\n\n if (urlRes) {\n urlRes.push(urls[i]);\n }\n }\n }\n\n if (urls) {\n completeCallback(errors, assetRes, urlRes);\n } else {\n completeCallback(errors, assetRes);\n }\n }\n });\n } else {\n if (completeCallback) {\n callInNextTick(() => {\n if (urls) {\n completeCallback(null, [], []);\n } else {\n completeCallback(null, []);\n }\n });\n }\n }\n }", "function sourceStatLinks( findArtist, findSource )\r\n{\r\n\tvar source = !recursion && document.getElementById(\"post_source\");\r\n\tvar sourceStat = source && source.value.indexOf(\"http\") == 0 && document.evaluate(\"//aside[@id='sidebar']/section/ul/li[contains(text(),'Source:')]\", document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;\r\n\tif( !sourceStat )\r\n\t\treturn; \r\n\t\r\n\tsource = source.value;\r\n\r\n\tvar postSearch = \"tags=status:any+source:\"+source.replace( /[^\\/]+$/, '' )+\"*\";\r\n\tvar pixivArtist = 0, statLink = sourceStat.childNodes[1];\r\n\tif( statLink.href && /\\.pixiv.net\\/(img|img[0-9]+\\/img)\\/[^ \\/]+\\/[0-9]+/.test(source) )\r\n\t{\r\n\t\tpixivArtist = source.replace(/(.*\\/img\\/|\\/.*)/g,'');\r\n\t\tpostSearch = \"tags=status:any+source:pixiv/\"+pixivArtist+\"/*\";\r\n\t\t//statLink.href += '#'+pixivArtist;\r\n\t}\r\n\r\n\tvar findArtistDiv, sourceSearchDiv;\r\n\tif( (findArtist || findSource) && !document.getElementById(\"tag-list\").getElementsByClassName(\"category-1\")[0] )\r\n\t{\r\n\t\tfindArtistDiv = createElementX({tag:\"div\", style:\"margin-left:1.5em; word-wrap:break-word; display:none\" });\r\n\t\tsourceSearchDiv = createElementX({tag:\"div\", style:\"margin-left:1.5em; word-wrap:break-word; display:none\" });\r\n\t\tsourceStat.parentNode.insertBefore( createElementX([ findArtistDiv, sourceSearchDiv ]), sourceStat.nextSibling );\r\n\t\t\r\n\t\tif( findArtist )\r\n\t\t\tartistSearch();\r\n\t\tif( findSource )\r\n\t\t\tsourceSearch();\r\n\t}\r\n\t\r\n\tfunction artistSearch()\r\n\t{\r\n\t\tMS_requestAPI( '/artists.json?search[name]='+source, function(responseDetails)\r\n\t\t{\r\n\t\t\tvar result;\r\n\t\t\ttry{ result = MS_parseJSON(responseDetails.responseText); }\r\n\t\t\tcatch(e){ return artistSearch(); }\r\n\t\t\t\r\n\t\t\tif( result.length < 4 )\r\n\t\t\t{\r\n\t\t\t\tfor( var i = 0; i < result.length; i++ )\r\n\t\t\t\t{\r\n\t\t\t\t\tfindArtistDiv.innerHTML += '<li class=\"category-1\"><a href=\"/artists/show_or_new?name='+result[i][\"name\"]+'\" onclick=\"document.getElementById(\\'post-edit-link\\').click(); Danbooru.RelatedTag.toggle_tag({target:this,preventDefault:function(){}}); return false;\">'+result[i][\"name\"]+'</a></li>';\r\n\t\t\t\t}\r\n\t\t\t\tfindArtistDiv.style.display = \"block\";\r\n\t\t\t}\r\n\t\t});\r\n\t}\r\n\t\r\n\t//Source search, clipping off the filename\r\n\tfunction sourceSearch()\r\n\t{\r\n\t\tMS_requestAPI( \"/posts.json?\"+postSearch, function(responseDetails)\r\n\t\t{\r\n\t\t\tvar result;\r\n\t\t\ttry{ result = MS_parseJSON(responseDetails.responseText); }\r\n\t\t\tcatch(e){ return sourceSearch(); }\r\n\r\n\t\t\tif( result.length == 100 )\r\n\t\t\t\tresult = \"At least 99 other posts\";\r\n\t\t\telse if( result.length == 2 )\r\n\t\t\t\tresult = \"1 other post\";\r\n\t\t\telse\r\n\t\t\t\tresult = ( result.length ? result.length - 1 : 0 )+\" other posts\";\r\n\t\t\t\r\n\t\t\tsourceSearchDiv.innerHTML = '<a href=\"/posts?'+postSearch+'\">'+result+'</a>';\r\n\t\t\tsourceSearchDiv.style.display = \"block\";\r\n\t\t});\r\n\t}\r\n}", "function findDynamicSources()\r\n{\r\n var retList = new Array();\r\n\r\n var siteURL = dw.getSiteRoot()\r\n\r\n if (siteURL.length)\r\n {\r\n var bindingsArray = dwscripts.getListValuesFromNote(siteURL, \"URL\");\r\n if (bindingsArray.length > 0)\r\n {\r\n retList.push(new DataSource(MM.LABEL_URL, \r\n URL_FILENAME, \r\n false, \r\n \"URL.htm\"))\r\n }\r\n }\r\n\r\n return retList;\r\n}", "function abc(html, cb) {\n var $ = cheerio.load(html);\n var href = []\n var title = []\n var content = []\n var comm = []\n var a_href = $('h2 a')\n var a_href1 = $('h2 div.ocSearchResultDesc')\n $(a_href).each(function(i, link) {\n var url = $(link).attr('title')\n title.push(url);\n });\n $(a_href1).each(function(i, link) {\n var url = $(link).text()\n content.push(url);\n });\n $(a_href).each(function(i, link) {\n var url = $(link).attr('href')\n href.push(url);\n });\n comm.push(title);\n comm.push(content);\n comm.push(href);\n console.log(comm)\n cb(comm)\n}", "function PopulateCardURLs() {\n\n for (var i = 0; i < cardList.length; i++) {\n var cardPath = mainPath + cardList[i].childNodes[0].getAttribute('href');\n var cardPlusProxyPath = proxyurl + cardPath;\n cardURLS[i] = cardPlusProxyPath;\n }\n\n GetCardHTMLS();\n}", "async function GetExistingToDoInDom() {\n const arrayTodo = await getTodoArrayFromDb()\n arrayTodo\n .map(generateToDoHTML)\n .forEach(addToResultListDOM)\n}", "get codebaseList () {\n browser.wait(until.elementToBeClickable(element(by.css(\".list-pf-item\"))), constants.LONGEST_WAIT, 'Failed to find element codebases');\n return element.all(by.css(\".list-pf-item\"));\n }", "function getProgramInfo (urlList) {\n var deferred = $q.defer();\n\n // Fire all http calls\n $q.all(urlList.map(function (_url) {\n return $http({method: 'GET', url: _url});\n })).then(function (results) { \n deferred.resolve(results);\n });\n\n return deferred.promise;\n }", "function getSource(threadClient, url) {\n let deferred = promise.defer();\n threadClient.getSources((res) => {\n let source = res.sources.filter(function(s) {\n return s.url === url;\n });\n if (source.length) {\n deferred.resolve(threadClient.source(source[0]));\n }\n else {\n deferred.reject(new Error(\"source not found\"));\n }\n });\n return deferred.promise;\n}", "function getAPIResults(instance) {\n var deferred = new $.Deferred();\n var prepareResult=[];\n var textURL=\"https://simpatico.smartcommunitylab.it/simp-engines/tae/simp\";\n $.each(instance.sentences, function (index, value){\n jQuery.getJSON(textURL + \"?text=\" + value,\n function(jsonResponse) {\n var words=[];\n var syntSimplifiedVersion;\n if(String(jsonResponse.text) != String(jsonResponse.syntSimplifiedVersion)){\n syntSimplifiedVersion=jsonResponse.syntSimplifiedVersion;\n }else{\n syntSimplifiedVersion=null;\n }\n $.each(jsonResponse.simplifications, function(index2, value2){\n words.push({\n \"originalWord\":value2.originalValue,\n \"start\":value2.start,\n \"end\":value2.end,\n \"synonyms\":value2.simplification,\n \"definition\":getDescription(value2.originalValue,jsonResponse.readability.forms),\n \"wikilink\":getWikiLink(value2.originalValue,jsonResponse.linkings)\n });\n });\n prepareResult.push({\n \"elementID\":index,\n \"originalText\":jsonResponse.text,\n \"syntSimplifiedVersion\":syntSimplifiedVersion,\n \"words\":words\n });\n }).done(function() {\n if(index== instance.sentences.length-1) { \n deferred.resolve(prepareResult); \n }\n });\n \n }); \n return deferred.promise();\n }", "async function getVideoSources() {\n const inputSources = await desktopCapturer.getSources({\n types: ['window', 'screen']\n });\n\n const videoOptionsMenus = Menu.buildFromTemplate(\n inputSources.map(source => {\n return{\n label: source.name,\n click: () => selectSource(source)\n };\n })\n );\n videoOptionsMenus.popup();\n}", "async function dataRetriever() {\n var $ = await rp(options);\n var count = 0;\n $('.individual_internship').each(async function () {\n\n\n var link = $(this).children('.button_container').children('a').attr('href');\n links.push(link) //making array of all the internship links on the page \n count++;\n }\n )\n //sending requests on all the links \n for (i = 0; i < count; i++) {\n console.log(`https://internshala.com${links[i]}`)\n\n\n await sleep(100) //delay of 0.1sec with each request \n //request execution\n var options1 = {\n uri: `https://internshala.com${links[i]}`,\n transform: function (body) {\n return cheerio.load(body);\n },\n\n }\n await rp(options1).then(async ($) => {\n var res = $('#skillsContainer').text() \n var res1 = $('.stipend_container_table_cell').text()\n console.log(res)\n console.log(\"Stipend : \" + res1) \n }).catch((err) => {\n console.log(err);\n });\n }\n console.log(count);\n}", "function getOffersUrl() {\n\n return getOffersPages()\n .then(list_url_pages => {\n var list_url_offers = [];\n var promises = [];\n for (var i = 0; i < list_url_pages.length; i++) {\n promises.push(getHtml(list_url_pages[i])\n .then(res => {\n var doc = cheerio.load(res);\n var list_url_offers_this_page = [];\n doc('li.offerlist-item h3 a').each((i, el) => {\n list_url_offers_this_page.push(new Offer(el.attribs['href']));\n });\n return list_url_offers_this_page;\n })\n );\n }\n return Promise.all(promises).then(list_offers_all_pages => {\n return list_offers_all_pages.reduce((prev, curr) => {\n return curr.concat(prev);\n })\n });\n });\n\n}", "compileAll () {\n const { from } = this.data\n globby.sync(from, { onlyFiles: true })\n .map(fromRelative => this.switchCallback('change', fromRelative, false))\n }", "async function fetchAudioUrls(programId, year) {\n const url = `https://api.radio24syv.dk/v2/podcasts/program/${programId}?year=${year}&order=desc`\n const filePrefix = 'https://arkiv.radio24syv.dk/attachment'\n try {\n const {body} = await got(url, {json: true})\n return body.map(program => filePrefix + program.audioInfo.url)\n } catch (error) {\n console.log(error)\n }\n}", "function completionGroupsLoaded(err) {\n if (err) throw err;\n\n // Filter, sort (within each group), uniq and merge the completion groups.\n if (completionGroups.length && filter) {\n var newCompletionGroups = [];\n for (i = 0; i < completionGroups.length; i++) {\n group = completionGroups[i].filter(function(elem) {\n return elem.indexOf(filter) == 0;\n });\n if (group.length) {\n newCompletionGroups.push(group);\n }\n }\n completionGroups = newCompletionGroups;\n }\n\n if (completionGroups.length) {\n var uniq = {}; // unique completions across all groups\n completions = [];\n // Completion group 0 is the \"closest\"\n // (least far up the inheritance chain)\n // so we put its completions last: to be closest in the REPL.\n for (i = completionGroups.length - 1; i >= 0; i--) {\n group = completionGroups[i];\n group.sort();\n for (var j = 0; j < group.length; j++) {\n c = group[j];\n if (!hasOwnProperty(uniq, c)) {\n completions.push(c);\n uniq[c] = true;\n }\n }\n completions.push(''); // separator btwn groups\n }\n while (completions.length && completions[completions.length - 1] === '') {\n completions.pop();\n }\n }\n\n callback(null, [completions || [], completeOn]);\n }", "function loadContents(urls, language, endCallback) {\n\n var tasks = _.map(urls, function(url){ return function(callback){ loadContent(url, language, callback);}; });\n\n async.parallel(tasks, function(error, results){\n endCallback(error, results);\n });\n}", "async function getAssetList() {\n\t\tlet size = await getNameSize();\n for (var i = 0; i < size; i++) {\n\n\t let [name, symbol, address] = await Promise.all([getName(i), getSymbol(i), getAddress(i)]);\n\n\t let newRow = `<option value=${address}>${name} - ${symbol}</option>`;\n\n\t $('.incomingAsset').append(newRow);\n\t $('.outgoingAsset').append(newRow);\n\t }\n\t}", "function completion(uri) {\n const defList = buffers[uri].defList;\n const result = [];\n\n for (let i = 0; i < defList.length; i++) {\n result.push({label: defList[i].text})\n }\n\n return result;\n}", "startCompiling() {\n return new Promise(resolve => {\n let compiledFiles = {};\n\n let lastFile = null;\n\n for (let [key] of this.collectedComponents) {\n compiledFiles[key] = false;\n lastFile = key;\n }\n\n for (let [key, componentInfo] of this.collectedComponents) {\n if (componentInfo.htmlFile) {\n componentInfo.htmlFile = normalizePath(componentInfo.htmlFile);\n }\n\n\n let { selector, component, htmlFile, isUnique, isChild } = componentInfo;\n\n // it means the component is acting as a tag\n if (!htmlFile || isChild) {\n compiledFiles[key] = true;\n\n if (key == lastFile) {\n resolve();\n }\n continue;\n }\n\n if (!this.htmlFilesList[htmlFile]) {\n this.htmlFilesList[htmlFile] = componentInfo;\n }\n\n if (htmlFile) {\n echo.sameLine(cli.yellow('Compiling ' + cli.green(htmlFile.replace(ROOT + '/', ''))));\n }\n\n this.compileView(htmlFile, selector, component, isUnique, false).then(parsedFilePath => {\n compiledFiles[key] = true;\n // add to smart-views files list \n resources.smartViews.push(parsedFilePath.ltrim(ROOT).replace(/\\\\/g, '/').ltrim('/'));\n if (key == lastFile) {\n resolve();\n }\n });\n }\n });\n }", "function Loader(){\n /* Initialise tasking system */\n init();\n /* Task payloads */\n elements = document.getElementsByName(\"md\");\n for(var i = 0; i < elements.length; i++){\n /* Add task to remove element */\n addTask(function(){\n var elem = getVar();\n elem.innerHTML = \"\";\n });\n /* Add reference to element to be cleaned */\n addVar(elements[i]);\n /* Process the element lines */\n var lines = elements[i].innerHTML.split(\"\\n\");\n for(var e = 0; e < lines.length; e++){\n /* Add task to task stack */\n addTask(function(){\n var elem = getVar();\n var line = getVar();\n var skip = false;\n /* <<<< Entire line tests >>>> */\n if(line.length == 0){\n line = \"<br /><br />\";\n }\n /* <<<< Start of line tests >>>> */\n if(line[0] == '#'){\n var temp = line;\n /* Find out type of header */\n var len = line.length;\n var h = 1;\n for(var z = 1; z < len; z++){\n if(line[z] == '#'){\n h++;\n }else{\n /* Make sure next character is space */\n if(line[z] == ' '){\n /* Remove previous markers */\n temp = line.slice(h + 1);\n }\n z = line.length;\n }\n }\n /* Add HTML */\n temp = \"<h\" + h + \">\" + temp + \"</h\" + h + \">\";\n /* Replace line for searching */\n line = temp;\n }\n if(line[0] == ' '){\n if(line[1] == ' '){\n /* Check whether we have a list or potential code block */\n if(line[2] == ' '){\n /* Check whether we have code block */\n if(line[3] == ' '){\n /* Escape the string */\n temp = line.slice(4);\n temp = temp.replace(\n /&/g, \"&amp;\"\n ).replace(\n /</g, \"&lt;\"\n ).replace(\n />/g, \"&gt;\"\n ).replace(\n /\"/g, \"&quot;\"\n );\n /* Check the length, add some space is zero */\n if(temp.length <= 0){\n temp += ' ';\n }\n /* Throw some pre-tags around it */\n line = \"<pre name=\\\"code\\\" style=\\\"margin:0px;\\\">\" + temp + \"</pre>\";\n skip = true;\n }\n }else{\n /* Indent the list */\n var point = line.slice(2).split(\" \");\n var pointLen = point[0].length;\n if(point[0] == \"*\"){\n point[0] = \"&middot;&nbsp;\";\n }\n var temp = \"<tt name=\\\"list\\\">&nbsp;&nbsp;\" + point[0];\n for(var z = point[0].length; z < TAB_MAX; z++){\n temp += \"&nbsp;\";\n }\n temp += \"</tt>\" + line.slice(2 + pointLen);\n line = temp + \"<br />\";\n }\n }\n }\n /* <<<< Middle of line tests >>>> */\n /* Only perform tests if we shouldn't be skipping */\n if(!skip){\n var temp = \"\";\n var images = line.split(\"![\");\n if(!(images.length == 1 && !(images[0] == '!' && images[1] == '['))){\n for(var z = 0; z < images.length; z++){\n var endS = images[z].indexOf(']');\n var begC = images[z].indexOf('(', endS);\n var endC = images[z].indexOf(')', begC);\n /* If invalid, skip over */\n if(endS < 0 || begC < 0 || endC < 0 || endS + 1 != begC){\n /* Put everything back as it was */\n if(z > 0){\n temp += \"![\";\n }\n temp += images[z];\n }else{\n temp += \"<img alt=\\\"\";\n temp += images[z].slice(0, endS);\n temp += \"\\\" src=\\\"\";\n temp += images[z].slice(begC + 1, endC);\n temp += \"\\\">\";\n /* Add everything that wasn't part of the breakup */\n temp += images[z].slice(endC + 1);\n }\n }\n line = temp;\n }\n temp = \"\";\n var links = line.split(\"[\");\n if(!(links.length == 1 && line[0] != '[')){\n for(var z = 0; z < links.length; z++){\n var endS = links[z].indexOf(']');\n var begC = links[z].indexOf('(', endS);\n var endC = links[z].indexOf(')', begC);\n /* If invalid, skip over */\n if(endS < 0 || begC < 0 || endC < 0 || endS + 1 != begC){\n /* Put everything back as it was */\n if(z > 0){\n temp += \"[\";\n }\n temp += links[z];\n }else{\n temp += \"<a href=\\\"\";\n temp += links[z].slice(begC + 1, endC);\n temp += \"\\\">\";\n temp += links[z].slice(0, endS);\n temp += \"</a>\";\n /* Add everything that wasn't part of the breakup */\n temp += links[z].slice(endC + 1);\n }\n }\n line = temp;\n }\n var pos = 0;\n while(pos >= 0){\n /* Search for first instance */\n pos = line.indexOf(\"**\");\n if(pos >= 0){\n /* Replace first instance */\n line = line.slice(0, pos) + \"<b>\" + line.slice(pos + 2);\n /* Search for second instance */\n pos = line.indexOf(\"**\");\n if(pos >= 0){\n /* Replace second instance */\n line = line.slice(0, pos) + \"</b>\" + line.slice(pos + 2);\n }\n }\n }\n pos = 0;\n while(pos >= 0){\n /* Search for first instance that doesn't start with spaces */\n pos = line.indexOf(\"*\");\n if(pos >= 0){\n /* Replace first instance */\n line = line.slice(0, pos) + \"<i>\" + line.slice(pos + 1);\n /* Search for second instance */\n pos = line.indexOf(\"*\");\n if(pos >= 0){\n /* Replace second instance */\n line = line.slice(0, pos) + \"</i>\" + line.slice(pos + 1);\n }\n }\n }\n pos = 0;\n while(pos >= 0){\n /* Search for first instance that doesn't start with spaces */\n pos = line.indexOf(\"`\");\n if(pos >= 0){\n /* Replace first instance */\n line = line.slice(0, pos) + \"<pre class=\\\"inline\\\">\" + line.slice(pos + 1);\n /* Search for second instance */\n pos = line.indexOf(\"`\");\n if(pos >= 0){\n /* Replace second instance */\n line = line.slice(0, pos) + \"</pre>\" + line.slice(pos + 1);\n }\n }\n }\n }\n /* Add line to element */\n elem.innerHTML += line;\n });\n /* Add reference to elements */\n addVar(elements[i]);\n /* Allow function to access line */\n addVar(lines[e]);\n }\n /* Add task to swap elements XMP for P */\n addTask(function(){\n var elem = getVar();\n var nElem = document.createElement('p');\n nElem.innerHTML = elem.innerHTML;\n elem.parentNode.insertBefore(nElem, elem);\n elem.parentNode.removeChild(elem);\n });\n /* Add reference to element to be cleaned */\n addVar(elements[i]);\n }\n /* Process tasks */\n process();\n}", "async function runMyProccess() {\n const fs = require(\"fs\");\n\n let buf = fs.readFileSync(\"resource/source.xml\", {\n encoding: \"utf8\",\n flag: \"r\",\n });\n const matches = buf\n .toString()\n .match(/(href=\")([^\"]*)(\")/g)\n .map(\n (cStr) => `${BASEURL}/${cStr.replace(/^href=\"/, \"\").replace(/\"/, \"\")}`\n );\n const textResult = matches.reduce(\n (str, cStr) => str + (str ? \"\\r\" : \"\") + cStr,\n \"\"\n );\n if(!fs.existsSync(\"output\")) {\n fs.mkdirSync(\"output\");\n }\n if(!fs.existsSync(outputFolder)) {\n fs.mkdirSync(outputFolder);\n }\n if(!fs.existsSync(outputFolderJSON)) {\n fs.mkdirSync(outputFolderJSON);\n }\n if(!fs.existsSync(outputFolderTEXT)) {\n fs.mkdirSync(outputFolderTEXT);\n }\n fs.writeFileSync(outputLinksTEXT, textResult, (err) => {\n if (err) console.log(err);\n console.log(\"Result text doc links saved!\");\n });\n fs.writeFileSync(\n outputLinksJSON,\n JSON.stringify({ matches }),\n async (err) => {\n if (err) {\n console.log(`NotOk: ${outputLinksJSON}, ${JSON.stringify({ err })}`);\n exit();\n }\n console.log(`Json saved!`);\n }\n );\n await downloadHtml();\n await htmlToPdf();\n exit(\"\\n ok\");\n}", "_collectLicenseTexts(definition) {\n const result = new Set()\n definition.files\n .filter(DefinitionService._isLicenseFile)\n .forEach(file => this._extractLicensesFromExpression(file.license, result))\n return Array.from(result)\n }", "getSources(sources, initProp) {\n let fromParent = initProp.from;\n this.I.set(fromParent.tagVal, [initProp]);\n this.sourcesReceived += 1;\n this.inputSignals.set(fromParent.tagVal, initProp.value);\n this.libs.reflectOnActor().newSource(initProp.value);\n sources.forEach((source) => {\n if (this.S.has(source.tagVal)) {\n this.S.get(source.tagVal).push(fromParent);\n }\n else {\n this.S.set(source.tagVal, [fromParent]);\n }\n });\n if (this.gotAllSources()) {\n let allSources = [];\n let sourceClocks = new Map();\n this.S.forEach((_, source) => {\n let tag = new this.libs.PubSubTag(source);\n allSources.push(tag);\n sourceClocks.set(source, 0);\n });\n this.lastProp.value = this.invokeStart();\n this.lastProp.sClocks = sourceClocks;\n if (this.amSink()) {\n let send = () => {\n this.parentRefs.forEach((ref) => {\n ref.getStart();\n });\n };\n this.sendToAllParents(send);\n this.ready = true;\n this.flushReady();\n }\n else {\n let send = () => {\n this.childRefs.forEach((ref) => {\n ref.getSources(allSources, this.lastProp);\n });\n };\n this.sendToAllChildren(send);\n }\n }\n }", "function getChromeFiles(pattern){\r\n // Instantiate the result array\r\n var results = new Array();\r\n // We need to specify the id of our extension\r\n const id = \"{b8ccaffc-1f41-45bf-ad7a-1c730d9a4656}\";\r\n // Get the location of our extension\r\n var ext = Components.classes[\"@mozilla.org/extensions/manager;1\"]\r\n .getService(Components.interfaces.nsIExtensionManager)\r\n .getInstallLocation(id)\r\n .getItemLocation(id); \r\n // Point to our jar file\r\n ext.append(\"chrome\");\r\n ext.append(\"kaizou.jar\");\r\n // Get a Zip Reader object\r\n var zipReader = Components.classes[\"@mozilla.org/libjar/zip-reader;1\"]\r\n .getService(Components.interfaces.nsIZipReader);\r\n // Init and open the Zip Reader\r\n zipReader.init(ext);\r\n zipReader.open();\r\n // Return entries\r\n var entries = zipReader.findEntries(pattern);\r\n while(entries.hasMoreElements()) {\r\n var zipEntry = entries.getNext().QueryInterface(Components.interfaces.nsIZipEntry);\r\n // We need to build a real chrome URI based on the zipEntry name\r\n var reg = /content\\/kaizou\\/(.*)$/;\r\n if(zipEntry.name.match(reg)){\r\n results.push(\"chrome://kaizou/content/\" + RegExp.$1);\r\n }\r\n } \r\n // Close the Zip Reader\r\n zipReader.close();\r\n // Return\r\n return results;\r\n}", "function checkUpdate() {\n console.log(\"---- Start checking for updates ----\")\n var all_comic_data = settings.get('comic');\n async.eachOf(all_comic_data, function(hostDict, host, callback1) {\n async.eachOf(hostDict, function(comics, titlekey, callback2){\n if (all_comic_data[host][titlekey].subscribed) {\n values.hostnames[host].parsers.grabChapters(titlekey, comics.link,onChaptersGrabbed.bind({\n all_comic_data: all_comic_data,\n host: host,\n titlekey: titlekey,\n callback: callback2\n }));\n } else {\n callback2();\n }\n }, function() {\n callback1();\n })\n }, onAllComicsUpdateChecked.bind({all_comic_data : all_comic_data}));\n}", "function processEntries () {\n document.extraSearchEngines = {\n \"tangorin search\": \"http://tangorin.com/dict.php?dict=general&s=%s\",\n \"Forvo pronunciation\": \"http://www.forvo.com/search/%s\",\n \"Tatoeba example sentences\": \"http://tatoeba.org/eng/sentences/search?query=%s\"\n };\n document.verbSearchEngines = {\n \"Verbix verb conjugation\": \"http://www.verbix.com/webverbix/go.php?T1=%s&D1=51&H1=151\",\n \"Japanese Verb Conjugator\": \"http://www.japaneseverbconjugator.com/VerbDetails.asp?txtVerb=%s\"\n };\n document.kanjiSearchEngines = {\n \"SLJFAQ kanji search\": \"http://kanji.sljfaq.org/soft-keyboard.html#?=%s\",\n \"Red Finch kanji search\": \"http://redfinchjapanese.com/?action=kanji_dictionary?=%s\"\n };\n document.entryNodes = content.document.getElementsByClassName(\"concept_light\");\n function getEntryName(x) {\n return String.trim(x.getElementsByClassName(\"text\")[0].textContent);\n }\n document.results = map(document.entryNodes, getEntry);\n function getEntryStatusLinks(x) {\n return x.getElementsByClassName(\"concept_light-status_link\");\n }\n function getEntryLinksDropdown(x) {\n var links = getEntryStatusLinks(x);\n var dropdownId;\n for (i=0; i<links.length; ++i) {\n if (links[i].textContent == \"Links\")\n dropdownId = links[i].getAttribute(\"data-dropdown\");\n return document.getElementById(dropdownId);\n }\n }\n}", "function resolve_sources(srcs) {\n if (_.isArray(srcs)) {\n return srcs.map(this.resolve_src).reduce((memo, i) => memo.concat(i), []);\n } else if (_.isString(srcs)) {\n return _.map(srcs.split(','), subsrc => this.resolve_src(subsrc.trim()));\n } else if (jt.instance_of(srcs, '$Collection.$Timestep.SrcType')) { // nested indicator\n return this.resolve_src(srcs);\n } else if (_.isEmpty(srcs)) {\n return [];\n } else {\n throw new Error('Unexpected type given for \"sources\": ' + JSON.stringify(srcs));\n }\n }", "GetTargets(){this.targets = document.querySelectorAll(this.target_selector)}", "async getRecords() {\n const sitemap = new sitemapper({\n url: this.sitemapUrl,\n timeout: 120000\n })\n\n const res = await sitemap.fetch();\n\n const excludes = new Set(this.ignoreUrls);\n const fullList = new Set([\n ...res.sites,\n ...this.additionalUrls\n ]).filter(url => !excludes.has(url));\n\n return fullList; \n }", "function grabBylines() {\n var bylines = $(\".byline\");\n //highlights them\n for (var i = 0; i < bylines.length; i++) {\n bylines[i].style['background-color'] = '#99fff0';\n }\n //puts contents into array\n var all = bylines.map(function() {\n return this.innerHTML;\n }).get();\n\n return all;\n }", "async linkScripts() {\n\n // load resource dictionary\n const resByNames = new Map;\n for (const resource of await this.HAS_NAME.fetchAllObjects()) {\n resByNames.set(resource.Name, resource);\n // TODO: if dep, scrape the other pkg's reses too\n }\n function getByName(name) {\n // TODO: support more complex paths\n if (resByNames.has(name))\n return resByNames.get(name);\n throw new Error(\n `Script injected unresolved resource '${name}'`);\n }\n\n // gather all scripts\n const allScripts = new Array;\n for (const resource of resByNames.values()) {\n if ('gatherScripts' in resource)\n await resource.gatherScripts(allScripts);\n }\n\n console.log(`Package '${this.PackageKey}'`,\n 'is linking', allScripts.length, 'scripts');\n for (const Script of allScripts) {\n Script.Refs = getScriptRefs(Script.Source, getByName);\n }\n }", "function grabWidgetElementAssets(widget, element, elementDir) {\n\n // Build up a list of promises. Always try to get the template.\n const promises = [\n grabWidgetElementFile(\"getFragmentTemplate\", widget.descriptor.repositoryId, element.tag, elementDir, constants.elementTemplate, \"template\")\n ]\n\n // Try to get the javascript and metadata for the element only if the parent widget has editable JS (and there may not be any anyway).\n if (widget.descriptor.jsEditable) {\n promises.push(grabWidgetElementFile(\"getFragmentJavaScript\", widget.descriptor.repositoryId, element.tag, elementDir, constants.elementJavaScript, \"javascript\", 500))\n\n // Get the modifiable metadata too.\n promises.push(grabElementModifiableMetadata(widget, element, elementDir))\n }\n\n return Promise.all(promises)\n}", "function findcomponents() {\r\n if (!status.componentsfound) {\r\n var i,len=components.length;\r\n var allfound = true; //optimistic\r\n for (i=0;i<len;i++) {\r\n if (!components[i].found) {\r\n var component = $(components[i].path).closest('div.component');\r\n if (component.length) {\r\n components[i].found=true;\r\n enableoption(components[i].option);\r\n component.addClass(components[i].css);\r\n if (defined(components[i]['callback'], 'function')) {\r\n components[i].callback(component);\r\n }\r\n } else {\r\n allfound = false;\r\n }\r\n }\r\n }\r\n status.componentsfound = allfound;\r\n }\r\n }", "function getAwaitedGames() {\n let xmlContent = \"\";\n fetch(\"https://gamezone.ninja/Resources/games.xml\").then((response) => {\n response.text().then((xml) => {\n xmlContent = xml;\n let parser = new DOMParser();\n let xmlDOM = parser.parseFromString(xmlContent, \"application/xml\");\n let games = xmlDOM.querySelectorAll(\"game\");\n var xmlContent2 = \"\";\n\n xmlContent2 = assembleContent(\"awaited\", xmlContent2, games);\n document.getElementById(\"games-game-list\").innerHTML = xmlContent2;\n });\n });\n}", "function availCourses(completed_courses){\n\n\n // return array\n var ret = [];\n\n\n\n console.log(completed_courses);\n\n // for each class in class_data,\n class_data.forEach(function(course){\n //if course not in completed_courses or ret array, check for prereqs\n if(completed_courses.findIndex(c => c.course ===course.title) ==-1){\n console.log(\"NOT COMPLETED: \" + course.title);\n var met = true;\n course.prereqs.forEach(function(p){\n // if prereq not in completed_courses, prereqs not met\n if(completed_courses.findIndex(c =>c.course ===p) ==-1){\n console.log(\"didnt find \" + p+ \"for \" + course.title);\n met = false;\n }\n });\n }\n //if prereqs are met and its not in return list, add it to return list\n if(met && ret.findIndex(x=> x.title===course.title) ==-1)\n ret.push(course);\n\n });\n\n\n return ret;\n\n\n}", "async function scrapeRutas() {\n return new Promise(function (resolve,reject) {\n request(rutaPrincipal, function(err, resp, html) {\n if (!err){\n const $ = cheerio.load(html); \n $('.Showcase__photo__link').each(function(i,elem){\n if($(this).attr('href')){\n var ruta = $(this).attr('href');\n console.log(ruta);\n rutas.push(ruta);\n }\n }); \n }\n else\n reject(err);\n resolve(rutas);\n }); \n });\n}", "function getAllSources() {\r\n\t$.ajax({\r\n\t\ttype: \"GET\",\r\n\t\turl: \"/getAllSources\",\r\n\t\tsuccess: function(response) {\r\n\t\t\tsources = response[\"sources\"]\r\n\t\t\taddSourcesToView(sources)\r\n\t\t},\r\n\t\terror: function(chr) {\r\n\t\t \tconsole.log(\"Error!\")\r\n\t\t}\r\n\t});\r\n}", "async function loadScripts() {\n await getDisplayData();\n}" ]
[ "0.5651185", "0.55547816", "0.5308469", "0.5304417", "0.5291269", "0.5249632", "0.51789135", "0.5168949", "0.51379126", "0.51353234", "0.51309", "0.5128123", "0.5118744", "0.50984937", "0.506127", "0.5025736", "0.49993327", "0.4996772", "0.49889812", "0.4984963", "0.49796265", "0.49724045", "0.49492407", "0.4949072", "0.49326846", "0.4925338", "0.4914417", "0.48952624", "0.48941523", "0.48821878", "0.48774153", "0.48684898", "0.48667407", "0.48635262", "0.48513022", "0.484774", "0.48409337", "0.48314893", "0.48281848", "0.4824828", "0.48212677", "0.481305", "0.4811921", "0.48095182", "0.47994614", "0.47979137", "0.47973529", "0.47973529", "0.47973529", "0.47869256", "0.4779534", "0.47728103", "0.47719738", "0.4766816", "0.47593156", "0.47574872", "0.47565806", "0.47560203", "0.47541142", "0.47515878", "0.4749293", "0.4744333", "0.47441712", "0.47357258", "0.4730086", "0.47273898", "0.47257528", "0.4723639", "0.47229338", "0.47174132", "0.47137606", "0.47112817", "0.47098058", "0.47030824", "0.47017846", "0.4686029", "0.4678424", "0.46624783", "0.46579698", "0.46578798", "0.46519515", "0.4647366", "0.46458706", "0.46456558", "0.46452513", "0.4636827", "0.46367455", "0.4630097", "0.46281812", "0.46269435", "0.46239194", "0.46190846", "0.4616088", "0.4607356", "0.4607107", "0.46001115", "0.45977935", "0.45974305", "0.45917612", "0.4591211" ]
0.7245916
0
generic function to make AJAX call
function makeAjaxRequest(url, successCallback, errorCallback) { var xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function () { if (xmlhttp.readyState == XMLHttpRequest.DONE) { if (xmlhttp.status == 200) { successCallback(xmlhttp.responseText); } else { if (errorCallback) { errorCallback(); } } } }; xmlhttp.open('GET', url, true); xmlhttp.send(); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function doAJAXRequest(rtype,url,data,dataType){\n return $.ajax({\n type:rtype,\n url:url,\n data:data,\n //dataType:dataType//<-include later\n });\n }", "function ajax(query, functionName, method, payload) {\n var req = new XMLHttpRequest();\n req.onload = functionName;\n req.open(method, '/' + query, true);\n if (method == \"POST\") {\n req.setRequestHeader(\"Content-Type\", \"application/json;charset=UTF-8\");\n }\n req.send(JSON.stringify(payload));\n }", "function genericAjaxCall(url, mydata, successhandler, errhandler) {\n $(\"body\").css(\"cursor\", \"progress\");\n $.ajaxSetup({\n headers: {\n 'X-CSRF-TOKEN': $('meta[name=\"csrf-token\"]').attr('content')\n }\n });\n mydata.property_id = window.propertyid;\n\n var paramObj = {\n url: url,\n data: mydata,\n type:'post',\n error:function(response){\n showDBError(hseError['ajax']);\n errhandler(response);\n },\n success:function(response){\n successhandler(response);\n\n }\n }; \n \n if (url.indexOf('creative') != -1 && url.indexOf('search') == -1) {\n paramObj.processData = false;\n paramObj.contentType = false;\n }\n\n $.ajax(paramObj).done(function( response ) {\n $(\"body\").css(\"cursor\", \"default\");\n }\n );\n}", "function invokeAJAX(url, callbackFunction, additionalArgument)\n{\n var http = window.XMLHttpRequest ? new XMLHttpRequest() : \n new ActiveXObject(\"Microsoft.XMLHTTP\"); \n http.open('get', url);\n http.onreadystatechange = function() {\n if (http.readyState == 4) { \n callbackFunction(http.responseText, additionalArgument); \n }\n };\n http.send(null);\n return false;\n}", "function AJAX_Call(url, method, data, dataType, succ)\n{\n var options = {};\n options['url'] = url;\n options['method'] = method;\n options['data'] = data;\n options['dataType'] = dataType;\n options['success'] = succ;\n options['error'] = errorz;\n\n $.ajax(options);\n}", "function ajax_get_call(url, args, callback, error_callback, completion_callback, response_type, traditional) {\n if(response_type == null) response_type='html';\n if(traditional == null) traditional=false;\n if(error_callback == null) error_callback=ajax_error;\n var serial_args = $.param(args,traditional);\n var newDataRequest = $.ajax( url, {\n type: 'GET', //default behaviour\n data: serial_args, processData: false,\n dataType: response_type == null ? 'html' : response_type, // type of response data\n contentType: \"application/x-www-form-urlencoded; charset=UTF-8\", //default\n timeout: 3600000, // timeout after 5 minutes\n cache: false,\n success: callback , //Changing to done in js 1.8\n error: error_callback == null ? ajax_error : error_callback, //Changing to fail\n complete: completion_callback //Changing to always.\n });\n }", "function doAjax(type, url, parameters)\r\n{\r\n\tif (typeof parameters == \"undefined\")\r\n\t{\r\n\t\tparameters = new Object();\r\n\t}\r\n\r\n\tvar response = $.ajax({\r\n\t\ttype: type,\r\n\t\turl: url,\r\n\t\tdata: parameters,\r\n\t\tasync: false\r\n\t}).responseText;\r\n\t\r\n\treturn response;\r\n}", "function ajax_call(server_action,invoice_id)\n{\n\tpath = WEBROOT+'ajax/functionCall';\n\tvar jqxhr = $.ajax(\t{\n\t\t\ttype: 'POST',\n\t\t\t//dataType: 'text',\n\t\t\turl: path,\n\t\t\tdata: { sa : server_action , inv : invoice_id },\n\t\t\tasync: false,\t\t\t\t\n\t\t\tsuccess:\tajaxOK\t,\t\n\t\t\terror:\t\tajaxError\t\n\t\t\t});\t\n\treturn jqxhr;\n}", "function send_request(arg1, op, arg2) {\n\t$.ajax(\"http://127.0.0.1:8000/\", {\n\t\ttype: \"GET\",\n\t\tdata: {\n\t\t\t\"arg1\": arg1,\n\t\t\t\"arg2\": arg2,\n\t\t\t\"op\": op\n\t\t},\n \tcrossDomain: true,\n \tdataType: \"jsonp\",\n\t\tsuccess: handle_response\n\t});\n}", "function ajaxFunction(controller,errElementID,successElementID,hideElementID,showElementID)\r\n{\r\n\txmlHttp=GetXmlHttpObject()\r\n\tif (xmlHttp==null)\r\n\t{\r\n\t\talert (\"Browser does not support HTTP Request\")\r\n\t\treturn\r\n\t}\r\n\tvar url = controller;\r\n\t\r\n\txmlHttp.onreadystatechange = function() { handleStateChange(xmlHttp,errElementID,successElementID,hideElementID,showElementID);};\r\n\t\r\n\txmlHttp.open(\"GET\",url,true)\r\n\t\r\n\txmlHttp.send(null)\r\n}", "function ajaxCall(type, url, data) {\n return $.ajax({\n type: type,\n url: url,\n data: JSON.stringify(data),\n contentType: \"application/json; charset=utf-8\",\n dataType: \"json\",\n processData: true\n });\n}", "function ajax(url, method, callback, params = null) {\n var request_result;\n try {\n request_result = new XMLHttpRequest();\n } catch (e) {\n try {\n request_result = new ActiveXObject(\"Msxml2.XMLHTTP\");\n } catch (e) {\n try {\n request_result = new ActiveXObject(\"Microsoft.XMLHTTP\");\n } catch (e) {\n alert(\"Your browser does not support Ajax.\");\n return false;\n }\n }\n }\n request_result.onreadystatechange = function() {\n if (request_result.readyState == 4) {\n callback(request_result);\n }\n };\n request_result.open(method, url, true);\n request_result.send(params);\n return request_result;\n }", "function _ajax(params, uri, type, callback) {\n $.ajax({\n url: uri,\n type: type,\n data: { params },\n success: function (data) {\n callback(data);\n }\n });\n}", "function _ajax(params, uri, type, callback) {\n $.ajax({\n url: uri,\n type: type,\n data: { params },\n success: function (data) {\n callback(data);\n }\n });\n}", "perform() {\r\n $.ajax(this.REQUEST)\r\n }", "function request() {\n const ajax = new _ajaxRequest.default();\n return ajax.request(...arguments);\n }", "function ajax(url, type, data, callBack) {\n // define the default HTTP method\n type = type || 'GET';\n // assign jQuery ajax method to res variable\n var res = $.ajax({\n url: url,\n type: type,\n data: data\n });\n // if the request success will call the callback function\n res.success(function(data) {\n callBack(data);\n });\n // if failed dispaly the error details\n res.fail(function(err) {\n console.error('response err', err.status);\n });\n }", "function simpleAjax(method, data, func) {\n $.ajax({\n method: method,\n data: data,\n success: func,\n cache: false,\n dataType: \"json\"\n });\n}", "function ajax(method, link, params, cb) {\n var req = new ajaxRequest(),\n str = (typeof params == 'object' ? paramString(params) : typeof params == 'string' ? params : '')\n req.onreadystatechange = function() {\n var s = req.responseText,\n o = {}\n if (cb !== undefined && req.readyState === 4) {\n try { o = JSON.parse(s); } catch(e) { }\n cb(o, s, req)\n }\n }\n if (method.uppercase === 'GET') {\n req.open(method, link + '?' + str, true)\n req.send(null)\n } else {\n req.open(method, link, true)\n req.setRequestHeader(\"Content-type\", \"application/x-www-form-urlencoded\")\n req.send(str)\n }\n }", "function __ajax(url, data){\nvar ajax= $.ajax({\n \"method\":\"POST\",\n \"url\":url,\n \"data\":data\n })\n return ajax\n}", "function ajaxCall(type, url, data, success) {\n $.ajax({\n type: type,\n url: url,\n dataType: \"json\",\n contentType: \"application/json; charset=utf-8\",\n data: data,\n success: function(response) {\n success(response);\n },\n error: function (jqXHR, textStatus, errorThrown) {\n $(\"#data\").append(textStatus + \": Error occured when trying to load from \" + url);\n }\n });\n}", "function fnAjaxRequest(url,sendMethod,params,type){\n let error=null,payload=null;\n \n window.$.ajax({\n \"async\":false,\n \"url\":url,\n \"data\":params,\n \"dataType\":type,\n \"type\":String(sendMethod||\"GET\").toUpperCase(),\n \"error\":function(req,status,err){error=\"ajax: \" + status;},\n \"success\":function(data,status,req){payload=data;}});\n \n if(error){\n throw(error);\n }\n return payload;\n}", "function ajax(method, url, data, success, error) {\n var xhr = new XMLHttpRequest();\n xhr.open(method, url);\n xhr.setRequestHeader(\"Accept\", \"application/json\");\n xhr.onreadystatechange = function() {\n if (xhr.readyState !== XMLHttpRequest.DONE) return;\n if (xhr.status === 200) {\n success(xhr.response, xhr.responseType);\n } else {\n error(xhr.status, xhr.response, xhr.responseType);\n }\n };\n xhr.send(data);\n }", "function callAjaxJson(call_back_func, method, url, field_id, form_id, loading_func, field_element_id) {\n\t\n\t\tvar requester \t= createXmlObject();\n\t\t\tmethod \t\t= method.toUpperCase();\n\n\t\t// Event handler for an event that fires at every state change,\n\t\t// for every state , it will run callback function.\n\t\t// Set the event listener\n\t\trequester.onreadystatechange = \tfunction() { stateHandlerJson(requester, url, call_back_func, field_id, loading_func, field_element_id)}\n\n\t\tswitch (method) {\n\t\t\tcase 'GET':\n\t\t\tcase 'HEAD':\n\t\t\t\trequester.open(method, url);\n\t\t\t\trequester.send(null);\n\t\t\t\tbreak;\n\t\t\tcase 'POST':\n\t\t\t\tquery = generate_query(form_id);\n\t\t\t\trequester.open(method, url);\n\t\t\t\t// In order to get the request body values to show up in $_POST \n\t\t\t\trequester.setRequestHeader(\"Content-Type\", \"application/x-www-form-urlencoded; charset=UTF-8\");\n\t\t\t\trequester.send(query);\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\talert('Error: Unknown method or method not supported');\n\t\t\t\tbreak;\n\t\t}\n\t}", "function ajaxRequest(url,func,obj) {\r\n\tif (window.XMLHttpRequest) {var req = new XMLHttpRequest();}\r\n\telse if (window.ActiveXObject) {try {req = new ActiveXObject(\"Msxml2.XMLHTTP\");}catch(e) {req = new ActiveXObject(\"Microsoft.XMLHTTP\");}}\r\n\tif (func) {req.onreadystatechange = function() {func(req,obj);}}\r\n\treq.open('GET',url,true);\r\n\treq.setRequestHeader('X-Requested-With','XMLHttpRequest');\r\n\treq.setRequestHeader('If-Modified-Since','Wed, 15 Nov 1995 00:00:00 GMT');\r\n\treq.send(null);\r\n\treturn false;\r\n}", "function ajax_request(args, success_func, error_msg_args) {\n\tvar connection = new Ext.data.Connection();\n\tconnection.request(\n\t\t{\n\t\t\turl: args.url,\n\t\t\tmethod: args.method || \"POST\",\n\t\t\tparams: args.params,\n\t\t\t\n\t\t\tcallback: function (options, success, response) {\n\t\t\t\tif(success) {\n\t\t\t\t\tif(success_func(response)) {\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t// not success\n\t\t\t\tExt.Msg.show(\n\t\t\t\t\t{\n\t\t\t\t\t\ttitle: error_msg_args.title,\n\t\t\t\t\t\tmsg: error_msg_args.msg,\n\t\t\t\t\t\tbuttons: Ext.Msg.OK,\n\t\t\t\t\t\ticon: Ext.MessageBox.ERROR,\n\t\t\t\t\t\tminWidth: error_msg_args.minWidth\n\t\t\t\t\t}\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t);\n}", "function ajaxRequest (url, data, onSuccess, method = 'POST', returnDataType = 'JSON', onError = null)\n{\n $.ajax ({\n url: url,\n method: method,\n data: data,\n dataType: returnDataType,\n processData: false,\n contentType: false,\n success: onSuccess,\n error: onError\n });\n}", "function request() {\n var ajax = new _ajaxRequest.default();\n return ajax.request.apply(ajax, arguments);\n }", "function AJAXCaller(URL, data010101, successFunc, errorFunc, timeOut, typeOfRequest, typeOfData, asyncValue ) {\n var xhr;\n\terrorFunc = typeof errorFunc !== 'undefined' ? errorFunc : errorHandle;\n\ttimeOut = typeof timeOut !== 'undefined' ? timeOut : 50000;\n\ttypeOfRequest = typeof typeOfRequest !== 'undefined' ? typeOfRequest : \"POST\";\n\ttypeOfData = typeof typeOfData !== 'undefined' ? typeOfData : \"json\";\n\tasyncValue = typeof asyncValue !== 'undefined' ? asyncValue : true;\n xhr = jQuery.ajax({\n url: URL,\n type: typeOfRequest,\n dataType: typeOfData,\n data: data010101,\n cache: false,\n timeout: timeOut,\n success: successFunc,\n\t\tasync: asyncValue,\n\t\terror: errorFunc\n\t});\n\n\tfunction errorHandle(xhr, ajaxOptions, thrownError) {\n\t\t//alert(thrownError + \"\\r\\n\" + xhr.statusText + \"\\r\\n\" + xhr.responseText);\n\t}\n\n return xhr;\n}", "function Ajax(url, obj) {\n\t\tvar request = null;\n\t\tif (window.XMLHttpRequest) {\n\t\t\trequest = new XMLHttpRequest();\n\t\t} else if (window.ActiveXObject) {\n\t\t\trequest = new ActiveXObject(\"Microsoft.XMLHttp\");\n\t\t}\n\t\tif (request) {\n\t\t\trequest.open(\"POST\", url, true);\n\t\t\trequest.setRequestHeader(\"Content-Type\", \"application/x-www-form-urlencoded; charset=UTF-8\");\n\t\t\trequest.setRequestHeader(\"If-Modified-Since\", \"0\");\n\t\t\trequest.onreadystatechange = function () {\n\t\t\t\tif (request.readyState == 4 && request.status == 200) {\n\t\t\t\t\tobj.innerHTML = request.responseText;\n\t\t\t\t} else {\n\t\t\t\t\tobj.innerHTML = \"Loading....\";\n\t\t\t\t}\n\t\t\t}\n\t\t\trequest.send(null);\n\t\t}\n\t}", "function ajax_call(ajax_obj){\n\t$.ajax({\n\t\turl: ajax_obj.url,\n\t\ttype: ajax_obj.type,\n\t\tdata: ajax_obj.data,\n\t\tdataType: ajax_obj.dataType,\n\t\tsuccess: ajax_obj.onSuccess,\n\t\terror: ajax_obj.onError,\n\t\tcomplete: ajax_obj.onComplete,\n\t\tcache:ajax_obj.cache,\n\t});\n}", "function ajax(method, url, data, success, error) {\r\n var xhr = new XMLHttpRequest();\r\n xhr.open(method, url);\r\n xhr.setRequestHeader(\"Accept\", \"application/json\");\r\n xhr.onreadystatechange = function() {\r\n if (xhr.readyState !== XMLHttpRequest.DONE) return;\r\n if (xhr.status === 200) {\r\n success(xhr.response, xhr.responseType);\r\n } else {\r\n error(xhr.status, xhr.response, xhr.responseType);\r\n }\r\n };\r\n xhr.send(data);\r\n }", "function ajax(method, url, data, success, error) {\n var xhr = new XMLHttpRequest();\n xhr.open(method, url);\n xhr.setRequestHeader(\"Accept\", \"application/json\");\n xhr.onreadystatechange = function () {\n if (xhr.readyState !== XMLHttpRequest.DONE) return;\n if (xhr.status === 200) {\n success(xhr.response, xhr.responseType);\n } else { \n error(xhr.status, xhr.response, xhr.responseType);\n }\n };\n xhr.send(data);\n\n}", "function xhr(url,param,handler,handle_id) {\n var ro=window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject(\"Microsoft.XMLHTTP\");\n ro.open('POST',url,true);\n ro.setRequestHeader('Content-Type','application/x-www-form-urlencoded');\n ro.onreadystatechange=function(){if(ro.readyState==4) handler(ro.responseText,handle_id)};\n ro.send(param);\n}", "function ajax(method, url, data, success, error) {\n var xhr = new XMLHttpRequest();\n xhr.open(method, url);\n xhr.setRequestHeader(\"Accept\", \"application/json\");\n xhr.onreadystatechange = function() {\n if (xhr.readyState !== XMLHttpRequest.DONE) return;\n if (xhr.status === 200) {\n success(xhr.response, xhr.responseType);\n } else {\n error(xhr.status, xhr.response, xhr.responseType);\n }\n };\n xhr.send(data);\n }", "function ajax(method, url, data, success, error) {\r\n var xhr = new XMLHttpRequest();\r\n xhr.open(method, url);\r\n xhr.setRequestHeader(\"Accept\", \"application/json\");\r\n xhr.onreadystatechange = function () {\r\n if (xhr.readyState !== XMLHttpRequest.DONE) return;\r\n if (xhr.status === 200) {\r\n success(xhr.response, xhr.responseType);\r\n } else {\r\n error(xhr.status, xhr.response, xhr.responseType);\r\n }\r\n };\r\n xhr.send(data);\r\n }", "function ajax(method, url, data, success, error) {\r\n var xhr = new XMLHttpRequest();\r\n xhr.open(method, url);\r\n xhr.setRequestHeader(\"Accept\", \"application/json\");\r\n xhr.onreadystatechange = function () {\r\n if (xhr.readyState !== XMLHttpRequest.DONE) return;\r\n if (xhr.status === 200) {\r\n success(xhr.response, xhr.responseType);\r\n } else {\r\n error(xhr.status, xhr.response, xhr.responseType);\r\n }\r\n };\r\n xhr.send(data);\r\n }", "function ajax(method, php, data, cb) {\n var xhr = false;\n if (window.XMLHttpRequest) {\n xhr = new XMLHttpRequest();\n } else if (window.ActiveXObject) {\n xhr = new ActiveXObject(\"Microsoft.XMLHTTP\");\n }\n\n xhr.open(method, php, true);\n xhr.setRequestHeader(\"Content-type\", \"application/x-www-form-urlencoded\")\n xhr.onreadystatechange = function() {\n if ((xhr.readyState == 4) && (xhr.status == 200)) {\n var serverResponse = xhr.responseText;\n cb(serverResponse);\n }\n }\n xhr.send(data);\n}", "function ajax ( type, fichier, variables /* , fonction */ ) \r\n{ \r\n\tif ( window.XMLHttpRequest ) var req = new XMLHttpRequest();\r\n\telse if ( window.ActiveXObject ) var req = new ActiveXObject(\"Microsoft.XMLHTTP\");\r\n\telse alert(\"Votre navigateur n'est pas assez récent pour accéder à cette fonction, ou les ActiveX ne sont pas autorisés\");\r\n\tif ( arguments.length==4 ) var fonction = arguments[3];\r\n\r\n\tif (type.toLowerCase()==\"post\") {\r\n\t\treq.open(\"POST\", _URL+fichier, true);\r\n\t\treq.setRequestHeader('Content-Type','application/x-www-form-urlencoded; charset=iso-8859-1');\r\n\t\treq.send(variables);\r\n\t} else if (type.toLowerCase()==\"get\") {\r\n\t\treq.open('get', _URL+fichier+\"?\"+variables, true);\r\n\t\treq.setRequestHeader('Content-type', 'application/x-www-form-urlencoded; charset=iso-8859-1');\r\n\t\treq.send(null);\r\n\t} else { \r\n\t\talert(\"Méthode d'envoie des données invalide\"); \r\n\t}\r\n\r\n\treq.onreadystatechange = function() { \r\n\t\tif (req.readyState == 4 && req.responseText != null )\r\n\t\t{\t\t\t\t\r\n\t\t\tif (fonction) eval( fonction + \"('\"+escape(req.responseText)+\"')\");\r\n\t\t\t\r\n\t\t} \r\n\t}\r\n}", "function ajax ( type, fichier, variables /* , fonction */ ) \r\n{ \r\n\tif ( window.XMLHttpRequest ) var req = new XMLHttpRequest();\r\n\telse if ( window.ActiveXObject ) var req = new ActiveXObject(\"Microsoft.XMLHTTP\");\r\n\telse alert(\"Votre navigateur n'est pas assez récent pour accéder à cette fonction, ou les ActiveX ne sont pas autorisés\");\r\n\tif ( arguments.length==4 ) var fonction = arguments[3];\r\n\r\n\tif (type.toLowerCase()==\"post\") {\r\n\t\treq.open(\"POST\", _URL+fichier, true);\r\n\t\treq.setRequestHeader('Content-Type','application/x-www-form-urlencoded; charset=iso-8859-1');\r\n\t\treq.send(variables);\r\n\t} else if (type.toLowerCase()==\"get\") {\r\n\t\treq.open('get', _URL+fichier+\"?\"+variables, true);\r\n\t\treq.setRequestHeader('Content-type', 'application/x-www-form-urlencoded; charset=iso-8859-1');\r\n\t\treq.send(null);\r\n\t} else { \r\n\t\talert(\"Méthode d'envoie des données invalide\"); \r\n\t}\r\n\r\n\treq.onreadystatechange = function() { \r\n\t\tif (req.readyState == 4 && req.responseText != null )\r\n\t\t{\t\t\t\t\r\n\t\t\tif (fonction) eval( fonction + \"('\"+escape(req.responseText)+\"')\");\r\n\t\t\t\r\n\t\t} \r\n\t}\r\n}", "function sendAjaxGet(url, func) {\r\n\t//make ur XMLHttpRequest object\r\n\tlet xhr = new XMLHttpRequest() || new ActiveXObject(\"Microsoft.HTTPRequest\");\r\n\txhr.onreadystatechange = function () {\r\n\t\tif(this.readyState === 4 && this.status === 200)\r\n\t\t\tfunc(this); //remember readystate 4 means DONE\r\n\t}\r\n\t\r\n\txhr.open(\"GET\", url);\r\n\txhr.send();\r\n}", "function ajax (params){\n \n // expecting params properties url, successFn, and errorId\n if (!params || !params.url || (!params.successFn && !params.failFn)) {\n alert (\"function ajax requires an input parameter object with properties: url, successFn.\");\n return;\n }\n\n var httpReq;\n if (window.XMLHttpRequest) {\n httpReq = new XMLHttpRequest(); //For Firefox, Safari, Opera\n } else if (window.ActiveXObject) {\n httpReq = new ActiveXObject(\"Microsoft.XMLHTTP\"); //For IE 5+\n } else {\n alert('ajax not supported');\n }\n \n if(!params.query){\n params.query = \"\";\n }\n\n console.log(\"ready to get content \" + params.url + params.query);\n var send = params.url + params.query; // url plus query, if any, to be sent in the request.\n httpReq.open(\"GET\", send); // specify which page you want to get\n\n // Ajax calls are asyncrhonous (non-blocking). Specify the code that you \n // want to run when the response (to the http request) is available. \n httpReq.onreadystatechange = function () {\n\n // readyState == 4 means that the http request is complete\n if (httpReq.readyState === 4) {\n if (httpReq.status === 200) {\n \n try{\n var obj = JSON.parse(httpReq.responseText);\n params.successFn(obj); // like the jQuery ajax call, pass back JSON already parsed to JS objecg\n }\n catch(Exception){\n console.log(\"Error in parsing json. Treating as if there is no JSON intended to be passed, and calling function without params.\");\n var char = httpReq.responseText.charAt(4);\n if(httpReq.responseText !== null && char === \"\"){ // not a json object, but a string was sent back\n params.successFn(httpReq.responseText);\n if(params.passFlag){\n params.passFlag = true; \n }\n }\n else if(params.failFn){\n if(params.passFlag){\n params.passFlag = false;\n }\n params.failFn(); //if a failure function is specified, this is executed.\n }\n else{\n params.successFn(); // if a failure function is not specified, the success function is executed without a parameter.\n }\n }\n \n } else {\n // First use of property creates new (custom) property\n //document.getElementById(params.errorId).innerHTML = \"Error (\" + httpReq.status + \" \" + httpReq.statusText +\n //\") while attempting to read '\" + params.url + \"'\";\n alert(\"Error (\" + httpReq.status + \" \" + httpReq.statusText +\n \") while attempting to read '\" + params.url + \"'\");\n }\n }\n }; // end of anonymous function\n\n httpReq.send(null); // initiate ajax call\n\n} // end function ajax2", "function ajax(method, url, data, success, error) {\n\t\t\t\tvar xhr = new XMLHttpRequest();\n\t\t\t\txhr.open(method, url);\n\t\t\t\txhr.setRequestHeader(\"Accept\", \"application/json\");\n\t\t\t\txhr.onreadystatechange = function () {\n\t\t\t\t\tif (xhr.readyState !== XMLHttpRequest.DONE) return;\n\t\t\t\t\tif (xhr.status === 200) {\n\t\t\t\t\t\tsuccess(xhr.response, xhr.responseType);\n\t\t\t\t\t} else {\n\t\t\t\t\t\terror(xhr.status, xhr.response, xhr.responseType);\n\t\t\t\t\t}\n\t\t\t\t};\n\t\t\t\txhr.send(data);\n\t\t\t}", "function doAjaxWithArgAndReturn(url, requestType, data, updateMethod, responseDataType){\n\ttry{\n\t\tif (responseDataType == undefined || responseDataType == null){\n\t\t\tresponseDataType = \"json\";\n\t\t}\n\t\t$.ajax({\n\t\t\turl : G_URL_Rest + url,\n\t\t\ttype : requestType,\n\t\t\tcontentType : \"application/json\",\n\t\t\tdata : data,\n\t\t\tasync: false,\n\t\t\tcache: false,\n\t\t\tdataType: responseDataType,\n\t\t\tbeforeSend: function(request){\n\t\t\t\trequest.setRequestHeader(\"authorization\", G_Session);\n\t\t\t\tconsole.log(\"doAjaxWithReturn \"+ url + \" request initiated\");\n\t\t\t // Handle the beforeSend event\n\t\t\t\t// Show Loading and parameters preparation\n\t\t\t\tif($('#divLoading').length > 0)\n\t\t\t\t\t$('#divLoading').addClass(\"show\");\n\t\t\t\t$('#successDiv').hide();\n\t\t\t\t$('#errorDiv').hide();\n\t\t\t\tshowInProgress();\n\t\t\t},\n\t\t\tsuccess : updateMethod,\n\t\t\tcomplete: function(data, textStatus, request){\n\t\t\t\t/*if(geturl.getResponseHeader('action')=='logout'){\n\t\t\t\t\tlogoutUser();\n\t\t\t\t}*/\n\t\t\t\tif($('#divLoading').length > 0)\n\t\t\t\t\t$('#divLoading').removeClass(\"show\");\n\t\t\t\tconsole.log(\"doAjaxWithArgAndReturn \"+url +\" request complete\");\n\t\t\t // Handle the complete event\n\t\t\t\t// Hide Loading \n\t\t\t\thideInProgress();\n\t\t\t},\n\t\t\terror: function(data){\n\t\t\t\t//$('#errorMsg').html('Unable to perform User Action, Contact After some time or support');\n\t\t\t\t//$('#errorDiv').show();\n\t\t\t\t$('#msgContainer').html(\"<div class='alert alert-error' id='errorDiv' style='margin-top:10px;margin-bottom:10px'><a class='close' data-dismiss='alert'>x</a><div id='errorMsg'>Internal Server problem Happened,please try again after refresh, If problem exists contact support</div></div>\");\n\t\t\t}\n\t\t});\n\t} catch(error){\n\t\tconsole.log(\"doAjaxWithArgAndReturn \"+error);\n\t}\n}", "function sendAjax(method,params,onResponse,url,elm)\n{\n var xmlhttp;\n if (elm)\n elm.setAttribute(\"value\", \"Please wait...\");\n if (window.XMLHttpRequest)\n {// code for IE7+, Firefox, Chrome, Opera, Safari\n xmlhttp=new XMLHttpRequest();\n }\n else\n {// code for IE6, IE5\n xmlhttp=new ActiveXObject(\"Microsoft.XMLHTTP\");\n }\n xmlhttp.onreadystatechange=function(){\n if (xmlhttp.readyState==4 && xmlhttp.status==200)\n onResponse(xmlhttp);\n };\n if (method==\"POST\")\n {\n xmlhttp.open(\"POST\",url,true);\n \n xmlhttp.setRequestHeader(\"Content-type\",\"application/x-www-form-urlencoded\");\n xmlhttp.send(params);\n }\n else\n {\n if (params!=\"\" && params !=null)\n url=url+\"?\"+params;\n xmlhttp.open(\"GET\",url,true);\n xmlhttp.send();\n }\n \n}", "function run_ajax_call(params,more_params){\n\tvar opts = {\n\t\t\turl: encodeURI(pos_location),\n\t\t\ttype: \"POST\",\n\t\t\tcontentType: \"application/json\",\n\t\t\tdataType: \"json\",\n\t\t\tdata: JSON.stringify(params)\t\t\n\t}\n\t\n\tif(more_params != undefined)\n\t\t$.extend( opts, more_params);\t\n\tconsole.log(more_params)\n\tconsole.log(opts)\t\n\t// DO ajax here\n\txhr = $.ajax(opts);\n}", "function ajaxInvoke(phpFunction, searchParams, container, htmlOperation, lastLoadedVehicleId, limit)\n{\n $.ajax({\n url: url,\n data: { phpFunction: phpFunction, searchParams: searchParams, lastLoadedVehicleId: lastLoadedVehicleId, limit: limit},\n type: \"POST\",\n dataType: \"html\"\n }).done(function (output)\n {\n if (htmlOperation === \"html\") {\n $(\"#\" + container).html(output);\n }\n else if (htmlOperation === \"append\") {\n $(\"#\" + container).append(output);\n }\n });\n}", "function ajax(method, url, data, success, error) {\n var xhr = new XMLHttpRequest();\n xhr.open(method, url);\n xhr.setRequestHeader(\"Accept\", \"application/json\");\n xhr.onreadystatechange = function() {\n if (xhr.readyState !== XMLHttpRequest.DONE) return;\n if (xhr.status === 200) {\n success(xhr.response, xhr.responseType);\n } else {\n error(xhr.status, xhr.response, xhr.responseType);\n }\n };\n xhr.send(data);\n}", "function xhrCall(method, data, endpoint, successHandler, failHandler) {\n var httpRequest = new XMLHttpRequest();\n if (!httpRequest) {\n return failHandler('Giving up :( Cannot create an XMLHTTP instance');\n }\n\n httpRequest.onreadystatechange = handler;\n httpRequest.open(method, endpoint, true);\n if (method.toUpperCase() === 'POST') {\n httpRequest.setRequestHeader(\"Content-type\", \"application/x-www-form-urlencoded\");\n }\n httpRequest.send(data);\n\n function handler() {\n if (httpRequest.readyState === XMLHttpRequest.DONE) {\n if (httpRequest.status === 200) {\n return successHandler(httpRequest.response);\n } else {\n return failHandler(httpRequest);\n }\n }\n } // end handler function \n} // end function xhrCall", "function AjaxRequest(type, url, sendData, responseType, fncSuccess, fncFail)\n{\n var options = {};\n options[\"type\"] = type;\n options[\"url\"] = url;\n options[\"data\"] = sendData;\n options[\"dataType\"] = responseType;\n options[\"success\"] = fncSuccess;\n options[\"error\"] = fncFail;\n $.ajax(options);\n}", "function ajax(method, url, data, success, error) {\n var xhr = new XMLHttpRequest();\n xhr.open(method, url);\n xhr.setRequestHeader(\"Accept\", \"application/json\");\n xhr.onreadystatechange = function() {\n if (xhr.readyState !== XMLHttpRequest.DONE) return;\n if (xhr.status === 200) {\n success(xhr.response, xhr.responseType);\n } else {\n error(xhr.status, xhr.response, xhr.responseType);\n }\n };\n xhr.send(data);\n }", "function ajax(method, url, data, success, error) {\n var xhr = new XMLHttpRequest();\n xhr.open(method, url);\n xhr.setRequestHeader(\"Accept\", \"application/json\");\n xhr.onreadystatechange = function() {\n if (xhr.readyState !== XMLHttpRequest.DONE) return;\n if (xhr.status === 200) {\n success(xhr.response, xhr.responseType);\n } else {\n error(xhr.status, xhr.response, xhr.responseType);\n }\n };\n xhr.send(data);\n }", "function ajax(method, url, data, success, error) {\n var xhr = new XMLHttpRequest();\n xhr.open(method, url);\n xhr.setRequestHeader(\"Accept\", \"application/json\");\n xhr.onreadystatechange = function() {\n if (xhr.readyState !== XMLHttpRequest.DONE) return;\n if (xhr.status === 200) {\n success(xhr.response, xhr.responseType);\n } else {\n error(xhr.status, xhr.response, xhr.responseType);\n }\n };\n xhr.send(data);\n }", "function ajax(method, url, data, success, error) {\n var xhr = new XMLHttpRequest();\n xhr.open(method, url);\n xhr.setRequestHeader(\"Accept\", \"application/json\");\n xhr.onreadystatechange = function() {\n if (xhr.readyState !== XMLHttpRequest.DONE) return;\n if (xhr.status === 200) {\n success(xhr.response, xhr.responseType);\n } else {\n error(xhr.status, xhr.response, xhr.responseType);\n }\n };\n xhr.send(data);\n }", "function wpsc_do_ajax_request( data, success_callback ) {\n\tjQuery.ajax({\n\t\ttype : \"post\",\n\t\tdataType : \"json\",\n\t\turl : wpsc_ajax.ajaxurl,\n\t\tdata : data,\n\t\tsuccess : success_callback\n\t});\n}", "function request(url,type,data,success,error){\n\t\t$.ajax({\n\t\t\t url: url,\n\t\t\t type:type,\n\t\t\t data:data,\n\t\t\t processData: false,\n\t\t\t contentType: false,\n\t\t\t success: success,\n\t\t\t error:error\n\t\t});\n\t}", "function ajax(method, url, data, success, error) {\n var xhr = new XMLHttpRequest();\n xhr.open(method, url);\n xhr.setRequestHeader(\"Accept\", \"application/json\");\n xhr.onreadystatechange = function () {\n if (xhr.readyState !== XMLHttpRequest.DONE) return;\n if (xhr.status === 200) {\n success(xhr.response, xhr.responseType);\n } else {\n error(xhr.status, xhr.response, xhr.responseType);\n }\n };\n xhr.send(data);\n }", "function ajax(method, url, data, success, error) {\r\n var xhr = new XMLHttpRequest();\r\n xhr.open(method, url);\r\n xhr.setRequestHeader(\"Accept\", \"application/json\");\r\n xhr.onreadystatechange = function () {\r\n if (xhr.readyState !== XMLHttpRequest.DONE) return;\r\n if (xhr.status === 200) {\r\n success(xhr.response, xhr.responseType);\r\n } else {\r\n error(xhr.status, xhr.response, xhr.responseType);\r\n }\r\n };\r\n xhr.send(data);\r\n}", "function button_click_fn() {\n\t//call ajax\n\tajax_handler.request({\n url: '/query/end_point',\n async: false,\n method: 'GET',\n response_type: 'json',\n data: { id_value = document.getElementById('el_id').value },\n on_success: function (data) { \n\t\t/*Do things with data*/ \n\t },\n\t on_error: function (status, error_msg) {\n\t if(console) console.log('status:' + status + ' || error msg:' + error_msg);\n\t }\n \t});\n}", "function AjaxCall(url, data, type, loader) {\r\n return $.ajax({\r\n url: url,\r\n type: type ? type : 'GET',\r\n data: data,\r\n contentType: 'application/json',\r\n dataType: \"json\",\r\n async: true,\r\n cache: false,\r\n beforeSend: function () { $(loader).show(); },\r\n complete: function () { $(loader).hide(); }\r\n\r\n });\r\n}", "function ajax(url, method, params, loading, respuesta){\n if(params != null)\n $.ajax({\n data:params,\n url: url,\n type: method,\n beforeSend: loading,\n success: respuesta\n });\n else\n $.ajax({\n url: url,\n type: method,\n beforeSend: loading,\n success: respuesta\n });\n}", "function ajaxCall(url) {\n jQuery.ajax({\n type: 'GET',\n url: 'threddi/ajaxhelper',\n success: displayNewContent, // The js function that will be called upon success request\n error: ajaxTimeout,\n dataType: 'text', //define the type of data that is going to get back from the server\n data: {url: url, spacing: domLevel}, //this data is used by threddi_ajaxhelper function in threddi.module\n timeout: Drupal.settings.threddi.timeout // how long (in milliseconds) until the request times out\n });\n}", "function ajax(method, url, data, success, error) {\n\t\tvar xhr = new XMLHttpRequest();\n\t\txhr.open(method, url);\n\t\txhr.setRequestHeader(\"Accept\", \"application/json\");\n\t\txhr.onreadystatechange = function () {\n\t\t\tif (xhr.readyState !== XMLHttpRequest.DONE) return;\n\t\t\tif (xhr.status === 200) {\n\t\t\t\tsuccess(xhr.response, xhr.responseType);\n\t\t\t} else {\n\t\t\t\terror(xhr.status, xhr.response, xhr.responseType);\n\t\t\t}\n\t\t};\n\t\txhr.send(data);\n }", "function ajax(method, url, data, success, error) {\n var xhr = new XMLHttpRequest();\n xhr.open(method, url);\n xhr.setRequestHeader(\"Accept\", \"application/json\");\n xhr.onreadystatechange = function() {\n if (xhr.readyState !== XMLHttpRequest.DONE) return;\n if (xhr.status === 200) {\n success(xhr.response, xhr.responseType);\n } else {\n error(xhr.status, xhr.response, xhr.responseType);\n }\n };\n xhr.send(data);\n}", "function ajax(method, url, data, success, error) {\n var xhr = new XMLHttpRequest();\n xhr.open(method, url);\n xhr.setRequestHeader(\"Accept\", \"application/json\");\n xhr.onreadystatechange = function () {\n if (xhr.readyState !== XMLHttpRequest.DONE) return;\n if (xhr.status === 200) {\n success(xhr.response, xhr.responseType);\n } else {\n error(xhr.status, xhr.response, xhr.responseType);\n }\n };\n xhr.send(data);\n}", "function makeAjaxcall(url,data,element,callback){\n\telement.parent().prepend($(\"#ajaxSpinnerImage\"));\n\t$.ajax({\n\t\turl:url,\n\t\tdata:data,\n\t\tsuccess: function (response) {\n\t\t\tconsole.log(response);\n\t\t\tcallback(response)\n\t\t}\n\t});\n}", "function sendAjaxGet(url, func) {\n \n // step 1: obtain xhr object (Internet Explorer 5,6 don't have it...)\n let xhr = new XMLHttpRequest() || new ActiveXObject(\"Microsoft.HTTPRequest\");\n // step 2: define onreadystatechange\n xhr.onreadystatechange = function() {\n \n // readyState of 4 means request is complete\n // status of 200 means ok\n if (this.readyState == 4 && this.status == 200) {\n func(this);\n }\n }\n // step 3: prepare the request\n xhr.open(\"GET\", url, true);\n // step 4: send the request\n xhr.send(); \n // IF WE WERE SENDING A POST REQUEST OR ANYTHING THAT USED THE BODY\n // IT WOULD GO AS AN ARGUMENT TO SEND()\n}", "function ajax(endpoint, returnFunction) {\r\n\t\r\n\tlet httpRequest = new XMLHttpRequest();\r\n\thttpRequest.open(\"GET\", endpoint);\t\r\n\thttpRequest.send();\r\n\t\r\n\thttpRequest.onreadystatechange = function() {\r\n\t\t\r\n\t\tif( httpRequest.readyState == 4) {\r\n\t\t\tif(httpRequest.status == 200) {\t\t\t\t\r\n\t\t\t\treturnFunction(httpRequest.responseText);\r\n\t\t\t}\r\n\t\t\telse {\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n}", "function jQueryAjax(webMethodUrl, parameters, requestType, returnDataType, elementId, function_auxiliar) {\n win.showPleaseWait();\n $.ajax({\n url: webMethodUrl,\n type: requestType,\n data: parameters,\n contentType: \"application/json; charset=utf-8\",\n dataType: returnDataType,\n success: function (data) {\n actionExecute(elementId, data);\n if (function_auxiliar != undefined) { function_auxiliar(data); }\n win.hidePleaseWait();\n },\n error: function (xhr, ajaxOptions, thrownError) {\n win.hidePleaseWait();\n var err = eval(\"(\" + xhr.responseText + \")\");\n alert(err.Message);\n }\n });\n}", "function AjaxRequest (url, opts){\r\n var headers = {\r\n 'X-Requested-With': 'XMLHttpRequest',\r\n 'X-Prototype-Version': '1.6.1',\r\n 'Accept': 'text/javascript, text/html, application/xml, text/xml, */*'\r\n };\r\n var ajax = null;\r\n\r\nif (DEBUG_TRACE_AJAX) logit (\"AJAX: \"+ url +\"\\n\" + inspect (opts, 3, 1)); \r\n \r\n if (window.XMLHttpRequest)\r\n ajax=new XMLHttpRequest();\r\n else\r\n ajax=new ActiveXObject(\"Microsoft.XMLHTTP\");\r\n \r\n if (opts.method==null || opts.method=='')\r\n method = 'GET';\r\n else\r\n method = opts.method.toUpperCase(); \r\n \r\n if (method == 'POST'){\r\n headers['Content-type'] = 'application/x-www-form-urlencoded; charset=UTF-8';\r\n } else if (method == 'GET'){\r\n addUrlArgs (url, opts.parameters);\r\n }\r\n\r\n ajax.onreadystatechange = function(){\r\n// ['Uninitialized', 'Loading', 'Loaded', 'Interactive', 'Complete']; states 0-4\r\n if (ajax.readyState==4) {\r\n if (ajax.status >= 200 && ajax.status < 305)\r\n if (opts.onSuccess) opts.onSuccess(ajax);\r\n else\r\n if (opts.onFailure) opts.onFailure(ajax);\r\n } else {\r\n if (opts.onChange) opts.onChange (ajax);\r\n }\r\n } \r\n \r\n ajax.open(method, url, true); // always async!\r\n\r\n for (var k in headers)\r\n ajax.setRequestHeader (k, headers[k]);\r\n if (matTypeof(opts.requestHeaders)=='object')\r\n for (var k in opts.requestHeaders)\r\n ajax.setRequestHeader (k, opts.requestHeaders[k]);\r\n \r\n if (method == 'POST'){\r\n var a = [];\r\n for (k in opts.parameters){\r\n\t if(matTypeof(opts.parameters[k]) == 'object')\r\n\t\tfor(var h in opts.parameters[k])\r\n\t\t\ta.push (k+'['+h+'] ='+ opts.parameters[k][h] );\r\n\t else\r\n a.push (k +'='+ opts.parameters[k] );\r\n\t}\r\n ajax.send (a.join ('&'));\r\n } else {\r\n ajax.send();\r\n }\r\n}", "function makeAjaxRequest(url) {\n var method = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'GET';\n\n\n return method;\n //logic to make the request\n}", "function apiCall(){\r\nxhr.open('GET', url);\r\nxhr.send();\r\n}", "function makeRequest(url,data,funname,httptype) {\n http_request = false;\n \n if (!httptype) httptype = \"GET\";\n\n if (window.XMLHttpRequest) { // If IE7, Mozilla, Safari, etc: Use native object\n http_request = new XMLHttpRequest();\n if (http_request.overrideMimeType) {\n http_request.overrideMimeType('text/xml');\n }\n } else if (window.ActiveXObject) { // ...otherwise, use the ActiveX control for IE5.x and IE6\n try {\n http_request = new ActiveXObject(\"Msxml2.XMLHTTP\");\n } catch (e) {\n try {\n http_request = new ActiveXObject(\"Microsoft.XMLHTTP\");\n } catch (e) {}\n }\n }\n\n if (!http_request) {\n alert('Cannot Create an XMLHttp request');\n return false;\n }\n http_request.onreadystatechange = funname;\n http_request.open(httptype, url, true);\n http_request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');\n http_request.send(data);\n\n}", "function sendAjax(type,url,data,callback){\n $.ajax({\n url: url,\n data: data,\n type: type,\n success: function(result) {\n if (callback!=undefined) callback(result);\n },\n error: function(result){\n if (callback!=undefined) callback(result);\n }\n });\n }", "function ajax(method, url, data, success, error) {\n \n var xhr = new XMLHttpRequest();\n xhr.open(method, url);\n xhr.setRequestHeader(\"Accept\", \"application/json\");\n xhr.onreadystatechange = function () {\n if (xhr.readyState !== XMLHttpRequest.DONE) return;\n if (xhr.status === 200) {\n success(xhr.response, xhr.responseType);\n } else {\n error(xhr.status, xhr.response, xhr.responseType);\n }\n };\n xhr.send(data);\n}", "function requestAjaxData(url, f, es) {\n $.ajax({\n url: url,\n success: function(data) {\n try {\n data = JSON.parse(data);\n }\n catch (e) {\n console.log(url);\n console.log(data);\n throw e;\n }\n if (data.status !== 'success') {\n alert(data.message);\n return;\n }\n\n f(data.data, es);\n },\n error: function() {\n alert('Error occurred when requesting via ajax. Please refresh the page and try again.');\n },\n });\n}", "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 ajax(method, url, data, success, error) {\n\tvar xhr = new XMLHttpRequest();\n\txhr.open(method, url);\n\txhr.setRequestHeader(\"Accept\", \"application/json\");\n\txhr.onreadystatechange = function () {\n\t\tif (xhr.readyState !== XMLHttpRequest.DONE) return;\n\t\tif (xhr.status === 200) {\n\t\t\tsuccess(xhr.response, xhr.responseType);\n\t\t} else {\n\t\t\terror(xhr.status, xhr.response, xhr.responseType);\n\t\t}\n\t};\n\txhr.send(data);\n}", "function ajaxRequest(url, method, param, onSuccess, onFailure){\n\t\tvar xmlHttpRequest = new XMLHttpRequest();\n\t\txmlHttpRequest.onreadystatechange = function() {\n\t\t\tif (xmlHttpRequest.readyState == 4 && xmlHttpRequest.status == 200) onSuccess(xmlHttpRequest);\n\t\t\telse if (xmlHttpRequest.readyState == 4 && xmlHttpRequest.status != 200) onFailure(xmlHttpRequest);\n\t\t};\n\t\txmlHttpRequest.open(method, url, true);\n\t\tif (method == 'POST') xmlHttpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');\n\t\txmlHttpRequest.send(param);\n\t}", "function ajax(method, url, data, success, error) {\n var xhr = new XMLHttpRequest();\n xhr.open(method, url);\n xhr.setRequestHeader(\"Accept\", \"application/json\");\n xhr.onreadystatechange = function() {\n if (xhr.readyState !== XMLHttpRequest.DONE) return;\n if (xhr.status === 200) {\n success(xhr.response, xhr.responseType);\n } else {\n error(xhr.status, xhr.response, xhr.responseType);\n }\n };\n xhr.send(data);\n}", "function ajax(method, url, data, success, error) {\n var xhr = new XMLHttpRequest();\n xhr.open(method, url);\n xhr.setRequestHeader(\"Accept\", \"application/json\");\n xhr.onreadystatechange = function() {\n if (xhr.readyState !== XMLHttpRequest.DONE) return;\n if (xhr.status === 200) {\n success(xhr.response, xhr.responseType);\n } else {\n error(xhr.status, xhr.response, xhr.responseType);\n }\n };\n xhr.send(data);\n}", "function ajax(method, url, data, success, error) {\n var xhr = new XMLHttpRequest();\n xhr.open(method, url);\n xhr.setRequestHeader(\"Accept\", \"application/json\");\n xhr.onreadystatechange = function() {\n if (xhr.readyState !== XMLHttpRequest.DONE) return;\n if (xhr.status === 200) {\n success(xhr.response, xhr.responseType);\n } else {\n error(xhr.status, xhr.response, xhr.responseType);\n }\n };\n xhr.send(data);\n}", "function ajaxFunction(controller,elementID)\r\n{\r\n\tajaxFunction(controller,elementID,'');\r\n\r\n}", "function makeAjaxCall(urlToCall){\r\n\tvar ajaxObject = getAjaxObj();\r\n\t\r\n\tajaxObject.onreadystatechange=function(){\r\n\t\tif(ajaxObject.readyState == 4){\r\n\t\t\tif(ajaxObject.status == 200){\r\n\t\t\t\t//la llamada termino ok\r\n\t\t\t\t//inyectamos la respuesta\r\n\t\t\t\tdocument.getElementById(\"pagingValues\").innerHTML = ajaxObject.responseText;\r\n\t\t\t} else {\r\n\t\t\t\talert(mensajeErrorAjaxInvocacion);\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\tdocument.getElementById(\"ajaxExecution\").style.display = \"none\";\r\n\t\t\tdocument.getElementById(\"pagingValues\").style.display = \"block\";\r\n\t\t}\r\n\t};\r\n\t\r\n\t//colocamos la imagen de \"cargando\"\r\n\tdocument.getElementById(\"pagingValues\").style.display = \"none\";\r\n\tdocument.getElementById(\"ajaxExecution\").style.display = \"inline-table\";\r\n\t\r\n\tajaxObject.open(\"POST\", urlToCall);\r\n\tajaxObject.send(null);\r\n}", "function ajaxCall(type, url, data) {\n return $.ajax({ // return the promise that `$.ajax` returns\n type: type,\n url: url,\n data: JSON.stringify(data),\n contentType: 'application/json; charset=utf-8',\n dataType: \"json\",\n processData: true,\n });\n}", "ajaxCall(actionStr, urlStr, dataObj = {}) {\n return new Promise((resolve) => {\n let req = $.ajax({\n type: actionStr,\n url: this.baseURL + urlStr,\n data: dataObj\n });\n req.done((data) => {\n resolve(data);\n });\n });\n }", "function ajax(method, url, data, success, error) {\n var xhr = new XMLHttpRequest();\n xhr.open(method, url);\n\n xhr.setRequestHeader(\"Accept\", \"application/json\");\n\n xhr.onreadystatechange = function() {\n if (xhr.readyState !== XMLHttpRequest.DONE) return;\n\n if (xhr.status === 200) {\n success(xhr.response, xhr.responseType);\n } else {\n error(xhr.status, xhr.response, xhr.responseType);\n }\n };\n\n xhr.send(data);\n }", "function ajax(u,d){\n return $.ajax({\n url:u,\n data:d,\n type:'post',\n dataType:'json'\n });\n }", "function AjaxHelper(url, dataType, type, async, element) {\n $.ajax({\n url: url,\n dataType: dataType,\n type: type,\n async: async,\n success: function (data) {\n $(element).html(data);\n },\n error: function (jqXhr, textStatus, errorThrown) {\n alert('Error!');\n }\n });\n}", "buildRequest(resource, successFunc, failFunc, extraHeaders, method, postData) {\n\t\t$.ajax({\n\t\t\ttype: method, //GET or POST\n\t\t\tdataType: \"text\",\n\t\t\tdata: postData, //Set the reuqest body\n\t\t\turl: \"http://127.0.0.1/\" + resource, //Set the requested function\n\t\t\tsuccess: successFunc, //Success callback\n\t\t\terror: failFunc, //Error callback\n\t\t\theaders: extraHeaders, //Extra headers\n\t\t\ttimeout: 3000 //Default 3 second connection timeout (should be ok for localhost)\n\t\t});\n\t}", "function theia_ajax_get(id, s, f){\n\tvar url = server_url + request_page;\n\t$.ajax({\n\t\turl:url,\n\t\tdata:{\"id\":id},\n\t\terror:f,\n\t\tsuccess:s,\n\t\tdataType:\"json\",\n\t\ttype:\"GET\"\n\t});\n}", "function ajax() {\r\n return $.ajax({\r\n url: 'http://127.0.0.1:5000/send_url',\r\n data: {\r\n 'url': tabUrl.toString(),\r\n 'username': customerUserName\r\n },\r\n type: 'GET',\r\n dataType: 'json',\r\n success: function(data){ ajaxResults = data}\r\n })\r\n }", "function __ajax(url, data){\n var ajax = $.ajax({\n \"method\": \"POST\",\n \"url\": url,\n \"data\": data\n })\n return ajax;\n}", "function doAjaxGet(url, parameters)\r\n{\r\n\treturn doAjax(\"GET\", url, parameters);\r\n}", "function teacher_ajaxcall() {\n response = $.ajax({\n url: \"/teacher_refresh/\",\n });\n}", "function jqueryAjax(method, url, data, callback) {\n\t\treturn $.ajax({\n\t\t\turl: url,\n\t\t\tdata: data,\n\t\t\tmethod: method,\n\t\t\tsuccess: callback\n\t\t});\n\t}", "function call_ajax(url, parameters, element, execute_on_response) {\n\t\t\t\n\tvar request = false;\n var date = new Date();\n var time = date.getTime();\n\t\n\tloading_element = document.getElementById(element);\n\tloading_element.innerHTML = \"Loading...\";\n\t\n\tif(window.XMLHttpRequest) {\n\t\trequest = new XMLHttpRequest();\n\t\tif (request.overrideMimeType) {\n\t\t\trequest.overrideMimeType('text/xml');\n\t\t}\n\t} else if(window.ActiveXObject) {\n\t\ttry {\n\t\t\trequest = new ActiveXObject(\"Msxml2.XMLHTTP\");\n\t\t} catch(e) {\n\t\t\ttry {\n\t\t\t\trequest = new ActiveXObject(\"Microsoft.XMLHTTP\");\n\t\t\t} catch(e) {}\n\t\t}\t \n\t}\n\t\n\tif (!request) {\n return false;\n\t}\n\n\tif(parameters) {\n\t parameters += \"&t=\" + time;\n\t} else {\n\t parameters = \"t=\" + time;\n\t}\n\t\n\turl = url + \"?\" + parameters;\n\t\n\tif (typeof execute_on_response == \"undefined\") {\n\t\trequest.onreadystatechange = function() { response_ajax(request, element); };\n\t} else {\n\t\trequest.onreadystatechange = function() { response_ajax(request, element, execute_on_response); };\n\t}\n\trequest.open(\"GET\", url, true);\n request.send(null);\n}", "function ajaxRequest(url, method, param, onSuccess, onFailure){\r\n\t\tvar xmlHttpRequest = new XMLHttpRequest();\r\n\t\txmlHttpRequest.onreadystatechange = function() {\r\n\t\t\tif (xmlHttpRequest.readyState == 4 && xmlHttpRequest.status == 200 && onSuccess != null) onSuccess(xmlHttpRequest);\r\n\t\t\telse if (xmlHttpRequest.readyState == 4 && xmlHttpRequest.status != 200 && onFailure != null) onFailure(xmlHttpRequest);\r\n\t\t};\r\n\t\txmlHttpRequest.open(method, url, true);\r\n\t\txmlHttpRequest.url = url;\r\n\t\tif (method == 'POST') xmlHttpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');\r\n\t\txmlHttpRequest.send(param);\r\n\t}", "function sendRequest() {\n if (window.XMLHttpRequest) {\n req = new XMLHttpRequest();\n } else {\n req = new ActiveXObject(\"Microsoft.XMLHTTP\");\n }\n req.onreadystatechange = handleResponse;\n req.open(\"GET\", \"/get_post_json\", true);\n req.send(); \n}", "function ajax(method, url, data, success, error) {\n let xhr = new XMLHttpRequest();\n xhr.open(method, url);\n xhr.setRequestHeader(\"Accept\", \"application/json\");\n xhr.onreadystatechange = function() {\n if (xhr.readyState !== XMLHttpRequest.DONE) return;\n if (xhr.status === 200) {\n success(xhr.response, xhr.responseType);\n } else {\n error(xhr.status, xhr.response, xhr.responseType);\n }\n };\n xhr.send(data);\n }", "function doAjax( endpoint, data ) {\n\treturn jQuery.ajax( {\n\t\turl: endpoint,\n\t\tdataType: 'json',\n\t\tdata: data\n\t} );\n}" ]
[ "0.7367697", "0.7197598", "0.71736264", "0.7151691", "0.7071032", "0.70672566", "0.7049878", "0.7023651", "0.7004157", "0.69736546", "0.695231", "0.69519967", "0.6913252", "0.6913252", "0.68934417", "0.68720675", "0.6870236", "0.68623143", "0.6851088", "0.6849855", "0.68358433", "0.6832907", "0.68147826", "0.68020236", "0.67863", "0.67854255", "0.677609", "0.67711514", "0.6765345", "0.6765111", "0.6764844", "0.67558587", "0.67532736", "0.67528605", "0.6751598", "0.6741348", "0.6741348", "0.67377186", "0.6736834", "0.6736834", "0.6732185", "0.67140466", "0.67086256", "0.67074794", "0.67050207", "0.67046165", "0.66938335", "0.6693721", "0.668917", "0.6682918", "0.66823614", "0.66823614", "0.66823614", "0.66823614", "0.6679187", "0.66667354", "0.6662643", "0.6660234", "0.6659987", "0.66595113", "0.665471", "0.6647951", "0.66452956", "0.6644456", "0.6630693", "0.66261286", "0.6625948", "0.66250855", "0.6622136", "0.66152817", "0.66106975", "0.6608054", "0.6605862", "0.659806", "0.659073", "0.6584263", "0.6583177", "0.65803176", "0.6575731", "0.6572558", "0.6572558", "0.6572558", "0.65691274", "0.6564195", "0.65634304", "0.6561766", "0.65597296", "0.65581334", "0.65515566", "0.6542052", "0.6541197", "0.6540296", "0.65367746", "0.6529272", "0.65280735", "0.6526024", "0.65258145", "0.65245783", "0.6521715", "0.65178776", "0.6509991" ]
0.0
-1
adds the implied classes (Object, IO, Integer, etc.) to our program node's class list
function addBuiltinObjects(programNode) { // Object class var objectClass = new CoolToJS.ClassNode('Object'); var abortMethodNode = new CoolToJS.MethodNode(); abortMethodNode.methodName = 'abort'; abortMethodNode.returnTypeName = 'Object'; abortMethodNode.parent = objectClass; objectClass.children.push(abortMethodNode); var typeNameMethodNode = new CoolToJS.MethodNode(); typeNameMethodNode.methodName = 'type_name'; typeNameMethodNode.returnTypeName = 'String'; typeNameMethodNode.parent = objectClass; objectClass.children.push(typeNameMethodNode); var copyMethodNode = new CoolToJS.MethodNode(); copyMethodNode.methodName = 'copy'; copyMethodNode.returnTypeName = 'SELF_TYPE'; copyMethodNode.parent = objectClass; objectClass.children.push(copyMethodNode); programNode.children.push(objectClass); // IO Class var ioClass = new CoolToJS.ClassNode('IO'); var outStringMethodNode = new CoolToJS.MethodNode(); outStringMethodNode.methodName = 'out_string'; outStringMethodNode.returnTypeName = 'SELF_TYPE'; outStringMethodNode.parameters.push({ parameterName: 'x', parameterTypeName: 'String' }); outStringMethodNode.parent = ioClass; ioClass.children.push(outStringMethodNode); var outIntMethodNode = new CoolToJS.MethodNode(); outIntMethodNode.methodName = 'out_int'; outIntMethodNode.returnTypeName = 'SELF_TYPE'; outIntMethodNode.parameters.push({ parameterName: 'x', parameterTypeName: 'Int' }); outIntMethodNode.parent = ioClass; ioClass.children.push(outIntMethodNode); var inStringMethodNode = new CoolToJS.MethodNode(); inStringMethodNode.methodName = 'in_string'; inStringMethodNode.returnTypeName = 'String'; inStringMethodNode.isAsync = true; inStringMethodNode.isInStringOrInInt = true; inStringMethodNode.parent = ioClass; ioClass.children.push(inStringMethodNode); var inIntMethodNode = new CoolToJS.MethodNode(); inIntMethodNode.methodName = 'in_int'; inIntMethodNode.returnTypeName = 'Int'; inIntMethodNode.isAsync = true; inIntMethodNode.isInStringOrInInt = true; inIntMethodNode.parent = ioClass; ioClass.children.push(inIntMethodNode); programNode.children.push(ioClass); // Int var intClass = new CoolToJS.ClassNode('Int'); programNode.children.push(intClass); // String var stringClass = new CoolToJS.ClassNode('String'); var lengthMethodNode = new CoolToJS.MethodNode(); lengthMethodNode.methodName = 'length'; lengthMethodNode.returnTypeName = 'Int'; lengthMethodNode.parent = stringClass; stringClass.children.push(lengthMethodNode); var concatMethodNode = new CoolToJS.MethodNode(); concatMethodNode.methodName = 'concat'; concatMethodNode.returnTypeName = 'String'; concatMethodNode.parameters.push({ parameterName: 's', parameterTypeName: 'String' }); concatMethodNode.parent = stringClass; stringClass.children.push(concatMethodNode); var substrMethodNode = new CoolToJS.MethodNode(); substrMethodNode.methodName = 'substr'; substrMethodNode.returnTypeName = 'String'; substrMethodNode.parameters.push({ parameterName: 'i', parameterTypeName: 'Int' }); substrMethodNode.parameters.push({ parameterName: 'l', parameterTypeName: 'Int' }); stringClass.parent = stringClass; stringClass.children.push(substrMethodNode); programNode.children.push(stringClass); // Bool var boolClass = new CoolToJS.ClassNode('Bool'); programNode.children.push(boolClass); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function classes(root) {\n\t\t\t\t\t\t var classes = [];\n\n\t\t\t\t\t\t function recurse(name, node) {\n\t\t\t\t\t\t if (node.children) node.children.forEach(function(child) { recurse(node.name, child); });\n\t\t\t\t\t\t else classes.push({packageName: name, className: node.name, value: node.size});\n\t\t\t\t\t\t }\n\n\t\t\t\t\t\t recurse(null, root);\n\t\t\t\t\t\t return {children: classes};\n\t\t\t\t\t\t}", "function exAddClass(node, name) {\n var list = node.classList;\n var parts = name.split(/\\s+/);\n for (var i = 0, n = parts.length; i < n; ++i) {\n if (parts[i])\n list.add(parts[i]);\n }\n}", "function writeNodeClasses(node) {\n for (var i in node.classList) { // classes\n addSelectorIfNodeMatchesRule(node, node.classList[i]);\n }\n addSelectorIfNodeMatchesRule(node, node.id); // id\n addSelectorIfNodeMatchesRule(node, node.localName); // tag name\n }", "function classes(root) {\n var classes = [];\n\n function recurse(name, node) {\n if (node.children) node.children.forEach(function(child) { recurse(node.name, child); });\n else classes.push({packageName: name, className: node.name, value: node.size});\n }\n\n recurse(null, root);\n return {children: classes};\n }", "function classes(root) {\r\n\t\t var classes = [];\r\n\r\n\t\t function recurse(name, node) {\r\n\t\t if (node.children) node.children.forEach(function(child) { recurse(node.name, child); });\r\n\t\t else classes.push({packageName: name, className: node.name, value: node.size});\r\n\t\t }\r\n\r\n\t\t recurse(null, root);\r\n\t\t return {children: classes};\r\n\t\t}", "function classes(root) {\n\t\t\t\t var classes = [];\n\n\t\t\t\t function recurse(name, node) {\n\t\t\t\t\tif (node.children) node.children.forEach(function(child) { recurse(node.name, child); });\n\t\t\t\t\telse classes.push({packageName: name, className: node.name, value: node.size});\n\t\t\t\t }\n\n\t\t\t\t recurse(null, root);\n\t\t\t\t return {children: classes};\n\t\t\t\t}", "function DeclareClass(node, print) {\n this.push(\"declare class \");\n this._interfaceish(node, print);\n}", "function classes(root) {\n var classes = [];\n\n function recurse(name, node) {\n if (node.children) node.children.forEach(function(child) { recurse(node.name, child); });\n else classes.push({packageName: name, className: node.name, value: node.size});\n }\n\n recurse(null, root);\n return {children: classes};\n }", "function classes(root) {\n var classes = [];\n function recurse(name, node) {\n if (node.children) node.children.forEach(function(child) { recurse(node.name, child); });\n else classes.push({packageName: name, className: node.name, value: node.size});\n }\n recurse(null, root);\n return {children: classes};\n}", "function classes(root) {\n var classes = [];\n\n function recurse(name, node) {\n if (node.children) node.children.forEach(function(child) { recurse(node.name, child); });\n else classes.push({packageName: name, className: node.name, value: node.size});\n }\n\n recurse(null, root);\n return {children: classes};\n}", "function classes(root) {\n var classes = [];\n\n function recurse(name, node) {\n if (node.children) node.children.forEach(function(child) { recurse(node.name, child); });\n else classes.push({packageName: node.name, className: node.name, value: node.size});\n }\n\n recurse(null, root);\n //console.log({children:classes});\n return {children: classes};\n\n }", "function classes(root) {\n\t var classes = [];\n\n\t function recurse(name, node) {\n\t if (node.children) node.children.forEach(function(child) { recurse(node.name, child); });\n\t else classes.push({packageName: name, className: node.name, value: node.size});\n\t }\n\n\t recurse(null, root);\n\t return {children: classes};\n\t}", "function classes(root) {\n var classes = [];\n\n function recurse(name, node) {\n if (node.children) node.children.forEach(function(child) { recurse(node.name, child); });\n else classes.push({packageName: name, className: node.name, value: node.size});\n }\n\n recurse(null, root);\n return {children: classes};\n }", "function classes(root) {\n var classes = [];\n\n function recurse(name, node) {\n if (node.children) node.children.forEach(function(child) { recurse(node.name, child); });\n else classes.push({packageName: node.name, className: node.name, value: pScale(node.size) });\n }\n\n recurse(null, root);\n //console.log({children:classes});\n return {children: classes};\n\n }", "function DeclareClass(node, print) {\n\t this.push(\"declare class \");\n\t this._interfaceish(node, print);\n\t}", "function DeclareClass(node, print) {\n\t this.push(\"declare class \");\n\t this._interfaceish(node, print);\n\t}", "function uuklassadd(node, // @param Node:\r\n classNames) { // @param String: \"class1 class2 ...\"\r\n // @return Node:\r\n node.className += \" \" + classNames; // [OPTIMIZED] // uutriminner()\r\n return node;\r\n}", "function classes(root) {\n var classes = [];\n\n function recurse(name, node) {\n if (node.children) node.children.forEach(function (child) {\n recurse(node.name, child);\n });\n else classes.push({\n packageName: name,\n className: node.name,\n value: node.size\n });\n }\n\n recurse(null, root);\n return {\n children: classes\n };\n}", "function classes(root) {\n\t\t\t\t\tvar classes = [];\n\n\t\t\t\t\tfunction recurse(name, node) {\n\t\t\t\t\t\tif (node.children) node.children.forEach(function(child) {\n\t\t\t\t\t\t\trecurse(node.name, child);\n\t\t\t\t\t\t});\n\t\t\t\t\t\telse classes.push({\n\t\t\t\t\t\t\tpackageName: name,\n\t\t\t\t\t\t\tclassName: node.name,\n\t\t\t\t\t\t\tvalue: node.size,\n\t\t\t\t\t\t\tid: node.id,\n\t\t\t\t\t\t\tgenre: node.genre,\n\t\t\t\t\t\t\tviews: node.views,\n\t\t\t\t\t\t\tproportion: node.size/totalLikes\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\n\t\t\t\t\trecurse(null, root);\n\t\t\t\t\treturn {\n\t\t\t\t\t\tchildren: classes\n\t\t\t\t\t};\n\t\t\t\t}", "function _Classes()\n{\n if (typeof(_classes) != 'undefined')\n throw('Only one instance of _Classes() can be created');\n \n function registerClass(className, parentClassName)\n {\n if (!className)\n throw('xbObjects.js:_Classes::registerClass: className missing');\n \n if (className in _classes)\n return;\n \n if (className != 'xbObject' && !parentClassName)\n parentClassName = 'xbObject';\n \n if (!parentClassName)\n parentClassName = null;\n else if ( !(parentClassName in _classes))\n throw('xbObjects.js:_Classes::registerClass: parentClassName ' + parentClassName + ' not defined');\n\n // evaluating and caching the prototype object in registerClass\n // works so long as we are dealing with 'normal' source files\n // where functions are created in the global context and then \n // statements executed. when evaling code blocks as in xbCOM,\n // this no longer works and we need to defer the prototype caching\n // to the defineClass method\n\n _classes[className] = { 'classConstructor': null, 'parentClassName': parentClassName };\n }\n _Classes.prototype.registerClass = registerClass;\n\n function defineClass(className, prototype_func)\n {\n var p;\n\n if (!className)\n throw('xbObjects.js:_Classes::defineClass: className not given');\n \n var classRef = _classes[className];\n if (!classRef)\n throw('xbObjects.js:_Classes::defineClass: className ' + className + ' not registered');\n \n if (classRef.classConstructor)\n return;\n \n classRef.classConstructor = eval( className );\n var childPrototype = classRef.classConstructor.prototype;\n var parentClassName = classRef.parentClassName;\n \n if (parentClassName)\n {\n var parentClassRef = _classes[parentClassName];\n if (!parentClassRef)\n throw('xbObjects.js:_Classes::defineClass: parentClassName ' + parentClassName + ' not registered');\n\n if (!parentClassRef.classConstructor)\n {\n // force parent's prototype to be created by creating a dummy instance\n // note constructor must handle 'default' constructor case\n var dummy;\n eval('dummy = new ' + parentClassName + '();');\n }\n \n var parentPrototype = parentClassRef.classConstructor.prototype;\n \n for (p in parentPrototype)\n {\n switch (p)\n {\n case 'isa':\n case 'classRef':\n case 'parentPrototype':\n case 'parentConstructor':\n case 'inheritedFrom':\n break;\n default:\n childPrototype[p] = parentPrototype[p];\n break;\n }\n }\n }\n\n prototype_func();\n \n childPrototype.isa = className;\n childPrototype.classRef = classRef;\n\n // cache method implementor info\n childPrototype.inheritedFrom = new Object();\n if (parentClassName)\n {\n for (p in parentPrototype)\n {\n switch (p)\n {\n case 'isa':\n case 'classRef':\n case 'parentPrototype':\n case 'parentConstructor':\n case 'inheritedFrom':\n break;\n default:\n if (childPrototype[p] == parentPrototype[p] && parentPrototype.inheritedFrom[p])\n {\n childPrototype.inheritedFrom[p] = parentPrototype.inheritedFrom[p];\n }\n else\n {\n childPrototype.inheritedFrom[p] = parentClassName;\n }\n break;\n }\n }\n }\n }\n _Classes.prototype.defineClass = defineClass;\n}", "function getClassList(type) {\n\t\t\tvar classList = davinci.ve.metadata.queryDescriptor(type, 'class');\n\t\t\tif (classList) {\n\t\t\t\tclassList = classList.split(/\\s+/);\n\t\t\t\tclassList.push(type);\n\t\t\t\treturn classList;\n\t\t\t}\n\t\t\treturn [type];\n\t\t}", "onClassChange() {\n for ( let i = 0; i < this.node.pdomClasses.length; i++ ) {\n const dataObject = this.node.pdomClasses[ i ];\n this.setClassToElement( dataObject.className, dataObject.options );\n }\n }", "get classList() {\n if (!this.hasAttribute(\"class\")) {\n return new DOMTokenList(null, null);\n }\n const classes = this.getAttribute(\"class\", true)\n .filter((attr) => attr.isStatic)\n .map((attr) => attr.value)\n .join(\" \");\n return new DOMTokenList(classes, null);\n }", "function classes(root) {\n var classes = [];\n\n function recurse(name, node) {\n if (node.children) node.children.forEach(function(child) { recurse(node.name, child); });\n else {\n \t\tvar d = new Date(node.date)\n \t\tnode.date_fmt = d.strftime\n \t\t\t\t\t\t\t? d.strftime(input.style.date_format)\n \t\t\t\t\t\t\t: node.date.substr(8,2)+\".\"+node.date.substr(5,2)+\".\"+node.date.substr(0,4);\n\n classes.push({packageName: name, className: node.name, value: node.size, for_print:node.for_print, date:node.date_fmt});\n }\n }\n\n recurse(null, root);\n return {children: classes};\n }", "function add (domNode, classes) {\n classes.split(' ').forEach(function (c) {\n if (!has(domNode, c)) {\n domNode.setAttribute('class', domNode.getAttribute('class') + ' ' + c);\n }\n });\n}", "function createElementModAddClass(type, parent, classname) {\n var telem = document.createElement(type);\n telem.classList.add(classname);\n parent.appendChild(telem);\n}", "function classes(root) {\n var classes = [];\n\n//pushing hashes into an array here, renamed our keyvalue set, can add year here too\n function recurse(name, node) {\n if (node.children) node.children.forEach(function(child) { recurse(node.name, child); });\n else classes.push({packageName: name, className: node.name, value: node.size, url: node.url});\n }\n\n recurse(null, root);\n return {children: classes};\n}", "function getAllClasses() {\n return readObject('classes');\n\n }", "bind() {\n\t\tvar classnames = [];\n\n\t\t// add new classes if not already added\n\t\tvar names = typeof this.resolver.resolved === 'string' ? [this.resolver.resolved.trim()] : this.resolver.resolved;\n\t\tfor (var a in names)\n\t\t{\n\t\t\tvar classname = isNaN(a) ? a.trim() : names[a].trim();\n\t\t\tif (typeof a === 'string' && !names[a]) continue; // skip falsy objects\n\t\t\tclassnames.push(classname); // add already present to stack\n\t\t\tif (new RegExp('([^a-z0-9_-]{1}|^)' + classname + '([^a-z0-9_-]{1}|$)').test(this.node.className)) continue; // skip already present\n\n\t\t\tthis.node.className += ' ' + classname + ' ';\n\t\t\tclassnames.push(classname);\n\t\t}\n\n\t\t// remove any that where there previosly but now not in stack\n\t\tif (this.classnames.length > 0)\n\t\t{\n\t\t\t// remove any classes not in\n\t\t\tfor (var i = 0; i < this.classnames.length; i++)\n\t\t\t{\n\t\t\t\tif (classnames.indexOf(this.classnames[i]) >= 0) continue;\n\t\t\t\tthis.node.className = this.node.className.replace(new RegExp('([^a-z0-9_-]{1}|^)' + this.classnames[i] + '([^a-z0-9_-]{1}|$)', 'g'), ' ');\n\n\t\t\t}\n\t\t}\n\n\t\t// update node and cache stack\n\t\tthis.node.className = this.node.className.replace(/\\s{1}\\s{1}/g, ' ');\n\t\tthis.classnames = classnames;\n\t}", "function RegisteredClasses (application) {\n this.application = application;\n this._classes = {};\n}", "get classes()\n {\n var instanciable = this.instanciable;\n if(!instanciable) return [_object];\n return instanciable.supClasses;\n }", "_$kind() {\n super._$kind();\n this._value.kind = 'class';\n }", "function classes(root) {\n const classes = [];\n\n for (const node of root) {\n if (node.key) {\n classes.push({\n packageName: node.key,\n className: node.key,\n value: node.value\n });\n }\n }\n return {children: classes};\n}", "showClasses(classElements) {\n const props = this.props\n classElements.forEach(item => {\n props.classListElement.appendChild(item)\n })\n }", "function addClasses(el) {\n eachDom(el.querySelectorAll(\"[data-add-class]\"), function (el) {\n var cls = el.getAttribute(\"data-add-class\");\n if (cls) el.classList.add(cls);\n });\n }", "function addClasses(el) {\n eachDom(el.querySelectorAll(\"[data-add-class]\"), function (el) {\n var cls = el.getAttribute(\"data-add-class\");\n if (cls) el.classList.add(cls);\n });\n }", "function createClassAttribute(vnode) {\n const {\n elm,\n data: {\n classMap\n },\n owner: {\n renderer\n }\n } = vnode;\n\n if (isUndefined$3(classMap)) {\n return;\n }\n\n const classList = renderer.getClassList(elm);\n\n for (const name in classMap) {\n classList.add(name);\n }\n }", "async function getClasses () {\n try {\n console.log('nothing')\n } catch (error) {\n console.log(error)\n }\n }", "function classAdd(me, strin) {\n me.className += \" \" + strin;\n }", "classType () {\n const depTypeFn = depTypes[String(this.currentAstNode)]\n if (!depTypeFn) {\n throw Object.assign(\n new Error(`\\`${String(this.currentAstNode)}\\` is not a supported dependency type.`),\n { code: 'EQUERYNODEPTYPE' }\n )\n }\n const nextResults = depTypeFn(this.initialItems)\n this.processPendingCombinator(nextResults)\n }", "function findClassNames() {\n\n if (SC._object_foundObjectClassNames) return ;\n SC._object_foundObjectClassNames = true ;\n\n var seen = [] ;\n var searchObject = function(root, object, levels) {\n levels-- ;\n\n // not the fastest, but safe\n if (seen.indexOf(object) >= 0) return ;\n seen.push(object) ;\n\n for(var key in object) {\n if (key == '__scope__') continue ;\n if (key == 'superclass') continue ;\n if (!key.match(/^[A-Z0-9]/)) continue ;\n\n var path = (root) ? [root,key].join('.') : key ;\n var value = object[key] ;\n\n\n switch(SC.typeOf(value)) {\n case SC.T_CLASS:\n if (!value._object_className) value._object_className = path;\n if (levels>=0) searchObject(path, value, levels) ;\n break ;\n\n case SC.T_OBJECT:\n if (levels>=0) searchObject(path, value, levels) ;\n break ;\n\n case SC.T_HASH:\n if (((root) || (path==='SC')) && (levels>=0)) searchObject(path, value, levels) ;\n break ;\n\n default:\n break;\n }\n }\n } ;\n\n searchObject(null, require('system', 'default').global, 2) ;\n\n // Internet Explorer doesn't loop over global variables...\n /*if ( SC.browser.isIE ) {\n searchObject('SC', SC, 2) ; // get names for the SC classes\n\n // get names for the model classes, including nested namespaces (untested)\n for ( var i = 0; i < SC.Server.servers.length; i++ ) {\n var server = SC.Server.servers[i];\n if (server.prefix) {\n for (var prefixLoc = 0; prefixLoc < server.prefix.length; prefixLoc++) {\n var prefixParts = server.prefix[prefixLoc].split('.');\n var namespace = window;\n var namespaceName;\n for (var prefixPartsLoc = 0; prefixPartsLoc < prefixParts.length; prefixPartsLoc++) {\n namespace = namespace[prefixParts[prefixPartsLoc]] ;\n namespaceName = prefixParts[prefixPartsLoc];\n }\n searchObject(namespaceName, namespace, 2) ;\n }\n }\n }\n }*/\n}", "function add_css_class(dom_ob, cl) {\n var classes=dom_ob.className.split(\" \");\n\n if(!in_array(cl, classes)) {\n classes.push(cl);\n }\n\n dom_ob.className=classes.join(\" \");\n\n return classes;\n}", "static applyReflectionClasses(reflection) {\n const classes = [];\n let kind;\n if (reflection.kind === index_1.ReflectionKind.Accessor) {\n if (!reflection.getSignature) {\n classes.push(\"tsd-kind-set-signature\");\n }\n else if (!reflection.setSignature) {\n classes.push(\"tsd-kind-get-signature\");\n }\n else {\n classes.push(\"tsd-kind-accessor\");\n }\n }\n else {\n kind = index_1.ReflectionKind[reflection.kind];\n classes.push(DefaultTheme.toStyleClass(\"tsd-kind-\" + kind));\n }\n if (reflection.parent &&\n reflection.parent instanceof index_1.DeclarationReflection) {\n kind = index_1.ReflectionKind[reflection.parent.kind];\n classes.push(DefaultTheme.toStyleClass(`tsd-parent-kind-${kind}`));\n }\n let hasTypeParameters = !!reflection.typeParameters;\n reflection.getAllSignatures().forEach((signature) => {\n hasTypeParameters = hasTypeParameters || !!signature.typeParameters;\n });\n if (hasTypeParameters) {\n classes.push(\"tsd-has-type-parameter\");\n }\n if (reflection.overwrites) {\n classes.push(\"tsd-is-overwrite\");\n }\n if (reflection.inheritedFrom) {\n classes.push(\"tsd-is-inherited\");\n }\n if (reflection.flags.isPrivate) {\n classes.push(\"tsd-is-private\");\n }\n if (reflection.flags.isProtected) {\n classes.push(\"tsd-is-protected\");\n }\n if (reflection.flags.isStatic) {\n classes.push(\"tsd-is-static\");\n }\n if (reflection.flags.isExternal) {\n classes.push(\"tsd-is-external\");\n }\n reflection.cssClasses = classes.join(\" \");\n }", "function recurse(name, node) {\n if (node.children) node.children.forEach(function(child) { recurse(node.name, child); });\n else classes.push({packageName: name, className: node.name, value: node.size, url: node.url});\n }", "function Class(){}", "function Class(){}", "function Class(){}", "function _addClassesOption(options, classes) {classes.forEach(function(cls){_addClassOption(options, cls)})}", "function createClassAttribute(vnode) {\n const {\n elm,\n data: {\n classMap\n }\n } = vnode;\n\n if (isUndefined(classMap)) {\n return;\n }\n\n const {\n classList\n } = elm;\n\n for (const name in classMap) {\n classList.add(name);\n }\n }", "function createClassAttribute$1(vnode) {\n const {\n elm,\n data: {\n classMap\n }\n } = vnode;\n\n if (isUndefined$3(classMap)) {\n return;\n }\n\n const {\n classList\n } = elm;\n\n for (const name in classMap) {\n classList.add(name);\n }\n }", "createClass (data) {\n\t\treturn Classify.create(data).exec();\n\t}", "function getClassList(){\n request(classListUrl,processClassList);\n}", "_setClassNames() {\n const classNames = ['osjs-window', ...this.attributes.classNames];\n if (this.id) {\n classNames.push(`Window_${this.id}`);\n }\n\n classNames.filter(val => !!val)\n .forEach((val) => this.$element.classList.add(val));\n }", "function ClassList(element) {\n this.element = element;\n }", "function populateSpryCSSClasses()\n{\n var dom = dw.getDocumentDOM();\n\tvar allClasses = dom.getSelectorsDefinedInStylesheet('class');\n\tfor (i = 0; i < allClasses.length; i++)\n\t{\n\t\tif (allClasses[i][0] == '.')\n\t\t{\n\t\t\tallClasses[i] = allClasses[i].slice(1);\n\t\t}\n\t}\n\t_LIST_SPRY_HOVER_CLASSES.setAll(allClasses,allClasses);\n\t_LIST_SPRY_SELECT_CLASSES.setAll(allClasses,allClasses);\n\t_LIST_SPRY_ODD_CLASSES.setAll(allClasses,allClasses);\n\t_LIST_SPRY_EVEN_CLASSES.setAll(allClasses,allClasses);\n}", "function ClassList(element) {\n this.element = element;\n }", "function ClassList(element) {\n this.element = element;\n }", "function classOf() {\n ;\n}", "function extendClassContext(context, name, global) {\n\n\t/*\n\t * general extensions\n\t */\n\tcontext.name = name;\n\tcontext.children = [];\n\n\t// files\n\textendFilePaths(context, name, global);\n\t\n\t// make a depth-first recursion of sub-classes to have the context of the children (sub-classes) ready for variables and other things\n\tfor (var p in context.properties) {\n\t\tvar prop = context.properties[p];\n\t\t\n\t\t// set property ID (variable name)\n\t\tprop.id = p;\n\t\tprop.name = name + '_' + prop.id;\n\t\t\n\t\t// is it a sub class?\n\t\tif ( prop.type == 'object' ) {\n\t\t\t\n\t\t\t// process sub-class recursively\n\t\t\textendClassContext(prop, prop.name, global);\n\t\t\t\n\t\t\t// add to sub-class list\n\t\t\tcontext.children.push(prop);\n\t\t}\n\n\t\t// is it an array?\n\t\tif ( prop.type == 'array' ) {\n\t\t\textendArrayContext(context, prop, prop.name, global);\n\t\t}\n\n\t\t\n\t\t// prepare member variables (properties)\n\t\t\n\t\t// set C/C++ type\n\t\t// do this after we have all sub-class types \n\t\tsetCType( prop, context );\n\t}\t\n\n\t// set type of class itself \n\tsetCType( context, context );\t\t\n}", "function setClass(node, index, newClass){\n let newClasses = [];\n let classList = node.classList;\n for(let i = 2; i >= 0; i--){\n newClasses.unshift(node.classList[i]);\n classList.remove(classList[i]);\n }\n\n newClasses[index] = newClass;\n\n for(let i = 0; i < 3; i++){\n classList.add(newClasses[i]);\n }\n\n}", "function setClassName() {\n logBody.push(\"setClassName\");\n if (inOuterClass === false) {\n attribute[\"outerClass\"][\"name\"] = tokenValue;\n\n logBody.push(`attribute[\"outerClass\"][\"name\"] -> ${attribute[\"outerClass\"][\"name\"]}`)\n }\n //TODO: Add else to account for inner classes \n }", "addClasses(){\n\t\tif(!this.visible) return;\n\t\t\n\t\tif(this.classes){\n\t\t\tthis.appliedClasses = this.classes;\n\t\t\tthis.element.classList.add(...this.appliedClasses);\n\t\t}\n\t}", "function enumClasses(agent_api){\n agent_api.enumerateClasses().then(function() {\n agent_handler.handler.enumerateClassesDone();\n });;\n}", "getClassNames(){return this.__classNames}", "function addClassName(obj, className) {\n if (obj.classNames !== undefined) {\n obj.classNames.push(className);\n }\n else {\n obj.classNames = [className];\n }\n}", "function ClassList(element) {\n this.element = element;\n }", "function classes() {\n var classes = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n classes[_i] = arguments[_i];\n }\n return classes.filter(function (c) { return !!c; }).join(' ');\n}", "function classes() {\n var classes = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n classes[_i] = arguments[_i];\n }\n return classes.filter(function (c) { return !!c; }).join(' ');\n}", "function classes() {\n var classes = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n classes[_i] = arguments[_i];\n }\n return classes.filter(function (c) { return !!c; }).join(' ');\n}", "function classes() {\n var classes = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n classes[_i] = arguments[_i];\n }\n return classes\n .map(function (c) { return c && typeof c === 'object' ? Object.keys(c).map(function (key) { return !!c[key] && key; }) : [c]; })\n .reduce(function (flattened, c) { return flattened.concat(c); }, [])\n .filter(function (c) { return !!c; })\n .join(' ');\n}", "function reClass(automaton) {\n\tconsole.log(\"Before re class\");\n\tconsole.log(JSON.stringify(minStruct));\n\tObject.keys(minStruct).forEach((state) => {\n\t\tminStruct[state].newClass = minStruct[state].class;\n\t\tObject.keys(minStruct[state].trans).forEach((symbol) => {\n\t\t\tvar nextState = minStruct[state].trans[symbol];\n\t\t\tminStruct[state].newClass+=minStruct[nextState].class;\n\t\t})\n\t})\n\tconsole.log(\"After re class\");\n\tconsole.log(JSON.stringify(minStruct));\n}", "function loadClasses(input) {\n const ret = {};\n for (const myClass in input) {\n if ({}.hasOwnProperty.call(input, myClass)) {\n ret[myClass] = new InspectorClass(input[myClass]);\n }\n }\n return ret;\n}", "loadClasses(...classes) {\n const allClasses = classes.flat().map(c => Object.values(c)).flat(2);\n const flatClasses = [...new Set(allClasses)];\n const allCommands = flatClasses.map(fC => Object.values(fC)).flat(2);\n const flatCommands = [...new Set(allCommands)];\n if (allClasses.length > flatClasses.length)\n console.error(\"notice: you are probably loading the same class multiple times\");\n if (allCommands.length > flatClasses.length)\n console.error(\"notice: your class(es) have the same command more than once\");\n flatClasses.forEach((fClass) => this.classes.includes(fClass) ? console.error((fClass === null || fClass === void 0 ? void 0 : fClass.name) + \" is already added\") : this.classes.push(fClass));\n flatCommands.forEach(fCommand => this.commands.includes(fCommand) ? console.error(fCommand.name + \" is already added\") : this.commands.push(fCommand));\n flatCommands.forEach(this.createUUID.bind(this));\n }", "function ClassHandle() {\n}", "function ClassList(ele) {\n\t\t\t\tthis.ele = ele;\n\t\t\t\tthis.add = this._add.bind(this);\n\t\t\t\tthis.remove = this._remove.bind(this);\n\t\t\t}", "function AddClass(obj,cName){ KillClass(obj,cName); return obj && (obj.className+=(obj.className.length>0?' ':'')+cName); }", "function addClassToElementByClassName(obj) {\n\n var newClass = obj.class;\n for (var index = 0; index < obj.classnames.length; index++) {\n\n classname = obj.classnames[index];\n\n var e = document.getElementsByClassName(classname);\n\n for (var i = 0; i < e.length; i++) {\n\n e[i].classList.add(newClass);\n }\n }\n}", "function addClassNode(node) {\n \tif (node.classList !== undefined) {\n\t \tif (node.classList.contains(className)) {\n\t \t\telements.push(node);\n\t \t}\n\t}\n \tfor (var i = 0; i < node.childNodes.length; i++) {\n \t\taddClassNode(node.childNodes[i]);\n \t}\n }", "ReplaceClass(node, className) {\n node.className = className;\n }", "addClass(id, data) {\n this.classes[id] = new ClassData(data);\n this.classNames.push(data.name);\n }", "function initClasses(lib, name) {\n\t\tuniverse[name] = new lib.ClassCollection();\n\t\treturn initClasses; // some thing like: initClasses(a, b)(d, e)(g, h) instead of do them sepparately.\n\t}", "isClass(node) {\n return super.isClass(node) || this.getClassSymbol(node) !== undefined;\n }", "function _add (className) {\n //add class name to class names array\n this._classNames.push(className);\n\n //apply class name\n this._targetElement.className += ' ' + className;\n\n //exec\n _exec.call(this);\n }", "function AssignClass() {\n\tswitch(Dice(1)) {\n\t\tdefault:\n\t\t\tOPC.class = \"fighter\";\n\t\t\tbreak;\n\t}\n}", "function addClass(object,clazz){\n if(!classExists(object,clazz)) {\n object.className += object.className ? ' ' + clazz : clazz;\n }\n}", "function _addClass(string, node) {\n\tclasses(node).add(string);\n}", "function classList(element) {\n\t return (' ' + (element.className || '') + ' ').replace(/\\s+/gi, ' ');\n\t }", "function classList(element) {\n\t return (' ' + (element.className || '') + ' ').replace(/\\s+/gi, ' ');\n\t }", "function classList(element) {\n\t return (' ' + (element.className || '') + ' ').replace(/\\s+/gi, ' ');\n\t }", "function classList(element) {\n\t return (' ' + (element.className || '') + ' ').replace(/\\s+/gi, ' ');\n\t }", "setClass(el, classname) {\n el.className += ' ' + classname;\n }", "get cls() {\n if (!this._cls) {\n this._cls = new DomClassList(super.get('cls'));\n }\n return this._cls;\n }", "function hashClasses() {\n for (i in classes) {\n nodeHash[classes[i].class] = classes[i]\n }\n for (i in relations) {\n relations[i].source = nodeHash[relations[i].source]\n relations[i].target = nodeHash[relations[i].target]\n }\n }", "function addClass(obj, className) {\n obj.classList.add(className);\n}", "function lisp_add_superclass(c, sc) {\n lisp_assert(lisp_is_instance(c, Lisp_Class));\n lisp_assert(lisp_is_instance(sc, Lisp_Class));\n if (!lisp_native_array_contains(c.lisp_superclasses, sc)) {\n c.lisp_superclasses.push(sc);\n }\n return lisp_void;\n}", "function Class() {}", "static type() {\n console.log('Class way')\n }", "function ProcessClasses(topics) {\n const classes = ForwardDeclareClasses(topics);\n BuildClasses(topics, classes);\n return classes;\n}", "function evaluateClassDeclaration({ node, environment, evaluate, stack, logger, reporting, typescript, statementTraversalStack }) {\n let extendedType;\n const ctorMember = node.members.find(typescript.isConstructorDeclaration);\n const otherMembers = node.members.filter(member => !typescript.isConstructorDeclaration(member));\n let ctor;\n if (ctorMember != null) {\n evaluate.declaration(ctorMember, environment, statementTraversalStack);\n ctor = stack.pop();\n }\n if (node.heritageClauses != null) {\n const extendsClause = node.heritageClauses.find(clause => clause.token === typescript.SyntaxKind.ExtendsKeyword);\n if (extendsClause != null) {\n const [firstExtendedType] = extendsClause.types;\n if (firstExtendedType != null) {\n extendedType = evaluate.expression(firstExtendedType.expression, environment, statementTraversalStack);\n }\n }\n }\n const name = node.name == null ? undefined : node.name.text;\n let classDeclaration = generateClassDeclaration({ name, extendedType, ctor });\n if (node.decorators != null) {\n for (const decorator of node.decorators) {\n evaluate.nodeWithArgument(decorator, environment, [classDeclaration], statementTraversalStack);\n classDeclaration = stack.pop();\n }\n }\n classDeclaration.toString = () => `[Class${name == null ? \"\" : `: ${name}`}]`;\n if (name != null) {\n setInLexicalEnvironment({ env: environment, path: name, value: classDeclaration, newBinding: true, reporting, node });\n }\n // Walk through all of the class members\n for (const member of otherMembers) {\n evaluate.nodeWithArgument(member, environment, hasModifier(member, typescript.SyntaxKind.StaticKeyword) ? classDeclaration : classDeclaration.prototype, statementTraversalStack);\n }\n logger.logHeritage(classDeclaration);\n stack.push(classDeclaration);\n logger.logStack(stack);\n}", "function addClasses(elems, className) {\n var ln = elems.length, i;\n\n for (i = 0; i < ln; i++) {\n var elem = elems[i];\n if (elem.nodeType === 1) addClass(elem, className);\n };\n }" ]
[ "0.6078186", "0.59882", "0.59697807", "0.59568006", "0.59298676", "0.59283644", "0.5882288", "0.5857108", "0.5855861", "0.5852656", "0.58404225", "0.58293825", "0.5826724", "0.5822816", "0.5822047", "0.5822047", "0.5794311", "0.57835263", "0.5765428", "0.5725444", "0.5702823", "0.56959665", "0.5653963", "0.561269", "0.55990505", "0.55947685", "0.55892664", "0.5581912", "0.55381674", "0.55376303", "0.55235016", "0.55097836", "0.5509601", "0.54928327", "0.54470646", "0.54470646", "0.5440054", "0.54361564", "0.543417", "0.54291207", "0.5424794", "0.54198813", "0.5418201", "0.541678", "0.5406056", "0.5406056", "0.5406056", "0.539498", "0.5389499", "0.5378128", "0.5358225", "0.5353153", "0.5351948", "0.53367007", "0.5336613", "0.53360194", "0.53360194", "0.5335417", "0.533255", "0.53314215", "0.5327963", "0.53106976", "0.52952313", "0.5287735", "0.526263", "0.5259867", "0.52486515", "0.52486515", "0.52486515", "0.52431434", "0.5234462", "0.5232352", "0.52217007", "0.52194285", "0.5219181", "0.5215615", "0.52090275", "0.5207899", "0.52066237", "0.5202278", "0.5200587", "0.5160589", "0.51567554", "0.5150616", "0.5149223", "0.5148706", "0.51428574", "0.51428574", "0.51428574", "0.51428574", "0.51260966", "0.51249653", "0.51209384", "0.5116756", "0.5113389", "0.5101522", "0.5090841", "0.5080272", "0.5079871", "0.5076761" ]
0.62256926
0
Overide the initialize authenticator to make sure `__monkeypatchNode` run once.
init() { this.framework(framework); this.use(new SessionStrategy()); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "init() {\n ['post', 'get', 'put', 'patch', 'delete'].forEach((method) => {\n moduleUtils.patchModule(\n 'superagent',\n method,\n superagentWrapper\n );\n });\n }", "init() {\n // using shimmer directly cause can only be bundled in node\n shimmer.wrap(http, 'get', () => httpGetWrapper(http));\n shimmer.wrap(http, 'request', httpWrapper);\n shimmer.wrap(https, 'get', () => httpGetWrapper(https));\n shimmer.wrap(https, 'request', httpWrapper);\n\n module_utils.patchModule(\n 'fetch-h2/dist/lib/context-http1',\n 'connect',\n fetchH2Wrapper,\n fetch => fetch.OriginPool.prototype\n );\n // simple-oauth2 < 4.0\n module_utils.patchModule(\n 'simple-oauth2/lib/client.js',\n 'request',\n clientRequestWrapper,\n client => client.prototype\n );\n // simple-oauth2 >= 4.0\n module_utils.patchModule(\n 'simple-oauth2/lib/client/client.js',\n 'request',\n clientRequestWrapper,\n client => client.prototype\n );\n }", "init() {\n module_utils.patchModule(\n 'ldapjs',\n 'bind',\n bindWrapper,\n ldapjs => ldapjs.Client.prototype\n );\n }", "init() {\n moduleUtils.patchModule(\n 'express',\n 'init',\n expressWrapper,\n express => express.application\n );\n }", "init() {\n _listenToCurrentUser();\n }", "function init() {\n checkCredentials();\n}", "init() {\n module_utils.patchModule(\n 'nats',\n 'connect',\n wrapNatsConnectFunction\n );\n }", "initialize() {\n // Needs to be implemented by derived classes.\n }", "init() {\n if (http2) {\n utils.debugLog('Patching http2 module');\n shimmer.wrap(http2, 'connect', wrapHttp2Connect);\n }\n }", "initialize() {}", "initialize() {}", "initialize() {}", "initialize() {}", "initialize() {}", "initialize() {}", "init() {\n // No-op by default.\n }", "function init() {\n const kc = this;\n const cache = kc.cache;\n const token = cache.get('token');\n const state = cache.get('state');\n const authorized = !!(token && state);\n if (!authorized) {\n return kc.onReady(false);\n }\n\n processTokenCallback(kc, token);\n // kc.onAuthSuccess();\n }", "_initialize() {\n\n }", "function init(){\n\tthis.applyBehavior(\"MynaAuth\",{\n\t\twhitelist:[],\n\t\tproviders:Myna.Permissions.getAuthTypes(),\n\t\tredirectParams:{}\n\t})\n\t\n\t\n}", "async _initConnector() {\n logger.debug('Entering _initConnector');\n const tlsInfo = this.networkUtil.isMutualTlsEnabled() ? 'mutual'\n : (this.networkUtil.isTlsEnabled() ? 'server' : 'none');\n logger.info(`Fabric SDK version: ${this.version.toString()}; TLS: ${tlsInfo}`);\n\n await this._prepareOrgWallets();\n await this._initializeAdmins();\n // Initialize registrars *after* initialization of admins so that admins are not created\n this.registrarHelper = await RegistrarHelper.newWithNetwork(this.networkUtil);\n await this._initializeUsers();\n logger.debug('Exiting _initConnector');\n }", "function init() {\n\t\tuserAgentCheck();\n\t\ttestThis();\n\t}", "static initialize() {\n //\n }", "_initialize() {\n var _a2;\n this.__updatePromise = new Promise((res) => this.enableUpdating = res);\n this._$changedProperties = /* @__PURE__ */ new Map();\n this.__saveInstanceProperties();\n this.requestUpdate();\n (_a2 = this.constructor._initializers) === null || _a2 === void 0 ? void 0 : _a2.forEach((i) => i(this));\n }", "[APPLICATION_INITIALIZE_APP](state, nextRootState) {\n _.merge(state, nextRootState.authentication)\n }", "init() {\n\t\tconsole.log(\"No special init\");\n\t}", "async init(){}", "function init() {}", "function init() {}", "function init() {}", "function init() {}", "function init() {}", "function init() {}", "function init() {}", "function init() {}", "function init() {}", "function init() {}", "constructor() { \n \n PatchedChangePassword.initialize(this);\n }", "init() {\n if (this.initialized) {\n throw Error('Client has already been initialized.');\n }\n this.api = this.setUpApi(this.token, this.apiOptions);\n this.selfAssignHandlerFunctions();\n this.initialized = true;\n }", "async init () {\r\n debug.log('called init');\r\n return;\r\n }", "_initialize () {\n this.socket.on('data', data => this._sessionProtocol.chuck(data))\n this.socket.once('close', () => this.disconnect())\n }", "async init() {}", "async init() {}", "init() {}", "init() {}", "init() {}", "init() {}", "init() {}", "init() {}", "init() {}", "init() {}", "init() {}", "init() {}", "init() {}", "init() {}", "init() {}", "init() {\n module_utils.patchModule(\n 'openwhisk/lib/actions.js',\n 'invoke',\n openWhiskWrapper$1,\n actions => actions.prototype\n );\n }", "function _init() {\n }", "init() {\n //todo: other init stuff here\n }", "initialize() {\n this.rootScope_.$on('$routeUpdate', this.onRouteUpdate.bind(this));\n this.initialized_ = true;\n this.onRouteUpdate();\n }", "init({ state }) {\n setDefaultAuthHeaders(state);\n }", "constructor() { \n \n OrgApacheJackrabbitOakSpiSecurityAuthenticationExternalImplExProperties.initialize(this);\n }", "getAuthenticator () {\n return null // Disable authentication\n }", "init() {\n this.attach();\n }", "function initialize() {}", "initialize() {\n //\n }", "function _initialize() {\n\n /* FUTURE - revisit how we handle user config option overrides in a way that\n doesn't prevent us from updating shipped config option values. */\n try {\n // Try to read the Load the user options synchronously\n if(fs.existsSync(testOptionsFile)){\n userOptions = fs.readFileSync(testOptionsFile);\n }\n else\n userOptions = fs.readFileSync(userOptionsFile);\n userOptions = userOptions || \"{}\";\n userOptions = JSON.parse(userOptions.toString());\n } catch(e) {\n userOptions = defaultOptions;\n }\n\n checkUserOptions();\n\n dynamicOptions = {};\n\n // Added default options to dynamic options\n deepExtend(dynamicOptions, defaultOptions);\n\n // Add user options to dynamic options\n deepExtend(dynamicOptions, userOptions);\n\n}", "async init () {}", "init() {\n module_utils.patchModule(\n 'mqtt',\n 'MqttClient',\n mqttClientWrapper,\n mqttModule => mqttModule\n );\n }", "init() {\n module_utils.patchModule(\n 'pino/lib/tools',\n 'asJson',\n logWrapper\n );\n }", "init() { }", "init() { }", "init() { }", "init() { }", "init() { }", "async init () {\r\n return;\r\n }", "function _init() {\n }", "function _init() {\n }", "function _init() {\n }", "function init() {\n // Initialize scanner state machine and plugins\n INIT.scanner = init$2(INIT.customSchemes);\n for (let i = 0; i < INIT.tokenQueue.length; i++) {\n INIT.tokenQueue[i][1]({\n scanner: INIT.scanner\n });\n }\n\n // Initialize parser state machine and plugins\n INIT.parser = init$1(INIT.scanner.tokens);\n for (let i = 0; i < INIT.pluginQueue.length; i++) {\n INIT.pluginQueue[i][1]({\n scanner: INIT.scanner,\n parser: INIT.parser\n });\n }\n INIT.initialized = true;\n}", "init () {}", "init () {}", "init() {\n this._super(...arguments);\n this._applyDefaults();\n }", "initialize() {\n\n }", "init() {\n module_utils.patchModule(\n 'redis',\n 'internal_send_command',\n redisClientWrapper,\n redis => redis.RedisClient.prototype\n );\n }", "static initialize(obj, password) { \n obj['password'] = password;\n }", "__init2() {this._installFunc = {\n\t onerror: _installGlobalOnErrorHandler,\n\t onunhandledrejection: _installGlobalOnUnhandledRejectionHandler,\n\t };}", "initialize()\n {\n }", "static initialize(obj, login) { \n obj['login'] = login;\n }", "__init2() {this._installFunc = {\n onerror: _installGlobalOnErrorHandler,\n onunhandledrejection: _installGlobalOnUnhandledRejectionHandler,\n };}", "function init() {\n\t//TODO\n}", "init() {\n\t\tthis.replaceData(\n\t\t\tthis.manager.get(\"hostReq\"),\n\t\t\tthis.endpoints.check,\n\t\t\tthis.data.check\n\t\t);\n\t}", "init() {\n if ((process.env.EPSAGON_DNS_INSTRUMENTATION || '').toUpperCase() === 'TRUE') {\n const dnsExportedFunctions = Object.keys(dns);\n Object.keys(rrtypesMethods).forEach((functionToTrace) => {\n if (dnsExportedFunctions.includes(functionToTrace)) {\n module_utils.patchSingle(dns, functionToTrace, wrapDnsResolveFunction);\n }\n });\n module_utils.patchSingle(dns, 'resolve', () => wrapDnsResolveFunction(dns.resolve));\n module_utils.patchSingle(dns, 'reverse', () => wrapDnsReverseFunction(dns.reverse));\n module_utils.patchSingle(dns, 'lookup', () => wrapDnsLookupFunction(dns.lookup));\n module_utils.patchSingle(dns, 'lookupService', () => wrapDnsLookupServiceFunction(dns.lookupService));\n }\n }", "init() {\n module_utils.patchModule(\n 'aws-sdk',\n 'send',\n AWSSDKWrapper,\n AWSmod => AWSmod.Request.prototype\n );\n module_utils.patchModule(\n 'aws-sdk',\n 'promise',\n AWSSDKWrapper,\n AWSmod => AWSmod.Request.prototype\n );\n\n // This method is static - not in prototype\n module_utils.patchModule(\n 'aws-sdk',\n 'addPromisesToClass',\n wrapPromiseOnAdd,\n AWSmod => AWSmod.Request\n );\n }", "init() {\n module_utils.patchModule(\n 'cassandra-driver/lib/client',\n 'execute',\n cassandraClientWrapper,\n cassandra => cassandra.prototype\n );\n }", "init () {\n }", "function init() { }", "function init() { }", "init() {\n }", "init() {\n }", "init() {\n }", "function init() {\n\n // sends scopes and main url of page to the node server\n fetch(nodeHost + '/data', {\n method: 'POST',\n body: JSON.stringify({\n scopes: scopes,\n hostURL: windowURL\n }),\n headers: {\n 'Content-Type': 'application/json'\n }\n }).catch(function(err) {\n // Error :(\n window.alert('An error has occurred\\nPlease check the console log');\n console.log(err);\n console.log('error');\n });\n\n // tests to see if there is a refresh token already\n // and if it can be used, refresh current token and hide login\n // else do nothing\n if (localStorage.getItem('refresh_token')) {\n\n // strips the http and https replace with ws for websocket\n var host = nodeHost.replace(/^https|^http/, 'wss');\n\n // opens websockets to recive tokens from node server\n var ws = new WebSocket(host + '/refresh');\n ws.onopen = function() {\n ws.send(JSON.stringify(localStorage.getItem('refresh_token')));\n };\n\n ws.onmessage = function(message) {\n var newToken = JSON.parse(message.data);\n\n // if error code 400 is not recived a new token has been recived\n if (newToken.statusCode !== 400) {\n storage(newToken);\n\n // calls fadeLogin with a 1 to hide, to show call with a 0\n fadeLogin(1);\n\n }\n ws.close();\n };\n }\n\n }" ]
[ "0.5943074", "0.5811683", "0.5780885", "0.5737202", "0.56183046", "0.5586573", "0.55326116", "0.549155", "0.5488245", "0.5471313", "0.5471313", "0.5471313", "0.5471313", "0.5471313", "0.5471313", "0.5414937", "0.53891635", "0.53858817", "0.5383071", "0.53767943", "0.5364781", "0.5334314", "0.53169477", "0.53052026", "0.5279344", "0.5259521", "0.5256441", "0.5256441", "0.5256441", "0.5256441", "0.5256441", "0.5256441", "0.5256441", "0.5256441", "0.5256441", "0.5256441", "0.52376765", "0.5224108", "0.5223195", "0.5219857", "0.52024657", "0.52024657", "0.5196465", "0.5196465", "0.5196465", "0.5196465", "0.5196465", "0.5196465", "0.5196465", "0.5196465", "0.5196465", "0.5196465", "0.5196465", "0.5196465", "0.5196465", "0.51932687", "0.51909345", "0.51839286", "0.5179423", "0.5178942", "0.51675546", "0.51640534", "0.5162773", "0.51490927", "0.5141932", "0.5138438", "0.5137317", "0.5123241", "0.511737", "0.5114914", "0.5114914", "0.5114914", "0.5114914", "0.5114914", "0.51027906", "0.5095966", "0.5095966", "0.5095966", "0.50906044", "0.5088104", "0.5088104", "0.50833905", "0.5078814", "0.5070537", "0.5068359", "0.50626403", "0.50413543", "0.5036874", "0.50249124", "0.50245506", "0.50242674", "0.50149846", "0.5008993", "0.5005764", "0.4995956", "0.49939", "0.49939", "0.49928233", "0.49928233", "0.49928233", "0.49817672" ]
0.0
-1
Last update: 2016/06/26 Everything between 'BEGIN' and 'END' was copied from the url above. fork from for support brower
function sM(a) { var b; if (null !== yr) b = yr; else { b = wr(String.fromCharCode(84)); var c = wr(String.fromCharCode(75)); b = [b(), b()]; b[1] = c(); b = (yr = window[b.join(c())] || "") || "" } var d = wr(String.fromCharCode(116)) , c = wr(String.fromCharCode(107)) , d = [d(), d()]; d[1] = c(); c = "&" + d.join("") + "="; d = b.split("."); b = Number(d[0]) || 0; for (var e = [], f = 0, g = 0; g < a.length; g++) { var l = a.charCodeAt(g); 128 > l ? e[f++] = l : (2048 > l ? e[f++] = l >> 6 | 192 : (55296 == (l & 64512) && g + 1 < a.length && 56320 == (a.charCodeAt(g + 1) & 64512) ? (l = 65536 + ((l & 1023) << 10) + (a.charCodeAt(++g) & 1023), e[f++] = l >> 18 | 240, e[f++] = l >> 12 & 63 | 128) : e[f++] = l >> 12 | 224, e[f++] = l >> 6 & 63 | 128), e[f++] = l & 63 | 128) } a = b; for (f = 0; f < e.length; f++) a += e[f], a = xr(a, "+-a^+6"); a = xr(a, "+-3^+b+-f"); a ^= Number(d[1]) || 0; 0 > a && (a = (a & 2147483647) + 2147483648); a %= 1E6; return c + (a.toString() + "." + (a ^ b)) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "static get END() { return 6; }", "function adjustSpanBegin2(beginPosition) {\n var pos = beginPosition;\n while ((pos < sourceDoc.length) && (isNonEdgeCharacter(sourceDoc.charAt(pos)) || !isDelimiter(sourceDoc.charAt(pos - 1)))) {pos++}\n return pos;\n }", "function adjustSpanBegin(beginPosition) {\n var pos = beginPosition;\n while (isNonEdgeCharacter(sourceDoc.charAt(pos))) {pos++}\n while (!isDelimiter(sourceDoc.charAt(pos)) && pos > 0 && !isDelimiter(sourceDoc.charAt(pos - 1))) {pos--}\n return pos;\n }", "function getBetween(doc, start, end) {\n\t\t var out = [], n = start.line;\n\t\t doc.iter(start.line, end.line + 1, function(line) {\n\t\t var text = line.text;\n\t\t if (n == end.line) text = text.slice(0, end.ch);\n\t\t if (n == start.line) text = text.slice(start.ch);\n\t\t out.push(text);\n\t\t ++n;\n\t\t });\n\t\t return out;\n\t\t }", "function getBetween(doc, start, end) {\n\t\t var out = [], n = start.line;\n\t\t doc.iter(start.line, end.line + 1, function (line) {\n\t\t var text = line.text;\n\t\t if (n == end.line) { text = text.slice(0, end.ch); }\n\t\t if (n == start.line) { text = text.slice(start.ch); }\n\t\t out.push(text);\n\t\t ++n;\n\t\t });\n\t\t return out\n\t\t }", "initFormatting () {\n\n let openScriptTag = this.content.match(utils.regExp.scriptStart);\n\n if (openScriptTag && openScriptTag[0]) {\n openScriptTag = openScriptTag[0];\n }\n this.importIndentLength = openScriptTag.length - openScriptTag.trim().length;\n }", "function getEndBlockCode()\n{\n\tvar aCounter = ms_CounterStep;\n\n\tms_CounterStep++;\n\n\treturn 'highlightBlock( ' + aCounter + ' );' ;\n}", "function htmldb_Get_trimPartialPage(startTag,endTag,obj) {\n if(obj) {this.obj = $x(obj);}\n if(!startTag){startTag = '<!--START-->'}\n if(!endTag){endTag = '<!--END-->'}\n var start = this.response.indexOf(startTag);\n var part;\n var result;\n var node;\n if(start>0){\n this.response = this.response.substring(start+startTag.length);\n var end = this.response.indexOf(endTag);\n this.response = this.response.substring(0,end);\n }\n if(this.obj){\n if(document.all){\n result = this.response;\n node = this.obj;\n setTimeout(function() {htmldb_get_WriteResult(node, result)},100);\n }else{\n $s(this.obj,this.response);\n }\n }\n return this.response;\n}", "function getBetween(doc, start, end) {\n\t var out = [], n = start.line;\n\t doc.iter(start.line, end.line + 1, function(line) {\n\t var text = line.text;\n\t if (n == end.line) text = text.slice(0, end.ch);\n\t if (n == start.line) text = text.slice(start.ch);\n\t out.push(text);\n\t ++n;\n\t });\n\t return out;\n\t }", "function getBetween(doc, start, end) {\n\t var out = [], n = start.line;\n\t doc.iter(start.line, end.line + 1, function(line) {\n\t var text = line.text;\n\t if (n == end.line) text = text.slice(0, end.ch);\n\t if (n == start.line) text = text.slice(start.ch);\n\t out.push(text);\n\t ++n;\n\t });\n\t return out;\n\t }", "function getBetween(doc, start, end) {\n\t var out = [], n = start.line;\n\t doc.iter(start.line, end.line + 1, function(line) {\n\t var text = line.text;\n\t if (n == end.line) text = text.slice(0, end.ch);\n\t if (n == start.line) text = text.slice(start.ch);\n\t out.push(text);\n\t ++n;\n\t });\n\t return out;\n\t }", "function getBetween(doc, start, end) {\n var out = [], n = start.line;\n doc.iter(start.line, end.line + 1, function (line) {\n var text = line.text;\n if (n == end.line) { text = text.slice(0, end.ch); }\n if (n == start.line) { text = text.slice(start.ch); }\n out.push(text);\n ++n;\n });\n return out\n }", "function getBetween(doc, start, end) {\n var out = [], n = start.line;\n doc.iter(start.line, end.line + 1, function (line) {\n var text = line.text;\n if (n == end.line) { text = text.slice(0, end.ch); }\n if (n == start.line) { text = text.slice(start.ch); }\n out.push(text);\n ++n;\n });\n return out\n }", "function getBetween(doc, start, end) {\n var out = [], n = start.line;\n doc.iter(start.line, end.line + 1, function (line) {\n var text = line.text;\n if (n == end.line) { text = text.slice(0, end.ch); }\n if (n == start.line) { text = text.slice(start.ch); }\n out.push(text);\n ++n;\n });\n return out\n }", "function getBetween(doc, start, end) {\n var out = [], n = start.line;\n doc.iter(start.line, end.line + 1, function (line) {\n var text = line.text;\n if (n == end.line) { text = text.slice(0, end.ch); }\n if (n == start.line) { text = text.slice(start.ch); }\n out.push(text);\n ++n;\n });\n return out\n }", "function getBetween(doc, start, end) {\n var out = [], n = start.line;\n doc.iter(start.line, end.line + 1, function (line) {\n var text = line.text;\n if (n == end.line) { text = text.slice(0, end.ch); }\n if (n == start.line) { text = text.slice(start.ch); }\n out.push(text);\n ++n;\n });\n return out\n }", "function getBetween(doc, start, end) {\n var out = [], n = start.line;\n doc.iter(start.line, end.line + 1, function (line) {\n var text = line.text;\n if (n == end.line) { text = text.slice(0, end.ch); }\n if (n == start.line) { text = text.slice(start.ch); }\n out.push(text);\n ++n;\n });\n return out\n }", "function getBetween(doc, start, end) {\n var out = [], n = start.line;\n doc.iter(start.line, end.line + 1, function (line) {\n var text = line.text;\n if (n == end.line) { text = text.slice(0, end.ch); }\n if (n == start.line) { text = text.slice(start.ch); }\n out.push(text);\n ++n;\n });\n return out\n }", "function getBetween(doc, start, end) {\n var out = [], n = start.line;\n doc.iter(start.line, end.line + 1, function (line) {\n var text = line.text;\n if (n == end.line) { text = text.slice(0, end.ch); }\n if (n == start.line) { text = text.slice(start.ch); }\n out.push(text);\n ++n;\n });\n return out\n }", "function getBetween(doc, start, end) {\n var out = [], n = start.line;\n doc.iter(start.line, end.line + 1, function (line) {\n var text = line.text;\n if (n == end.line) { text = text.slice(0, end.ch); }\n if (n == start.line) { text = text.slice(start.ch); }\n out.push(text);\n ++n;\n });\n return out\n }", "function getBetween(doc, start, end) {\n var out = [], n = start.line;\n doc.iter(start.line, end.line + 1, function (line) {\n var text = line.text;\n if (n == end.line) { text = text.slice(0, end.ch); }\n if (n == start.line) { text = text.slice(start.ch); }\n out.push(text);\n ++n;\n });\n return out\n }", "function getBetween(doc, start, end) {\n var out = [], n = start.line;\n doc.iter(start.line, end.line + 1, function (line) {\n var text = line.text;\n if (n == end.line) { text = text.slice(0, end.ch); }\n if (n == start.line) { text = text.slice(start.ch); }\n out.push(text);\n ++n;\n });\n return out\n }", "function getBetween(doc, start, end) {\n var out = [], n = start.line;\n doc.iter(start.line, end.line + 1, function (line) {\n var text = line.text;\n if (n == end.line) { text = text.slice(0, end.ch); }\n if (n == start.line) { text = text.slice(start.ch); }\n out.push(text);\n ++n;\n });\n return out\n }", "function getBetween(doc, start, end) {\n var out = [], n = start.line;\n doc.iter(start.line, end.line + 1, function (line) {\n var text = line.text;\n if (n == end.line) { text = text.slice(0, end.ch); }\n if (n == start.line) { text = text.slice(start.ch); }\n out.push(text);\n ++n;\n });\n return out\n }", "function getBetween(doc, start, end) {\n var out = [], n = start.line;\n doc.iter(start.line, end.line + 1, function (line) {\n var text = line.text;\n if (n == end.line) { text = text.slice(0, end.ch); }\n if (n == start.line) { text = text.slice(start.ch); }\n out.push(text);\n ++n;\n });\n return out\n }", "function getBetween(doc, start, end) {\n var out = [], n = start.line;\n doc.iter(start.line, end.line + 1, function (line) {\n var text = line.text;\n if (n == end.line) { text = text.slice(0, end.ch); }\n if (n == start.line) { text = text.slice(start.ch); }\n out.push(text);\n ++n;\n });\n return out\n }", "function getBetween(doc, start, end) {\n var out = [], n = start.line;\n doc.iter(start.line, end.line + 1, function (line) {\n var text = line.text;\n if (n == end.line) { text = text.slice(0, end.ch); }\n if (n == start.line) { text = text.slice(start.ch); }\n out.push(text);\n ++n;\n });\n return out\n }", "function getBetween(doc, start, end) {\n var out = [], n = start.line;\n doc.iter(start.line, end.line + 1, function (line) {\n var text = line.text;\n if (n == end.line) { text = text.slice(0, end.ch); }\n if (n == start.line) { text = text.slice(start.ch); }\n out.push(text);\n ++n;\n });\n return out\n }", "function getBetween(doc, start, end) {\n var out = [], n = start.line;\n doc.iter(start.line, end.line + 1, function(line) {\n var text = line.text;\n if (n == end.line) text = text.slice(0, end.ch);\n if (n == start.line) text = text.slice(start.ch);\n out.push(text);\n ++n;\n });\n return out;\n }", "function getBetween(doc, start, end) {\n var out = [], n = start.line;\n doc.iter(start.line, end.line + 1, function(line) {\n var text = line.text;\n if (n == end.line) text = text.slice(0, end.ch);\n if (n == start.line) text = text.slice(start.ch);\n out.push(text);\n ++n;\n });\n return out;\n }", "function getBetween(doc, start, end) {\n var out = [], n = start.line;\n doc.iter(start.line, end.line + 1, function(line) {\n var text = line.text;\n if (n == end.line) text = text.slice(0, end.ch);\n if (n == start.line) text = text.slice(start.ch);\n out.push(text);\n ++n;\n });\n return out;\n }", "function getBetween(doc, start, end) {\n var out = [], n = start.line;\n doc.iter(start.line, end.line + 1, function(line) {\n var text = line.text;\n if (n == end.line) text = text.slice(0, end.ch);\n if (n == start.line) text = text.slice(start.ch);\n out.push(text);\n ++n;\n });\n return out;\n }", "function getBetween(doc, start, end) {\n var out = [], n = start.line;\n doc.iter(start.line, end.line + 1, function(line) {\n var text = line.text;\n if (n == end.line) text = text.slice(0, end.ch);\n if (n == start.line) text = text.slice(start.ch);\n out.push(text);\n ++n;\n });\n return out;\n }", "function getBetween(doc, start, end) {\n var out = [], n = start.line;\n doc.iter(start.line, end.line + 1, function(line) {\n var text = line.text;\n if (n == end.line) text = text.slice(0, end.ch);\n if (n == start.line) text = text.slice(start.ch);\n out.push(text);\n ++n;\n });\n return out;\n }", "function getBetween(doc, start, end) {\n var out = [], n = start.line;\n doc.iter(start.line, end.line + 1, function(line) {\n var text = line.text;\n if (n == end.line) text = text.slice(0, end.ch);\n if (n == start.line) text = text.slice(start.ch);\n out.push(text);\n ++n;\n });\n return out;\n }", "function adjustSpanEnd2(endPosition) {\n var pos = endPosition;\n while ((pos > 0) && (isNonEdgeCharacter(sourceDoc.charAt(pos - 1)) || !isDelimiter(sourceDoc.charAt(pos)))) {pos--}\n return pos;\n }", "function getBetween(doc, start, end) {\r\n var out = [], n = start.line;\r\n doc.iter(start.line, end.line + 1, function(line) {\r\n var text = line.text;\r\n if (n == end.line) text = text.slice(0, end.ch);\r\n if (n == start.line) text = text.slice(start.ch);\r\n out.push(text);\r\n ++n;\r\n });\r\n return out;\r\n }", "function getBetween(doc, start, end) {\n var out = [], n = start.line\n doc.iter(start.line, end.line + 1, function (line) {\n var text = line.text\n if (n == end.line) { text = text.slice(0, end.ch) }\n if (n == start.line) { text = text.slice(start.ch) }\n out.push(text)\n ++n\n })\n return out\n}", "function getBetween(doc, start, end) {\n var out = [], n = start.line\n doc.iter(start.line, end.line + 1, function (line) {\n var text = line.text\n if (n == end.line) { text = text.slice(0, end.ch) }\n if (n == start.line) { text = text.slice(start.ch) }\n out.push(text)\n ++n\n })\n return out\n}", "function doChunk() {\n\t var origStart = start;\n\t var box, pos = text.substr(start).search(/\\S/);\n\t start += pos;\n\t if (pos < 0 || start >= end) {\n\t return true;\n\t }\n\t\n\t // Select a single character to determine the height of a line of text. The box.bottom\n\t // will be essential for us to figure out where the next line begins.\n\t range.setStart(node, start);\n\t range.setEnd(node, start + 1);\n\t box = actuallyGetRangeBoundingRect(range);\n\t\n\t // for justified text we must split at each space, because space has variable width.\n\t var found = false;\n\t if (isJustified || columnCount > 1) {\n\t pos = text.substr(start).search(/\\s/);\n\t if (pos >= 0) {\n\t // we can only split there if it's on the same line, otherwise we'll fall back\n\t // to the default mechanism (see findEOL below).\n\t range.setEnd(node, start + pos);\n\t var r = actuallyGetRangeBoundingRect(range);\n\t if (r.bottom == box.bottom) {\n\t box = r;\n\t found = true;\n\t start += pos;\n\t }\n\t }\n\t }\n\t\n\t if (!found) {\n\t // This code does three things: (1) it selects one line of text in `range`, (2) it\n\t // leaves the bounding rect of that line in `box` and (3) it returns the position\n\t // just after the EOL. We know where the line starts (`start`) but we don't know\n\t // where it ends. To figure this out, we select a piece of text and look at the\n\t // bottom of the bounding box. If it changes, we have more than one line selected\n\t // and should retry with a smaller selection.\n\t //\n\t // To speed things up, we first try to select all text in the node (`start` ->\n\t // `end`). If there's more than one line there, then select only half of it. And\n\t // so on. When we find a value for `end` that fits in one line, we try increasing\n\t // it (also in halves) until we get to the next line. The algorithm stops when the\n\t // right side of the bounding box does not change.\n\t //\n\t // One more thing to note is that everything happens in a single Text DOM node.\n\t // There's no other tags inside it, therefore the left/top coordinates of the\n\t // bounding box will not change.\n\t pos = (function findEOL(min, eol, max){\n\t range.setEnd(node, eol);\n\t var r = actuallyGetRangeBoundingRect(range);\n\t if (r.bottom != box.bottom && min < eol) {\n\t return findEOL(min, (min + eol) >> 1, eol);\n\t } else if (r.right != box.right) {\n\t box = r;\n\t if (eol < max) {\n\t return findEOL(eol, (eol + max) >> 1, max);\n\t } else {\n\t return eol;\n\t }\n\t } else {\n\t return eol;\n\t }\n\t })(start, Math.min(end, start + estimateLineLength), end);\n\t\n\t if (pos == start) {\n\t // if EOL is at the start, then no more text fits on this line. Skip the\n\t // remainder of this node entirely to avoid a stack overflow.\n\t return true;\n\t }\n\t start = pos;\n\t\n\t pos = range.toString().search(/\\s+$/);\n\t if (pos === 0) {\n\t return false; // whitespace only; we should not get here.\n\t }\n\t if (pos > 0) {\n\t // eliminate trailing whitespace\n\t range.setEnd(node, range.startOffset + pos);\n\t box = actuallyGetRangeBoundingRect(range);\n\t }\n\t }\n\t\n\t // another workaround for IE: if we rely on getBoundingClientRect() we'll overlap with the bullet for LI\n\t // elements. Calling getClientRects() and using the *first* rect appears to give us the correct location.\n\t // Note: not to be used in Chrome as it randomly returns a zero-width rectangle from the previous line.\n\t if (microsoft) {\n\t box = range.getClientRects()[0];\n\t }\n\t\n\t var str = range.toString();\n\t if (!/^(?:pre|pre-wrap)$/i.test(whiteSpace)) {\n\t // node with non-significant space -- collapse whitespace.\n\t str = str.replace(/\\s+/g, \" \");\n\t }\n\t else if (/\\t/.test(str)) {\n\t // with significant whitespace we need to do something about literal TAB characters.\n\t // There's no TAB glyph in a font so they would be rendered in PDF as an empty box,\n\t // and the whole text will stretch to fill the original width. The core PDF lib\n\t // does not have sufficient context to deal with it.\n\t\n\t // calculate the starting column here, since we initially discarded any whitespace.\n\t var cc = 0;\n\t for (pos = origStart; pos < range.startOffset; ++pos) {\n\t var code = text.charCodeAt(pos);\n\t if (code == 9) {\n\t // when we meet a TAB we must round up to the next tab stop.\n\t // in all browsers TABs seem to be 8 characters.\n\t cc += 8 - cc % 8;\n\t } else if (code == 10 || code == 13) {\n\t // just in case we meet a newline we must restart.\n\t cc = 0;\n\t } else {\n\t // ordinary character --> advance one column\n\t cc++;\n\t }\n\t }\n\t\n\t // based on starting column, replace any TAB characters in the string we actually\n\t // have to display with spaces so that they align to columns multiple of 8.\n\t while ((pos = str.search(\"\\t\")) >= 0) {\n\t var indent = \" \".substr(0, 8 - (cc + pos) % 8);\n\t str = str.substr(0, pos) + indent + str.substr(pos + 1);\n\t }\n\t }\n\t\n\t if (!found) {\n\t prevLineBottom = box.bottom;\n\t }\n\t drawText(str, box);\n\t }", "getSelectionInfo() {\n const range = window.getSelection().getRangeAt(0);\n\n let startNode;\n let endNode;\n\n if (range.startContainer.nodeName == \"P\") {\n startNode = range.startContainer;\n } else {\n startNode = range.startContainer.parentNode;\n }\n\n if (range.endContainer.nodeName == \"P\") {\n endNode = range.endContainer;\n } else {\n endNode = range.endContainer.parentNode;\n }\n\n if (startNode.nodeName == \"STRONG\") {\n console.log(\"start strong\");\n startNode = startNode.parentNode;\n }\n if (endNode.nodeName == \"STRONG\") {\n console.log(\"end strong\");\n endNode = endNode.parentNode;\n }\n\n //find the startIndex and endIndex\n const parentNode = document.getElementById(\"content\");\n let startIndex = 0;\n let endIndex = 0;\n let i = 0;\n console.log(startNode);\n console.log(endNode);\n\n for (let i = 0; i < parentNode.childElementCount; i++) {\n // Do stuff\n // console.log(parentNode.children[i]);\n\n if (parentNode.children[i] == startNode) {\n startIndex = i;\n }\n if (parentNode.children[i] == endNode) {\n endIndex = i;\n }\n }\n\n console.log(startIndex);\n console.log(endIndex);\n\n let doc = document.getElementById(\"content\");\n let selectionPosition = doc.scrollTop;\n\n return {\n startIndex: startIndex,\n endIndex: endIndex,\n startOffset: range.startOffset,\n endOffset: range.endOffset,\n yPosition: selectionPosition,\n };\n }", "match(input, start, end){}", "function find_start_line() {\n // TODO:\n return 0\n}", "function getBetween(doc, start, end) {\r\n var out = [], n = start.line;\r\n doc.iter(start.line, end.line + 1, function (line) {\r\n var text = line.text;\r\n if (n == end.line) { text = text.slice(0, end.ch); }\r\n if (n == start.line) { text = text.slice(start.ch); }\r\n out.push(text);\r\n ++n;\r\n });\r\n return out\r\n}", "function getBetween(doc, start, end) {\n var out = [], n = start.line;\n doc.iter(start.line, end.line + 1, function (line) {\n var text = line.text;\n if (n == end.line) { text = text.slice(0, end.ch); }\n if (n == start.line) { text = text.slice(start.ch); }\n out.push(text);\n ++n;\n });\n return out\n}", "function getBetween(doc, start, end) {\n var out = [], n = start.line;\n doc.iter(start.line, end.line + 1, function (line) {\n var text = line.text;\n if (n == end.line) { text = text.slice(0, end.ch); }\n if (n == start.line) { text = text.slice(start.ch); }\n out.push(text);\n ++n;\n });\n return out\n}", "function getBetween(doc, start, end) {\n var out = [], n = start.line;\n doc.iter(start.line, end.line + 1, function (line) {\n var text = line.text;\n if (n == end.line) { text = text.slice(0, end.ch); }\n if (n == start.line) { text = text.slice(start.ch); }\n out.push(text);\n ++n;\n });\n return out\n}", "function getBetween(doc, start, end) {\n var out = [], n = start.line;\n doc.iter(start.line, end.line + 1, function (line) {\n var text = line.text;\n if (n == end.line) { text = text.slice(0, end.ch); }\n if (n == start.line) { text = text.slice(start.ch); }\n out.push(text);\n ++n;\n });\n return out\n}", "function getBetween(doc, start, end) {\n var out = [], n = start.line;\n doc.iter(start.line, end.line + 1, function (line) {\n var text = line.text;\n if (n == end.line) { text = text.slice(0, end.ch); }\n if (n == start.line) { text = text.slice(start.ch); }\n out.push(text);\n ++n;\n });\n return out\n}", "function getBetween(doc, start, end) {\n var out = [], n = start.line;\n doc.iter(start.line, end.line + 1, function (line) {\n var text = line.text;\n if (n == end.line) { text = text.slice(0, end.ch); }\n if (n == start.line) { text = text.slice(start.ch); }\n out.push(text);\n ++n;\n });\n return out\n}", "function getBetween(doc, start, end) {\n var out = [], n = start.line;\n doc.iter(start.line, end.line + 1, function (line) {\n var text = line.text;\n if (n == end.line) { text = text.slice(0, end.ch); }\n if (n == start.line) { text = text.slice(start.ch); }\n out.push(text);\n ++n;\n });\n return out\n}", "function getBetween(doc, start, end) {\n var out = [], n = start.line;\n doc.iter(start.line, end.line + 1, function (line) {\n var text = line.text;\n if (n == end.line) { text = text.slice(0, end.ch); }\n if (n == start.line) { text = text.slice(start.ch); }\n out.push(text);\n ++n;\n });\n return out\n}", "function getBetween(doc, start, end) {\n var out = [], n = start.line;\n doc.iter(start.line, end.line + 1, function (line) {\n var text = line.text;\n if (n == end.line) { text = text.slice(0, end.ch); }\n if (n == start.line) { text = text.slice(start.ch); }\n out.push(text);\n ++n;\n });\n return out\n}", "function getBetween(doc, start, end) {\n var out = [], n = start.line;\n doc.iter(start.line, end.line + 1, function (line) {\n var text = line.text;\n if (n == end.line) { text = text.slice(0, end.ch); }\n if (n == start.line) { text = text.slice(start.ch); }\n out.push(text);\n ++n;\n });\n return out\n}", "function getBetween(doc, start, end) {\n var out = [], n = start.line;\n doc.iter(start.line, end.line + 1, function (line) {\n var text = line.text;\n if (n == end.line) { text = text.slice(0, end.ch); }\n if (n == start.line) { text = text.slice(start.ch); }\n out.push(text);\n ++n;\n });\n return out\n}", "function start_and_end(str, tr) {\n\tif($('#body-user:visible').length && tr.find('.filetags-wrap:visible').length && str.length > 24 ){\n\t\treturn str.substr(0, 10) + '...' + str.substr(str.length-8, str.length);\n\t}\n\telse {\n\t\treturn str;\n\t}\n}", "function WithFragments() {}", "function END() {}", "function d(){for(var a=i,b=f[i++],c=b.split(/@@ -(\\d+)(?:,(\\d+))? \\+(\\d+)(?:,(\\d+))? @@/),d={oldStart:+c[1],oldLines:+c[2]||1,newStart:+c[3],newLines:+c[4]||1,lines:[],linedelimiters:[]},h=0,j=0;i<f.length&&!(0===f[i].indexOf(\"--- \")&&i+2<f.length&&0===f[i+1].indexOf(\"+++ \")&&0===f[i+2].indexOf(\"@@\"));i++){var k=f[i][0];if(\"+\"!==k&&\"-\"!==k&&\" \"!==k&&\"\\\\\"!==k)break;d.lines.push(f[i]),d.linedelimiters.push(g[i]||\"\\n\"),\"+\"===k?h++:\"-\"===k?j++:\" \"===k&&(h++,j++)}\n// Perform optional sanity checking\nif(\n// Handle the empty block count case\nh||1!==d.newLines||(d.newLines=0),j||1!==d.oldLines||(d.oldLines=0),e.strict){if(h!==d.newLines)throw new Error(\"Added line count did not match for hunk at line \"+(a+1));if(j!==d.oldLines)throw new Error(\"Removed line count did not match for hunk at line \"+(a+1))}return d}", "constructor(begin, end) {\n this.begin = begin;\n this.end = end;\n this.finished = false;\n }", "retrieveCharacterFormat(start, end) {\n this.characterFormat.copyFormat(start.paragraph.characterFormat);\n if (start.paragraph === end.paragraph && start.currentWidget.isLastLine()\n && start.offset === this.getLineLength(start.currentWidget) && start.offset + 1 === end.offset) {\n return;\n }\n let para = start.paragraph;\n if (start.offset === this.getParagraphLength(para) && !this.isEmpty) {\n para = this.getNextParagraphBlock(para);\n }\n while (!isNullOrUndefined(para) && para !== end.paragraph && para.isEmpty()) {\n para = this.getNextParagraphBlock(para);\n }\n let offset = para === start.paragraph ? start.offset : 0;\n let indexInInline = 0;\n if (!isNullOrUndefined(para) && !para.isEmpty()) {\n let position = new TextPosition(this.owner);\n let elemInfo = start.currentWidget.getInline(offset, indexInInline);\n let physicalLocation = this.getPhysicalPositionInternal(start.currentWidget, offset, true);\n position.setPositionForSelection(start.currentWidget, elemInfo.element, elemInfo.index, physicalLocation);\n this.getCharacterFormatForSelection(para, this, position, end);\n }\n }", "begin() {}", "function doChunk() {\n var origStart = start;\n var box, pos = text.substr(start).search(/\\S/);\n start += pos;\n if (pos < 0 || start >= end) {\n return true;\n }\n\n // Select a single character to determine the height of a line of text. The box.bottom\n // will be essential for us to figure out where the next line begins.\n range.setStart(node, start);\n range.setEnd(node, start + 1);\n box = actuallyGetRangeBoundingRect(range);\n\n // for justified text we must split at each space, because space has variable width.\n var found = false;\n if (isJustified || columnCount > 1) {\n pos = text.substr(start).search(/\\s/);\n if (pos >= 0) {\n // we can only split there if it's on the same line, otherwise we'll fall back\n // to the default mechanism (see findEOL below).\n range.setEnd(node, start + pos);\n var r = actuallyGetRangeBoundingRect(range);\n if (r.bottom == box.bottom) {\n box = r;\n found = true;\n start += pos;\n }\n }\n }\n\n if (!found) {\n // This code does three things: (1) it selects one line of text in `range`, (2) it\n // leaves the bounding rect of that line in `box` and (3) it returns the position\n // just after the EOL. We know where the line starts (`start`) but we don't know\n // where it ends. To figure this out, we select a piece of text and look at the\n // bottom of the bounding box. If it changes, we have more than one line selected\n // and should retry with a smaller selection.\n //\n // To speed things up, we first try to select all text in the node (`start` ->\n // `end`). If there's more than one line there, then select only half of it. And\n // so on. When we find a value for `end` that fits in one line, we try increasing\n // it (also in halves) until we get to the next line. The algorithm stops when the\n // right side of the bounding box does not change.\n //\n // One more thing to note is that everything happens in a single Text DOM node.\n // There's no other tags inside it, therefore the left/top coordinates of the\n // bounding box will not change.\n pos = (function findEOL(min, eol, max){\n range.setEnd(node, eol);\n var r = actuallyGetRangeBoundingRect(range);\n if (r.bottom != box.bottom && min < eol) {\n return findEOL(min, (min + eol) >> 1, eol);\n } else if (r.right != box.right) {\n box = r;\n if (eol < max) {\n return findEOL(eol, (eol + max) >> 1, max);\n } else {\n return eol;\n }\n } else {\n return eol;\n }\n })(start, Math.min(end, start + estimateLineLength), end);\n\n if (pos == start) {\n // if EOL is at the start, then no more text fits on this line. Skip the\n // remainder of this node entirely to avoid a stack overflow.\n return true;\n }\n start = pos;\n\n pos = range.toString().search(/\\s+$/);\n if (pos === 0) {\n return false; // whitespace only; we should not get here.\n }\n if (pos > 0) {\n // eliminate trailing whitespace\n range.setEnd(node, range.startOffset + pos);\n box = actuallyGetRangeBoundingRect(range);\n }\n }\n\n // another workaround for IE: if we rely on getBoundingClientRect() we'll overlap with the bullet for LI\n // elements. Calling getClientRects() and using the *first* rect appears to give us the correct location.\n // Note: not to be used in Chrome as it randomly returns a zero-width rectangle from the previous line.\n if (microsoft) {\n box = range.getClientRects()[0];\n }\n\n var str = range.toString();\n if (!/^(?:pre|pre-wrap)$/i.test(whiteSpace)) {\n // node with non-significant space -- collapse whitespace.\n str = str.replace(/\\s+/g, \" \");\n }\n else if (/\\t/.test(str)) {\n // with significant whitespace we need to do something about literal TAB characters.\n // There's no TAB glyph in a font so they would be rendered in PDF as an empty box,\n // and the whole text will stretch to fill the original width. The core PDF lib\n // does not have sufficient context to deal with it.\n\n // calculate the starting column here, since we initially discarded any whitespace.\n var cc = 0;\n for (pos = origStart; pos < range.startOffset; ++pos) {\n var code = text.charCodeAt(pos);\n if (code == 9) {\n // when we meet a TAB we must round up to the next tab stop.\n // in all browsers TABs seem to be 8 characters.\n cc += 8 - cc % 8;\n } else if (code == 10 || code == 13) {\n // just in case we meet a newline we must restart.\n cc = 0;\n } else {\n // ordinary character --> advance one column\n cc++;\n }\n }\n\n // based on starting column, replace any TAB characters in the string we actually\n // have to display with spaces so that they align to columns multiple of 8.\n while ((pos = str.search(\"\\t\")) >= 0) {\n var indent = \" \".substr(0, 8 - (cc + pos) % 8);\n str = str.substr(0, pos) + indent + str.substr(pos + 1);\n }\n }\n\n if (!found) {\n prevLineBottom = box.bottom;\n }\n drawText(str, box);\n }", "function doChunk() {\n var origStart = start;\n var box, pos = text.substr(start).search(/\\S/);\n start += pos;\n if (pos < 0 || start >= end) {\n return true;\n }\n\n // Select a single character to determine the height of a line of text. The box.bottom\n // will be essential for us to figure out where the next line begins.\n range.setStart(node, start);\n range.setEnd(node, start + 1);\n box = actuallyGetRangeBoundingRect(range);\n\n // for justified text we must split at each space, because space has variable width.\n var found = false;\n if (isJustified || columnCount > 1) {\n pos = text.substr(start).search(/\\s/);\n if (pos >= 0) {\n // we can only split there if it's on the same line, otherwise we'll fall back\n // to the default mechanism (see findEOL below).\n range.setEnd(node, start + pos);\n var r = actuallyGetRangeBoundingRect(range);\n if (r.bottom == box.bottom) {\n box = r;\n found = true;\n start += pos;\n }\n }\n }\n\n if (!found) {\n // This code does three things: (1) it selects one line of text in `range`, (2) it\n // leaves the bounding rect of that line in `box` and (3) it returns the position\n // just after the EOL. We know where the line starts (`start`) but we don't know\n // where it ends. To figure this out, we select a piece of text and look at the\n // bottom of the bounding box. If it changes, we have more than one line selected\n // and should retry with a smaller selection.\n //\n // To speed things up, we first try to select all text in the node (`start` ->\n // `end`). If there's more than one line there, then select only half of it. And\n // so on. When we find a value for `end` that fits in one line, we try increasing\n // it (also in halves) until we get to the next line. The algorithm stops when the\n // right side of the bounding box does not change.\n //\n // One more thing to note is that everything happens in a single Text DOM node.\n // There's no other tags inside it, therefore the left/top coordinates of the\n // bounding box will not change.\n pos = (function findEOL(min, eol, max){\n range.setEnd(node, eol);\n var r = actuallyGetRangeBoundingRect(range);\n if (r.bottom != box.bottom && min < eol) {\n return findEOL(min, (min + eol) >> 1, eol);\n } else if (r.right != box.right) {\n box = r;\n if (eol < max) {\n return findEOL(eol, (eol + max) >> 1, max);\n } else {\n return eol;\n }\n } else {\n return eol;\n }\n })(start, Math.min(end, start + estimateLineLength), end);\n\n if (pos == start) {\n // if EOL is at the start, then no more text fits on this line. Skip the\n // remainder of this node entirely to avoid a stack overflow.\n return true;\n }\n start = pos;\n\n pos = range.toString().search(/\\s+$/);\n if (pos === 0) {\n return false; // whitespace only; we should not get here.\n }\n if (pos > 0) {\n // eliminate trailing whitespace\n range.setEnd(node, range.startOffset + pos);\n box = actuallyGetRangeBoundingRect(range);\n }\n }\n\n // another workaround for IE: if we rely on getBoundingClientRect() we'll overlap with the bullet for LI\n // elements. Calling getClientRects() and using the *first* rect appears to give us the correct location.\n // Note: not to be used in Chrome as it randomly returns a zero-width rectangle from the previous line.\n if (microsoft) {\n box = range.getClientRects()[0];\n }\n\n var str = range.toString();\n if (!/^(?:pre|pre-wrap)$/i.test(whiteSpace)) {\n // node with non-significant space -- collapse whitespace.\n str = str.replace(/\\s+/g, \" \");\n }\n else if (/\\t/.test(str)) {\n // with significant whitespace we need to do something about literal TAB characters.\n // There's no TAB glyph in a font so they would be rendered in PDF as an empty box,\n // and the whole text will stretch to fill the original width. The core PDF lib\n // does not have sufficient context to deal with it.\n\n // calculate the starting column here, since we initially discarded any whitespace.\n var cc = 0;\n for (pos = origStart; pos < range.startOffset; ++pos) {\n var code = text.charCodeAt(pos);\n if (code == 9) {\n // when we meet a TAB we must round up to the next tab stop.\n // in all browsers TABs seem to be 8 characters.\n cc += 8 - cc % 8;\n } else if (code == 10 || code == 13) {\n // just in case we meet a newline we must restart.\n cc = 0;\n } else {\n // ordinary character --> advance one column\n cc++;\n }\n }\n\n // based on starting column, replace any TAB characters in the string we actually\n // have to display with spaces so that they align to columns multiple of 8.\n while ((pos = str.search(\"\\t\")) >= 0) {\n var indent = \" \".substr(0, 8 - (cc + pos) % 8);\n str = str.substr(0, pos) + indent + str.substr(pos + 1);\n }\n }\n\n if (!found) {\n prevLineBottom = box.bottom;\n }\n drawText(str, box);\n }", "function doChunk() {\n var origStart = start;\n var box, pos = text.substr(start).search(/\\S/);\n start += pos;\n if (pos < 0 || start >= end) {\n return true;\n }\n\n // Select a single character to determine the height of a line of text. The box.bottom\n // will be essential for us to figure out where the next line begins.\n range.setStart(node, start);\n range.setEnd(node, start + 1);\n box = actuallyGetRangeBoundingRect(range);\n\n // for justified text we must split at each space, because space has variable width.\n var found = false;\n if (isJustified || columnCount > 1) {\n pos = text.substr(start).search(/\\s/);\n if (pos >= 0) {\n // we can only split there if it's on the same line, otherwise we'll fall back\n // to the default mechanism (see findEOL below).\n range.setEnd(node, start + pos);\n var r = actuallyGetRangeBoundingRect(range);\n if (r.bottom == box.bottom) {\n box = r;\n found = true;\n start += pos;\n }\n }\n }\n\n if (!found) {\n // This code does three things: (1) it selects one line of text in `range`, (2) it\n // leaves the bounding rect of that line in `box` and (3) it returns the position\n // just after the EOL. We know where the line starts (`start`) but we don't know\n // where it ends. To figure this out, we select a piece of text and look at the\n // bottom of the bounding box. If it changes, we have more than one line selected\n // and should retry with a smaller selection.\n //\n // To speed things up, we first try to select all text in the node (`start` ->\n // `end`). If there's more than one line there, then select only half of it. And\n // so on. When we find a value for `end` that fits in one line, we try increasing\n // it (also in halves) until we get to the next line. The algorithm stops when the\n // right side of the bounding box does not change.\n //\n // One more thing to note is that everything happens in a single Text DOM node.\n // There's no other tags inside it, therefore the left/top coordinates of the\n // bounding box will not change.\n pos = (function findEOL(min, eol, max){\n range.setEnd(node, eol);\n var r = actuallyGetRangeBoundingRect(range);\n if (r.bottom != box.bottom && min < eol) {\n return findEOL(min, (min + eol) >> 1, eol);\n } else if (r.right != box.right) {\n box = r;\n if (eol < max) {\n return findEOL(eol, (eol + max) >> 1, max);\n } else {\n return eol;\n }\n } else {\n return eol;\n }\n })(start, Math.min(end, start + estimateLineLength), end);\n\n if (pos == start) {\n // if EOL is at the start, then no more text fits on this line. Skip the\n // remainder of this node entirely to avoid a stack overflow.\n return true;\n }\n start = pos;\n\n pos = range.toString().search(/\\s+$/);\n if (pos === 0) {\n return false; // whitespace only; we should not get here.\n }\n if (pos > 0) {\n // eliminate trailing whitespace\n range.setEnd(node, range.startOffset + pos);\n box = actuallyGetRangeBoundingRect(range);\n }\n }\n\n // another workaround for IE: if we rely on getBoundingClientRect() we'll overlap with the bullet for LI\n // elements. Calling getClientRects() and using the *first* rect appears to give us the correct location.\n // Note: not to be used in Chrome as it randomly returns a zero-width rectangle from the previous line.\n if (browser$2.msie) {\n box = range.getClientRects()[0];\n }\n\n var str = range.toString();\n if (!/^(?:pre|pre-wrap)$/i.test(whiteSpace)) {\n // node with non-significant space -- collapse whitespace.\n str = str.replace(/\\s+/g, \" \");\n }\n else if (/\\t/.test(str)) {\n // with significant whitespace we need to do something about literal TAB characters.\n // There's no TAB glyph in a font so they would be rendered in PDF as an empty box,\n // and the whole text will stretch to fill the original width. The core PDF lib\n // does not have sufficient context to deal with it.\n\n // calculate the starting column here, since we initially discarded any whitespace.\n var cc = 0;\n for (pos = origStart; pos < range.startOffset; ++pos) {\n var code = text.charCodeAt(pos);\n if (code == 9) {\n // when we meet a TAB we must round up to the next tab stop.\n // in all browsers TABs seem to be 8 characters.\n cc += 8 - cc % 8;\n } else if (code == 10 || code == 13) {\n // just in case we meet a newline we must restart.\n cc = 0;\n } else {\n // ordinary character --> advance one column\n cc++;\n }\n }\n\n // based on starting column, replace any TAB characters in the string we actually\n // have to display with spaces so that they align to columns multiple of 8.\n while ((pos = str.search(\"\\t\")) >= 0) {\n var indent = \" \".substr(0, 8 - (cc + pos) % 8);\n str = str.substr(0, pos) + indent + str.substr(pos + 1);\n }\n }\n\n if (!found) {\n prevLineBottom = box.bottom;\n }\n drawText(str, box);\n }", "function adjustSpanEnd(endPosition) {\n var pos = endPosition;\n while (isNonEdgeCharacter(sourceDoc.charAt(pos - 1))) {pos--}\n while (!isDelimiter(sourceDoc.charAt(pos)) && pos < sourceDoc.length) {pos++}\n return pos;\n }", "retrieveSectionFormat(start, end) {\n let startParaSection = this.getContainerWidget(start.paragraph);\n let endParaSection = this.getContainerWidget(end.paragraph);\n if (!isNullOrUndefined(startParaSection)) {\n this.sectionFormat.copyFormat(startParaSection.sectionFormat);\n let startPageIndex = this.viewer.pages.indexOf(startParaSection.page);\n let endPageIndex = this.viewer.pages.indexOf(endParaSection.page);\n for (let i = startPageIndex + 1; i <= endPageIndex; i++) {\n this.sectionFormat.combineFormat(this.viewer.pages[i].bodyWidgets[0].sectionFormat);\n }\n }\n }", "getAsyncBeginPos(){\n\t\tvar sz = this.async_stop_pos.count();\n\t\tif (sz == 0){\n\t\t\treturn \"\";\n\t\t}\n\t\tvar obj = this.async_stop_pos.item(sz - 1);\n\t\treturn obj.get(\"begin\", \"\", \"string\");\n\t}", "function bn(e,t,a,n){null==t&&(t=e.doc.first),null==a&&(a=e.doc.first+e.doc.size),n||(n=0);var r=e.display;if(n&&a<r.viewTo&&(null==r.updateLineNumbers||r.updateLineNumbers>t)&&(r.updateLineNumbers=t),e.curOp.viewChanged=!0,t>=r.viewTo)// Change after\n Jo&&pe(e.doc,t)<r.viewTo&&vn(e);else if(a<=r.viewFrom)// Change before\n Jo&&ge(e.doc,a+n)>r.viewFrom?vn(e):(r.viewFrom+=n,r.viewTo+=n);else if(t<=r.viewFrom&&a>=r.viewTo)// Full overlap\n vn(e);else if(t<=r.viewFrom){// Top overlap\n var f=wn(e,a,a+n,1);f?(r.view=r.view.slice(f.index),r.viewFrom=f.lineN,r.viewTo+=n):vn(e)}else if(a>=r.viewTo){// Bottom overlap\n var o=wn(e,t,t,-1);o?(r.view=r.view.slice(0,o.index),r.viewTo=o.lineN):vn(e)}else{// Gap in the middle\n var i=wn(e,t,t,-1),s=wn(e,a,a+n,1);i&&s?(r.view=r.view.slice(0,i.index).concat(ht(e,i.lineN,s.lineN)).concat(r.view.slice(s.index)),r.viewTo+=n):vn(e)}var c=r.externalMeasured;c&&(a<c.lineN?c.lineN+=n:t<c.lineN+c.size&&(r.externalMeasured=null))}", "function findBeginningAndEnd(cm, head, symb, inclusive) {\n var cur = copyCursor(head);\n var line = cm.getLine(cur.line);\n var chars = line.split('');\n var start, end, i, len;\n var firstIndex = chars.indexOf(symb);\n\n // the decision tree is to always look backwards for the beginning first,\n // but if the cursor is in front of the first instance of the symb,\n // then move the cursor forward\n if (cur.ch < firstIndex) {\n cur.ch = firstIndex;\n // Why is this line even here???\n // cm.setCursor(cur.line, firstIndex+1);\n }\n // otherwise if the cursor is currently on the closing symbol\n else if (firstIndex < cur.ch && chars[cur.ch] == symb) {\n end = cur.ch; // assign end to the current cursor\n --cur.ch; // make sure to look backwards\n }\n\n // if we're currently on the symbol, we've got a start\n if (chars[cur.ch] == symb && !end) {\n start = cur.ch + 1; // assign start to ahead of the cursor\n } else {\n // go backwards to find the start\n for (i = cur.ch; i > -1 && !start; i--) {\n if (chars[i] == symb) {\n start = i + 1;\n }\n }\n }\n\n // look forwards for the end symbol\n if (start && !end) {\n for (i = start, len = chars.length; i < len && !end; i++) {\n if (chars[i] == symb) {\n end = i;\n }\n }\n }\n\n // nothing found\n if (!start || !end) {\n return { start: cur, end: cur };\n }\n\n // include the symbols\n if (inclusive) {\n --start; ++end;\n }\n\n return {\n start: Pos(cur.line, start),\n end: Pos(cur.line, end)\n };\n }", "function findBeginningAndEnd(cm, head, symb, inclusive) {\n var cur = copyCursor(head);\n var line = cm.getLine(cur.line);\n var chars = line.split('');\n var start, end, i, len;\n var firstIndex = chars.indexOf(symb);\n\n // the decision tree is to always look backwards for the beginning first,\n // but if the cursor is in front of the first instance of the symb,\n // then move the cursor forward\n if (cur.ch < firstIndex) {\n cur.ch = firstIndex;\n // Why is this line even here???\n // cm.setCursor(cur.line, firstIndex+1);\n }\n // otherwise if the cursor is currently on the closing symbol\n else if (firstIndex < cur.ch && chars[cur.ch] == symb) {\n end = cur.ch; // assign end to the current cursor\n --cur.ch; // make sure to look backwards\n }\n\n // if we're currently on the symbol, we've got a start\n if (chars[cur.ch] == symb && !end) {\n start = cur.ch + 1; // assign start to ahead of the cursor\n } else {\n // go backwards to find the start\n for (i = cur.ch; i > -1 && !start; i--) {\n if (chars[i] == symb) {\n start = i + 1;\n }\n }\n }\n\n // look forwards for the end symbol\n if (start && !end) {\n for (i = start, len = chars.length; i < len && !end; i++) {\n if (chars[i] == symb) {\n end = i;\n }\n }\n }\n\n // nothing found\n if (!start || !end) {\n return { start: cur, end: cur };\n }\n\n // include the symbols\n if (inclusive) {\n --start; ++end;\n }\n\n return {\n start: Pos(cur.line, start),\n end: Pos(cur.line, end)\n };\n }", "function rangeFromTokens(start, end) {\n if (!end) {\n end = start;\n }\n return util_1.default.createRange(start.startLine - 1, start.startColumn - 1, end.endLine - 1, end.endColumn);\n}", "function splitOnlyLoader(content, { beginReg, endReg }) {\n let finish = false;\n let tempContent = '';\n\n while (!finish) {\n const begin = content.search(beginReg);\n const end = content.search(endReg);\n\n if (begin === -1 || end === -1) break;\n\n if (begin > end) {\n this.emitError(new Error('js end comments in front of begin comments'));\n } else if (end > begin) {\n tempContent += content.slice(0, begin);\n content = content.slice(end + content.match(endReg)[0].length);\n } else {\n finish = true;\n }\n }\n\n tempContent += content;\n\n return tempContent;\n}", "function match_block(node) {\n if (node.name === \"end\") {\n if (node.parent.name === \"IfStatement\") {\n // Try moving to the \"if\" part because\n // the rest of the code is looking for that\n node = node.parent?.firstChild?.firstChild\n } else {\n node = node.parent.firstChild\n }\n }\n\n if (node == null) {\n return []\n }\n\n // if (node.name === \"StructDefinition\") node = node.firstChild\n if (node.name === \"mutable\" || node.name === \"struct\") {\n if (node.name === \"struct\") node = node.parent.firstChild\n\n let struct_node = node.parent.getChild(\"struct\")\n let possibly_end = node.parent.lastChild\n let did_match = possibly_end.name === \"end\"\n if (!did_match || !struct_node) return null\n\n return [\n { from: node.from, to: struct_node.to },\n { from: possibly_end.from, to: possibly_end.to },\n ]\n }\n if (node.name === \"struct\") {\n let possibly_end = node.parent.lastChild\n let did_match = possibly_end.name === \"end\"\n if (!did_match) return null\n\n return [\n { from: node.from, to: node.to },\n { from: possibly_end.from, to: possibly_end.to },\n ]\n }\n\n if (node.name === \"quote\") {\n let possibly_end = node.parent.lastChild\n let did_match = possibly_end.name === \"end\"\n if (!did_match) return null\n\n return [\n { from: node.from, to: node.to },\n { from: possibly_end.from, to: possibly_end.to },\n ]\n }\n\n if (node.name === \"begin\") {\n let possibly_end = node.parent.lastChild\n let did_match = possibly_end.name === \"end\"\n if (!did_match) return null\n\n return [\n { from: node.from, to: node.to },\n { from: possibly_end.from, to: possibly_end.to },\n ]\n }\n\n if (node.name === \"do\") {\n let possibly_end = node.parent.lastChild\n let did_match = possibly_end.name === \"end\"\n if (!did_match) return null\n\n return [\n { from: node.from, to: node.to },\n { from: possibly_end.from, to: possibly_end.to },\n ]\n }\n\n if (node.name === \"for\") {\n let possibly_end = node.parent.lastChild\n let did_match = possibly_end.name === \"end\"\n if (!did_match) return null\n\n return [\n { from: node.from, to: node.to },\n { from: possibly_end.from, to: possibly_end.to },\n ]\n }\n\n if (node.name === \"let\") {\n let possibly_end = node.parent.lastChild\n let did_match = possibly_end.name === \"end\"\n if (!did_match) return null\n\n return [\n { from: node.from, to: node.to },\n { from: possibly_end.from, to: possibly_end.to },\n ]\n }\n\n if (node.name === \"macro\") {\n let possibly_end = node.parent.lastChild\n let did_match = possibly_end.name === \"end\"\n if (!did_match) return null\n\n return [\n { from: node.from, to: node.to },\n { from: possibly_end.from, to: possibly_end.to },\n ]\n }\n\n if (node.name === \"function\") {\n let possibly_end = node.parent.lastChild\n let did_match = possibly_end.name === \"end\"\n if (!did_match) return null\n\n return [\n { from: node.from, to: node.to },\n { from: possibly_end.from, to: possibly_end.to },\n ]\n }\n\n if (node.name === \"while\") {\n let possibly_end = node.parent.lastChild\n let did_match = possibly_end.name === \"end\"\n if (!did_match) return null\n\n return [\n { from: node.from, to: node.to },\n { from: possibly_end.from, to: possibly_end.to },\n ]\n }\n\n if (node.name === \"type\") node = node.parent.firstChild\n if (node.name === \"abstract\" || node.name === \"primitive\") {\n let possibly_end = node.parent.lastChild\n let did_match = possibly_end.name === \"end\"\n let struct_node = node.parent.getChild(\"type\")\n if (!did_match || !struct_node) return null\n\n return [\n { from: node.from, to: struct_node.to },\n { from: possibly_end.from, to: possibly_end.to },\n ]\n }\n\n if (node.name === \"try\" || node.name === \"catch\" || node.name === \"finally\") {\n if (node.name === \"catch\") node = node.parent\n if (node.name === \"finally\") node = node.parent\n\n let try_node = node.parent.firstChild\n let possibly_end = node.parent.lastChild\n let did_match = possibly_end.name === \"end\"\n if (!did_match) return null\n\n let catch_node = node.parent.getChild(\"CatchClause\")?.firstChild\n let finally_node = node.parent.getChild(\"FinallyClause\")?.firstChild\n\n return [\n { from: try_node.from, to: try_node.to },\n catch_node && { from: catch_node.from, to: catch_node.to },\n finally_node && { from: finally_node.from, to: finally_node.to },\n { from: possibly_end.from, to: possibly_end.to },\n ].filter((x) => x != null)\n }\n\n if (node.name === \"if\" || node.name === \"else\" || node.name === \"elseif\") {\n if (node.name === \"if\") node = node.parent\n if (node.name === \"else\") node = node.parent\n if (node.name === \"elseif\") node = node.parent.parent\n\n let try_node = node.parent.firstChild\n let possibly_end = node.parent.lastChild\n let did_match = possibly_end.name === \"end\"\n if (!did_match) return null\n\n let decorations = []\n decorations.push({ from: try_node.from, to: try_node.to })\n for (let elseif_clause_node of node.parent.getChildren(\"ElseifClause\")) {\n let elseif_node = elseif_clause_node.firstChild\n decorations.push({ from: elseif_node.from, to: elseif_node.to })\n }\n for (let else_clause_node of node.parent.getChildren(\"ElseClause\")) {\n let else_node = else_clause_node.firstChild\n decorations.push({ from: else_node.from, to: else_node.to })\n }\n decorations.push({ from: possibly_end.from, to: possibly_end.to })\n\n return decorations\n }\n\n return null\n}", "function wrappedRegionJParser (file, beg, end, fmt, cb) {\n if (beg >= end) {\n wrappedJParser(file, beg, fmt, cb);\n } else {\n inflateRegion(\n file, beg, end,\n function (b, ebsz) {\n nextBlockOffset(\n file, end,\n function (x2) {\n _wrapperCB(this, file, b, ebsz, fmt, end, x2, cb)\n });\n });\n };\n}", "function annot_offset(range_end){\n var lines = editor.getSession().getDocument().getLines(0, range_end.row);\n var total_off = 0;\n var num_char;\n\n for(var i = 0; i < lines.length; i++){\n num_char = lines[i].length;\n total_off += parseInt((num_char - 1) / 80, 10);\n }\n\n return total_off;\n}", "function shouldBreak(start, mid, end) {\n\t\t\tvar all = [start].concat(mid).concat([end]);\n\t\t\tvar previous = all[all.length - 2];\n\t\t\tvar next = end;\n\n\t\t\t// Lookahead termintor for:\n\t\t\t// GB10. (E_Base | EBG) Extend* ?\tE_Modifier\n\t\t\tvar eModifierIndex = all.lastIndexOf(E_Modifier);\n\t\t\tif (eModifierIndex > 1 && all.slice(1, eModifierIndex).every(function (c) {\n\t\t\t\treturn c == Extend;\n\t\t\t}) && [Extend, E_Base, E_Base_GAZ].indexOf(start) == -1) {\n\t\t\t\treturn Break;\n\t\t\t}\n\n\t\t\t// Lookahead termintor for:\n\t\t\t// GB12. ^ (RI RI)* RI\t?\tRI\n\t\t\t// GB13. [^RI] (RI RI)* RI\t?\tRI\n\t\t\tvar rIIndex = all.lastIndexOf(Regional_Indicator);\n\t\t\tif (rIIndex > 0 && all.slice(1, rIIndex).every(function (c) {\n\t\t\t\treturn c == Regional_Indicator;\n\t\t\t}) && [Prepend, Regional_Indicator].indexOf(previous) == -1) {\n\t\t\t\tif (all.filter(function (c) {\n\t\t\t\t\treturn c == Regional_Indicator;\n\t\t\t\t}).length % 2 == 1) {\n\t\t\t\t\treturn BreakLastRegional;\n\t\t\t\t} else {\n\t\t\t\t\treturn BreakPenultimateRegional;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// GB3. CR X LF\n\t\t\tif (previous == CR && next == LF) {\n\t\t\t\treturn NotBreak;\n\t\t\t}\n\t\t\t// GB4. (Control|CR|LF) ÷\n\t\t\telse if (previous == Control || previous == CR || previous == LF) {\n\t\t\t\t\tif (next == E_Modifier && mid.every(function (c) {\n\t\t\t\t\t\treturn c == Extend;\n\t\t\t\t\t})) {\n\t\t\t\t\t\treturn Break;\n\t\t\t\t\t} else {\n\t\t\t\t\t\treturn BreakStart;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t// GB5. ÷ (Control|CR|LF)\n\t\t\t\telse if (next == Control || next == CR || next == LF) {\n\t\t\t\t\t\treturn BreakStart;\n\t\t\t\t\t}\n\t\t\t\t\t// GB6. L X (L|V|LV|LVT)\n\t\t\t\t\telse if (previous == L && (next == L || next == V || next == LV || next == LVT)) {\n\t\t\t\t\t\t\treturn NotBreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t\t// GB7. (LV|V) X (V|T)\n\t\t\t\t\t\telse if ((previous == LV || previous == V) && (next == V || next == T)) {\n\t\t\t\t\t\t\t\treturn NotBreak;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t// GB8. (LVT|T) X (T)\n\t\t\t\t\t\t\telse if ((previous == LVT || previous == T) && next == T) {\n\t\t\t\t\t\t\t\t\treturn NotBreak;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t// GB9. X (Extend|ZWJ)\n\t\t\t\t\t\t\t\telse if (next == Extend || next == ZWJ) {\n\t\t\t\t\t\t\t\t\t\treturn NotBreak;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t// GB9a. X SpacingMark\n\t\t\t\t\t\t\t\t\telse if (next == SpacingMark) {\n\t\t\t\t\t\t\t\t\t\t\treturn NotBreak;\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t// GB9b. Prepend X\n\t\t\t\t\t\t\t\t\t\telse if (previous == Prepend) {\n\t\t\t\t\t\t\t\t\t\t\t\treturn NotBreak;\n\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t// GB10. (E_Base | EBG) Extend* ?\tE_Modifier\n\t\t\tvar previousNonExtendIndex = all.indexOf(Extend) != -1 ? all.lastIndexOf(Extend) - 1 : all.length - 2;\n\t\t\tif ([E_Base, E_Base_GAZ].indexOf(all[previousNonExtendIndex]) != -1 && all.slice(previousNonExtendIndex + 1, -1).every(function (c) {\n\t\t\t\treturn c == Extend;\n\t\t\t}) && next == E_Modifier) {\n\t\t\t\treturn NotBreak;\n\t\t\t}\n\n\t\t\t// GB11. ZWJ ? (Glue_After_Zwj | EBG)\n\t\t\tif (previous == ZWJ && [Glue_After_Zwj, E_Base_GAZ].indexOf(next) != -1) {\n\t\t\t\treturn NotBreak;\n\t\t\t}\n\n\t\t\t// GB12. ^ (RI RI)* RI ? RI\n\t\t\t// GB13. [^RI] (RI RI)* RI ? RI\n\t\t\tif (mid.indexOf(Regional_Indicator) != -1) {\n\t\t\t\treturn Break;\n\t\t\t}\n\t\t\tif (previous == Regional_Indicator && next == Regional_Indicator) {\n\t\t\t\treturn NotBreak;\n\t\t\t}\n\n\t\t\t// GB999. Any ? Any\n\t\t\treturn BreakStart;\n\t\t}", "function testStartsEndsWith(callback)\n{\n\ttesting.assert('pepito'.startsWith('pe'), 'Failed to match using startsWith()', callback);\n\ttesting.assert(!'pepito'.startsWith('po'), 'Invalid match using startsWith()', callback);\n\ttesting.assert('pepito'.endsWith('to'), 'Failed to match using endsWith()', callback);\n\ttesting.assert(!'pepito'.startsWith('po'), 'Invalid match using endsWith()', callback);\n\ttesting.success(callback);\n}", "getEndLocation() {\n const self = this;\n const ends = [\"End of the Project Gutenberg EBook\",\n \"End of Project Gutenberg's\",\n \"\\\\*\\\\*\\\\*END OF THE PROJECT GUTENBERG EBOOK\",\n \"\\\\*\\\\*\\\\* END OF THIS PROJECT GUTENBERG EBOOK\"\n ]\n const joined = ends.join('|');\n\n let endLocation;\n const lastLine = this.lines.find((line, i) => {\n return line.match(joined)\n })\n\n if (lastLine) {\n endLocation = this.lines.indexOf(lastLine);\n this.endLine = this.lines[endLocation]\n } else { // if Can 't find the ending.\n console.info(\"Can't find an ending line. Assuming that the book ends at the end of the text.\")\n endLocation = this.lines.length - 1 //# The end\n this.endLine = false;\n\n }\n console.info(`End line:: ${this.endLine} at line:: ${endLocation}`);\n return endLocation;\n }", "function dwscripts_canStripScriptDelimiters(charRange)\n{\n var dom = dw.getDocumentDOM();\n var nodeStr;\n var offsets;\n var i;\n\n // If we were not given a charRange, then assume that we're not\n // inside a script block\n if (charRange == null)\n return false;\n\n // Get the node containing this character range. \n var node = dom.offsetsToNode(charRange.startoffset, charRange.endoffset);\n if (node == null)\n return false;\n\n if (node.nodeType == Node.COMMENT_NODE)\n {\n // Both comments and script directives are treated as COMMENT_NODEs in\n // the DOM. In either case, we want to strip the script delimiters.\n //\n // Verify that the range is inside the node, as opposed to just before\n // or just after it. If it is inside, return true.\n\n offsets = dom.nodeToOffsets(node);\n return charRange.startoffset > offsets[0] &&\n charRange.endoffset < offsets[1];\n }\n\n if (node.nodeType == Node.ELEMENT_NODE &&\n (node.tagName == \"MM:BEGINLOCK\" || node.tagName == \"MM:ENDLOCK\"))\n {\n // The range is inside a locked region, which may be a script block.\n // Get the original source for the locked region and compare it to \n // the set of script delimiters for this server model. If no match\n // is found, this isn't a script block.\n\n var delimInfo = dom.serverModel.getDelimiters();\n var nodeStr = node.outerHTML;\n var isScriptBlock = false;\n for (i=0; i < delimInfo.length; i++)\n {\n delim = delimInfo[i];\n re = new RegExp(\"^\" + delim.startPattern + \"[^\\\\0]*\" + delim.endPattern + \"$\", \"i\");\n if (re.test(nodeStr))\n {\n isScriptBlock = true;\n break;\n }\n }\n if (!isScriptBlock)\n return false;\n \n // As we did for comments above, verify that the range is inside the\n // node. If it is, return true.\n var offsets = dom.nodeToOffsets(node);\n return charRange.startoffset > offsets[0] &&\n charRange.endoffset < offsets[1];\n }\n\n // The range is not inside a directive or a locked region, so return false\n return false;\n}", "function expandRangeToStartOfLine(range){!range.collapsed?true?invariant(false,'expandRangeToStartOfLine: Provided range is not collapsed.'):invariant(false):void 0;range=range.cloneRange();var containingElement=range.startContainer;if(containingElement.nodeType!==1){containingElement=containingElement.parentNode;}var lineHeight=getLineHeightPx(containingElement);// Imagine our text looks like:\r\n\t// <div><span>once upon a time, there was a <em>boy\r\n\t// who lived</em> </span><q><strong>under^ the\r\n\t// stairs</strong> in a small closet.</q></div>\r\n\t// where the caret represents the cursor. First, we crawl up the tree until\r\n\t// the range spans multiple lines (setting the start point to before\r\n\t// \"<strong>\", then before \"<div>\"), then at each level we do a search to\r\n\t// find the latest point which is still on a previous line. We'll find that\r\n\t// the break point is inside the span, then inside the <em>, then in its text\r\n\t// node child, the actual break point before \"who\".\r\n\tvar bestContainer=range.endContainer;var bestOffset=range.endOffset;range.setStart(range.startContainer,0);while(areRectsOnOneLine(getRangeClientRects(range),lineHeight)){bestContainer=range.startContainer;bestOffset=range.startOffset;!bestContainer.parentNode?true?invariant(false,'Found unexpected detached subtree when traversing.'):invariant(false):void 0;range.setStartBefore(bestContainer);if(bestContainer.nodeType===1&&getComputedStyle(bestContainer).display!=='inline'){// The start of the line is never in a different block-level container.\r\n\tbreak;}}// In the above example, range now spans from \"<div>\" to \"under\",\r\n\t// bestContainer is <div>, and bestOffset is 1 (index of <q> inside <div>)].\r\n\t// Picking out which child to recurse into here is a special case since we\r\n\t// don't want to check past <q> -- once we find that the final range starts\r\n\t// in <span>, we can look at all of its children (and all of their children)\r\n\t// to find the break point.\r\n\t// At all times, (bestContainer, bestOffset) is the latest single-line start\r\n\t// point that we know of.\r\n\tvar currentContainer=bestContainer;var maxIndexToConsider=bestOffset-1;do{var nodeValue=currentContainer.nodeValue;for(var ii=maxIndexToConsider;ii>=0;ii--){if(nodeValue!=null&&ii>0&&UnicodeUtils.isSurrogatePair(nodeValue,ii-1)){// We're in the middle of a surrogate pair -- skip over so we never\r\n\t// return a range with an endpoint in the middle of a code point.\r\n\tcontinue;}range.setStart(currentContainer,ii);if(areRectsOnOneLine(getRangeClientRects(range),lineHeight)){bestContainer=currentContainer;bestOffset=ii;}else{break;}}if(ii===-1||currentContainer.childNodes.length===0){// If ii === -1, then (bestContainer, bestOffset), which is equal to\r\n\t// (currentContainer, 0), was a single-line start point but a start\r\n\t// point before currentContainer wasn't, so the line break seems to\r\n\t// have occurred immediately after currentContainer's start tag\r\n\t//\r\n\t// If currentContainer.childNodes.length === 0, we're already at a\r\n\t// terminal node (e.g., text node) and should return our current best.\r\n\tbreak;}currentContainer=currentContainer.childNodes[ii];maxIndexToConsider=getNodeLength(currentContainer);}while(true);range.setStart(bestContainer,bestOffset);return range;}", "constructor(beginNode, endNode) {//construtor dos caminhos\r\n this.begin = beginNode;//no inicial\r\n this.end = endNode;//no final\r\n }", "function scaner(string,tset){\n \n // The first if statement is with PSTART to solve the problem of overlap we set priorities in the RE's\n\n if(PSTART.test(string.substr(0,3))){ // We check if the token set PSTART in it's properties\n\t\t // We use the regular expression PSTART.test to check if there is a match\n\t\tif(tset.hasOwnProperty(\"PSTART\"))\n\t\treturn {token: \"PSTART\", value: string.substr(0,3)} // If there is a match we retrun an object with the token name and the value matched\n\t}\n\n\t// PEND }}} Following our ordering PEnd comes befor TEND\n if(PEND.test(string.substr(0,3))) { \n\t\tif(tset.hasOwnProperty(\"PEND\"))\n\t\treturn {token: \"PEND\", value: string.substr(0,3)} \n\t}\n\n //Second case with the TSART following our priority\n\n\tif(TSTART.test(string.substr(0,2))){ // We check if the token set TSTART in it's properties\n\t\tif(tset.hasOwnProperty(\"TSTART\")) // We use the regular expression TSTART.test to check if there is a match\n\t\treturn {token: \"TSTART\", value: string.substr(0,2)} // If there is a match we retrun an object with the token name and the value matched\n\t}\n\n// DSTART\nif(DSTART.test(string.substr(0,2))){ \n\t\t if(tset.hasOwnProperty(\"DSTART\"))\n\t\treturn {token: \"DSTART\", value: string.substr(0,2)} \n\t}\n\n\n// TEND }}\nif(TEND.test(string.substr(0,2))) { \n\t\tif(tset.hasOwnProperty(\"TEND\")) \n\t\treturn {token: \"TEND\", value: string.substr(0,2)} \n\t}\n\n// DEND :}\nif(DEND.test(string.substr(0,2))) { \n\t\tif(tset.hasOwnProperty(\"DEND\"))\n\t\treturn {token: \"DEND\", value: string.substr(0,2)} \n\t}\n\n//PIPE\n\nif(PIPE.test(string.substr(0,1))) { \n\t\t if(tset.hasOwnProperty(\"PIPE\"))\n\t\treturn {token: \"PIPE\", value: string.substr(0,1)} \n\t}\n\n\n\n\n\n\n\n\n\n\n\n//OUTERTEXT\n\n\nvar s0= string;\nvar counter =0;\nvar val0=\"\";\n\n\nwhile(s0){\n\n\n\tif(!OUTERTEXT.test(s0.substr(0,2)))// 0-2 because of Tstart and Tstart\n\t\tbreak\n\n\tval0 += s0.charAt(0);\n\ts0= s0.substr(1);\n\t\n\t}\n\tif(tset.hasOwnProperty(\"OUTERTEXT\")){ \n\t\treturn {token:\"OUTERTEXT\", value: val0} \n\t\t}\n\n\n\n\n// INNERTEXT\n\n\n\n\t\t//if(INNERTEXT.test(string.substr(0,1))) \n\nvar s1= string;\nvar val1=\"\";\n\nwhile(s1){\n\n\t//if(!INNERTEXT.test(s.substr(0,2))) // 0-3 because of Pstart \"{{{\"\n\t//\tbreak\n\n\tif(PSTART.test(s1.substr(0,3))) // check the ending conditions\n\t\tbreak\n\tif(TSTART.test(s1.substr(0,2)))\n\t\tbreak\n\telse if(DSTART.test(s1.substr(0,2)))\n\t\tbreak\n\tif(TEND.test(s1.substr(0,2)))\n\t\tbreak \n\tif(PIPE.test(s1.charAt(0)))\n\t\tbreak\n\t\t\n\tval1= val1+s1.charAt(0);\n\ts1= s1.substr(1);\n\t}\n\nif(tset.hasOwnProperty(\"INNERTEXT\")){ \n\t\treturn {token: \"INNERTEXT\", value: val1} \n\t}\n\n\n\n\n\n// INNER D TEXT \n\n\t\t//if(INNERDTEXT.test(string.substr(0,1))) \n\n\tvar s2= string;\n\tvar val2=\"\";\n\nwhile(s2){\n\n\t//if(!INNERDTEXT.test(s.substr(0,2))) // 0-3 because of Pstart \"{{{\"\n\t//\tbreak \n\n\t\tif(PSTART.test(s2.substr(0,3))) // check the ending conditions\n\t\tbreak\n\telse if(TSTART.test(s2.substr(0,2)))\n\t\tbreak\n\telse if(DSTART.test(s2.substr(0,2)))\n\t\tbreak\n\telse if(DEND.test(s2.substr(0,2)))\n\t\tbreak\n\telse if(PIPE.test(s2.charAt(0)))\n\t\tbreak\n\t\t\n\tval2+= s2.charAt(0);\n\ts2= s2.substr(1);\n\t\n\t}\n\n\tif(tset.hasOwnProperty(\"INNERDTEXT\")){ \n\n\t\treturn {token: \"INNERDTEXT\", value: val2} \n\t}\n\n\n\n\n\n// PNAME \n\n\t\t//if(PNAME.test(string.substr(0,1))) \n\t\tvar s3= string;\n\t\tvar val3=\"\";\n\n\t\twhile(s3){\n\n\t\tif(!PNAME.test(s3.substr(0,3))) // 0-3 because of PEND\n\t\t\tbreak \n\t\t\n\tval3= val3+s3.charAt(0);\n\ts3= s3.substr(1);\n\t}\n\n\tif(tset.hasOwnProperty(\"PNAME\")){ \n\t\treturn {token: \"PNAME\", value: val3} \n\t}\n\n\n\n\n\n\n\n\n}", "prevMatchInRange(state, from, to) {\n for (let pos = to;;) {\n let start = Math.max(from, pos - 10000 /* ChunkSize */ - this.spec.unquoted.length);\n let cursor = stringCursor(this.spec, state, start, pos), range = null;\n while (!cursor.nextOverlapping().done)\n range = cursor.value;\n if (range)\n return range;\n if (start == from)\n return null;\n pos -= 10000 /* ChunkSize */;\n }\n }", "function shouldBreak(start, mid, end){\n\t\tvar all = [start].concat(mid).concat([end]);\n\t\tvar previous = all[all.length - 2];\n\t\tvar next = end;\n\t\t\n\t\t// Lookahead termintor for:\n\t\t// GB10. (E_Base | EBG) Extend* ?\tE_Modifier\n\t\tvar eModifierIndex = all.lastIndexOf(E_Modifier);\n\t\tif(eModifierIndex > 1 &&\n\t\t\tall.slice(1, eModifierIndex).every(function(c){return c == Extend}) &&\n\t\t\t[Extend, E_Base, E_Base_GAZ].indexOf(start) == -1){\n\t\t\treturn Break\n\t\t}\n\n\t\t// Lookahead termintor for:\n\t\t// GB12. ^ (RI RI)* RI\t?\tRI\n\t\t// GB13. [^RI] (RI RI)* RI\t?\tRI\n\t\tvar rIIndex = all.lastIndexOf(Regional_Indicator);\n\t\tif(rIIndex > 0 &&\n\t\t\tall.slice(1, rIIndex).every(function(c){return c == Regional_Indicator}) &&\n\t\t\t[Prepend, Regional_Indicator].indexOf(previous) == -1) { \n\t\t\tif(all.filter(function(c){return c == Regional_Indicator}).length % 2 == 1) {\n\t\t\t\treturn BreakLastRegional\n\t\t\t}\n\t\t\telse {\n\t\t\t\treturn BreakPenultimateRegional\n\t\t\t}\n\t\t}\n\t\t\n\t\t// GB3. CR X LF\n\t\tif(previous == CR && next == LF){\n\t\t\treturn NotBreak;\n\t\t}\n\t\t// GB4. (Control|CR|LF) ÷\n\t\telse if(previous == Control || previous == CR || previous == LF){\n\t\t\tif(next == E_Modifier && mid.every(function(c){return c == Extend})){\n\t\t\t\treturn Break\n\t\t\t}\n\t\t\telse {\n\t\t\t\treturn BreakStart\n\t\t\t}\n\t\t}\n\t\t// GB5. ÷ (Control|CR|LF)\n\t\telse if(next == Control || next == CR || next == LF){\n\t\t\treturn BreakStart;\n\t\t}\n\t\t// GB6. L X (L|V|LV|LVT)\n\t\telse if(previous == L && \n\t\t\t(next == L || next == V || next == LV || next == LVT)){\n\t\t\treturn NotBreak;\n\t\t}\n\t\t// GB7. (LV|V) X (V|T)\n\t\telse if((previous == LV || previous == V) && \n\t\t\t(next == V || next == T)){\n\t\t\treturn NotBreak;\n\t\t}\n\t\t// GB8. (LVT|T) X (T)\n\t\telse if((previous == LVT || previous == T) && \n\t\t\tnext == T){\n\t\t\treturn NotBreak;\n\t\t}\n\t\t// GB9. X (Extend|ZWJ)\n\t\telse if (next == Extend || next == ZWJ){\n\t\t\treturn NotBreak;\n\t\t}\n\t\t// GB9a. X SpacingMark\n\t\telse if(next == SpacingMark){\n\t\t\treturn NotBreak;\n\t\t}\n\t\t// GB9b. Prepend X\n\t\telse if (previous == Prepend){\n\t\t\treturn NotBreak;\n\t\t}\n\t\t\n\t\t// GB10. (E_Base | EBG) Extend* ?\tE_Modifier\n\t\tvar previousNonExtendIndex = all.indexOf(Extend) != -1 ? all.lastIndexOf(Extend) - 1 : all.length - 2;\n\t\tif([E_Base, E_Base_GAZ].indexOf(all[previousNonExtendIndex]) != -1 &&\n\t\t\tall.slice(previousNonExtendIndex + 1, -1).every(function(c){return c == Extend}) &&\n\t\t\tnext == E_Modifier){\n\t\t\treturn NotBreak;\n\t\t}\n\t\t\n\t\t// GB11. ZWJ ? (Glue_After_Zwj | EBG)\n\t\tif(previous == ZWJ && [Glue_After_Zwj, E_Base_GAZ].indexOf(next) != -1) {\n\t\t\treturn NotBreak;\n\t\t}\n\n\t\t// GB12. ^ (RI RI)* RI ? RI\n\t\t// GB13. [^RI] (RI RI)* RI ? RI\n\t\tif(mid.indexOf(Regional_Indicator) != -1) { \n\t\t\treturn Break;\n\t\t}\n\t\tif(previous == Regional_Indicator && next == Regional_Indicator) {\n\t\t\treturn NotBreak;\n\t\t}\n\n\t\t// GB999. Any ? Any\n\t\treturn BreakStart;\n\t}", "function expandTagUnderCursor(cm, head, inclusive) {\n var cur = head;\n if (!CodeMirror.findMatchingTag || !CodeMirror.findEnclosingTag) {\n return { start: cur, end: cur };\n }\n\n var tags = CodeMirror.findMatchingTag(cm, head) || CodeMirror.findEnclosingTag(cm, head);\n if (!tags || !tags.open || !tags.close) {\n return { start: cur, end: cur };\n }\n\n if (inclusive) {\n return { start: tags.open.from, end: tags.close.to };\n }\n return { start: tags.open.to, end: tags.close.from };\n }", "function getOffsetsAfterCheckingForBodySelection(allText,currOffs){\n var offsets = currOffs;\n var selStr = allText.substring(offsets[0],offsets[1]);\n var newStartOff = currOffs[0];\n var newEndOff = currOffs[1];\n var openBracketInd,closeBracketInd,nOpenBrackets,nCloseBrackets;\n var ind;\n \n if ( selStr.indexOf(\"<BODY\") == 0 || selStr.indexOf(\"<body\") == 0 ){\n nOpenBrackets = 1;\n nCloseBrackets = 0;\n closeBracketInd = 0; // index of closing bracket of </body>\n ind=1;\n \n while ( !closeBracketInd && selStr.charAt(ind) ) {\n if ( selStr.charAt(ind) == \"<\" ){\n nOpenBrackets++;\n } else if (selStr.charAt(ind) == \">\" ){\n nCloseBrackets++;\n if( nOpenBrackets == nCloseBrackets ){\n closeBracketInd = ind;\n }\n }\n ind++;\n }\n \n // get first non-newline character inside of the body tag\n newStartOff = closeBracketInd + 1;\n while ( selStr.charAt(newStartOff) == \"\\n\" ||\n selStr.charAt(newStartOff) == \"\\r\" ) {\n newStartOff++;\n }\n \n // get last non-newline character inside of the body tag\n openBracketInd = selStr.lastIndexOf(\"<\"); // open bracket index of </body>\n newEndOff = openBracketInd - 1;\n while ( selStr.charAt(newEndOff) == \"\\n\" ||\n selStr.charAt(newEndOff) == \"\\r\" ) {\n newEndOff--;\n }\n \n // add 1 because selection actually goes to newEndOff minus one\n newEndOff++;\n\n newStartOff += currOffs[0];\n newEndOff += currOffs[0];\n }\n\n return new Array(newStartOff,newEndOff); \n}", "function substringByStartAndEnd(input, start, end) {}", "function loadannotationBlock(utt) {\n /* main orthographic line */\n\tvar utts = $(utt);\n\t/* user and time information */\n // console.log(\"ts: \" + utts.attr(\"start\"));\n // console.log(\"tsx: \" + ts);\n\tvar ts = checknumber(timelineRef(utts.attr(\"start\")));\n\tvar te = checknumber(timelineRef(utts.attr(\"end\")));\n lastEndTime = ts; // time of the previous end of an element, even if no element processed yet\n\tvar loc = checkstring(utts.attr(\"who\"));\n\tif (loc !== '') trjs.data.codesdata[loc] = true;\n\t// names of the locutors found in the transcript in case persons description is incomplete\n /* segments contain u and anchors */\n var tmp = utts.find(\"u\");\n if (!tmp || tmp.length < 1) { // no u found\n \ttmp = utts.find(\"note\");\n \tif (tmp && tmp.length > 0) {\n \t\tvar tr = $(tmp[0]).attr('type');\n \t\tvar ty = $(tmp[0]).text();\n//\t\t\t'<table><tr><td class=\"notetxt ttype\">' + tr + '</td><td class=\"notetxt tsubtype\">' + ty + '</td></tr></table>';\n loadTrans.push({loc: \"+note+\", ts: '', te: '', tx: (tr ? tr : ''), stx: ty, type: 'note'});\n \t}\n } else {\n\t var elt = loadUSeg('', tmp[0], ts, te, loc, 'loc');\n addLineOfTranscript(loc, lastEndTime, te, elt, 'loc');\n }\n /* tiers lines */\n /* for now because it is not final:\n * read u and spanGrp\n */\n\tvar childs = utts.children();\n for (var spg=0; spg < childs.length; spg++) {\n if (childs[spg].nodeName === 'spanGrp')\n loadSpanGrp(childs[spg], loc);\n }\n}", "function boyer_moore_horspool(raw, templ) {\n\tvar indexes = [];\n\tvar stop_table = {};\n\tvar t_len = templ.length;\n\tvar start_offset = 0;\n\tvar curr_substr = '';\n\tfor(var i = 0; i < t_len - 1; i++) {\n\t\tstop_table[templ[i]] = t_len - i - 1;\n\t}\n\t//console.log(stop_table);\n\twhile(true) {\n\t\tcurr_substr = raw.substr(start_offset, t_len);\n\t\t//console.log(curr_substr, start_offset, t_len);\n\t\tif(curr_substr === templ)\n\t\t\tindexes.push(start_offset)\n\t\tif(start_offset + t_len > raw.length)\n\t\t\tbreak\n\t\tlsymb = curr_substr[curr_substr.length-1]\n\t\tstart_offset += stop_table[lsymb]? stop_table[lsymb] : t_len;\n\t}\n\treturn indexes\n}", "match(input, start, end) {\n start = start || 0\n end = end || input.length\n if(typeof input === 'string') input = new Source(input)\n if(!this.startsWith(input.get(start))) return this.error(input, start, start)\n var n = end\n end = start+1\n if(end==n) return this.error(input, start, end)\n var str = \"\"\n while(end<n && input.get(end)!=this.quotation){\n if(input.get(end)=='\\\\'){\n end++\n if(end==n) return this.error(input, start, end)\n if(input.get(end)=='u') {\n end++\n var c = 0\n while(end<n && c<4 && Character.isHexa(input.get(end))){\n end++\n c++\n }\n if(c!=4) return this.error(input, start, end)\n str += String.fromCharCode(Number.parseInt(input.substring(end-4,end),16)) \n }else {\n switch(input.get(end)){\n case 'n': str += '\\n'; break;\n case 'r': str += '\\r'; break;\n case 't': str += '\\t'; break;\n case 'b': str += '\\b'; break;\n case 'f': str += '\\f'; break;\n case '\\\\': case '/': str += input.get(end); break;\n default:\n if(input.get(end)!=this.quotation)\n return this.error(input, start, end)\n str += this.quotation\n }\n end++\n }\n }else{\n str += input.get(end)\n end++\n }\n }\n if(end==n) return this.error(input, start, end)\n end++\n return this.token(input, start, end, str)\n }", "function textInlineCommentEndIndex(text, i) {\n var j = indexOfEndRecurse(text, \"<%--\", \"--%>\", i + 4);\n if ( !j ) {\n textExceptionThrow(text, i, \"The inline comment statement '<%--' was not closed with a '--%>'\")\n }\n return j + 4; // Returns start of index for comment\n }", "match(input, start, end){\n start = start || 0\n end = end || input.length\n if(typeof input === 'string') input = new Source(input)\n if(!this.startsWith(input.get(start)))\n return this.error(input,start,start+1)\n var n=end\n end=start+1\n while(end<n && this.valid(input.get(end))) end++\n var s = (this.useStarter)?start+1:start\n var m = (end-s)%4\n if(s==end || m==1) return this.error(input,start,end)\n if(m>0) {\n while(end<n && m<4 && input.get(end)=='=') {\n end++\n m++\n }\n if(m<4) return this.error(input,start,end)\n }\n return this.token(input,start,end,Base64.decode(input.substring(s,end)))\n }", "function Qn(e,t,a,n){function r(e){return a?a[e]:null}function f(e,a,r){ot(e,a,r,n),wt(e,\"change\",e,t)}function o(e,t){for(var a=[],f=e;f<t;++f)a.push(new gi(c[f],r(f),n));return a}var i=t.from,s=t.to,c=t.text,u=T(e,i.line),l=T(e,s.line),d=p(c),_=r(c.length-1),m=s.line-i.line;\n // Adjust the line structure\n if(t.full)e.insert(0,o(0,c.length)),e.remove(c.length,e.size-c.length);else if(Zn(e,t)){\n // This is a whole-line replace. Treated specially to make\n // sure line objects move the way they are supposed to.\n var g=o(0,c.length-1);f(l,l.text,_),m&&e.remove(i.line,m),g.length&&e.insert(i.line,g)}else if(u==l)if(1==c.length)f(u,u.text.slice(0,i.ch)+d+u.text.slice(s.ch),_);else{var h=o(1,c.length-1);h.push(new gi(d+u.text.slice(s.ch),_,n)),f(u,u.text.slice(0,i.ch)+c[0],r(0)),e.insert(i.line+1,h)}else if(1==c.length)f(u,u.text.slice(0,i.ch)+c[0]+l.text.slice(s.ch),r(0)),e.remove(i.line+1,m);else{f(u,u.text.slice(0,i.ch)+c[0],r(0)),f(l,d+l.text.slice(s.ch),_);var b=o(1,c.length-1);m>1&&e.remove(i.line+1,m-1),e.insert(i.line+1,b)}wt(e,\"change\",e,t)}", "function getInjectorTagsRegExp (starttag, endtag) {\n return new RegExp('([\\t ]*)(' + escapeForRegExp(starttag) + ')(\\\\n|\\\\r|.)*?(' + escapeForRegExp(endtag) + ')', 'gi');\n //return new RegExp('(' + escapeForRegExp(starttag) + ')(\\\\n|\\\\r|.)*?(' + escapeForRegExp(endtag) + ')', 'gi');\n}", "parseBlock(s, currentRehearsalGroup, latest_variables){\n // parase until block boundary is found\n // block boundary = \"[\" or 2 successive NL or NOL\n try{\n var r = null;\n var loop_cnt = 0;\n\n var block = new common.Block();\n var current_align = \"expand\";\n\n this.context.contiguous_line_break = 0; // This should be done only if NL is really consumed.\n\n let num_meas_row = 0;\n\n let MAX_LOOP = 1000;\n\n let end_of_rg = false;\n\n // eslint-disable-next-line no-constant-condition\n while (true) {\n r = this.nextToken(s);\n if (r.type == TOKEN_END){\n s = r.s; // explicitly consume the last spaces if any.\n end_of_rg = true;\n break;\n }else if (r.type == TOKEN_NL) {\n this.context.line += 1;\n this.context.contiguous_line_break += 1;\n current_align = \"expand\"; // default is expand\n //if(this.context.contiguous_line_break >= 2) break; Do not break here. If the first non NL element is found, then break.\n } else if(r.type == TOKEN_BACK_SLASH){\n if(this.context.contiguous_line_break >= 2) break;\n // Expect TOKEN_NL \n r = this.nextToken(r.s);\n if(r.type != TOKEN_NL) this.onParseError(\"INVALID CODE DETECTED AFTER BACK SLASH\");\n this.context.line += 1;\n //block.appendChild(new common.RawSpaces(r.sss));\n //block.appendChild(new common.RawSpaces(r.token)); \n // Does not count as line break\n }else if(r.type == TOKEN_BRACKET_RA){\n if(this.context.contiguous_line_break >= 2) break;\n // Right aligh indicoator > which is outside measure\n current_align = \"right\";\n }else if(r.type == TOKEN_BRACKET_LA){\n if(this.context.contiguous_line_break >= 2) break;\n // Right aligh indicoator > which is outside measure\n current_align = \"left\";\n } else if (r.type == TOKEN_BRACKET_LS) {\n // Next rehearsal mark detected.\n // Do not consume.\n end_of_rg = true;\n break;\n } else if (\n [\n TOKEN_MB,\n TOKEN_MB_DBL,\n TOKEN_MB_LOOP_BEGIN,\n TOKEN_MB_LOOP_END,\n TOKEN_MB_LOOP_BOTH,\n TOKEN_MB_FIN,\n TOKEN_MB_DBL_SIMILE\n ].indexOf(r.type) >= 0\n ) {\n if(this.context.contiguous_line_break >= 2) break;\n\n let is_new_line_middle_of_block = num_meas_row > 0 && this.context.contiguous_line_break == 1;\n\n this.context.contiguous_line_break = 0;\n \n r = this.parseMeasures(r, r.s); // the last NL has not been consumed.\n // Apply the variables valid at this point for each measures\n //r.measures.forEach(m=>{ m.variables = common.shallowcopy(latest_variables);});\n r.measures.forEach(m=>{\n for(let key in latest_variables){\n m.setVariable(latest_variables[key]);\n }\n });\n\n // For the first measure, set align and new line mark.\n r.measures[0].align = current_align;\n r.measures[0].raw_new_line = is_new_line_middle_of_block; // mark to the first measure\n block.concat(r.measures);\n\n ++num_meas_row;\n\n } else if (r.type == TOKEN_PERCENT) {\n if(this.context.contiguous_line_break >= 2) break;\n // Expression\n r = this.parseVariable(r.s); // last NL would not be consumed\n let variable = new common.Variable(r.key, r.value);\n //block.setVariable(r.key, r.value); Do not do this as with this, only the last variable will be valid.\n latest_variables[r.key] = variable;\n block.appendChild(variable);\n this.context.contiguous_line_break = 0; // -= 1; // Does not reset to 0, but cancell the new line in the same row as this variable\n } else {\n console.log(r.token);\n this.onParseError(\"ERROR_WHILE_PARSE_MOST_OUTSIDER\");\n }\n s = r.s;\n loop_cnt++;\n if (loop_cnt >= MAX_LOOP){\n throw \"Too much elements or infnite loop detected with unkown reason\";\n }\n }\n return { block:block, s:s, end_of_rg:end_of_rg};\n }catch(e){\n console.error(e);\n return null;\n }\n }", "function findSameString(startPos, endPos) {\n var oentity = sourceDoc.substring(startPos, endPos);\n var strLen = endPos - startPos;\n\n var ary = new Array();\n var from = 0;\n while (true) {\n var sameStrPos = sourceDoc.indexOf(oentity, from);\n if (sameStrPos == -1) break;\n\n if (!isOutsideDelimiter(sourceDoc, sameStrPos, sameStrPos + strLen)) {\n var obj = new Object();\n obj['begin'] = sameStrPos;\n obj['end'] = sameStrPos + strLen;\n\n var isExist = false;\n for(var sid in spans) {\n if(spans[sid]['begin'] == obj['begin'] && spans[sid]['end'] == obj['end'] && spans[sid].category == obj.category) {\n isExist = true;\n break;\n }\n }\n\n if(!isExist && startPos != sameStrPos) {\n ary.push(obj);\n }\n }\n from = sameStrPos + 1;\n }\n return ary;\n }", "ranges(words, history, custom = () => {}) {\n // [[start, end, type], ...]\n let ranges = words.map((w, n) => w.ranges(this.toString()).map(r => [...r, n])).flat().sort((a, b) => {\n return a[0] - b[0];\n });\n // remove conflicts\n let offset = 0;\n ranges.forEach((range, m) => {\n ranges[m][0] = Math.max(range[0], offset);\n offset = Math.max(range[1] + 1, offset);\n });\n // remove empty ranges\n ranges = ranges.filter(r => r[1] >= r[0]);\n\n // extract text nodes\n const content = this.toString();\n\n const doc = this.e.ownerDocument;\n const walk = doc.createTreeWalker(this.e, NodeFilter.SHOW_TEXT, {\n acceptNode: () => {\n return NodeFilter.FILTER_ACCEPT;\n }\n }, false);\n let t;\n let position = -1;\n let ch;\n const update = () => {\n position += 1;\n if (position === content.length) {\n return false;\n }\n ch = content[position];\n };\n update();\n let range = ranges.shift();\n let e = doc.createRange();\n\n const track = () => {\n const out = [];\n\n while (t = walk.nextNode()) {\n const ignore = history.has(t);\n\n history.add(t);\n const data = t.data.replace(/[\\n\\t]/g, ' ');\n\n for (let x = 0; x < data.length; x += 1) {\n if (data[x] === ch) {\n if (range[0] === position) {\n e.setStart(t, x);\n }\n if (range[1] === position) {\n e.setEnd(t, x + 1);\n if (ignore === false) {\n custom(e, this.words[range[2]]);\n out.push(e);\n }\n\n range = ranges.shift();\n\n if (!range) {\n return out;\n }\n e = doc.createRange();\n }\n if (update() === false) {\n throw Error('position reached');\n }\n }\n }\n }\n throw Error('end of stream');\n };\n\n return track();\n }", "function cmtx_add_tag(start, end) {\n var obj = document.getElementById('cmtx_comment');\n\n jQuery('#cmtx_comment').focus();\n\n if (document.selection && document.selection.createRange) { // Internet Explorer\n selection = document.selection.createRange();\n\n if (selection.parentElement() == obj) {\n selection.text = start + selection.text + end;\n }\n } else if (typeof(obj) != 'undefined') { // Firefox\n var length = jQuery('#cmtx_comment').val().length;\n var selection_start = obj.selectionStart;\n var selection_end = obj.selectionEnd;\n\n jQuery('#cmtx_comment').val(obj.value.substring(0, selection_start) + start + obj.value.substring(selection_start, selection_end) + end + obj.value.substring(selection_end, length));\n } else {\n jQuery('#cmtx_comment').val(start + end);\n }\n\n cmtxUpdateCommentCounter();\n\n jQuery('#cmtx_comment').focus();\n}", "matchEnd() {\n return false;\n }", "onLineEnd() { }" ]
[ "0.6421277", "0.60679513", "0.5765159", "0.5595722", "0.558579", "0.55312395", "0.5516178", "0.54527944", "0.54402745", "0.54402745", "0.54402745", "0.54167163", "0.54167163", "0.54167163", "0.54167163", "0.54167163", "0.54167163", "0.54167163", "0.54167163", "0.54167163", "0.54167163", "0.54167163", "0.54167163", "0.54167163", "0.54167163", "0.54167163", "0.54167163", "0.54167163", "0.5413029", "0.5413029", "0.5413029", "0.5413029", "0.5413029", "0.5413029", "0.5413029", "0.5408794", "0.54029584", "0.5391722", "0.5391722", "0.53746605", "0.5350087", "0.53469735", "0.5345908", "0.5341633", "0.53152573", "0.53152573", "0.53152573", "0.53152573", "0.53152573", "0.53152573", "0.53152573", "0.53152573", "0.53152573", "0.53152573", "0.53152573", "0.52996826", "0.52747875", "0.52586985", "0.5254748", "0.5246221", "0.5227591", "0.521664", "0.52058226", "0.52058226", "0.52058226", "0.5200219", "0.5194244", "0.5172723", "0.5154143", "0.51419616", "0.51419616", "0.51389205", "0.5122465", "0.51086795", "0.51071644", "0.5097591", "0.50797725", "0.5057151", "0.5052306", "0.5047024", "0.5044913", "0.5030063", "0.5027961", "0.50215185", "0.50143385", "0.500835", "0.5002545", "0.5002359", "0.49816507", "0.49701336", "0.49678177", "0.49601066", "0.49580795", "0.49573165", "0.4956104", "0.49532637", "0.49518698", "0.49479046", "0.4943025", "0.49367052", "0.49181965" ]
0.0
-1
Build the script in Listing 31 in such a way that one variable would control the size of all the circles (meaning changing that variable should change the size of all the circles) and another one should control the radius difference for all the circles
function setup() { createCanvas(400, 400); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function set_bokeh_radius() {\n RADIUS_MIN_VAR = Math.min(bokeh_radiusMin.value, bokeh_radiusMax.value);\n RADIUS_MAX_VAR = Math.max(bokeh_radiusMin.value, bokeh_radiusMax.value);\n radiusMin = (RADIUS_MIN_VAR * Math.min(WIDTH, HEIGHT)) / 256;\n radiusMax = (RADIUS_MAX_VAR * Math.min(WIDTH, HEIGHT)) / 256;\n radiusDepth = radiusMax * DEPTH_VAR;\n main();\n}", "function circleSize(magnitude) {\n return magnitude * 20000;\n}", "function initCircles() {\n CIRCLE_PROPS.forEach((props) => {\n let ele = id(props.id);\n const length = props.radiusPixels * 2.0 + \"px\";\n ele.style.height = length;\n ele.style.width = length;\n ele.style.borderWidth = props.borderWidthPixels + \"px\";\n const parentWidth = id(\"game-frame\").getBoundingClientRect().width;\n const parentHeight = id(\"game-frame\").getBoundingClientRect().height;\n ele.style.left = parentWidth * props.leftInitialPct - STYLE_OFFSET + \"px\";\n ele.style.top = parentHeight * props.topInitialPct - STYLE_OFFSET + \"px\";\n });\n setCircleVisibility(true);\n addDragListeners();\n }", "function circleGrow(){\nxSize = xSize + 30;\nySize = ySize + 30;\n}", "function setCircle(){\n\n initialWidth = parseInt($(\"input[name=width]\").val());\n growthAmount = parseInt($(\"input[name=growth-amount]\").val());\n interval = parseInt($(\"input[name=grow-rate]\").val());\n counter = numberCircles = parseInt($(\"input[name=number-circles]\").val());\n\n console.log(\"setCircle-w:\"+initialWidth);\n console.log(\"setCircle-ga:\"+growthAmount);\n console.log(\"setCircle-gr:\"+interval);\n\n for (let i = 0; i < numberCircles; i++) {\n let circle = $(\"<div>\");\n circle.addClass(\"circle\");\n\n circle.css(\"width\", initialWidth+\"px\");\n circle.css(\"height\", initialWidth+\"px\");\n circle.css(\"border-radius\", initialWidth+\"px\");\n\n circle.on(\"click\", removeCircle);\n circle.on(\"mouseover\", mouseOverCircle);\n circle.on(\"mouseout\", mouseOutCircle);\n $(\"#circle-div\").append(circle);\n circles.push(circle);\n }\n\n timer = window.setInterval(growCircle, interval);\n }", "function setJewelPaletteCircles(){\n setCircle('red', generateJewel(generateRed())); //red\n setCircle('orange', generateJewel(generateOrange())); //orange\n setCircle('yellow', generateJewel(generateYellow())); //yellow\n setCircle('yellowgreen', generateJewel(generateYellowGreen())); //yellowGreen\n setCircle('green', generateJewel(generateGreen())); //green\n setCircle('greencyan', generateJewel(generateGreenCyan())); //greenCyan\n setCircle('cyan', generateJewel(generateCyan())); //cyan\n setCircle('cyanblue', generateJewel(generateCyanBlue())); //cyanBlue\n setCircle('blue', generateJewel(generateBlue())); //blue\n setCircle('bluemagenta', generateJewel(generateBlueMagenta())); //blueMagenta\n setCircle('magenta', generateJewel(generateMagenta())); //magenta\n setCircle('magentared', generateJewel(generateMagentaRed())); //magentaRed\n}", "function circleSize(mag) {\n return mag * 10000;\n}", "function circleSize(magnitude) {\r\n return magnitude ** 2;\r\n}", "function circleShrink(){\nxSize = xSize - 30;\nySize = ySize - 30;\n}", "function computeGeometryOfColorCircles() {\n //Color circles\n let listOfColorCicrcles = document.querySelectorAll('.inner-left-side--main ul > li');\n let colorCicrcles = [];\n for(let i = 0; i < listOfColorCicrcles.length; i++) {\n listOfColorCicrcles[i].style.cssText = ''; \n colorCicrcles.push(listOfColorCicrcles[i]);\n }\n let containerOfCircles = document.querySelector('.inner-left-side--main ul');\n let widthOfContainer = parseInt(containerOfCircles.offsetWidth - 5);\n\n //Define the scale of the screen\n //Laptop\n if(window.innerWidth >= 1280) {\n let space = parseInt(widthOfContainer * 0.06);\n let scaleOfCircles = parseInt((widthOfContainer - space * 7) / 8);\n colorCicrcles.forEach((element, index) => {\n let styleOfElement = element.style;\n styleOfElement.width = scaleOfCircles + 'px';\n styleOfElement.height = scaleOfCircles + 'px';\n styleOfElement.backgroundColor = element.dataset.color;\n if(index != 7 && index != 22 && index != 30 && index != 14) {\n styleOfElement.marginRight = space + 'px';\n }\n if((index >= 8 && index <= 14) || (index >= 23)) {\n styleOfElement.marginTop = parseInt(scaleOfCircles * 0.5) + 'px'\n }\n });\n\n //Ipad\n } else if(window.innerWidth >= 768) {\n let space = parseInt(widthOfContainer * 0.04);\n let scaleOfCircles = parseInt((widthOfContainer - space * 8) / 9);\n colorCicrcles.forEach((element, index) => {\n let styleOfElement = element.style;\n styleOfElement.width = scaleOfCircles + 'px';\n styleOfElement.height = scaleOfCircles + 'px';\n styleOfElement.backgroundColor = element.dataset.color;\n if(index != 8 && index != 23) {\n styleOfElement.marginRight = space + 'px';\n }\n if((index >= 9 && index <= 14) || (index >= 24)) {\n styleOfElement.marginTop = parseInt(scaleOfCircles * 0.5) + 'px'\n }\n });\n\n //Mobile\n } else {\n let space = parseInt(widthOfContainer * 0.04);\n let scaleOfCircles = parseInt((widthOfContainer - space * 8) / 9);\n colorCicrcles.forEach((element, index) => {\n let styleOfElement = element.style;\n styleOfElement.width = scaleOfCircles + 'px';\n styleOfElement.height = scaleOfCircles + 'px';\n styleOfElement.backgroundColor = element.dataset.color;\n if(index != 8 && index != 23) {\n styleOfElement.marginRight = space + 'px';\n }\n if((index >= 9 && index <= 14) || (index >= 24)) {\n styleOfElement.marginTop = parseInt(scaleOfCircles * 0.7) + 'px'\n }\n });\n }\n}", "function range() {\n var p = document.getElementById('resize');\n var res = document.getElementById('radiusVal');\n rad = p.value;\n res.innerHTML=p.value+ \" m\";\n cityCircle.setMap(null);//deletes the origial circle to avoid redraws\n createCityCircle();\n}//range", "function ck(a){this.radius=a}", "function createCircles() {\n \n \tconst dTheta = 0.5*2.43;\n \n \tlet c1 = new OrthoganalCircle(0,dTheta);\n \tlet c2 = new OrthoganalCircle(TWO_PI/3,dTheta);\n \tlet c3 = new OrthoganalCircle(2*TWO_PI/3,dTheta);\n\n \tcircles = [c1,c2,c3]; \n \n}", "function addCircles(num){\r\n\tfor(var i=0; i<num; i++){\r\n\r\n\t\t\tvar c = {};\r\n\t\t\tc.x = getRandom(START_RADIUS*2,CANVAS_WIDTH-START_RADIUS*2);\r\n\t\t\tc.y = getRandom(START_RADIUS*2,CANVAS_HEIGHT-START_RADIUS*2);\r\n\r\n\t\t\tc.radius = START_RADIUS;\r\n\t\t\tc.xSpeed = getRandom(-MAX_SPEED,MAX_SPEED);\r\n\t\t\tc.ySpeed = getRandom(-MAX_SPEED,MAX_SPEED);\r\n\t\t\t// c.xSpeed = MAX_SPEED;\r\n\t\t\t// c.ySpeed = MAX_SPEED;\r\n\t\t\tc.fillStyle=getRandomColor();\r\n\t\t\tcircles.push(c);\r\n\t}\r\n}", "function createSliderRadius() {\n var group = createDiv('');\n group.position(width + 10, height / 2 + 40);\n sliderRadius = createSlider(2, 50, 20, 1);\n sliderRadius.parent(group);\n var label = createSpan('Radius of ball');\n label.parent(group);\n}", "function circleMoreRed(){\n r = r + 40;\n}", "function sizeCircle(magnitude) {\n return magnitude * 4;\n}", "function tc(a){this.radius=a}", "function changeBoxRadius(topLeftRadius,topRightRadius,bottomLeftRadius,bottomRightRadius){\n // coutning radius of each corner,\n box.style.borderTopLeftRadius = topLeftRadius + \"px\"\n box.style.borderTopRightRadius = topRightRadius + \"px\"\n box.style.borderBottomLeftRadius = bottomLeftRadius + \"px\" \n box.style.borderBottomRightRadius = bottomRightRadius + \"px\"\n generateCssCode() // calling function what will generate css code\n}", "function setup() {\n createCanvas(800, 800);\n smooth();\n //noLoop();\n \n n = 1600;\n \n // put bounding circles\n circles.push(new Circ(-10, height/2, 20));\n circles.push(new Circ(width+10, height/2, 20));\n circles.push(new Circ(width/2, -10, 20));\n circles.push(new Circ(width/2, height+10, 20));\n \n //for (var i=0; i<n; i++) {\n //circles.push(new Circ()); \n //}\n}", "function penSize(){\n\t$('#btnIncrease').click(function(){\n\t\tradius = radius + 2;\n\t\tif (radius >= maxRadius) {\n\t\t\tradius = maxRadius;\n\t\t}\n\t\t$('#penVal').text(radius);\n\n\t});\n\n\t$('#btnDecrease').click(function(){\n\t\tradius = radius - 2;\n\t\tif (radius <= minRadius) {\n\t\t\tradius = minRadius;\n\t\t}\n\t\t$('#penVal').text(radius);\n\n\t});\n}", "function circle(x, y, px, py) {\n //this is the speed part making the size be determined by speed of mouse\n var distance = abs(x-px) + abs(y-py);\n stroke(r, g, b);\n strokeWeight(2);\n //first set of variables for bigger circle\n r = random(255);\n g = random(255);\n b = random(255);\n\n//second set of colours so the inner circle is different colour or else it is the same\n r2 = random(255);\n g2 = random(255);\n b2 = random(255);\n //this is the big circle\n fill(r, g, b);\n ellipse(x, y, distance, distance);\n //this is the smaller inner circle\n fill(r2, g2, b2);\n ellipse(x, y, distance/2, distance/2);\n}", "function hk(a){this.radius=a}", "function drawTarget() {\n let circleSize = 400;\n \n //draw circles of decreasing size\n for (let i = 0; i < NUM_CIRC; i++) {\n ellipse(X_POS, Y_POS, circleSize, circleSize);\n circleSize -= 40;\n }\n}", "function addNewCircle() {\n\n // circles can expose in 3 position,\n // bottom-left corner, bottom-right corner and bottom center.\n const entrances = [\"bottomRight\", \"bottomCenter\", \"bottomLeft\"];\n // I take one of entrances randomly as target entrance\n const targetEntrance = entrances[rndNum(entrances.length, 0, true)];\n\n // we have 5 different gradient to give each\n // circle a different appearance. each item\n // in below array has colors and offset of gradient.\n const possibleGradients = [\n [\n [0, \"rgba(238,31,148,0.14)\"],\n [1, \"rgba(238,31,148,0)\"]\n ],\n [\n [0, \"rgba(213,136,1,.2)\"],\n [1, \"rgba(213,136,1,0)\"]\n ],\n [\n [.5, \"rgba(213,136,1,.2)\"],\n [1, \"rgba(213,136,1,0)\"]\n ],\n [\n [.7, \"rgba(255,254,255,0.07)\"],\n [1, \"rgba(255,254,255,0)\"]\n ],\n [\n [.8, \"rgba(255,254,255,0.05)\"],\n [.9, \"rgba(255,254,255,0)\"]\n ]\n ];\n // I take one of gradients details as target gradient details\n const targetGrd = possibleGradients[rndNum(possibleGradients.length, 0, true)];\n\n // each circle should have a radius. and it will be\n // a random number between three and four quarters of canvas-min side\n const radius = rndNum(canvasMin / 3, canvasMin / 4);\n\n // this will push the created Circle to the circles array\n circles.push(new Circle(targetEntrance, radius, targetGrd))\n}", "grow(factor) {\n this.radius = this.radius * factor\n }", "function growCircle() {\n console.log(\"growCircle\");\n let size = parseInt(circles[0].css(\"width\"));\n let newsize = size + growthAmount + \"px\";\n\n for (let i = 0; i < numberCircles; i++) {\n let circle = circles[i];\n circle.css(\"width\", newsize);\n circle.css(\"height\", newsize);\n circle.css(\"border-radius\", newsize);\n }\n }", "function updateCircle(){\n steps.text = today.adjusted.steps;\n cals.text = today.adjusted.calories;\n floors.text = today.adjusted.elevationGain;\n batteryp.text = battery.chargeLevel;\n csteps = today.adjusted.steps;\n ccals = today.adjusted.calories;\n cfloors = today.adjusted.elevationGain;\n if(csteps > goal){\n cone = 360;\n }else{\n cone = (csteps / goalo)*3.6;\n };\n \n if(ccals > goalc){\n ctwo = 360;\n }else{\n ctwo = (ccals / goalt)*3.6;\n };\n \n if(cfloors > goalf){\n cthree = 360;\n }else{\n cthree = (cfloors / goalth)*3.6;\n \n };\n arcSweep.sweepAngle = cone;\n arcSweepC.sweepAngle = ctwo;\n arcSweepF.sweepAngle = cthree;\n arcSweepB.sweepAngle = battery.chargeLevel * 3.6;\n}", "function hc(a){this.radius=a}", "function Hc(a){this.radius=a}", "function oc(a){this.radius=a}", "function ob(a){this.radius=a}", "constructor({colorCode, context, x, y, radius, percentFromCenter}) {\n this.circles = [];\n this.percentFromCenter = percentFromCenter;\n\n if (Math.abs(this.percentFromCenter) < 0.01) {\n this.circles.push(new ColorCircle({\n x: 0,\n y: 0,\n radius: radius,\n colorCode: new ColorCode({\n base: colorCode.getBase(),\n bits: colorCode.getBits(),\n red: colorCode.getComponent('R'),\n green: colorCode.getComponent('G'),\n blue: colorCode.getComponent('B')\n }),\n context\n }));\n }\n else {\n // Add red circle in bottom left position\n this.circles.push(new ColorCircle({\n x: x - radius * MAX_CIRCLE_DIST_MULT * this.percentFromCenter * RT_3_OVER_2,\n y: y - radius * MAX_CIRCLE_DIST_MULT * this.percentFromCenter * ONE_HALF,\n radius: radius,\n colorCode: new ColorCode({\n base: colorCode.getBase(),\n bits: colorCode.getBits(),\n red: colorCode.getComponent('R'),\n green: 0,\n blue: 0,\n }),\n context\n }));\n // Add green circle in top position\n this.circles.push(new ColorCircle({\n x: x,\n y: y + radius * MAX_CIRCLE_DIST_MULT * this.percentFromCenter,\n radius: radius,\n colorCode: new ColorCode({\n base: colorCode.getBase(),\n bits: colorCode.getBits(),\n red: 0,\n green: colorCode.getComponent('G'),\n blue: 0,\n }),\n context\n }));\n // Add blue circle in bottom right position\n this.circles.push(new ColorCircle({\n x: x + radius * MAX_CIRCLE_DIST_MULT * this.percentFromCenter * RT_3_OVER_2,\n y: y - radius * MAX_CIRCLE_DIST_MULT * this.percentFromCenter * ONE_HALF,\n radius: radius,\n colorCode: new ColorCode({\n base: colorCode.getBase(),\n bits: colorCode.getBits(),\n red: 0,\n green: 0,\n blue: colorCode.getComponent('B'),\n }),\n context\n }));\n }\n }", "_createRandomCircles2(options) {\n let { n, filled, stroke, colours, minRadius, maxRadius, acceleration, friction, dx, dy } = options;\n minRadius = minRadius ? minRadius : this.MIN_RADIUS;\n maxRadius = maxRadius ? maxRadius : this.MAX_RADIUS;\n dx = dx === undefined ? 2 : dx;\n dy = dy === undefined ? 10 : dy;\n\n for (let i = 0; i < n; i++) {\n const radius = randomIntFromRange(minRadius, maxRadius);\n const x = randomIntFromRange(radius, this.canvas.width - radius);\n const y = randomIntFromRange(0, this.canvas.height / 2);\n const colour = randomColour(colours);\n const dx_ = randomIntFromRange(-dx, dx);\n const dy_ = randomIntFromRange(-dy, dy);\n this.makeCircle({ x, y, dx: dx_, dy: dy_, colour, radius, filled, gravity: true, acceleration, friction, stroke })\n }\n\n }", "function setPastelPaletteCircles(){\n setCircle('red', generatePastel(generateRed())); //red\n setCircle('orange', generatePastel(generateOrange())); //orange\n setCircle('yellow', generatePastel(generateYellow())); //yellow\n setCircle('yellowgreen', generatePastel(generateYellowGreen())); //yellowGreen\n setCircle('green', generatePastel(generateGreen())); //green\n setCircle('greencyan', generatePastel(generateGreenCyan())); //greenCyan\n setCircle('cyan', generatePastel(generateCyan())); //cyan\n setCircle('cyanblue', generatePastel(generateCyanBlue())); //cyanBlue\n setCircle('blue', generatePastel(generateBlue())); //blue\n setCircle('bluemagenta', generatePastel(generateBlueMagenta())); //blueMagenta\n setCircle('magenta', generatePastel(generateMagenta())); //magenta\n setCircle('magentared', generatePastel(generateMagentaRed())); //magentaRed\n}", "function cdGet(){\n if(width<=530){\n circRadius=5;\n }\n else{\n circRadius=10;\n }\n}", "function resizeCircles(girlsLayer, boysLayer, currentGrade) {\n\n girlsLayer.eachLayer(function (layer) {\n var radius = calcRadius(Number(layer.feature.properties['G' + currentGrade]));\n layer.setRadius(radius);\n });\n\n boysLayer.eachLayer(function (layer) {\n var radius = calcRadius(Number(layer.feature.properties['B' + currentGrade]));\n layer.setRadius(radius);\n });\n\n retrieveInfo(boysLayer, currentGrade);\n }", "function setRadius(a) { \n return\ta > 801 ? 15 : \n\t\t\t\t\ta > 601 ? 12 : \n\t\t\t\t\ta > 401 ? 9 : \n\t\t\t\t\ta > 201 ? 6 : \n\t\t\t \t\t\t\t\t\t3 ; \n}", "function re(b){this.radius=b}", "setRadius(r){\n\t\tthis.radius= r;\n\t}", "function updateSize() {\n innerRadius = innerRadiusArg * canvas.width / 2;\n outerRadius = outerRadiusArg * canvas.width / 2;\n \n centerX = centerXArg * canvas.width;\n centerY = centerYArg * canvas.height;\n }", "function setCreamPaletteCircles(){\n setCircle('red', generateCream(generateRed())); //red\n setCircle('orange', generateCream(generateOrange())); //orange\n setCircle('yellow', generateCream(generateYellow())); //yellow\n setCircle('yellowgreen', generateCream(generateYellowGreen())); //yellowGreen\n setCircle('green', generateCream(generateGreen())); //green\n setCircle('greencyan', generateCream(generateGreenCyan())); //greenCyan\n setCircle('cyan', generateCream(generateCyan())); //cyan\n setCircle('cyanblue', generateCream(generateCyanBlue())); //cyanBlue\n setCircle('blue', generateCream(generateBlue())); //blue\n setCircle('bluemagenta', generateCream(generateBlueMagenta())); //blueMagenta\n setCircle('magenta', generateCream(generateMagenta())); //magenta\n setCircle('magentared', generateCream(generateMagentaRed())); //magentaRed\n}", "function ub(a){this.radius=a}", "function ub(a){this.radius=a}", "function Circles(x, y, size)\r\n{\r\n this.x = x;\r\n this.y = y;\r\n this.size = size;\r\n this.shape = 'circle';\r\n}", "function createCircles(number){\n //Generate number of circles told\n for (let i = 0; i < number; i++){\n let x = 0;\n let y = 0;\n \n switch(Math.floor(getRandom(0,4))){\n //left side of screen\n case 0:\n x = -10;\n y = Math.floor(getRandom(5,710));\n break;\n //right side of screen\n case 1:\n x = 1290;\n y = Math.floor(getRandom(5,710));\n break;\n //top of screen\n case 2:\n y = -10;\n x = Math.floor(getRandom(5,1270));\n break;\n //bottom of screen\n case 3:\n y = 730;\n x = Math.floor(getRandom(5,1270));\n break;\n }\n\n let circle = new Circle(Math.floor(getRandom(20,60)),0x0000FF,x,y,Math.floor(getRandom(20,80)),time);\n circles.push(circle);\n gameScene.addChild(circle);\n }\n}", "function pokemonHeight(){\n if (heights <=4) {circleheight = 200}\n if (heights >4) {circleheight = 220}\n if (heights >6) {circleheight = 240}\n if (heights >8) {circleheight = 260}\n if (heights >10) {circleheight = 280}\n if (heights >12) {circleheight = 300}\n if (heights >14) {circleheight = 320}\n if (heights >16) {circleheight = 340}\n if (heights >18) {circleheight = 360}\n}", "set diameter(d) {\n this.radius = d / 2;\n }", "function ve(b){this.radius=b}", "function circleMoreGreen(){\n g = g + 40;\n}", "constructor(radius){\r\n this.radius = radius; //radius of circle of Tiles to render from the Scene\r\n this.offsets = []; //list of coordinate offsets used to determine what to render\r\n this.ui = []; //list of UI elements\r\n\r\n //x = sqrt(r^2 - y^2)\r\n //generate list of offsets\r\n //\r\n //iterate from top to bottom of circle\r\n //for each iteration, calculate x axis boundaries using above formula\r\n //iterate from left to right and add each coordinate to list\r\n for(var y = -this.radius; y <= this.radius; y++){\r\n let bound = parseInt(Math.sqrt(this.radius * this.radius - y * y + 1));\r\n for(var x = -bound; x <= bound; x++)\r\n this.offsets.push({x: x, y: y});\r\n }\r\n }", "function setCircleRadius(d) {\r\n switch (d.type) {\r\n case \"root\":\r\n return config.rootWidth;\r\n case \"dp\":\r\n return config.dpWidth;\r\n case \"dec\":\r\n return d.predetermined ? config.decWidth - 1 : config.decWidth;\r\n case \"out\":\r\n return d.highlighted ? config.outWidth - 1 : config.outWidth;\r\n }\r\n }", "function makeCircle() {\n \"use strict\";\n var radius = 380,\n fields = $('.smallSquares'),\n container = $('#fullCircleStuff'),\n width = container.width(),\n height = container.height(),\n angle = 180,\n step = (2 * Math.PI) / fields.length;\n fields.each(function () {\n var x = Math.round(width / 2 + radius * Math.cos(angle) - $(this).width() / 2),\n y = Math.round(height / 2 + radius * Math.sin(angle) - $(this).height() / 2);\n// used to log out the x, y coordinates to the console for testing.\n// if (window.console) {\n// console.log($(this).text(), x, y);\n// }\n $(this).css({\n left: x + 'px',\n top: y + 'px'\n });\n angle += step;\n });\n}", "function te(b){this.radius=b}", "function init() {\n\n circles = []; // make sure everytime the window is resized, the previous circles are cleared away;\n\n for (let i = 0; i < 400; i++) {\n let radius = Math.random() * 3 + 1; //randomize the initial size of the circle\n let x = Math.random() * (innerWidth - radius * 2) + radius; //give a random x start position, also prevent circles being caught at the corner\n let y = Math.random() * (innerHeight - radius * 2) + radius; //give a random y start position, also prevent circles being caught at the corner\n\n let dx = (Math.random() - 0.5) * 3; // the varibale for moving distance horizontally, randomized - speed\n let dy = (Math.random() - 0.5) * 3; // the varibale for moving distance vertically, randomized - speed\n circles.push(new Circle(x, y, dx, dy, radius))\n } //creating many circles\n}", "function Vc(a){this.radius=a}", "update(){\n\n //if the size is either too small, or too big, flip the size speed sign (if it was positive (growing) - make it negative (shrink) - and vice versa)\n if(this.radius < this.minRadius || this.radius > this.maxRadius) {\n this.radiusSpeed *= -1;\n }\n //increment the size with the size speed (be it positive or negative)\n this.radius += this.radiusSpeed;\n }", "function cannonHeightChange(scope) {\n cannon_height = scope.cannon_height;\n calculation(scope); /** Value calculation function */\n var height_box_tween = createjs.Tween.get(getChild(\"height_box\")).to({\n scaleY: (-0.1 - cannon_height / 40)\n }, 500); /** Height box y scaling using tween */\n var height_box_top_tween = createjs.Tween.get(getChild(\"height_box_top\")).to({\n y: (height_box_top_initial_y - (cannon_height * 3.2))\n }, 500); /** Height box top part y scaling using tween */\n var wheel_behind_tween = createjs.Tween.get(getChild(\"wheel_behind\")).to({\n y: (wheel_initial_y - (cannon_height * 3.2))\n }, 500); /** Behind wheel y scaling using tween */\n var wheel_front_tween = createjs.Tween.get(getChild(\"wheel_front\")).to({\n y: (wheel_initial_y - (cannon_height * 3.2))\n }, 500); /** Front wheel y scaling using tween */\n var bullet_tween = createjs.Tween.get(getChild(\"bullet\")).to({\n y: (bullet_initial_y - (cannon_height * 3.2))\n }, 500); /** Bullet y scaling using tween */\n var bullet_case_tween = createjs.Tween.get(getChild(\"bullet_case\")).to({\n y: (bullet_case_initial_y - (cannon_height * 3.2))\n }, 500); /** Bullet case y scaling tween */\n\tvar wheel_front_tween = createjs.Tween.get(getChild(\"wheel_separate\")).to({\n y: (wheel_initial_y - (cannon_height * 3.2))\n }, 500); /** Front wheel y scaling using tween */\n\t var bullet_case_tween = createjs.Tween.get(getChild(\"case_separate\")).to({\n y: (bullet_case_initial_y - (cannon_height * 3.2))\n }, 500); /** Bullet case y scaling tween */\n\t\t\t\t\n bullet_moving_x = getChild(\"bullet\").x; /** Initial x position of bullet in a variable */\n bullet_moving_y = getChild(\"bullet\").y; /** Initial y position of bullet in a variable */\n bullet_start_x = bullet_moving_x; /** Bullet x and y position changed in this function. So the startx and starty is changed */\n bullet_start_y = getChild(\"bullet\").y; \n scope.erase_disable = true; /** Disable the erase button */\n}", "constructor(radius) {\n super(2 * radius, 2 * radius);\n this.shape = \"circle\"; //set shape property\n this.radius = radius; //set radius\n //sets size and position\n let circle = `<div class='shape circle' id='${counter}' style=\"height:${\n this.height\n }px; width:${this.width}px; left:${randomPosition(\n this.width\n )}px; top:${randomPosition(this.height)}px\"></div>`;\n $(\"#board\").append(circle);\n }", "function setRadiusAndForceForCurrentData(){\n\t\t\t\t\tif(nodes.length <= 19){\n\t\t\t\t\t\tselectedRadius = circleRadius.big;\n\t\t\t\t\t\tselectedForce = -600;\n\t\t\t\t\t} else if(nodes.length >= 20 && nodes.length <= 39){\n\t\t\t\t\t\tselectedRadius = circleRadius.medium;\n\t\t\t\t\t\tselectedForce = -375;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tselectedRadius = circleRadius.small;\n\t\t\t\t\t\tselectedForce = -220;\n\t\t\t\t\t}\n\t\t\t\t}", "function planets()\n{\n with (Math) {\n\n var RAD = 180 / PI;\n\n document.planets.size6.value = \"\";\n document.planets.size7.value = \"\";\n document.planets.phase7.value = \"\";\n document.planets.phase6.value = \"\";\n document.planets.dawn.value = \"\";\n document.planets.dusk.value = \"\";\n document.planets.tr0.value = \"...\";\n document.planets.tr1.value = \"...\";\n document.planets.tr2.value = \"...\";\n document.planets.tr3.value = \"...\";\n document.planets.tr4.value = \"...\";\n document.planets.tr5.value = \"...\";\n document.planets.tr6.value = \"...\";\n\n var planet_dec = new Array(9);\n var planet_ra = new Array(9);\n var planet_dist = new Array(9);\n var planet_phase = new Array(9);\n var planet_size = new Array(9);\n var planet_alt = new Array(9);\n var planet_az = new Array(9);\n\n var ang_at_1au = [1,6.68,16.82,9.36,196.94,166.6];\n\n var planet_a = new Array(5);\n var planet_l = new Array(5);\n var planet_i = new Array(5);\n var planet_e = new Array(5);\n var planet_n = new Array(5);\n var planet_m = new Array(5);\n var planet_r = new Array(5);\n\n var jd, t, l, m, e, c, sl, r, R, Rm, u, p, q, v, z, a, b, ee, oe, t0, gt;\n var g0, x, y, i, indx, count, hl, ha, eg, et, dr, en, de, ra, la, lo, height;\n var az, al, size, il, dist, rho_sin_lat, rho_cos_lat, rise_str, set_str;\n var dawn, dusk, gt_dawn, gt_dusk, dawn_planets, dusk_planets, morn, eve;\n var sunrise_set, moonrise_set, twilight_begin_end, twilight_start, twilight_end;\n var sat_lat, phase_angle, dt_as_str, tm_as_str, ut_hrs, ut_mns, part_day, dt;\n var moon_days, Days, age, N, M_sun, Ec, lambdasun, P0, N0, rise, set, tr, h0;\n var i_m, e_m, l_m, M_m, N_m, Ev, Ae, A3, A4, lambda_moon, beta_moon, phase;\n var transit, lambda_transit, beta_transit, ra_transit;\n var ra_np, d_beta, d_lambda, lambda_moon_D, beta_moon_D, yy;\n\n la = latitude / RAD;\n lo = longitude / RAD;\n height = 10.0;\n\n tm_as_str = document.planets.ut_h_m.value;\n ut_hrs = eval(tm_as_str.substring(0,2));\n ut_mns = eval(tm_as_str.substring(3,5));\n dt_as_str = document.planets.date_txt.value;\n yy = eval(dt_as_str.substring(6,10));\n\n\n part_day = ut_hrs / 24.0 + ut_mns / 1440.0;\n\n jd = julian_date() + part_day;\n\n document.planets.phase8.value = round_1000(jd);\n\n y = floor(yy / 50 + 0.5) * 50;\n if (y == 1600) dt = 2;\n if (y == 1650) dt = 0.8;\n if (y == 1700) dt = 0.1;\n if (y == 1750) dt = 0.2;\n if (y == 1800) dt = 0.2;\n if (y == 1850) dt = 0.1;\n if (y == 1900) dt = 0;\n if (y == 1950) dt = 0.5;\n if (y == 2000) dt = 1.1;\n if (y == 2050) dt = 3;\n if (y == 2100) dt = 5;\n if (y == 2150) dt = 6;\n if (y == 2200) dt = 8;\n if (y == 2250) dt = 11;\n if (y == 2300) dt = 13;\n if (y == 2350) dt = 16;\n if (y == 2400) dt = 19;\n dt = dt / 1440;\n\n jd += dt;\n\n zone_date_time();\n\n moon_facts();\n\n t=(jd-2415020.0)/36525;\n oe=.409319747-2.271109689e-4*t-2.8623e-8*pow(t,2)+8.779e-9*pow(t,3);\n t0=(julian_date()-2415020.0)/36525;\n g0=.276919398+100.0021359*t0+1.075e-6*pow(t0,2);\n g0=(g0-floor(g0))*2*PI;\n gt=proper_ang_rad(g0+part_day*6.30038808);\n\n l=proper_ang_rad(4.88162797+628.331951*t+5.27962099e-6*pow(t,2));\n m=proper_ang_rad(6.2565835+628.3019457*t-2.617993878e-6*pow(t,2)-5.759586531e-8*pow(t,3));\n e=.01675104-4.18e-5*t-1.26e-7*pow(t,2);\n c=proper_ang_rad(3.3500896e-2-8.358382e-5*t-2.44e-7*pow(t,2))*sin(m)+(3.50706e-4-1.7e-6*t)*sin(2*m)+5.1138e-6*sin(3*m);\n sl=proper_ang_rad(l+c);\n R=1.0000002*(1-pow(e,2))/(1+e*cos(m+c));\n\n de = asin(sin(oe) * sin(sl));\n y = sin(sl) * cos(oe);\n x = cos(sl);\n ra = proper_ang_rad(atan2(y,x));\n dist = R;\n size = 31.9877 / dist;\n\n ha=proper_ang_rad(gt-lo-ra);\n al=asin(sin(la)*sin(de)+cos(la)*cos(de)*cos(ha));\n az=acos((sin(de)-sin(la)*sin(al))/(cos(la)*cos(al)));\n if (sin(ha)>=0) az=2*PI-az;\n\n planet_decl[0] = de;\n planet_r_a[0] = ra;\n planet_mag[0] = -26.7;\n\n planet_dec[8] = \"\";\n planet_ra[8] = \"\";\n planet_dist[8] = \"\";\n planet_size[8] = \"\";\n planet_alt[8] = \"\";\n planet_az[8] = \"\";\n\n y = sin(-0.8333/RAD) - sin(la) * sin(de);\n x = cos(la) * cos(de);\n if (y/x >= 1)\n {\n //rise_str = \"No rise\";\n //set_str = \"No rise\";\n h0 = 0;\n }\n if (y/x <= -1)\n {\n //rise_str = \"No set\";\n //set_str = \"No set\";\n h0 = 0;\n }\n if (abs(y/x) < 1)\n {\n h0 = acos(y/x) * RAD;\n tr = range_1((ra * RAD + lo * RAD - g0 * RAD) / 360);\n document.planets.tr0.value = am_pm(range_1(tr + zone / 24 - dt) * 24);\n document.planets.tr0_2.value = am_pm(range_1(tr + zone / 24 - dt) * 24);\n\n\n }\n y = sin(-18/RAD) - sin(la) * sin(de);\n x = cos(la) * cos(de);\n if (y/x >= 1)\n {\n twilight_start = \"No twilight\";\n twilight_end = \"No twilight\";\n h0 = 0;\n }\n if (y/x <= -1)\n {\n twilight_start = \"All night\";\n twilight_end = \"All night\";\n h0 = 0;\n }\n if (abs(y/x) < 1)\n {\n h0 = acos(y/x) * RAD;\n tr = range_1((ra * RAD + lo * RAD - g0 * RAD) / 360);\n twilight_start = am_pm(range_1(tr - h0 / 360 + zone / 24 - dt) * 24);\n twilight_end = am_pm(range_1(tr + h0 / 360 + zone / 24 - dt) * 24);\n }\n\n al = al * RAD;\n az = az * RAD;\n if (al >= 0)\n {\n al += 1.2 / (al + 2);\n }\n else\n {\n al += 1.2 / (abs(al) + 2);\n }\n\n planet_altitude[0] = al;\n planet_azimuth[0] = az;\n\n de = de * RAD;\n ra = ra * RAD / 15;\n\n x = round_10(abs(de));\n if (de < 0)\n {\n planet_dec[8] += \"-\";\n }\n else\n {\n planet_dec[8] += \"+\";\n }\n if (x < 10) planet_dec[8] += \"0\";\n planet_dec[8] += x;\n if (x == floor(x)) planet_dec[8] += \".0\";\n planet_dec[8] += \"\\u00B0\";\n\n x = floor(ra);\n y = floor((ra - x) * 60 + 0.5);\n if (y == 60)\n {\n x += 1;\n y = 0;\n }\n if (x < 10) planet_ra[8] += \"0\";\n planet_ra[8] += x + \"h \";\n if (y < 10) planet_ra[8] += \"0\";\n planet_ra[8] += y + \"m\";\n\n dist = round_100(dist);\n if (dist < 10)\n planet_dist[8] += \"0\";\n planet_dist[8] += dist;\n\n size = round_10(size);\n planet_size[8] += size;\n if (size == floor(size)) planet_size[8] += \".0\";\n planet_size[8] += \"\\'\";\n\n sunrise_set = sun_rise_set(la,lo,zone);\n rise_str = sunrise_set.substring(0,8);\n set_str = sunrise_set.substring(11,19);\n planet_alt[8] = rise_str;\n planet_az[8] = set_str;\n\n /*\n planet_alt[8] = rise_str;\n planet_az[8] = set_str;\n sunrise_set = rise_str + \" / \" + set_str;\n */\n\n moon_days = 29.53058868;\n Days = jd - 2444238.5;\n N = proper_ang(Days / 1.01456167);\n M_sun = proper_ang(N - 3.762863);\n Ec = 1.91574168 * sin(M_sun / RAD);\n lambdasun = proper_ang(N + Ec + 278.83354);\n l0 = 64.975464;\n P0 = 349.383063;\n N0 = 151.950429;\n i_m = 5.145396;\n e_m = 0.0549;\n l_m = proper_ang(13.1763966 * Days + l0);\n M_m = proper_ang(l_m - 0.111404 * Days - P0);\n N_m = proper_ang(N0 - 0.0529539 * Days);\n Ev = 1.2739 * sin((2 * (l_m - lambdasun) - M_m) / RAD);\n Ae = 0.1858 * sin(M_sun / RAD);\n A3 = 0.37 * sin(M_sun / RAD);\n M_m += Ev - Ae - A3;\n Ec = 6.2886 * sin(M_m / RAD);\n dist = hundred_miles(238855.7 * (1 - pow(e_m,2)) / (1 + e_m * cos((M_m + Ec) / RAD)));\n A4 = 0.214 * sin(2 * M_m / RAD);\n l_m += Ev + Ec - Ae + A4;\n l_m += 0.6583 * sin(2 * (l_m - lambdasun) / RAD);\n N_m -= 0.16 * sin(M_sun / RAD);\n\n y = sin((l_m - N_m) / RAD) * cos(i_m / RAD);\n x = cos((l_m - N_m) / RAD);\n lambda_moon = proper_ang_rad(atan2(y,x) + N_m / RAD);\n beta_moon = asin(sin((l_m - N_m) / RAD) * sin(i_m / RAD));\n d_beta = 8.727e-4 * cos((l_m - N_m) / RAD);\n d_lambda = 9.599e-3 + 1.047e-3 * cos(M_m / RAD);\n\n de = asin(sin(beta_moon) * cos(oe) + cos(beta_moon) * sin(oe) * sin(lambda_moon));\n y = sin(lambda_moon) * cos(oe) - tan(beta_moon) * sin(oe);\n x = cos(lambda_moon);\n ra = proper_ang_rad(atan2(y,x));\n\n ra_np = ra;\n\n size = 2160 / dist * RAD * 60;\n\n x = proper_ang(l_m - lambdasun);\n phase = 50.0 * (1.0 - cos(x / RAD));\n\n age = jd - new_moon;\n if (age > moon_days) age -= moon_days;\n if (age < 0) age += moon_days;\n\n /*\n age = (x / 360 * moon_days);\n */\n Rm = R - dist * cos(x / RAD) / 92955800;\n phase_angle = acos((pow(Rm,2) + pow((dist/92955800),2) - pow(R,2)) / (2 * Rm * dist/92955800)) * RAD / 100;\n planet_mag[6] = round_10(0.21 + 5 * log(Rm * dist / 92955800)/log(10) + 3.05 * (phase_angle) - 1.02 * pow(phase_angle,2) + 1.05 * pow(phase_angle,3));\n if (planet_mag[6] == floor(planet_mag[6])) planet_mag[6] += \".0\";\n\n /*\n thisImage = floor(age / moon_days * 28);\n */\n\n thisImage = floor(age / moon_days * 27 + 0.5);\n document.myPicture.src = myImage[thisImage];\n age = round_10(age);\n\n x = atan(0.996647 * tan(la));\n rho_sin_lat = 0.996647 * sin(x) + height * sin(la) / 6378140;\n rho_cos_lat = cos(x) + height * cos(la) / 6378140;\n r = dist / 3963.2;\n ha = proper_ang_rad(gt - lo - ra);\n x = atan(rho_cos_lat * sin(ha) / (r * cos(de) - rho_cos_lat * cos(ha)));\n ra -= x;\n y = ha;\n ha += x;\n de = atan(cos(ha) * (r * sin(de) - rho_sin_lat) / (r * cos(de) * cos(y) - rho_cos_lat));\n ha = proper_ang_rad(gt - lo - ra);\n al = asin(sin(de) * sin(la) + cos(de) * cos(la) * cos(ha));\n az = acos((sin(de) - sin(la) * sin(al)) / (cos(la) * cos(al)));\n if (sin(ha) >= 0) az = 2 * PI - az;\n\n planet_decl[6] = de;\n planet_r_a[6] = ra;\n\n planet_dec[9] = \"\";\n planet_ra[9] = \"\";\n planet_dist[9] = \"\";\n planet_dist[6] = \"\";\n planet_phase[9] = \"\";\n planet_size[9] = \"\";\n planet_alt[9] = \"\";\n planet_az[9] = \"\";\n\n lambda_moon_D = lambda_moon - d_lambda * part_day * 24;\n beta_moon_D = beta_moon - d_beta * part_day * 24;\n\n tr = range_1((ra_np * RAD + lo * RAD - g0 * RAD) / 360);\n transit = tr * 24;\n lambda_transit = lambda_moon_D + transit * d_lambda;\n beta_transit = beta_moon_D + transit * d_beta;\n\n y = sin(lambda_transit) * cos(oe) - tan(beta_transit) * sin(oe);\n x = cos(lambda_transit);\n ra_transit = proper_ang_rad(atan2(y,x));\n tr = range_1((ra_transit * RAD + lo * RAD - g0 * RAD) / 360);\n document.planets.tr6.value = am_pm(range_1(tr + zone / 24 - dt) * 24);\n document.planets.tr6_2.value = am_pm(range_1(tr + zone / 24 - dt) * 24);\n\n\n al = al * RAD;\n az = az * RAD;\n if (al >= 0)\n {\n al += 1.2 / (al + 2);\n }\n else\n {\n al += 1.2 / (abs(al) + 2);\n }\n\n planet_altitude[6] = al;\n planet_azimuth[6] = az;\n\n de = de * RAD;\n ra = ra * RAD / 15;\n\n x = round_10(abs(de));\n if (de < 0)\n {\n planet_dec[9] += \"-\";\n }\n else\n {\n planet_dec[9] += \"+\";\n }\n if (x < 10) planet_dec[9] += \"0\";\n planet_dec[9] += x;\n if (x == floor(x)) planet_dec[9] += \".0\";\n planet_dec[9] += \"\\u00B0\";\n\n x = floor(ra);\n y = floor((ra - x) * 60 + 0.5);\n if (y == 60)\n {\n x += 1;\n y = 0;\n }\n if (x < 10) planet_ra[9] += \"0\";\n planet_ra[9] += x + \"h \";\n if (y < 10) planet_ra[9] += \"0\";\n planet_ra[9] += y + \"m\";\n\n if (age < 10)\n planet_dist[6] += \"0\";\n planet_dist[6] += age;\n if (age == floor(age)) planet_dist[6] += \".0\";\n planet_dist[6] += \" days\";\n\n planet_dist[9] += dist;\n\n size = round_10(size);\n planet_size[9] += size;\n if (size == floor(size)) planet_size[9] += \".0\";\n planet_size[9] += \"\\'\";\n\n phase = floor(phase + 0.5);\n planet_phase[9] += phase + \"%\";\n\n moonrise_set = moon_rise_set(la,lo,zone);\n rise_str = moonrise_set.substring(0,8);\n set_str = moonrise_set.substring(11,19);\n planet_alt[9] = rise_str;\n planet_az[9] = set_str;\n\n\n if (twilight_start == \"All night\")\n {\n twilight_begin_end = \"twilight all night\";\n }\n else if (twilight_start == \"No twilight\")\n {\n twilight_begin_end = \"Sky dark for 24h\";\n }\n else\n {\n twilight_begin_end = twilight_start + \" / \" + twilight_end;\n }\n\n u=t/5+.1;\n p=proper_ang_rad(4.14473024+52.96910393*t);\n q=proper_ang_rad(4.64111846+21.32991139*t);\n\n v=5*q-2*p;\n z=proper_ang_rad(q-p);\n if (v >= 0)\n {\n v=proper_ang_rad(v);\n }\n else\n {\n v=proper_ang_rad(abs(v))+2*PI;\n }\n\n planet_a[1]=0.3870986;\n planet_l[1]=proper_ang_rad(3.109811569+2608.814681*t+5.2552e-6*pow(t,2));\n planet_e[1]=.20561421+2.046e-5*t-3e-8*pow(t,2);\n planet_i[1]=.12222333+3.247708672e-5*t-3.194e-7*pow(t,2);\n planet_n[1]=.822851951+.020685787*t+3.035127569e-6*pow(t,2);\n planet_m[1]=proper_ang_rad(1.785111938+2608.787533*t+1.22e-7*pow(t,2));\n planet_a[2]=0.7233316;\n planet_l[2]=proper_ang_rad(5.982413642+1021.352924*t+5.4053e-6*pow(t,2));\n planet_e[2]=.00682069-4.774e-5*t+9.1e-8*pow(t,2);\n planet_i[2]=.059230034+1.75545e-5*t-1.7e-8*pow(t,2);\n planet_n[2]=1.322604346+.0157053*t+7.15585e-6*pow(t,2);\n planet_m[2]=proper_ang_rad(3.710626189+1021.328349*t+2.2445e-5*pow(t,2));\n planet_a[3]=1.5236883;\n planet_l[3]=proper_ang_rad(5.126683614+334.0856111*t+5.422738e-6*pow(t,2));\n planet_e[3]=.0933129+9.2064e-5*t-7.7e-8*pow(t,2);\n planet_i[3]=.032294403-1.178097e-5*t+2.199e-7*pow(t,2);\n planet_n[3]=.851484043+.013456343*t-2.44e-8*pow(t,2)-9.3026e-8*pow(t,3);\n planet_m[3]=proper_ang_rad(5.576660841+334.0534837*t+3.159e-6*pow(t,2));\n planet_l[4]=proper_ang_rad(4.154743317+52.99346674*t+5.841617e-6*pow(t,2)-2.8798e-8*pow(t,3));\n a=.0058*sin(v)-1.1e-3*u*cos(v)+3.2e-4*sin(2*z)-5.8e-4*cos(z)*sin(q)-6.2e-4*sin(z)*cos(q)+2.4e-4*sin(z);\n b=-3.5e-4*cos(v)+5.9e-4*cos(z)*sin(q)+6.6e-4*sin(z)*cos(q);\n ee=3.6e-4*sin(v)-6.8e-4*sin(z)*sin(q);\n planet_e[4]=.04833475+1.6418e-4*t-4.676e-7*pow(t,2)-1.7e-9*pow(t,3);\n planet_a[4]=5.202561+7e-4*cos(2*z);\n planet_i[4]=.022841752-9.941569952e-5*t+6.806784083e-8*pow(t,2);\n planet_n[4]=1.735614994+.017637075*t+6.147398691e-6*pow(t,2)-1.485275193e-7*pow(t,3);\n planet_m[4]=proper_ang_rad(3.932721257+52.96536753*t-1.26012772e-5*pow(t,2));\n planet_m[4]=proper_ang_rad(planet_m[4]+a-b/planet_e[4]);\n planet_l[4]=proper_ang_rad(planet_l[4]+a);\n planet_e[4]=planet_e[4]+ee;\n\n planet_a[5]=9.554747;\n planet_l[5]=proper_ang_rad(4.652426047+21.35427591*t+5.663593422e-6*pow(t,2)-1.01229e-7*pow(t,3));\n a=-.014*sin(v)+2.8e-3*u*cos(v)-2.6e-3*sin(z)-7.1e-4*sin(2*z)+1.4e-3*cos(z)*sin(q);\n a=a+1.5e-3*sin(z)*cos(q)+4.4e-4*cos(z)*cos(q);\n a=a-2.7e-4*sin(3*z)-2.9e-4*sin(2*z)*sin(q)+2.6e-4*cos(2*z)*sin(q);\n a=a+2.5e-4*cos(2*z)*cos(q);\n b=1.4e-3*sin(v)+7e-4*cos(v)-1.3e-3*sin(z)*sin(q);\n b=b-4.3e-4*sin(2*z)*sin(q)-1.3e-3*cos(q)-2.6e-3*cos(z)*cos(q)+4.7e-4*cos(2*z)*cos(q);\n b=b+1.7e-4*cos(3*z)*cos(q)-2.4e-4*sin(z)*sin(2*q);\n b=b+2.3e-4*cos(2*z)*sin(2*q)-2.3e-4*sin(z)*cos(2*q)+2.1e-4*sin(2*z)*cos(2*q);\n b=b+2.6e-4*cos(z)*cos(2*q)-2.4e-4*cos(2*z)*cos(2*q);\n planet_l[5]=proper_ang_rad(planet_l[5]+a);\n planet_e[5]=.05589232-3.455e-4*t-7.28e-7*pow(t,2)+7.4e-10*pow(t,3);\n planet_i[5]=.043502663-6.839770806e-5*t-2.703515011e-7*pow(t,2)+6.98e-10*pow(t,3);\n planet_n[5]=1.968564089+.015240129*t-2.656042056e-6*pow(t,2)-9.2677e-8*pow(t,3);\n planet_m[5]=proper_ang_rad(3.062463265+21.32009513*t-8.761552845e-6*pow(t,2));\n planet_m[5]=proper_ang_rad(planet_m[5]+a-b/planet_e[5]);\n planet_a[5]=planet_a[5]+.0336*cos(z)-.00308*cos(2*z)+.00293*cos(v);\n planet_e[5]=planet_e[5]+1.4e-3*cos(v)+1.2e-3*sin(q)+2.7e-3*cos(z)*sin(q)-1.3e-3*sin(z)*cos(q);\n\n for (i=1; i<6; i++)\n\n {\n\n e = planet_m[i];\n for (count = 1; count <= 50; count++)\n {\n de = e - planet_e[i] * sin(e) - planet_m[i];\n if (abs(de) <= 5e-8) break;\n e = e - de / (1 - planet_e[i] * cos(e));\n }\n v=2*atan(sqrt((1+planet_e[i])/(1-planet_e[i]))*tan(e/2));\n planet_r[i]=planet_a[i]*(1-planet_e[i]*cos(e));\n u=proper_ang_rad(planet_l[i]+v-planet_m[i]-planet_n[i]);\n x=cos(planet_i[i])*sin(u);\n y=cos(u);\n y=acos(y/sqrt(pow(x,2)+pow(y,2)));\n if (x<0) y=2*PI-y;\n\n hl=proper_ang_rad(y+planet_n[i]);\n ha=asin(sin(u)*sin(planet_i[i]));\n x=planet_r[i]*cos(ha)*sin(proper_ang_rad(hl-sl));\n y=planet_r[i]*cos(ha)*cos(proper_ang_rad(hl-sl))+R;\n y=acos(y/sqrt(pow(x,2)+pow(y,2)));\n if (x<0) y=2*PI-y;\n\n eg=proper_ang_rad(y+sl);\n dr=sqrt(pow(R,2)+pow(planet_r[i],2)+2*planet_r[i]*R*cos(ha)*cos(proper_ang_rad(hl-sl)));\n size=ang_at_1au[i]/dr;\n il=floor((pow((planet_r[i]+dr),2)-pow(R,2))/(4*planet_r[i]*dr)*100+.5);\n phase_angle=acos((pow(planet_r[i],2)+pow(dr,2)-pow(R,2))/(2*planet_r[i]*dr))*RAD;\n et=asin(planet_r[i]/dr*sin(ha));\n en=acos(cos(et)*cos(proper_ang_rad(eg-sl)));\n de=asin(sin(et)*cos(oe)+cos(et)*sin(oe)*sin(eg));\n y=cos(eg);\n x=sin(eg)*cos(oe)-tan(et)*sin(oe);\n y=acos(y/sqrt(pow(x,2)+pow(y,2)));\n if (x<0) y=2*PI-y;\n\n ra=y;\n ha=proper_ang_rad(gt-lo-ra);\n al=asin(sin(la)*sin(de)+cos(la)*cos(de)*cos(ha));\n az=acos((sin(de)-sin(la)*sin(al))/(cos(la)*cos(al)));\n if (sin(ha)>=0) az=2*PI-az;\n\n planet_decl[i] = de;\n planet_r_a[i] = ra;\n\n planet_mag[i]=5*log(planet_r[i]*dr)/log(10);\n if (i == 1) planet_mag[i] = -0.42 + planet_mag[i] + 0.038*phase_angle - 0.000273*pow(phase_angle,2) + 0.000002*pow(phase_angle,3);\n if (i == 2) planet_mag[i] = -4.4 + planet_mag[i] + 0.0009*phase_angle + 0.000239*pow(phase_angle,2) - 0.00000065*pow(phase_angle,3);\n if (i == 3) planet_mag[i] = -1.52 + planet_mag[i] + 0.016*phase_angle;\n if (i == 4) planet_mag[i] = -9.4 + planet_mag[i] + 0.005*phase_angle;\n if (i == 5)\n {\n sat_lat = asin(0.47063*cos(et)*sin(eg-2.9585)-0.88233*sin(et));\n planet_mag[i] = -8.88 + planet_mag[i] + 0.044*phase_angle - 2.6*sin(abs(sat_lat)) + 1.25*pow(sin(sat_lat),2);\n }\n planet_mag[i] = round_10(planet_mag[i]);\n if (planet_mag[i] == floor(planet_mag[i])) planet_mag[i] += \".0\";\n if (planet_mag[i] >= 0) planet_mag[i] = \"+\" + planet_mag[i];\n\n planet_dec[i] = \"\";\n planet_ra[i] = \"\";\n planet_dist[i] = \"\";\n planet_size[i] = \"\";\n planet_phase[i] = \"\";\n planet_alt[i] = \"\";\n planet_az[i] = \"\";\n\n y = sin(-0.5667/RAD) - sin(la) * sin(de);\n x = cos(la) * cos(de);\n if (y/x >= 1)\n {\n rise_str = \"No rise\";\n set_str = \"No rise\";\n h0 = 0;\n }\n if (y/x <= -1)\n {\n rise_str = \"No set\";\n set_str = \"No set\";\n h0 = 0;\n }\n if (abs(y/x) < 1)\n {\n h0 = acos(y/x) * RAD;\n tr = range_1((ra * RAD + lo * RAD - g0 * RAD) / 360);\n rise_str = am_pm(range_1(tr - h0 / 360 + zone / 24 - dt) * 24);\n set_str = am_pm(range_1(tr + h0 / 360 + zone / 24 - dt) * 24);\n tr = am_pm(range_1(tr + zone / 24 - dt) * 24);\n if (i == 1) document.planets.tr1.value = tr;\n if (i == 2) document.planets.tr2.value = tr;\n if (i == 3) document.planets.tr3.value = tr;\n if (i == 4) document.planets.tr4.value = tr;\n if (i == 5) document.planets.tr5.value = tr;\n\n if (i == 1) document.planets.tr1_2.value = tr;\n if (i == 2) document.planets.tr2_2.value = tr;\n if (i == 3) document.planets.tr3_2.value = tr;\n if (i == 4) document.planets.tr4_2.value = tr;\n if (i == 5) document.planets.tr5_2.value = tr;\n }\n\n al = al * RAD;\n az = az * RAD;\n planet_altitude[i] = al;\n planet_azimuth[i] = az;\n\n de = de * RAD;\n ra = ra * RAD / 15;\n\n x = round_10(abs(de));\n if (de < 0)\n {\n planet_dec[i] += \"-\";\n }\n else\n {\n planet_dec[i] += \"+\";\n }\n if (x < 10) planet_dec[i] += \"0\";\n planet_dec[i] += x;\n if (x == floor(x)) planet_dec[i] += \".0\";\n planet_dec[i] += \"\\u00B0\";\n\n x = floor(ra);\n y = floor((ra - x) * 60 + 0.5);\n if (y == 60)\n {\n x += 1;\n y = 0;\n }\n if (x < 10) planet_ra[i] += \"0\";\n planet_ra[i] += x + \"h \";\n if (y < 10) planet_ra[i] += \"0\";\n planet_ra[i] += y + \"m\";\n\n dr = round_100(dr);\n if (dr < 10)\n planet_dist[i] += \"0\";\n planet_dist[i] += dr;\n\n size = round_10(size);\n if (size < 10)\n planet_size[i] += \"0\";\n planet_size[i] += size;\n if (size == floor(size)) planet_size[i] += \".0\";\n planet_size[i] += \"\\\"\";\n\n planet_phase[i] += il + \"%\";\n\n planet_alt[i] = rise_str;\n planet_az[i] = set_str;\n\n }\n\n dawn_planets = \"\";\n dusk_planets = \"\";\n phenomena = \"\";\n\n y = sin(-9/RAD) - sin(la) * sin(planet_decl[0]);\n x = cos(la) * cos(planet_decl[0]);\n if (y/x >= 1)\n {\n\n dawn_planets = \"-----\";\n dusk_planets = \"-----\";\n }\n if (y/x <= -1)\n {\n\n dawn_planets = \"-----\";\n dusk_planets = \"-----\";\n }\n if (abs(y/x) < 1)\n {\n h0 = acos(y/x) * RAD;\n tr = range_1((planet_r_a[0] * RAD + lo * RAD - g0 * RAD) / 360);\n dawn = range_1(tr - h0 / 360 - dt);\n dusk = range_1(tr + h0 / 360 - dt);\n }\n gt_dawn = proper_ang_rad(g0 + dawn * 6.30038808);\n gt_dusk = proper_ang_rad(g0 + dusk * 6.30038808);\n\n indx = 0;\n morn = 0;\n eve = 0;\n for (i=0; i<17; i++)\n {\n\n if (i < 6)\n {\n ha = proper_ang_rad(gt_dawn - lo - planet_r_a[i]);\n al = asin(sin(la) * sin(planet_decl[i]) + cos(la) * cos(planet_decl[i]) * cos(ha));\n\n if (al >= 0)\n {\n if (morn > 0) dawn_planets += \", \";\n dawn_planets += planet_name[i];\n morn ++;\n }\n\n ha = proper_ang_rad(gt_dusk - lo - planet_r_a[i]);\n al = asin(sin(la) * sin(planet_decl[i]) + cos(la) * cos(planet_decl[i]) * cos(ha));\n\n if (al >= 0)\n {\n if (eve > 0) dusk_planets += \", \";\n dusk_planets += planet_name[i];\n eve ++;\n }\n }\n\n x = round_10(acos(sin(planet_decl[6]) * sin(planet_decl[i]) + cos(planet_decl[6]) * cos(planet_decl[i]) * cos(planet_r_a[6] - planet_r_a[i])) * RAD);\n\n if (x <= 10 && i != 6)\n {\n if (indx > 0) phenomena += \" and \";\n if (x < 1)\n {\n phenomena += \"less than 1\";\n }\n else\n {\n phenomena += floor(x + 0.5);\n }\n phenomena += \"\\u00B0\" + \" from \" + planet_name[i];\n if (x < 0.5)\n {\n if (i == 0)\n {\n phenomena += \" (eclipse possible)\";\n }\n else\n {\n phenomena += \" (occultation possible)\";\n }\n }\n indx ++\n }\n }\n\n if (dawn_planets == \"\") dawn_planets = \"-----\";\n if (dusk_planets == \"\") dusk_planets = \"-----\";\n\n if (indx > 0)\n {\n phenomena = \"The Moon is \" + phenomena + \". \";\n }\n indx = 0;\n for (i=1; i<16; i++)\n {\n for (count=i+1; count<17; count++)\n {\n if (i != 6 && count != 6)\n {\n x = round_10(acos(sin(planet_decl[count]) * sin(planet_decl[i]) + cos(planet_decl[count]) * cos(planet_decl[i]) * cos(planet_r_a[count] - planet_r_a[i])) * RAD);\n if (x <= 5)\n {\n if (indx > 0) phenomena += \" and \";\n phenomena += planet_name[count] + \" is \";\n if (x < 1)\n {\n phenomena += \"less than 1\";\n }\n else\n {\n phenomena += floor(x + 0.5);\n }\n phenomena += \"\\u00B0\" + \" from \" + planet_name[i];\n indx ++\n }\n x = 0;\n }\n }\n }\n if (indx > 0) phenomena += \".\";\n\n if (jd > 2454048.3007 && jd < 2454048.5078)\n {\n phenomena += \"\\nMercury is transiting the face of the Sun. \";\n x = round_10((2454048.50704 - jd) * 24);\n if (x >= 0.1)\n {\n phenomena += \"The spectacle continues for a further \" + x + \" hours.\"\n }\n }\n\n if (phenomena != \"\") { phenomena += \"\\n\"; }\n if (planet_altitude[0] < -18) phenomena += \"The sky is dark. \";\n if (planet_altitude[0] >= -18 && planet_altitude[0] < -12) phenomena += \"The Sun is below the horizon (altitude \" + floor(planet_altitude[0] + 0.5) + \"\\u00B0) and the sky is in deep twilight. \";\n if (planet_altitude[0] >= -12 && planet_altitude[0] < -6) phenomena += \"The Sun is below the horizon (altitude \" + floor(planet_altitude[0] + 0.5) + \"\\u00B0) and the sky is in twilight. \";\n if (planet_altitude[0] >= -6 && planet_altitude[0] < -0.3) phenomena += \"The Sun is below the horizon (altitude \" + floor(planet_altitude[0] + 0.5) + \"\\u00B0) and the sky is in bright twilight. \";\n if (planet_altitude[0] >= -0.3) phenomena += \"The Sun is above the horizon (altitude \" + floor(planet_altitude[0] + 0.5) + \"\\u00B0). \";\n if (planet_altitude[6] >= -0.3) phenomena += \"The Moon is above the horizon (altitude \" + floor(planet_altitude[6] + 0.5) + \"\\u00B0). \";\n if (planet_altitude[6] < -0.3) phenomena += \"The Moon is below the horizon. \";\n phenomena += \"\\n\";\n phenomena += moon_data;\n\n /* Commented out 2009-specific events 2010/01/27 - DAF\n phenomena += \"-----\\n2009 Phenomena\\n\";\n phenomena += \"yyyy mm dd hh UT All dates and times are UT\\n\"\n + \"2009 01 02 04 UT Mercury at greatest illuminated extent (evening)\\n\"\n + \"2009 01 03 13 UT Meteor shower peak -- Quadrantids\\n\"\n + \"2009 01 04 14 UT Mercury at greatest elongation, 19.3\\u00B0 east of Sun (evening)\\n\"\n + \"2009 01 04 16 UT Earth at perihelion 91,400,939 miles (147,095,552 km)\\n\"\n + \"2009 01 10 11 UT Moon at perigee, 222,137 miles (357,495 km)\\n\"\n + \"2009 01 14 21 UT Venus at greatest elongation, 47.1\\u00B0 east of Sun (evening)\\n\"\n + \"2009 01 23 00 UT Moon at apogee, 252,350 miles (406,118 km)\\n\"\n + \"2009 01 26 Annular eclipse of the Sun (South Atlantic, Indonesia)\\n\"\n + \"2009 02 07 20 UT Moon at perigee, 224,619 miles (361,489 km)\\n\"\n + \"2009 02 09 14:38 UT Penumbral lunar eclipse (midtime)\\n\"\n + \"2009 02 11 01 UT Mercury at greatest illuminated extent (morning)\\n\"\n + \"2009 02 13 21 UT Mercury at greatest elongation, 26.1\\u00B0 west of Sun (morning)\\n\"\n + \"2009 02 19 16 UT Venus at greatest illuminated extent (evening)\\n\"\n + \"2009 02 19 17 UT Moon at apogee, 251,736 miles (405,129 km)\\n\"\n + \"2009 03 07 15 UT Moon at perigee, 228,053 miles (367,016 km)\\n\"\n + \"2009 03 08 20 UT Saturn at opposition\\n\"\n + \"2009 03 19 13 UT Moon at apogee, 251,220 miles (404,299 km)\\n\"\n + \"2009 03 20 11:44 UT Spring (Northern Hemisphere) begins at the equinox\\n\"\n + \"2009 03 27 19 UT Venus at inferior conjunction with Sun\\n\"\n + \"2009 04 02 02 UT Moon at perigee, 229,916 miles (370,013 km)\\n\"\n + \"2009 04 13 05 UT Mercury at greatest illuminated extent (evening)\\n\"\n + \"2009 04 16 09 UT Moon at apogee, 251,178 miles (404,232 km)\\n\"\n + \"2009 04 22 11 UT Meteor shower peak -- Lyrids\\n\"\n + \"2009 04 26 08 UT Mercury at greatest elongation, 20.4\\u00B0 east of Sun (evening)\\n\"\n + \"2009 04 28 06 UT Moon at perigee, 227,446 miles (366,039 km)\\n\"\n + \"2009 05 02 14 UT Venus at greatest illuminated extent (morning)\\n\"\n + \"2009 05 06 00 UT Meteor shower peak -- Eta Aquarids\\n\"\n + \"2009 05 14 03 UT Moon at apogee, 251,603 miles (404,915 km)\\n\"\n + \"2009 05 26 04 UT Moon at perigee, 224,410 miles (361,153 km)\\n\"\n + \"2009 06 05 21 UT Venus at greatest elongation, 45.8\\u00B0 west of Sun (morning)\\n\"\n + \"2009 06 10 16 UT Moon at apogee, 252,144 miles (405,787 km)\\n\"\n + \"2009 06 13 12 UT Mercury at greatest elongation, 23.5\\u00B0 west of Sun (morning)\\n\"\n + \"2009 06 21 05:46 UT Summer (Northern Hemisphere) begins at the solstice\\n\"\n + \"2009 06 23 11 UT Moon at perigee, 222,459 miles (358,013 km)\\n\"\n + \"2009 07 03 21 UT Mercury at greatest illuminated extent (morning)\\n\"\n + \"2009 07 04 02 UT Earth at aphelion 94,505,048 miles (152,091,132 km)\\n\"\n + \"2009 07 07 09:39 UT Penumbral lunar eclipse (too slight to see)\\n\"\n + \"2009 07 07 22 UT Moon at apogee, 252,421 miles (406,232 km)\\n\"\n + \"2009 07 21 20 UT Moon at perigee, 222,118 miles (357,464 km)\\n\"\n + \"2009 07 22 Total solar eclipse (India, China, and a few Pacific islands)\\n\"\n + \"2009 07 28 02 UT Meteor shower peak -- Delta Aquarids\\n\"\n + \"2009 08 04 01 UT Moon at apogee, 252,294 miles (406,028 km)\\n\"\n + \"2009 08 06 00:39 UT Weak penumbral lunar eclipse (midtime)\\n\"\n + \"2009 08 12 17 UT Meteor shower peak -- Perseids\\n\"\n + \"2009 08 14 18 UT Jupiter at opposition\\n\"\n + \"2009 08 17 21 UT Neptune at opposition\\n\"\n + \"2009 08 19 05 UT Moon at perigee, 223,469 miles (359,638 km)\\n\"\n + \"2009 08 24 16 UT Mercury at greatest elongation, 27.4\\u00B0 east of Sun (evening)\\n\"\n + \"2009 08 26 09 UT Mercury at greatest illuminated extent (evening)\\n\"\n + \"2009 08 31 11 UT Moon at apogee, 251,823 miles (405,269 km)\\n\"\n + \"2009 09 16 08 UT Moon at perigee, 226,211 miles (364,052 km)\\n\"\n + \"2009 09 17 09 UT Uranus at opposition\\n\"\n + \"2009 09 22 21:19 UT Fall (Northern Hemisphere) begins at the equinox\\n\"\n + \"2009 09 28 04 UT Moon at apogee, 251,302 miles (404,432 km)\\n\"\n + \"2009 10 06 02 UT Mercury at greatest elongation, 17.9\\u00B0 west of Sun (morning)\\n\"\n + \"2009 10 11 07 UT Mercury at greatest illuminated extent (morning)\\n\"\n + \"2009 10 13 12 UT Moon at perigee, 229,327 miles (369,066 km)\\n\"\n + \"2009 10 21 10 UT Meteor shower peak -- Orionids\\n\"\n + \"2009 10 25 23 UT Moon at apogee, 251,137 miles (404,166 km)\\n\"\n + \"2009 11 05 10 UT Meteor shower peak -- Southern Taurids\\n\"\n + \"2009 11 07 07 UT Moon at perigee, 229,225 miles (368,902 km)\\n\"\n + \"2009 11 12 10 UT Meteor shower peak -- Northern Taurids\\n\"\n + \"2009 11 17 15 UT Meteor shower peak -- Leonids\\n\"\n + \"2009 11 22 20 UT Moon at apogee, 251,489 miles (404,733 km)\\n\"\n + \"2009 12 04 14 UT Moon at perigee, 225,856 miles (363,481 km)\\n\"\n + \"2009 12 14 05 UT Meteor shower peak -- Geminids\\n\"\n + \"2009 12 17 13 UT Mercury at greatest illuminated extent (evening)\\n\"\n + \"2009 12 18 17 UT Mercury at greatest elongation, 20.3\\u00B0 east of Sun (evening)\\n\"\n + \"2009 12 20 15 UT Moon at apogee, 252,109 miles (405,731 km)\\n\"\n + \"2009 12 21 17:47 UT Winter (Northern Hemisphere) begins at the solstice\\n\"\n + \"2009 12 31 Partial lunar eclipse, 18:52 UT to 19:54 UT\\n-----\\n\";\n END Comment DAF */\n\n document.planets.ra1.value = planet_ra[1];\n document.planets.dec1.value = planet_dec[1];\n document.planets.dist1.value = planet_mag[1];\n document.planets.size1.value = planet_size[1];\n document.planets.phase1.value = planet_phase[1];\n document.planets.alt1.value = planet_alt[1];\n document.planets.az1.value = planet_az[1];\n\n document.planets.ra1_2.value = planet_ra[1];\n document.planets.dec1_2.value = planet_dec[1];\n document.planets.dist1_2.value = planet_mag[1];\n document.planets.size1_2.value = planet_size[1];\n document.planets.phase1_2.value = planet_phase[1];\n document.planets.alt1_2.value = planet_alt[1];\n document.planets.az1_2.value = planet_az[1];\n\n document.planets.ra2.value = planet_ra[2];\n document.planets.dec2.value = planet_dec[2];\n document.planets.dist2.value = planet_mag[2];\n document.planets.size2.value = planet_size[2];\n document.planets.phase2.value = planet_phase[2];\n document.planets.alt2.value = planet_alt[2];\n document.planets.az2.value = planet_az[2];\n\n document.planets.ra2_2.value = planet_ra[2];\n document.planets.dec2_2.value = planet_dec[2];\n document.planets.dist2_2.value = planet_mag[2];\n document.planets.size2_2.value = planet_size[2];\n document.planets.phase2_2.value = planet_phase[2];\n document.planets.alt2_2.value = planet_alt[2];\n document.planets.az2_2.value = planet_az[2];\n\n document.planets.ra3.value = planet_ra[3];\n document.planets.dec3.value = planet_dec[3];\n document.planets.dist3.value = planet_mag[3];\n document.planets.size3.value = planet_size[3];\n document.planets.phase3.value = planet_phase[3];\n document.planets.alt3.value = planet_alt[3];\n document.planets.az3.value = planet_az[3];\n\n document.planets.ra3_2.value = planet_ra[3];\n document.planets.dec3_2.value = planet_dec[3];\n document.planets.dist3_2.value = planet_mag[3];\n document.planets.size3_2.value = planet_size[3];\n document.planets.phase3_2.value = planet_phase[3];\n document.planets.alt3_2.value = planet_alt[3];\n document.planets.az3_2.value = planet_az[3];\n\n document.planets.ra4.value = planet_ra[4];\n document.planets.dec4.value = planet_dec[4];\n document.planets.dist4.value = planet_mag[4];\n document.planets.size4.value = planet_size[4];\n // document.planets.phase4.value = planet_phase[4];\n document.planets.alt4.value = planet_alt[4];\n document.planets.az4.value = planet_az[4];\n\n document.planets.ra4_2.value = planet_ra[4];\n document.planets.dec4_2.value = planet_dec[4];\n document.planets.dist4_2.value = planet_mag[4];\n document.planets.size4_2.value = planet_size[4];\n // document.planets.phase4_2.value = planet_phase[4];\n document.planets.alt4_2.value = planet_alt[4];\n document.planets.az4_2.value = planet_az[4];\n\n document.planets.ra5.value = planet_ra[5];\n document.planets.dec5.value = planet_dec[5];\n document.planets.dist5.value = planet_mag[5];\n document.planets.size5.value = planet_size[5];\n // document.planets.phase5.value = planet_phase[5];\n document.planets.alt5.value = planet_alt[5];\n document.planets.az5.value = planet_az[5];\n\n document.planets.ra5_2.value = planet_ra[5];\n document.planets.dec5_2.value = planet_dec[5];\n document.planets.dist5_2.value = planet_mag[5];\n document.planets.size5_2.value = planet_size[5];\n // document.planets.phase5_2.value = planet_phase[5];\n document.planets.alt5_2.value = planet_alt[5];\n document.planets.az5_2.value = planet_az[5];\n\n document.planets.dist6.value = planet_dist[6];\n document.planets.size6.value = sunrise_set;\n document.planets.phase6.value = phenomena;\n document.planets.dawn.value = dawn_planets;\n document.planets.dusk.value = dusk_planets;\n document.planets.size7.value = moonrise_set;\n document.planets.phase7.value = twilight_begin_end;\n\n document.planets.ra8.value = planet_ra[8];\n document.planets.dec8.value = planet_dec[8];\n document.planets.dist8.value = planet_mag[0];\n document.planets.size8.value = planet_size[8];\n document.planets.alt8.value = planet_alt[8];\n document.planets.az8.value = planet_az[8];\n\n document.planets.ra8_2.value = planet_ra[8];\n document.planets.dec8_2.value = planet_dec[8];\n document.planets.dist8_2.value = planet_mag[0];\n document.planets.size8_2.value = planet_size[8];\n document.planets.alt8_2.value = planet_alt[8];\n document.planets.az8_2.value = planet_az[8];\n\n document.planets.ra9.value = planet_ra[9];\n document.planets.dec9.value = planet_dec[9];\n document.planets.dist9.value = planet_mag[6];\n document.planets.size9.value = planet_size[9];\n document.planets.phase9.value = planet_phase[9];\n document.planets.alt9.value = planet_alt[9];\n document.planets.az9.value = planet_az[9];\n\n document.planets.ra9_2.value = planet_ra[9];\n document.planets.dec9_2.value = planet_dec[9];\n document.planets.dist9_2.value = planet_mag[6];\n document.planets.size9_2.value = planet_size[9];\n document.planets.phase9_2.value = planet_phase[9];\n document.planets.alt9_2.value = planet_alt[9];\n document.planets.az9_2.value = planet_az[9];\n\n }\n}", "function circleKoords(e) {\n \n circfeqcnt = circfeqcnt + 1; //alert(circfeqcnt);\n \n if (circfeqcnt <= 1) { var circolor = 'blue'; }\n else if (circfeqcnt == 2) { var circolor = 'red'; }\n else if (circfeqcnt == 3) { var circolor = 'green'; }\n else if (circfeqcnt == 4) { var circolor = 'purple'; }\n else if (circfeqcnt == 5) { var circolor = 'yellow'; }\n else if (circfeqcnt > 5) { var circolor = 'black'; }\n \n var LatLng = e.latlng; console.log('@13 '+LatLng);\n var lat = e.latlng[\"lat\"]; \n var lng = e.latlng[\"lng\"]; \n \n var i; var j;\n var r = 1609.34; // in meters = 1 mile, 4,828.03 meters in 3 miles\n \n //https://jsfiddle.net/3u09g2mf/2/ \n //https://gis.stackexchange.com/questions/240169/leaflet-onclick-add-remove-circles\n var group1 = L.featureGroup(); // Allows us to group the circles for easy removal, but not working\n \n var circleOptions = {\n color: circolor,\n fillOpacity: 0.005 ,\n fillColor: '#69e'\n } // End circleOptions var \n \n // This routine sets a default number of miles between rings and the number of rings\n // Based on the number of rings selected and marker that was clicked, it calculates \n // the distance to the furthest corner and returns an appropriate number of rings\n // to draw to reach it, auto magically.\n // Variable dbr is the distance between rings, might be feet or miles\n // Variable maxdist is the calculated distance to the furthest corner marker\n \n var dbr = 5; // Default for miles between circles for general markers\n var maxdist = 0;\n var maxdistr = 0;\n var numberofrings = 1;\n var distancebetween = 0;\n var Lval = 'miles'; \n var marker = lastLayer; \n \n \n //alert('your in the right place, outside the obj loop');\n // Use this for Objects\n // Much of this code is thanks to Florian at Falke Design without who it was just over my head 4/30/2021\n if(marker.getPopup() && marker.getPopup().getContent().indexOf('OBJ') > -1){ \n // greater then -1 because the substring OBJ is found (if the substring OBJ is found, it returns the index > -1, if not found === -1)\n console.log('@51 content= '+marker.getPopup().getContent());\n // @51 content= <div class='xx'>OBJ:<br>W0DLK04<br></div><div class='gg'>W3W: posters.sheep.pretty </div><br><div class='cc'>Comment:<br> who know?</div><br><div class='bb'><br>Cross Roads:<br>N Ames Ave &amp; NW 59 St </div><br><div class='gg'>39.200908,-94.601471<br>Grid: EM29QE<br><br>Captured:<br>2021-07-28 16:07:27</div>\n \n\n // Object Markers: Test only the object markers\n // The distanceTo() function calculates in meters\n // 1 mile = 1609.34 meters. \n // this is test calculation only because the min distance might point to the wrong marker\n var whoArray = [];\n var markerName = [];\n var ownerCall = '';\n var maxdist = 0;\n \n if(marker.getPopup() && marker.getPopup().getContent().indexOf('OBJ') > -1){\n // whose marker did we find? This 3 statements work for the middle and the corners\n markerText = marker.getPopup().getContent(); // Everything in the marker\n whoArray = markerText.split('<br>'); // add markerText words to an array\n markerName = whoArray[1]; // Get the callsign (I hope)\n //LatLng = 'LatLng('+lat+', '+lng+')'; // whoArray[2];\n //markerKord = whoArray[2];\n ownerCall = markerName.slice(0, -2); // Deletes the number from the call\n padCall = ownerCall.concat('PAD');\n \n console.log('@74 markerName= '+markerName+' ownerCall= '+ownerCall+' padCall= '+padCall+' LatLng= '+LatLng)+' dist= '+LatLng.distanceTo( sw );\n \n maxdist = Math.max(\n LatLng.distanceTo( se ), \n LatLng.distanceTo( ne ), \n LatLng.distanceTo( nw ),\n LatLng.distanceTo( sw ),\n LatLng.distanceTo( window[padCall].getSouthWest() ),\n LatLng.distanceTo( window[padCall].getSouthEast() ),\n LatLng.distanceTo( window[padCall].getNorthWest() ),\n LatLng.distanceTo( window[padCall].getNorthEast() ) \n )/1609.34; \n \n /* maxdist = Math.max( \n LatLng.distanceTo( se ), \n LatLng.distanceTo( ne ), \n LatLng.distanceTo( nw ), \n LatLng.distanceTo( sw ))/1609.34; */\n \n console.log('@89 Object maxdist= '+maxdist+' from '+markerName+' for '+window[padCall] );\n \n \n } // end of if(marker.getPopup... \n} // end of marker is an object\nelse if(!marker.getPopup() || marker.getPopup().getContent().indexOf('OBJ') === -1){ \n // if the marker has NO popup or the marker has not containing OBJ in the popup\n // General Markers: Test all the general and object markers for the furthest out\n //alert('in G');\n \n maxdist = Math.max( \n LatLng.distanceTo( se ), \n LatLng.distanceTo( ne ), \n LatLng.distanceTo( nw ), \n LatLng.distanceTo( sw ))/1609.34;\n\n console.log('@105 Station maxdist: '+maxdist+' miles Lval= '+Lval); \n} // end of marker is a station \n \n \n if (maxdist < 1) { \n Lval = 'feet';\n maxfeet = maxdist*5280;\n if (maxdist > 0 && maxdist <= .5) {dbr = .05;}\n else if (maxdist > .5 && maxdist <= 1) {dbr = .075;}\n console.log('@114 maxdist= '+maxdist+' Lval= '+Lval); \n } else { \n // Set the new calculated distance between markers, 5 is the default dbr \n if (maxdist > 1 && maxdist <= 2) {dbr = .75;}\n else if (maxdist > 2 && maxdist <= 10) {dbr = 1;}\n else if (maxdist > 10 && maxdist <= 50) {dbr = 5;}\n else if (maxdist > 50 && maxdist <= 500) {dbr = 25;}\n else if (maxdist > 500 && maxdist <= 750) {dbr = 50;}\n else if (maxdist > 750 && maxdist <= 1000) {dbr = 75;}\n else if (maxdist > 1000 && maxdist <= 2000) {dbr = 300;}\n else if (maxdist > 2000 && maxdist <= 6000) {dbr = 500;}\n else {dbr = 5;}\n console.log('@124 maxdist= '+maxdist+' Lval= '+Lval);\n }\n\n\n distancebetween = prompt('Distance to furthest corner is '+maxdist+\" \"+Lval+\".\\n How many \"+ Lval+\" between circles?\", dbr);\n \t\t//if (distancebetween <= 0) {distancebetween = 1;} \n \t\t//if (distancebetween > 0 && distancebetween <= 10) {distancebetween = 2;}\n \t\tconsole.log('@131 db: '+distancebetween);\n \t\t\n maxdist = maxdist/distancebetween;\n console.log('@134 distancebetween= '+distancebetween+' maxdist= '+maxdist);\n \n numberofrings = prompt(Math.round(maxdist)+\" circles will cover all these objects.\\n How many circles do you want to see?\", Math.round(maxdist));\n \t\t//if (numberofrings <= 0) {numberofrings = 5;}\t\n \t\t\n console.log('@139 numberofrings = '+numberofrings+' round(maxdist): '+Math.round(maxdist,2));\t\n \t\t\n \n angle1 = 90; // mileage boxes going East\n angle2 = 270; // mileage boxes going West\n angle3 = 0; // degree markers\n \n \n // The actual circles are created here at the var Cname =\n for (i=0 ; i < numberofrings; i++ ) {\n var Cname = 'circle'+i; \n r = (r * i) + r; \n r = r*distancebetween;\n var Cname = L.circle([lat, lng], r, circleOptions);\n Cname.addTo(group1); \n map.addLayer(group1);\n \n // angle1, angle2 puts the mileage markers on the lines p_c1 and p_c2\n angle1 = angle1 + 10;\n angle2 = angle2 + 10;\n \n // i is the number of rings, depending how many have been requested the delta between bears\n // will be adjusted from 15 degrees at the 2nd circle to 5 degrees at the furthest.\n if ( i === 0 ) { //alert(numberofrings);\n for (j=0; j < 360; j+=20) {\n // j in the icon definition is the degrees \n var p_c0 = L.GeometryUtil.destination(L.latLng([lat, lng]),angle3,r);\n var icon = L.divIcon({ className: 'deg-marger', html: j , iconSize: [40,null] });\n var marker0 = L.marker(p_c0, { title: 'degrees', icon: icon});\n marker0.addTo(map);\n angle3 = angle3 + 20;\n }\n }else if ( i === 5 ) {\n for (j=0; j < 360; j+=10) {\n // j in the icon definition is the degrees \n var p_c0 = L.GeometryUtil.destination(L.latLng([lat, lng]),angle3,r);\n var icon = L.divIcon({ className: 'deg-marger', html: j , iconSize: [40,null] });\n var marker0 = L.marker(p_c0, { title: 'degrees', icon: icon});\n marker0.addTo(map);\n angle3 = angle3 + 10;\n } \n }else if ( i === 2 ) {\n for (j=0; j < 360; j+=10) {\n // j in the icon definition is the degrees \n var p_c0 = L.GeometryUtil.destination(L.latLng([lat, lng]),angle3,r);\n var icon = L.divIcon({ className: 'deg-marger', html: j , iconSize: [40,null] });\n var marker0 = L.marker(p_c0, { title: 'degrees', icon: icon});\n marker0.addTo(map);\n angle3 = angle3 + 10;\n }\n }else if ( i === numberofrings-1 ) {\n for (j=0; j < 360; j+=5) {\n // j in the icon definition is the degrees \n var p_c0 = L.GeometryUtil.destination(L.latLng([lat, lng]),angle3,r);\n var icon = L.divIcon({ className: 'deg-marger', html: j , iconSize: [40,null] });\n var marker0 = L.marker(p_c0, { title: 'degrees', icon: icon});\n marker0.addTo(map);\n angle3 = angle3 + 5;\n } // End for loop \n } // end of else if\n \n var p_c1 = L.GeometryUtil.destination(L.latLng([lat, lng]),angle1,r);\n var p_c2 = L.GeometryUtil.destination(L.latLng([lat, lng]),angle2,r);\n //var inMiles = (toFixed(0)/1609.34)*.5;\n var inMiles = Math.round(r.toFixed(0)/1609.34)+' Mi';\n var inFeet = Math.round((r.toFixed(0)/1609.34)*5280)+' Ft';\n var inKM = Math.round(r.toFixed(0)/1000)+' Km';\n var inM = Math.round((r.toFixed(0)/1000)*1000)+' M';\n \n if(Math.round(r.toFixed(0)/1609.34) < 2) {inMiles = inFeet; inKM = inM;}\n \n // Put mile and km or feet and m on each circle\n var icon = L.divIcon({ className: 'dist-marker-'+circolor, html: inMiles+' <br> '+inKM, iconSize: [60, null] });\n \n var marker = L.marker(p_c1, { title: inMiles+'Miles', icon: icon});\n var marker2 = L.marker(p_c2, { title: inMiles+'Miles', icon: icon});\n \n marker.addTo(map);\n marker2.addTo(map);\n \n // reset r so r calculation above works for each 1 mile step \n r = 1609.34; \n var dbr = 1; // Default for miles between circles for general markers\n var maxdist = 1;\n } // end of for loop \n} // end circleKoords function", "function xe(a){this.radius=a}", "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 circleMoreBlue(){\n b = b + 40;\n}", "function initManyCircles() \r\n{\r\n\tfor (let i = 0; i < noc; i++) \r\n\t{\r\n\t\trandomInitialize();\r\n\r\n\t\tcircleArr.push(new Circle(center_x_pos,center_y_pos,radius,arc_start,arc_end,colour,dx,dy));\r\n\t}\t\r\n}", "function drawCircles() {\n for (var i = 0; i < numCircles; i++) {\n var randomX = Math.round(-100 + Math.random() * 704);\n var randomY = Math.round(-100 + Math.random() * 528);\n var speed = 1 + Math.random() * 3;\n var size = 1 + Math.random() * circleSize;\n\n var circle = new Circle(speed, size, randomX, randomY);\n circles.push(circle);\n }\n update();\n }", "function increase_ball_size()\r\n{\r\n\t// the object is to co-ordinate the functions to increase the ball's size and record it\r\n\tball_size(\"increase\");\r\n\t//variable_content_viewer();\r\n\tdisplay();\r\n}", "function expansionhour() \n{\n var maxRadius = 67.5;\n var rateOfGrowth = maxRadius * refreshInterval / millisInAnHour;\n var circle2 = document.getElementById(\"circle2\");\n var circleRadius = circle2.getAttribute('r');\n circleRadius = parseFloat(circleRadius);\n circleRadius = circleRadius + rateOfGrowth;\n console.log(circleRadius);\n if (circleRadius > maxRadius)\n {\n circleRadius = 0;\n }\n \n circle2.setAttribute('r', circleRadius);\n}", "function calcRingArea() {\r\n var tbRadius = document.getElementById('tbRadius').value;\r\n var tbInnerRad = document.getElementById('tbInnerRad').value;\r\n var areaCircle = document.getElementById('areaCircle');\r\n var areaRing = document.getElementById('areaRing');\r\n var bigCirc = 3.14 * tbRadius * tbRadius;\r\n var smallCirc = 3.14 * tbInnerRad * tbInnerRad;\r\n areaRing.textContent = bigCirc - smallCirc;\r\n}", "function createTarget() {\r\n for (i = 0; i < ringNumber; i++) {\r\n radWidth = ((scry / 2) / ringNumber) * (ringNumber - i);\r\n ctx.beginPath();\r\n ctx.arc(scrx / 2, scry / 2, radWidth, 0, 2 * Math.PI);\r\n ctx.strokeStyle = \"#222222\";\r\n ctx.stroke();\r\n ctx.fillStyle = ringColours[i][0];\r\n ctx.fill();\r\n /*alert(ringColours[i]+\" \"+(scry/2)+\",\"+(scrx/2)+\" \"+radWidth);*/\r\n }\r\n}", "changeRadius(newRadius=this.radius) {\n this.radius = newRadius;\n this.changeAnchorRadius(this.html, newRadius);\n // Update Edges\n this.updateEdges()\n }", "function setupCircles(){\n\n var delay=0;\n var i = 0;\n for(var radius=canvasDiagonalFromCenter; radius>0; radius-=10){\n var circle = new Circle(radius, 0*Math.PI + i , 2*Math.PI + i ,0,0,delay,inputSpeed,inputAcceleration);\n circles.push(circle);\n delay+=delayIncrements;\n i+= 0.3*Math.PI;\n }\n drawAndUpdateCircles();\n}", "function setDifficulty(){\n if(difficulty==1){\n size = [12,20]\n }\n if(difficulty==2){\n size = [25,40]\n }\n if(difficulty==3){\n size = [50,80]\n }\n}", "function setDeepPaletteCircles(){\n setCircle('red', generateDeep(generateRed())); //red\n setCircle('orange', generateDeep(generateOrange())); //orange\n setCircle('yellow', generateDeep(generateYellow())); //yellow\n setCircle('yellowgreen', generateDeep(generateYellowGreen())); //yellowGreen\n setCircle('green', generateDeep(generateGreen())); //green\n setCircle('greencyan', generateDeep(generateGreenCyan())); //greenCyan\n setCircle('cyan', generateDeep(generateCyan())); //cyan\n setCircle('cyanblue', generateDeep(generateCyanBlue())); //cyanBlue\n setCircle('blue', generateDeep(generateBlue())); //blue\n setCircle('bluemagenta', generateDeep(generateBlueMagenta())); //blueMagenta\n setCircle('magenta', generateDeep(generateMagenta())); //magenta\n setCircle('magentared', generateDeep(generateMagentaRed())); //magentaRed\n}", "function buildCircles(earthquakes){\n circlearray = []\n console.log(\"function buildCircles in process... \")\n \n for (var i = 0; i < earthquakes.length; i++) {\n circlearray.push(\n\n L.circle([earthquakes[i].geometry.coordinates[1], earthquakes[i].geometry.coordinates[0]], {\n fillOpacity: 0.75,\n color: \"white\",\n stroke:false,\n fill: true,\n fillColor: magnitudeColors(earthquakes[i].properties.mag), \n\n // -- depth of earthquake -- color\n // fillColor: magnitudeColors([earthquakes[i].geometry.coordinates[3]]), \n\n radius: markerSize(earthquakes[i].properties.mag),\n }).bindPopup (\"<h3>\" + earthquakes[i].properties.place + \n \"<h3> Magnitude: \" + earthquakes[i].properties.mag +\n \"</h3><hr><p>\" + new Date(earthquakes[i].properties.time) + \"</p>\")\n ) // end of push\n }\n console.log(circlearray.length)\n console.log(\"Magnitude = \")\n console.log(markerSize)\n \n // .addTo(myMap);\n return L.layerGroup(circlearray)\n \n} // end bracket for function createMap", "function setBrightPaletteCircles(){\n setCircle('red', generateBright(generateRed())); //red\n setCircle('orange', generateBright(generateOrange())); //orange\n setCircle('yellow', generateBright(generateYellow())); //yellow\n setCircle('yellowgreen', generateBright(generateYellowGreen())); //yellowGreen\n setCircle('green', generateBright(generateGreen())); //green\n setCircle('greencyan', generateBright(generateGreenCyan())); //greenCyan\n setCircle('cyan', generateBright(generateCyan())); //cyan\n setCircle('cyanblue', generateBright(generateCyanBlue())); //cyanBlue\n setCircle('blue', generateBright(generateBlue())); //blue\n setCircle('bluemagenta', generateBright(generateBlueMagenta())); //blueMagenta\n setCircle('magenta', generateBright(generateMagenta())); //magenta\n setCircle('magentared', generateBright(generateMagentaRed())); //magentaRed\n}", "function init() { //!!! See how to make it work well\n\n\n\t\t// for (var i = 0; i < 800; i++) { //numbers of circles\n\t\t\t\n\t\t// \tcircleArray = [];\n\t\t// \t//var radius = 30;\n\t\t// \tvar radius = Math.random() * 3 +1; //min radius of 1 => range 1 to 4\n\t\t// \tvar x = Math.random() * (innerWidth - radius * 2) + radius;\n\t\t// \tvar y = Math.random() * (innerHeight - radius * 2) + radius;\n\t\t// \tvar dx = (Math.random() - 0.5) * 6.5;\n\t\t// \tvar dy = (Math.random() - 0.5) * 6.5;\n\t\t// \t//var radius = 30;\n\t\t// \tcircleArray.push(new Circle(x, y, dx, dy, radius));\n\t\t// \tvar circle = new Circle(200, 200, 3, 3, 30);\n\n\t\t// }\n\t}", "function calculateCircle(c1, c2, c3, properties, pathIndex, level)\n{\t\n\tcalCount++;\n\t\n\tvar k1 = properties.k1;\n\tvar k2 = properties.k2;\n\tvar k3 = properties.k3;\n\tvar k4 = properties.k4;\n\t\n\tvar z4 = mRC((1/k4), aCC(aCC(aCC(mRC(k1, c1._origin), mRC(k2, c2._origin)), mRC(k3, c3._origin)), mRC(2, sqrtC(aCC(aCC(mRC(k1*k2, mCC(c1._origin, c2._origin)), mRC(k2*k3, mCC(c2._origin, c3._origin))), mRC(k1*k3, mCC(c1._origin, c3._origin)))))));\n\tvar tangencyList = [c1, c2, c3];\n\tvar circ = new Circle(z4, 1/k4, c1.id + pathIndex, tangencyList, c1, level+1, \"#FFFFFF\", false);\n\t\n\treturn circ;\n}", "constructor( x, y, r ){\n //This instance of x, y, and r are given assigned variables x, y, and r\n this.x = x;\n this.y = y;\n this.r = r;\n //Assigns value of 50 to this instance of variable abductionSize\n this.abductionSize = 50;\n //Assigns value of half of value of abductionSize to this instance of variable abductionR\n // this.abductionR = this.abductionSize / 2;\n\n //This instance of deltaX and deltaY are assigned values of 3\n this.deltaX = 3;\n this.deltaY = 3;\n\n //Assigns Boolean value of false\n this.flyOff = false;\n }", "function updatePopupCircleSize(circle) {\n popup.style(\"visibility\", \"visible\")\n .attr(\"x\", parseFloat(circle.attr(\"cx\")) - popupWidth)\n .attr(\"y\", parseFloat(circle.attr(\"cy\")) - popupHeight - 20)\n .attr(\"class\", \"popup\");\n console.log(\"Toa do: \", parseFloat(circle.attr(\"cx\")) - popupWidth);\n\n popupRect.style(\"visibility\", \"visible\")\n .attr(\"x\", parseFloat(circle.attr(\"cx\")) - popupWidth)\n .attr(\"y\", parseFloat(circle.attr(\"cy\")) - popupHeight - 20)\n .attr(\"width\", popupWidth + 1)\n .attr(\"height\", popupHeight + 1)\n}", "function circles(cod, online, x){\n console.log(cod);\n online = Math.atan((online+50)/40)*(57.295);\n switch(x){\n case 'sjt': {\n console.log(\"hahah\");\n sjtcir.setCenter(cod);\n sjtcir.setRadius(online);\n break;\n }\n case 'tt': {\n ttcir.setCenter(cod);\n ttcir.setRadius(online);\n break;\n }\n case 'smv': {\n smvcir.setCenter(cod);\n smvcir.setRadius(online);\n break;\n }\n }\n}", "function radiusSize(magnitude) {\n return magnitude * 20000;\n }", "function getRadius(value){\n return value*30000\n}", "function buildCircleScene() {\n var posOrig = new THREE.Vector2(0, 0, 0); \n var posTarget = new THREE.Vector2(0, 0, 0); \n var num = sceneData.nAgents;\n var radius = 4;\n\n positionsArray = new Array();\n\n for (var i = 0; i < num; i++) {\n // circle shape\n var theta = 2*M_PI/num * i;\n var xLoc = radius * Math.cos(theta);\n var zLoc = radius * Math.sin(theta);\n var xLocDest = radius * Math.cos(theta + M_PI);\n var zLocDest = radius * Math.sin(theta + M_PI);\n\n posOrig = new THREE.Vector3(xLoc, zLoc);\n posTarget = new THREE.Vector3(xLocDest, zLocDest);\n\n positionsArray.push(posOrig);\n positionsArray.push(posTarget);\n }\n}", "function changeRadius() {\n heatmap.set(\"radius\", heatmap.get(\"radius\") ? null : 20);\n }", "function buildArray() {\n \"use strict\";\n\n for (var i = 0; i < numCircles; i++) {\n var color = Math.floor(Math.random() * (colors.length - 1 + 1)) + 1,\n left = Math.floor(Math.random() * (canvas.width - 0 + 1)) + 0,\n top = Math.floor(Math.random() * (canvas.height - 0 + 1)) + 0,\n size = Math.floor(Math.random() * (maxSize - minSize + 1)) + minSize,\n leftSpeed =\n (Math.floor(Math.random() * (maxSpeed - minSpeed + 1)) + minSpeed) / 10,\n topSpeed =\n (Math.floor(Math.random() * (maxSpeed - minSpeed + 1)) + minSpeed) / 10,\n expandState = expandState;\n\n while (leftSpeed == 0 || topSpeed == 0) {\n (leftSpeed =\n (Math.floor(Math.random() * (maxSpeed - minSpeed + 1)) + minSpeed) /\n 10),\n (topSpeed =\n (Math.floor(Math.random() * (maxSpeed - minSpeed + 1)) + minSpeed) /\n 10);\n }\n var circle = {\n color: color,\n left: left,\n top: top,\n size: size,\n leftSpeed: leftSpeed,\n topSpeed: topSpeed,\n expandState: expandState,\n };\n circles.push(circle);\n }\n}", "function circleColor(magnitude){\r\n if (magnitude < 1) {\r\n return \"#bdff20\"\r\n }\r\n else if (magnitude < 2) {\r\n return \"#fff941\"\r\n }\r\n else if (magnitude < 3) {\r\n return \"#ffc039\"\r\n }\r\n else if (magnitude < 4) {\r\n return \"#ff863c\"\r\n }\r\n else if (magnitude < 5) {\r\n return \"#ff6835\"\r\n }\r\n else {\r\n return \"#ff1e20\"\r\n }\r\n}", "calculateRadiusLegendValues() {\n const vis = this;\n\n let min = vis.minCount;\n let max = vis.maxCount;\n const range = max - min;\n const radiusLegendValues = [];\n\n // default numOfCircles for legend\n const numOfCircles = 4;\n\n // range === 0\n min = vis.roundToNearestTens(min);\n radiusLegendValues.push(min);\n\n if (range === 1) {\n max = vis.roundToNearestTens(max);\n radiusLegendValues.push(max);\n } else if (range === 2) {\n const value = min + 1;\n radiusLegendValues.push(value);\n\n max = vis.roundToNearestTens(max);\n radiusLegendValues.push(max);\n } else if (range > 2) {\n if (range > 5) {\n for (let i = 1; i < numOfCircles - 1; i++) {\n let value = (range / numOfCircles) * i;\n value = vis.roundToNearestTens(value);\n radiusLegendValues.push(value);\n }\n } else { // range === 2, 3, 4\n const value = Math.round(range / 2);\n radiusLegendValues.push(value);\n }\n max = vis.roundToNearestTens(max);\n radiusLegendValues.push(max);\n }\n\n vis.minCount = min;\n vis.maxCount = max;\n\n return radiusLegendValues;\n }", "function bolas_viewport(){\n for(let i = 0; i < total_moleculas; i++){\n atomo_rojo = Bodies.circle(280,150, radio_atomo_rojo,{render:{fillStyle:'red',strokeStyle:'red',sprite:{texture:'js/img2/Esfera_Grande.png'}},id:\"circulo_rojo_\"+[i]});\n atomo_blanco = Bodies.circle(((atomo_rojo.position.x) + 5),((atomo_rojo.position.y) + 15),radio_atomo_blanco,{render:{fillStyle:'white',strokeStyle:'black',sprite:{texture:'js/img2/Esfera_2.png'}},id:\"circulo_blanco_\"+[i]});\n \n moleculas_unidas = Body.create({\n parts: [atomo_rojo,atomo_blanco],\n restitution: 1,\n friction: 0,\n frictionStatic : 0,\n frictionAir: 0,\n inertia: Infinity,\n mass: 1,\n id: \"molecula_unida_\"+[i],\n });\n\n Body.setVelocity( moleculas_unidas, {x: velocity, y: -velocity});\n moleculas_unidas.restitution = 0;\n moleculas_unidas.friction = 0;\n moleculas_unidas.frictionStatic = 0;\n moleculas_unidas.frictionAir = 0;\n moleculas_unidas.inertia = Infinity;\n moleculas_unidas.mass = 1;\n moleculas_unidas.collisionFilter.mask = pega_Default;\n cambiar_color(valor_value);\n\n array_moleculas_unidas.push(moleculas_unidas);\n\n\n }\n World.add(world, array_moleculas_unidas);\n Runner.run(runner, engine);\n Render.run(render);\n }", "function ne(a){this.radius=a}", "function RadiusWidget(map, center, selectedPictures) {\r\n\tvar color;\r\n\tvar raza;\r\n\tif (selectedPictures >= 100000) {\r\n\t\tcolor = '#CC0000'; // red\r\n\t}\r\n\tif ((selectedPictures >= 10000) && (selectedPictures <= 99999)) {\r\n\t\tcolor = '#CCFF00'; // yellow\r\n\t}\r\n\tif ((selectedPictures >= 1000) && (selectedPictures <= 9999)) {\r\n\t\tcolor = '#00FF00'; // green\r\n\t}\r\n\tif ((selectedPictures >= 1) && (selectedPictures <= 999)) {\r\n\t\tcolor = '#0000CC'; // blue\r\n\t}\r\n\tif (selectedPictures == 0) {\r\n\t\tcolor = '#FFFFFF'; // white\r\n\t}\r\n\tif (map.getZoom() == 1) {\r\n\t\t$(\"#zoomMapLevel\").html(\" \" + map.getZoom());\r\n\t\t// $(\"#legendInfo\").append(\" here1 \");\r\n\t\traza = 320000;\r\n\t}\r\n\tif (map.getZoom() == 2) {\r\n\t\t$(\"#zoomMapLevel\").html(\" \" + map.getZoom());\r\n\t\traza = 320000\r\n\t}\r\n\tif (map.getZoom() == 3) {\r\n\t\t$(\"#zoomMapLevel\").html(\" \" + map.getZoom());\r\n\t\traza = 160000;\r\n\t}\r\n\tif (map.getZoom() == 4) {\r\n\t\t$(\"#zoomMapLevel\").html(\" \" + map.getZoom());\r\n\t\traza = 80000;\r\n\t}\r\n\tif (map.getZoom() == 5) {//\r\n\t\t$(\"#zoomMapLevel\").html(\" \" + map.getZoom());\r\n\t\traza = 40000;\r\n\t}\r\n\tif (map.getZoom() == 6) {//ok\r\n\t\t$(\"#zoomMapLevel\").html(\" \" + map.getZoom());\r\n\t\traza = 20000;\r\n\t}\r\n\tif (map.getZoom() == 7) {//ok\r\n\t\t$(\"#zoomMapLevel\").html(\" \" + map.getZoom());\r\n\t\traza = 10000;\r\n\t}\r\n\tif (map.getZoom() == 8) {//ok\r\n\t\t$(\"#zoomMapLevel\").html(\" \" + map.getZoom());\r\n\t\traza = 5000;\r\n\t}\r\n\tif (map.getZoom() == 9) {//ok\r\n\t\t$(\"#zoomMapLevel\").html(\" \" + map.getZoom());\r\n\t\traza = 2500;\r\n\t}\r\n\tif (map.getZoom() == 10) {//ok\r\n\t\t$(\"#zoomMapLevel\").html(\" \" + map.getZoom());\r\n\t\traza = 1250;\r\n\t}\r\n\tif (map.getZoom() == 11) {//ok\r\n\t\t$(\"#zoomMapLevel\").html(\" \" + map.getZoom());\r\n\t\traza = 625;\r\n\t}\r\n\tif (map.getZoom() == 12) {//ok\r\n\t\t$(\"#zoomMapLevel\").html(\" \" + map.getZoom());\r\n\t\traza = 312.5;\r\n\t}\r\n\tif (map.getZoom() == 13) {//ok\r\n\t\t$(\"#zoomMapLevel\").html(\" \" + map.getZoom());\r\n\t\traza = 156.25;\r\n\t}\r\n\tif (map.getZoom() == 14) {//ok\r\n\t\t$(\"#zoomMapLevel\").html(\" \" + map.getZoom());\r\n\t\traza = 78.125;\r\n\t}\r\n\tif (map.getZoom() == 15) {\r\n\t\t$(\"#zoomMapLevel\").html(\" \" + map.getZoom());\r\n\t\traza = 78.125;\r\n\t}\r\n\tif (map.getZoom() == 16) {\r\n\t\t$(\"#zoomMapLevel\").html(\" \" + map.getZoom());\r\n\t\traza = 78.125;\r\n\t}\r\n\tif (map.getZoom() == 17) {\r\n\t\t$(\"#zoomMapLevel\").html(\" \" + map.getZoom());\r\n\t\traza = 78.125;\r\n\t}\r\n\tif (map.getZoom() == 18) {\r\n\t\t$(\"#zoomMapLevel\").html(\" \" + map.getZoom());\r\n\t\traza = 78.125;\r\n\t}\r\n\tif (map.getZoom() == 19) {\r\n\t\t$(\"#zoomMapLevel\").html(\" \" + map.getZoom());\r\n\t\traza = 78.125;\r\n\t}\r\n\tif (map.getZoom() == 20) {\r\n\t\t$(\"#zoomMapLevel\").html(\" \" + map.getZoom());\r\n\t\traza = 78.125;\r\n\t}\r\n\tif (map.getZoom() == 21) {\r\n\t\t$(\"#zoomMapLevel\").html(\" \" + map.getZoom());\r\n\t\traza = 78.125;\r\n\t}\r\n\t// max 21 zoom levels\r\n\r\n\tvar circle = new google.maps.Circle( {\r\n\t\tmap : map,\r\n\t\tstrokeWeight : 2,\r\n\t\tfillOpacity : 0.6,\r\n\t\tcenter : center,\r\n\t\t//inverse projectiong scale\r\n\t\tradius : raza * map.getProjection().fromLatLngToPoint(new google.maps.LatLng(Math.abs(center.lat()), center.lng())).y / 100,\r\n\t\tfillColor : color,\r\n\t\tzIndex : 1\r\n\t});\r\n\r\n\tcircles.push(circle);\r\n\r\n\tcircles[circles.length - 1].setMap(map);\r\n}", "function swap_Shapes() {\r\n setInterval(next_Radius, 1000);\r\n}", "function circleParameter(r){\n//calc area = 2 * PI * r\n var circumference= 2 * Math.PI * r;\n//return the value\n return circumference;\n }", "function drawCircles() {\r\n placing = Placing.CIRCLE;\r\n}", "initializeCircles () {\n\t\tfor ( let i = 0; i < this.numberOfCircles; i++ ) {\n\t\t\tthis\n\t\t\t\t\t\t\t\t.circles\n\t\t\t\t\t\t\t\t.push( new Circle( this.position.x, this.position.y + Math.random(), this.baseRadius, this.bounceRadius, i * this.singleSlice ) );\n\t\t}\n\t}", "function changeCircleRadius(e) {\n // Determine which geocode box is filled\n // And fire click event\n\n\n // This will determine how many markers are within the circle\n pointsInCircle(circle, milesToMeters( $('#radius-selected').val() ) )\n\n // Set radius of circle only if we already have one on the map\n if (circle) {\n circle.setRadius( milesToMeters( $('#radius-selected').val() ) );\n }\n}", "function createCityCircle(){\n cityCircle = new google.maps.Circle({\n strokeColor: \"#6600ff\",\n strokeOpacity: 0.8,\n strokeWeight: 2,\n fillColor: \"#6666ff\",\n fillOpacity: 0.35,\n map: map,\n center: map.getCenter(),\n radius: Number(rad)\n //radius: 1000\n});\n}//createCityCircle", "function draw() {\n background(\"white\");\n for (let i = 0; i < width; i += 10) {\n for (let j = 0; j < height; j += 10) {\n//applied random variable for color of circles\n randFillR = random(255);\n randFillG = random(255);\n randFillB = random(255);\n fill(randFillR, randFillG, randFillB);\n circle(i, j, r);\n }\n }\n}", "defineStyles(){\n\t\tif(window.innerWidth < 850){\n\t\t\treturn {\n\t\t\t\t// circle radius has to be determined in javascript because the text is cordinated in the middle of the cicle\n\t\t\t\t// the circle boundries can be calculated by the radius\n\t\t\t\tcircleRadius: 45,\n\t\t\t\tsvgHeight: 350,\n\t\t\t\tsvgWidth: 750,\n\t\t\t}\n\t\t}else{\n\t\t\treturn {\n\t\t\t\tcircleRadius: 40,\n\t\t\t\tsvgHeight: 600,\n\t\t\t\t svgWidth: 1000\n\t\t\t}\n\t\t}\n\t}", "function circle18(x, y, r){\n for(let a=0; a<1000; a++){\n context.beginPath()\n let rt = r * Math.pow(Math.random(), 1/4)\n let theta = Math.random() * Math.PI * 2\n const xoff = Math.cos(theta) * rt + x\n const yoff = Math.sin(theta) * rt + y\n context.arc(xoff, yoff, 10, 0, 2 * Math.PI)\n context.stroke()\n }\n}" ]
[ "0.66542804", "0.66362405", "0.65755236", "0.6490662", "0.63981", "0.6365333", "0.6315636", "0.6312176", "0.630026", "0.62965107", "0.6291148", "0.6260898", "0.62564105", "0.62394935", "0.6214489", "0.62113225", "0.6194673", "0.61796325", "0.6149475", "0.6127785", "0.6125934", "0.6107163", "0.610123", "0.6074866", "0.6065789", "0.6065778", "0.6060317", "0.6054372", "0.6042411", "0.60201854", "0.6000436", "0.5995807", "0.59913707", "0.59795207", "0.5935253", "0.59205514", "0.59196955", "0.59128916", "0.5910464", "0.5908745", "0.5900759", "0.590016", "0.589974", "0.589974", "0.5898511", "0.5895601", "0.5889461", "0.58871317", "0.5842873", "0.5838656", "0.583437", "0.58321923", "0.58241427", "0.58211917", "0.58183193", "0.5817938", "0.58165956", "0.58142996", "0.58069366", "0.5805639", "0.57994133", "0.5793102", "0.5780707", "0.57783085", "0.57744896", "0.57546175", "0.57522", "0.5751056", "0.57452404", "0.5739656", "0.57392323", "0.5734883", "0.5732042", "0.57232714", "0.5717706", "0.5714851", "0.57105607", "0.57094425", "0.5674657", "0.5667419", "0.5663228", "0.5650278", "0.5649229", "0.56427485", "0.56305796", "0.5629355", "0.5629344", "0.56279594", "0.5624163", "0.5612216", "0.5607942", "0.5605843", "0.5605693", "0.5598757", "0.55945474", "0.55903786", "0.5585984", "0.55832696", "0.55819565", "0.55739194", "0.55738896" ]
0.0
-1
The service is actually this function, which we call with the func that should be debounced and how long to wait in between calls
function debounce(func, wait, immediate) { var timeout; // Create a deferred object that will be resolved when we need to // actually call the func var deferred = $q.defer(); return function() { var context = this, args = arguments; var later = function() { timeout = null; if (!immediate) { deferred.resolve(func.apply(context, args)); deferred = $q.defer(); } }; var callNow = immediate && !timeout; if (timeout) { $timeout.cancel(timeout); } timeout = $timeout(later, wait); if (callNow) { deferred.resolve(func.apply(context, args)); deferred = $q.defer(); } return deferred.promise; }; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function debouncer( func , timeout ) {\nvar timeoutID , timeout = timeout || 200;\nreturn function () {\nvar scope = this , args = arguments;\nclearTimeout( timeoutID );\ntimeoutID = setTimeout( function () {\n func.apply( scope , Array.prototype.slice.call( args ) );\n} , timeout );\n}\n}", "debounce(fn, quietMillis, bindedThis) {\n let isWaiting = false;\n return function func() {\n if (isWaiting) return;\n\n if (bindedThis === undefined) {\n bindedThis = this;\n }\n\n fn.apply(bindedThis, arguments);\n isWaiting = true;\n\n setTimeout(function () {\n isWaiting = false;\n }, quietMillis);\n };\n }", "function debounce(fn, ms){\n let startTime = 0;\n return function(){\n if (!startTime){ //run in the first call\n fn.apply(null, arguments);\n startTime = Date.now();\n }\n else if (Date.now() - startTime >= ms){ //check if ms amount time passed from the last call\n fn.apply(null, arguments);\n startTime = Date.now();\n }\n else {\n return;\n }\n } \n}", "static Debounce(func, threshold) {\n\t\tvar timeout;\n\t\n\t\treturn function debounced () {\n\t\t\t\n\t\t\tfunction delayed () {\n\t\t\t\tfunc.apply(this, arguments);\n\t\t\t\t\n\t\t\t\ttimeout = null; \n\t\t\t}\n\t \n\t\t\tif (timeout) clearTimeout(timeout);\n\t \n\t\t\ttimeout = setTimeout(delayed.bind(this), threshold || 100); \n\t\t};\n\t}", "function debounce(func, wait, context) {\n\t var timer;\n\n\t return function debounced() {\n\t var context = $scope,\n\t args = Array.prototype.slice.call(arguments);\n\t $timeout.cancel(timer);\n\t timer = $timeout(function() {\n\t timer = undefined;\n\t func.apply(context, args);\n\t }, wait || 10);\n\t };\n\t }", "function debounce(func, wait, context) {\n var timer;\n return function debounced() {\n var context = vm,\n args = Array.prototype.slice.call(arguments);\n $timeout.cancel(timer);\n timer = $timeout(function() {\n timer = undefined;\n func.apply(context, args);\n }, wait || 10);\n };\n }", "function debounce(func, wait, context) {\n var timer;\n return function debounced() {\n var context = $scope,\n args = Array.prototype.slice.call(arguments);\n $timeout.cancel(timer);\n timer = $timeout(function() {\n timer = undefined;\n func.apply(context, args);\n }, wait || 10);\n };\n }", "function debounce(func, wait, context) {\n\t\t\t\t\tvar timer;\n\t\t\t\t\treturn function debounced() {\n\t\t\t\t\t\tvar context = $scope,\n\t\t\t\t\t\t\targs = Array.prototype.slice.call(arguments);\n\t\t\t\t\t\t$timeout.cancel(timer);\n\t\t\t\t\t\ttimer = $timeout(function() {\n\t\t\t\t\t\t\ttimer = undefined;\n\t\t\t\t\t\t\tfunc.apply(context, args);\n\t\t\t\t\t\t}, wait || 10);\n\t\t\t\t\t};\n\t \t\t\t}", "function debounce(func, wait, context) {\n var timer;\n return function debounced() {\n var context = $scope,\n args = Array.prototype.slice.call(arguments);\n $timeout.cancel(timer);\n timer = $timeout(function() {\n timer = undefined;\n func.apply(context, args);\n }, wait || 10);\n };\n }", "function debounce(func, wait, context) {\n var timer;\n return function debounced() {\n var context = vm,\n args = Array.prototype.slice.call(arguments);\n $timeout.cancel(timer);\n timer = $timeout(function () {\n timer = undefined;\n func.apply(context, args);\n }, wait || 10);\n };\n }", "function debounce(func, wait, context) {\n var timer;\n return function debounced() {\n var context = $scope,\n args = Array.prototype.slice.call(arguments);\n $timeout.cancel(timer);\n timer = $timeout(function() {\n timer = undefined;\n func.apply(context, args);\n }, wait || 10);\n };\n }", "function debounce(func, wait, context) {\n var timer;\n return function debounced() {\n var context = $scope,\n args = Array.prototype.slice.call(arguments);\n $timeout.cancel(timer);\n timer = $timeout(function() {\n timer = undefined;\n func.apply(context, args);\n }, wait || 10);\n };\n }", "function debounce(func, wait, context) {\n var timer;\n\n return function debounced() {\n var context = $scope,\n args = Array.prototype.slice.call(arguments);\n $timeout.cancel(timer);\n timer = $timeout(function () {\n timer = undefined;\n func.apply(context, args);\n }, wait || 10);\n };\n }", "function debounce(func, wait, context) {\n\t\t\t\tvar timer;\n\t\t\t\treturn function debounced() {\n\t\t\t\t\tvar context = scope,\n\t\t\t\t\t\targs = Array.prototype.slice.call(arguments);\n\t\t\t\t\t\t$timeout.cancel(timer);\n\t\t\t\t\t\ttimer = $timeout(function() {\n\t\t\t\t\t\t timer = undefined;\n\t\t\t\t\t\t func.apply(context, args);\n\t\t\t\t\t\t}, wait || 10);\n\t\t\t \t};\n\t\t\t}", "function debounce(func, wait, context) {\n var timer;\n return function debounced() {\n var context,\n args = Array.prototype.slice.call(arguments);\n $timeout.cancel(timer);\n timer = $timeout(function() {\n timer = undefined;\n func.apply(context, args);\n }, wait || 10);\n };\n }", "function debounce(func, wait, context) {\n var timer;\n\n return function debounced() {\n var context = $scope,\n args = Array.prototype.slice.call(arguments);\n \n $timeout.cancel(timer);\n timer = $timeout(function () {\n timer = undefined;\n func.apply(context, args);\n }, wait || 10);\n };\n }", "function debounce(func, wait, context) {\n var timer;\n return function debounced() {\n var context = $scope,\n args = Array.prototype.slice.call(arguments);\n $timeout.cancel(timer);\n timer = $timeout(function () {\n timer = undefined;\n func.apply(context, args);\n }, wait || 10);\n };\n }", "function debounce(func, wait, context) {\n var timer;\n return function debounced() {\n var context = $scope,\n args = Array.prototype.slice.call(arguments);\n $timeout.cancel(timer);\n timer = $timeout(function() {\n timer = undefined;\n func.apply(context, args);\n }, wait || 10);\n };\n }", "function debounce(func, wait, context) {\n var timer;\n return function debounced() {\n var context = $scope,\n args = Array.prototype.slice.call(arguments);\n $timeout.cancel(timer);\n timer = $timeout(function() {\n timer = undefined;\n func.apply(context, args);\n }, wait || 10);\n };\n }", "function debouncer( func , timeout ) {\n var timeoutID;\n var timeoutVAR;\n\n if (timeout) {\n timeoutVAR = timeout;\n } else {\n timeoutVAR = 200;\n }\n\n return function() {\n var scope = this , args = arguments;\n clearTimeout( timeoutID );\n timeoutID = setTimeout( function () {\n func.apply( scope , Array.prototype.slice.call( args ) );\n }, timeoutVAR );\n };\n\n}", "function debouncer( func , timeout ) {\n var timeoutID;\n var timeoutVAR;\n\n if (timeout) {\n timeoutVAR = timeout;\n } else {\n timeoutVAR = 200;\n }\n\n return function() {\n var scope = this , args = arguments;\n clearTimeout( timeoutID );\n timeoutID = setTimeout( function () {\n func.apply( scope , Array.prototype.slice.call( args ) );\n }, timeoutVAR );\n };\n\n}", "function debounced(delay, fn) { \n let timerID\n return function (...args) {\n if (timerID) {\n clearTimeout(timerID);\n }\n timerID = setTimeout (() => {\n fn(...args);\n timerID = null;\n }, delay);\n }\n}", "function debounce(func, wait, context) {\n var timer;\n return function debounced() {\n var context = $scope,\n args = Array.prototype.slice.call(arguments);\n $timeout.cancel(timer);\n timer = $timeout(function() {\n timer = undefined;\n func.apply(context, args);\n }, wait || 10);\n };\n }", "function debounce(func, wait, context) {\n var timer;\n return function debounced() {\n var context = $scope,\n args = Array.prototype.slice.call(arguments);\n $timeout.cancel(timer);\n timer = $timeout(function() {\n timer = undefined;\n func.apply(context, args);\n }, wait || 10);\n };\n }", "function debounce(func, wait, context) {\n var timer;\n return function debounced() {\n var context = $scope,\n args = Array.prototype.slice.call(arguments);\n $timeout.cancel(timer);\n timer = $timeout(function() {\n timer = undefined;\n func.apply(context, args);\n }, wait || 10);\n };\n }", "function debounce (func, wait, context) {\n var timer;\n\n return function debounced () {\n var context = $scope,\n args = Array.prototype.slice.call(arguments);\n $timeout.cancel(timer);\n timer = $timeout(function () {\n timer = undefined;\n func.apply(context, args);\n }, wait || 10);\n };\n }", "static debouncer(func, tOut) {\n\t\tvar timeoutID, timeout = tOut || 200;\n\t\treturn function () {\n\t\t\tlet scope = window,\n\t\t\t\targs = arguments;\n\t\t\tclearTimeout(timeoutID);\n\t\t\ttimeoutID = setTimeout(() => {\n\t\t\t\tfunc\n\t\t\t\t\t.apply(scope, Array.prototype.slice.call(args));\n\t\t\t}, timeout);\n\t\t};\n\t}", "function debounce(func, wait, context) {\n var timer;\n\n return function debounced() {\n var context = $scope,\n args = Array.prototype.slice.call(arguments);\n $timeout.cancel(timer);\n timer = $timeout(function() {\n timer = undefined;\n func.apply(context, args);\n }, wait || 10);\n };\n }", "function debounce(func, wait, context) {\n var timer;\n\n return function debounced() {\n var context = $scope,\n args = Array.prototype.slice.call(arguments);\n $timeout.cancel(timer);\n timer = $timeout(function() {\n timer = undefined;\n func.apply(context, args);\n }, wait || 10);\n };\n }", "function debounce(func, wait, context) {\n var timer;\n\n return function debounced() {\n var context = $scope,\n args = Array.prototype.slice.call(arguments);\n $timeout.cancel(timer);\n timer = $timeout(function() {\n timer = undefined;\n func.apply(context, args);\n }, wait || 10);\n };\n }", "function debounce(func, wait, context) {\n var timer;\n\n return function debounced() {\n var context = $scope,\n args = Array.prototype.slice.call(arguments);\n $timeout.cancel(timer);\n timer = $timeout(function() {\n timer = undefined;\n func.apply(context, args);\n }, wait || 10);\n };\n }", "function debounce(func, wait, context) {\n var timer;\n\n return function debounced() {\n var context = $scope,\n args = Array.prototype.slice.call(arguments);\n $timeout.cancel(timer);\n timer = $timeout(function() {\n timer = undefined;\n func.apply(context, args);\n }, wait || 10);\n };\n }", "function debounce(func) {\n var wait = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 166;\n var timeout;\n\n function debounced() {\n for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {\n args[_key] = arguments[_key];\n } // eslint-disable-next-line consistent-this\n\n\n var that = this;\n\n var later = function later() {\n func.apply(that, args);\n };\n\n clearTimeout(timeout);\n timeout = setTimeout(later, wait);\n }\n\n debounced.clear = function () {\n clearTimeout(timeout);\n };\n\n return debounced;\n}", "function debounce(func) {\n var wait = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 166;\n var timeout;\n\n function debounced() {\n for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {\n args[_key] = arguments[_key];\n } // eslint-disable-next-line consistent-this\n\n\n var that = this;\n\n var later = function later() {\n func.apply(that, args);\n };\n\n clearTimeout(timeout);\n timeout = setTimeout(later, wait);\n }\n\n debounced.clear = function () {\n clearTimeout(timeout);\n };\n\n return debounced;\n}", "function debounce(func, wait, context) {\n var timer;\n return function debounced() {\n var context = $scope\n , args = Array.prototype.slice.call(arguments);\n $timeout.cancel(timer);\n timer = $timeout(function () {\n timer = undefined;\n func.apply(context, args);\n }, wait || 10);\n };\n }", "function debounce(func, wait, context) {\n var timer;\n\n return function debounced() {\n var context = $scope,\n args = Array.prototype.slice.call(arguments);\n $timeout.cancel(timer);\n timer = $timeout(function () {\n timer = undefined;\n func.apply(context, args);\n }, wait || 10);\n };\n }", "function debounce(func, wait, context) {\n var timer;\n\n return function debounced() {\n var context = $scope,\n args = Array.prototype.slice.call(arguments);\n $timeout.cancel(timer);\n timer = $timeout(function() {\n timer = undefined;\n func.apply(context, args);\n }, wait || 10);\n };\n }", "function debouncer( func , timeout ) {\n\tvar timeoutID , timeout = timeout || 200;\n\treturn function () {\n\t\tvar scope = this , args = arguments;\n\t\tclearTimeout( timeoutID );\n\t\ttimeoutID = setTimeout( function () {\n\t\t\tfunc.apply( scope , Array.prototype.slice.call( args ) );\n\t\t} , timeout );\n\t}\n}", "function debounce(func) {\n var wait = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 166;\n var timeout;\n\n function debounced() {\n for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {\n args[_key] = arguments[_key];\n }\n\n // eslint-disable-next-line consistent-this\n var that = this;\n\n var later = function later() {\n func.apply(that, args);\n };\n\n clearTimeout(timeout);\n timeout = setTimeout(later, wait);\n }\n\n debounced.clear = function () {\n clearTimeout(timeout);\n };\n\n return debounced;\n }", "function debounce(func, wait, context) {\n var timer;\n return function debounced() {\n var context = $scope,\n args = Array.prototype.slice.call(arguments);\n $timeout.cancel(timer);\n timer = $timeout(function() {\n timer = undefined;\n func.apply(context, args);\n }, wait || 10);\n };\n }", "function debounce(func) {\n var wait = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 166;\n var timeout;\n\n function debounced() {\n for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {\n args[_key] = arguments[_key];\n }\n\n // eslint-disable-next-line consistent-this\n var that = this;\n\n var later = function later() {\n func.apply(that, args);\n };\n\n clearTimeout(timeout);\n timeout = setTimeout(later, wait);\n }\n\n debounced.clear = function () {\n clearTimeout(timeout);\n };\n\n return debounced;\n}", "function debounce(func) {\n var wait = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 166;\n var timeout;\n\n function debounced() {\n for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {\n args[_key] = arguments[_key];\n }\n\n // eslint-disable-next-line consistent-this\n var that = this;\n\n var later = function later() {\n func.apply(that, args);\n };\n\n clearTimeout(timeout);\n timeout = setTimeout(later, wait);\n }\n\n debounced.clear = function () {\n clearTimeout(timeout);\n };\n\n return debounced;\n}", "function debounce(func) {\n var wait = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 166;\n var timeout;\n\n function debounced() {\n for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {\n args[_key] = arguments[_key];\n }\n\n // eslint-disable-next-line consistent-this\n var that = this;\n\n var later = function later() {\n func.apply(that, args);\n };\n\n clearTimeout(timeout);\n timeout = setTimeout(later, wait);\n }\n\n debounced.clear = function () {\n clearTimeout(timeout);\n };\n\n return debounced;\n}", "function debounce(func) {\n var wait = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 166;\n var timeout;\n\n function debounced() {\n for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {\n args[_key] = arguments[_key];\n }\n\n // eslint-disable-next-line consistent-this\n var that = this;\n\n var later = function later() {\n func.apply(that, args);\n };\n\n clearTimeout(timeout);\n timeout = setTimeout(later, wait);\n }\n\n debounced.clear = function () {\n clearTimeout(timeout);\n };\n\n return debounced;\n}", "function debounce(func) {\n var wait = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 166;\n var timeout;\n\n function debounced() {\n for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {\n args[_key] = arguments[_key];\n }\n\n // eslint-disable-next-line consistent-this\n var that = this;\n\n var later = function later() {\n func.apply(that, args);\n };\n\n clearTimeout(timeout);\n timeout = setTimeout(later, wait);\n }\n\n debounced.clear = function () {\n clearTimeout(timeout);\n };\n\n return debounced;\n}", "function debounce(func) {\n var wait = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 166;\n var timeout;\n\n function debounced() {\n for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {\n args[_key] = arguments[_key];\n }\n\n // eslint-disable-next-line consistent-this\n var that = this;\n\n var later = function later() {\n func.apply(that, args);\n };\n\n clearTimeout(timeout);\n timeout = setTimeout(later, wait);\n }\n\n debounced.clear = function () {\n clearTimeout(timeout);\n };\n\n return debounced;\n}", "function debounce(func) {\n var wait = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 166;\n var timeout;\n\n function debounced() {\n for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {\n args[_key] = arguments[_key];\n }\n\n // eslint-disable-next-line consistent-this\n var that = this;\n\n var later = function later() {\n func.apply(that, args);\n };\n\n clearTimeout(timeout);\n timeout = setTimeout(later, wait);\n }\n\n debounced.clear = function () {\n clearTimeout(timeout);\n };\n\n return debounced;\n}", "function debounce(func) {\n var wait = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 166;\n var timeout;\n\n function debounced() {\n for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {\n args[_key] = arguments[_key];\n }\n\n // eslint-disable-next-line consistent-this\n var that = this;\n\n var later = function later() {\n func.apply(that, args);\n };\n\n clearTimeout(timeout);\n timeout = setTimeout(later, wait);\n }\n\n debounced.clear = function () {\n clearTimeout(timeout);\n };\n\n return debounced;\n}", "function debounce(func) {\n var wait = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 166;\n var timeout;\n\n function debounced() {\n for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {\n args[_key] = arguments[_key];\n }\n\n // eslint-disable-next-line consistent-this\n var that = this;\n\n var later = function later() {\n func.apply(that, args);\n };\n\n clearTimeout(timeout);\n timeout = setTimeout(later, wait);\n }\n\n debounced.clear = function () {\n clearTimeout(timeout);\n };\n\n return debounced;\n}", "function debounce(func) {\n var wait = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 166;\n var timeout;\n\n function debounced() {\n for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {\n args[_key] = arguments[_key];\n }\n\n // eslint-disable-next-line consistent-this\n var that = this;\n\n var later = function later() {\n func.apply(that, args);\n };\n\n clearTimeout(timeout);\n timeout = setTimeout(later, wait);\n }\n\n debounced.clear = function () {\n clearTimeout(timeout);\n };\n\n return debounced;\n}", "function debounce(func) {\n var wait = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 166;\n var timeout;\n\n function debounced() {\n for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {\n args[_key] = arguments[_key];\n }\n\n // eslint-disable-next-line consistent-this\n var that = this;\n\n var later = function later() {\n func.apply(that, args);\n };\n\n clearTimeout(timeout);\n timeout = setTimeout(later, wait);\n }\n\n debounced.clear = function () {\n clearTimeout(timeout);\n };\n\n return debounced;\n}", "function debounce(func) {\n var wait = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 166;\n var timeout;\n\n function debounced() {\n for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {\n args[_key] = arguments[_key];\n }\n\n // eslint-disable-next-line consistent-this\n var that = this;\n\n var later = function later() {\n func.apply(that, args);\n };\n\n clearTimeout(timeout);\n timeout = setTimeout(later, wait);\n }\n\n debounced.clear = function () {\n clearTimeout(timeout);\n };\n\n return debounced;\n}", "function debounce(func) {\n var wait = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 166;\n var timeout;\n\n function debounced() {\n for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {\n args[_key] = arguments[_key];\n }\n\n // eslint-disable-next-line consistent-this\n var that = this;\n\n var later = function later() {\n func.apply(that, args);\n };\n\n clearTimeout(timeout);\n timeout = setTimeout(later, wait);\n }\n\n debounced.clear = function () {\n clearTimeout(timeout);\n };\n\n return debounced;\n}", "function debounce$1(func) {\n var wait = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 166;\n var timeout;\n\n function debounced() {\n for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {\n args[_key] = arguments[_key];\n }\n\n // eslint-disable-next-line consistent-this\n var that = this;\n\n var later = function later() {\n func.apply(that, args);\n };\n\n clearTimeout(timeout);\n timeout = setTimeout(later, wait);\n }\n\n debounced.clear = function () {\n clearTimeout(timeout);\n };\n\n return debounced;\n}", "function debounce(func, wait, context) {\n var timer;\n\n return function debounced() {\n var context = $scope,\n args = Array.prototype.slice.call(arguments);\n $timeout.cancel(timer);\n timer = $timeout(function () {\n timer = undefined;\n func.apply(context, args);\n }, wait || 10);\n };\n }", "function debounce(func, wait, context) {\n var timer;\n\n return function debounced() {\n var context = $scope,\n args = Array.prototype.slice.call(arguments);\n $timeout.cancel(timer);\n timer = $timeout(function () {\n timer = undefined;\n func.apply(context, args);\n }, wait || 10);\n };\n }", "function debounce(func, wait, context) {\n var timer;\n\n return function debounced() {\n var context = $scope,\n args = Array.prototype.slice.call(arguments);\n $timeout.cancel(timer);\n timer = $timeout(function() {\n timer = undefined;\n func.apply(context, args);\n }, wait || 10);\n };\n }", "function debounce(func, wait, context) {\n var timer;\n\n return function debounced() {\n var context = $scope,\n args = Array.prototype.slice.call(arguments);\n $timeout.cancel(timer);\n timer = $timeout(function() {\n timer = undefined;\n func.apply(context, args);\n }, wait || 10);\n };\n }", "function debounce(func) {\n var wait = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 166;\n var timeout;\n\n function debounced() {\n var _this = this;\n\n for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {\n args[_key] = arguments[_key];\n }\n\n var later = function later() {\n func.apply(_this, args);\n };\n\n clearTimeout(timeout);\n timeout = setTimeout(later, wait);\n }\n\n debounced.clear = function () {\n clearTimeout(timeout);\n };\n\n return debounced;\n}", "function debounce(func, wait) {\n var timeout;\n return function() {\n var context = this;\n var args = arguments;\n var later = function later() {\n timeout = null;\n func.apply(context, args);\n };\n clearTimeout(timeout);\n timeout = setTimeout(later, wait);\n };\n }", "function debounce(func, wait) {\n let timeout;\n \n return function executedFunction(...args) {\n // console.log(debouncing);\n const later = () => {\n clearTimeout(timeout);\n func(...args);\n };\n \n clearTimeout(timeout);\n timeout = setTimeout(later, wait);\n };\n }", "function wrapper(){var self=this;var elapsed=Number(new Date())-lastExec;var args=arguments;// Execute `callback` and update the `lastExec` timestamp.\nfunction exec(){lastExec=Number(new Date());callback.apply(self,args);}// If `debounceMode` is true (at begin) this is used to clear the flag\n// to allow future `callback` executions.\nfunction clear(){timeoutID=undefined;}if(debounceMode&&!timeoutID){// Since `wrapper` is being called for the first time and\n// `debounceMode` is true (at begin), execute `callback`.\nexec();}// Clear any existing timeout.\nif(timeoutID){clearTimeout(timeoutID);}if(debounceMode===undefined&&elapsed>delay){// In throttle mode, if `delay` time has been exceeded, execute\n// `callback`.\nexec();}else if(noTrailing!==true){// In trailing throttle mode, since `delay` time has not been\n// exceeded, schedule `callback` to execute `delay` ms after most\n// recent execution.\n//\n// If `debounceMode` is true (at begin), schedule `clear` to execute\n// after `delay` ms.\n//\n// If `debounceMode` is false (at end), schedule `callback` to\n// execute after `delay` ms.\ntimeoutID=setTimeout(debounceMode?clear:exec,debounceMode===undefined?delay-elapsed:delay);}}// Return the wrapper function.", "function debounce(fn, threshold) {\n var timeout;\n return function debounced() {\n if (timeout) {\n clearTimeout(timeout);\n }\n\n function delayed() {\n fn();\n timeout = null;\n }\n setTimeout(delayed, threshold || 100);\n }\n } // end used for packery: debounce", "function debounce(fn) {\n\t if (!App.vars.debounceTimer) fn.call(this);\n\t if (App.vars.debounceTimer) global.clearTimeout(App.vars.debounceTimer);\n\t App.vars.debounceTimer = global.setTimeout(function() {\n\t App.vars.debounceTimer = null;\n\t fn.call(this);\n\t }, App.setup.debounce);\n\t}", "function pnDebounce(func, wait, immediate) {\r\n var timeout;\r\n return function() {\r\n var context = this,\r\n args = arguments;\r\n var later = function() {\r\n timeout = null;\r\n if ( !immediate ) {\r\n func.apply(context, args);\r\n }\r\n };\r\n var callNow = immediate && !timeout;\r\n clearTimeout(timeout);\r\n timeout = setTimeout(later, wait || 200);\r\n if ( callNow ) {\r\n func.apply(context, args);\r\n }\r\n };\r\n }", "function debounce(f, waitMs) {\n var lastTime = tfjs_core_1.util.now();\n var lastResult;\n var f2 = function () {\n var args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n }\n var now = tfjs_core_1.util.now();\n if (now - lastTime < waitMs) {\n return lastResult;\n }\n lastTime = now;\n lastResult = f.apply(void 0, args);\n return lastResult;\n };\n return f2;\n}", "function debounce(f, waitMs) {\n var lastTime = tfjs_core_1.util.now();\n var lastResult;\n var f2 = function () {\n var args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n }\n var now = tfjs_core_1.util.now();\n if (now - lastTime < waitMs) {\n return lastResult;\n }\n lastTime = now;\n lastResult = f.apply(void 0, args);\n return lastResult;\n };\n return f2;\n}", "function debounce(fn, wait) {\n let timer = null;\n return function() {\n let context = this;\n clearTimeout(timer);\n timer = setTimeout(() => fn.apply(context, [...arguments]), wait);\n }\n}", "function debounce( fn, threshold ) {\r\n var timeout;\r\n return function debounced() {\r\n if ( timeout ) {\r\n clearTimeout( timeout );\r\n }\r\n function delayed() {\r\n fn();\r\n timeout = null;\r\n }\r\n timeout = setTimeout( delayed, threshold || 100 );\r\n }\r\n}", "function debounce(func, wait) {\n var timeout;\n return function() {\n var context = this;\n var args = arguments;\n var callback = function() {\n func.apply(context, args);\n };\n\n clearTimeout(timeout);\n timeout = setTimeout(callback, wait);\n };\n }", "function debounce(func, wait, options) {\n let callbackReturnValue;\n\n let timerId;\n let maxTimerId;\n\n const maxWait = options && options.maxWait ? Math.max(options.maxWait, wait) : 0;\n\n function invokeFunc() {\n cancelTimers();\n callbackReturnValue = func();\n return callbackReturnValue;\n }\n\n function cancelTimers() {\n timerId !== undefined && clearTimeout(timerId);\n maxTimerId !== undefined && clearTimeout(maxTimerId);\n timerId = maxTimerId = undefined;\n }\n\n function flush() {\n if (timerId !== undefined || maxTimerId !== undefined) {\n return invokeFunc();\n }\n return callbackReturnValue;\n }\n\n function debounced() {\n if (timerId) {\n clearTimeout(timerId);\n }\n timerId = setTimeout(invokeFunc, wait);\n\n if (maxWait && maxTimerId === undefined) {\n maxTimerId = setTimeout(invokeFunc, maxWait);\n }\n\n return callbackReturnValue;\n }\n\n debounced.cancel = cancelTimers;\n debounced.flush = flush;\n return debounced;\n }", "function _debounce(func, wait, immediate) {\n var timeout;\n var result;\n\n return function() {\n var context = this;\n var args = arguments;\n var later = function() {\n timeout = null;\n if (!immediate) {\n result = func.apply(context, args);\n }\n };\n var callNow = immediate && !timeout;\n\n clearTimeout(timeout);\n timeout = setTimeout(later, wait);\n if (callNow) {\n result = func.apply(context, args);\n }\n return result;\n };\n }", "get debounce() { return this._debounce; }", "get debounce() { return this._debounce; }", "get debounce() { return this._debounce; }", "function _debounce(func, wait, immediate) {\n var timeout;\n return function() {\n var context = this, args = arguments;\n var later = function() {\n timeout = null;\n if (!immediate) func.apply(context, args);\n };\n var callNow = immediate && !timeout;\n clearTimeout(timeout);\n timeout = setTimeout(later, wait);\n if (callNow) func.apply(context, args);\n };\n }", "function debounce(func, wait) {\n var timeout;\n return function debounce_run() {\n var context = this, args = arguments;\n var later = function() {\n timeout = null;\n func.apply(context, args);\n };\n clearTimeout(timeout);\n timeout = setTimeout(later, wait);\n };\n }", "function debounce(fn, threshold) {\r\n var timeout;\r\n return function debounced() {\r\n if (timeout) {\r\n clearTimeout(timeout);\r\n }\r\n function delayed() {\r\n fn();\r\n timeout = null;\r\n }\r\n timeout = setTimeout(delayed, threshold || 100);\r\n };\r\n}", "function debounce(callback){\n var queued = false;\n return function () {\n if(!queued){\n queued = true;\n setTimeout(function () {\n queued = false;\n callback();\n }, 0);\n }\n };\n}", "function debounce( fn, threshold ) {\n var timeout;\n return function debounced() {\n if ( timeout ) {\n clearTimeout( timeout );\n }\n function delayed() {\n fn();\n timeout = null;\n }\n setTimeout( delayed, threshold || 100 );\n };\n }", "function debounce( fn, threshold ) {\n var timeout;\n return function debounced() {\n if ( timeout ) {\n clearTimeout( timeout );\n }\n function delayed() {\n fn();\n timeout = null;\n }\n setTimeout( delayed, threshold || 100 );\n };\n}", "function debounce(func,wait,immediate){if(immediate===void 0){immediate=false;}var timeout;var args;var context;var timestamp;var result;var later=function later(){var last=+new Date()-timestamp;if(last<wait){timeout=setTimeout(later,wait-last);}else{timeout=null;if(!immediate){result=func.apply(context,args);context=args=null;}}};return function(){context=this;args=arguments;timestamp=+new Date();var callNow=immediate&&!timeout;if(!timeout){timeout=setTimeout(later,wait);}if(callNow){result=func.apply(context,args);context=args=null;}return result;};}", "function debounce(func, opt_threshold_ms) {\n let timeout;\n return function() {\n let context = this, args = arguments;\n let later = function() {\n timeout = null;\n func.apply(context, args);\n };\n clearTimeout(timeout);\n timeout = setTimeout(later, opt_threshold_ms || DEBOUNCE_THRESH_MS);\n };\n}", "function debounce(f, t) {\n return f;\n}", "function debounce( fn, threshold ) {\n var timeout;\n threshold = threshold || 100;\n return function debounced() {\n clearTimeout( timeout );\n var args = arguments;\n var _this = this;\n function delayed() {\n fn.apply( _this, args );\n }\n timeout = setTimeout( delayed, threshold );\n };\n }", "function debounce( fn, threshold ) {\n var timeout;\n threshold = threshold || 100;\n return function debounced() {\n clearTimeout( timeout );\n var args = arguments;\n var _this = this;\n function delayed() {\n fn.apply( _this, args );\n }\n timeout = setTimeout( delayed, threshold );\n };\n }", "function debounce ( func, wait, immediate ) {\n var timeout;\n return function () {\n var context = this,\n args = arguments;\n clearTimeout(timeout);\n timeout = setTimeout(function () {\n timeout = null;\n if ( !immediate ) {\n func.apply(context, args);\n }\n }, wait);\n if ( immediate && !timeout ) {\n func.apply(context, args);\n }\n };\n }", "function debounce( fn, threshold ) {\n var timeout;\n return function debounced() {\n if ( timeout ) {\n clearTimeout( timeout );\n }\n function delayed() {\n fn();\n timeout = null;\n }\n timeout = setTimeout( delayed, threshold || 100 );\n }\n}", "function debounce( fn, threshold ) {\n var timeout;\n return function debounced() {\n if ( timeout ) {\n clearTimeout( timeout );\n }\n function delayed() {\n fn();\n timeout = null;\n }\n timeout = setTimeout( delayed, threshold || 100 );\n }\n}", "function debounce(func, wait, immediate) { // Debounce function (Bing it if you don't know)\n var timeout;\n return function () {\n var context = this, args = arguments;\n var later = function () {\n timeout = null;\n if (!immediate) func.apply(context, args);\n };\n var callNow = immediate && !timeout;\n clearTimeout(timeout);\n timeout = setTimeout(later, wait);\n if (callNow) func.apply(context, args);\n };\n}", "function debounce(f, waitMs) {\n let lastTime = _tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__[\"util\"].now();\n let lastResult;\n const f2 = (...args) => {\n const now = _tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__[\"util\"].now();\n if (now - lastTime < waitMs) {\n return lastResult;\n }\n lastTime = now;\n lastResult = f(...args);\n return lastResult;\n };\n return f2;\n}", "function debounce(func) {\n var wait = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 10;\n var immediate = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true;\n var timeout;\n return function () {\n var context = this,\n args = arguments;\n\n var later = function later() {\n timeout = null;\n if (!immediate) func.apply(context, args);\n };\n\n var callNow = immediate && !timeout;\n clearTimeout(timeout);\n timeout = setTimeout(later, wait);\n if (callNow) func.apply(context, args);\n };\n }", "function debounce(callback, delay){\n var timer;\n return function(){\n var args = arguments;\n var context = this;\n clearTimeout(timer);\n timer = setTimeout(function(){\n callback.apply(context, args);\n }, delay);\n }\n }", "function debounce(f, ms) {\n\n var timer = null;\n\n return function(...args) {\n var onComplete = function() {\n f.apply(this, args);\n timer = null;\n }\n\n if (timer) {\n clearTimeout(timer);\n }\n\n timer = setTimeout(onComplete, ms);\n };\n}", "function debounce(fn, threshold) {\n var timeout;\n return function debounced() {\n if (timeout) {\n clearTimeout(timeout);\n }\n function delayed() {\n fn();\n timeout = null;\n }\n timeout = setTimeout(delayed, threshold || 100);\n }\n}", "function later() {\n // Nullify the variable that stores unique ID (number) after the\n // timeout passed.\n timeout = null;\n\n // If we set `func` not to run immediately after `debounce` being\n // called, run it anyway after the timeout passed.\n if (!immediate) {\n func.apply(context, args);\n }\n }", "function debounce(func, wait, immediate) {\n var timeout;\n return function() {\n var context = this, args = arguments;\n $timeout.cancel(timeout);\n timeout = $timeout(function() {\n timeout = null;\n if (!immediate) {\n func.apply(context, args);\n }\n }, wait);\n if (immediate && !timeout) {\n func.apply(context, args);\n }\n };\n }", "function debounce(fn, threshold) {\n var timeout;\n return function debounced() {\n if (timeout) {\n clearTimeout(timeout);\n }\n\n function delayed() {\n fn();\n timeout = null;\n }\n timeout = setTimeout(delayed, threshold || 100);\n };\n }", "function debounce(func, delay = 500) {\n let timer\n return () => {\n clearTimeout(timer)\n timer = setTimeout(() => {\n func()\n }, delay)\n }\n }", "function debounce(fn, threshold) {\n var timeout;\n return function debounced() {\n if (timeout) {\n clearTimeout(timeout);\n }\n\n function delayed() {\n fn();\n timeout = null;\n }\n timeout = setTimeout(delayed, threshold || 1000);\n }\n }", "function debounce(fn, ms) {\n // Avoid wrapping in `setTimeout` if ms is 0 anyway\n if (ms === 0) {\n return fn;\n }\n\n var timeout;\n return function (arg) {\n clearTimeout(timeout);\n timeout = setTimeout(function () {\n fn(arg);\n }, ms);\n };\n }" ]
[ "0.7292353", "0.72527575", "0.71959347", "0.704033", "0.70142347", "0.6980934", "0.6979344", "0.6966226", "0.6938462", "0.69089085", "0.6895548", "0.6894507", "0.68416345", "0.6835207", "0.68262565", "0.6819591", "0.68153465", "0.6814475", "0.6814475", "0.6811435", "0.6811435", "0.68103886", "0.6803387", "0.6803387", "0.6803387", "0.6798261", "0.67944866", "0.67639536", "0.67639536", "0.67639536", "0.67639536", "0.67639536", "0.6756591", "0.6756591", "0.6754536", "0.6752133", "0.67465913", "0.6723181", "0.6718218", "0.67141736", "0.667391", "0.667391", "0.667391", "0.667391", "0.667391", "0.667391", "0.667391", "0.667391", "0.667391", "0.667391", "0.667391", "0.667391", "0.667391", "0.6667719", "0.6663557", "0.6663557", "0.6659861", "0.6659861", "0.663771", "0.6617199", "0.6582216", "0.65779877", "0.65463585", "0.65156287", "0.65103745", "0.64723563", "0.64723563", "0.6469604", "0.6435158", "0.64167637", "0.64110476", "0.63792664", "0.63722587", "0.63722587", "0.63722587", "0.63627326", "0.63625914", "0.63379085", "0.63373303", "0.63287145", "0.6317711", "0.63158715", "0.63127685", "0.6310736", "0.6304304", "0.6304304", "0.6296627", "0.62918097", "0.62918097", "0.6291349", "0.62771106", "0.6275936", "0.6270219", "0.62478906", "0.62397677", "0.6238316", "0.6232823", "0.623034", "0.6229213", "0.62207144", "0.6217797" ]
0.0
-1
Util for finding an object by its 'id' property among an array
function findById(a, id) { for (var i = 0; i < a.length; i++) { if (a[i].id == id) return a[i]; } return null; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "getById(array, id){\n let result = false\n array.forEach(object => {\n if(id === object.id){\n result = object\n }\n })\n return result\n }", "function findObById(id, arr) {\n return lodash.find(arr, function(obj) { return obj.id == id });\n }", "function findObjectById(id,arr)\n{\n\tfor(var i = 0; i < arr.length; i++)\n\t\tif(arr[i].id == id) return arr[i];\n\n\treturn false;\n}", "function findById(array, objId) {\n var obj = {};\n\n if (array === null || array.length <= 0) {\n return obj;\n }\n\n var len = array.length;\n var found = false;\n for (var i = 0; i < len && !found; i++) {\n var _obj = array[i];\n if (_obj.id == objId) {\n obj = _obj;\n found = true;\n }\n }\n\n return obj;\n }", "elementoById(id, array){\r\n return array.find((ele) => ele.getId() === id);\r\n }", "function searchByID(array, id) {\n for (var i = 0; i < array.length; i++) {\n if (array[i].id == id)\n return array[i];\n }\n}", "function lookupByIdProp(array, id) {\n for (var i = 0; i < array.length; i++) {\n if (array[i].id === id) return array[i];\n }\n }", "function indexById(array, id) {\n if (!array) return -1;\n return smartIndexOf(array, function (obj) {\n return obj.id === id;\n });\n}", "function find_object_by_id_in_a_list(data, id) {\n var object;\n $.each(data, function(key, value) {\n if (value.id == id) {\n object = value;\n }\n });\n return object;\n }", "function findById(someArray, someId) {\n for (let i = 0; i < someArray.length; i++) {\n const item = someArray[i];\n\n if (item.id === someId) {\n return item;\n }\n }\n}", "function getById(arr, id) {\n\t for (var d = 0, len = arr.length; d < len; d += 1) {\n\t if (arr[d].id == id) /* Bilo je 3 === */ {\n\t return arr[d];\n\t }\n\t }\n\t}", "function findById( items, id ) {\n for ( i = 0; i < items.length; i++ ) {\n if ( items[ i ].id === id ) {\n return items[ i ];\n }\n }\n }", "function getbyId (index, arr) {\n\t\t\tvar i = 0;\n\t\t\tindex = index.toString();\n\n\t\t\twhile (i < arr.length) {\n\t\t\t\tif (arr[i].id === index) {\n\t\t\t\t\treturn arr[i];\n\t\t\t\t}\n\n\t\t\t\ti += 1;\n\t\t\t}\n\n\t\t}", "function findById(source, id) {\n try {\n var resultObj = undefined;\n for (var i = 0; i < source.length; i++) {\n if (source[i].id == id)\n resultObj = source[i];\n }\n return resultObj;\n } catch (e) {\n console.log(\"err findById : \" + e);\n }\n }", "function arrayItemById(arr, id) {\n // Find JSON item in arrray by id property\n for (var i = 0; i < arr.length; i++) {\n if (arr[i].id === id) {\n return arr[i];\n }\n }\n return null;\n}", "function findById(id, animalsArray) {\n const result = animalsArray.filter(animal => animal.id === id)[0];\n return result;\n}", "function findbyId(id) {\r\n var record = arrayOfObj.filter(function (i) { return i.id === id; });\r\n console.log(record);\r\n}", "function searchID(_id,list){\n for (let i = 0; i < list.length; i++){\n if (list[i]._id == _id){\n return list[i];\n }\n }\n return undefined;\n}", "function _find( items, id ) {\n for ( var i=0; i < items.length; i++ ) {\n if ( items[i].id == id ) return i;\n }\n }", "function myFindId(list, id)\n{\n return _.find(list, function(obj)\n {\n return obj.id == id\n });\n}", "function findObjectById(list, id){\n if(!list){\n return null;\n }\n \n for(var i = 0; i < list.size(); i++){\n if(list.get(i).id == id){\n return list.get(i);\n }\n }\n\n return null;\n}", "function pesquisarArray(array, id) {\n return _.findWhere(array, {\n _id: id\n });\n }", "function findObjectById(list, id){\r\n\tif(!list){\r\n\t\treturn null;\r\n\t}\r\n\t\r\n\tfor(var i = 0; i < list.size(); i++){\r\n\t\tif(list.get(i).id == id){\r\n\t\t\treturn list.get(i);\r\n\t\t}\r\n\t}\r\n\r\n\treturn null;\r\n}", "function findItemById(items, id) {\n for (let item of items) {\n if (item._id === id) {\n return item;\n }\n }\n\n return false;\n}", "buscarIndex(id,array){\r\n return array.findIndex((elem) => elem.getId() === id);\r\n }", "function findById(id, notesArray) {\n const result = notesArray.filter(note => note.id === id)[0];\n return result; \n}", "function getById(arr, id) {\n for (var d = 0, len = arr.length; d < len; d += 1) {\n if (arr[d].team_id == id) /* Bilo je 3 === */ {\n return arr[d];\n }\n }\n }", "getItemById(items, targetId, idProp) {\n var results = $.grep(items, (item) => {\n return item['_id' || idProp] === targetId\n })\n return (results && results[0]) || null\n }", "function findById (id, notesArray) {\n const result = notesArray.filter(note => note.id === id)[0];\n return result;\n}", "function testItem(id, arr) {\r\n for (let i = 0; i < arr.length; i++) {\r\n if (arr[i].id === id) {\r\n return true;\r\n }\r\n }\r\n}", "function findById(items, idNum) {\n return items.find( (element) => element.id === idNum );\n}", "function findItemById(items, id) {\n\t\t\t\n\t\t\tfor (var i=0; i<items.length; i++){\n\t\t\t\tif (items[i].artid === id) { //property must match name in db here\n\t\t\t\t\treturn items[i];\t\t//return one object\n\t\t\t\t}\n\t\t\t}\n\t\t}", "function containsObject(id, list) {\n\tfor (let i = 0; i < list.length; i++) {\n\t\tif (list[i].id == id) {\n\t\t\treturn true;\n\t\t}\n\t}\n\treturn false;\n}", "function findById(id, notesArray) {\n const result = notesArray.filter(note => note.id === id)[0];\n return result;\n}", "function findById(id, notesArray) {\n const retrieve = notesArray.filter(notes => notes.id === id)[0];\n return retrieve;\n}", "function find(id) {\n // eslint-disable-next-line eqeqeq\n return data.find(q => q.id == id);\n}", "function findBookById(books, id) {\n //2 parameters: array of books, id of single book\n //.find function to find book object with matching id\n let found = books.find(book => book.id === id);\n //return found book\n return found;\n}", "function findById(id, tasksArray){\n const result = tasksArray.filter(task => task.id === id)[0];\n return result;\n}", "function temukanItem(id, array) {\n const i = array.findIndex( item => item.ID == id)\n return array[i]\n}", "function getProductByID(productArray, id) {\n return productArray.find(function (product) {\n return product.id == id;\n });\n}", "function findId(object) {\n return object.id\n }", "function findIndex(array, id) {\n var low = 0, high = array.length, mid;\n while (low < high) {\n mid = (low + high) >>> 1;\n array[mid]._id < id ? low = mid + 1 : high = mid\n }\n return low;\n }", "function findById(index, id) {\n\t\t\tif (index < 0 || index >= vrWebGLArrays.length) \n\t\t\t\tthrow \"ERROR: The provided index '\" + index + \"' is out of scope.\";\n\t\t\tvar obj = null;\n\t\t\tvar vrWebGLArray = vrWebGLArrays[index];\n\t\t\tfor (var i =0; !obj && i < vrWebGLArray.length; i++) {\n\t\t\t\tobj = vrWebGLArray[i];\n\t\t\t\tif (obj.id !== id) {\n\t\t\t\t\tobj = null;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn obj;\n\t\t}", "function findIndex(array, id) {\n var low = 0, high = array.length, mid;\n while (low < high) {\n mid = (low + high) >>> 1;\n array[mid]._id < id ? low = mid + 1 : high = mid\n }\n return low;\n }", "function findIndex(array, id) {\n var low = 0, high = array.length, mid;\n while (low < high) {\n mid = (low + high) >>> 1;\n array[mid]._id < id ? low = mid + 1 : high = mid\n }\n return low;\n }", "function findIndex(array, id) {\n var low = 0, high = array.length, mid;\n while (low < high) {\n mid = (low + high) >>> 1;\n array[mid]._id < id ? low = mid + 1 : high = mid\n }\n return low;\n }", "function contains(a, obj) {\n for (var i = 0; i < a.length; i++) {\n if (a[i].data.id == obj.data.id) {\n return true;\n }\n }\n return false;\n }", "function contains(a, obj) {\n for (var i = 0; i < a.length; i++) {\n if (a[i].data.id == obj.data.id) {\n return true;\n }\n }\n return false;\n }", "function findIndex(array, id) {\n\t\tvar low = 0,\n\t\t\thigh = array.length,\n\t\t\tmid;\n\t\twhile (low < high) {\n\t\t\tmid = (low + high) >>> 1;\n\t\t\tarray[mid]._id < id ? low = mid + 1 : high = mid;\n\t\t}\n\t\treturn low;\n\t}", "function findIndex(id, objs){\n\t\t\tfor(var i = 0; i < objs.length; i++){\n\t\t\t\tvar obj = objs[i];\n\t\t\t\tif(obj && obj.id === id){\n\t\t\t\t\treturn i;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn -1;\n\t\t}", "function getElement(arr, id, idName) {\r\n if (!idName)\r\n idName = \"id\";\r\n for (var i=0; i<arr.length; i++) {\r\n if (arr[i][idName] == id)\r\n return arr[i];\r\n }\r\n return null;\r\n}", "function filterIndexById(input, id) {\n var i=0, len=Object.size(input);\n for (i=0; i<len; i++) {\n if (input[i]._id == id) {\n return input[i];\n }\n }\n }", "function find(list, id) {\n for (let i = 0; i < list.length; i++) {\n const img = list[i];\n if (img.id === id) return img;\n }\n return null;\n}", "function indexOf(item, array) {\n if (typeof item == 'undefined' || typeof array == 'undefined' || array.length <= 0) {\n return -1;\n }\n\n if (typeof item.id == 'undefined') {\n return -1;\n }\n\n var length = array.length;\n var index = -1;\n for (var i = 0; i < length; i++) {\n if (item.id === array[i].id) {\n index = i;\n break;\n }\n }\n\n return index;\n }", "function getObject(theObject, id) {\n var result = null;\n if (theObject instanceof Array) {\n for (var i = 0; i < theObject.length; i++) {\n result = getObject(theObject[i], key);\n if (result) {\n break;\n }\n }\n }\n else {\n for (var prop in theObject) {\n //console.log(prop + ': ' + theObject[prop]);\n if (prop == 'id') {\n if (theObject[prop] == key) {\n return theObject;\n }\n }\n if (theObject[prop] instanceof Object || theObject[prop] instanceof Array) {\n result = getObject(theObject[prop], key);\n if (result) {\n break;\n }\n }\n }\n }\n return result;\n }", "indexContainingID(currentArray, id) {\n for (let i = 0; i < currentArray.length; i++) {\n if (JSON.stringify(currentArray[i]).includes(id)) {\n return i;\n }\n }\n return -1;\n }", "function mustBeInArray(array, id) {\n return new Promise((resolve, reject) => {\n // compare id passed in with the id in the array\n const row = array.find(r => r.id == id)\n if (!row) {\n reject({\n message: 'record does not exist',\n })\n }\n resolve(row)\n })\n}", "function findCard(id, cardsArray) {\n for (const card of cardsArray) {\n if (card.id == id) {\n return card;\n }\n }\n }", "function getID(array, key) {\n let index = array\n .map(function (e) {\n return e.name;\n })\n .indexOf(key);\n return array[index].id;\n}", "function getItem(item, id) {\n for( var i = 0; i < item.length; i++){\n\n if(id == item[i].id){\n return item[i];\n }\n }\n}", "function animalsByIds(...ids) {\n const spreadedArray = ids;\n const result = [];\n spreadedArray.forEach((id) => {\n result.push(animals.find((animal) => animal.id === id));\n });\n return result;\n}", "function returnObjectById(id){\n\n return selectableObjects.find(object=> object.id == id)\n}", "item(id) {\n const list = this.get('list') || [];\n return list.find((i) => i.id === id || i.email === id);\n }", "indexOfId(id) {\n for (let index = 0; index < this.items.length; index++) {\n if (this.items[index].id === id) return index;\n }\n }", "function find_playerid(id) {\n for (var i = 0; i < player_lst.length; i++) {\n if (player_lst[i].id == id) {\n return player_lst[i]; \n }\n }\n \n return false; \n}", "function getRecordById(recordArray, recordId){\n for(var i=0; i<recordArray.length; i++){\n if(recordArray[i].id == recordId){\n var record = recordArray[i];\n return record;\n }\n }\n}", "function containsObject(obj, list) {\n\n var i;\n for (i = 0; i < list.length; i++) {\n if (list[i].id === obj.id) {\n return list.indexOf(list[i]);\n }\n }\n return -1;\n\n}", "function containsObject(obj, list) {\n var i;\n for (i = 0; i < list.length ; i++) {\n if ( list[i].id === obj.id ) {\n return i;\n }\n }\n return -1;\n }", "function getUserById(arr, id, cb){\n arr.forEach(function(input, i){\n if (input.id === id){\n cb(arr[i]);\n }\n });\n}", "function findplayerbyid (ids) {\n for (var i = 0; i < enemies.length; i++) {\n if (enemies[i].id == ids) {\n return enemies[i]; \n }\n }\n }", "function find_playerid(id) {\r\n\r\n\tfor (var i = 0; i < player_lst.length; i++) {\r\n\r\n\t\tif (player_lst[i].id == id) {\r\n\t\t\treturn player_lst[i]; \r\n\t\t}\r\n\t}\r\n\t\r\n\treturn false; \r\n}", "function findById(id) {\n return store.items.find(item => item.id === id);\n }", "function find_playerid(id) {\r\n\r\n\tfor (var i = 0; i < player_lst.length; i++) {\r\n\r\n\t\tif (player_lst[i].id == id) {\r\n\t\t\treturn player_lst[i]; \r\n\t\t}\r\n\t}\r\n\tthrow \"Player not found\"\r\n}", "function getById(id) {\n for (let i = 0; i < allListings.length; i += 1) {\n if (id === allListings[i].id) {\n return allListings[i];\n }\n }\n return null;\n}", "function isIdInUse(id, idArray) {\n let found = idArray.find((element) => {\n return element.userId == id;\n });\n return found ? true : false;\n}", "function findById(id) {\n console.log('###EXECUTING User_findById');\n console.log(_.contains(_.pluck(users, 'id'), id));\n\tconsole.log(id);\n \n console.log(_.contains(_.pluck(users, 'id'), username));\n\tif(_.contains(_.pluck(users, 'id'), username)){\n\t\tconsole.log('id found');\n\t\treturn(id);\n\t}\n\telse {\n\t\tconsole.log('id not found'); \n\t\treturn(_.contains(_.pluck(users, 'id'), id));\n\t}\n // return _.find(users, function(user) { return user.id === id }); // this was the orig code\n}", "function existsId(id, arr) {\n // console.debug(`isWatched focused--${id}`, arr.some(item => item === id));\n return arr.some(item => item === id);\n }", "function getAttrId(arr, attr, id) {\n for (var i = 0; i < arr.length; i++) {\n if (arr[i]._id === id) {\n return i;\n }\n }\n}", "function findById(id) {\n return _.find(entities, { '_id': id });\n }", "function searchbyID(idKey, myArray) {\n for (var i = 0; i < myArray.length; i++) {\n if (myArray[i].userID == idKey) {\n return myArray[i];\n }\n }\n }", "function find(array, id, value) {\n for(var i=0,l=array.length; i<l; i++) { if (array[i][id] == value) { return i; } }\n return -1;\n }", "findById(id) {\n for(const annotation of this.set) {\n if (id == annotation.getId()) {\n return annotation;\n }\n }\n return null;\n }", "getProduct(id) {\n let productDetails = [\n {\n id: 1,\n name: 'Car',\n details: 'Car details'\n },\n {\n id: 2,\n name: 'Bike',\n details: 'Bike details'\n },\n {\n id: 3,\n name: 'Bus',\n details: 'Bus details'\n },\n {\n id: 4,\n name: 'Truck',\n details: 'Truck details'\n }\n ];\n return productDetails.find(item => item.id == id);\n }", "function findBookById(books, id) {\n return found = books.find(book=> book.id ===id)\n}", "function includes (array, element) {\n\t\n\tfor (var i = 0; i < array.length; i++) if (array[i].id == element.id) return true;\n\treturn false;\n\t\n}", "function getPerson(id) {\n for (var i = 0; i < peopleArray.length; i++) {\n if (peopleArray[i].id == id) {\n return peopleArray[i];\n }\n }\n return '404';\n}", "function getItemByID(id, items) {\n for (i = 0; i < items.length; i++) {\n if (items[i].ID === id) {\n return items[i];\n }\n }\n }", "function findCatById (id) {\r\n return catArray.find(c => c.id == id);\r\n }", "function getId(object, key, value) {\n for (const id in object){\n if (object[id][key] === value) return id;\n }\n return false;\n}", "function posicion(id, array) {\n var ctl = -1;\n var long = array.length;\n for (var i = 0; i < long; i++) {\n if (array[i] == id) {\n ctl = i;\n return ctl;\n }\n }\n return ctl;\n}", "function getEmployeeById (id) {\n var i;\n for (i = 0; i < employees.length; i++) {\n if (employees[i].id === id) {\n return employees[i];\n }\n }\n\n return undefined\n}", "function getItemByID(data,id){\n\tif (!data) return;\n\tfor (var _item=0; _item< data.length;_item++){\n\t\t\tif (data[_item].id == id){\n\t\t\t\treturn data[_item];\n\t\t\t}\n\t}\n}", "function findUser(userlist, id){\n for (var i in userlist){\n if (userlist[i].uid === id){\n return userlist[i]\n }\n }\n}", "Get(id) {\n\t\treturn this.obj.filter(function(o){return o.id == id;})[0];\n\t}", "function getIndexElemFrom(id, list) {\n for (var index = 0; index < list.length; index++) {\n var element = list[index];\n if (element.id === id) {\n return index;\n }\n }\n }", "getObjectById (id) {\n\n for (var emitters of this.emitters) {\n if (emitters.id === id) {\n return emitters\n }\n }\n\n for (var fields of this.fields) {\n if (fields.id === id) {\n return fields\n }\n }\n\n return null\n }", "function findItemInCart(id) {\n for(var i=0;i < products_cart.items.length; i++){\n if(products_cart.items[i].id == id){\n return {item:products_cart.items[i],index:i};\n }\n }\n}", "function findItemById(data, id) {\n\tlet itemData = data.getIn(['items',id]);\n\tif (itemData) {\n\t\treturn [id,itemData];\n\t}\n\treturn null;\n}", "function matchingId(id) {\n return (el) => el.id === id;\n }", "find(id) {\n if(id) {\n return this.movieList.find(element => {\n return element.id === id;\n });\n }else {\n return this.movieList;\n }\n }" ]
[ "0.81107444", "0.7984318", "0.79724485", "0.7954282", "0.77091575", "0.77081734", "0.75430924", "0.7506697", "0.7496117", "0.74841595", "0.7388143", "0.7360041", "0.7343788", "0.73369175", "0.7206437", "0.71979576", "0.71479046", "0.7137408", "0.7093528", "0.70909756", "0.7031074", "0.70004845", "0.69231546", "0.6879815", "0.68428713", "0.6840813", "0.683723", "0.6805688", "0.6804075", "0.67664886", "0.67624164", "0.6756419", "0.6744632", "0.6736425", "0.67135125", "0.67096573", "0.669093", "0.6673754", "0.6663806", "0.66631156", "0.66461337", "0.66137165", "0.6607136", "0.65983933", "0.6556355", "0.6556355", "0.6551144", "0.6551144", "0.6547666", "0.6522825", "0.6517286", "0.65096086", "0.64973384", "0.6494055", "0.6485185", "0.6465683", "0.6463718", "0.6427301", "0.6427188", "0.6425882", "0.6419405", "0.64192766", "0.6415396", "0.64098674", "0.6395828", "0.6394041", "0.6362023", "0.63475144", "0.6295669", "0.6293347", "0.6289025", "0.62742126", "0.6266477", "0.6263968", "0.6257607", "0.62495774", "0.6248251", "0.62081945", "0.62030625", "0.6198831", "0.61978954", "0.6195955", "0.61915815", "0.6188135", "0.61647207", "0.6156839", "0.6156409", "0.615237", "0.61053056", "0.6104752", "0.6091879", "0.60779846", "0.60676616", "0.60636926", "0.6056318", "0.605421", "0.6049782", "0.6047445", "0.6045085", "0.6032515" ]
0.772842
4
Util for returning a random key from a collection that also isn't the current key
function newRandomKey(coll, key, currentKey) { var randKey; do { randKey = coll[Math.floor(coll.length * Math.random())][key]; } while (randKey == currentKey); return randKey; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function getRandomKey(collection) {\n let keys = Array.from(collection.keys());\n return keys[Math.floor(Math.random() * keys.length)];\n}", "function random_key(keys, exclude) {\n return keys[(keys.indexOf(exclude) + Math.floor(Math.random() * (keys.length - 1)) + 1) % keys.length];\n }", "_selectUnpickedKey(){\n const values = Array.from(this.unpickedKeys);\n let randomIndex = Math.floor(Math.random() * this.unpickedKeys.size);\n return values[randomIndex];\n }", "function getRandomElementFrom(collection) {\n\n var itemNumber = Math.floor(Math.random() * collection.length);\n return collection[itemNumber];\n}", "function randkey(obj){\n var rand = Math.floor(Math.random()*obj.length)\n return rand}", "function sample(collection) {\n if (collection instanceof Array) {\n let size = array.length;\n let indx = Math.floor(Math.random() * size);\n return collection[indx]\n }\n let k = Object.keys(collection);\n let randIndx = Math.floor(Math.random() * k.length);\n return collection[k[randIndx]]\n}", "getRandomKey () {\n return Math.random() * (1000000 - 100) + 100\n }", "function getRandomKey(menuItemsLength) {\n return Math.floor(Math.random() * menuItemsLength) + 1;\n}", "function getKey(arr){\n keyIndex = Math.floor(Math.random()*arr.length);\n console.log(arr[keyIndex]);\n return arr[keyIndex];\n }", "function getRandomKey(menuItemsLength) {\n return Math.floor(Math.random() * (menuItemsLength - 1) + 1);\n}", "function makeKey () {\n var r = Math.floor(Math.random() * options.num)\n , k = keyTmpl + r\n return k.substr(k.length - 16)\n}", "function randomProperty(obj, needKey) {\n var keys = Object.keys(obj)\n\n if (!needKey) {\n return obj[keys[keys.length * Math.random() << 0]];\n } else {\n return keys[keys.length * Math.random() << 0];\n }\n}", "function getRandomElementFromArray(collection) {\n return collection[Math.floor(Math.random() * collection.length)];\n}", "function getRandomElementFromArray(collection) {\n return collection[Math.floor(Math.random() * collection.length)];\n}", "function getRandomKey() {\n return apiKeyBank[Math.floor(Math.random() * apiKeyBank.length)];\n}", "function generateKey() { return 10*Math.random();}", "function getRandomPantone(){\n const keys = Object.keys(pantoneColors)\n // Generate random index based on number of keys\n const randIndex = Math.floor(Math.random() * keys.length)\n // Select a key from the array of keys using the random index\n const randKey = keys[randIndex]\n // Use the key to get the corresponding name from the \"names\" object\n const name = pantoneColors[randKey]\n return name;\n}", "function getByUnique (collection, key) {\n var index = collection + ':' + key\n\n return function (value, options, callback) {\n var Model = this\n var client = Model.__client\n\n if (!callback) {\n callback = options\n options = {}\n }\n\n client.hget(index, value, function (err, id) {\n if (err) { return callback(err) }\n\n Model.get(id, options, function (err, instance) {\n if (err) { return callback(err) }\n callback(null, instance)\n })\n })\n }\n}", "function getNewWord() {\n\n \n var startAt = Math.floor(Math.random() * words.size)\n\n\n //Assign starting word\n var iter = words.keys()\n var newShit = \"\"\n var pos = 0\n for(var w of iter) {\n newShit = w\n if(pos === startAt) break\n pos++\n }\n\n return newShit\n\n}", "key(item) {\n return item;\n }", "function getRandomWord () {\n var rand = Math.floor(Math.random() * Object.keys(dict).length);\n return Object.keys(dict)[rand];\n}", "function selectScnd (chain, key) {\n var len = chain.tableLen.scnd[key] || 1\n var idx = Math.floor(Math.random() * len)\n\n var t = 0\n for (var token in chain.scnd[key]) {\n t += chain.scnd[key][token]\n if (idx < t) {\n return token\n }\n }\n return '~'\n}", "function make_key() {\n return Math.random().toString(36).substring(2,8);\n }", "function retakeQuiz() {\n return setKey(Math.random());\n }", "function isUnique(currentKey) {\n if (currentKey === globalKey) {\n return \"\";\n } else {\n globalKey = currentKey;\n return currentKey;\n }\n}", "function defaultKey (elem) { return elem }", "function randomKey() {\n var randKey = '';\n for (var i = 0; i < 100; i++) {\n randKey += String.fromCharCode(Math.floor(Math.random() * (122 - 97 + 1)) + 97);\n };\n return randKey;\n}", "function random() {\n randomNum = Math.floor(Math.random() * 6 + 1);\n console.log(\"KeyNum is \" + randomNum);\n}", "function randomCategory() {\n const keys = Object.keys(originals)\n return keys[Math.floor(Math.random() * keys.length)]\n}", "getRandom() {\n return this.get(Math.floor(Math.random() * (this.size() - 1)));\n }", "function random(){\n return random.get();\n }", "function random(){\n return random.get();\n }", "function getRandomEvent(possibleList) {\r\n\tvar S = 0;\r\n\tfor (var key in possibleList) {\r\n\t\tS += possibleList[key];\r\n\t}\r\n\tvar R = Math.floor(Math.random() * S); \r\n\tvar T = 0;\r\n\tfor (var key in possibleList) {\r\n\t\tT += possibleList[key];\r\n\t\tif (T > R) {\r\n\t\t\treturn key;\r\n\t\t}\r\n\t}\r\n}", "getRandomId(currentId, max) {\n const id = this.getRandom(0, max); \n\n // don't want a repeated piece on the next quote\n if (id === currentId) {\n return this.getRandomId(currentId, max);\n } else {\n return id;\n }\n }", "function pickQuestion(){\n\n var random_question_id = Math.floor((Math.random() * questions_array.length ));\n while(_.contains(already_picked_questions,random_question_id.toString())){\n\n random_question_id = Math.floor((Math.random() * questions_array.length ));\n\n }\n if (random_question_id == 0){\n var is_contained = _.contains(already_picked_questions, \"15\");\n console.log(is_contained);\n if ( is_contained == false){\n var tmp_picked_question = \"15\";\n return random_question_id;\n }\n else {\n pickQuestion()\n }\n\n }\n\n\n return random_question_id;\n\n }", "key() { }", "function findUniqueKey(){\n let key\n\n //check unique key\n let next = true\n while(next){\n key = uniqid()\n Users.findOne({\n where:{\n referralKey: key\n }\n })\n .then((user)=>{\n if(!user){\n next = false\n }\n })\n }\n return key\n}", "function getRandomIndex() {\n return Math.floor(Math.random() * Product.all.length);\n}", "function random_item(items) {\n\n return items[Math.floor(Math.random() * items.length)];\n\n}", "function singleKey(map) {\n var id, counter = 0, ret;\n for(id in map) {\n if(map.hasOwnProperty(id)) {\n if( counter !== 0) {\n ret = undefined;\n break;\n }\n counter++;\n ret = id;\n }\n }\n\n return ret;\n }", "function defaultKeyGetter(item) {\n return item;\n}", "function defaultKeyGetter(item) {\n return item;\n}", "function defaultKeyGetter(item) {\n return item;\n}", "function defaultKeyGetter(item) {\n return item;\n}", "function defaultKeyGetter(item) {\n return item;\n}", "function generateRandomNumber() {\n newRandomNumber = Math.floor(Math.random()*Object.keys(current_dict).length);\n return newRandomNumber;\n}", "function getOneProduct(){ \n var randomDisplay = Math.floor(Math.random() * SurveyItems.productList.length);\n var getItem = SurveyItems.productList[randomDisplay];\n\n return getItem; \n}", "function randomChoices(keyArray, numToGet) {\n\t\tvar chosen = [],\n\t\t total = keyArray.length,\n\t\t i = 0,\n\t\t number, randKey, inSet;\n\n // check there's actually some documents in the database\n if(total == 0) {\n return;\n }\n // check we have enough documents otherwise the do/while\n // loop will never return\n total < numToGet ? number = total : numToGet\n\n\t\t do {\n\t randKey = keyArray[randomInt(0, total)];\n\t // check if key already in chosen\n\t\t \t inSet = chosen.some(function(key){\n\t\t\t \t\t return randKey == key;\n\t\t\t \t });\n\n\t\t \t if(!inSet) {\n\t\t \t\t chosen.push(randKey);\n\t\t \t\t i += 1;\n\t\t \t }\n\t\t } while(i < number);\n\n\t\trandomQuery(chosen);\n\t}", "function pickRandomIn(collection, count) {\n let array = collection;\n // convert object to array of object values\n if (!Array.isArray(collection) && typeof collection === 'object') {\n array = Object.values(collection);\n }\n // bound array size to 'count'\n count = count > array.length ? array.length : count;\n const pickedIdx = [];\n let randIdx;\n while (pickedIdx.length < count) { // pick until 'count' is reached\n do { // get random array index not picked before\n randIdx = Math.floor(Math.random() * array.length);\n } while (pickedIdx.indexOf(randIdx) !== -1);\n pickedIdx.push(randIdx);\n }\n return pickedIdx.map(idx => array[idx]); // map array items back according to indices\n}", "function getRandomChar() {\n \n return pool[Math.floor(Math.random() * Object.keys(pool).length)] \n \n}", "function generateRandomIndex() {\n\n return Math.floor(Math.random() * Product.allProducts.length);\n}", "function pickword(dictionary) {\n return dictionary[Math.floor(Math.random() * (dictionary.length - 1))];\n }", "function key() {\n\tvar hashName = _.result( this, 'hashAttribute' ) || _.result( this, 'idAttribute' ),\n\t\trangeNake = _.result( this, 'rangeAttribute' );\n\n\treturn this.pick( hashName, rangeNake );\n}", "function getRandom() {\n const rand = Math.ceil(Math.random() * (sizeX * sizeY));\n if (mineMap.hasOwnProperty(rand)) {\n return getRandom();\n }\n return rand;\n }", "function karteGenerieren() {\r\n /* Eine beliebige Zahl wird mit der Länge multipliziert und die Karte nehmen wir*/\r\n let random = Math.floor(Math.random() * alle32Karten.length);\r\n console.log('random Number: ' + random);\r\n let karte = alle32Karten[random];\r\n alle32Karten.splice(random, 1);\r\n return karte;\r\n}", "function nextKey () {\n return (uniqueId++) + dataStoreKeyExpandoPropertyName\n }", "genId(collection, collectionName) {\n const genId = this.bind('genId');\n if (genId) {\n const id = genId(collection, collectionName);\n if (id != null) {\n return id;\n }\n }\n return this.genIdDefault(collection, collectionName);\n }", "random() {\n\t\treturn this.at(Math.floor(Math.random() * this.size()));\n\t}", "function generateKey(){\n return Math.random().toString(36).substr(-8)\n}", "function randomClient() {\n // var objectLength = Object.keys(clients).length;\n var selected = clients[Math.floor(Math.random()*clients.length)];\n console.log('selected object ' + selected);\n return selected;\n}", "function random(){\n\t return random.get();\n\t }", "function random(){\n\t return random.get();\n\t }", "getKey() {\n return container[idx]\n }", "function getRandomArrItem(arr) {\n var random = Math.floor(Math.random() * arr.length);\n return arr[random];\n}", "function getRandomIndex() {\n return Math.floor(Math.random() * allProducts.length);\n}", "function randomItem(arr) {\n return arr[Math.floor(Math.random()*arr.length)]\n}", "\"personality.getRandomQuestion\"() {\n if (Meteor.isServer) {\n const fetchedQuestion = Personality.rawCollection()\n .aggregate([\n { $sample: { size: 1 } }, // Select 1 document from collection.\n {\n $project: {\n item: {\n $arrayElemAt: [\n \"$items\",\n {\n $floor: { $multiply: [{ $size: \"$items\" }, Math.random()] },\n },\n ],\n },\n },\n },\n ])\n .toArray();\n return fetchedQuestion;\n }\n }", "function pickRandomProperty(obj) {\n\t var keys = Object.keys(obj)\n \treturn keys[ keys.length * Math.random() << 0];\n\t}", "function randomVal(obj) {\n var ret;\n var c = 0;\n for (var key in obj)\n if (Math.random() < 1/++c)\n ret = key;\n return obj[ret];\n}", "function getRandomIndex() {\n // 0=>18\n return Math.floor(Math.random() * (products.length));\n}", "getKey() {\n // return last keys as reference\n return this.keys[this.keys.length - 1];\n }", "function getRandomItem(arr) {\n\treturn arr[Math.floor(Math.random() * arr.length)];\n}", "function createNewUniqueKey(existingKeys) {\n\t // The base of the key is the current time, in milliseconds since epoch.\n\t var base = \"\" + new Date().getTime();\n\t if (!existingKeys.includes(base)) {\n\t return base;\n\t }\n\n\t // But, if the user is a fast-clicker or time-traveler or something, and\n\t // already has a highlight from this millisecond, then let's attach a\n\t // suffix and keep incrementing it until we find an unused suffix.\n\t var suffix = 0;\n\t var key = void 0;\n\t do {\n\t key = base + \"-\" + suffix;\n\t suffix++;\n\t } while (existingKeys.includes(key));\n\n\t return key;\n\t}", "get key(): string {\n return this.data._id || \"concept\";\n }", "function _makeRandomItem() {\n\tvar ran = Math.floor(Math.random() * 200);\n\tif(ran < 4) {\n\t\treturn ran;\n\t} else {\n\t\treturn -1;\n\t}\n}", "function createNewUniqueKey(existingKeys) {\n // The base of the key is the current time, in milliseconds since epoch.\n var base = \"\".concat(new Date().getTime());\n\n if (!existingKeys.includes(base)) {\n return base;\n } // But, if the user is a fast-clicker or time-traveler or something, and\n // already has a highlight from this millisecond, then let's attach a\n // suffix and keep incrementing it until we find an unused suffix.\n\n\n var suffix = 0;\n var key;\n\n do {\n key = \"\".concat(base, \"-\").concat(suffix);\n suffix++;\n } while (existingKeys.includes(key));\n\n return key;\n}", "function randItem(selectedArray) {\n return selectedArray[Math.floor(Math.random()*selectedArray.length)];\n}", "static selectRandomSeededItem(seed, arrList) {\r\n seedrandom(seed, { global: true });\r\n let randItem = Math.floor(Math.random() * arrList.length);\r\n return arrList[randItem];\r\n }", "function withRandom(keypath, func, seedOffset) {\n if (seedOffset === void 0) { seedOffset = 0; }\n faker.seed(seedFromKeypath(keypath.map(function (_a) {\n var fieldIndex = _a.fieldIndex, responseName = _a.responseName;\n return keyPathElement(responseName, fieldIndex);\n })) + seedOffset);\n var value = func();\n faker.seed(Math.random() * 10000);\n return value;\n}", "function rand_element(list){ return list[Math.floor(Math.random() * list.length)]; }", "function thingSingular() {\n let a = Math.floor(Math.random() * things.length)\n let thing = things[a].singular\n return thing\n}", "getKeys() {\n errors.throwNotImplemented(\"returning the keys of a collection\");\n }", "get key()\n\t{\n\t\tvar priv = PRIVATE.get(this);\n\t\treturn priv.key;\n\t}", "get(key) {\n\t\treturn key in this.collection ? this.collection[key] : null;\n\t}", "function randomItem(arr) {\n return arr[Math.floor(arr.length*Math.random())];\n}", "function r(item){\n var rand=Math.floor(Math.random()*item.length);\n return rand;\n}", "function getRandomQuote(){\n var allQuotes = JSON.parse(localStorage['list']);\n var allKeys = Object.keys(allQuotes);\n var randomKey = allKeys[Math.floor(allKeys.length * Math.random())];\n //console.log(randomKey);\n var randomQuote = allQuotes[randomKey];\n //console.log(randomQuote);\n return randomQuote;\n }", "get key() {\n return itKey;\n }", "function chooseKnot(list) {\n\n // protecting against a null or empty list being tossed in\n if (list === null || list.length === 0) {\n throw new Error(\"The list cannot be empty\");\n }\n\n var randomIndex = randomNumber(0, list.length - 1);\n\n return list[randomIndex];\n}", "function getRandomIndex() {\n // 0=>20\n return Math.floor(Math.random() * products.length);\n}", "random (items) {\n return items[Math.floor(Math.random() * items.length)]\n }", "function revocationKey() {\n return [...Array(10)].map(() => Math.random().toString(36)[2]).join('');\n}", "function randomTwiddle_(key) {\n key += ~(key << 15);\n key ^= (key >> 10);\n key += (key << 3);\n key ^= (key >> 6);\n key += ~ (key << 11);\n key ^= (key >> 16);\n return key;\n}", "randomSuitName(){\n// Pointer to a random suit\nconst randomSuitIdx = Math.floor(Math.random()*this.remainingSuitNames.length);\n// suit key\nconst randomSuitName = this.remainingSuitNames[randomSuitIdx];\n// Preserve randomSuitName for future usage\n// this.randomBldgBlocks.randomSuitName = randomSuitName; \nreturn randomSuitName; //this.randomBldgBlocks.randomSuitName;\n }", "randomSuitName(){\n// Pointer to a random suit\nconst randomSuitIdx = Math.floor(Math.random()*this.remainingSuitNames.length);\n// suit key\nconst randomSuitName = this.remainingSuitNames[randomSuitIdx];\n// Preserve randomSuitName for future usage\n// this.randomBldgBlocks.randomSuitName = randomSuitName; \nreturn randomSuitName; //this.randomBldgBlocks.randomSuitName;\n }", "function pick() {\r\n index = Math.floor(Math.random() * words.length);\r\n return words[index];\r\n}", "function randomIndexOf(arr) {\n if(arr.length < 1) return -1;\n return Math.floor(Math.random() * arr.length);\n}", "function getRandomItem(arr){\n let num = Math.floor(Math.random() * arr.length)\n return arr[num];\n}", "function getRandomItem(array) {\n return array[Math.floor(Math.random() * array.length)];\n}", "getRandomId() {\n // window.msCrypto for IE 11\n return (window.crypto || window.msCrypto).getRandomValues(\n new Uint32Array(1)\n )[0];\n }" ]
[ "0.8389413", "0.68432087", "0.6811147", "0.67932403", "0.6725988", "0.6545734", "0.6388025", "0.6319874", "0.6290437", "0.6268335", "0.6037222", "0.6012711", "0.5913117", "0.5913117", "0.5829245", "0.5797225", "0.57566464", "0.57423174", "0.5731292", "0.57159156", "0.57056063", "0.568358", "0.5681676", "0.56766325", "0.56745404", "0.5608083", "0.55848897", "0.557674", "0.5563508", "0.5557661", "0.5555827", "0.5555827", "0.5533458", "0.5526929", "0.5524953", "0.5519985", "0.5507559", "0.5505314", "0.5497229", "0.54662836", "0.54614854", "0.54614854", "0.54614854", "0.54614854", "0.54614854", "0.54559606", "0.54546213", "0.54481053", "0.54372", "0.5432897", "0.5431166", "0.54296565", "0.54251796", "0.5414558", "0.54144865", "0.5407375", "0.53962237", "0.53908557", "0.5380393", "0.5378663", "0.53736687", "0.53736687", "0.53660184", "0.53602964", "0.53570974", "0.5352242", "0.5339399", "0.5337999", "0.53269976", "0.53180647", "0.5302737", "0.5300325", "0.5298521", "0.529153", "0.5287246", "0.5278259", "0.5276598", "0.5270401", "0.52695394", "0.5261966", "0.5257734", "0.5247878", "0.5245557", "0.5243923", "0.52389306", "0.52370095", "0.52363807", "0.5233276", "0.5232975", "0.52291244", "0.5226094", "0.52164024", "0.5215428", "0.52150476", "0.52150476", "0.5214754", "0.5214599", "0.52099913", "0.51979893", "0.518731" ]
0.7995288
1
Merge browser pack, browserify, and CodePaths options with some default options to create full browserify options. Default options are: extensions: [".js", ".jsx"] entries: [opts.entryFile]
function createOptions(opts, paths, plugins) { var defaults = { debug: opts.debug, entries: opts.entries || [paths.entryFile], extensions: opts.extensions || [".js", ".jsx"], paths: paths.srcPaths, plugin: plugins || [], cache: opts.cache || {}, packageCache: opts.packageCache || {}, }; return Object.assign(defaults, opts); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function browserifyThoseApps(options, cb) {\n let entry = options.entry;\n let outfilePattern = options.outfilePattern;\n let dependencies = options.dependencies || [];\n let externals = options.externals || [];\n let watchFiles = options.hasOwnProperty('watchFiles') ? options.watchFiles : false;\n let isProd = options.hasOwnProperty('isProd') ? options.isProd : true;\n\n let bundler = browserify({\n entries: [entry || SRC_DIR + SOURCES.app],\n debug: true,\n cache: {},\n packageCache: {},\n fullPaths: true,\n extensions: ['.js', '.jsx'],\n transform: [\n ['babelify', {\n extensions: ['.js', '.jsx']\n }]\n ]\n });\n _.each(dependencies, function(version, dependency){\n bundler.require(dependency);\n });\n _.each(externals, function(version, dependency){\n bundler.external(dependency);\n });\n\n if(watchFiles) {\n let watcher = watchify(bundler);\n watcher.on('update', updateApp.bind(undefined, bundler, outfilePattern, isProd, function() {}));\n bundler = watcher;\n }\n\n bundleApp(bundler, outfilePattern, isProd, cb);\n}", "function createServeConfig(args, options) {\n let {\n commandConfig: extraConfig = {},\n defaultTitle,\n renderShim,\n renderShimAliases\n } = options;\n\n let entry = _path2.default.resolve(args._[1]);\n let dist = _path2.default.resolve(args._[2] || 'dist');\n let mountId = args['mount-id'] || 'app';\n\n let config = {\n babel: {\n stage: 0\n },\n output: {\n filename: 'app.js',\n path: dist,\n publicPath: '/'\n },\n plugins: {\n html: {\n mountId,\n title: args.title || defaultTitle\n }\n }\n };\n\n if (args.force === true || renderShim == null) {\n config.entry = [entry];\n } else {\n config.entry = [renderShim];\n config.plugins.define = { NWB_QUICK_MOUNT_ID: JSON.stringify(mountId) };\n config.resolve = {\n alias: _extends({\n // Allow the render shim module to import the provided entry module\n 'nwb-quick-entry': entry\n }, renderShimAliases)\n };\n }\n\n if (args.polyfill === false || args.polyfills === false) {\n config.polyfill = false;\n }\n\n return (0, _webpackMerge2.default)(config, extraConfig);\n}", "function createBuildConfig(args, options) {\n let {\n commandConfig: extraConfig = {},\n defaultTitle,\n renderShim,\n renderShimAliases\n } = options;\n\n let entry = _path2.default.resolve(args._[1]);\n let dist = _path2.default.resolve(args._[2] || 'dist');\n let mountId = args['mount-id'] || 'app';\n\n let production = process.env.NODE_ENV === 'production';\n let filenamePattern = production ? '[name].[chunkhash:8].js' : '[name].js';\n\n let config = {\n babel: {\n stage: 0\n },\n devtool: 'source-map',\n output: {\n chunkFilename: filenamePattern,\n filename: filenamePattern,\n path: dist,\n publicPath: '/'\n },\n plugins: {\n html: {\n mountId,\n title: args.title || defaultTitle\n },\n // A vendor bundle can be explicitly enabled with a --vendor flag\n vendor: args.vendor\n }\n };\n\n if (renderShim == null || args.force === true) {\n config.entry = { app: [entry] };\n } else {\n // Use a render shim module which supports quick prototyping\n config.entry = { app: [renderShim] };\n config.plugins.define = { NWB_QUICK_MOUNT_ID: JSON.stringify(mountId) };\n config.resolve = {\n alias: _extends({\n // Allow the render shim module to import the provided entry module\n 'nwb-quick-entry': entry\n }, renderShimAliases)\n };\n }\n\n if (args.polyfill === false || args.polyfills === false) {\n config.polyfill = false;\n }\n\n return (0, _webpackMerge2.default)(config, extraConfig);\n}", "function buildConfig(args) {\n var entry = args._[1];\n var mountId = args['mount-id'] || 'app';\n\n var config = {\n babel: {\n presets: ['inferno'],\n stage: 0\n },\n output: {\n filename: 'app.js',\n path: process.cwd(),\n publicPath: '/'\n },\n plugins: {\n html: {\n mountId,\n title: args.title || 'Inferno App'\n }\n },\n resolve: {\n alias: {\n 'react': 'inferno-compat',\n 'react-dom': 'inferno-compat'\n }\n }\n };\n\n if (args.force === true) {\n config.entry = [_path2.default.resolve(entry)];\n } else {\n // Use a render shim module which supports quick prototyping\n config.entry = [require.resolve('../infernoRunEntry')];\n config.plugins.define = { NWB_INFERNO_RUN_MOUNT_ID: JSON.stringify(mountId) };\n // Allow the render shim module to resolve Inferno from the cwd\n config.resolve.alias['inferno'] = _path2.default.dirname(_resolve2.default.sync('inferno/package.json', { basedir: process.cwd() }));\n // Allow the render shim module to import the provided entry module\n config.resolve.alias['nwb-inferno-run-entry'] = _path2.default.resolve(entry);\n }\n\n if (args.polyfill === false || args.polyfills === false) {\n config.polyfill = false;\n }\n\n return config;\n}", "function readOptions(opts) {\n opts = opts || readCommandLineOptions();\n opts = readFableConfigOptions(opts);\n\n opts.projFile = Array.isArray(opts.projFile) ? opts.projFile : [opts.projFile];\n for (var i = 0; i < opts.projFile.length; i++) {\n var fullProjFile = fableLib.pathJoin(opts.workingDir, opts.projFile[i] || '');\n if (!fableLib.isFSharpProject(fullProjFile)) {\n throw \"Not an F# project (.fsproj) or script (.fsx): \" + fullProjFile;\n }\n if (fs && !fs.existsSync(fullProjFile)) {\n throw \"Cannot find file: \" + fullProjFile;\n }\n }\n\n // Default values & option processing\n opts.ecma = opts.ecma || \"es5\";\n opts.outDir = opts.outDir ? opts.outDir : (opts.projFile.length === 1 ? path.dirname(opts.projFile[0]) : \".\");\n if (opts.module == null) {\n opts.module = opts.rollup ? \"iife\" : \"es2015\";\n }\n if (opts.coreLib) {\n opts.refs = Object.assign(opts.refs || {}, { \"Fable.Core\": opts.coreLib })\n delete opts.coreLib;\n }\n if (opts.refs) {\n for (var k in opts.refs) {\n var k2 = k.replace(/\\.dll$/, \"\");\n if (k !== k2) {\n opts.refs[k2] = opts.refs[k];\n delete opts.refs[k];\n }\n }\n }\n\n // Check version\n var curNpmCfg = fableLib.pathJoin(opts.workingDir, \"package.json\");\n if (!(opts.extra && opts.extra.noVersionCheck) && fs && fs.existsSync(curNpmCfg)) {\n curNpmCfg = JSON.parse(fs.readFileSync(curNpmCfg).toString());\n if (curNpmCfg.engines && (curNpmCfg.engines.fable || curNpmCfg.engines[\"fable-compiler\"])) {\n var semver = require(\"semver\");\n var fableRequiredVersion = curNpmCfg.engines.fable || curNpmCfg.engines[\"fable-compiler\"];\n if (!semver.satisfies(constants.PKG_VERSION, fableRequiredVersion)) {\n throw \"Fable version: \" + constants.PKG_VERSION + \"\\n\" +\n \"Required: \" + fableRequiredVersion + \"\\n\" +\n \"Please upgrade fable-compiler package\";\n }\n }\n }\n\n opts = readBabelOptions(opts);\n opts = readRollupOptions(opts);\n\n return opts;\n}", "function watchFile(opts) {\r\n var bundler = new Browserify(opts.entries, {\r\n cache: {},\r\n packageCache: {},\r\n debug: true,\r\n detectGlobals: false, // dont insert `process`, `global`, `__filename`, and `__dirname`\r\n bundleExternal: false, // dont bundle external modules\r\n plugin: [Watchify]\r\n });\r\n \r\n bundler.on('update', bundle);\r\n\r\n if (opts.skips) {\r\n var skips = opts.skips;\r\n for (var i = 0; i < skips.length; ++i) {\r\n var file = require.resolve(skips[i]);\r\n bundler.ignore(file);\r\n } \r\n }\r\n \r\n function bundle() {\r\n var name = new Date().toTimeString() + ' : browserify for ' + opts.dest + '. ';\r\n console.time(name);\r\n\r\n // append prefix to index.js\r\n var prefix = '';\r\n if (opts.prefix) {\r\n if (typeof opts.prefix === 'function') {\r\n prefix = opts.prefix();\r\n }\r\n else if (typeof opts.prefix === 'string') {\r\n prefix = opts.prefix;\r\n }\r\n }\r\n\r\n bundler.transform(function (file) {\r\n var data = '';\r\n \r\n if (Path.basename(file) === 'index.js') {\r\n data += prefix;\r\n }\r\n\r\n return through(write, end);\r\n\r\n function write (buf) { data += buf; }\r\n function end () {\r\n this.queue(data);\r\n this.queue(null);\r\n }\r\n return;\r\n });\r\n\r\n // do bundle\r\n var b = bundler.bundle();\r\n\r\n b.on('end', function () {\r\n console.timeEnd(name);\r\n });\r\n\r\n b = b.pipe(Fs.createWriteStream(opts.dest));\r\n\r\n // fixed chinese character in source maps\r\n // b = b.pipe(source(Path.basename(opts.dest)))\r\n // .pipe(buffer())\r\n // .pipe(sourcemaps.init({loadMaps: true}))\r\n // .pipe(sourcemaps.write('./'))\r\n // .pipe(gulp.dest(Path.dirname(opts.dest)));\r\n \r\n return b;\r\n }\r\n \r\n return bundle();\r\n}", "function processConfigOptions() {\n if (OPTIONS.base_dir === 'cwd' || OPTIONS.base_dir === './') {\n OPTIONS.base_dir = soi.utils.normalizeSysPath(process.cwd() + '/');\n } else {\n OPTIONS.base_dir = soi.utils.normalizeSysPath(\n path.resolve(process.cwd() + '/', OPTIONS.base_dir) + '/');\n }\n\n if (OPTIONS.dist_dir) {\n OPTIONS.dist_dir = soi.utils.normalizeSysPath(\n path.resolve(OPTIONS.base_dir, OPTIONS.dist_dir) + '/');\n }\n if (OPTIONS.module_loader) {\n OPTIONS.module_loader = soi.utils.normalizeSysPath(\n path.resolve(OPTIONS.base_dir, OPTIONS.module_loader));\n }\n if (OPTIONS.map_file) {\n OPTIONS.map_file = soi.utils.normalizeSysPath(\n path.resolve(OPTIONS.base_dir, OPTIONS.map_file));\n }\n if (OPTIONS.output_base) {\n OPTIONS.output_base = soi.utils.normalizeSysPath(\n path.resolve(OPTIONS.base_dir, OPTIONS.output_base) + '/');\n }\n\n // clean(OPTIONS.dist_dir, function(err) {});\n\n // newly added\n if (OPTIONS.bundles.img) {\n processStaticBundles(OPTIONS.bundles.img);\n }\n\n if (OPTIONS.bundles.swf) {\n processStaticBundles(OPTIONS.bundles.swf);\n }\n\n if (OPTIONS.bundles.htc) {\n processStaticBundles(OPTIONS.bundles.htc);\n }\n\n if (OPTIONS.bundles.font) {\n processStaticBundles(OPTIONS.bundles.font);\n }\n\n if (OPTIONS.bundles.css) {\n processDynamicBundles(OPTIONS.bundles.css);\n }\n\n if (OPTIONS.bundles.js) {\n processDynamicBundles(OPTIONS.bundles.js);\n }\n\n // added default ones, because we don't read in it as first\n // calling soi.config.extend\n soi.config.extend({\n optimizer: OPTIONS\n });\n}", "customOptions({\n __createDll,\n __react,\n __typescript,\n __server,\n __routes,\n __spaTemplateInject,\n ...loader\n }) {\n Object.assign(customOptions, {\n __createDll,\n __react,\n __typescript,\n __server,\n __routes,\n __spaTemplateInject,\n });\n // Pull out any custom options that the loader might have.\n return {\n // Pass the options back with the two custom options removed.\n loader,\n };\n }", "function prepareEntryFile(opts, require) {\n // if there is no require and an entryPath is provided than just use that file directly\n if (!require && opts.entryPath) return opts.entryPath;\n\n const entry = [\n \"`rm -rf /workspace/entry.rb`\",\n require || ''\n ];\n\n if (opts.entryPath) {\n entry.push(`require \"${opts.entryPath}\"`);\n }\n else {\n if (opts.setup) {\n entry.push(`require \"${_outputFileSync(path.join(opts.dir, 'setup.rb'), opts.setup)}\"`);\n // have the file remove itself from the file system after it is loaded, so that it cannot be read by users trying to solve\n entry.push(\"`rm -rf /workspace/setup.rb`\");\n }\n entry.push(`require \"${_outputFileSync(path.join(opts.dir, 'solution.rb'), opts.solution)}\"`);\n if (opts.fixture)\n entry.push(`require \"${_outputFileSync(path.join(opts.dir, 'spec.rb'), opts.fixture)}\"`);\n }\n return _outputFileSync(path.join(opts.dir, 'entry.rb'), entry.join('\\n'));\n}", "function browserifyBundle(filename) {\n\tlet basename = path.basename(filename);\n\tlet jsMapBasename = basename.replace('.js', '.js.map');\n\tutils.def(() => fs.mkdirSync('./dist/js'));\n\n\tlet bundler = browserify({\n\t\tcache: {},\n\t\tpackageCache: {},\n\t\tentries: filename,\n\t\tbasedir: __dirname,\n\t\tdebug: config.isDebugable\n\t});\n\n\tif (isWatching)\n\t\tbundler = watchify(bundler, {poll: true});\n\n\tfunction ownCodebaseTransform (transform) {\n\t\treturn filterTransform(\n\t\t\t\tfile => file.includes(path.resolve(__dirname, paths.scripts.inputFolder)),\n\t\t\ttransform);\n\t}\n\n\tfunction bundle(changedFiles) {\n\t\tlet lintStatus = {};\n\n\t\tlet bundleStream = bundler.bundle()\n\t\t\t.on('error', (err) => {\n\t\t\t\tconsole.log('browserify error:', err);\n\t\t\t})\n\t\t\t.pipe(exorcist('./' + paths.scripts.output + jsMapBasename))\n\t\t\t.pipe(source(filename))\n\t\t\t.pipe(plg.rename({\n\t\t\t\tdirname: ''\n\t\t\t}))\n\t\t\t.pipe(plg.buffer())\n\t\t\t.pipe(config.isProduction ? plg.tap(pipelines.revTap(paths.scripts.output)) : plg.util.noop())\n\t\t\t.pipe(plg.stream())\n\t\t\t.pipe(gulp.dest(paths.scripts.output))\n\t\t\t.pipe(pipelines.livereloadPipeline()());\n\n\t\tif (changedFiles) {\n\t\t\tlet lintStream = lintScripts(changedFiles, lintStatus);\n\n\t\t\treturn merge(lintStream, bundleStream);\n\t\t}\n\n\t\treturn bundleStream;\n\t}\n\n\tbundler\n\t\t.transform(ownCodebaseTransform(babelify), {externalHelpers: true})\n\t\t.transform(ownCodebaseTransform(bulkify))\n\t\t.transform(ownCodebaseTransform(envify))\n\t\t.transform(ownCodebaseTransform(brfs));\n\n\tif (!config.isLogs)\n\t\tbundler\n\t\t\t.transform(stripify);\n\n\tif (config.isProduction)\n\t\tbundler\n\t\t\t.transform(ownCodebaseTransform(browserifyNgAnnotate))\n\t\t\t.transform(uglifyify);\n\n\tif (isWatching)\n\t\tbundler\n\t\t\t.on('update', (changedFiles) => {\n\t\t\t\tconsole.log(`re-bundling '${filename}'...`);\n\t\t\t\treturn bundle(changedFiles);\n\t\t\t})\n\t\t\t.on('log', msg => {\n\t\t\t\tconsole.log(`bundled '${filename}'`, msg);\n\t\t\t});\n\n\treturn bundle();\n}", "function browserifyClient(callback) {\n var\n bundleConfig = require('../../../bundle.yml'),\n packageConfig = bundleConfig.packages.fontello,\n clientConfig = packageConfig.client,\n clientRoot = path.resolve(N.runtime.apps[0].root, clientConfig.root),\n findOptions = _.pick(clientConfig, 'include', 'exclude');\n\n findOptions.root = clientRoot;\n\n findPaths(findOptions, function (err, pathnames) {\n var\n heads = [],\n bodies = [],\n export_list = [],\n requisite = new Requisite(N.runtime.apps[0].root);\n\n if (err) {\n callback(err);\n return;\n }\n\n async.forEachSeries(pathnames, function (pathname, nextPath) {\n pathname.read(function (err, source) {\n var // [ '[\"foo\"]', '[\"bar\"]', '[\"baz\"]' ]\n apiPathParts = extractApiPathParts(pathname);\n\n if (err) {\n nextPath(err);\n return;\n }\n\n // feed all parents of apiPath into heads array\n apiPathParts.reduce(function (prev, curr) {\n if (-1 === heads.indexOf(prev)) {\n heads.push(prev);\n }\n\n return prev + curr;\n });\n\n try {\n source = requisite.process(source, pathname);\n } catch (err) {\n nextPath(err);\n return;\n }\n\n bodies.push(\n ('this' + apiPathParts.join('') + ' = (function (require) {'),\n ('(function (exports, module) {'),\n source,\n ('}.call(this.exports, this.exports, this));'),\n ('return this.exports;'),\n ('}.call({ exports: {} }, require));')\n );\n\n export_list.push('this' + apiPathParts.join(''));\n\n nextPath();\n });\n }, function (err) {\n var head = _.uniq(heads.sort(), true).map(function (api) {\n return 'this' + api + ' = {};';\n }).join('\\n');\n\n callback(err, [\n '(function () {',\n 'var require = ' + requisite.bundle() + ';\\n\\n',\n head + '\\n\\n' + bodies.join('\\n') + '\\n\\n',\n '_.map([' + export_list.sort().join(',') + '], function (api) {',\n 'if (api && _.isFunction(api.init)) { api.init(window, N); }',\n '});',\n '}.call(N.client));'\n ].join('\\n'));\n });\n });\n}", "function browserifyBuild() {\n\tvar entry = 'bundle.js';\n\n\tvar bundler = browserify({\n\t\tentries: config.scriptsEntryPoint,\n\t debug: true,\n\t cache: {},\n\t packageCache: {},\n\t fullPaths: true\n\t}, watchify.args);\n\n\tif ( !global.isProd ) {\n\t bundler = watchify(bundler);\n\t bundler.on('update', function() {\n\t rebundle();\n\t });\n\t}\n\n\tvar transforms = [\n//\t\tbabelify,\n\t shim,\n//\t ngAnnotate,\n\t brfs\n\t];\n\n\ttransforms.forEach(function(transform) {\n\t bundler.transform(transform);\n\t});\n\n\tfunction rebundle() {\n\t var stream = bundler.bundle();\n\t // var createSourcemap = global.isProd && config.browserify.sourcemap;\n\t bundleLogger.start();\n\t return stream.on('error', handleErrors)\n\t .pipe(source(entry))\n\t .pipe(buffer())\n .pipe(sourcemaps.init({loadMaps: true, debug:true}))\n\t .pipe(sourcemaps.write('./'))\n\t .on('end', bundleLogger.end)\n\t .pipe(gulp.dest(config.dist + config.scripts))\n\t .pipe(gulpif(browserSync.active, browserSync.reload({ stream: true, once: true })));\n\t}\n\treturn rebundle();\n}", "function processArgs() {\n let args = process.argv.slice(2);\n let conf = {\n cPath: undefined,\n jsPath: undefined,\n outPath: undefined,\n supFiles: [],\n debug: false,\n noCompile: false,\n preprocessOnly: false,\n verbose: false,\n callGraphFlag: false,\n yieldPoint: false,\n cSideEffectTable: \"None\",\n jsSideEffectTable: \"None\"\n };\n\n for (var i = 0; i < args.length; i++) {\n if (args[i].charAt(0) === \"-\") {\n if (args[i] === \"-d\" || args[i] === \"--debug\") {\n conf.debug = true;\n } else if (args[i] === \"-h\" || args[i] === \"--help\") {\n printHelp();\n process.exit(0);\n } else if (args[i] === \"-n\" || args[i] === \"--nocompile\") {\n conf.noCompile = true;\n } else if (args[i] === \"-o\" || args[i] === \"--output\") {\n // Set output name\n conf.outPath = args[i + 1];\n i = i + 1;\n } else if (args[i] === \"-p\" || args[i] === \"--preprocess\") {\n // Preprocessor only\n conf.preprocessOnly = true;\n } else if (args[i] === \"-v\" || args[i] === \"--version\") {\n // Print version\n console.log(require(\"./package.json\").version);\n process.exit(0);\n } else if (args[i] === \"-V\" || args[i] === \"--verbose\") {\n // Verbose\n conf.verbose = true;\n } else if (args[i] === \"-a\" || args[i] === \"--analyze\") {\n // Generate call graph files\n conf.callGraphFlag = true;\n } else if (args[i] === \"-y\" || args[i] === \"yield\") {\n conf.yieldPoint = true;\n }\n } else {\n let inputPath = args[i];\n let extension = path.extname(inputPath);\n if (extension === \".js\") {\n if (conf.jsPath === undefined) {\n conf.jsPath = inputPath;\n if (conf.outPath === undefined) {\n conf.outPath = path.basename(inputPath, \".js\");\n }\n } else {\n conf.supFiles.push(inputPath);\n }\n } else if (extension === \".c\") {\n conf.cPath = inputPath;\n } else {\n if (path.extname(inputPath) !== \".jxe\") conf.supFiles.push(inputPath);\n }\n }\n }\n\n return conf;\n}", "function readBabelOptions(opts) {\n var babelPresets = [],\n // Add plugins to emit .d.ts files if necessary\n babelPlugins = opts.declaration\n ? [[require(\"babel-dts-generator\"),\n {\n \"packageName\": \"\",\n \"typings\": fableLib.pathJoin(opts.workingDir, opts.outDir),\n \"suppressAmbientDeclaration\": true,\n \"ignoreEmptyInterfaces\": false\n }],\n require(\"babel-plugin-transform-flow-strip-types\"),\n require(\"babel-plugin-transform-class-properties\")]\n : [];\n\n // Add custom plugins\n babelPlugins = babelPlugins.concat(\n customPlugins.transformMacroExpressions,\n // removeUnneededNulls must come after transformMacroExpressions (see #377)\n customPlugins.removeUnneededNulls,\n customPlugins.removeFunctionExpressionNames\n );\n\n // if opts.babelrc is true, read Babel plugins and presets from .babelrc\n if (opts.babelrc) {\n opts.babel = { presets: babelPresets, plugins: babelPlugins };\n return opts;\n }\n\n // ECMAScript target\n if (opts.ecma != \"es2015\" && opts.ecma != \"es6\") {\n if (opts.module === \"es2015\" || opts.module === \"es6\") {\n opts.module = false;\n }\n else if (opts.module in constants.JS_MODULES === false) {\n throw \"Unknown module target: \" + opts.module;\n }\n babelPresets.push([require.resolve(\"babel-preset-es2015\"), {\n \"loose\": opts.loose,\n \"modules\": opts.rollup ? false : opts.module\n }]);\n }\n else if (!opts.rollup && opts.module in constants.JS_MODULES) {\n babelPlugins.push(require(\"babel-plugin-transform-es2015-modules-\" + opts.module));\n }\n\n // Extra Babel plugins\n if (opts.babelPlugins) {\n babelPlugins = babelPlugins.concat(\n fableLib.resolvePlugins(opts.babelPlugins, opts.workingDir, \"babel-plugin-\"));\n }\n\n opts.babel = { presets: babelPresets, plugins: babelPlugins };\n return opts;\n}", "function browserifyFile(src, dest, opts){\n opts = opts || {};\n\n var b = browserify({\n entries: join(__dirname, src),\n debug: true,\n transform: [\n ['jadeify'],\n ['browserify-ngannotate']\n ]\n });\n\n function update(){\n var stream = b.bundle()\n .on('error', gutil.log)\n .pipe(source(src))\n .pipe(buffer())\n .pipe(sourcemaps.init({loadMaps: true}))\n .pipe(rename('index.js'))\n\n if (opts.uglify) {\n stream = stream.pipe(uglify());\n }\n\n if (opts.watch) {\n stream = stream.pipe(livereload());\n }\n\n stream\n .pipe(sourcemaps.write('./'))\n .pipe(gulp.dest(dest));\n\n gutil.log('built browserify %s', src)\n }\n\n if (opts.watch) {\n b = watchify(b);\n b.on('update', update);\n b.on('log', gutil.log);\n }\n\n b.external(vendor_packages);\n update();\n}", "function processOptions(opts) {\n opts = opts || {};\n var options = {};\n\n options.harmony = opts.harmony;\n options.stripTypes = opts.stripTypes;\n options.sourceMap = opts.sourceMap;\n options.filename = opts.sourceFilename;\n\n if (opts.es6module) {\n options.sourceType = 'module';\n }\n if (opts.nonStrictEs6module) {\n options.sourceType = 'nonStrictModule';\n }\n\n // Instead of doing any fancy validation, only look for 'es3'. If we have\n // that, then use it. Otherwise use 'es5'.\n options.es3 = opts.target === 'es3';\n options.es5 = !options.es3;\n\n return options;\n}", "function processOptions(opts) {\n opts = opts || {};\n var options = {};\n\n options.harmony = opts.harmony;\n options.stripTypes = opts.stripTypes;\n options.sourceMap = opts.sourceMap;\n options.filename = opts.sourceFilename;\n\n if (opts.es6module) {\n options.sourceType = 'module';\n }\n if (opts.nonStrictEs6module) {\n options.sourceType = 'nonStrictModule';\n }\n\n // Instead of doing any fancy validation, only look for 'es3'. If we have\n // that, then use it. Otherwise use 'es5'.\n options.es3 = opts.target === 'es3';\n options.es5 = !options.es3;\n\n return options;\n}", "function getBrowserCodeStream(opts) {\n opts = normalize_1.normalize(opts);\n var bOpts = {\n entries: [__dirname + '/../browser/preboot_browser.js'],\n standalone: 'preboot',\n basedir: __dirname + '/../browser',\n browserField: false\n };\n var b = browserify(bOpts);\n // ignore any strategies that are not being used\n ignoreUnusedStrategies(b, bOpts, opts.listen, normalize_1.listenStrategies, './listen/listen_by_');\n ignoreUnusedStrategies(b, bOpts, opts.replay, normalize_1.replayStrategies, './replay/replay_after_');\n if (opts.freeze) {\n ignoreUnusedStrategies(b, bOpts, [opts.freeze], normalize_1.freezeStrategies, './freeze/freeze_with_');\n }\n // ignore other code not being used\n if (!opts.buffer) {\n b.ignore('./buffer_manager.js', bOpts);\n }\n if (!opts.debug) {\n b.ignore('./log.js', bOpts);\n }\n // use gulp to get the stream with the custom preboot browser code\n var outputStream = b.bundle()\n .pipe(source('src/browser/preboot_browser.js'))\n .pipe(buffer())\n .pipe(insert.append('\\n\\n;preboot.init(' + utils_1.stringifyWithFunctions(opts) + ');\\n\\n'))\n .pipe(rename('preboot.js'));\n // uglify if the option is passed in\n return opts.uglify ? outputStream.pipe(uglify()) : outputStream;\n}", "function buildForBrowserify() {\n return doRollup('src/index.js', 'lib/index-browser.js', true);\n}", "function combineSrc(ctxt, callback) {\n\t\tvar bundlePath = path.join(ctxt.binDir, 'j2j-' + version + '.js');\n\n\t\tvar browserify = require('browserify');\n\t\tbrowserify()\n\t\t .require(ctxt.srcMainPath, { \n\t\t \tentry: true, \n\t\t \tdebug: true \n\t\t })\n\t\t .bundle()\n\t\t .on('error', function (err) { console.error(err); })\n\t\t .pipe(fs.createWriteStream(bundlePath))\n\t\t .on('finish', function () {\n\t\t ctxt.bundlePath = bundlePath;\n\t\t moduleExportationAddition(ctxt, callback);\t\t \t\n\t\t });\n\t}", "function wrap(opts) {\n if (!opts) opts = {};\n\n var first = true;\n var lineno = (opts.prelude ? newlinesIn(defaultPrelude) : 0) + 2;\n var sourcemap;\n\n var stream = through.obj(write, end);\n\n return stream;\n\n function write(row, enc, next) {\n if (first && opts.prelude) {\n stream.push(defaultPrelude);\n }\n\n if (row.sourceFile && !row.nomap) {\n if (!sourcemap) {\n sourcemap = combineSourceMap.create();\n }\n\n if (first && opts.prelude) {\n sourcemap.addFile(\n {sourceFile: defaultPreludePath, source: defaultPrelude.toString()},\n {line: 0}\n );\n }\n\n sourcemap.addFile(\n {sourceFile: ensureJSFileName(row.sourceFile), source: row.source},\n {line: lineno}\n );\n }\n\n var deps = row.deps || {};\n\n // make sure the deduped file requires the other module correctly.\n // Browserify requires \"require(dedupeIndex)\". In our case however, it\n // is easier to simply require by the module ID directly.\n if (row.dedupe) {\n row.source = \"module.exports=require(0);\";\n deps[0] = row.dedupe;\n }\n\n deps = Object.keys(deps).sort().map(function (key) {\n //return JSON.stringify(key) + ':' + JSON.stringify(row.deps[key]);\n var depValue = JSON.stringify(row.deps[key]);\n var aIn;\n if (depValue.substr(-4).indexOf('.js') > -1 ) {\n depValue = depValue.replace(/\\\\\\\\/g, '/');\n aIn = depValue.indexOf('/app/');\n if(aIn > -1) {\n depValue = '\".' + depValue.substring(aIn, depValue.indexOf('.js')) + '\"';\n } else {\n depValue = '\".' + depValue.substring(depValue.indexOf('/config/'), depValue.indexOf('.js')) + '\"';\n }\n }\n return JSON.stringify(key) + ':' + depValue;\n }).join(',');\n\n var wrappedSource = wrapModule(row, deps);\n\n stream.push(wrappedSource);\n lineno += newlinesIn(wrappedSource);\n\n if (first && opts.prelude) {\n\n if (opts.url) {\n stream.push(new Buffer('\\nloadjs.url = \"' + opts.url + '\";'));\n }\n\n stream.push(new Buffer('\\nloadjs.files = [' + opts.files.map(function(file) {\n return '\"' + file + '\"';\n }).join(',') + ']'));\n\n stream.push(new Buffer([\n '\\nloadjs.map = ',\n JSON.stringify(createFileMap(opts.map, opts.files, opts.firstFile)),\n ';'\n ].join('')));\n\n }\n\n first = false;\n next();\n }\n\n function end() {\n if (opts.main && opts.prelude) {\n stream.push(new Buffer(\"loadjs(\" + JSON.stringify(opts.main) + \");\\n\"));\n }\n\n if (sourcemap) {\n var comment = sourcemap.comment();\n stream.push(new Buffer('\\n' + comment + '\\n'));\n }\n stream.push(null);\n }\n\n}", "function generateBuildOptions(metadata, options) {\n const results = Object.assign({}, command_1.filterOptionsByIntent(metadata, options), command_1.filterOptionsByIntent(metadata, options, 'app-scripts'));\n // Serve specific options not related to the actual run or emulate code\n return Object.assign({}, results, { externalAddressRequired: true, iscordovaserve: true, nobrowser: true, target: 'cordova' });\n}", "async function $build(argv: string[], options: Options) {\n const {\n \"--base\": base = \"/\",\n \"--out-client\": outClient = \"dist/client\",\n \"--out-server\": outServer = \"dist/server\",\n \"--source-map\": sourceMap = false,\n \"--help\": help = false,\n } = arg(\n {\n \"--base\": String,\n \"--out-server\": String,\n \"--out-client\": String,\n \"--source-map\": Boolean,\n \"--help\": Boolean,\n },\n { argv }\n );\n\n if (help) {\n return console.log(`\nBuild client and server-side bundles for deploying to a production environment.\n\n--base Base public path when built in production (default: \"/\")\n--out-client Output directory for client files relative to root (default: \"dist/client\")\n--out-client Output directory for server files relative to root (default: \"dist/server\")\n--source-map Generate production source maps (default: false)\n`);\n }\n\n await build({\n base: base,\n sourceMap: sourceMap,\n src: options.src,\n root: options.root,\n publicDir: options.publicDir,\n out: { server: outServer, client: outClient },\n });\n}", "function generateBuildConfig(){\n var jsBaseDir = './js';\n var lessBaseDir = './less';\n var fontsBaseDir= './fonts';\n\n var buildConfig = {\n jsBaseDir: jsBaseDir,\n fontsBaseDir: fontsBaseDir,\n fontsDestDir: './dist',\n jsDistDir: './dist',\n lessDistDir: './dist',\n lessBaseDir: lessBaseDir,\n //tell browserify to scan the js directory so we don't have to use relative paths when referencing modules (e.g. no ../components).\n paths:['./js'],\n //assume these extensions for require statements so we don't have to include in requires e.g. components/header vs components/header.jsx\n extensions:['.js'],\n\n //http://jshint.com/docs/options/\n jshintThese:[\n \"core/**/*\"\n ],\n jshint:{\n curly: true,\n strict: true,\n browserify: true\n },\n\n //http://lisperator.net/uglifyjs/codegen\n uglify:{\n mangle:true,\n output:{ //http://lisperator.net/uglifyjs/codegen\n beautify: false,\n quote_keys: true //this is needed because when unbundling/browser unpack, the defined modules need to be strings or we wont know what their names are.\n }\n //compress:false // we can refine if needed. http://lisperator.net/uglifyjs/compress\n }\n };\n\n\n return buildConfig;\n}", "_mergeSettings(settings, extraSettings) {\r\n for (let name in extraSettings) {\r\n if (name == 'paths') {\r\n continue;\r\n }\r\n\r\n if (!_.has(settings, name)) {\r\n settings[name] = extraSettings[name];\r\n continue;\r\n }\r\n\r\n let option = _.findWhere(argvOptions, { realName: name });\r\n\r\n if (option.type == 'array') {\r\n for (let value in extraSettings[name]) {\r\n if (!_.includes(settings[name], value)) {\r\n settings[name].push(value);\r\n }\r\n }\r\n }\r\n }\r\n\r\n if (extraSettings.paths) {\r\n if (!settings.paths) {\r\n settings.paths = {};\r\n }\r\n\r\n for (let urlPath in extraSettings.paths) {\r\n if (!_.has(settings.paths, urlPath)) {\r\n settings.paths[urlPath] = extraSettings.paths[urlPath];\r\n }\r\n else {\r\n extraSettings.paths[urlPath].forEach(function(staticPath) {\r\n if (!_.includes(settings.paths[urlPath], staticPath)) {\r\n settings.paths[urlPath].push(staticPath);\r\n }\r\n });\r\n }\r\n }\r\n }\r\n }", "function main(opts, args) {\n if (cli.active) {\n // If this is a command-line invocation, parse the args and opts. If the\n // args are missing or the help opt is given, print the help and exit.\n opts = cli.parse();\n args = opts._;\n if (args.length < 1 || opts.help) {\n cli.help();\n process.exit();\n }\n } else {\n // Create defaults for options if not provided.\n opts = opts || {};\n for (var d in DEFAULTS) {\n if (!(d in opts)) {\n opts[d] = DEFAULTS[d];\n }\n }\n }\n\n // Get all files specified.\n var paths = files.find(opts.path);\n var inputs = files.find(args);\n\n // Calculate the dependencies.\n var infos = deps.calculate(paths, inputs);\n\n // Format output.\n var output;\n if (opts.mode == 'list') {\n output = infos.map(function(info) { return info.path; });\n } else if (opts.mode == 'concat') {\n output = infos.map(function(info) { return info.content; }).join('\\n');\n } else {\n console.error('Unknown output mode');\n process.exit(1);\n }\n\n // Print the output to stdout, if needed (for the command-line).\n if (cli.active) {\n if ($.util.isArray(output)) {\n console.log(output.join('\\n'));\n } else {\n console.log(output);\n }\n }\n\n // Return the output (for the module).\n return output;\n}", "async function browserifyFiles(entries, distFile){\n\tconsole.log(\"browserify - \" + distFile);\n\n\n\tvar mapFile = distFile + \".map\";\t\n\n\tawait fs.unlinkFiles([distFile, mapFile]);\n\n\tvar b = browserify({ \n\t\tentries,\n\t\tentry: true, \n\t\tdebug: true \n\t});\n\t\n\n\t// wrap the async browserify bundle into a promise to make it \"async\" friendlier\n\treturn new Promise(function(resolve, reject){\n\n\t\tvar writableFs = fs.createWriteStream(distFile);\n\t\t// resolve promise when file is written\n\t\twritableFs.on(\"finish\", () => resolve());\t\t\n\t\t// reject if we have a write error\n\t\twritableFs.on(\"error\", (ex) => reject(ex));\t\t\n\n\t\tb.bundle()\n\t\t\t// reject if we have a bundle error\n\t\t\t.on(\"error\", function (err) { reject(err); })\t\t\n\t\t\t// or continue the flow\n\t\t\t.pipe(exorcist(mapFile))\n\t\t\t.pipe(writableFs);\n\n\t});\t\n}", "function main() {\n const options = minimist(process.argv.slice(2));\n\n const source = fs\n .readFileSync(path.join(root, \"package.json\"))\n .toString(\"utf-8\");\n const sourceObj = JSON.parse(source);\n\n if (options.legacy) {\n sourceObj.name = \"@lolopinto/ent\";\n // TODO this needs to be updated here everytime we wanna update legacy version...\n // the legacy path is difficult because of tsent though...\n sourceObj.version = \"0.0.100\";\n }\n sourceObj.scripts = {};\n sourceObj.devDependencies = {};\n if (sourceObj.main.startsWith(\"dist/\")) {\n sourceObj.main = sourceObj.main.slice(5);\n }\n fs.writeFileSync(\n path.join(root, \"dist\", \"/package.json\"),\n Buffer.from(JSON.stringify(sourceObj, null, 2), \"utf-8\"),\n );\n\n fs.copyFileSync(\n path.join(root, \".npmignore\"),\n path.join(root, \"dist\", \".npmignore\"),\n );\n}", "function createServerWebpackConfig(args, commandConfig, serverConfig) {\n let pluginConfig = (0, _config.getPluginConfig)(args);\n let userConfig = (0, _config.getUserConfig)(args, { pluginConfig });\n let { entry, plugins = {} } = commandConfig,\n otherCommandConfig = _objectWithoutProperties(commandConfig, ['entry', 'plugins']);\n\n if (args['auto-install'] || args.install) {\n plugins.autoInstall = true;\n }\n\n return (0, _createWebpackConfig2.default)(_extends({\n server: true,\n devtool: 'cheap-module-source-map',\n entry: getHMRClientEntries(args, serverConfig).concat(entry),\n plugins\n }, otherCommandConfig), pluginConfig, userConfig);\n}", "_convertArgvToObject(argv) {\r\n let settings = { };\r\n\r\n // If running tyranno-serve directly, just lob off base command\r\n let startIndex = 1;\r\n if (argv[0].indexOf('tyranno-serve') == -1) {\r\n // Otherwise this is node, so we have to lob off node and index.js\r\n startIndex = 2;\r\n }\r\n\r\n for (let i = startIndex; i < argv.length; i++) {\r\n let name = 'path';\r\n let value = '';\r\n\r\n if (argv[i].startsWith('--')) {\r\n name = argv[i].substring(2);\r\n }\r\n else if (argv[i].startsWith('-')) {\r\n throw new Error(\"Single hyphen args not yet supported. Please use -- args.\");\r\n }\r\n else {\r\n value = '=' + argv[i];\r\n }\r\n\r\n if (!_.has(argvOptions, name)) {\r\n throw new Error(\"Unknown option '\" + name + \"'.\");\r\n }\r\n\r\n let option = argvOptions[name];\r\n\r\n let realName = name;\r\n if (option.name) {\r\n realName = option.name;\r\n }\r\n\r\n if (option.type == 'flag') {\r\n settings[realName] = true;\r\n continue;\r\n }\r\n\r\n // If it's not a flag we need to assume the next one is the value, unless we already grabbed\r\n // it.\r\n if (!value) {\r\n i++;\r\n\r\n if (i >= argv.length) {\r\n throw new Error(\"Expecting argument for key '\" + name + \"'.\");\r\n }\r\n\r\n value = argv[i];\r\n }\r\n\r\n if (name == 'path') {\r\n // Paths work differently with special parsing rules\r\n if (!_.has(settings, 'paths')) {\r\n settings.paths = {};\r\n }\r\n\r\n let index = value.indexOf('=');\r\n let serverPath = value.substring(0, index);\r\n let filePath = value.substring(index + 1);\r\n\r\n if (!_.has(settings.paths, serverPath)) {\r\n settings.paths[serverPath] = [filePath];\r\n }\r\n else {\r\n settings.paths[serverPath].push(filePath);\r\n }\r\n }\r\n else if (option.type == 'array') {\r\n if (!_.has(settings, name)) {\r\n settings[realName] = [value];\r\n }\r\n else {\r\n settings[realName].push(value);\r\n }\r\n }\r\n else {\r\n if (!_.has(settings, name)) {\r\n settings[realName] = value;\r\n }\r\n else {\r\n throw new Error(\"Argument option '\" + name + \"' can only be specified once.\");\r\n }\r\n }\r\n }\r\n\r\n return settings;\r\n }", "manipulateOptions(opts, parserOpts) {\n parserOpts.plugins.push('dynamicImport');\n }", "async function loader(\n args\n ) {\n try {\n const isCommonjs = args.namespace.endsWith('commonjs');\n \n const key = removeEndingSlash(args.path);\n const contents = polyfilledBuiltins.get(key) || polyfillLib[key + '.js'];\n const resolveDir = path.dirname(key);\n\n if (isCommonjs) {\n return {\n loader: 'js',\n contents: commonJsTemplate({\n importPath: args.path,\n }),\n resolveDir,\n };\n }\n return {\n loader: 'js',\n contents,\n resolveDir,\n };\n } catch (e) {\n console.error('node-modules-polyfill', e);\n return {\n contents: `export {}`,\n loader: 'js',\n };\n }\n }", "function init(options) {\n const ENV = options.ENV || \"dev\";\n const ROOT = options.ROOT || __dirname;\n // const TEST = options.TEST || false;\n\n const config = new Config();\n // Check if git repo exists\n const gitRepoExists = fs.existsSync(\"../.git\");\n\n // set all common configurations here\n config\n .entry(\"main\")\n .add(\"./src/main.ts\");\n\n config\n .output\n .path(path.join(ROOT, \"dist\", ENV))\n .filename(\"main.js\")\n .pathinfo(false)\n .libraryTarget(\"commonjs2\")\n .sourceMapFilename(\"[file].map\")\n .devtoolModuleFilenameTemplate(\"[resource-path]\");\n\n config.devtool(\"source-map\");\n\n config.target(\"node\");\n\n config.node.merge({\n Buffer: false,\n __dirname: false,\n __filename: false,\n console: true,\n global: true,\n process: false,\n });\n\n config.watchOptions({ ignored: /node_modules/ });\n\n config.resolve\n .extensions\n .merge([\".webpack.js\", \".web.js\", \".ts\", \".tsx\", \".js\"]);\n\n // see for more info about TsConfigPathsPlugin\n // https://github.com/s-panferov/awesome-typescript-loader/issues/402\n config.resolve.plugin(\"tsConfigPaths\") // name here is just an identifier\n .use(TsConfigPathsPlugin);\n\n config.externals([nodeExternals(), {\n // webpack will not try to rewrite require(\"main.js.map\")\n \"main.js.map\": \"main.js.map\",\n }]);\n\n /////////\n /// Plugins\n\n // NOTE: do not use 'new' on these, it will be called automatically\n // this plugin is for typescript's typeschecker to run in async mode\n config.plugin(\"tsChecker\")\n .use(CheckerPlugin);\n\n // this plugin wipes the `dist` directory clean before each new deploy\n config.plugin(\"clean\")\n .use(CleanWebpackPlugin, [ // arguments passed to CleanWebpackPlugin ctor\n [ `dist/${options.ENV}/*` ],\n { root: options.ROOT },\n ]);\n\n // you can use this to define build toggles; keys defined here\n // will be replaced in the output code with their values;\n // Note that because the plugin does a direct text replacement,\n // the value given to it must include actual quotes inside of the\n // string itself. Typically, this is done either with either\n // alternate quotes, such as '\"production\"', or by using\n // JSON.stringify('production').\n // Make sure to let typescript know about these via `define` !\n // See https://github.com/kurttheviking/git-rev-sync-js for more git options\n config.plugin(\"define\")\n .use((webpack.DefinePlugin), [{\n PRODUCTION: JSON.stringify(true),\n __BUILD_TIME__: JSON.stringify(Date.now()), // example defination\n __REVISION__: gitRepoExists ? JSON.stringify(git.short()) : JSON.stringify(\"\"),\n __PROFILER_ENABLED__: true,\n }]);\n\n config.plugin(\"screeps-source-map\")\n .use((ScreepsSourceMapToJson));\n\n config.plugin(\"no-emit-on-errors\")\n .use((webpack.NoEmitOnErrorsPlugin));\n\n const webpackUglifyJsPlugin = require('uglifyjs-webpack-plugin');\n\n config.plugin(\"uglify-js\").use(webpackUglifyJsPlugin, [{\n parallel: true,\n sourceMap: true,\n uglifyOptions: {\n output: { ascii_only: true, beautify: false, semicolons: false }\n }\n }]);\n\n /////////\n /// Modules\n\n config.module.rule(\"js-source-maps\")\n .test(/\\.js$/)\n .enforce(\"pre\")\n .use(\"source-map\")\n .loader(\"source-map-loader\");\n\n config.module.rule(\"tsx-source-maps\")\n .test(/\\.tsx?$/)\n .enforce(\"pre\")\n .use(\"source-map\")\n .loader(\"source-map-loader\");\n\n config.module.rule(\"compile\")\n .test(/\\.tsx?$/)\n .exclude\n .add(path.join(ROOT, \"src/snippets\"))\n .end()\n .use(\"typescript\")\n .loader(\"awesome-typescript-loader\")\n .options({ configFileName: \"tsconfig.json\" });\n\n config.module.rule(\"lint\")\n .test(/\\.tsx?$/)\n .exclude\n .add(path.join(ROOT, \"src/snippets\"))\n .add(path.join(ROOT, \"src/lib\"))\n .end()\n .use(\"tslint\")\n .loader(\"tslint-loader\")\n .options({\n configFile: path.join(ROOT, \"tslint.json\"),\n // automaticall fix linting errors\n fix: false,\n // you can search NPM and install custom formatters\n formatter: \"stylish\",\n // enables type checked rules like 'for-in-array'\n // uses tsconfig.json from current working directory\n typeCheck: false,\n });\n\n // return the config object\n return config;\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 }", "function getCSBData(opts) {\n const isTSX = Boolean(opts.sources._.tsx);\n const ext = isTSX ? '.tsx' : '.jsx';\n const files = {};\n const deps = {};\n const CSSDeps = Object.values(opts.dependencies).filter(dep => dep.css);\n const appFileName = `App${ext}`;\n const entryFileName = `index${ext}`; // generate dependencies\n\n Object.entries(opts.dependencies).forEach(([dep, {\n version\n }]) => {\n deps[dep] = version;\n }); // add react-dom dependency\n\n if (!deps['react-dom']) {\n deps['react-dom'] = deps.react || 'latest';\n } // append sandbox.config.json\n\n\n files['sandbox.config.json'] = {\n content: JSON.stringify({\n template: isTSX ? 'create-react-app-typescript' : 'create-react-app'\n }, null, 2)\n }; // append package.json\n\n files['package.json'] = {\n content: JSON.stringify({\n name: opts.title,\n description: getTextContent(opts.description) || 'An auto-generated demo by dumi',\n main: entryFileName,\n dependencies: deps,\n // add TypeScript dependency if required, must in devDeps to avoid csb compile error\n devDependencies: isTSX ? {\n typescript: '^3'\n } : {}\n }, null, 2)\n }; // append index.html\n\n files['index.html'] = {\n content: '<div style=\"margin: 16px;\" id=\"root\"></div>'\n }; // append entry file\n\n files[entryFileName] = {\n content: `/**\n* This is an auto-generated demo by dumi\n* if you think it is not working as expected,\n* please report the issue at\n* https://github.com/umijs/dumi/issues\n**/\n\nimport React from 'react';\nimport ReactDOM from 'react-dom';\n${CSSDeps.map(({\n css\n }) => `import '${css}';`).join('\\n')}\nimport App from './App';\n\nReactDOM.render(\n <App />,\n document.getElementById('root'),\n);`\n }; // append other imported local files\n\n Object.entries(opts.sources).forEach(([filename, {\n tsx,\n jsx,\n content\n }]) => {\n // handle primary content\n files[filename === '_' ? appFileName : filename] = {\n content: tsx || jsx || content\n };\n });\n return serialize({\n files\n });\n}", "'package'(js_file_path, options = {}, callback) {\n\n\t\tlet a = arguments;\n\t\tif (typeof a[2] === 'function') {\n\t\t\tcallback = a[2];\n\t\t\toptions = {\n\t\t\t\t//'babel': 'mini',\n\t\t\t\t'include_sourcemaps': true\n\t\t\t};\n\t\t}\n\n\t\treturn prom_or_cb((resolve, reject) => {\n\t\t\t(async () => {\n\t\t\t\t// options\n\t\t\t\t// may want a replacement within the client-side code.\n\t\t\t\t// Can we call browserify on the code string?\n\t\t\t\t// Creating a modified copy of the file would do.\n\t\t\t\t// Load the file, modify it, save it under a different name\n\n\t\t\t\tlet s = new require('stream').Readable(),\n\t\t\t\t\tpath = require('path').parse(js_file_path);\n\n\t\t\t\tlet fileContents = await fnlfs.load(js_file_path);\n\t\t\t\t//console.log('1) fileContents.length', fileContents.length);\n\t\t\t\t// are there any replacements to do?\n\t\t\t\t// options.replacements\n\n\t\t\t\tif (options.js_mode === 'debug') {\n\t\t\t\t\toptions.include_sourcemaps = true;\n\t\t\t\t}\n\t\t\t\tif (options.js_mode === 'compress' || options.js_mode === 'mini') {\n\t\t\t\t\toptions.include_sourcemaps = false;\n\t\t\t\t\toptions.babel = 'mini';\n\t\t\t\t}\n\n\t\t\t\t//console.log('options.babel', options.babel);\n\n\t\t\t\tif (options.replace) {\n\t\t\t\t\tlet s_file_contents = fileContents.toString();\n\t\t\t\t\t//console.log('s_file_contents', s_file_contents);\n\t\t\t\t\teach(options.replace, (text, key) => {\n\t\t\t\t\t\t//console.log('key', key);\n\t\t\t\t\t\t//console.log('text', text);\n\t\t\t\t\t\tlet running_fn = '(' + text + ')();'\n\t\t\t\t\t\t//console.log('running_fn', running_fn);\n\t\t\t\t\t\ts_file_contents = s_file_contents.split(key).join(running_fn);\n\t\t\t\t\t})\n\t\t\t\t\tfileContents = Buffer.from(s_file_contents);\n\t\t\t\t\t//console.log('2) fileContents.length', fileContents.length);\n\t\t\t\t}\n\t\t\t\t// Then we can replace some of the file contents with specific content given when we tall it to serve that file.\n\t\t\t\t// We have a space for client-side activation.\n\t\t\t\ts.push(fileContents);\n\t\t\t\ts.push(null);\n\n\t\t\t\t//let include_sourcemaps = true;\n\n\t\t\t\tlet b = browserify(s, {\n\t\t\t\t\tbasedir: path.dir,\n\t\t\t\t\t//builtins: false,\n\t\t\t\t\tbuiltins: ['buffer', 'process'],\n\t\t\t\t\t'debug': options.include_sourcemaps\n\t\t\t\t});\n\n\t\t\t\tlet parts = await stream_to_array(b.bundle());\n\n\t\t\t\tconst buffers = parts\n\t\t\t\t\t.map(part => util.isBuffer(part) ? part : Buffer.from(part));\n\t\t\t\tlet buf_js = Buffer.concat(buffers);\n\t\t\t\tlet str_js = buf_js.toString();\n\n\t\t\t\tlet babel_option = options.babel\n\t\t\t\t//console.log('babel_option', babel_option);\n\t\t\t\tif (babel_option === 'es5') {\n\n\t\t\t\t\tlet o_transform = {\n\t\t\t\t\t\t\"presets\": [\n\t\t\t\t\t\t\t\"es2015\",\n\t\t\t\t\t\t\t\"es2017\"\n\t\t\t\t\t\t],\n\t\t\t\t\t\t\"plugins\": [\n\t\t\t\t\t\t\t\"transform-runtime\"\n\t\t\t\t\t\t] //,\n\t\t\t\t\t\t//'sourceMaps': 'inline'\n\t\t\t\t\t};\n\n\t\t\t\t\tif (options.include_sourcemaps) o_transform.sourceMaps = 'inline';\n\t\t\t\t\tlet res_transform = babel.transform(str_js, o_transform);\n\t\t\t\t\t//console.log('res_transform', res_transform);\n\t\t\t\t\t//console.log('Object.keys(res_transform)', Object.keys(res_transform));\n\t\t\t\t\tlet jst_es5 = res_transform.code;\n\t\t\t\t\t//let {jst_es5, map, ast} = babel.transform(str_js);\n\t\t\t\t\t//console.log('jst_es5.length', jst_es5.length);\n\t\t\t\t\tbuf_js = Buffer.from(jst_es5);\n\t\t\t\t} else if (babel_option === 'mini') {\n\t\t\t\t\t/*\n\t\t\t\t\tlet o_transform = {\n\t\t\t\t\t\tpresets: [\"minify\"]//,\n\t\t\t\t\t\t//'sourceMaps': 'inline'\n\t\t\t\t\t};\n\t\t\t\t\t*/\n\t\t\t\t\tlet o_transform = {\n\t\t\t\t\t\t\"presets\": [\n\t\t\t\t\t\t\t[\"minify\", {\n\t\t\t\t\t\t\t\t//\"mangle\": {\n\t\t\t\t\t\t\t\t//\"exclude\": [\"MyCustomError\"]\n\t\t\t\t\t\t\t\t//},\n\t\t\t\t\t\t\t\t//\"unsafe\": {\n\t\t\t\t\t\t\t\t//\t\"typeConstructors\": false\n\t\t\t\t\t\t\t\t//},\n\t\t\t\t\t\t\t\t//\"keepFnName\": true\n\t\t\t\t\t\t\t}]\n\t\t\t\t\t\t],\n\t\t\t\t\t\t//plugins: [\"minify-dead-code-elimination\"]\n\t\t\t\t\t};\n\t\t\t\t\tif (options.include_sourcemaps) o_transform.sourceMaps = 'inline';\n\n\t\t\t\t\tlet res_transform = babel.transform(str_js, o_transform);\n\t\t\t\t\tbuf_js = Buffer.from(res_transform.code);\n\t\t\t\t} else {\n\t\t\t\t\tbuf_js = Buffer.from(str_js);\n\t\t\t\t}\n\t\t\t\tresolve(buf_js);\n\t\t\t})();\n\t\t}, callback);\n\t}", "constructor(options) {\n options = options || {};\n this.filesPath = options[\"filesPath\"] || \"./webpack.files.json\";\n this.manifestPath = options[\"manifestPath\"] || \"./src/manifest.json\";\n this.manifestVars = options[\"manifestVars\"] || {};\n }", "function commonjsMain (args) {\n if (!args[1]) {\n console.log('Usage: ' + args[0] + ' FILE');\n process.exit(1);\n }\n var source = require('fs').readFileSync(require('path').normalize(args[1]), 'utf8');\n return exports.parser.parse(source);\n}", "async function compile(opts, ctx = {}) {\n const options = ctx.options || await createOptions(opts)\n\n const {\n filter,\n loader,\n sourceMap,\n replaceExt,\n absoluteBaseDir,\n absoluteOutDir,\n } = options\n\n const files = await extractFiles(absoluteBaseDir, filter)\n\n const basicFileInfos = await getFilesInfo(files)\n\n // repeat\n const rawFileInfos = appendTargetFilePath(\n replaceExt,\n absoluteBaseDir,\n absoluteOutDir,\n basicFileInfos,\n )\n\n const compiledFiles = await compileFiles(loader, options, rawFileInfos)\n\n const outputFilesByPath = getOutPutFiles(sourceMap, compiledFiles)\n\n const filesToOuput = getDiff(ctx.outputFilesByPath, outputFilesByPath)\n\n await outputFiles(filesToOuput)\n\n return {\n options,\n compiledFiles,\n outputFilesByPath,\n }\n}", "function parseOptions (opts) {\n return removeEmpty({\n plugins: convertFn.call(this, opts.plugins),\n locals: convertFn.call(this, opts.locals),\n filename: convertFn.call(this, opts.filename),\n parserOptions: convertFn.call(this, opts.parserOptions),\n generatorOptions: convertFn.call(this, opts.generatorOptions),\n runtime: convertFn.call(this, opts.runtime),\n parser: convertFnSpecial.call(this, opts.parser),\n generator: convertFnSpecial.call(this, opts.generator)\n })\n}", "function createBundle(config) {\n\n var bopts = config.browserify || {};\n\n function warn(key) {\n log.warn('Invalid config option: \"' + key + 's\" should be \"' + key + '\"');\n }\n\n _.forEach([ 'transform', 'plugin' ], function(key) {\n if (bopts[key + 's']) {\n warn(key);\n }\n });\n\n var browserifyOptions = _.extend({}, watchify.args, _.omit(bopts, [\n 'transform', 'plugin', 'prebundle'\n ]));\n\n var w = watchify(browserify(browserifyOptions));\n\n _.forEach(bopts.plugin, function(p) {\n // ensure we can pass plugin options as\n // the first parameter\n if (!Array.isArray(p)) {\n p = [ p ];\n }\n w.plugin.apply(w, p);\n });\n\n _.forEach(bopts.transform, function(t) {\n // ensure we can pass transform options as\n // the first parameter\n if (!Array.isArray(t)) {\n t = [ t ];\n }\n w.transform.apply(w, t);\n });\n\n // test if we have a prebundle function\n if (bopts.prebundle && typeof bopts.prebundle === 'function') {\n bopts.prebundle(w);\n }\n\n // register rebuild bundle on change\n if (config.autoWatch) {\n log.info('registering rebuild (autoWatch=true)');\n\n w.on('update', function() {\n log.debug('files changed');\n deferredBundle();\n });\n }\n\n w.on('log', function(msg) {\n log.info(msg);\n });\n\n // files contained in bundle\n var files = [ ];\n\n\n // update bundle file\n w.on('bundled', function(err, content) {\n if (w._builtOnce && !err) {\n bundleFile.update(content.toString('utf-8'));\n log.info('bundle updated');\n }\n\n w._builtOnce = true;\n });\n\n\n function deferredBundle(cb) {\n if (cb) {\n w.once('bundled', cb);\n }\n\n rebuild();\n }\n\n\n var MISSING_MESSAGE = /^Cannot find module '([^']+)'/;\n\n var rebuild = _.debounce(function rebuild() {\n\n log.debug('bundling');\n\n w.reset();\n\n files.forEach(function(f) {\n w.require(f, { expose: path.relative(config.basePath, f) });\n });\n\n w.bundle(function(err, content) {\n\n if (err) {\n log.error('bundle error');\n log.error(String(err));\n\n // try to recover from removed test case\n // rebuild, if successful\n var match = MISSING_MESSAGE.exec(err.message);\n if (match) {\n var idx = files.indexOf(match[1]);\n\n if (idx !== -1) {\n log.debug('removing %s from bundle', match[1]);\n files.splice(idx, 1);\n\n log.debug('attempting rebuild');\n return rebuild();\n }\n }\n }\n\n w.emit('bundled', err, content);\n });\n }, 500);\n\n\n w.bundleFile = function(file, done) {\n\n var absolutePath = file.path,\n relativePath = path.relative(config.basePath, absolutePath);\n\n if (files.indexOf(absolutePath) === -1) {\n\n // add file\n log.debug('adding %s to bundle', relativePath);\n\n files.push(absolutePath);\n }\n\n deferredBundle(function(err) {\n done(err, 'require(\"' + escape(relativePath) + '\");');\n });\n };\n\n\n /**\n * Wait for the bundle creation to have stabilized (no more additions) and invoke a callback.\n *\n * @param {Function} cb\n * @param {Number} delay\n * @param {Number} timeout\n */\n w.deferredBundle = deferredBundle;\n\n return w;\n }", "config(cfg) {\n // if (cfg.hasFilesystemConfig()) {\n // // Use the normal config\n // return cfg.options;\n // }\n\n const {\n __createDll,\n __react,\n __typescript = false,\n __server = false,\n __spaTemplateInject = false,\n __routes,\n } = customOptions;\n const { presets, plugins, ...options } = cfg.options;\n const isServer =\n __server || process.env.WEBPACK_BUILD_STAGE === 'server';\n // console.log({ options });\n\n // presets ========================================================\n const newPresets = [...presets];\n if (__typescript) {\n newPresets.unshift([\n require('@babel/preset-typescript').default,\n __react\n ? {\n isTSX: true,\n allExtensions: true,\n }\n : {},\n ]);\n // console.log(newPresets);\n }\n newPresets.forEach((preset, index) => {\n if (\n typeof preset.file === 'object' &&\n /^@babel\\/preset-env$/.test(preset.file.request)\n ) {\n const thisPreset = newPresets[index];\n if (typeof thisPreset.options !== 'object')\n thisPreset.options = {};\n thisPreset.options.modules = false;\n thisPreset.options.exclude = [\n // '@babel/plugin-transform-regenerator',\n // '@babel/plugin-transform-async-to-generator'\n ];\n if (isServer || __spaTemplateInject) {\n thisPreset.options.targets = {\n node: true,\n };\n thisPreset.options.ignoreBrowserslistConfig = true;\n thisPreset.options.exclude.push(\n '@babel/plugin-transform-regenerator'\n );\n thisPreset.options.exclude.push(\n '@babel/plugin-transform-async-to-generator'\n );\n }\n // console.log(__spaTemplateInject, thisPreset);\n }\n });\n\n // plugins ========================================================\n // console.log('\\n ');\n // console.log('before', plugins.map(plugin => plugin.file.request));\n\n const newPlugins = plugins.filter((plugin) => {\n // console.log(plugin.file.request);\n if (testPluginName(plugin, /^extract-hoc(\\/|\\\\)babel$/))\n return false;\n if (testPluginName(plugin, /^react-hot-loader(\\/|\\\\)babel$/))\n return false;\n if (testPluginName(plugin, 'transform-regenerator'))\n return false;\n\n return true;\n });\n\n // console.log('after', newPlugins.map(plugin => plugin.file.request));\n\n if (\n !__createDll &&\n __react &&\n process.env.WEBPACK_BUILD_ENV === 'dev'\n ) {\n // newPlugins.push(require('extract-hoc/babel'));\n newPlugins.push(require('react-hot-loader/babel'));\n }\n\n if (!__createDll && !isServer) {\n let pathname = path.resolve(getCwd(), __routes);\n if (fs.lstatSync(pathname).isDirectory()) pathname += '/index';\n if (!fs.existsSync(pathname)) {\n const exts = ['.js', '.ts'];\n exts.some((ext) => {\n const newPathname = path.resolve(pathname + ext);\n if (fs.existsSync(newPathname)) {\n pathname = newPathname;\n return true;\n }\n return false;\n });\n }\n newPlugins.push([\n path.resolve(\n __dirname,\n './plugins/client-sanitize-code-spliting-name.js'\n ),\n {\n routesConfigFile: pathname,\n },\n ]);\n // console.log(newPlugins);\n }\n\n const thisOptions = {\n ...options,\n presets: newPresets,\n plugins: newPlugins,\n };\n // console.log(isServer);\n\n return thisOptions;\n }", "function normalize$1( options, opts ) {\n\topts = opts || {};\n\tconst rawOptions = Object.assign( {}, options );\n\tconst supportOptions = getSupportInfo$1( {\n\t\tplugins: options.plugins,\n\t\tshowUnreleased: true,\n\t\tshowDeprecated: true,\n\t} ).options;\n\tconst defaults = Object.assign( {}, hiddenDefaults, {}, fromPairs_1( supportOptions.filter( ( optionInfo ) => optionInfo.default !== undefined ).map( ( option ) => [ option.name, option.default ] ) ) );\n\n\tif ( ! rawOptions.parser ) {\n\t\tif ( ! rawOptions.filepath ) {\n\t\t\tconst logger = opts.logger || console;\n\t\t\tlogger.warn( \"No parser and no filepath given, using 'babel' the parser now \" + 'but this will throw an error in the future. ' + 'Please specify a parser or a filepath so one can be inferred.' );\n\t\t\trawOptions.parser = 'babel';\n\t\t} else {\n\t\t\trawOptions.parser = inferParser( rawOptions.filepath, rawOptions.plugins );\n\n\t\t\tif ( ! rawOptions.parser ) {\n\t\t\t\tthrow new UndefinedParserError$1( `No parser could be inferred for file: ${ rawOptions.filepath }` );\n\t\t\t}\n\t\t}\n\t}\n\n\tconst parser = resolveParser$1(\n\t\toptionsNormalizer.normalizeApiOptions( rawOptions, [ supportOptions.find( ( x ) => x.name === 'parser' ) ], {\n\t\t\tpassThrough: true,\n\t\t\tlogger: false,\n\t\t} )\n\t);\n\trawOptions.astFormat = parser.astFormat;\n\trawOptions.locEnd = parser.locEnd;\n\trawOptions.locStart = parser.locStart;\n\tconst plugin = getPlugin( rawOptions );\n\trawOptions.printer = plugin.printers[ rawOptions.astFormat ];\n\tconst pluginDefaults = supportOptions\n\t\t.filter( ( optionInfo ) => optionInfo.pluginDefaults && optionInfo.pluginDefaults[ plugin.name ] !== undefined )\n\t\t.reduce(\n\t\t\t( reduced, optionInfo ) =>\n\t\t\t\tObject.assign( reduced, {\n\t\t\t\t\t[ optionInfo.name ]: optionInfo.pluginDefaults[ plugin.name ],\n\t\t\t\t} ),\n\t\t\t{}\n\t\t);\n\tconst mixedDefaults = Object.assign( {}, defaults, {}, pluginDefaults );\n\tObject.keys( mixedDefaults ).forEach( ( k ) => {\n\t\tif ( rawOptions[ k ] == null ) {\n\t\t\trawOptions[ k ] = mixedDefaults[ k ];\n\t\t}\n\t} );\n\n\tif ( rawOptions.parser === 'json' ) {\n\t\trawOptions.trailingComma = 'none';\n\t}\n\n\treturn optionsNormalizer.normalizeApiOptions(\n\t\trawOptions,\n\t\tsupportOptions,\n\t\tObject.assign(\n\t\t\t{\n\t\t\t\tpassThrough: Object.keys( hiddenDefaults ),\n\t\t\t},\n\t\t\topts\n\t\t)\n\t);\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 }", "function commonjsMain(args) {\n if (!args[1]) {\n console.log('Usage: ' + args[0] + ' FILE');\n process.exit(1);\n }\n\n var source = require('fs').readFileSync(require('path').normalize(args[1]), \"utf8\");\n\n return exports.parser.parse(source);\n } // debug mixin for LR parser generators", "async function bundle() {\n const since = lastRun(bundle);\n const polyfillPath = path.join(config.buildBase, 'js', 'polyfill.js');\n const factorBundlePath = path.join(\n config.buildBase,\n 'js',\n 'factor-bundle.js'\n );\n\n await makeDir(path.join(config.buildBase, 'js'));\n\n async function getFactorBundle() {\n const paths = await globby('**/*.js', { cwd: 'assets/js' });\n const factorBundle = await new Promise((resolve, reject) => {\n browserify({\n entries: paths.map((string) => `assets/js/${string}`),\n debug: true\n })\n .plugin('bundle-collapser/plugin')\n .plugin('factor-bundle', {\n outputs: paths.map((string) =>\n path.join(config.buildBase, 'js', string)\n )\n })\n .bundle((err, data) => {\n if (err) return reject(err);\n resolve(data);\n });\n });\n await fs.promises.writeFile(factorBundlePath, factorBundle);\n }\n\n await Promise.all([\n fs.promises.copyFile(\n path.join(\n __dirname,\n 'node_modules',\n '@babel',\n 'polyfill',\n 'dist',\n 'polyfill.js'\n ),\n polyfillPath\n ),\n getFactorBundle()\n ]);\n\n // concatenate files\n await getStream(\n src([\n 'build/js/polyfill.js',\n 'build/js/factor-bundle.js',\n 'build/js/uncaught.js',\n 'build/js/core.js'\n ])\n .pipe(sourcemaps.init({ loadMaps: true }))\n .pipe(concat('build.js'))\n .pipe(sourcemaps.write('./'))\n .pipe(dest(path.join(config.buildBase, 'js')))\n .pipe(through2.obj((chunk, enc, cb) => cb()))\n );\n\n let stream = src('build/js/**/*.js', { base: 'build', since })\n .pipe(sourcemaps.init({ loadMaps: true }))\n .pipe(unassert())\n .pipe(envify())\n .pipe(babel());\n\n if (PROD) stream = stream.pipe(terser());\n\n stream = stream.pipe(sourcemaps.write('./')).pipe(dest(config.buildBase));\n\n if (DEV) stream = stream.pipe(lr(config.livereload));\n\n stream = stream.pipe(dest(config.buildBase));\n\n // convert to conventional stream\n stream = stream.pipe(through2.obj((chunk, enc, cb) => cb()));\n\n await getStream(stream);\n}", "constructor(args, opts) {\n super(args, opts);\n\n console.log(args);\n // Cconsole.log(opts);\n /**\n * Set option skip welcome message\n */\n this.option('skip-welcome-msg', {\n desc: 'Skips the welcome message',\n type: Boolean\n });\n\n /**\n * Set option skip install message\n */\n this.option('skip-install-msg', {\n desc: 'Skips the message after the installation of dependencies',\n type: Boolean\n });\n\n /**\n * Set option use feature for jquery or bootstrap\n */\n this.option('use-feature', {\n desc: 'Includes bootstrap or jquery: bs-reset, bs-grid, bs-modules, jquery or none',\n type: String\n });\n\n /**\n * Set option use velocity\n */\n this.option('use-velocity', {\n desc: 'Includes velocity',\n type: Boolean\n });\n\n /**\n * Set option use vrt (visual regression testing)\n */\n this.option('use-vrt', {\n desc: 'Includes a tool for Visual Regression Testing',\n type: Boolean\n });\n }", "function optimize(opts) {\n console.log('optimizing for requireJs');\n requirejs.optimize(opts);\n}", "function webpackCommonConfigCreator(options) {\r\n\r\n return {\r\n mode: options.mode, // 开发模式\r\n entry: \"./src/index.js\",\r\n externals: {\r\n \"react\": \"react\",\r\n \"react-dom\": \"react-dom\",\r\n // \"lodash\": \"lodash\",\r\n \"antd\": \"antd\",\r\n \"@fluentui/react\": \"@fluentui/react\",\r\n \"styled-components\": \"styled-components\"\r\n },\r\n output: {\r\n // filename: \"bundle.js\",\r\n // 分配打包后的目录,放于js文件夹下\r\n // filename: \"js/bundle.js\",\r\n // 对输出的 bundle.js 进行优化:分割输出,减小体积\r\n // filename: \"js/[name][hash].js\", // 改在 webpack.prod.js 和 webpack.dev.js 中根据不同环境配置不同的hash值\r\n path: path.resolve(__dirname, \"../build\"),\r\n publicPath: \"/\"\r\n },\r\n // 对输出的 bundle.js 进行优化:分割输出,减小体积\r\n optimization: {\r\n splitChunks: {\r\n chunks: \"all\",\r\n minSize: 50000,\r\n minChunks: 1,\r\n }\r\n },\r\n plugins: [\r\n // new HtmlWebpackPlugin(),\r\n new HtmlWebpackPlugin({\r\n template: path.resolve(__dirname, \"../public/index.html\"),\r\n // filename: \"./../html/index.html\", //编译后生成新的html文件路径\r\n // thunks: ['vendor', 'index'], // 需要引入的入口文件\r\n // excludeChunks: ['login'], // 不需要引入的入口文件\r\n favicon: path.resolve(__dirname, \"../src/assets/images/favicon.ico\") //favicon.ico文件路径\r\n }),\r\n new CleanWebpackPlugin({\r\n cleanOnceBeforeBuildPatterns: [path.resolve(process.cwd(), \"build/\"), path.resolve(process.cwd(), \"dist/\")]\r\n }),\r\n new ExtractTextPlugin({\r\n // filename: \"[name][hash].css\"\r\n // 分配打包后的目录,放于css文件夹下\r\n filename: \"css/[name][hash].css\"\r\n }),\r\n ],\r\n module: {\r\n rules: [\r\n {\r\n test: /\\.(js|jsx)$/,\r\n // include: path.resolve(__dirname, \"../src\"),\r\n // 用排除的方式,除了 /node_modules/ 都让 babel-loader 进行解析,这样一来就能解析引用的别的package中的组件了\r\n // exclude: /node_modules/,\r\n use: [\r\n {\r\n loader: \"babel-loader\",\r\n options: {\r\n presets: ['@babel/preset-react'],\r\n plugins: [\"react-hot-loader/babel\"]\r\n }\r\n }\r\n ]\r\n },\r\n // {\r\n // test: /\\.html$/,\r\n // use: [\r\n // {\r\n // loader: 'html-loader'\r\n // }\r\n // ]\r\n // },\r\n // {\r\n // test: /\\.css$/,\r\n // use: [MiniCssExtractPlugin.loader, 'css-loader']\r\n // },\r\n {\r\n // test: /\\.css$/,\r\n test: /\\.(css|scss)$/,\r\n // test: /\\.scss$/,\r\n // include: path.resolve(__dirname, '../src'),\r\n exclude: /node_modules/,\r\n // 进一步优化 配置css-module模式(样式模块化),将自动生成的样式抽离到单独的文件中\r\n use: ExtractTextPlugin.extract({\r\n fallback: \"style-loader\",\r\n use: [\r\n {\r\n loader: \"css-loader\",\r\n options: {\r\n modules: {\r\n mode: \"local\",\r\n localIdentName: '[path][name]_[local]--[hash:base64:5]'\r\n },\r\n localsConvention: 'camelCase'\r\n }\r\n },\r\n \"sass-loader\",\r\n // 使用postcss对css3属性添加前缀\r\n {\r\n loader: \"postcss-loader\",\r\n options: {\r\n ident: 'postcss',\r\n plugins: loader => [\r\n require('postcss-import')({ root: loader.resourcePath }),\r\n require('autoprefixer')()\r\n ]\r\n }\r\n }\r\n ]\r\n })\r\n },\r\n {\r\n test: /\\.less$/,\r\n use: [\r\n { loader: 'style-loader' },\r\n { loader: 'css-loader' },\r\n {\r\n loader: 'less-loader',\r\n options: {\r\n // modifyVars: {\r\n // 'primary-color': '#263961',\r\n // 'link-color': '#263961'\r\n // },\r\n javascriptEnabled: true\r\n }\r\n }\r\n ]\r\n },\r\n // 为第三方包配置css解析,将样式表直接导出\r\n {\r\n test: /\\.(css|scss|less)$/,\r\n exclude: path.resolve(__dirname, '../src'),\r\n use: [\r\n \"style-loader\",\r\n \"css-loader\",\r\n \"sass-loader\",\r\n \"less-loader\"\r\n // {\r\n // loader: 'file-loader',\r\n // options: {\r\n // name: \"css/[name].css\"\r\n // }\r\n // }\r\n ]\r\n },\r\n // 字体加载器 (前提:yarn add file-loader -D)\r\n {\r\n test: /\\.(woff|woff2|eot|ttf|otf)$/,\r\n use: ['file-loader']\r\n },\r\n // 图片加载器 (前提:yarn add url-loader -D)\r\n {\r\n test: /\\.(jpg|png|svg|gif)$/,\r\n use: [\r\n {\r\n loader: 'url-loader',\r\n options: {\r\n limit: 10240,\r\n // name: '[hash].[ext]',\r\n // 分配打包后的目录,放于images文件夹下\r\n name: 'images/[hash].[ext]',\r\n publicPath: \"/\"\r\n }\r\n },\r\n ]\r\n },\r\n ]\r\n },\r\n // 后缀自动补全\r\n resolve: {\r\n // symlinks: false,\r\n extensions: ['.js', '.jsx', '.png', '.svg'],\r\n alias: {\r\n src: path.resolve(__dirname, '../src'),\r\n components: path.resolve(__dirname, '../src/components'),\r\n routes: path.resolve(__dirname, '../src/routes'),\r\n utils: path.resolve(__dirname, '../src/utils'),\r\n api: path.resolve(__dirname, '../src/api')\r\n }\r\n }\r\n }\r\n}", "function build(args, appConfig, cb) {\n if (args._.length === 1) {\n return cb(new _errors.UserError('An entry module must be specified.'));\n }\n\n let dist = args._[2] || 'dist';\n\n (0, _runSeries2.default)([cb => (0, _utils.install)(appConfig.getQuickDependencies(), { args, check: true }, cb), cb => (0, _cleanApp2.default)({ _: ['clean-app', dist] }, cb), cb => (0, _webpackBuild2.default)(`${appConfig.getName()} app`, args, () => createBuildConfig(args, appConfig.getQuickBuildConfig()), cb)], cb);\n}", "function cli(options) {\n // if all option is passed, do not pass go, do not collect 200 dollars, go straight to main\n if (options.all) {\n return main(\n Object.assign({}, presets.defaults, { npmPackages: true, npmGlobalPackages: true }),\n options\n );\n }\n // if raw, parse the row options and skip to main\n if (options.raw) return main(JSON.parse(options.raw), options);\n // if helper flag, run just that helper then log the results\n if (options.helper) {\n const helper =\n helpers[`get${options.helper}`] ||\n helpers[`get${options.helper}Info`] ||\n helpers[options.helper];\n return helper ? helper().then(console.log) : console.error('Not Found'); // eslint-disable-line no-console\n }\n // generic function to make sure passed option exists in presets.defaults list\n // TODO: This will eventually be replaced with a better fuzzy finder.\n const matches = (list, opt) => list.toLowerCase().includes(opt.toLowerCase());\n // check cli options to see if any args are top level categories\n const categories = Object.keys(options).filter(o =>\n Object.keys(presets.defaults).some(c => matches(c, o))\n );\n // build the props object for filtering presets.defaults\n const props = Object.entries(presets.defaults).reduce((acc, entry) => {\n if (categories.some(c => matches(c, entry[0]))) {\n return Object.assign(acc, { [entry[0]]: entry[1] || options[entry[0]] });\n }\n return acc;\n }, {});\n // if there is a preset, merge that with the parsed props and options\n if (options.preset) {\n if (!presets[options.preset]) return console.error(`\\nNo \"${options.preset}\" preset found.`); // eslint-disable-line no-console\n return main(\n Object.assign({}, utils.omit(presets[options.preset], ['options']), props),\n Object.assign(\n {},\n presets[options.preset].options,\n utils.pick(options, ['duplicates', 'fullTree', 'json', 'markdown', 'console'])\n )\n );\n }\n // call the main function with the filtered props, and cli options\n return main(props, options);\n}", "function appFiles(opt) {\n return gulp.src(['./client/{app,components}/**/*.js', './.tmp/templates.js'], opt);\n}", "function generateFromOpts(opt) {\n var code = '';\n\n if (opt.moduleType === 'commonjs') {\n code = generateCommonJSModule(opt);\n } else if (opt.moduleType === 'amd') {\n code = generateAMDModule(opt);\n } else {\n code = generateModule(opt);\n }\n\n return code;\n}", "function generateFromOpts(opt) {\n var code = '';\n\n if (opt.moduleType === 'commonjs') {\n code = generateCommonJSModule(opt);\n } else if (opt.moduleType === 'amd') {\n code = generateAMDModule(opt);\n } else {\n code = generateModule(opt);\n }\n\n return code;\n}", "function generateFromOpts(opt) {\n var code = '';\n\n if (opt.moduleType === 'commonjs') {\n code = generateCommonJSModule(opt);\n } else if (opt.moduleType === 'amd') {\n code = generateAMDModule(opt);\n } else {\n code = generateModule(opt);\n }\n\n return code;\n}", "function combine() {\n utils.richlog(`vendor modules to combine: `, utils.LOGTYPE.INFO)\n console.log(entry)\n\n for (let entry_name in entry) {\n let code = {}\n let temp = [].concat(entry[entry_name])\n\n temp.forEach(function (v) {\n let module_path = '',\n mini = {}\n\n try {\n if (DOT_RE.test(v)) { // for vendor modules under src/vendor\n module_path = path.resolve(rootPath, v)\n } else { // for vendor modules under node_modules\n module_path = handleNodeMudulesPath(v)\n }\n\n mini = handleMini(module_path)\n code[mini.suffix] = (code[mini.suffix] || '') + mini.code\n } catch (err) {\n utils.log(`cannot find vendor: `, `${v}`, 'red')\n }\n\n })\n\n for (let entry_type in code) {\n mkdirSync(outputPath, function () {\n let file = path.join(outputPath, entry_name + '.' + entry_type)\n utils.richlog(`generated compressed vendor file: ${file}`, utils.LOGTYPE.SUCCESSFUL)\n fs.writeFileSync(file, code[entry_type])\n })\n }\n }\n}", "function commonjsMain(args) {\n if (!args[1]) {\n console.log('Usage: '+args[0]+' FILE');\n process.exit(1);\n }\n let source = fs.readFileSync(path.normalize(args[1]), 'utf8');\n return exports.parser.parse(source);\n}", "function bundler(options) {\n var allFiles = {};\n var bundles = {};\n var dir = options.src;\n var dest = options.dest;\n var resourcesFile = options.resourceJson;\n var indexBundles = options.indexBundles;\n var titleIndexBnudles = {};\n var traversed_bundles = {}, traversed_files = {}, excluded_bundles = {};\n var resourcesJs = {};\n for (var key in options) {\n resourcesJs[key] = options[key];\n }\n resourcesJs.bundles = bundles;\n\n function getFiles(packageName, files, bundledFile, includedBundles) {\n if (!traversed_bundles[packageName] && !excluded_bundles[packageName]) {\n traversed_bundles[packageName] = true;\n var bundle = resourcesJs.bundles[packageName];\n if (bundle) {\n bundle.bundled = bundle.bundled || [];\n bundle.bundled_html = bundle.bundled_html || [];\n bundle.in = bundle.in || [];\n for (var i in bundle.on) {\n files = getFiles(bundle.on[i], files, bundledFile, includedBundles);\n }\n for (var j in bundle.js) {\n var _file2 = cleanURL(dir + \"/\" + bundle.js[j]);\n if (!traversed_files[_file2]) {\n files.js.push(_file2);\n traversed_files[_file2] = packageName;\n }\n }\n if (files.js.length > 0) {\n bundle.bundled.push(bundledFile + \".js\");\n }\n\n for (var i in bundle.html) {\n var _file = cleanURL(dir + \"/\" + bundle.html[i]);\n if (!traversed_files[_file]) {\n files.html.push(_file);\n traversed_files[_file] = packageName;\n }\n }\n if (files.html.length > 0) {\n bundle.bundled_html.push(bundledFile + \".html\");\n }\n\n includedBundles.push(packageName);\n }\n }\n return files;\n }\n\n if (TASK_BUNDLIFY || TASK_SCAN) {\n grunt.file.recurse(dir, function(abspath, rootdir, subdir, filename) {\n if (filename === \"module.json\" && abspath.indexOf(dest) !== 0) {\n var packageInfo = {};\n if (grunt.file.exists(subdir + \"/.bower.json\")) {\n var bowerJson = grunt.file.readJSON(subdir + \"/.bower.json\");\n packageInfo.bowerName = bowerJson.name;\n packageInfo.bowerVersion = bowerJson.version;\n }\n if (grunt.file.exists(subdir + \"/composer.json\")) {\n var composerJson = grunt.file.readJSON(subdir + \"/composer.json\");\n packageInfo.composerName = composerJson.name;\n packageInfo.composerVersion = composerJson.version;\n }\n var _bundles = grunt.file.readJSON(abspath);\n var packageName = _bundles.name;\n if (_bundles.exclude) {\n for (var i in _bundles.exclude) {\n excluded_bundles[_bundles.exclude[i]] = true;\n }\n }\n if (packageName !== undefined) {\n titleIndexBnudles[packageName] = [];\n for (var bundleName in _bundles) {\n if ((bundleName === packageName || bundleName.indexOf(packageName + \"/\") === 0) && !excluded_bundles[bundleName]) {\n if (bundles[bundleName]) {\n console.log(\"====Duplicate Package\", bundleName);\n } else if (!toIgnore(bundleName)) {\n titleIndexBnudles[packageName].push(bundleName);\n }\n bundles[bundleName] = { js: [], on: [], css: [], html: [], packageInfo: packageInfo};\n for (var file_i in _bundles[bundleName].js) {\n var js_file = subdir + \"/\" + _bundles[bundleName].js[file_i];\n bundles[bundleName].js.push(js_file);\n if (!allFiles[js_file]) {\n allFiles[js_file] = js_file;\n } else {\n console.log(\"====Duplicate File\" + js_file);\n }\n }\n for (var file_j in _bundles[bundleName].css) {\n var css_file = subdir + \"/\" + _bundles[bundleName].css[file_j];\n bundles[bundleName].css.push(css_file);\n if (!allFiles[css_file]) {\n allFiles[css_file] = css_file;\n } else {\n console.log(\"====Duplicate File\" + css_file);\n }\n }\n for (var file_k in _bundles[bundleName].html) {\n var html_file = subdir + \"/\" + _bundles[bundleName].html[file_k];\n bundles[bundleName].html.push(html_file);\n if (!allFiles[html_file]) {\n allFiles[html_file] = html_file;\n } else {\n console.log(\"====Duplicate File\" + html_file);\n }\n }\n bundles[bundleName].on = _bundles[bundleName].on || [];\n console.log(\"╬═╬ Module.json\", abspath);\n //console.log(bundleName, _bundles[bundleName].on);\n }\n }\n }\n }\n });\n\n\n var titleIndexBnudlesNames = Object.keys(titleIndexBnudles);\n\n if (options.modulize) {\n titleIndexBnudlesNames.map(function(bundName) {\n if (!bundles[bundName] && !toIgnore(bundName)) {\n bundles[bundName] = { js: [], on: titleIndexBnudles[bundName], css: [], html: [], packageInfo: {}};\n console.log(\"New Package \", bundName, bundles[bundName]);\n }\n });\n }\n\n for (var packageKey in excluded_bundles) {\n delete bundles[packageKey];\n }\n\n var firstIndexBundled = null;\n\n if (!TASK_SKIP_INIT) {\n var myIndexBnudles = indexBundles;\n if (TASK_BUNDLIFY) {\n\n var moreBundles = Object.keys(bundles);\n\n if (options.sort) {\n moreBundles = moreBundles.sort();\n }\n\n if (options.projectPrefix !== undefined) {\n myIndexBnudles = uniqueArray(myIndexBnudles.concat(titleIndexBnudlesNames.concat(moreBundles).filter(function(bundleName) {\n return bundleName.indexOf(options.projectPrefix) === 0;\n })));\n }\n\n myIndexBnudles = uniqueArray(myIndexBnudles.concat(titleIndexBnudlesNames.concat(moreBundles))).filter(function(bundleName) {\n return !toIgnore(bundleName);\n });\n\n }\n console.log(\"Bundles in Order\", myIndexBnudles);\n\n var prevBundle = null;\n myIndexBnudles.forEach(function(bundleName) {\n var _bundleMap = {};\n var includedBundles = [];\n var bundledFile = dest + \"/bootloader_bundled/\" + bundleName.split(\"/\").join(\".\");\n var bundledFile_js = bundledFile + \".js\";\n var files = getFiles(bundleName, {js: [], html: []}, bundledFile, includedBundles);\n var js_files = uniqueArray(files.js.reverse()).reverse();\n if (js_files.length > 0) {\n if (!firstIndexBundled && options.resourcesInline) {\n firstIndexBundled = bundleName;\n js_files.unshift(resourcesFile + \".js\");\n }\n _bundleMap[bundledFile_js] = js_files;\n //console.log(\"files\",bundleName,files.length,files);\n setBundleConfig(bundleName, _bundleMap, includedBundles, bundledFile_js);\n\n if (prevBundle && options.order) {\n var bundle = resourcesJs.bundles[bundleName];\n if (bundle) {\n bundle.on = [prevBundle].concat(bundle.on);\n }\n }\n prevBundle = bundleName;\n\n } else console.log(\"╬═╬ No File in bundle to bundlify thus skipping \", bundleName);\n\n var html_files = uniqueArray(files.html.reverse()).reverse();\n if (html_files.length) {\n var html_file_content = \"\";\n for (var i in html_files) {\n html_file_content += '<script type=\"text/html\" src=\"' + html_files[i] + '\">' + grunt.file.read(html_files[i]).split(\"\\t\").join(\"\")\n .split(\"\\n\").join(\" \")\n .split(\">\").map(function(v) {\n return v.trim();\n }).join(\">\") + '</script>';\n }\n grunt.file.write(bundledFile + \".html\", html_file_content);\n }\n\n });\n\n resourcesJs.gitinfo = grunt.config().gitinfo;\n if (firstIndexBundled) {\n var resJsonString = JSON.stringify({\n RESOURCES_JSON: resourcesJs,\n RESOURCES_FILE: resourcesFile\n }).replace(/\\r?\\n|\\r|\\\\n/g, ' ');\n\n var packed = resJsonString;\n var unpack = \"\";\n if(options.jsonpack){\n var jsonpack = require('jsonpack/main');\n var fs = require(\"fs\");\n unpack = grunt.file.read('node_modules/jsonpack/main.js');\n packed =('(jsonpack.unpack(\\''+jsonpack.pack(resJsonString)+'\\'))');\n }\n\n grunt.file.write(resourcesFile + \".js\", unpack+\";var _BOOTLOADER_CONFIG_=\" + packed);\n resourcesJs.bundles[firstIndexBundled].js.unshift(resourcesFile + \".js\");\n }\n\n grunt.task.run(\"uglify\");\n }\n\n grunt.file.write(resourcesFile, JSON.stringify(resourcesJs));\n\n }\n }", "function buildMain() {\n const wrapper = fs.readFileSync('src/.wrapper.js', { encoding: 'utf8' })\n .split('@@js\\n');\n\n const files_to_load = [\n ...CORE_JS,\n ...Object.values(ALL_PLUGINS_JS),\n ];\n\n const output = BANNER()\n + '\\n\\n'\n + wrapper[0]\n + files_to_load.map(f => fs.readFileSync(f, { encoding: 'utf8' })).join('\\n\\n')\n + '\\n\\n'\n + getLang('en')\n + wrapper[1];\n\n const outpath = `${DIST}js/query-builder.js`;\n console.log(`MAIN (${outpath})`);\n fs.writeFileSync(outpath, output);\n}", "async function bundleMain() {\n\tconst result = await esbuild.build({\n\t\tentryPoints: [\"index.js\"],\n\t\tbundle: true,\n\t\tformat: \"iife\",\n\t\twrite: false,\n\t\tabsWorkingDir: workerPath,\n\t\tdefine: {\n\t\t\tglobal: \"globalThis\",\n\t\t},\n\t\tplugins: [\n\t\t\tNodeGlobalsPolyfillPlugin({ buffer: true }),\n\t\t\tNodeModulesPolyfillPlugin(),\n\t\t],\n\t});\n\n\tlet main = result.outputFiles[0].text;\n\n\t// Patch any dynamic imports (converting `require()` calls to `import()` calls).\n\tmain = main.replace(\n\t\t'installChunk(__require(\"./\" + __webpack_require__.u(chunkId))',\n\t\t'promises.push(import(\"./\" + __webpack_require__.u(chunkId)).then((mod) => installChunk(mod.default))'\n\t);\n\t// Export the fetch handler (grabbing it from the global).\n\tmain += \"\\nexport default { fetch : globalThis.__workerFetchHandler };\";\n\n\tawait fs.writeFile(path.resolve(workerPath, \"index.js\"), main);\n}", "function normalize(options, opts) {\n opts = opts || {};\n var rawOptions = Object.assign({}, options);\n var supportOptions = getSupportInfo(null, {\n plugins: options.plugins,\n showUnreleased: true,\n showDeprecated: true\n }).options;\n var defaults = supportOptions.reduce(function (reduced, optionInfo) {\n return optionInfo[\"default\"] !== undefined ? Object.assign(reduced, _defineProperty({}, optionInfo.name, optionInfo[\"default\"])) : reduced;\n }, Object.assign({}, hiddenDefaults));\n\n if (!rawOptions.parser) {\n if (!rawOptions.filepath) {\n var logger = opts.logger || console;\n logger.warn(\"No parser and no filepath given, using 'babel' the parser now \" + \"but this will throw an error in the future. \" + \"Please specify a parser or a filepath so one can be inferred.\");\n rawOptions.parser = \"babel\";\n } else {\n rawOptions.parser = inferParser(rawOptions.filepath, rawOptions.plugins);\n\n if (!rawOptions.parser) {\n throw new UndefinedParserError(\"No parser could be inferred for file: \".concat(rawOptions.filepath));\n }\n }\n }\n\n var parser = resolveParser(normalizer.normalizeApiOptions(rawOptions, [supportOptions.find(function (x) {\n return x.name === \"parser\";\n })], {\n passThrough: true,\n logger: false\n }));\n rawOptions.astFormat = parser.astFormat;\n rawOptions.locEnd = parser.locEnd;\n rawOptions.locStart = parser.locStart;\n var plugin = getPlugin(rawOptions);\n rawOptions.printer = plugin.printers[rawOptions.astFormat];\n var pluginDefaults = supportOptions.filter(function (optionInfo) {\n return optionInfo.pluginDefaults && optionInfo.pluginDefaults[plugin.name] !== undefined;\n }).reduce(function (reduced, optionInfo) {\n return Object.assign(reduced, _defineProperty({}, optionInfo.name, optionInfo.pluginDefaults[plugin.name]));\n }, {});\n var mixedDefaults = Object.assign({}, defaults, pluginDefaults);\n Object.keys(mixedDefaults).forEach(function (k) {\n if (rawOptions[k] == null) {\n rawOptions[k] = mixedDefaults[k];\n }\n });\n\n if (rawOptions.parser === \"json\") {\n rawOptions.trailingComma = \"none\";\n }\n\n return normalizer.normalizeApiOptions(rawOptions, supportOptions, Object.assign({\n passThrough: Object.keys(hiddenDefaults)\n }, opts));\n}", "function browserifyWrapper() {\n return browserify('./src/app.js', {\n debug: true\n }).transform(babel);\n}", "function generateFromOpts(opt) {\n var code = '';\n\n switch (opt.moduleType) {\n case 'js':\n code = generateModule(opt);\n break;\n case 'amd':\n code = generateAMDModule(opt);\n break;\n case 'es':\n code = generateESModule(opt);\n break;\n case 'commonjs':\n default:\n code = generateCommonJSModule(opt);\n break;\n }\n\n return code;\n}", "function getOptions(opts) {\n var options = {};\n\n for (var opt in defaultOptions)\n { options[opt] = opts && has(opts, opt) ? opts[opt] : defaultOptions[opt]; }\n\n if (options.ecmaVersion >= 2015)\n { options.ecmaVersion -= 2009; }\n\n if (options.allowReserved == null)\n { options.allowReserved = options.ecmaVersion < 5; }\n\n if (isArray(options.onToken)) {\n var tokens = options.onToken;\n options.onToken = function (token) { return tokens.push(token); };\n }\n if (isArray(options.onComment))\n { options.onComment = pushComment(options, options.onComment); }\n\n return options\n }", "function getOptions(opts) {\n var options = {};\n\n for (var opt in defaultOptions)\n { options[opt] = opts && has(opts, opt) ? opts[opt] : defaultOptions[opt]; }\n\n if (options.ecmaVersion >= 2015)\n { options.ecmaVersion -= 2009; }\n\n if (options.allowReserved == null)\n { options.allowReserved = options.ecmaVersion < 5; }\n\n if (isArray(options.onToken)) {\n var tokens = options.onToken;\n options.onToken = function (token) { return tokens.push(token); };\n }\n if (isArray(options.onComment))\n { options.onComment = pushComment(options, options.onComment); }\n\n return options\n }", "function getOptions(opts) {\n var options = {};\n for (var opt in defaultOptions) {\n options[opt] = opts && _util.has(opts, opt) ? opts[opt] : defaultOptions[opt];\n }if (options.allowReserved == null) options.allowReserved = options.ecmaVersion < 5;\n\n if (_util.isArray(options.onToken)) {\n (function () {\n var tokens = options.onToken;\n options.onToken = function (token) {\n return tokens.push(token);\n };\n })();\n }\n if (_util.isArray(options.onComment)) options.onComment = pushComment(options, options.onComment);\n\n return options;\n}", "function webpackConfigDev(options = {}) {\n // get the common configuration to start with\n const config = init(options);\n\n // // make \"dev\" specific changes here\n // const credentials = require(\"./credentials.json\");\n // credentials.branch = \"dev\";\n //\n // config.plugin(\"screeps\")\n // .use(ScreepsWebpackPlugin, [credentials]);\n\n // modify the args of \"define\" plugin\n config.plugin(\"define\").tap((args) => {\n args[0].PRODUCTION = JSON.stringify(false);\n return args;\n });\n\n return config;\n}", "function registryFromOptions(options) {\n if (options.requireAssets && options.mapping)\n return options;\n if (options.prefix || options.root)\n return requireAssets.createRegistry(options);\n return requireAssets.currentRegistry();\n}", "async bundleCwd(cwd, index) {\n return concat(cwd).then((result) => {\n let base = cwd.map((p) => p.split(path.sep));\n base = base.map((b) => b.filter((bb) => base[0].includes(bb)));\n\n const suffix = '.bundle';\n let bundle = path.resolve(\n path.join(\n path.dirname(base.sort((a, b) => a.length - b.length)[0].join(path.sep)),\n `${Object.keys(this.config.entry)[index]}${suffix}${path.extname(cwd[0])}`\n )\n );\n\n const directory = bundle.substring(0, bundle.indexOf('.bundle'));\n // Check if the current bundle can be placed.\n if (fs.existsSync(directory) && fs.lstatSync(directory).isDirectory()) {\n this.Console.info(`Compatible bundle directory detected, writing to ${directory}`);\n bundle = path.join(directory, path.basename(bundle));\n }\n\n mkdirp.sync(path.dirname(bundle));\n\n try {\n const minifiedResult = minify(result, this.getOption('minify', {}));\n\n if (minifiedResult.error || !minifiedResult.code) {\n this.Console.log(`Writing bundle: ${bundle}`);\n\n fs.writeFileSync(bundle, result);\n } else {\n this.Console.log(`Writing minified bundle: ${bundle}`);\n\n fs.writeFileSync(bundle, minifiedResult.code);\n }\n } catch (error) {\n this.Console.warning(`Unable to bundle: ${error}`);\n }\n });\n }", "extend (config, ctx) {\n const path = require('path')\n const WorkboxPlugin = require('workbox-webpack-plugin')\n const WebpackPwaManifest = require('webpack-pwa-manifest')\n const IdGuideDataProcessorPlugin = require('./webpack/id-guide-data-processor-plugin')\n\n config.plugins.push(\n new WorkboxPlugin.GenerateSW({\n swDest: `service-worker-${config.id}.js`,\n clientsClaim: true,\n skipWaiting: true,\n cacheId: `${config.id}`,\n maximumFileSizeToCacheInBytes: 9999 * 1024 * 1024\n }),\n new WebpackPwaManifest({\n name: config.name,\n short_name: config.short_name,\n description: config.description,\n background_color: config.background_color,\n crossorigin: 'use-credentials',\n theme_color: config.theme_color,\n start_url: config.start_url,\n icons: [\n {\n src: './assets/img/icon.png',\n sizes: [36, 48, 192, 512]\n },\n {\n src: './assets/img/icon.png',\n sizes: [36, 48, 192, 512, 1024],\n destination: path.join('icons', 'ios'),\n ios: true\n }\n ]\n // }),\n // new IdGuideDataProcessorPlugin({\n // dataDir: 'assets/data',\n // candidateDir: 'candidates',\n // questionDir: 'questions'\n })\n )\n }", "setDriverOpts (opts) {\n debug('set driver opts', opts)\n this.driverOpts = this.testRunner.match(/phantom/)\n ? opts\n : {}\n\n // Don't do anything for chrome here.\n if (this.testRunner.match(/chrome/)) {\n return\n }\n\n if (opts.parameters) {\n this.driverOpts.parameters = opts.parameters\n }\n\n this.driverOpts.path = require(this.testRunner).path\n\n // The dnode `weak` dependency is failing to install on travis.\n // Disable this for now until someone needs it.\n this.driverOpts.dnodeOpts = { weak: false }\n }", "function getOptions(opts) {\n var options = {};\n\n for (var opt in defaultOptions)\n { options[opt] = opts && has(opts, opt) ? opts[opt] : defaultOptions[opt]; }\n\n if (options.ecmaVersion >= 2015)\n { options.ecmaVersion -= 2009; }\n\n if (options.allowReserved == null)\n { options.allowReserved = options.ecmaVersion < 5; }\n\n if (isArray(options.onToken)) {\n var tokens = options.onToken;\n options.onToken = function (token) { return tokens.push(token); };\n }\n if (isArray(options.onComment))\n { options.onComment = pushComment(options, options.onComment); }\n\n return options\n}", "function getOptions(opts) {\n var options = {};\n\n for (var opt in defaultOptions)\n { options[opt] = opts && has(opts, opt) ? opts[opt] : defaultOptions[opt]; }\n\n if (options.ecmaVersion >= 2015)\n { options.ecmaVersion -= 2009; }\n\n if (options.allowReserved == null)\n { options.allowReserved = options.ecmaVersion < 5; }\n\n if (isArray(options.onToken)) {\n var tokens = options.onToken;\n options.onToken = function (token) { return tokens.push(token); };\n }\n if (isArray(options.onComment))\n { options.onComment = pushComment(options, options.onComment); }\n\n return options\n}", "function getOptions(opts) {\n var options = {};\n\n for (var opt in defaultOptions)\n { options[opt] = opts && has(opts, opt) ? opts[opt] : defaultOptions[opt]; }\n\n if (options.ecmaVersion >= 2015)\n { options.ecmaVersion -= 2009; }\n\n if (options.allowReserved == null)\n { options.allowReserved = options.ecmaVersion < 5; }\n\n if (isArray(options.onToken)) {\n var tokens = options.onToken;\n options.onToken = function (token) { return tokens.push(token); };\n }\n if (isArray(options.onComment))\n { options.onComment = pushComment(options, options.onComment); }\n\n return options\n}", "function getOptions(opts) {\n var options = {};\n\n for (var opt in defaultOptions)\n { options[opt] = opts && has(opts, opt) ? opts[opt] : defaultOptions[opt]; }\n\n if (options.ecmaVersion >= 2015)\n { options.ecmaVersion -= 2009; }\n\n if (options.allowReserved == null)\n { options.allowReserved = options.ecmaVersion < 5; }\n\n if (isArray(options.onToken)) {\n var tokens = options.onToken;\n options.onToken = function (token) { return tokens.push(token); };\n }\n if (isArray(options.onComment))\n { options.onComment = pushComment(options, options.onComment); }\n\n return options\n}", "function getOptions(opts) {\n var options = {};\n\n for (var opt in defaultOptions)\n { options[opt] = opts && has(opts, opt) ? opts[opt] : defaultOptions[opt]; }\n\n if (options.ecmaVersion >= 2015)\n { options.ecmaVersion -= 2009; }\n\n if (options.allowReserved == null)\n { options.allowReserved = options.ecmaVersion < 5; }\n\n if (isArray(options.onToken)) {\n var tokens = options.onToken;\n options.onToken = function (token) { return tokens.push(token); };\n }\n if (isArray(options.onComment))\n { options.onComment = pushComment(options, options.onComment); }\n\n return options\n}", "function getOptions(opts) {\n var options = {};\n\n for (var opt in defaultOptions)\n { options[opt] = opts && has(opts, opt) ? opts[opt] : defaultOptions[opt]; }\n\n if (options.ecmaVersion >= 2015)\n { options.ecmaVersion -= 2009; }\n\n if (options.allowReserved == null)\n { options.allowReserved = options.ecmaVersion < 5; }\n\n if (isArray(options.onToken)) {\n var tokens = options.onToken;\n options.onToken = function (token) { return tokens.push(token); };\n }\n if (isArray(options.onComment))\n { options.onComment = pushComment(options, options.onComment); }\n\n return options\n}", "function getOptions(opts) {\n var options = {};\n\n for (var opt in defaultOptions)\n { options[opt] = opts && has(opts, opt) ? opts[opt] : defaultOptions[opt]; }\n\n if (options.ecmaVersion >= 2015)\n { options.ecmaVersion -= 2009; }\n\n if (options.allowReserved == null)\n { options.allowReserved = options.ecmaVersion < 5; }\n\n if (isArray(options.onToken)) {\n var tokens = options.onToken;\n options.onToken = function (token) { return tokens.push(token); };\n }\n if (isArray(options.onComment))\n { options.onComment = pushComment(options, options.onComment); }\n\n return options\n}", "function getOptions(opts) {\n var options = {};\n\n for (var opt in defaultOptions)\n { options[opt] = opts && has(opts, opt) ? opts[opt] : defaultOptions[opt]; }\n\n if (options.ecmaVersion >= 2015)\n { options.ecmaVersion -= 2009; }\n\n if (options.allowReserved == null)\n { options.allowReserved = options.ecmaVersion < 5; }\n\n if (isArray(options.onToken)) {\n var tokens = options.onToken;\n options.onToken = function (token) { return tokens.push(token); };\n }\n if (isArray(options.onComment))\n { options.onComment = pushComment(options, options.onComment); }\n\n return options\n}", "function getOptions(opts) {\n var options = {};\n\n for (var opt in defaultOptions)\n { options[opt] = opts && has(opts, opt) ? opts[opt] : defaultOptions[opt]; }\n\n if (options.ecmaVersion >= 2015)\n { options.ecmaVersion -= 2009; }\n\n if (options.allowReserved == null)\n { options.allowReserved = options.ecmaVersion < 5; }\n\n if (isArray(options.onToken)) {\n var tokens = options.onToken;\n options.onToken = function (token) { return tokens.push(token); };\n }\n if (isArray(options.onComment))\n { options.onComment = pushComment(options, options.onComment); }\n\n return options\n}", "function getOptions(opts) {\n var options = {};\n\n for (var opt in defaultOptions)\n { options[opt] = opts && has(opts, opt) ? opts[opt] : defaultOptions[opt]; }\n\n if (options.ecmaVersion >= 2015)\n { options.ecmaVersion -= 2009; }\n\n if (options.allowReserved == null)\n { options.allowReserved = options.ecmaVersion < 5; }\n\n if (isArray(options.onToken)) {\n var tokens = options.onToken;\n options.onToken = function (token) { return tokens.push(token); };\n }\n if (isArray(options.onComment))\n { options.onComment = pushComment(options, options.onComment); }\n\n return options\n}", "function getPackageOptions() {\n var pkg;\n var options = {};\n\n try {\n pkg = require(process.cwd() + '/package.json');\n } catch (e) {}\n\n if (!pkg || !pkg.stylify) {\n return options;\n }\n\n if (pkg.stylify.use) {\n options.use = pkg.stylify.use;\n }\n if (pkg.stylify.paths) {\n options.set = {\n paths: pkg.stylify.paths\n };\n }\n return options;\n}", "packageFilter(pkg) {\n\n extensions.forEach(ext => {\n if (pkg[`main.${ext}`]) {\n pkg.main = pkg[`main.${ext}`];\n }\n });\n\n if (!pkg.main) {\n pkg.main = pkg.style;\n }\n\n return pkg;\n }", "function bundle() {\n return b.bundle()\n .on('error', gutil.log.bind(gutil, 'Browserify Error'))\n .pipe(source('bundle.js'))\n .pipe(buffer())\n .pipe(sourcemaps.init({loadMaps: true}))\n .pipe(gutil.env.type === 'production' ? uglify() : gutil.noop())\n .pipe(gutil.env.type !== 'production' ? sourcemaps.write('.', {sourceRoot: '/assets/js'}): gutil.noop())\n .pipe(gutil.env.type === 'production' ? gutil.noop() : gulp.dest('./assets/js'))\n .pipe(gutil.env.type === 'production' ? rename({suffix: '.min'}) : gutil.noop())\n .pipe(gutil.env.type === 'production' ? gulp.dest('./assets/js') : gutil.noop())\n .pipe(gutil.env.type === 'production' ? stripDebug() : gutil.noop())\n .pipe(livereload({start: true}));\n}", "function bundle() {\n return bundler.bundle()\n //log les erreurs quand elles surviennent\n .on('error', gutil.log.bind(gutil, 'Browserify Error'))\n .pipe(source('bundle.js'))\n //optionnel, permet de bufferiser le contenu des fichiers pour améliorer les perf du build\n .pipe(buffer())\n //optionnel, permet d'ajouter les sourcemaps pour le debug\n .pipe(sourcemaps.init({loadMaps: true}))\n //Ecrit les fichiers .map\n .pipe(sourcemaps.write('./'))\n //Copie le tout dans le répertoire final\n .pipe(gulp.dest(paths.app + '/scripts'))\n //Stream le résultat à BrowserSync pour qu'il recharge auto la page\n .pipe(browserSync.stream());\n}", "function load_shims(paths, cb) {\n // identify if our file should be replaced per the browser field\n // original filename|id -> replacement\n var shims = {};\n\n (function next() {\n var cur_path = paths.shift();\n if (!cur_path) {\n return cb(null, shims);\n }\n\n var pkg_path = path.join(cur_path, 'package.json');\n\n fs.readFile(pkg_path, 'utf8', function(err, data) {\n if (err) {\n // ignore paths we can't open\n // avoids an exists check\n if (err.code === 'ENOENT') {\n return next();\n }\n\n return cb(err);\n }\n\n try {\n var info = JSON.parse(data);\n }\n catch (err) {\n err.message = pkg_path + ' : ' + err.message\n return cb(err);\n }\n\n // support legacy browserify field for easier migration from legacy\n // many packages used this field historically\n if (typeof info.browserify === 'string' && !info.browser) {\n info.browser = info.browserify;\n }\n\n // no replacements, skip shims\n if (!info.browser) {\n return cb(null, shims);\n }\n\n // if browser field is a string\n // then it just replaces the main entry point\n if (typeof info.browser === 'string') {\n var key = path.resolve(cur_path, info.main || 'index.js');\n shims[key] = path.resolve(cur_path, info.browser);\n return cb(null, shims);\n }\n\n // http://nodejs.org/api/modules.html#modules_loading_from_node_modules_folders\n Object.keys(info.browser).forEach(function(key) {\n if (info.browser[key] === false) {\n return shims[key] = __dirname + '/empty.js';\n }\n\n var val = info.browser[key];\n\n // if target is a relative path, then resolve\n // otherwise we assume target is a module\n if (val[0] === '.') {\n val = path.resolve(cur_path, val);\n }\n\n // if does not begin with / ../ or ./ then it is a module\n if (key[0] !== '/' && key[0] !== '.') {\n return shims[key] = val;\n }\n\n var key = path.resolve(cur_path, key);\n shims[key] = val;\n });\n return cb(null, shims);\n });\n })();\n}", "function bundle() {\n return browserify(nodeDir, {\n standalone: bundleGlobal\n })\n .bundle()\n .on(\"error\", handleError)\n .pipe(source(bundleFile))\n .pipe(buffer())\n .pipe(gulpSourcemaps.init({\n loadMaps: true\n }))\n .pipe(gulpSourcemaps.write(\".\", {\n sourceRoot: path.relative(bundleDir, nodeDir)\n }))\n .pipe(gulp.dest(bundleDir));\n}", "function normalize$1(options, opts) {\n opts = opts || {};\n const rawOptions = Object.assign({}, options);\n const supportOptions = getSupportInfo$2({\n plugins: options.plugins,\n showUnreleased: true,\n showDeprecated: true\n }).options;\n const defaults = Object.assign({}, hiddenDefaults, fromPairs_1(supportOptions.filter(optionInfo => optionInfo.default !== undefined).map(option => [option.name, option.default])));\n\n if (!rawOptions.parser) {\n if (!rawOptions.filepath) {\n const logger = opts.logger || console;\n logger.warn(\"No parser and no filepath given, using 'babel' the parser now \" + \"but this will throw an error in the future. \" + \"Please specify a parser or a filepath so one can be inferred.\");\n rawOptions.parser = \"babel\";\n } else {\n rawOptions.parser = inferParser(rawOptions.filepath, rawOptions.plugins);\n\n if (!rawOptions.parser) {\n throw new UndefinedParserError$1(`No parser could be inferred for file: ${rawOptions.filepath}`);\n }\n }\n }\n\n const parser = resolveParser$1(optionsNormalizer.normalizeApiOptions(rawOptions, [supportOptions.find(x => x.name === \"parser\")], {\n passThrough: true,\n logger: false\n }));\n rawOptions.astFormat = parser.astFormat;\n rawOptions.locEnd = parser.locEnd;\n rawOptions.locStart = parser.locStart;\n const plugin = getPlugin(rawOptions);\n rawOptions.printer = plugin.printers[rawOptions.astFormat];\n const pluginDefaults = supportOptions.filter(optionInfo => optionInfo.pluginDefaults && optionInfo.pluginDefaults[plugin.name] !== undefined).reduce((reduced, optionInfo) => Object.assign(reduced, {\n [optionInfo.name]: optionInfo.pluginDefaults[plugin.name]\n }), {});\n const mixedDefaults = Object.assign({}, defaults, pluginDefaults);\n Object.keys(mixedDefaults).forEach(k => {\n if (rawOptions[k] == null) {\n rawOptions[k] = mixedDefaults[k];\n }\n });\n\n if (rawOptions.parser === \"json\") {\n rawOptions.trailingComma = \"none\";\n }\n\n return optionsNormalizer.normalizeApiOptions(rawOptions, supportOptions, Object.assign({\n passThrough: Object.keys(hiddenDefaults)\n }, opts));\n}", "function setPkgConfig(loader, pkgName, cfg, prependConfig) {\n var pkg;\n\n // first package is config by reference for fast path, cloned after that\n if (!loader.packages[pkgName]) {\n pkg = loader.packages[pkgName] = cfg;\n }\n else {\n var basePkg = loader.packages[pkgName];\n pkg = loader.packages[pkgName] = {};\n\n extendPkgConfig(pkg, prependConfig ? cfg : basePkg, pkgName, loader, prependConfig);\n extendPkgConfig(pkg, prependConfig ? basePkg : cfg, pkgName, loader, !prependConfig);\n }\n \n // main object becomes main map\n if (typeof pkg.main == 'object') {\n pkg.map = pkg.map || {};\n pkg.map['./@main'] = pkg.main;\n pkg.main['default'] = pkg.main['default'] || './';\n pkg.main = '@main';\n }\n\n return pkg;\n}", "addChunkSplitting(options) {\n if (options.target === \"production\") {\n // replace the single production entry point by a dictionary of entry points\n const oldEntryPoint = this.config.entry;\n this.config.entry = {\n main: oldEntryPoint,\n vendor: \"./src/js/vendor.ts\"\n };\n\n // make sure that code that overlaps between the chunks only gets placed in the vendor chunk\n this.config.plugins.push(new webpack.optimize.CommonsChunkPlugin({\n name: \"vendor\"\n }));\n\n // change the fixed bundle names into names equal to those of their entry points\n this.config.output.filename = \"[name].js\";\n }\n return this;\n }", "function main(opts, cb) {\n function onSources(err, sources) {\n if(err) {\n return cb(err); \n }\n if(!sources.length) {\n return cb(new Error('no input markdown definition files found')); \n }\n build(sources, opts, cb);\n }\n collect(opts.files, opts, onSources);\n}", "function compileFiles(appName) {\n\n let stream;\n\n const cssOnly = process.argv.indexOf('--css-only') !== -1;\n const jsOnly = process.argv.indexOf('--js-only') !== -1;\n\n let styles;\n let scripts;\n\n if (cssOnly) {\n\n styles = css();\n\n stream = styles;\n }\n\n if (jsOnly) {\n\n scripts = js();\n\n stream = scripts;\n }\n\n if (!cssOnly && !jsOnly) {\n\n styles = css();\n scripts = js();\n\n stream = merge(styles, scripts);\n }\n\n return stream;\n\n // realiza processos para gerar os arquivos js\n function js() {\n\n let streamJs = gulp.src('.');\n\n const tsPath = `${src.ts}/inits/${appName}.init.ts`;\n\n if (fs.existsSync(tsPath)) {\n\n // 1 - pegue o arquivo \"init\" typescript do app\n // 2 - compile o arquivo para javascript\n // 3 - aplique pollyfills caso seja necessário \n let scripts = browserify(tsPath)\n .plugin(tsify, { typeRoots: [\"./node_modules/@types\", \"./type-definitions\"], target: \"esnext\" })\n .transform(stringify, {\n appliesTo: { includeExtensions: ['.html'] },\n minify: true,\n minifyOptions: {\n collapseBooleanAttributes: true,\n collapseInlineTagWhitespace: true,\n collapseWhitespace: true,\n removeEmptyAttributes: true,\n removeRedundantAttributes: true,\n sortAttributes: true,\n sortClassName: true,\n trimCustomFragments: true\n }\n })\n .transform(babelify, {\n presets: [\n [\n '@babel/preset-env',\n {\n 'useBuiltIns': 'usage',\n 'corejs': 3\n }\n ]\n ],\n extensions: ['.ts']\n })\n .transform('exposify', { expose: { angular: 'angular' }, filePattern: /\\.ts/ })\n .external(['angular']);\n\n // se solicitado a minificação...\n if (production) {\n\n // aplique os seguintes plugins:\n // 1 - Aplique as configurações de produção\n // 2 - Minifique cada módulo (arquivo .ts) individualmente\n // 3 - Remove exports não utilizados\n // 4 - Simplifica os 'require' do js final para variáveis\n scripts = scripts.transform('envify', { global: true })\n .transform(uglifyify, { global: true })\n .plugin('common-shakeify')\n .plugin('browser-pack-flat/plugin');\n }\n\n // junte os arquivos e coloque o arquivo final na pasta de destino\n scripts = scripts.bundle();\n\n // se solicitado a minificação...\n if (production) {\n\n // aplique o seguinte plugin:\n // 1 - minifica o arquivo js final\n scripts = scripts.pipe(minifyStream({ sourceMap: false }));\n }\n\n scripts = scripts.pipe(source(`${appName}.min.js`))\n .pipe(buffer());\n\n scripts = scripts.pipe(gulp.dest(dest.js));\n\n streamJs = scripts;\n }\n\n return streamJs;\n }\n\n // realiza processos para gerar os arquivos css\n function css() {\n\n // 1 - pegue o arquivo sass/scss referente ao app\n // 2 - compile o arquivo para css\n // 3 - aplique atributos compatíveis com a versão de browser especificada na propriedade \"browserslist\" do arquivo package.json\n // 4 - crie os arquivos e coloque o compilado css na pasta de destino\n // 5 - minifique o arquivo css\n // 6 - renomeie o arquivo minificado\n // 7 - coloque minificado css na pasta de destino\n let css = gulp.src(`${src.sass}/${appName}.{scss,sass}`)\n .pipe(sassCompiler().on('error', sassCompiler.logError))\n .pipe(autoprefixer())\n .pipe(csso())\n .pipe(rename({ extname: '.min.css' }))\n .pipe(gulp.dest(dest.css));\n\n if (uploadFiles) {\n\n // aplique a stream de upload de arquivos\n css = upload(css, dest.css);\n }\n\n return css;\n }\n}", "function main(opts) {\n\n _.defaults(opts, {\n beforeStart: (live) => {},\n })\n\n // Locate and register plugins.\n\n if (!__CLIENT__) {\n locator().map(file => {\n const module = require(file)\n live.register(module, file)\n })\n } else {\n Object.keys(window.livePlugins).map(file => {\n const module = window.livePlugins[file]\n live.register(module, file)\n })\n }\n\n opts.beforeStart(live)\n\n // Start app.\n\n live.start().then(() => {\n // App has now started.\n })\n\n return live\n\n}", "function readFableConfigOptions(opts) {\n opts.workingDir = path.resolve(opts.workingDir || process.cwd());\n if (typeof opts.projFile === \"string\") {\n opts.projFile = [opts.projFile];\n }\n var cfgFile = fableLib.pathJoin(opts.workingDir, constants.FABLE_CONFIG_FILE);\n\n if (Array.isArray(opts.projFile) && opts.projFile.length === 1) {\n var fullProjFile = fableLib.pathJoin(opts.workingDir, opts.projFile[0]);\n var projDir = fs && fs.statSync(fullProjFile).isDirectory()\n ? fullProjFile\n : path.dirname(fullProjFile);\n cfgFile = fableLib.pathJoin(projDir, constants.FABLE_CONFIG_FILE);\n\n // Delete projFile from opts if it isn't a true F# project\n if (!fableLib.isFSharpProject(fullProjFile)) {\n delete opts.projFile;\n }\n }\n\n if (fs && fs.existsSync(cfgFile)) {\n // Change workingDir to where fableconfig.json is if necessary\n if (opts.workingDir !== path.dirname(cfgFile)) {\n for (var key in opts) {\n opts[key] = resolvePath(key, opts[key], opts.workingDir);\n }\n opts.workingDir = path.dirname(cfgFile);\n }\n\n var cfg = require('json5').parse(fs.readFileSync(cfgFile).toString());\n for (var key in cfg) {\n if (key in opts === false)\n opts[key] = cfg[key];\n }\n // Check if a target is requested\n if (opts.debug) { opts.target = \"debug\" }\n if (opts.production) { opts.target = \"production\" }\n if (opts.target) {\n if (!opts.targets || !opts.targets[opts.target]) {\n throw \"Target \" + opts.target + \" is missing\";\n }\n cfg = opts.targets[opts.target];\n for (key in cfg) {\n if ((typeof cfg[key] === \"object\") && !Array.isArray(cfg[key]) &&\n (typeof opts[key] === \"object\") && !Array.isArray(opts[key])) {\n for (var key2 in cfg[key])\n opts[key][key2] = cfg[key][key2];\n }\n else {\n opts[key] = cfg[key];\n }\n }\n }\n }\n return opts;\n}", "function cons() {\n return src([\n 'src/js/jquery.custom.min.js',\n 'src/js/menu.min.js',\n 'src/js/swiper.custom.min.js',\n ], { sourcemaps: true })\n .pipe(concat('app.min.js'))\n .pipe(dest('dist/', { sourcemaps: true }))\n}", "function compilerArgsFromOptions(options, logWarning) {\n return _.flatten(_.map(options, function(value, opt) {\n if (value) {\n switch(opt) {\n case \"yes\": return [\"--yes\"];\n case \"help\": return [\"--help\"];\n case \"output\": return [\"--output\", escapePath(value)];\n default:\n if (supportedOptions.indexOf(opt) === -1) {\n logWarning('Unknown Elm compiler option: ' + opt);\n }\n\n return [];\n }\n } else {\n return [];\n }\n }));\n}", "function processOptions(options) {\n\t // Parse preset names\n\t var presets = (options.presets || []).map(function (presetName) {\n\t var preset = loadBuiltin(availablePresets, presetName);\n\n\t if (preset) {\n\t // workaround for babel issue\n\t // at some point, babel copies the preset, losing the non-enumerable\n\t // buildPreset key; convert it into an enumerable key.\n\t if (isArray(preset) && _typeof(preset[0]) === 'object' && preset[0].hasOwnProperty('buildPreset')) {\n\t preset[0] = _extends({}, preset[0], { buildPreset: preset[0].buildPreset });\n\t }\n\t } else {\n\t throw new Error('Invalid preset specified in Babel options: \"' + presetName + '\"');\n\t }\n\t return preset;\n\t });\n\n\t // Parse plugin names\n\t var plugins = (options.plugins || []).map(function (pluginName) {\n\t var plugin = loadBuiltin(availablePlugins, pluginName);\n\n\t if (!plugin) {\n\t throw new Error('Invalid plugin specified in Babel options: \"' + pluginName + '\"');\n\t }\n\t return plugin;\n\t });\n\n\t return _extends({\n\t babelrc: false\n\t }, options, {\n\t presets: presets,\n\t plugins: plugins\n\t });\n\t}", "function processOptions(options) {\n\t // Parse preset names\n\t var presets = (options.presets || []).map(function (presetName) {\n\t var preset = loadBuiltin(availablePresets, presetName);\n\n\t if (preset) {\n\t // workaround for babel issue\n\t // at some point, babel copies the preset, losing the non-enumerable\n\t // buildPreset key; convert it into an enumerable key.\n\t if (isArray(preset) && _typeof(preset[0]) === 'object' && preset[0].hasOwnProperty('buildPreset')) {\n\t preset[0] = _extends({}, preset[0], { buildPreset: preset[0].buildPreset });\n\t }\n\t } else {\n\t throw new Error('Invalid preset specified in Babel options: \"' + presetName + '\"');\n\t }\n\t return preset;\n\t });\n\n\t // Parse plugin names\n\t var plugins = (options.plugins || []).map(function (pluginName) {\n\t var plugin = loadBuiltin(availablePlugins, pluginName);\n\n\t if (!plugin) {\n\t throw new Error('Invalid plugin specified in Babel options: \"' + pluginName + '\"');\n\t }\n\t return plugin;\n\t });\n\n\t return _extends({\n\t babelrc: false\n\t }, options, {\n\t presets: presets,\n\t plugins: plugins\n\t });\n\t}", "function normalizeConfig(config) {\n const cwd = process.cwd();\n config.knownEntrypoints = config.install || [];\n config.installOptions.dest = path.resolve(cwd, config.installOptions.dest);\n config.devOptions.out = path.resolve(cwd, config.devOptions.out);\n config.exclude = Array.from(new Set([...ALWAYS_EXCLUDE, ...config.exclude]));\n\n if (!config.scripts) {\n config.exclude.push('**/.*');\n config.scripts = {\n 'mount:*': 'mount . --to /'\n };\n }\n\n if (!config.proxy) {\n config.proxy = {};\n }\n\n const allPlugins = {}; // remove leading/trailing slashes\n\n config.buildOptions.metaDir = config.buildOptions.metaDir.replace(/^(\\/|\\\\)/g, '') // replace leading slash\n .replace(/(\\/|\\\\)$/g, ''); // replace trailing slash\n\n config.plugins = config.plugins.map(plugin => {\n const configPluginPath = Array.isArray(plugin) ? plugin[0] : plugin;\n const configPluginOptions = Array.isArray(plugin) && plugin[1] || {};\n\n const configPluginLoc = require.resolve(configPluginPath, {\n paths: [cwd]\n });\n\n const configPlugin = require(configPluginLoc)(config, configPluginOptions);\n\n if ((configPlugin.build ? 1 : 0) + (configPlugin.transform ? 1 : 0) + (configPlugin.bundle ? 1 : 0) > 1) {\n handleConfigError(`plugin[${configPluginLoc}]: A valid plugin can only have one build(), transform(), or bundle() function.`);\n }\n\n allPlugins[configPluginPath] = configPlugin;\n\n if (configPlugin.knownEntrypoints) {\n config.knownEntrypoints.push(...configPlugin.knownEntrypoints);\n }\n\n if (configPlugin.defaultBuildScript && !config.scripts[configPlugin.defaultBuildScript] && !Object.values(config.scripts).includes(configPluginPath)) {\n config.scripts[configPlugin.defaultBuildScript] = configPluginPath;\n }\n\n return configPlugin;\n });\n\n if (config.devOptions.bundle === true && !config.scripts['bundle:*']) {\n handleConfigError(`--bundle set to true, but no \"bundle:*\" script/plugin was provided.`);\n }\n\n config = handleLegacyProxyScripts(config);\n config.proxy = normalizeProxies(config.proxy);\n config.scripts = normalizeScripts(config.scripts);\n config.scripts.forEach(script => {\n if (script.plugin) return; // Ensure plugins are properly registered/configured\n\n if (['build', 'bundle'].includes(script.type)) {\n var _allPlugins$script$cm;\n\n if ((_allPlugins$script$cm = allPlugins[script.cmd]) === null || _allPlugins$script$cm === void 0 ? void 0 : _allPlugins$script$cm[script.type]) {\n script.plugin = allPlugins[script.cmd];\n } else if (allPlugins[script.cmd] && !allPlugins[script.cmd][script.type]) {\n handleConfigError(`scripts[${script.id}]: Plugin \"${script.cmd}\" has no ${script.type} script.`);\n } else if (script.cmd.startsWith('@') || script.cmd.startsWith('.')) {\n handleConfigError(`scripts[${script.id}]: Register plugin \"${script.cmd}\" in your Snowpack \"plugins\" config.`);\n }\n }\n });\n return config;\n}", "function compilerArgsFromOptions(options) {\n return Object.entries(options)\n .map(function ([opt, value]) {\n if (value) {\n switch (opt) {\n case \"help\":\n return [\"--help\"];\n case \"output\":\n return [\"--output\", value];\n case \"report\":\n return [\"--report\", value];\n case \"debug\":\n return [\"--debug\"];\n case \"docs\":\n return [\"--docs\", value];\n case \"optimize\":\n return [\"--optimize\"];\n case \"runtimeOptions\":\n return [].concat([\"+RTS\"], value, [\"-RTS\"]);\n default:\n if (supportedOptions.indexOf(opt) === -1) {\n if (opt === \"yes\") {\n throw new Error(\n \"node-elm-compiler received the `yes` option, but that was removed in Elm 0.19. Try re-running without passing the `yes` option.\"\n );\n } else if (opt === \"warn\") {\n throw new Error(\n \"node-elm-compiler received the `warn` option, but that was removed in Elm 0.19. Try re-running without passing the `warn` option.\"\n );\n } else if (opt === \"pathToMake\") {\n throw new Error(\n \"node-elm-compiler received the `pathToMake` option, but that was renamed to `pathToElm` in Elm 0.19. Try re-running after renaming the parameter to `pathToElm`.\"\n );\n } else {\n throw new Error(\n \"node-elm-compiler was given an unrecognized Elm compiler option: \" +\n opt\n );\n }\n }\n\n return [];\n }\n } else {\n return [];\n }\n })\n .flat();\n}" ]
[ "0.5962663", "0.59392846", "0.57876426", "0.5553486", "0.5461311", "0.5306602", "0.5277167", "0.5193653", "0.5187042", "0.51710844", "0.5149455", "0.5145855", "0.513054", "0.51038057", "0.5080869", "0.5077297", "0.5077297", "0.5062954", "0.50248617", "0.5017232", "0.500823", "0.49990588", "0.4990375", "0.49874213", "0.49569157", "0.4935851", "0.49202374", "0.48878387", "0.48874128", "0.4870722", "0.48498085", "0.4849569", "0.48485702", "0.48411977", "0.4835401", "0.48312235", "0.4819249", "0.47999677", "0.4784168", "0.47727808", "0.47714055", "0.4766527", "0.47535324", "0.47487348", "0.47461033", "0.47378707", "0.4723426", "0.47216144", "0.47183716", "0.4716299", "0.4716072", "0.47102147", "0.47101524", "0.47101524", "0.47101524", "0.47051924", "0.47035816", "0.46964413", "0.4689846", "0.46879342", "0.46503514", "0.46477032", "0.464169", "0.46353436", "0.46353436", "0.4633021", "0.46267697", "0.46229994", "0.4610934", "0.46092626", "0.46015486", "0.46004343", "0.46004343", "0.46004343", "0.46004343", "0.46004343", "0.46004343", "0.46004343", "0.46004343", "0.46004343", "0.46004343", "0.45998526", "0.45961624", "0.45932522", "0.45886937", "0.45869234", "0.4586867", "0.45797762", "0.45613453", "0.4560702", "0.45588958", "0.455567", "0.45536432", "0.4547638", "0.4545229", "0.45427904", "0.45320514", "0.45320514", "0.4525092", "0.45219213" ]
0.638709
0
Setup a browserify/watchify rebundler given an initial stream and further stream transforms. This method does roughly the equivalent of bundler.pipe(...).pipe(...).pipe..., as well as adding a bundler.on('update', ...) listener which reruns the bundler piping process whenever bundle updates are detected. The major reason to use this method instead of hand rolling the pipe() calls is the detailed error handling this method adds to each pipe() step.
function setupRebundleListener(rebuildOnSrcChange, verbose, bundler, getSourceStreams, additionalStreamPipes, listeners) { listeners = listeners || {}; function rebundle(updateEvent) { var expectedTotal = 0; var expectDoneFiles = []; var doneFiles = []; var skippedFiles = []; var startTime = Date.now(); var startTimes = {}; var endTimes = {}; function startCb(file) { startTimes[file] = Date.now(); expectDoneFiles.push(file); if (verbose) { log("start building '" + file + "'..."); } if (listeners.startBundle) { tryCall(listeners.startBundle, file); } } function doneCb(srcName, file, type) { endTimes[file] = Date.now(); if (type === "compile") { doneFiles.push(file); if (listeners.finishBundle) { tryCall(listeners.finishBundle, file); } } else if (type === "skip") { skippedFiles.push(file); if (listeners.skipBundle) { tryCall(listeners.skipBundle, file); } } else { var errMsg = "invalid bundle completion type (expected: 'compile' or 'skip'): " + type; console.error(errMsg); if (listeners.error) { tryCall(listeners.error, srcName, file, errMsg); } return; } var totalDone = doneFiles.length + skippedFiles.length; if (totalDone >= expectedTotal) { var endTime = Date.now(); var bldMsg = doneFiles.length > 0 ? doneFiles.map(function (f) { return f + " (" + (endTimes[file] - startTimes[file]) + " ms)"; }).join(", ") : null; var skpMsg = skippedFiles.length > 0 ? "skipped: " + skippedFiles.join(", ") : null; var buildMsg = "done building (" + (endTime - startTime) + " ms): " + (bldMsg ? bldMsg + (skpMsg ? " | " + skpMsg : "") : (skpMsg ? skpMsg : "no bundles")); if (verbose) { log(buildMsg); } if (listeners.finishAll) { tryCall(listeners.finishAll, { buildMsg: buildMsg, totalTimeMillis: endTime - startTime, builtBundles: doneFiles.map(function (f) { return ({ fileName: f, timeMillis: (endTimes[f] - startTimes[f]) }); }), skippedBundles: skippedFiles.map(function (f) { return ({ fileName: f, timeMillis: (endTimes[f] - startTimes[f]) }); }), }); } } } function createErrorCb(srcName, dstFile) { return function (err) { console.error("error building '" + dstFile + "' at stream '" + srcName + "'", err); if (listeners.error) { tryCall(listeners.error, srcName, dstFile, err); } }; } function startStreams(bundleStreams) { expectedTotal = bundleStreams.length; bundleStreams.forEach(function (bundle) { var dstFilePath = bundle.dstFileName; var resStream = bundle.stream; if (resStream == null) { doneCb("initial-stream", dstFilePath, "skip"); return; } resStream.on("error", createErrorCb("initial-stream", dstFilePath)); for (var i = 0, size = additionalStreamPipes.length; i < size; i++) { var streamName = additionalStreamPipes[i][0]; var streamCreator = additionalStreamPipes[i][1]; resStream = streamCreator(resStream, bundle); resStream.on("error", createErrorCb(streamName, dstFilePath)); } resStream.on("end", function () { return doneCb(streamName, dstFilePath, "compile"); }); startCb(dstFilePath); }); } var bundles = getSourceStreams(bundler, updateEvent); bundler.pipeline.on("error", createErrorCb("initial-stream", "bundle")); if (isPromise(bundles.bundleStreams)) { bundles.bundleStreams.then(function (streams) { return startStreams(streams); }, createErrorCb("creating initial-stream", "multi-stream-base")); } else { startStreams(bundles.bundleStreams); } } if (rebuildOnSrcChange) { bundler.on("update", rebundle); } rebundle(); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function bundlePipe (onFinish) {\n var stream = b.bundle()\n .pipe(zlib.createGzip({level: zlib.Z_BEST_COMPRESSION}))\n .pipe(fs.createWriteStream(bundles_target + '/' + module + '.js'));\n if (typeof onFinish === 'function') {\n stream.on('finish', onFinish);\n }\n }", "function bundle() {\n stream.push(watcher.bundle())\n if (fs.once) {\n stream.push(null)\n }\n }", "_bundleFiles(file, callback) {\n// Instantiate the jsonTransform....\n const JSONTransform = new jsonTransform()\n\n// Set up options with a transforms array....\n let transforms = [],\n opts = {\n transform: transforms\n }\n\n if (this.options.babel) {\n opts.transform.push(this._processBabel)\n }\n\n// invoke module-deps by passing in the entry point file\n let mDeps = moduleDependencies(opts),\n parser = JSONStream.parse(['file'])\n\n mDeps\n .pipe(JSONStream.stringify())\n .pipe(this._esWait())\n .on('data', (data)=> {\n// Store json data into memory....\n this.moduleDepsJSON = JSON.parse(data)\n })\n .pipe(JSONTransform)\n .pipe(browserPack( {\n prelude: this.prelude,\n preludePath: this.preludePath\n } ))\n .pipe(this._esWait())\n .on('data', (data)=> {\n let bundle\n // log('DATA', 'yellow'); log(data)\n// Tack on/ remove any additional needed code....\n if (this.options.strict) {\n if (this.options.reloading) {\n bundle = this._addHMRClientCode(data)\n } else {\n bundle = String(data)\n }\n } else {\n if (this.options.reloading) {\n bundle = this._loosyGoosy(\n this._addHMRClientCode(data)\n )\n } else {\n bundle = this._loosyGoosy(String(data))\n }\n }\n // log('BUNDLE', 'yellow');log(bundle)\n// Write the data to bundle string file....\n fs.writeFile(this.outputFile, bundle, (err)=> {\n if (err) {\n log(err, ['red', 'bold'])\n return\n }\n\n// Call the callBack....\n if (typeof callback === 'function') {\n// Call the callback....\n callback()\n// Bundle success message.....\n log(\n `🎶 ${chalk.hex('#161616').bgWhite.bold(` Mixolydian `)}${chalk.hex('#4073ff').bold(' bundle written in: ')}${chalk.hex('#fccd1b').bold(`${this.ms}ms.`)} 🎶\\n`\n )\n\n// If This is the first bundle from the initial command....\n if (this.firstBundle) {\n/// If the watch option is set....\n if (this.options.watch && this.options.mode !== 'production') {\n/// log out dev server started message....\n log(`${chalk.white.bold(`Development Server started on port ${app.get('port')}. Press Ctrl-C to terminate.`)}\n ${this.options.jc? chalk.hex('#fccd1b').bold('\\n⛪️ Jesus is King!! ⛪️') : ''}\n `)\n process.stdout.write(`\\n`)\n }\n }\n\n// Check for jc option, if present, praise Jesus Christ!\n if (this.options.jc && !this.firstBundle) {\n log(`${chalk.hex('#fccd1b').bold(`🙏 Praise the Lord! 🙏\\n`)}`)\n }\n if (this.firstBundle) {\n this.firstBundle = false\n }\n }\n })\n })\n// End the stream....\n mDeps.end({\n file: path.join(process.env.PWD, file)\n })\n }", "function processBundle(b) {\n var bundle = _.clone(b);\n var totalLatches = 0;\n var latchCount = 0;\n if (bundle.lessIn && bundle.lessIn.length > 0) {\n totalLatches++;\n }\n\n if (bundle.sassIn && bundle.sassIn.length > 0) {\n totalLatches++;\n }\n\n if (bundle.cssIn && bundle.cssIn.length > 0) {\n totalLatches++;\n }\n\n var bundleState = {\n bundleFiles : [],\n acceptFile : function() {\n var self = this;\n return through.obj(function (file, enc, cb) {\n self.bundleFiles.push(file);\n cb(null, file);\n });\n },\n pipelineComplete : function () {\n latchCount++;\n if (latchCount >= totalLatches) {\n this.nextPipeline();\n }\n },\n nextPipeline: function(){\n var self = this;\n // need a virtual source\n var src = require('stream').Readable({objectMode: true});\n src.findex = 0;\n src._read = function (cb) {\n for (; this.findex < self.bundleFiles.length; this.findex++) {\n this.push(self.bundleFiles[this.findex]);\n }\n if(this.findex >= self.bundleFiles.length){\n // undocumented on https://nodejs.org/api/stream.html#stream_event_data\n // but \"null\" is the control signal that there is no more data in the stream...\n this.push(null);\n }\n };\n\n var postcss = require('gulp-postcss');\n var sourcemaps = require('gulp-sourcemaps');\n var autoprefixer = require('autoprefixer-core');\n\n src.pipe(concatCss(bundle.out + buildCssExt))\n .pipe(sourcemaps.init())\n .pipe(postcss([ autoprefixer({ browsers: ['last 2 version'] }) ]))\n .pipe(sourcemaps.write('.'))\n .pipe(rename(function (path) {\n path.basename = bundle.out;\n path.extname = buildCssExt;\n }))\n .pipe(gulp.dest(cssDest))\n .on('end', function () {\n bundleComplete();\n });\n }\n };\n\n if (bundle.lessIn && bundle.lessIn.length > 0) {\n gulp.src(bundle.lessIn)\n .pipe(less({\n paths: [path.join(__dirname, 'less', 'includes')]\n }))\n .pipe(bundleState.acceptFile())\n .on('finish', function () {\n bundleState.pipelineComplete();\n })\n }\n\n if (bundle.sassIn && bundle.sassIn.length > 0) {\n gulp.src(bundle.sassIn)\n .pipe(sass())\n .pipe(bundleState.acceptFile())\n .on('finish', function () {\n bundleState.pipelineComplete();\n })\n }\n\n if (bundle.cssIn && bundle.cssIn.length > 0) {\n gulp.src(bundle.cssIn)\n .pipe(bundleState.acceptFile())\n .on('finish', function () {\n bundleState.pipelineComplete();\n })\n }\n }", "function pipeStream() {\n var args = _.toArray(arguments);\n var src = args.shift();\n\n return new Promise(function(resolve, reject) {\n var stream = src;\n var target;\n\n while ((target = args.shift()) != null) {\n stream = stream.pipe(target).on('error', reject);\n }\n\n stream.on('finish', resolve);\n stream.on('end', resolve);\n stream.on('close', resolve);\n });\n}", "function bundle() {\n return b.bundle()\n .on('error', log.error.bind(log, 'Browserify Error'))\n .pipe(source('bundle.js'))\n //.pipe(streamify(terser()))\n .pipe(gulp.dest('./client/static/js'));\n}", "function bundleShare(b, fileStream) {\n b.bundle()\n .on('data'\n , function(err){\n if (err.message){\n console.warn(err.toString());\n }\n })\n .on('error'\n , function(err){\n console.error(err.toString());\n })\n .pipe(fileStream());\n}", "function bundle() {\n return bundler.bundle()\n // log errors if they happen\n .on('error', gutil.log.bind(gutil, 'Browserify Error'))\n .pipe(source('bundle.js'))\n // .pipe(streamify(uglify()))\n .pipe(gulp.dest(paths.client.lib));\n}", "function pipe(stream) {\n var cache, scope = this;\n if(stream) {\n // add to the pipeline\n this.fuse(stream);\n // ensure return values are also added to the pipeline\n cache = stream.pipe;\n stream.pipe = function(/* dest */) {\n // restore cached method when called\n this.pipe = cache;\n // proxy to the outer pipe function (recurses)\n return scope.pipe.apply(scope, arguments);\n }\n stream.pipe.cache = cache;\n }\n return stream;\n}", "function bundle() {\n return b.bundle()\n .on('error', gutil.log.bind(gutil, 'Browserify Error'))\n .pipe(source('bundle.js'))\n .pipe(buffer())\n .pipe(sourcemaps.init({loadMaps: true}))\n .pipe(gutil.env.type === 'production' ? uglify() : gutil.noop())\n .pipe(gutil.env.type !== 'production' ? sourcemaps.write('.', {sourceRoot: '/assets/js'}): gutil.noop())\n .pipe(gutil.env.type === 'production' ? gutil.noop() : gulp.dest('./assets/js'))\n .pipe(gutil.env.type === 'production' ? rename({suffix: '.min'}) : gutil.noop())\n .pipe(gutil.env.type === 'production' ? gulp.dest('./assets/js') : gutil.noop())\n .pipe(gutil.env.type === 'production' ? stripDebug() : gutil.noop())\n .pipe(livereload({start: true}));\n}", "function stream_pipeline(...streams) {\n if (streams.length === 0) throw new Error('empty pipeline');\n return new Promise((resolve, reject) => {\n streams.reduce((inlet, outlet) => {\n inlet.on('error', reject);\n return inlet.pipe(outlet);\n }).on('error', reject).on('finish', resolve);\n });\n}", "function bundle() {\n return b\n .transform(babelify)\n .transform(reactify)\n .bundle()\n // log errors if they happen\n .on('error', gutil.log.bind(gutil, 'Browserify Error'))\n .pipe(source('bundle.js'))\n // optional, remove if you don't need to buffer file contents\n .pipe(buffer())\n // optional, remove if you dont want sourcemaps\n .pipe(sourcemaps.init({loadMaps: true})) // loads map from browserify file\n // Add transformation tasks to the pipeline here.\n .pipe(sourcemaps.write('./')) // writes .map file\n .pipe(gulp.dest('./app/dist'));\n}", "function bundle() {\n\tvar stream = bundler.bundle().pipe(source('app.js'));\n\n\tif(process.env.NODE_ENV === 'production') {\n\t\tstream = stream.pipe(buffer()).pipe(uglify());\n\t}\n\telse {\n\t\tstream = stream.pipe(buffer())\n\t\t\t.pipe(sourcemaps.init({ loadMaps: true }))\n\t\t\t.pipe(sourcemaps.write());\n\t}\n\n\tstream = stream.pipe(gulp.dest('dist'));\n\n\tif(args['use-browser-sync']) {\n\t\tstream = stream.pipe(sync.reload({ stream: true, once: true }));\n\t}\n\treturn stream;\n}", "async function bundle() {\n const since = lastRun(bundle);\n const polyfillPath = path.join(config.buildBase, 'js', 'polyfill.js');\n const factorBundlePath = path.join(\n config.buildBase,\n 'js',\n 'factor-bundle.js'\n );\n\n await makeDir(path.join(config.buildBase, 'js'));\n\n async function getFactorBundle() {\n const paths = await globby('**/*.js', { cwd: 'assets/js' });\n const factorBundle = await new Promise((resolve, reject) => {\n browserify({\n entries: paths.map((string) => `assets/js/${string}`),\n debug: true\n })\n .plugin('bundle-collapser/plugin')\n .plugin('factor-bundle', {\n outputs: paths.map((string) =>\n path.join(config.buildBase, 'js', string)\n )\n })\n .bundle((err, data) => {\n if (err) return reject(err);\n resolve(data);\n });\n });\n await fs.promises.writeFile(factorBundlePath, factorBundle);\n }\n\n await Promise.all([\n fs.promises.copyFile(\n path.join(\n __dirname,\n 'node_modules',\n '@babel',\n 'polyfill',\n 'dist',\n 'polyfill.js'\n ),\n polyfillPath\n ),\n getFactorBundle()\n ]);\n\n // concatenate files\n await getStream(\n src([\n 'build/js/polyfill.js',\n 'build/js/factor-bundle.js',\n 'build/js/uncaught.js',\n 'build/js/core.js'\n ])\n .pipe(sourcemaps.init({ loadMaps: true }))\n .pipe(concat('build.js'))\n .pipe(sourcemaps.write('./'))\n .pipe(dest(path.join(config.buildBase, 'js')))\n .pipe(through2.obj((chunk, enc, cb) => cb()))\n );\n\n let stream = src('build/js/**/*.js', { base: 'build', since })\n .pipe(sourcemaps.init({ loadMaps: true }))\n .pipe(unassert())\n .pipe(envify())\n .pipe(babel());\n\n if (PROD) stream = stream.pipe(terser());\n\n stream = stream.pipe(sourcemaps.write('./')).pipe(dest(config.buildBase));\n\n if (DEV) stream = stream.pipe(lr(config.livereload));\n\n stream = stream.pipe(dest(config.buildBase));\n\n // convert to conventional stream\n stream = stream.pipe(through2.obj((chunk, enc, cb) => cb()));\n\n await getStream(stream);\n}", "function start_pipeline(){\n var commands = [\n ['xsltproc', [meta_xslt, '-'] ],\n ['xsltproc', ['-', tmpfile] ]\n ];\n logger.log(tmpfile);\n var transform = create_pipeline( commands, response );\n transform.on( 'finish', clean_tmp_file);\n\n request.pipe( transform );\n }", "function makeBrowserifyStream (bundleName) {\n let bundleConfig = config.bundles[bundleName]\n let outputName = `${bundleName}.js`\n let bundleSrc = bundleConfig.src\n let browserifyOptions = vendor.xtend(\n {},\n defaultBundleOptions,\n bundleConfig.browserify,\n global.isWatching ? watchify.args : {}\n )\n\n let browserifyInstance = createBrowserifyInstance(bundleName, browserifyOptions)\n modifyBrowserifyObject(browserifyInstance)\n\n if (browserifyOptions.modifyBrowserifyObject) {\n browserifyOptions.modifyBrowserifyObject(browserifyInstance)\n }\n\n if (global.isWatching) {\n browserifyInstance = watchify(browserifyInstance)\n browserifyInstance.on('update', createBundleFactory(bundleName, browserifyInstance))\n }\n\n return createBundleFactory(bundleName, browserifyInstance)()\n}", "function bundle() {\n\treturn bundler.bundle()\n\t\t.on('error', util.log.bind(util, 'Browserify Error'))\n\t\t.pipe(source('bundle.js'))\n\t\t.pipe(buffer())\n\t\t.pipe(sourcemaps.init({\n\t\t\tloadMaps: true\n\t\t}))\n\t\t.pipe(uglify())\n\t\t.pipe(sourcemaps.write('./'))\n\t\t.pipe(gulp.dest(destScripts))\n\t\t.pipe(browserSync.reload({\n\t\t\tstream: true,\n\t\t\tonce: true\n\t\t}));\n}", "function compile(watch) {\n var bundler = browserify(paths.scripts.bundleEntry, { debug: true })\n .transform(babelify)\n .transform(riotify, riotifyOptions)\n\t\t;\n\t\n var watcher = watch ? watchify(bundler) : '';\n\n if (watch) {\n watcher.on('update', function () {\n gutil.log('Bundling...');\n rebundle()\n .pipe(browsersync.stream({ once: true }));\n });\n }\n\n return rebundle();\n\n function rebundle() {\n return bundler.bundle()\n .on('error', function(err) { \n\t\t\t\tgutil.log('Bundle error: ', err); \n browsersync.notify('Browserify error!');\n this.emit('end'); \n })\n .pipe(source(paths.scripts.bundleFilename))\n .pipe(buffer())\n .pipe(sourcemaps.init({ loadMaps: true }))\n .pipe(sourcemaps.write('./'))\n .pipe(gulp.dest(paths.scripts.bundleDest));\n }\n}", "function bundle() {\n return w.bundle()\n // log errors if they happen\n .on('error', gutil.log.bind(gutil, 'Browserify Error'))\n .pipe(source('./bundle.js'))\n .pipe(buffer())\n // .pipe(uglify())\n .pipe(gulp.dest('./src/js/'))\n .pipe(connect.reload());\n}", "function Stream(/*optional*/xs, /*optional*/secondArg, /*optional*/mappingHint) {\n /*eslint-enable no-multi-spaces */\n if (xs && _.isStream(xs)) {\n // already a Stream\n return xs;\n }\n\n EventEmitter.call(this);\n var self = this;\n\n // used to detect Highland Streams using isStream(x), this\n // will work even in cases where npm has installed multiple\n // versions, unlike an instanceof check\n self.__HighlandStream__ = true;\n\n self.id = ('' + Math.random()).substr(2, 6);\n this.paused = true;\n this._incoming = [];\n this._outgoing = [];\n this._consumers = [];\n this._observers = [];\n this._destructors = [];\n this._send_events = false;\n this._nil_pushed = false;\n this._delegate = null;\n this._is_observer = false;\n this._in_consume_cb = false;\n this._repeat_resume = false;\n\n // Used by consume() to signal that next() hasn't been called, so resume()\n // shouldn't ask for more data. Backpressure handling is getting fairly\n // complicated, and this is very much a hack to get consume() backpressure\n // to work correctly.\n this._consume_waiting_for_next = false;\n this.source = null;\n\n // Old-style node Stream.pipe() checks for this\n this.writable = true;\n\n self.on('newListener', function (ev) {\n if (ev === 'data') {\n self._send_events = true;\n _.setImmediate(bindContext(self.resume, self));\n }\n else if (ev === 'end') {\n // this property avoids us checking the length of the\n // listners subscribed to each event on each _send() call\n self._send_events = true;\n }\n });\n\n // TODO: write test to cover this removeListener code\n self.on('removeListener', function (ev) {\n if (ev === 'end' || ev === 'data') {\n var end_listeners = self.listeners('end').length;\n var data_listeners = self.listeners('data').length;\n if (end_listeners + data_listeners === 0) {\n // stop emitting events\n self._send_events = false;\n }\n }\n });\n\n if (_.isUndefined(xs)) {\n // nothing else to do\n return this;\n }\n else if (_.isArray(xs)) {\n self._incoming = xs.concat([nil]);\n return this;\n }\n else if (_.isFunction(xs)) {\n this._generator = xs;\n this._generator_push = generatorPush(this);\n this._generator_next = function (s) {\n if (self._nil_pushed) {\n throw new Error('Cannot call next after nil');\n }\n\n if (s) {\n // we MUST pause to get the redirect object into the _incoming\n // buffer otherwise it would be passed directly to _send(),\n // which does not handle StreamRedirect objects!\n var _paused = self.paused;\n if (!_paused) {\n self.pause();\n }\n self.write(new StreamRedirect(s));\n if (!_paused) {\n self._resume(false);\n }\n }\n else {\n self._generator_running = false;\n }\n if (!self.paused) {\n self._resume(false);\n }\n };\n\n return this;\n }\n else if (_.isObject(xs)) {\n // check to see if we have a readable stream\n if (_.isFunction(xs.on) && _.isFunction(xs.pipe)) {\n var onFinish = _.isFunction(secondArg) ? secondArg : defaultReadableOnFinish;\n pipeReadable(xs, onFinish, self);\n return this;\n }\n else if (_.isFunction(xs.then)) {\n //probably a promise\n return promiseStream(xs);\n }\n // must check iterators and iterables in this order\n // because generators are both iterators and iterables:\n // their Symbol.iterator method returns the `this` object\n // and an infinite loop would result otherwise\n else if (_.isFunction(xs.next)) {\n //probably an iterator\n return iteratorStream(xs);\n }\n else if (!_.isUndefined(_global.Symbol) && xs[_global.Symbol.iterator]) {\n //probably an iterable\n return iteratorStream(xs[_global.Symbol.iterator]());\n }\n else {\n throw new Error(\n 'Object was not a stream, promise, iterator or iterable: ' + (typeof xs)\n );\n }\n }\n else if (_.isString(xs)) {\n var mapper = hintMapper(mappingHint);\n\n var callback_func = function () {\n var ctx = mapper.apply(this, arguments);\n self.write(ctx);\n };\n\n secondArg.on(xs, callback_func);\n var removeMethod = secondArg.removeListener // EventEmitter\n || secondArg.unbind; // jQuery\n\n if (removeMethod) {\n this._destructors.push(function() {\n removeMethod.call(secondArg, xs, callback_func);\n });\n }\n\n return this;\n }\n else {\n throw new Error(\n 'Unexpected argument type to Stream(): ' + (typeof xs)\n );\n }\n}", "function bundle() {\n return bundler.bundle()\n //log les erreurs quand elles surviennent\n .on('error', gutil.log.bind(gutil, 'Browserify Error'))\n .pipe(source('bundle.js'))\n //optionnel, permet de bufferiser le contenu des fichiers pour améliorer les perf du build\n .pipe(buffer())\n //optionnel, permet d'ajouter les sourcemaps pour le debug\n .pipe(sourcemaps.init({loadMaps: true}))\n //Ecrit les fichiers .map\n .pipe(sourcemaps.write('./'))\n //Copie le tout dans le répertoire final\n .pipe(gulp.dest(paths.app + '/scripts'))\n //Stream le résultat à BrowserSync pour qu'il recharge auto la page\n .pipe(browserSync.stream());\n}", "function Stream(/*optional*/xs, /*optional*/secondArg, /*optional*/mappingHint) {\n /*eslint-enable no-multi-spaces */\n if (xs && _.isStream(xs)) {\n // already a Stream\n return xs;\n }\n\n EventEmitter.call(this);\n var self = this;\n\n // used to detect Highland Streams using isStream(x), this\n // will work even in cases where npm has installed multiple\n // versions, unlike an instanceof check\n self.__HighlandStream__ = true;\n\n self.id = ('' + Math.random()).substr(2, 6);\n this.paused = true;\n this._incoming = [];\n this._outgoing = [];\n this._consumers = [];\n this._observers = [];\n this._destructors = [];\n this._send_events = false;\n this._nil_pushed = false;\n this._delegate = null;\n this._is_observer = false;\n this._in_consume_cb = false;\n this._repeat_resume = false;\n this.source = null;\n\n // Old-style node Stream.pipe() checks for this\n this.writable = true;\n\n self.on('newListener', function (ev) {\n if (ev === 'data') {\n self._send_events = true;\n _.setImmediate(self.resume.bind(self));\n }\n else if (ev === 'end') {\n // this property avoids us checking the length of the\n // listners subscribed to each event on each _send() call\n self._send_events = true;\n }\n });\n\n // TODO: write test to cover this removeListener code\n self.on('removeListener', function (ev) {\n if (ev === 'end' || ev === 'data') {\n var end_listeners = self.listeners('end').length;\n var data_listeners = self.listeners('data').length;\n if (end_listeners + data_listeners === 0) {\n // stop emitting events\n self._send_events = false;\n }\n }\n });\n\n if (_.isUndefined(xs)) {\n // nothing else to do\n return this;\n }\n else if (_.isArray(xs)) {\n self._incoming = xs.concat([nil]);\n return this;\n }\n else if (_.isFunction(xs)) {\n this._generator = xs;\n this._generator_push = generatorPush(this);\n this._generator_next = function (s) {\n if (self._nil_pushed) {\n throw new Error('Cannot call next after nil');\n }\n\n if (s) {\n // we MUST pause to get the redirect object into the _incoming\n // buffer otherwise it would be passed directly to _send(),\n // which does not handle StreamRedirect objects!\n var _paused = self.paused;\n if (!_paused) {\n self.pause();\n }\n self.write(new StreamRedirect(s));\n if (!_paused) {\n self.resume();\n }\n }\n else {\n self._generator_running = false;\n }\n if (!self.paused) {\n self.resume();\n }\n };\n\n return this;\n }\n else if (_.isObject(xs)) {\n // check to see if we have a readable stream\n if (_.isFunction(xs.on) && _.isFunction(xs.pipe)) {\n var onFinish = _.isFunction(secondArg) ? secondArg : defaultReadableOnFinish;\n pipeReadable(xs, onFinish, self);\n return this;\n }\n else if (_.isFunction(xs.then)) {\n //probably a promise\n return promiseStream(xs);\n }\n // must check iterators and iterables in this order\n // because generators are both iterators and iterables:\n // their Symbol.iterator method returns the `this` object\n // and an infinite loop would result otherwise\n else if (_.isFunction(xs.next)) {\n //probably an iterator\n return iteratorStream(xs);\n }\n else if (!_.isUndefined(_global.Symbol) && xs[_global.Symbol.iterator]) {\n //probably an iterable\n return iteratorStream(xs[_global.Symbol.iterator]());\n }\n else {\n throw new Error(\n 'Object was not a stream, promise, iterator or iterable: ' + (typeof xs)\n );\n }\n }\n else if (_.isString(xs)) {\n var mapper = hintMapper(mappingHint);\n\n secondArg.on(xs, function () {\n var ctx = mapper.apply(this, arguments);\n self.write(ctx);\n });\n\n return this;\n }\n else {\n throw new Error(\n 'Unexpected argument type to Stream(): ' + (typeof xs)\n );\n }\n}", "function bundle() {\n return b.bundle()\n // log errors if they happen\n .on('error', gutil.log.bind(gutil, 'Browserify Error'))\n .pipe(source('bundle.js'))\n // optional, remove if you don't need to buffer file contents\n .pipe(buffer())\n // optional, remove if you dont want sourcemaps\n .pipe(sourcemaps.init({loadMaps: true})) // loads map from browserify file\n // Add transformation tasks to the pipeline here.\n .pipe(uglify()) // minify\n .pipe(sourcemaps.write('./')) // writes .map file\n .pipe(gulp.dest('./js'));\n}", "function bundle() {\n return b.bundle()\n // log errors if they happen\n .on('error', gutil.log.bind(gutil, 'Browserify Error'))\n .pipe(source('app-bundle.js'))\n // optional, remove if you don't need to buffer file contents\n //.pipe(buffer())\n // optional, remove if you dont want sourcemaps\n //.pipe(sourcemaps.init({loadMaps: true})) // loads map from browserify file\n // Add transformation tasks to the pipeline here.\n //.pipe(sourcemaps.write('./')) // writes .map file\n .pipe(gulp.dest('public/js/app/'));\n}", "function bundle() {\n return b.bundle()\n .on('error', gutil.log.bind(gutil, 'Browserify Error'))\n .pipe(source('bundle.js'))\n .pipe(gulp.dest('./'));\n}", "function preMinifiedDependenciesStream() {\n return gulp.src([paths.lib + '/**/*.min.js'])\n .pipe(concat('pre-minified-deps.min.js'));\n}", "function bundle() {\n return b.bundle()\n .on('error', gutil.log.bind(gutil, 'Browserify Error'))\n .pipe(source('bundle.js'))\n .pipe(buffer())\n .pipe(uglify())\n .pipe(gulp.dest(path.join(paths.build, 'js')));\n}", "function createBundlerStreams(globPattern, destDir, transforms){\n var moduleStripRegex = /.*\\//;\n var extStripRegex = /\\.js/;\n\n return glob.sync(globPattern).map(function (thisFile){\n gutil.log(\"Bundling \", thisFile);\n var fileName = thisFile.replace(moduleStripRegex,'');\n var bundleName = fileName.replace(extStripRegex,'');\n var bundler = browserify({\n plugin : \"browserify-derequire\",\n entries: [\"./\" + thisFile],\n standalone: bundleName\n });\n if (transforms){\n bundler.transform({\n global: true\n }, transforms);\n }\n return bundler\n .bundle()\n .pipe(source(fileName))\n .pipe(gulp.dest(destDir));\n });\n}", "function bundleJs(srcStream, outputFile){\n\n if(concatFiles){\n return srcStream.pipe(sourcemaps.init())\n //.pipe(print())\n .pipe(concat(outputFile))\n .pipe(uglify())\n .pipe(sourcemaps.write())\n .pipe(gulp.dest(paths.dist));\n }\n\n return srcStream\n .pipe(bundle(outputFile, {base: paths.src.client}))\n .pipe(changed(paths.dist))\n .pipe(gulp.dest(paths.dist));\n}", "function preMinifiedDependenciesStream() {\n return gulp.src(['app/lib/**/*.min.js'])\n .pipe(concat('pre-minified-deps.min.js'));\n}", "function BinaryPipe(buffer, initialObject = {}) {\n const generator = bufferGenerator_1.bufferGenerator(buffer);\n return {\n /**\n * Pipes buffer through given parsers.\n * It's up to parser how many bytes it takes from buffer.\n * Each parser should return new literal object, that will be merged to previous object (or initialObject) by pipe.\n *\n * @param parsers - parsers for pipeline\n */\n pipe(...parsers) {\n // Call each parser and merge returned value into one object\n return parsers.reduce((previousValue, parser) => {\n const result = parser[1](generator);\n return Object.assign({}, previousValue, { [parser[0]]: result });\n }, initialObject);\n },\n /**\n * Returns special pipe function, which iterates `count` times over buffer,\n * returning array of results.\n *\n * @param count - number of times to iterate.\n */\n loop(count) {\n // save basePipe reference to avoid returned pipe calling itself\n const basePipe = this.pipe;\n return {\n pipe(...parsers) {\n const entries = [];\n // Call basePipe `count` times\n for (let i = 0; i < count; i += 1) {\n entries.push(basePipe(...parsers));\n }\n return entries;\n },\n };\n },\n /**\n * Returns buffer not parsed by pipe yet.\n * Closes generator, so no piping will be available after calling `finish`.\n */\n finish() {\n const buf = [];\n // Take all bytes and close generator\n let lastResult;\n do {\n lastResult = generator.next();\n buf.push(lastResult.value);\n } while (!lastResult.done);\n return Buffer.from(buf);\n },\n };\n}", "function bundle() {\n\n return b.bundle()\n // log errors if they happen\n .on('error', gutil.log.bind(gutil, 'Browserify Error'))\n .pipe(source('npmBundle.js')) //output file name here\n // optional, remove if you don't need to buffer file contents\n .pipe(buffer())\n // optional, remove if you dont want sourcemaps\n .pipe(sourcemaps.init({loadMaps: true})) // loads map from browserify file\n // Add transformation tasks to the pipeline here.\n .pipe(sourcemaps.write('./')) // writes .map file\n .pipe(gulp.dest('./app/scripts'));\n}", "function bundle()\n{\n return bundler.bundle()\n // log errors if they happen\n .on( 'error', gutil.log.bind( gutil, 'Browserify Error' ) )\n .pipe( source( 'webplayer.js' ) )\n //\n .pipe( gulp.dest( './dist/js/' ) );\n}", "function bundle_task () {\n\n return bundler.bundle()\n .on('error', gutil.log.bind(gutil, 'Browserify Error'))\n .pipe(source('dev.js'))\n .pipe(buffer())\n .pipe(sourcemaps.init({loadMaps: true}))\n .pipe(sourcemaps.write('./'))\n .pipe(gulp.dest('./dist'));\n}", "function bundle(callback) {\n \n bundleLogger.start(bfvars.entries);\n return bf.bundle()\n\n .pipe(source(bfvars.outputName))\n // optional, remove if you don't need to buffer file contents\n .pipe(buffer())\n // use sourcemaps to find correct module locations\n .pipe(sourcemaps.init({loadMaps: true})) // load maps file from browserify file\n .pipe(sourcemaps.write('./')) // writes .map file\n // output to dist folder\n .pipe(gulp.dest(bfvars.dest))\n\n .pipe(gulpif(bs.active, bs.reload({ stream: true })));\n}", "function bundle( bundler ) {\n var bundleTimer = duration( 'Javascript bundle time' );\n\n return bundler\n .bundle()\n .on( 'error', function( err ) {\n console.error( err ); this.emit( 'end' );\n })\n .pipe( source( 'batch.jsx' ) ) // Set source name.\n .pipe( buffer() ) // Convert to gulp pipeline.\n .pipe( rename( config.js.outputFile ) ) // Rename the output file.\n .pipe( sourcemaps.init( { loadMaps: true } ) ) // Extract the inline sourcemaps.\n .pipe( uglify() ) // Minify the JS.\n .pipe( sourcemaps.write( './map' ) ) // Set folder for sourcemaps to output to.\n .pipe( gulp.dest( config.js.outputDir ) ) // Set the output folder.\n .pipe( notify( {\n message: 'Generated file: <%= file.relative %>'\n } ) ) // Output the file being created.\n .pipe( bundleTimer ) // Output time timing of the file creation.\n .pipe( livereload() ); // Reload the view in the browser.\n}", "function StreamCombiner(stream) {\n\n // Wrapped stream.\n this.target = stream;\n\n // Input streams to combine.\n this.sources = [];\n\n // Index of currently streaming stream.\n this.index = -1;\n\n // If true then close once there are no streams.\n this.closeOnEnd = false;\n\n this.streaming = false;\n\n // If true stream on this.index ended and was closed.\n this.currentClosed = false;\n\n const _this = this;\n\n // Append given stream to the wrapped stream.\n this.append = function (stream) {\n _this.sources.push(stream);\n if (!_this.streaming) {\n pipeNext();\n }\n };\n\n this.end = function () {\n // Close after the last stream is processed.\n _this.closeOnEnd = true;\n if (!_this.streaming) {\n pipeNext();\n }\n };\n\n // Look for next stream and pipe it.\n function pipeNext() {\n _this.streaming = true;\n closeCurrent();\n if (_this.index + 1 < _this.sources.length) {\n // Send new stream.\n _this.index += 1;\n const stream = _this.sources[_this.index];\n stream.on(\"end\", pipeNext);\n stream.pipe(_this.target, {\"end\": false});\n _this.currentClosed = false;\n } else {\n // Nothing more to stream.\n if (_this.closeOnEnd) {\n _this.target.end();\n } else {\n }\n // Wait for next stream.\n _this.streaming = false;\n }\n }\n\n function closeCurrent() {\n if (_this.index > -1 && !_this.currentClosed) {\n // Close stream under this.index.\n const oldStream = _this.sources[_this.index];\n oldStream.unpipe(_this.target);\n _this.currentClosed = true;\n }\n }\n\n}", "function Stream(generator) {\n EventEmitter.call(this);\n\n // used to detect Highland Streams using isStream(x), this\n // will work even in cases where npm has installed multiple\n // versions, unlike an instanceof check\n this.__HighlandStream__ = true;\n\n this.id = ('' + Math.random()).substr(2, 6);\n\n this.paused = true;\n this.ended = false;\n\n // Old-style node Stream.pipe() checks for writable, and gulp checks for\n // readable. Discussion at https://github.com/caolan/highland/pull/438.\n this.readable = true;\n this.writable = false;\n\n this._outgoing = new Queue();\n this._observers = [];\n this._destructors = [];\n this._send_events = false;\n\n this._nil_pushed = false; // Sets to true when a nil has been queued.\n this._explicitly_destroyed = false; // Sets to true when destroy() is called.\n\n this._request = null;\n this._multiplexer = null;\n this._consumer = null;\n\n this._generator = generator;\n this._generator_requested = true;\n this._defer_run_generator = false;\n this._run_generator_deferred = false;\n\n // Signals whether or not a call to write() returned false, and thus we can\n // drain. This is only relevant for streams constructed with _().\n this._can_drain = false;\n\n var self = this;\n\n // These are defined here instead of on the prototype\n // because bind is super slow.\n this._push_fn = function (err, x) {\n if (x === nil) {\n // It's possible that next was called before the\n // nil, causing the generator to be deferred. This\n // is allowed since push can be called at any time.\n // We have to cancel the deferred call to preserve the\n // generator contract.\n self._run_generator_deferred = false;\n }\n\n // This will set _nil_pushed if necessary.\n self._writeOutgoing(err ? new StreamError(err) : x);\n };\n\n this._next_fn = function (xs) {\n if (self._explicitly_destroyed) {\n return;\n }\n\n // It's possible to get into a situation where a call to next() is\n // scheduled asynchonously, but before it is run, destroy() is called,\n // usually by a downstream consumer like take(1). The call to next()\n // still completes, and there is nothing the original caller can do can\n // do. We do not want to throw in that situation.\n if (self._nil_pushed) {\n throw new Error('Cannot call next after nil');\n }\n\n self._generator_requested = true;\n if (xs) {\n xs = self.create(xs);\n var pull = newPullFunction(xs);\n self._generator = newDelegateGenerator(pull);\n }\n\n if (!self.paused) {\n if (self._defer_run_generator) {\n self._run_generator_deferred = true;\n }\n else {\n _.setImmediate(function () {\n self._runGenerator();\n });\n }\n }\n };\n\n this.on('newListener', function (ev) {\n if (ev === 'data') {\n self._send_events = true;\n _.setImmediate(bindContext(self.resume, self));\n }\n else if (ev === 'end') {\n // this property avoids us checking the length of the\n // listners subscribed to each event on each _send() call\n self._send_events = true;\n }\n });\n\n // TODO: write test to cover this removeListener code\n this.on('removeListener', function (ev) {\n if (ev === 'end' || ev === 'data') {\n var end_listeners = self.listeners('end').length;\n var data_listeners = self.listeners('data').length;\n if (end_listeners + data_listeners === 0) {\n // stop emitting events\n self._send_events = false;\n }\n }\n });\n}", "function writeBundledOutput(stream) {\n return new Promise(resolve => {\n stream.pipe(project.bundler)\n .pipe(gulp.dest(bundledPath))\n .on('end', resolve);\n });\n}", "function bundle() {\n return bundler.bundle()\n // log errors if they happen\n .on('error', gutil.log.bind(gutil, 'Browserify Error'))\n .pipe(source('bundle.js'))\n // optional, remove if you dont want sourcemaps\n .pipe(buffer())\n .pipe(sourcemaps.init({loadMaps: true})) // loads map from browserify file\n .pipe(sourcemaps.write()) \n //\n .pipe(gulp.dest('./js'));\n}", "function bundleJs(bundler){\n\n return bundler.bundle()\n .on('error', function(err){\n gutil.log(err.message);\n browserSync.notify('Browserify error!');\n this.emit('end');\n })\n .pipe(plumber())\n .pipe(source('bundle.js'))\n .pipe(buffer())\n .pipe(sourcemaps.init({loadMaps: true}))\n .pipe(sourcemaps.write('./'))\n .pipe(gulp.dest(config.scripts.dest))\n .pipe(size({showFiles: true}))\n .pipe(browserSync.stream({once: true}));\n}", "function processJs (bundler) {\n return bundler\n // Convert ES6 to ES2015\n .transform('babelify', {presets: ['es2015']})\n // Bundle up all our JS (makes require() work in the browser)\n .bundle()\n // Catch any errors thrown by bundle()\n .on('error', gutil.log)\n // Catch any errors thrown down the line\n .pipe(plumber({handleError: gutil.log}))\n // Convert the stream browserify created into a virtual file/buffer\n .pipe(source('app.min.js'))\n .pipe(buffer())\n // We want to set loadMaps to true because browserify has already\n // generated sourcemaps. gulp-sourcemaps can generate them too, but\n // since we've already bundled all of our JS using browserify, gulp-\n // sourcemaps would map all the JS to a single file.\n .pipe(gulpif(env.dev, sourcemaps.init({loadMaps: true})))\n\n // JS transforms go here\n\n // minify\n .pipe(gulpif(env.prod, uglify()))\n\n // Write sourcemaps\n .pipe(gulpif(env.dev, sourcemaps.write('./')))\n .pipe(gulp.dest(paths.public))\n // Reload browser\n .on('end', function () {\n if (env.dev) {\n browserSync.reload();\n }\n });\n}", "function createBundleFactory (bundleName, browserifyInstance) {\n let bundleConfig = config.bundles[bundleName]\n let outputName = `${bundleName}.js`\n\n return () => {\n return browserifyInstance.bundle()\n .on('error', handleErrors)\n\n // Convert browserify object to streaming vinyl file object\n .pipe(source(outputName))\n // Convert from streaming to buffered vinyl object\n .pipe(buffer())\n\n .pipe(makeSourcesRelative())\n .pipe(vendor.gulp().dest(`tmp/webapp/99-${bundleName}`))\n\n .on('end', () => {\n vendor.gutil.log('browserify', `Bundled ${outputName}`)\n if (global.isWatching && hasBuiltOnce) {\n vendor.gulp().start(`webapp-build-final-scripts--${bundleName}`)\n }\n })\n }\n}", "function bundle () {\n return b.bundle()\n .on('error', gutil.log.bind(gutil, 'Browserify Error'))\n .pipe(source('app.js'))\n .pipe(buffer())\n .pipe(sourcemaps.init({loadMaps: true})) // loads map from browserify file\n // Add transformation tasks to the pipeline here.\n .pipe(sourcemaps.write('./')) // writes .map file\n .pipe(gulp.dest('./dist/js'));\n }", "function streamify(promise, factory) {\n var _then = promise.then;\n promise.then = function() {\n factory();\n var newPromise = _then.apply(promise, arguments);\n return streamify(newPromise, factory);\n };\n promise.stream = factory;\n return promise;\n}", "function bundle() {\n return bundler.bundle()\n // log errors if they happen\n .on('error', gutil.log.bind(gutil, 'Browserify Error'))\n .pipe(source('bundle.js'))\n .pipe(buffer())\n .pipe(sourcemaps.init({loadMaps: true})) // loads map from browserify file\n .pipe(sourcemaps.write('./')) // writes .map file\n .pipe(gulp.dest('./dist'));\n}", "function createWrapperStream () {\n const stream = new PassThrough()\n let onFinishCallbacks = []\n\n stream._realOn = stream.on\n stream.on = function (eventName, callback) {\n if (eventName === 'finish') {\n return onFinishCallbacks.push(callback)\n }\n\n if (eventName === 'progress') {\n return stream.upload.on('httpUploadProgress', callback)\n }\n\n return stream._realOn(eventName, callback)\n }\n\n stream.triggerFinish = () => onFinishCallbacks.forEach(fn => fn())\n\n return stream\n}", "constructor(readable) {\n super();\n this.buffers = [];\n this.finished = false;\n this.error = null;\n\n // Pipe the input of the readable stream into this\n readable.pipe(this);\n\n this.on('error', this.handleError.bind(this));\n }", "function Bundler () {\n}", "import(stream) {\n stream.on('data', chunk => {\n this.write(chunk);\n });\n stream.on('end', () => {\n this.end();\n });\n stream.on('error', error => {\n this.emit('error', error);\n });\n return this;\n }", "function recurse (streams) {\n if(streams.length < 2)\n return\n streams[0].pipe(streams[1])\n recurse(streams.slice(1))\n }", "function recurse (streams) {\n if(streams.length < 2)\n return\n streams[0].pipe(streams[1])\n recurse(streams.slice(1))\n }", "function recurse (streams) {\n if(streams.length < 2)\n return\n streams[0].pipe(streams[1])\n recurse(streams.slice(1))\n }", "function ShimStream(options) {\n // be lenient with 'new' keyword\n if (!(this instanceof ShimStream)) {\n return new ShimStream(options);\n }\n\n // super\n Transform.call(this, options);\n\n // internal state\n this._onFirst = true;\n this._prefixString = prefixTemplate(); // TODO: dependencies support\n this._suffixString = suffixTemplate();\n}", "[PIPE] (job) {\n job.piped = true\n\n if (job.readdir)\n job.readdir.forEach(entry => {\n const p = this.prefix ?\n job.path.slice(this.prefix.length + 1) || './'\n : job.path\n\n const base = p === './' ? '' : p.replace(/\\/*$/, '/')\n this[ADDFSENTRY](base + entry)\n })\n\n const source = job.entry\n const zip = this.zip\n\n if (zip)\n source.on('data', chunk => {\n if (!zip.write(chunk))\n source.pause()\n })\n else\n source.on('data', chunk => {\n if (!super.write(chunk))\n source.pause()\n })\n }", "function bundleJS(bundler) {\n return bundler.bundle()\n .on('error', mapError)\n .pipe(source('client.js'))\n // optional, remove if you don't need to buffer file contents:\n .pipe(buffer())\n // capture sourcemaps from transforms:\n .pipe(gulpif(options.dev, sourcemaps.init({\n loadMaps: true\n })))\n // transform:\n .pipe(gulpif(!options.dev, streamify(uglify())))\n // write source maps:\n .pipe(gulpif(options.dev, sourcemaps.write('.')))\n .pipe(gulp.dest(options.dest + '/js'))\n .pipe(gulpif(options.dev, browserSync.reload({\n stream: true\n })));\n}", "[PIPE] (job) {\n job.piped = true\n\n if (job.readdir) {\n job.readdir.forEach(entry => {\n const p = job.path\n const base = p === './' ? '' : p.replace(/\\/*$/, '/')\n this[ADDFSENTRY](base + entry)\n })\n }\n\n const source = job.entry\n const zip = this.zip\n\n if (zip) {\n source.on('data', chunk => {\n if (!zip.write(chunk))\n source.pause()\n })\n } else {\n source.on('data', chunk => {\n if (!super.write(chunk))\n source.pause()\n })\n }\n }", "[PIPE] (job) {\n job.piped = true\n\n if (job.readdir) {\n job.readdir.forEach(entry => {\n const p = this.prefix ?\n job.path.slice(this.prefix.length + 1) || './'\n : job.path\n\n const base = p === './' ? '' : p.replace(/\\/*$/, '/')\n this[ADDFSENTRY](base + entry)\n })\n }\n\n const source = job.entry\n const zip = this.zip\n\n if (zip) {\n source.on('data', chunk => {\n if (!zip.write(chunk))\n source.pause()\n })\n } else {\n source.on('data', chunk => {\n if (!super.write(chunk))\n source.pause()\n })\n }\n }", "function make_bundle () {\n\t\tconsole.log( chalk.blue('Building Javascript') );\n\n\n\n\t\treturn bundler.bundle()\n\t\t .pipe(source('main.js'))\n\t\t .pipe(bufferify())\n\t\t .pipe(gulpif( args.prod, uglify() ))\n\t\t .pipe(gulp.dest(dir.compiled.js));\n\t}", "function createBundle(config) {\n\n var bopts = config.browserify || {};\n\n function warn(key) {\n log.warn('Invalid config option: \"' + key + 's\" should be \"' + key + '\"');\n }\n\n _.forEach([ 'transform', 'plugin' ], function(key) {\n if (bopts[key + 's']) {\n warn(key);\n }\n });\n\n var browserifyOptions = _.extend({}, watchify.args, _.omit(bopts, [\n 'transform', 'plugin', 'prebundle'\n ]));\n\n var w = watchify(browserify(browserifyOptions));\n\n _.forEach(bopts.plugin, function(p) {\n // ensure we can pass plugin options as\n // the first parameter\n if (!Array.isArray(p)) {\n p = [ p ];\n }\n w.plugin.apply(w, p);\n });\n\n _.forEach(bopts.transform, function(t) {\n // ensure we can pass transform options as\n // the first parameter\n if (!Array.isArray(t)) {\n t = [ t ];\n }\n w.transform.apply(w, t);\n });\n\n // test if we have a prebundle function\n if (bopts.prebundle && typeof bopts.prebundle === 'function') {\n bopts.prebundle(w);\n }\n\n // register rebuild bundle on change\n if (config.autoWatch) {\n log.info('registering rebuild (autoWatch=true)');\n\n w.on('update', function() {\n log.debug('files changed');\n deferredBundle();\n });\n }\n\n w.on('log', function(msg) {\n log.info(msg);\n });\n\n // files contained in bundle\n var files = [ ];\n\n\n // update bundle file\n w.on('bundled', function(err, content) {\n if (w._builtOnce && !err) {\n bundleFile.update(content.toString('utf-8'));\n log.info('bundle updated');\n }\n\n w._builtOnce = true;\n });\n\n\n function deferredBundle(cb) {\n if (cb) {\n w.once('bundled', cb);\n }\n\n rebuild();\n }\n\n\n var MISSING_MESSAGE = /^Cannot find module '([^']+)'/;\n\n var rebuild = _.debounce(function rebuild() {\n\n log.debug('bundling');\n\n w.reset();\n\n files.forEach(function(f) {\n w.require(f, { expose: path.relative(config.basePath, f) });\n });\n\n w.bundle(function(err, content) {\n\n if (err) {\n log.error('bundle error');\n log.error(String(err));\n\n // try to recover from removed test case\n // rebuild, if successful\n var match = MISSING_MESSAGE.exec(err.message);\n if (match) {\n var idx = files.indexOf(match[1]);\n\n if (idx !== -1) {\n log.debug('removing %s from bundle', match[1]);\n files.splice(idx, 1);\n\n log.debug('attempting rebuild');\n return rebuild();\n }\n }\n }\n\n w.emit('bundled', err, content);\n });\n }, 500);\n\n\n w.bundleFile = function(file, done) {\n\n var absolutePath = file.path,\n relativePath = path.relative(config.basePath, absolutePath);\n\n if (files.indexOf(absolutePath) === -1) {\n\n // add file\n log.debug('adding %s to bundle', relativePath);\n\n files.push(absolutePath);\n }\n\n deferredBundle(function(err) {\n done(err, 'require(\"' + escape(relativePath) + '\");');\n });\n };\n\n\n /**\n * Wait for the bundle creation to have stabilized (no more additions) and invoke a callback.\n *\n * @param {Function} cb\n * @param {Number} delay\n * @param {Number} timeout\n */\n w.deferredBundle = deferredBundle;\n\n return w;\n }", "function bundle() {\n return b.bundle()\n // log errors if they happen\n .on('error', gutil.log.bind(gutil, 'Browserify Error'))\n .pipe(source('stripe_express_angular.js'))\n //.pipe(uglify())\n // optional, remove if you don't need to buffer file contents\n .pipe(buffer())\n .pipe(ngannotate())\n .pipe(uglify())\n // optional, remove if you dont want sourcemaps\n .pipe(sourcemaps.init({loadMaps: true})) // loads map from browserify file\n // Add transformation tasks to the pipeline here.\n .pipe(sourcemaps.write('./')) // writes .map file\n .pipe(gulp.dest('./public/dest'));\n}", "import(stream) {\n var self = this;\n stream.on('data', function (chunk) {\n self.write(chunk);\n });\n stream.on('end', function () {\n self.end();\n });\n stream.on('error', function (error) {\n self.emit('error', error);\n });\n return this;\n }", "function base() {\n return streamCombiner(\n gulpif(tars.config.js.useBabel, tars.require('gulp-babel')()),\n concat({ cwd: cwd, path: 'main.js' }),\n rename({ suffix: tars.options.build.hash }),\n gulp.dest(destFolder),\n );\n}", "function bundle() {\n return browserify(nodeDir, {\n standalone: bundleGlobal\n })\n .bundle()\n .on(\"error\", handleError)\n .pipe(source(bundleFile))\n .pipe(buffer())\n .pipe(gulpSourcemaps.init({\n loadMaps: true\n }))\n .pipe(gulpSourcemaps.write(\".\", {\n sourceRoot: path.relative(bundleDir, nodeDir)\n }))\n .pipe(gulp.dest(bundleDir));\n}", "function recurse (streams) {\n if(streams.length < 2)\n return\n streams[0].pipe(streams[1])\n recurse(streams.slice(1)) \n }", "function recurse (streams) {\n if(streams.length < 2)\n return\n streams[0].pipe(streams[1])\n recurse(streams.slice(1)) \n }", "function chunk(pipe) {\n return run\n\n // Run the bound bound pipe and handles any errors.\n function run(context, file, fileSet, next) {\n pipe.run(context, file, fileSet, one);\n\n function one(error) {\n var messages = file.messages;\n var index;\n\n if (error) {\n index = messages.indexOf(error);\n\n if (index === -1) {\n error = file.message(error);\n index = messages.length - 1;\n }\n\n messages[index].fatal = true;\n }\n\n next();\n }\n }\n}", "function CollectStream() {\n stream.Transform.call(this);\n this._chunks = [];\n this._transform = (chunk, enc, cb) => { this._chunks.push(chunk); cb(); }\n this.collect = () => { return Buffer.concat(this._chunks); this._chunks = []; }\n}", "_restartStream(type, resource) {\n const { stream, jsonStream } = resource.restartStream();\n stream.on('close', this._closeHandler(type, resource));\n stream.on('error', this._errorHandler(type, resource));\n\n this.mergedStream = this.mergedStream.merge(Kefir.fromEvents(jsonStream, 'data'));\n this.mergedStream.onValue(this.sender);\n logger.info(`Stream ${type} was recreated`);\n }", "function transpileSource(bundler) {\r\n var timer = duration('Time Taken To Bundle');\r\n\r\n return bundler.bundle()\r\n .on('error', function (err) {\r\n browserSync.notify(\"Error\");\r\n gutil.log(err);\r\n })\r\n .pipe(source(config.js.srcName))\r\n .pipe(buffer())\r\n .pipe(rename(config.js.outputName))\r\n .pipe(gulp.dest(config.js.outputDir))\r\n .pipe(timer)\r\n .pipe(reload({\r\n stream: true\r\n }));\r\n}", "function bundleScripts(shouldWatch) {\n // Options for the browserify bundler\n const opts = {\n entries: [paths.scriptEntryPoint],\n debug: true,\n plugin: [],\n // These properties are used by watchify for caching\n cache: {},\n packageCache: {}\n };\n\n // Use the watchify plugin when we want to watch for file changes\n if(shouldWatch) opts.plugin.push(watchify);\n\n // Create the bundler\n const bundler = browserify(opts)\n .transform([babelify, { sourceMap: true }])\n .external(libs);\n\n // This function returns a stream which produces the final bundled output\n // from the bundler object\n const rebundle = () => {\n return bundler.bundle()\n .on('error', onError)\n .pipe(source('app.js'))\n .pipe(buffer())\n .pipe(gulp.dest('dist/js'));\n };\n\n // Rebundle when watchify detects a change\n bundler.on('update', () => {\n gutil.log('Rebundling...');\n rebundle().on('end', () => gutil.log('Finished rebundling.'));\n });\n\n // Return bundling stream (mostly for when `shouldWatch` is false)\n return rebundle();\n}", "streamsReinit(env) {\n const spot = Spot(env)\n env.upgrade(path, (...args) => {\n spot.connections.add(args)\n openConnections(env)\n })\n }", "passthrough() {\n const me = this;\n // A chunk counter for debugging\n let _scan_complete = false;\n let _av_waiting = null;\n let _av_scan_time = false;\n\n // DRY method for clearing the interval and counter related to scan times\n const clear_scan_benchmark = () => {\n if (_av_waiting) clearInterval(_av_waiting);\n _av_waiting = null;\n _av_scan_time = 0;\n };\n\n // Return a Transform stream so this can act as a \"man-in-the-middle\"\n // for the streaming pipeline.\n // Ex. upload_stream.pipe(<this_transform_stream>).pipe(destination_stream)\n return new Transform({\n // This should be fired on each chunk received\n async transform(chunk, encoding, cb) {\n\n // DRY method for handling each chunk as it comes in\n const do_transform = () => {\n // Write data to our fork stream. If it fails,\n // emit a 'drain' event\n if (!this._fork_stream.write(chunk)) {\n this._fork_stream.once('drain', () => {\n cb(null, chunk);\n });\n } else {\n // Push data back out to whatever is listening (if anything)\n // and let Node know we're ready for more data\n cb(null, chunk);\n }\n };\n\n // DRY method for handling errors when the arise from the\n // ClamAV Socket connection\n const handle_error = (err, is_infected=null, result=null) => {\n this._fork_stream.unpipe();\n this._fork_stream.destroy();\n this._clamav_transform.destroy();\n clear_scan_benchmark();\n\n // Finding an infected file isn't really an error...\n if (is_infected === true) {\n if (_scan_complete === false) {\n _scan_complete = true;\n this.emit('scan-complete', result);\n }\n this.emit('stream-infected', result); // just another way to catch an infected stream\n } else {\n this.emit('error', err);\n }\n };\n\n // If we haven't initialized a socket connection to ClamAV yet,\n // now is the time...\n if (!this._clamav_socket) {\n // We're using a PassThrough stream as a middle man to fork the input\n // into two paths... (1) ClamAV and (2) The final destination.\n this._fork_stream = new PassThrough();\n // Instantiate our custom Transform stream that coddles\n // chunks into the correct format for the ClamAV socket.\n this._clamav_transform = new NodeClamTransform({}, me.settings.debug_mode);\n // Setup an array to collect the responses from ClamAV\n this._clamav_response_chunks = [];\n\n try {\n // Get a connection to the ClamAV Socket\n this._clamav_socket = await me._init_socket('passthrough');\n if (me.settings.debug_mode) console.log(`${me.debug_label}: ClamAV Socket Initialized...`);\n\n // Setup a pipeline that will pass chunks through our custom Tranform and on to ClamAV\n this._fork_stream.pipe(this._clamav_transform).pipe(this._clamav_socket);\n\n // When the CLamAV socket connection is closed (could be after 'end' or because of an error)...\n this._clamav_socket.on('close', hadError => {\n if (me.settings.debug_mode) console.log(`${me.debug_label}: ClamAV socket has been closed! Because of Error:`, hadError);\n })\n // When the ClamAV socket connection ends (receives chunk)\n .on('end', () => {\n if (me.settings.debug_mode) console.log(`${me.debug_label}: ClamAV socket has received the last chunk!`);\n // Process the collected chunks\n const response = Buffer.concat(this._clamav_response_chunks);\n const result = me._process_result(response.toString('utf8'), null);\n this._clamav_response_chunks = [];\n if (me.settings.debug_mode) {\n console.log(`${me.debug_label}: Result of scan:`, result);\n console.log(`${me.debug_label}: It took ${_av_scan_time} seconds to scan the file(s).`);\n clear_scan_benchmark();\n }\n\n // NOTE: \"scan-complete\" could be called by the `handle_error` method.\n // We don't want to to double-emit this message.\n if (_scan_complete === false) {\n _scan_complete = true;\n this.emit('scan-complete', result);\n }\n })\n // If connection timesout.\n .on('timeout', () => {\n this.emit('timeout', new Error('Connection to host/socket has timed out'));\n if (me.settings.debug_mode) console.log(`${me.debug_label}: Connection to host/socket has timed out`);\n })\n // When the ClamAV socket is ready to receive packets (this will probably never fire here)\n .on('ready', () => {\n if (me.settings.debug_mode) console.log(`${me.debug_label}: ClamAV socket ready to receive`);\n })\n // When we are officially connected to the ClamAV socket (probably will never fire here)\n .on('connect', () => {\n if (me.settings.debug_mode) console.log(`${me.debug_label}: Connected to ClamAV socket`);\n })\n // If an error is emitted from the ClamAV socket\n .on('error', err => {\n console.error(`${me.debug_label}: Error emitted from ClamAV socket: `, err);\n handle_error(err);\n })\n // If ClamAV is sending stuff to us (ie, an \"OK\", \"Virus FOUND\", or \"ERROR\")\n .on('data', cv_chunk => {\n // Push this chunk to our results collection array\n this._clamav_response_chunks.push(cv_chunk);\n if (me.settings.debug_mode) console.log(`${me.debug_label}: Got result!`, cv_chunk.toString());\n\n // Parse what we've gotten back from ClamAV so far...\n const response = Buffer.concat(this._clamav_response_chunks);\n const result = me._process_result(response.toString(), null);\n\n // If there's an error supplied or if we detect a virus, stop stream immediately.\n if (result instanceof NodeClamError || (typeof result === 'object' && 'is_infected' in result && result.is_infected === true)) {\n // If a virus is detected...\n if (typeof result === 'object' && 'is_infected' in result && result.is_infected === true) {\n // handle_error(new NodeClamError(result, `Virus(es) found! ${'viruses' in result && Array.isArray(result.viruses) ? `Suspects: ${result.viruses.join(', ')}` : ''}`));\n handle_error(null, true, result);\n }\n // If any other kind of error is detected...\n else {\n handle_error(result);\n }\n }\n // For debugging purposes, spit out what was processed (if anything).\n else {\n if (me.settings.debug_mode) console.log(`${me.debug_label}: Processed Result: `, result, response.toString());\n }\n });\n\n if (me.settings.debug_mode) console.log(`${me.debug_label}: Doing initial transform!`);\n // Handle the chunk\n do_transform();\n } catch (err) {\n // If there's an issue connecting to the ClamAV socket, this is where that's handled\n if (me.settings.debug_mode) console.error(`${me.debug_label}: Error initiating socket to ClamAV: `, err);\n handle_error(err);\n }\n } else {\n //if (me.settings.debug_mode) console.log(`${me.debug_label}: Doing transform: ${++counter}`);\n // Handle the chunk\n do_transform();\n }\n },\n\n // This is what is called when the input stream has dried up\n flush(cb) {\n if (me.settings.debug_mode) console.log(`${me.debug_label}: Done with the full pipeline.`);\n\n // Keep track of how long it's taking to scan a file..\n _av_waiting = null;\n _av_scan_time = 0;\n if (me.settings.debug_mode) {\n _av_waiting = setInterval(() => {\n _av_scan_time += 1;\n if (_av_scan_time % 5 === 0) console.log(`${me.debug_label}: ClamAV has been scanning for ${_av_scan_time} seconds...`);\n }, 1000);\n }\n\n // TODO: Investigate why this needs to be done in order\n // for the ClamAV socket to be closed (why NodeClamTransform's\n // `_flush` method isn't getting called)\n // If the incoming stream is empty, transform() won't have been called, so we won't\n // have a socket here.\n if (this._clamav_socket && this._clamav_socket.writable === true) {\n const size = Buffer.alloc(4);\n size.writeInt32BE(0, 0);\n this._clamav_socket.write(size, cb);\n }\n }\n });\n }", "static install(lname, srcBasePath, distBasePath) {\n let p = new LambdaPacker(lname, srcBasePath, distBasePath); \n return gulp.series(p.copy, p.build, p.package, p.cleanup); \n }", "function compile(watch){\n var bundle= browserify('./src/index.js');\n\n\n\n if(watch){\n bundle=watchify(bundle);\n //se utilizara el metodo on y el evento update\n // la funcion se llamara cada cuendo haya cambios\n bundle.on('update', function(){\n console.log(\"--> Bundling....\");\n rebundle();\n })\n }\n\n function rebundle(){\n bundle\n .transform(babel, {presets: [\"es2015\"], plugins:['syntax-async-functions','transform-regenerator'] })\n .bundle()\n .on('error', function(err){\n console.log(err);\n this.emit('end')\n })\n .pipe(source('index.js'))\n //.pipe(souce('index.js'))\n .pipe(rename('app.js'))\n .pipe(gulp.dest('public'));\n }\n\n //lo llamara por primera vez\n rebundle();\n}", "function wrapStream(self, stream, cbExtra)\n{\n var duplex = new require(\"stream\").Duplex();\n\n // allow for manually injected json\n duplex.bufJS = {};\n duplex.js = function(js){\n Object.keys(js).forEach(function(key){ duplex.bufJS[key] = js[key]; });\n setTimeout(doChunk, 10);\n };\n \n // buffer writes and chunk them out\n duplex.bufBody = new Buffer(0);\n duplex.cbWrite;\n\n function doChunk(){\n console.log(\"CHUNKING\", duplex.bufJS, duplex.bufBody.length)\n if(duplex.bufBody.length === 0 && Object.keys(duplex.bufJS).length === 0) return; \n var bodyout;\n var jsout = duplex.bufJS;\n duplex.bufJS = {};\n if(duplex.bufBody.length > 0)\n {\n var len = 1024 - JSON.stringify(jsout).length; // max body size for a packet\n if(duplex.bufBody.length < len) len = duplex.bufBody.length;\n bodyout = duplex.bufBody.slice(0, len);\n duplex.bufBody = duplex.bufBody.slice(len, duplex.bufBody.length - len);\n }\n // send it!\n sendStream(self, stream, {js:jsout, body:bodyout, done:function(){\n // we might be backed up, let more in\n if(duplex.cbWrite)\n {\n // am I being paranoid that a cbWrite() could have set another duplex.cbWrite?\n var cb = duplex.cbWrite;\n delete duplex.cbWrite;\n cb();\n }\n }});\n // recurse nicely\n setTimeout(doChunk, 10);\n \n };\n\n duplex.end = function(){\n duplex.bufJS.end = true;\n if(stream.errMsg) duplex.bufJS.err = stream.errMsg;\n doChunk();\n }\n\n duplex._write = function(buf, enc, cbWrite){\n duplex.bufBody = Buffer.concat([duplex.bufBody, buf]);\n\n // if there's 50 packets waiting to be confirmed, hold up here, otherwise buffer up\n var cbPacket = doChunk;\n if(stream.outq.length > 50)\n {\n duplex.cbWrite = cbWrite;\n }else{\n cbWrite();\n }\n \n // try sending a chunk;\n doChunk();\n } \n \n duplex._read = function(size){\n // TODO handle backpressure\n // perform duplex.push(body)'s if any waiting, if not .push('')\n // handle return value logic properly\n };\n\n stream.handler = function(self, packet, cbHandler) {\n // TODO migrate to _read backpressure stuff above\n console.log(\"HANDLER\", packet.js)\n if(cbExtra) cbExtra(packet);\n if(packet.body) duplex.push(packet.body);\n if(packet.js.end) duplex.push(null);\n cbHandler();\n }\n return duplex; \n}", "_initializePipeline() {\n if (this.pipelineInitialized) return;\n this.zip = (0, _archiver.default)('zip', {\n forceUTC: true\n });\n this.zip.catchEarlyExitAttached = true; // Common xlsx archive files (not editable)\n\n this.zip.append(templates.ContentTypes, {\n name: '[Content_Types].xml'\n });\n this.zip.append(templates.Rels, {\n name: '_rels/.rels'\n });\n this.zip.append(templates.Workbook, {\n name: 'xl/workbook.xml'\n });\n this.zip.append(templates.WorkbookRels, {\n name: 'xl/_rels/workbook.xml.rels'\n }); // Style xlsx definitions (one time generation)\n\n const styles = new templates.Styles(this.options.styleDefs);\n this.zip.append(styles.render(), {\n name: 'xl/styles.xml'\n });\n this.zip.on('data', data => this.push(data)).on('warning', err => this.emit('warning', err)).on('error', err => this.emit('error', err));\n this.toXlsxRow = new _XLSXRowTransform.default({\n format: this.options.format,\n styles\n });\n this.sheetStream = new _stream.PassThrough();\n this.sheetStream.write(templates.SheetHeader);\n this.toXlsxRow.pipe(this.sheetStream, {\n end: false\n });\n this.zip.append(this.sheetStream, {\n name: 'xl/worksheets/sheet1.xml'\n });\n this.pipelineInitialized = true;\n }", "function preprocessor (stream) {\n // TODO: support new stream API once node's net.Socket supports it\n stream.on('data', onData);\n stream.realOn = stream.on;\n stream.on = stream.addListener = on;\n stream.realRemoveListener = stream.removeListener;\n stream.removeListener = removeListener;\n Object.defineProperty(stream, 'ondata', {\n set: setOnData\n });\n}", "function emitReadable$2(stream) {\n\t var state = stream._readableState;\n\t state.needReadable = false;\n\t if (!state.emittedReadable) {\n\t debug$2('emitReadable', state.flowing);\n\t state.emittedReadable = true;\n\t if (state.sync) processNextickArgs.nextTick(emitReadable_$2, stream);else emitReadable_$2(stream);\n\t }\n\t}", "function initstream() {\n function Stream( head, tailPromise ) {\n if ( typeof head != 'undefined' ) {\n this.headValue = head;\n }\n if ( typeof tailPromise == 'undefined' ) {\n tailPromise = function () {\n return new Stream();\n };\n }\n this.tailPromise = tailPromise;\n }\n\n // TODO: write some unit tests\n Stream.prototype = {\n empty: function() {\n return typeof this.headValue == 'undefined';\n },\n head: function() {\n if ( this.empty() ) {\n throw new Error('Cannot get the head of the empty stream.');\n }\n return this.headValue;\n },\n tail: function() {\n if ( this.empty() ) {\n throw new Error('Cannot get the tail of the empty stream.');\n }\n // TODO: memoize here\n return this.tailPromise();\n },\n item: function( n ) {\n if ( this.empty() ) {\n throw new Error('Cannot use item() on an empty stream.');\n }\n var s = this;\n while ( n != 0 ) {\n --n;\n try {\n s = s.tail();\n }\n catch ( e ) {\n throw new Error('Item index does not exist in stream.');\n }\n }\n try {\n return s.head();\n }\n catch ( e ) {\n throw new Error('Item index does not exist in stream.');\n }\n },\n length: function() {\n // requires finite stream\n var s = this;\n var len = 0;\n\n while ( !s.empty() ) {\n ++len;\n s = s.tail();\n }\n return len;\n },\n add: function( s ) {\n return this.zip( function ( x, y ) {\n return x + y;\n }, s );\n },\n append: function ( stream ) {\n if ( this.empty() ) {\n return stream;\n }\n var self = this;\n return new Stream(\n self.head(),\n function () {\n return self.tail().append( stream );\n }\n );\n },\n zip: function( f, s ) {\n if ( this.empty() ) {\n return s;\n }\n if ( s.empty() ) {\n return this;\n }\n var self = this;\n return new Stream( f( s.head(), this.head() ), function () {\n return self.tail().zip( f, s.tail() );\n } );\n },\n map: function( f ) {\n if ( this.empty() ) {\n return this;\n }\n var self = this;\n return new Stream( f( this.head() ), function () {\n return self.tail().map( f );\n } );\n },\n concatmap: function ( f ) {\n return this.reduce( function ( a, x ) {\n return a.append( f(x) );\n }, new Stream () );\n },\n reduce: function () {\n var aggregator = arguments[0];\n var initial, self;\n if(arguments.length < 2) {\n if(this.empty()) throw new TypeError(\"Array length is 0 and no second argument\");\n initial = this.head();\n self = this.tail();\n }\n else {\n initial = arguments[1];\n self = this;\n }\n // requires finite stream\n if ( self.empty() ) {\n return initial;\n }\n // TODO: iterate\n return self.tail().reduce( aggregator, aggregator( initial, self.head() ) );\n },\n sum: function () {\n // requires finite stream\n return this.reduce( function ( a, b ) {\n return a + b;\n }, 0 );\n },\n walk: function( f ) {\n // requires finite stream\n this.map( function ( x ) {\n f( x );\n return x;\n } ).force();\n },\n force: function() {\n // requires finite stream\n var stream = this;\n while ( !stream.empty() ) {\n stream = stream.tail();\n }\n },\n scale: function( factor ) {\n return this.map( function ( x ) {\n return factor * x;\n } );\n },\n filter: function( f ) {\n if ( this.empty() ) {\n return this;\n }\n var h = this.head();\n var t = this.tail();\n if ( f( h ) ) {\n return new Stream( h, function () {\n return t.filter( f );\n } );\n }\n return t.filter( f );\n },\n take: function ( howmany ) {\n if ( this.empty() ) {\n return this;\n }\n if ( howmany == 0 ) {\n return new Stream();\n }\n var self = this;\n return new Stream(\n this.head(),\n function () {\n return self.tail().take( howmany - 1 );\n }\n );\n },\n drop: function( n ){\n var self = this;\n\n while ( n-- > 0 ) {\n\n if ( self.empty() ) {\n return new Stream();\n }\n\n self = self.tail();\n }\n\n // create clone/a contructor which accepts a stream?\n return new Stream( self.headValue, self.tailPromise );\n },\n member: function( x ){\n var self = this;\n\n while( !self.empty() ) {\n if ( self.head() == x ) {\n return true;\n }\n\n self = self.tail();\n }\n\n return false;\n },\n toArray: function( n ) {\n var target, result = [];\n if ( typeof n != 'undefined' ) {\n target = this.take( n );\n }\n else {\n // requires finite stream\n target = this;\n }\n target.walk( function ( x ) {\n result.push( x );\n } );\n return result;\n },\n print: function( n ) {\n var target;\n if ( typeof n != 'undefined' ) {\n target = this.take( n );\n }\n else {\n // requires finite stream\n target = this;\n }\n target.walk( function ( x ) {\n //console.log( x );\n } );\n },\n toString: function() {\n // requires finite stream\n return '[stream head: ' + this.head() + '; tail: ' + this.tail() + ']';\n }\n };\n\n Stream.makeOnes = function() {\n return new Stream( 1, Stream.makeOnes );\n };\n Stream.makeNaturalNumbers = function() {\n return new Stream( 1, function () {\n return Stream.makeNaturalNumbers().add( Stream.makeOnes() );\n } );\n };\n Stream.make = function( /* arguments */ ) {\n if ( arguments.length == 0 ) {\n return new Stream();\n }\n var restArguments = Array.prototype.slice.call( arguments, 1 );\n return new Stream( arguments[ 0 ], function () {\n return Stream.make.apply( null, restArguments );\n } );\n };\n Stream.fromArray = function ( array ) {\n if ( array.length == 0 ) {\n return new Stream();\n }\n return new Stream( array[0], function() { return Stream.fromArray(array.slice(1)); } );\n };\n Stream.range = function ( low, high ) {\n if ( typeof low == 'undefined' ) {\n low = 1;\n }\n if ( low == high ) {\n return Stream.make( low );\n }\n // if high is undefined, there won't be an upper bound\n return new Stream( low, function () {\n return Stream.range( low + 1, high );\n } );\n };\n Stream.equals = function ( stream1, stream2 ) {\n if ( ! (stream1 instanceof Stream) ) return false;\n if ( ! (stream2 instanceof Stream) ) return false;\n if ( stream1.empty() && stream2.empty() ) {\n return true;\n }\n if ( stream1.empty() || stream2.empty() ) {\n return false;\n }\n if ( stream1.head() === stream2.head() ) {\n return Stream.equals( stream1.tail(), stream2.tail() );\n }\n };\n return Stream;\n}", "[PIPE] (job) {\n const source = job.entry\n const zip = this.zip\n\n if (job.readdir) {\n job.readdir.forEach(entry => {\n const p = job.path\n const base = p === './' ? '' : p.replace(/\\/*$/, '/')\n this[ADDFSENTRY](base + entry)\n })\n }\n\n if (zip) {\n source.on('data', chunk => {\n zip.write(chunk)\n })\n } else {\n source.on('data', chunk => {\n super[WRITE](chunk)\n })\n }\n }", "function HashPipeStream() {\n\tvar self = this;\n\tself.readable = true;\n\tself.writable = true;\n\tstream.Stream.call(this);\n}", "function streamPipelinePromise(streams) {\n return new Promise((resolve, reject) => {\n const lastStream = streams[streams.length - 1];\n lastStream.on('finish', resolve);\n pipeline(streams, (err) => {\n if (err) {\n reject(err);\n }\n });\n });\n}", "[PIPE] (job) {\n const source = job.entry\n const zip = this.zip\n\n if (job.readdir)\n job.readdir.forEach(entry => {\n const p = this.prefix ?\n job.path.slice(this.prefix.length + 1) || './'\n : job.path\n\n const base = p === './' ? '' : p.replace(/\\/*$/, '/')\n this[ADDFSENTRY](base + entry)\n })\n\n if (zip)\n source.on('data', chunk => {\n zip.write(chunk)\n })\n else\n source.on('data', chunk => {\n super[WRITE](chunk)\n })\n }", "_transform(data, done){\r\n this.stdio.stdin.splitPush(data)\r\n this.fork.stdin.write(data) && done() || this.fork.stdin.on('drain', done)\r\n }", "function initstream() {\n function Stream(head, tailPromise) {\n if (typeof head != 'undefined') {\n this.headValue = head;\n }\n if (typeof tailPromise == 'undefined') {\n tailPromise = function () {\n return new Stream();\n };\n }\n this.tailPromise = tailPromise;\n }\n\n // TODO: write some unit tests\n Stream.prototype = {\n empty: function () {\n return typeof this.headValue == 'undefined';\n },\n head: function () {\n if (this.empty()) {\n throw new Error('Cannot get the head of the empty stream.');\n }\n return this.headValue;\n },\n tail: function () {\n if (this.empty()) {\n throw new Error('Cannot get the tail of the empty stream.');\n }\n // TODO: memoize here\n return this.tailPromise();\n },\n item: function (n) {\n if (this.empty()) {\n throw new Error('Cannot use item() on an empty stream.');\n }\n var s = this;\n while (n != 0) {\n --n;\n try {\n s = s.tail();\n } catch (e) {\n throw new Error('Item index does not exist in stream.');\n }\n }\n try {\n return s.head();\n } catch (e) {\n throw new Error('Item index does not exist in stream.');\n }\n },\n length: function () {\n // requires finite stream\n var s = this;\n var len = 0;\n\n while (!s.empty()) {\n ++len;\n s = s.tail();\n }\n return len;\n },\n add: function (s) {\n return this.zip(function (x, y) {\n return x + y;\n }, s);\n },\n append: function (stream) {\n if (this.empty()) {\n return stream;\n }\n var self = this;\n return new Stream(self.head(), function () {\n return self.tail().append(stream);\n });\n },\n zip: function (f, s) {\n if (this.empty()) {\n return s;\n }\n if (s.empty()) {\n return this;\n }\n var self = this;\n return new Stream(f(s.head(), this.head()), function () {\n return self.tail().zip(f, s.tail());\n });\n },\n map: function (f) {\n if (this.empty()) {\n return this;\n }\n var self = this;\n return new Stream(f(this.head()), function () {\n return self.tail().map(f);\n });\n },\n concatmap: function (f) {\n return this.reduce(function (a, x) {\n return a.append(f(x));\n }, new Stream());\n },\n reduce: function () {\n var aggregator = arguments[0];\n var initial, self;\n if (arguments.length < 2) {\n if (this.empty()) throw new TypeError(\"Array length is 0 and no second argument\");\n initial = this.head();\n self = this.tail();\n } else {\n initial = arguments[1];\n self = this;\n }\n // requires finite stream\n if (self.empty()) {\n return initial;\n }\n // TODO: iterate\n return self.tail().reduce(aggregator, aggregator(initial, self.head()));\n },\n sum: function () {\n // requires finite stream\n return this.reduce(function (a, b) {\n return a + b;\n }, 0);\n },\n walk: function (f) {\n // requires finite stream\n this.map(function (x) {\n f(x);\n return x;\n }).force();\n },\n force: function () {\n // requires finite stream\n var stream = this;\n while (!stream.empty()) {\n stream = stream.tail();\n }\n },\n scale: function (factor) {\n return this.map(function (x) {\n return factor * x;\n });\n },\n filter: function (f) {\n if (this.empty()) {\n return this;\n }\n var h = this.head();\n var t = this.tail();\n if (f(h)) {\n return new Stream(h, function () {\n return t.filter(f);\n });\n }\n return t.filter(f);\n },\n take: function (howmany) {\n if (this.empty()) {\n return this;\n }\n if (howmany == 0) {\n return new Stream();\n }\n var self = this;\n return new Stream(this.head(), function () {\n return self.tail().take(howmany - 1);\n });\n },\n drop: function (n) {\n var self = this;\n\n while (n-- > 0) {\n\n if (self.empty()) {\n return new Stream();\n }\n\n self = self.tail();\n }\n\n // create clone/a contructor which accepts a stream?\n return new Stream(self.headValue, self.tailPromise);\n },\n member: function (x) {\n var self = this;\n\n while (!self.empty()) {\n if (self.head() == x) {\n return true;\n }\n\n self = self.tail();\n }\n\n return false;\n },\n toArray: function (n) {\n var target,\n result = [];\n if (typeof n != 'undefined') {\n target = this.take(n);\n } else {\n // requires finite stream\n target = this;\n }\n target.walk(function (x) {\n result.push(x);\n });\n return result;\n },\n print: function (n) {\n var target;\n if (typeof n != 'undefined') {\n target = this.take(n);\n } else {\n // requires finite stream\n target = this;\n }\n target.walk(function (x) {\n //console.log( x );\n });\n },\n toString: function () {\n // requires finite stream\n return '[stream head: ' + this.head() + '; tail: ' + this.tail() + ']';\n }\n };\n\n Stream.makeOnes = function () {\n return new Stream(1, Stream.makeOnes);\n };\n Stream.makeNaturalNumbers = function () {\n return new Stream(1, function () {\n return Stream.makeNaturalNumbers().add(Stream.makeOnes());\n });\n };\n Stream.make = function () /* arguments */{\n if (arguments.length == 0) {\n return new Stream();\n }\n var restArguments = Array.prototype.slice.call(arguments, 1);\n return new Stream(arguments[0], function () {\n return Stream.make.apply(null, restArguments);\n });\n };\n Stream.fromArray = function (array) {\n if (array.length == 0) {\n return new Stream();\n }\n return new Stream(array[0], function () {\n return Stream.fromArray(array.slice(1));\n });\n };\n Stream.range = function (low, high) {\n if (typeof low == 'undefined') {\n low = 1;\n }\n if (low == high) {\n return Stream.make(low);\n }\n // if high is undefined, there won't be an upper bound\n return new Stream(low, function () {\n return Stream.range(low + 1, high);\n });\n };\n Stream.equals = function (stream1, stream2) {\n if (!(stream1 instanceof Stream)) return false;\n if (!(stream2 instanceof Stream)) return false;\n if (stream1.empty() && stream2.empty()) {\n return true;\n }\n if (stream1.empty() || stream2.empty()) {\n return false;\n }\n if (stream1.head() === stream2.head()) {\n return Stream.equals(stream1.tail(), stream2.tail());\n }\n };\n return Stream;\n }", "[PIPE] (job) {\n const source = job.entry\n const zip = this.zip\n\n if (job.readdir) {\n job.readdir.forEach(entry => {\n const p = this.prefix ?\n job.path.slice(this.prefix.length + 1) || './'\n : job.path\n\n const base = p === './' ? '' : p.replace(/\\/*$/, '/')\n this[ADDFSENTRY](base + entry)\n })\n }\n\n if (zip) {\n source.on('data', chunk => {\n zip.write(chunk)\n })\n } else {\n source.on('data', chunk => {\n super[WRITE](chunk)\n })\n }\n }", "_processBabel(file) {\n// Return a through Transform stream, in which we transform source code with babel......\n return through( function(chunk, enc, done) {\n let {code} = babel.transformSync(chunk.toString(), {\n babelrc: true,\n filename: file\n })\n\n// Push result to stream....\n this.push(code)\n\n// Call callback.....\n done()\n })\n }", "function ReadableStreamTee(stream) {\n const reader = AcquireReadableStreamDefaultReader(stream);\n\n let closedOrErrored = false;\n let canceled1 = false;\n let canceled2 = false;\n let reason1;\n let reason2;\n let promise = v8_createPromise();\n\n const branch1Stream = new ReadableStream({pull, cancel: cancel1});\n\n const branch2Stream = new ReadableStream({pull, cancel: cancel2});\n\n const branch1 = branch1Stream[_controller];\n const branch2 = branch2Stream[_controller];\n\n thenPromise(\n reader[_closedPromise], undefined, function(r) {\n if (closedOrErrored === true) {\n return;\n }\n\n ReadableStreamDefaultControllerError(branch1, r);\n ReadableStreamDefaultControllerError(branch2, r);\n closedOrErrored = true;\n });\n\n return [branch1Stream, branch2Stream];\n\n function pull() {\n return thenPromise(\n ReadableStreamDefaultReaderRead(reader), function(result) {\n const value = result.value;\n const done = result.done;\n\n if (done === true && closedOrErrored === false) {\n if (canceled1 === false) {\n ReadableStreamDefaultControllerClose(branch1);\n }\n if (canceled2 === false) {\n ReadableStreamDefaultControllerClose(branch2);\n }\n closedOrErrored = true;\n }\n\n if (closedOrErrored === true) {\n return;\n }\n\n if (canceled1 === false) {\n ReadableStreamDefaultControllerEnqueue(branch1, value);\n }\n\n if (canceled2 === false) {\n ReadableStreamDefaultControllerEnqueue(branch2, value);\n }\n });\n }\n\n function cancel1(reason) {\n canceled1 = true;\n reason1 = reason;\n\n if (canceled2 === true) {\n const compositeReason = [reason1, reason2];\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n v8_resolvePromise(promise, cancelResult);\n }\n\n return promise;\n }\n\n function cancel2(reason) {\n canceled2 = true;\n reason2 = reason;\n\n if (canceled1 === true) {\n const compositeReason = [reason1, reason2];\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n v8_resolvePromise(promise, cancelResult);\n }\n\n return promise;\n }\n }", "function bundlePreprocessor(config) {\n\n var debug = config.browserify && config.browserify.debug;\n\n function updateSourceMap(file, content) {\n var map;\n\n if (debug) {\n map = convert.fromSource(content);\n\n if (map) {\n file.sourceMap = map.sourcemap;\n }\n }\n }\n\n return function(content, file, done) {\n\n if (b._builtOnce) {\n updateSourceMap(file, content);\n return done(content);\n }\n\n log.debug('building bundle');\n\n // wait for the initial bundle to be created\n b.deferredBundle(function(err, content) {\n\n if (err) {\n return done(err);\n }\n\n content = content.toString('utf-8');\n updateSourceMap(file, content);\n\n log.info('bundle built');\n done(content);\n });\n };\n }", "function initializeAndWatch (ComponentInitializer, path) {\n\n // make a component on the fn\n var c; \n\n // make a stream of component errors\n var componentErrorStream = Kefir.stream((emitter) => {\n c = new ComponentInitializer((err) => {\n emitter.error(err)\n })\n })\n\n // make a stream of components over tiem\n var componentStream = fileChangeS(path)\n .flatMap((path) => {\n return Kefir.fromNodeCallback((cb) => {\n idempotentRequireIfSyntaxOk(path, cb)\n })\n })\n .map((fn) => {\n c.update(fn)\n return c\n })\n\n // merge this stream with the stream of errors\n return Kefir.merge([componentStream, componentErrorStream])\n}", "pipe(...parsers) {\n // Call each parser and merge returned value into one object\n return parsers.reduce((previousValue, parser) => {\n const result = parser[1](generator);\n return Object.assign({}, previousValue, { [parser[0]]: result });\n }, initialObject);\n }", "function streamBuffer(stream) {\n return new Promise((resolve, reject) => {\n const chunks = []\n stream.on('data', chunk => chunks.push(chunk))\n stream.on('error', error => reject(error))\n stream.on('end', () => resolve(Buffer.concat(chunks)))\n })\n}", "chainWebpack(chain) {}", "run() {\n const self = this;\n return new Promise((resolve, reject) => {\n const pipelineArgs = [\n self.feedInStream,\n new LoggerStream({\n message: \"feedReader.run feedInStream>\"\n }),\n parallel.transform(\n (feed, encoding, callback) => {\n self\n .process(feed.url)\n .then(() => {\n callback(null, feed);\n return feed;\n })\n .catch(error => {\n callback(error);\n });\n }, {\n objectMode: true,\n concurrency: self.concurrency\n }),\n new LoggerStream({\n message: \"feedReader.run parallel.transform>\"\n }),\n ];\n if (self.feedOutStream) {\n pipelineArgs.push(\n new LoggerStream({\n message: \"feedReader.run >feedOutStream\"\n }),\n self.feedOutStream\n );\n }\n // Pipeline final argument is a callback\n pipelineArgs.push((error) => {\n if (error) {\n return reject(error);\n }\n resolve();\n });\n pipeline.apply(null, pipelineArgs);\n });\n }", "function toBrowserify(bundleType) {\n var args = merge(watchify.args, { debug: true });\n\n var bundler = browserify('./public/browserify/' + bundleType + '.js', args)\n .plugin(watchify)\n .transform(babelify, {presets: ['es2015', 'react']})\n\n function bundleFiles() {\n console.log(\"Browserify Bundling \" + bundleType);\n bundler.bundle()\n .on('error', gutil.log.bind(gutil, 'Browserify Error ' + bundleType))\n .pipe(source(bundleType + 'Bundle.js'))\n .pipe(buffer())\n .pipe(gulp.dest('./public/bundles'));\n }\n\n bundler.on('update', bundleFiles);\n bundleFiles();\n}", "function SimplePipeStream() {\n\tvar self = this;\n\tself.readable = true;\n\tself.writable = true;\n\tstream.Stream.call(this);\n}", "function gulpCallback(obj) {\n var stream = new Stream.Transform({objectMode: true});\n\n stream._transform = function(file, unused, callback) {\n var result = obj(file, stream);\n file = result === undefined ? file : result;\n callback(null, file);\n };\n\n return stream;\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 }", "loadDependencies() {\n gulpWebpack = require('webpack-stream');\n }" ]
[ "0.65482754", "0.63993907", "0.61874443", "0.6103823", "0.57085663", "0.5681246", "0.56087965", "0.5597793", "0.55820274", "0.55474615", "0.5523728", "0.5503719", "0.5476412", "0.5429697", "0.5413252", "0.53887784", "0.5371574", "0.5366755", "0.53527385", "0.53102314", "0.52937996", "0.52892286", "0.5285575", "0.52800417", "0.52510875", "0.5241388", "0.52372223", "0.5197097", "0.5196249", "0.51898986", "0.51760304", "0.5168955", "0.51552844", "0.51447785", "0.5091655", "0.50863767", "0.5081293", "0.5076691", "0.5055123", "0.5053989", "0.5051657", "0.5020049", "0.500223", "0.49783316", "0.49768195", "0.49747986", "0.49603948", "0.49566078", "0.4932172", "0.49298334", "0.4877824", "0.4877824", "0.4877824", "0.48753324", "0.48690355", "0.48646963", "0.48601374", "0.48552734", "0.48538017", "0.48495588", "0.4843379", "0.48241267", "0.48057735", "0.48038596", "0.4799151", "0.4799151", "0.4749007", "0.4729587", "0.47241682", "0.46992597", "0.46880293", "0.46777326", "0.4667382", "0.46623084", "0.46441248", "0.46386328", "0.46243596", "0.4624117", "0.4620314", "0.46078", "0.4597525", "0.4586692", "0.4574916", "0.4574754", "0.45608318", "0.45459482", "0.45451048", "0.4542928", "0.453838", "0.45342073", "0.45221245", "0.4517767", "0.45043445", "0.4494434", "0.44656566", "0.44544786", "0.445294", "0.4446086", "0.4446039", "0.4423505" ]
0.6311176
2
Add a dependency tracker to the provided 'bundler'
function addDependencyTracker(baseDir, bundler, filter) { var res = { bundler: bundler, allDeps: {} }; bundler.on("dep", function (evt) { if (filter != null && !filter(evt)) { return; } // relativize file absolute path to project directory var file = path.relative(baseDir, evt.file); // remove file extension file = file.substr(0, file.length - path.extname(file).length); // relative directory var fileDir = path.dirname(file); // resolve dependencies based on file directory relative to project directory var deps = Object.keys(evt.deps).map(function (d) { return path.join(fileDir, d); }); // save the dependencies res.allDeps[file] = deps; }); return res; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "addDependsOn(serviceName) {\n this.dependsOn.push(serviceName);\n }", "registerDependency(dependency) {\n this.allDependencies.push(dependency)\n }", "addBundledDeps(...deps) {\n if (deps.length && !this.allowLibraryDependencies) {\n throw new Error(`cannot add bundled dependencies to an APP project: ${deps.join(',')}`);\n }\n for (const dep of deps) {\n this.project.deps.addDependency(dep, deps_1.DependencyType.BUNDLED);\n }\n }", "addDep (dep) {\n if (!shouldTrack) return\n const id = dep.id\n if (!this.newDepIds.has(id)) {\n this.newDepIds.add(id)\n this.newDeps.push(dep)\n if (!this.depIds.has(id)) {\n dep.addSub(this)\n }\n }\n }", "function addRunDependency(id){runDependencies++;if(Module['monitorRunDependencies']){Module['monitorRunDependencies'](runDependencies);}}", "addDependency(spec) {\n return this.depsManager.addDependency(spec);\n }", "function addRunDependency(id) {\n runDependencies++;\n if (Module['monitorRunDependencies']) {\n Module['monitorRunDependencies'](runDependencies);\n }\n}", "function addRunDependency(id) {\n runDependencies++;\n if (Module['monitorRunDependencies']) {\n Module['monitorRunDependencies'](runDependencies);\n }\n}", "function addRunDependency(id) {\n runDependencies++;\n if (Module['monitorRunDependencies']) {\n Module['monitorRunDependencies'](runDependencies);\n }\n}", "function addRunDependency(id) {\n runDependencies++;\n if (Module['monitorRunDependencies']) {\n Module['monitorRunDependencies'](runDependencies);\n }\n}", "function addRunDependency(id) {\n runDependencies++;\n if (Module['monitorRunDependencies']) {\n Module['monitorRunDependencies'](runDependencies);\n }\n}", "function addRunDependency(id) {\n runDependencies++;\n if (Module['monitorRunDependencies']) {\n Module['monitorRunDependencies'](runDependencies);\n }\n}", "function addRunDependency(id) {\n runDependencies++;\n if (Module['monitorRunDependencies']) {\n Module['monitorRunDependencies'](runDependencies);\n }\n}", "function addRunDependency(id) {\n runDependencies++;\n if (Module['monitorRunDependencies']) {\n Module['monitorRunDependencies'](runDependencies);\n }\n}", "function addRunDependency(id) {\n runDependencies++;\n if (Module['monitorRunDependencies']) {\n Module['monitorRunDependencies'](runDependencies);\n }\n}", "function addRunDependency(id) {\n runDependencies++;\n if (Module['monitorRunDependencies']) {\n Module['monitorRunDependencies'](runDependencies);\n }\n}", "function addRunDependency(id) {\n runDependencies++;\n if (Module['monitorRunDependencies']) {\n Module['monitorRunDependencies'](runDependencies);\n }\n}", "function addRunDependency(id) {\n runDependencies++;\n if (Module['monitorRunDependencies']) {\n Module['monitorRunDependencies'](runDependencies);\n }\n}", "function addRunDependency(id) {\n runDependencies++;\n if (Module['monitorRunDependencies']) {\n Module['monitorRunDependencies'](runDependencies);\n }\n}", "function addRunDependency(id) {\n runDependencies++;\n if (Module['monitorRunDependencies']) {\n Module['monitorRunDependencies'](runDependencies);\n }\n}", "function addRunDependency(id) {\n runDependencies++;\n if (Module['monitorRunDependencies']) {\n Module['monitorRunDependencies'](runDependencies);\n }\n}", "function addRunDependency(id) {\n runDependencies++;\n if (Module['monitorRunDependencies']) {\n Module['monitorRunDependencies'](runDependencies);\n }\n}", "function addRunDependency(id) {\n runDependencies++;\n if (Module['monitorRunDependencies']) {\n Module['monitorRunDependencies'](runDependencies);\n }\n}", "function addRunDependency(id) {\n runDependencies++;\n if (Module['monitorRunDependencies']) {\n Module['monitorRunDependencies'](runDependencies);\n }\n}", "function addRunDependency(id) {\n runDependencies++;\n if (Module['monitorRunDependencies']) {\n Module['monitorRunDependencies'](runDependencies);\n }\n}", "function addRunDependency(id) {\n runDependencies++;\n if (Module['monitorRunDependencies']) {\n Module['monitorRunDependencies'](runDependencies);\n }\n}", "_addDependentsToPackage (packageNode, depObj, type) {\n Object.keys(depObj).forEach(dependencyName => {\n if (this.packageStore.hasOwnProperty(dependencyName)) {\n // packageNode has a dependency of dependencyName - therefore dependencyName is dependent on packageNode\n const dependentPackageNode = this.packageStore[dependencyName];\n const version = depObj[dependencyName];\n dependentPackageNode.addDependent(packageNode.name, new DependentLinkNode({\n type, version, packageNode\n }));\n }\n });\n }", "function addRunDependency(id) {\n runDependencies++;\n if (Module['monitorRunDependencies']) {\n Module['monitorRunDependencies'](runDependencies);\n }\n if (id) {\n assert(!runDependencyTracking[id]);\n runDependencyTracking[id] = 1;\n } else {\n Module.printErr('warning: run dependency added without ID');\n }\n}", "function recordDependencyList(uri, module) {\r\n if (!dependencyList[uri]) {\r\n dependencyList[uri] = [module]\r\n } else if (indexOf(dependencyList[uri], module) < 0) {\r\n dependencyList[uri].push(module)\r\n }\r\n}", "reportPackageWithExistingVersion(req, info) {\n this.delayedResolveQueue.push({ req: req, info: info });\n }", "addDevDependency(spec) {\n return this.depsManager.addDevDependency(spec);\n }", "function Bundler () {\n}", "function addRunDependency(id) {\n runDependencies++;\n if (Module['monitorRunDependencies']) {\n Module['monitorRunDependencies'](runDependencies);\n }\n }", "function addRubyGem(name, version) {\n rubyGems[name] = version;\n}", "function addStrongDependencies(dependency) {\n\t\t\tif (hasOwnProp.call(stronglyDependsOn[id], dependency.id)) return;\n\n\t\t\tstronglyDependsOn[id][dependency.id] = true;\n\t\t\tstrongDeps[dependency.id].forEach(addStrongDependencies);\n\t\t}", "function addRunDependency(id) {\n runDependencies++;\n if (Module['monitorRunDependencies']) {\n Module['monitorRunDependencies'](runDependencies);\n }\n if (id) {\n assert(!runDependencyTracking[id]);\n runDependencyTracking[id] = 1;\n if (runDependencyWatcher === null && typeof setInterval !== 'undefined') {\n // Check for missing dependencies every few seconds\n runDependencyWatcher = setInterval(function() {\n var shown = false;\n for (var dep in runDependencyTracking) {\n if (!shown) {\n shown = true;\n Module.printErr('still waiting on run dependencies:');\n }\n Module.printErr('dependency: ' + dep);\n }\n if (shown) {\n Module.printErr('(end of list)');\n }\n }, 10000);\n }\n } else {\n Module.printErr('warning: run dependency added without ID');\n }\n}", "dependencyLoaded (pkg) {\n this.loadedDepsProgress.tick({locationxxxxxxxxxxxxxxxxxx: pkg.location().substr(0, 'locationxxxxxxxxxxxxxxxxxx'.length)})\n }", "function markDependentTags(tagName) {\n var tag = tags[tagName];\n if (!tag) { return; }\n dependentTags[tagName] = true; \n if (!tag.requires) { return; }\n for (var i = 0; i < tag.requires.length; i += 1) {\n var requiredTagName = tag.requires[i];\n // only load if not already loaded\n if (!dependentTags[requiredTagName]) { \n markDependentTags(requiredTagName);\n }\n }\n }", "addDep (dep) {\n var id = dep.id;\n if (!this.newDepIds.has(id)) {\n this.newDepIds.add(id);\n this.newDeps.push(dep);\n if (!this.depIds.has(id)) {\n dep.addSub(this);\n }\n }\n }", "function inc(importance) {\n return gulp.src(['./package.json', './bower.json'])\n .pipe(gp_bump({type: importance}))\n .pipe(gulp.dest('./'))\n .pipe(gp_git.commit('Creating new package version'))\n .pipe(gp_filter('package.json'))\n .pipe(gp_tagversion());\n}", "install() {\n this.installDependencies();\n }", "function add_dependents_to_page(dist) {\n for ( var module in infoblocks_by_module ) {\n if ( infoblocks_by_module[module] && dists_by_module[module] == dist ) {\n infoblocks_by_module[module].innerHTML += \"(<a href=\\\"http://deps.cpantesters.org/depended-on-by.pl?dist=\" + dists_by_module[module] + \"\\\">CPAN dependents</a>: \" + dependent_counts[dist] + \")\";\n }\n }\n}", "addDep(dep) {\n const id = dep.id\n if (!this.newDepIds.has(id)) {\n this.newDepIds.add(id)\n this.newDeps.push(dep)\n if (!this.depIds.has(id)) {\n dep.addSub(this)\n }\n }\n }", "function inc(importance) {\n gulp.src(['./package.json', './bower.json'])\n // bump the version number in those files\n .pipe(plugins.bump({type: importance}))\n // save it back to filesystem\n .pipe(gulp.dest('./'))\n // commit the changed version number\n .pipe(plugins.git.add())\n .pipe(plugins.git.commit('update version'))\n\n // read only one file to get the version number\n .pipe(plugins.filter('package.json'))\n // **tag it in the repository**\n .pipe(plugins.tagVersion());\n }", "afterInstall () {\n return this.addBowerPackageToProject ('justgage', 'https://github.com/toorshia/justgage.git#1.2.9');\n }", "addDevDeps(...deps) {\n for (const dep of deps) {\n this.project.deps.addDependency(dep, deps_1.DependencyType.BUILD);\n }\n }", "function addDepsToPackageJson(deps, devDeps, addInstall = true) {\n return (host, context) => {\n const currentPackageJson = readJsonInTree(host, 'package.json');\n if (requiresAddingOfPackages(currentPackageJson, deps, devDeps)) {\n return schematics_1.chain([\n updateJsonInTree('package.json', (json, context) => {\n json.dependencies = Object.assign(Object.assign(Object.assign({}, (json.dependencies || {})), deps), (json.dependencies || {}));\n json.devDependencies = Object.assign(Object.assign(Object.assign({}, (json.devDependencies || {})), devDeps), (json.devDependencies || {}));\n json.dependencies = sortObjectByKeys(json.dependencies);\n json.devDependencies = sortObjectByKeys(json.devDependencies);\n return json;\n }),\n add_install_task_1.addInstallTask({\n skipInstall: !addInstall,\n }),\n ]);\n }\n else {\n return schematics_1.noop();\n }\n };\n}", "function _addPackage( pname, bowerJson, options, firstLevel, dotBowerJson ){\n\t\toptions.list.push({\n\t\t\tname\t\t: bowerJson.name\t\t\t|| dotBowerJson.name\t\t\t|| pname,\n\t\t\thomepage: bowerJson.homepage\t|| dotBowerJson.homepage\t|| '',\n\t\t\tversion\t: bowerJson.version\t\t|| dotBowerJson.version\t\t|| ''\n\t\t});\n\t}", "depend () {\n var i = this.deps.length;\n while (i--) {\n this.deps[i].depend();\n }\n }", "_depend(changers, _allow_unordered) {\n if (Tracker.active) {\n const dependency = new Tracker.Dependency;\n const notify = dependency.changed.bind(dependency);\n\n dependency.depend();\n\n const options = {_allow_unordered, _suppress_initial: true};\n\n ['added', 'addedBefore', 'changed', 'movedBefore', 'removed']\n .forEach(fn => {\n if (changers[fn]) {\n options[fn] = notify;\n }\n });\n\n // observeChanges will stop() when this computation is invalidated\n this.observeChanges(options);\n }\n }", "function addDepFn() {\n addDep();\n}", "_trackUnresolvedFileImport(specifier, originFilePath) {\n if (!this.unresolvedFiles.has(originFilePath)) {\n this.unresolvedFiles.set(originFilePath, [specifier]);\n }\n this.unresolvedFiles.get(originFilePath).push(specifier);\n }", "addToGlobalDependencyGraph() {\n for (let entry of this.map) {\n let paginationTagTarget = this.getPaginationTagTarget(entry);\n if (paginationTagTarget) {\n this.config.uses.addDependencyConsumesCollection(entry.inputPath, paginationTagTarget);\n }\n\n if (!entry.data.eleventyExcludeFromCollections) {\n this.config.uses.addDependencyPublishesToCollection(entry.inputPath, \"all\");\n\n if (Array.isArray(entry.data.tags)) {\n for (let tag of entry.data.tags) {\n this.config.uses.addDependencyPublishesToCollection(entry.inputPath, tag);\n }\n }\n }\n\n if (Array.isArray(entry.data.eleventyImport?.collections)) {\n for (let tag of entry.data.eleventyImport.collections) {\n this.config.uses.addDependencyConsumesCollection(entry.inputPath, tag);\n }\n }\n }\n }", "depend() {\n let i = this.deps.length\n while (i--) {\n this.deps[i].depend()\n }\n }", "depend () {\n let i = this.deps.length\n while (i--) {\n this.deps[i].depend()\n }\n }", "addDeps(...deps) {\n for (const dep of deps) {\n this.project.deps.addDependency(dep, deps_1.DependencyType.RUNTIME);\n }\n }", "function addDependencyToTask(input, li) {\n var id = jQuery(li).find(\".complete_value\").text();\n jQuery(input).val(\"\");\n\n jQuery.get(\"/tasks/dependency/\", { dependency_id : id }, function(data) {\n\tjQuery(\"#task_dependencies .dependencies\").append(data);\n });\n}", "depend () {\n let i = this.deps.length\n while (i--) {\n this.deps[i].depend()\n }\n }", "function add_deps(curr_deps) {\n for ( key in curr_deps ) {\n if (!(key in overall_deps)) {\n overall_deps[key] = [];\n }\n for (var q = 0; q < curr_deps[key].length; q++ ) {\n if ( !(curr_deps[key][q] in overall_deps[key] ) ) {\n overall_deps[key].push(curr_deps[key][q]);\n }\n }\n }\n}", "function addDependencies(generator) {\n const vavrVersion = '0.10.3';\n if (generator.buildTool === 'maven') {\n generator.addMavenProperty('vavr.version', vavrVersion);\n generator.addMavenDependency('io.vavr', 'vavr', '${vavr.version}'); // eslint-disable-line no-template-curly-in-string\n } else if (generator.buildTool === 'gradle') {\n generator.addGradleProperty('vavr_version', vavrVersion);\n generator.addGradleDependency('implementation', 'io.vavr', 'vavr', '${vavr_version}'); // eslint-disable-line no-template-curly-in-string\n }\n }", "function packages () {\n opts.packages = makeArray(argv.dep)\n opts.install = true\n }", "function BundleResolver(extensionResolver, requireConfigurator, $log) {\n this.extensionResolver = extensionResolver;\n this.requireConfigurator = requireConfigurator;\n this.$log = $log;\n }", "collectDependencies() {}", "function addDependencyToTask(input, li) {\n var id = jQuery(li).find(\".complete_value\").text();\n jQuery(input).val(\"\");\n\n jQuery.get(\"/tasks/dependency/\", { dependency_id : id }, function(data) {\n jQuery(\"#task_dependencies .dependencies\").append(data);\n });\n}", "bundle(user, flow, version){\n console.log(user)\n version = '0.0.1'\n return new Promise((resolve, reject) => {\n console.log(\"Bundling Flow: \", flow)\n let modulesUsed = this.find_modules(flow);\n let connectionsUsed = this.find_connections(flow)\n\n let packageFiles = modulesUsed.map((x) => {\n return `${x.fs_path}/package.json`\n })\n\n let moduleFileBundles = modulesUsed.map((x) => {\n return this.get_module_files(x)\n })\n\n let mergedPackageFile = JSON.stringify(this.merge_packfiles(flow, packageFiles, version)) \n \n \n \n let libraries = {}\n\n let publishedModules = moduleFileBundles.map((x, ix) => {\n let published_mod = this.libify(modulesUsed, x, ix)\n libraries = {...libraries, ...published_mod.files}\n return published_mod\n })\n console.log(\"Libraries\", publishedModules)\n \n this.registry.newRepo(flow).then(() => {\n \n this.write_main(flow, modulesUsed, connectionsUsed, publishedModules).then((indexFile) => {\n this.getPackage(user.user, flow, indexFile, mergedPackageFile, libraries, (sha) => {\n resolve({name: mergedPackageFile.name, version: sha})\n })\n \n })\n\n })\n }) \n }", "registerDependency(component, isMust) {\n }", "workspaceXdependencies(params = {}, span = new opentracing_1.Span()) {\n // Ensure package.json files\n return this.projectManager.ensureModuleStructure()\n .concat(rxjs_1.Observable.defer(() => util_1.observableFromIterable(this.inMemoryFileSystem.uris())))\n .filter(uri => uri.includes('/package.json') && !uri.includes('/node_modules/'))\n .mergeMap(uri => this.packageManager.getPackageJson(uri))\n .mergeMap(packageJson => rxjs_1.Observable.from(packages_1.DEPENDENCY_KEYS)\n .filter(key => !!packageJson[key])\n .mergeMap(key => lodash_2.toPairs(packageJson[key]))\n .map(([name, version]) => ({\n attributes: {\n name,\n version,\n },\n hints: {\n dependeePackageName: packageJson.name,\n },\n })))\n .map((dependency) => ({ op: 'add', path: '/-', value: dependency }))\n .startWith({ op: 'add', path: '', value: [] });\n }", "function install(obj) {\n obj.Buffer = Buffer;\n obj.process = process;\n var oldRequire = obj.require ? obj.require : null;\n // Monkey-patch require for Node-style code.\n obj.require = function (arg) {\n var rv = BFSRequire(arg);\n if (!rv) {\n return oldRequire.apply(null, Array.prototype.slice.call(arguments, 0));\n }\n else {\n return rv;\n }\n };\n}", "trackDependency(telemetry) {\n this.defaultClient.trackDependency(telemetry);\n }", "addStackDependency(stackDeployment) {\n try {\n jsiiDeprecationWarnings.aws_cdk_lib_pipelines_StackDeployment(stackDeployment);\n }\n catch (error) {\n if (process.env.JSII_DEBUG !== \"1\" && error.name === \"DeprecationError\") {\n Error.captureStackTrace(error, this.addStackDependency);\n }\n throw error;\n }\n this.stackDependencies.push(stackDeployment);\n }", "function patchResDeps() {\n [\"rescript\"].concat(bsconfig[\"bs-dependencies\"]).forEach((bsDep) => {\n fs.writeFileSync(`./node_modules/${bsDep}/index.js`, \"\");\n const json = require(`./node_modules/${bsDep}/package.json`);\n json.main = \"index.js\";\n fs.writeFileSync(\n `./node_modules/${bsDep}/package.json`,\n JSON.stringify(json, null, 2)\n );\n });\n}", "function updateVersion2gitTag(pkg) {\n\tlet tag = child_process.execSync('git describe --tag').toString().trim();\n\tpkg.version = tag;\n}", "getClassName(){return \"BayrellBundler.Bundler\";}", "function addDependency(source, target, reason) {\n operateOnDependency(DependencyOperation.ADD, source, target, reason);\n}", "function tagBump(cb) {\n var version = packageJson().version;\n git.checkout('master', function(error) {\n if (error) {\n return cb(error);\n }\n git.tag(version, 'Tag version ' + version, function(error) {\n if (error) {\n return cb(error);\n }\n git.push('origin', 'master', {\n args: '--tags'\n }, cb);\n });\n });\n}", "addDependency(from, to, weight) {\n this.nodes[from].dependencies[to] = { from, to, weight };\n }", "function addDependencyScriptElements(basePath, vendorPaths, reject) {\n\t\tvendorPaths.array.forEach(function (scriptPath) {\n\t\t\taddScriptElement(basePath, scriptPath, reject);\n\t\t});\n\t}", "function addHotjar(h, o, t, j, a, r) {\n\t\th.hj = h.hj || function() {\n\t\t\t(h.hj.q = h.hj.q || []).push(arguments);\n\t\t};\n\n\t\th._hjSettings = {\n\t\t\thjid: 61980,\n\t\t\thjsv: 5\n\t\t};\n\n\t\ta = o.getElementsByTagName('head')[0];\n\t\tr = o.createElement('script');\n\t\tr.async = 1;\n\t\tr.src = t + h._hjSettings.hjid + j + h._hjSettings.hjsv;\n\t\ta.appendChild(r);\n\t}", "function mapDependency (resourceName, srcPath) {\n var cmap = this._.CHANGEMAP[srcPath] || {};\n cmap[resourceName] = 1;\n this._.CHANGEMAP[srcPath] = cmap;\n return this;\n}", "function $SetDependencies(module, deps) {\n GetModuleInternalData(module).dependencies = deps;\n}", "npmDependencies(fpath, cb) {\n try {\n let unit = bna._parseFile(null, fpath, bna._cache);\n const warnings = _((() => {\n const result = [];\n for (unit of Array.from(bna._flattenRequires(unit))) {\n result.push(unit.warnings);\n }\n return result;\n })()).flatten();\n unit = bna._collapsePackages(unit);\n //log(JSON.stringify(unit,null, \" \"));\n let dependencies = null;\n let externDeps = null;\n\n dependencies = _(unit.requires).reduce(function(memo, unit) {\n if (unit.package) {\n memo[unit.mname] = unit.package.version;\n } else {\n if (unit.isCore) {\n memo[unit.fpath] = null; // required an individual file that's not a main file of a npm package\n } else {\n memo[unit.fpath] = null;\n }\n memo;\n }\n return memo;\n },\n\n {});\n\n externDeps = bna.externDeps(unit);\n //console.log(fpath, \", \", dependencies);\n return cb(null, dependencies, externDeps, unit, warnings);\n } catch (e) {\n return cb(e);\n }\n }", "function register(dependency) {\n var depInfo = getScriptInfo(dependency);\n lazyset(depInfo, \"_parents\", scriptInfo.name, scriptInfo);\n }", "function framework(emitter, config, logger) {\n\n log = logger.create('framework.browserify');\n\n if (!bundleFile) {\n bundleFile = new BundleFile();\n }\n\n bundleFile.touch();\n log.debug('created browserify bundle: %s', bundleFile.location);\n\n b = createBundle(config);\n\n // TODO(Nikku): hook into karma karmas file update facilities\n // to remove files from the bundle once karma detects the deletion\n\n // hook into exit for cleanup\n emitter.on('exit', function(done) {\n log.debug('cleaning up');\n\n b.close();\n bundleFile.remove();\n done();\n });\n\n\n // add bundle file to the list of files defined in the\n // configuration. be smart by doing so.\n addBundleFile(bundleFile, config);\n }", "install() {\n let logMsg = `To install your dependencies manually, run: ${chalk.yellow.bold(`${this.clientPackageManager} install`)}`;\n\n if (this.clientFramework === 'angular1') {\n logMsg = `To install your dependencies manually, run: ${chalk.yellow.bold(`${this.clientPackageManager} install & bower install`)}`;\n }\n\n const injectDependenciesAndConstants = (err) => {\n if (err) {\n this.log('Install of dependencies failed!');\n this.log(logMsg);\n } else if (this.clientFramework === 'angular1') {\n this.spawnCommand('gulp', ['install']);\n }\n };\n\n const installConfig = {\n bower: this.clientFramework === 'angular1',\n npm: this.clientPackageManager !== 'yarn',\n yarn: this.clientPackageManager === 'yarn',\n callback: injectDependenciesAndConstants\n };\n\n this.installDependencies(installConfig);\n }", "function patchBump() {\n return gulp.src([\n './package.json',\n './bower.json'\n ]).pipe(bump({type: 'patch'}))\n .pipe(gulp.dest('./'));\n}", "registerPackageActivator(activator, types) {\n this.packageActivators.push([activator, types]);\n }", "constructor(hooks = []) {\n this.configureDistributor();\n this.hooks = hooks;\n }", "_updatePackage() {\n let dest = this.destinationPath('package.json');\n let template = this.templatePath('dependencies.stub');\n let pkg = program.helpers.readJson(this, dest);\n\n let deps = JSON.parse(program.helpers.readTpl(this, template, {\n relationalDB: program.helpers.isRelationalDB(this.answers.database),\n answers: this.answers\n }));\n\n pkg.dependencies = Object.assign(pkg.dependencies, deps);\n this.fs.writeJSON(dest, pkg);\n }", "function addToPackage(history) {\n console.log(\"addToPackage\")\n packaged[SOURCE][history.id] =\n new EdisonTelemetrySeries(history.value);\n }", "_getPackageDescriptor(uri, childOf = new opentracing_1.Span()) {\n return tracing_1.traceObservable('Get PackageDescriptor', childOf, span => {\n span.addTags({ uri });\n // Get package name of the dependency in which the symbol is defined in, if any\n const packageName = packages_1.extractNodeModulesPackageName(uri);\n if (packageName) {\n // The symbol is part of a dependency in node_modules\n // Build URI to package.json of the Dependency\n const encodedPackageName = packageName.split('/').map(encodeURIComponent).join('/');\n const parts = url.parse(uri);\n const packageJsonUri = url.format(Object.assign({}, parts, { pathname: parts.pathname.slice(0, parts.pathname.lastIndexOf('/node_modules/' + encodedPackageName)) + `/node_modules/${encodedPackageName}/package.json` }));\n // Fetch the package.json of the dependency\n return this.updater.ensure(packageJsonUri, span)\n .concat(rxjs_1.Observable.defer(() => {\n const packageJson = JSON.parse(this.inMemoryFileSystem.getContent(packageJsonUri));\n const { name, version } = packageJson;\n if (!name) {\n return rxjs_1.Observable.empty();\n }\n // Used by the LSP proxy to shortcut database lookup of repo URL for PackageDescriptor\n let repoURL;\n if (name.startsWith('@types/')) {\n // if the dependency package is an @types/ package, point the repo to DefinitelyTyped\n repoURL = 'https://github.com/DefinitelyTyped/DefinitelyTyped';\n }\n else {\n // else use repository field from package.json\n repoURL = typeof packageJson.repository === 'object' ? packageJson.repository.url : undefined;\n }\n return rxjs_1.Observable.of({ name, version, repoURL });\n }));\n }\n else {\n // The symbol is defined in the root package of the workspace, not in a dependency\n // Get root package.json\n return this.packageManager.getClosestPackageJson(uri, span)\n .mergeMap(packageJson => {\n let { name, version } = packageJson;\n if (!name) {\n return [];\n }\n let repoURL = typeof packageJson.repository === 'object' ? packageJson.repository.url : undefined;\n // If the root package is DefinitelyTyped, find out the proper @types package name for each typing\n if (name === 'definitely-typed') {\n name = packages_1.extractDefinitelyTypedPackageName(uri);\n if (!name) {\n this.logger.error(`Could not extract package name from DefinitelyTyped URI ${uri}`);\n return [];\n }\n version = undefined;\n repoURL = 'https://github.com/DefinitelyTyped/DefinitelyTyped';\n }\n return [{ name, version, repoURL }];\n });\n }\n });\n }", "function addDependencies(app) {\n let dependents = `const expect = require('chai').expect;${newLine}`;\n dependents += `import React from 'react';${newLine}`;\n dependents += `import { mount } from 'enzyme';${newLine}`;\n dependents += `import 'jsdom-global/register';${newLine}`;\n dependents += `import ${app} from 'fill this in with proper path';${newLine}`;\n return dependents; \n}", "function bundleInstall(localPath, cb) {\n util.log(\"Installing dependencies\");\n exec('bundle install', { cwd: localPath, env: process.env }, cb);\n}", "function addPolyfillsToEntry(entry) {\n if ((0, _utils.typeOf)(entry) === 'array') {\n entry.unshift(require.resolve('../polyfills'));\n } else {\n // Assumption: there will only be one entry point, naming the entry chunk\n entry[Object.keys(entry)[0]].unshift(require.resolve('../polyfills'));\n }\n}", "function updateOwnDeps () {\n tools.updateOwnDependenciesFromLocalRepositories(args.depth);\n}", "function install(scope, installer){\n installer(scope);\n }", "function attachReviver(reviver) {\n jsonRevivers.push(reviver);\n }", "function attachReviver(reviver) {\n jsonRevivers.push(reviver);\n }", "function module_init(dist, deps){\n dist.status = 0;\n dist.dependencies = deps || [];\n dist.deps = {};\n dist._entry = [];\n return dist;\n}", "addDependency(key, dependencyKey) {\n let existingNode = this.nodes[key];\n if (existingNode) {\n let dependencies = existingNode.dependencies.includes(dependencyKey) ? existingNode.dependencies : [dependencyKey, ...existingNode.dependencies];\n this.addOrReplace(key, dependencies);\n }\n else {\n this.addOrReplace(key, [dependencyKey]);\n }\n }", "function add(name, plugin) {\n\t\tvar a = registry[name];\n\n\t\tif (a == null) {\n\t\t\ta = registry[name] = [];\n\t\t}\n\n\t\tplugin = aperture.util.viewOf(plugin);\n\n\t\t// clear this in case there is a problem loading it\n\t\tvar m = plugin.module;\n\t\tplugin.module = null;\n\n\t\t// register the plugin.\n\t\ta.push(plugin);\n\n\t\t// load required modules\n\t\tif (u.isString(m)) {\n\t\t\trequire(['../../' + m], function(module) {\n\t\t\t\tplugin.module = module;\n\t\t\t});\n\t\t}\n\t}" ]
[ "0.6029545", "0.6025915", "0.5773088", "0.56944126", "0.5647646", "0.55890507", "0.54927444", "0.54927444", "0.54770714", "0.54770714", "0.54770714", "0.54770714", "0.54770714", "0.54770714", "0.54770714", "0.54770714", "0.54770714", "0.54770714", "0.54770714", "0.54770714", "0.54770714", "0.54770714", "0.54770714", "0.54770714", "0.54770714", "0.54770714", "0.54645884", "0.5453433", "0.5443299", "0.54324704", "0.538255", "0.5380781", "0.53615487", "0.5357885", "0.5286966", "0.5286423", "0.52343947", "0.51778215", "0.5138276", "0.51311404", "0.51183224", "0.5095152", "0.50861853", "0.5074677", "0.4999204", "0.49336427", "0.49296895", "0.48841196", "0.48821938", "0.48693943", "0.48376352", "0.4835176", "0.48227084", "0.4816076", "0.48117355", "0.4772545", "0.4764453", "0.47643226", "0.47515976", "0.47461417", "0.4726642", "0.47250065", "0.47138476", "0.4697989", "0.46898687", "0.468852", "0.46786734", "0.4676947", "0.4672777", "0.46558774", "0.46399125", "0.4637892", "0.46317258", "0.46196112", "0.4602115", "0.4593573", "0.45929793", "0.4586081", "0.45664558", "0.45528063", "0.45202544", "0.45182315", "0.45166197", "0.45013824", "0.44997856", "0.44820932", "0.44758406", "0.44573212", "0.4451891", "0.44501507", "0.44419822", "0.44392857", "0.44361097", "0.44338167", "0.44250888", "0.44196677", "0.44196677", "0.44174513", "0.4408595", "0.44059995" ]
0.6626021
0
Check for circular dependencies in the 'allDeps' map
function detectCircularDependencies(entryFile, allDeps) { var paths = [entryFile]; var entryDeps = allDeps[entryFile]; if (entryDeps != null) { if (walkDeps(allDeps[entryFile], paths, allDeps)) { return paths; } } else { // helpful error for common function call mistake when using this with TsBrowserify or similar tool that mixes file paths containing extensions with require(...) paths without extensions throw new Error("No dependencies found for entry file '" + entryFile + "'"); } return []; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "checkNodesForCircularDependencies(graph) {\n // for each node in the dependency graph, check for circular dependencies\n for (let nodeName in this.graph.nodes) {\n let dependencyPathTaken = []; // record of path when looking for cicular dependency; reset each time\n logger_1.default.system.debug(`BootDependencyGraph.checkNodesForCircularDependencies -- nodeName=${nodeName}`);\n let isCircular = this.testOneNodeForCircularPath(dependencyPathTaken, nodeName);\n if (isCircular) {\n this.errorDiag = new DGDiagnostics(`${this.context} circular dependency`, dependencyPathTaken);\n this.graphState = \"error\";\n throw this.errorDiag.description;\n }\n }\n }", "function detectCycles (rows) {\n var cyclicalModules = new Set()\n var checked = new Set()\n rows.forEach(function (module) {\n var visited = []\n\n check(module)\n\n function check (row) {\n var i = visited.indexOf(row)\n if (i !== -1) {\n checked.add(row)\n for (; i < visited.length; i++) {\n cyclicalModules.add(visited[i])\n }\n return\n }\n if (checked.has(row)) return\n visited.push(row)\n Object.keys(row.deps).forEach(function (k) {\n var dep = row.deps[k]\n var other = rows.byId[dep]\n if (other) check(other, visited)\n })\n visited.pop()\n }\n })\n\n // mark cyclical dependencies\n for (var i = 0; i < rows.length; i++) {\n rows[i][kEvaluateOnDemand] = cyclicalModules.has(rows[i])\n }\n return cyclicalModules.size > 0\n}", "checkDependencies() {\n for (let id in this.dependencies) {\n let dependency = this.dependencies[id];\n let { dependencies, callback } = dependency;\n if (dependencies.clients.length && !this.clientsAreAllOnline[id]) {\n this.clientsAreAllOnline[id] = this.checkClients(dependencies.clients);\n if (!this.clientsAreAllOnline[id]) {\n continue;\n }\n }\n delete this.dependencies[id];\n dependency.clearStartupTimer();\n if (callback) {\n callback();\n }\n }\n }", "detectCycles() {\n\t\t\tconst flatOrder = Array.from(this.orderedNodes);\n\n\t\t\tfor (let i = 0; i < flatOrder.length; i++) {\n\t\t\t\tconst node = flatOrder[i];\n\n\t\t\t\tfor (const imp of node.analyze.value.importFirstUsage) {\n\t\t\t\t\tconst subnode = node.getNodeFromRelativeDependency(imp.source);\n\t\t\t\t\tif (subnode === undefined) {\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\tconst resolved = subnode.resolveImport(imp.imported, imp.loc);\n\t\t\t\t\tif (resolved.type !== \"FOUND\") {\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\t// Hoisted exports will always be accessible\n\t\t\t\t\tif (resolved.record.valueType === \"function\") {\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\tconst dep = resolved.node;\n\n\t\t\t\t\tconst isBefore = flatOrder.indexOf(dep) > i;\n\t\t\t\t\tif (isBefore) {\n\t\t\t\t\t\tthis.flagCycle(node, dep, imp);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}", "checkDependencies() {\n console.debug(\"checkDependencies\", this.dependencies);\n if (Object.keys(this.dependencies)) {\n for (let id in this.dependencies) {\n let { dependencies, callback } = this.dependencies[id];\n console.debug(\"checkDependency\", dependencies.services, this.offlineServices);\n if (dependencies.services.length) {\n let servicesAreAllOffline = this.checkServices(dependencies.services);\n if (!servicesAreAllOffline) {\n continue;\n }\n }\n console.debug(\"checkDependencies callback\");\n delete this.dependencies[id];\n if (callback) {\n callback();\n }\n }\n }\n }", "function detectCycles (rows) {\n var cyclicalModules = new Set()\n var checked = new Set()\n rows.forEach(function (module) {\n var visited = []\n\n check(module)\n\n function check (row) {\n var i = visited.indexOf(row)\n if (i !== -1) {\n checked.add(row)\n for (; i < visited.length; i++) {\n cyclicalModules.add(visited[i])\n }\n return\n }\n if (checked.has(row)) return\n visited.push(row)\n Object.keys(row.deps).forEach(function (k) {\n var dep = row.deps[k]\n var other = rows.byId[dep]\n if (other) check(other, visited)\n })\n visited.pop()\n }\n })\n\n // mark cyclical dependencies\n for (var i = 0; i < rows.length; i++) {\n rows[i].isCycle = cyclicalModules.has(rows[i])\n }\n return cyclicalModules.size > 0\n}", "function circularReferenceCheck(shadows) {\n // if any of the current objects to process exist in the queue\n // then throw an error.\n shadows.forEach(function (item) {\n if (item instanceof Object && visited.indexOf(item) > -1) {\n throw new Error('Circular reference error');\n }\n });\n // if none of the current objects were in the queue\n // then add references to the queue.\n visited = visited.concat(shadows);\n }", "function cycleCheck(node, path) {\n if (!node) {\n return;\n }\n const children = [...node.loadDependencyNames, ...node.lazyDependencyNames];\n for (const child of children) {\n if (path.indexOf(child) !== -1) {\n throw new Error(`Cyclic dependency detected! Module ${node.name} has a dependency ${child} that is also a parent!`);\n }\n cycleCheck(moduleDefinitions[child], [...path, child]);\n }\n }", "_checkDependencies(entity) {\n let missingDependencies = [];\n\n this.dependencies.forEach((dependency) => {\n let isMissing = true;\n\n for(let i=0; i < Object.keys(entity.components).length; i++) {\n if(Object.keys(entity.components)[i] == dependency) {\n isMissing = false;\n }\n }\n\n if(isMissing) missingDependencies.push(dependency);\n });\n\n if(missingDependencies.length > 0) {\n throw new Error(`${this.id} requires ${missingDependencies.length} other component dependencies. Make sure ${this.id} is added after it's dependencies.`);\n }\n }", "hoistDeps(duplicateDepsToCheck) {\n const dependentInfo = this.collectDependencyInfo(this.srcDeps);\n const peerDependentInfo = this.collectDependencyInfo(this.peerDeps, true);\n // In case peer dependency duplicates to existing transitive dependency, set \"missing\" to `false`\n for (const [peerDep, peerInfo] of peerDependentInfo.entries()) {\n if (!peerInfo.missing)\n continue;\n let normInfo = dependentInfo.get(peerDep);\n if (normInfo) {\n peerInfo.duplicatePeer = true;\n peerInfo.missing = false;\n peerInfo.by.unshift(normInfo.by[0]);\n }\n if (duplicateDepsToCheck) {\n normInfo = duplicateDepsToCheck.get(peerDep);\n if (normInfo) {\n peerInfo.duplicatePeer = true;\n peerInfo.missing = false;\n peerInfo.by.unshift(normInfo.by[0]);\n }\n }\n }\n // merge directDepsList (direct dependencies of workspace) into dependentInfo (transive dependencies)\n for (const [depName, item] of this.directDepsList.traverse()) {\n const info = {\n sameVer: true,\n direct: true,\n missing: false,\n duplicatePeer: false,\n by: [{ ver: item.ver, name: item.by }]\n };\n dependentInfo.set(depName, info);\n }\n return [dependentInfo, peerDependentInfo];\n }", "function ensureDeps(dep) {\n\n if (dep in depGraph) {\n // queue all required deps specified in the depGraph first\n var requiredDeps = depGraph[dep];\n for (var i = 0; i < requiredDeps.length; i++)\n ensureDeps(requiredDeps[i]);\n\n }\n\n // if it's already loaded, skip it\n if (loadedDeps.hasOwnProperty(dep) || $.inArray(dep, loadQueue) != -1)\n return;\n\n // else push it to the load queue\n loadQueue.push(dep);\n }", "function getAllDependencies(deps) {\n return promiseRequire(\n baseDependencies.concat(deps)\n );\n }", "toDependencyGraph() {\n return _.map(\n // FIND MAX UNIQUE VERSION FIRST\n _.groupBy(this.allDependencies,\"name\"), versionGroup =>\n versionGroup.reduce((maxVersion, version) =>\n !maxVersion || getValue(() =>\n SemVer.gt(SemVer.coerce(version.version),SemVer.coerce(maxVersion.version)),\n version.version <= maxVersion.version\n ) ?\n version :\n maxVersion\n , null))\n \n // SORT BY INTER-DEPENDENCY\n .sort((depA,depB) => {\n const\n depADependencies = this.collectDependencies(depA.project),\n depBDependencies = this.collectDependencies(depB.project),\n depARequiresB = depADependencies.includes(depB.name),\n depBRequiresA = depBDependencies.includes(depA.name)\n \n if (depARequiresB && depBRequiresA)\n throw `Dependency circular requirement: ${depA.name} <~> ${depB.name}`\n \n return (!depARequiresB && !depARequiresB) ? 0 : depARequiresB ? 1 : -1\n })\n \n \n }", "function checkCircular(type, found) {\n if (found[type]) {\n logger.throwArgumentError(`circular type reference to ${JSON.stringify(type)}`, \"types\", types);\n }\n found[type] = true;\n Object.keys(links[type]).forEach((child) => {\n if (!parents[child]) {\n return;\n }\n // Recursively check children\n checkCircular(child, found);\n // Mark all ancestors as having this decendant\n Object.keys(found).forEach((subtype) => {\n subtypes[subtype][child] = true;\n });\n });\n delete found[type];\n }", "function checkCircular(type, found) {\n if (found[type]) {\n logger.throwArgumentError(`circular type reference to ${JSON.stringify(type)}`, \"types\", types);\n }\n found[type] = true;\n Object.keys(links[type]).forEach((child) => {\n if (!parents[child]) {\n return;\n }\n // Recursively check children\n checkCircular(child, found);\n // Mark all ancestors as having this decendant\n Object.keys(found).forEach((subtype) => {\n subtypes[subtype][child] = true;\n });\n });\n delete found[type];\n }", "isCyclic() {\n return !this.isEnd && this.descendants.every(desc => desc == this);\n }", "function areDependenciesAvailable() {}", "function checkCircular(type, found) {\n if (found[type]) {\n logger.throwArgumentError(\"circular type reference to \" + JSON.stringify(type), \"types\", types);\n }\n found[type] = true;\n Object.keys(links[type]).forEach(function (child) {\n if (!parents[child]) {\n return;\n }\n // Recursively check children\n checkCircular(child, found);\n // Mark all ancestors as having this decendant\n Object.keys(found).forEach(function (subtype) {\n subtypes[subtype][child] = true;\n });\n });\n delete found[type];\n }", "validate() {\n const edges = [];\n\n _.forEach(this.serviceMap, (meta, serviceName) => {\n const instance = meta.instance;\n _.forEach(instance.deps, (_ignore, name) => {\n const child = this.serviceMap[name];\n if (!child)\n throw new Error(\n `The \"${serviceName}\" service has a dependency on the \"${name}\" service. But the \"${name}\" service was not registered.`,\n );\n edges.push([serviceName, name]);\n });\n _.forEach(instance.optionalDeps, (_ignore, name) => {\n const child = this.serviceMap[name];\n if (!child) return;\n edges.push([serviceName, name]);\n });\n });\n\n const ordered = toposort(edges).reverse();\n return ordered;\n }", "async function has_satisfied_deps(pkg) {\n const deps = await get_pkg_deps(pkg);\n DEBUG(\"deps for \" + pkg + \":\");\n DEBUG(deps);\n /* Discard pkg (last element) from the deps array */\n const answers = await Promise.all(deps.slice(0, -1).map(dep => is_finished(dep)));\n return answers.reduce((acc, cur) => { return acc && cur; }, true);\n}", "function shouldFindCircularRemoteDeps(assertFn) {\n return {\n topic: function () {\n var api = nock('http://api.testquill.com'),\n that = this;\n\n mock.systems.all(api);\n systemJson.dependencies({\n systems: this.context.name,\n client: composer.createClient({\n protocol: 'http',\n host: 'api.testquill.com',\n port: 80,\n auth: {}\n }).systems\n }, function (err, deps) {\n return that.callback(err, err || systemJson.remote.cycles(deps));\n });\n },\n \"should respond with the correct cycles\": assertFn\n }\n}", "[_canPlaceDep] (dep, target, edge, peerEntryEdge = null) {\n // peer deps of root deps are effectively root deps\n const isRootDep = target.isRoot && (\n // a direct dependency from the root node\n edge.from === target ||\n // a member of the peer set of a direct root dependency\n peerEntryEdge && peerEntryEdge.from === target\n )\n\n const entryEdge = peerEntryEdge || edge\n\n // has child by that name already\n if (target.children.has(dep.name)) {\n const current = target.children.get(dep.name)\n // if the integrities match, then it's literally the same exact bytes,\n // even if it came from somewhere else.\n if (dep.integrity && dep.integrity === current.integrity) {\n return KEEP\n }\n\n // we can always place the root's deps in the root nm folder\n if (isRootDep) {\n return this[_canPlacePeers](dep, target, edge, REPLACE, peerEntryEdge)\n }\n\n // if the version is greater, try to use the new one\n const curVer = current.package.version\n const newVer = dep.package.version\n // always try to replace if the version is greater\n const tryReplace = curVer && newVer && semver.gte(newVer, curVer)\n if (tryReplace && current.canReplaceWith(dep)) {\n return this[_canPlacePeers](dep, target, edge, REPLACE, peerEntryEdge)\n }\n\n // ok, see if the current one satisfies the edge we're working on then\n if (edge.satisfiedBy(current)) {\n return KEEP\n }\n\n // last try, if we prefer deduplication over novelty, check to see if\n // this (older) dep can satisfy the needs of the less nested instance\n if (this[_preferDedupe] && current.canReplaceWith(dep)) {\n return this[_canPlacePeers](dep, target, edge, REPLACE, peerEntryEdge)\n }\n\n // no agreement could be reached :(\n return CONFLICT\n }\n\n // check to see if the target DOESN'T have a child by that name,\n // but DOES have a conflicting dependency of its own. no need to check\n // if this is the edge we're already looking to resolve!\n if (target !== entryEdge.from && target.edgesOut.has(dep.name)) {\n const edge = target.edgesOut.get(dep.name)\n // It might be that the dep would not be valid here, BUT some other\n // version would. Could to try to resolve that, but that makes this no\n // longer a pure synchronous function. ugh.\n // This is a pretty unlikely scenario in a normal install, because we\n // resolve the peer dep set against the parent dependencies, and\n // presumably they all worked together SOMEWHERE to get published in the\n // first place, and since we resolve shallower deps before deeper ones,\n // this can only occur by a child having a peer dep that does not satisfy\n // the parent. It can happen if we're doing a deep update limited by\n // a specific name, however, or if a dep makes an incompatible change\n // to its peer dep in a non-semver-major version bump, or if the parent\n // is unbounded in its dependency list.\n if (!edge.satisfiedBy(dep)) {\n return CONFLICT\n }\n }\n\n // check to see what the name resolves to here, and who depends on it\n // and if they'd be ok with the new dep being there instead. we know\n // at this point that it's not the target's direct child node. this is\n // only a check we do when deduping. if it's a direct dep of the target,\n // then we just make the invalid edge and resolve it later.\n const current = target !== entryEdge.from && target.resolve(dep.name)\n if (current) {\n for (const edge of current.edgesIn.values()) {\n if (edge.from.isDescendantOf(target) && edge.valid) {\n if (!edge.satisfiedBy(dep)) {\n return CONFLICT\n }\n }\n }\n }\n\n return this[_canPlacePeers](dep, target, edge, OK, peerEntryEdge)\n }", "function checkDependencies() {\n console.log('Reading package.json'.green);\n fs.readFile('./package.json', (err, data) => {\n const pkgJson = JSON.parse(data);\n for (let dependency in pkgJson.dependencies) {\n // console.log(dependency);\n for (let package of packages) {\n if (dependency === package) {\n\n let index = packages.indexOf(package);\n console.log(index, dependency + ' already exist! '.yellow);\n packages.splice(index, 1);\n }\n }\n }\n // console.log(packages.length);\n if (packages.length == 0) {\n console.log('All dependencies are already exist skipping installation process!'.rainbow);\n updateAngularJson();\n } else {\n installDependencies();\n }\n });\n\n\n}", "function _walkDeps(depsMap, id, file, entryDepsSet, isParentOurs, lastDirectDeps, parentDepsMap) {\n\t\t\tvar deps;\n\t\t\tif (!file) { // since for external module, the `file` is always `false`\n\t\t\t\tdeps = depsMap[id];\n\t\t\t\tif (parentDepsMap && !deps) {\n\t\t\t\t\tdeps = parentDepsMap[id];\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tdeps = depsMap[file];\n\t\t\t\tdeps = deps ? deps : depsMap[id];\n\t\t\t\tif (parentDepsMap && !deps) {\n\t\t\t\t\tdeps = parentDepsMap[file] ? parentDepsMap[file] : parentDepsMap[id];\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (!deps && !{}.hasOwnProperty.call(i18nModuleNameSet, id)) {\n\t\t\t\tlog.error('Can not walk dependency tree for: ' + id +\n\t\t\t\t', missing depended module or you may try rebuild all bundles');\n\t\t\t\tlog.info(parentDepsMap[id]);\n\t\t\t\tlog.info('i18nModuleNameSet: ' + JSON.stringify(i18nModuleNameSet, null, ' '));\n\t\t\t\tgutil.beep();\n\t\t\t}\n\t\t\tif (!deps) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\t_.forOwn(deps, function(depsValue, depsKey) {\n\t\t\t\tvar isRelativePath = _.startsWith(depsKey, '.');\n\n\t\t\t\tif (!isRelativePath) {\n\t\t\t\t\t// require id is a module name\n\t\t\t\t\tvar isOurs = isParentOurs && !packageUtils.is3rdParty(depsKey);\n\t\t\t\t\tif ({}.hasOwnProperty.call(entryDepsSet, depsKey)) {\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tentryDepsSet[depsKey] = isParentOurs ? true : lastDirectDeps;\n\t\t\t\t\tif (isOurs) {\n\t\t\t\t\t\t_walkDeps(depsMap, depsKey, depsValue, entryDepsSet, true, null, parentDepsMap);\n\t\t\t\t\t} else {\n\t\t\t\t\t\t_walkDeps(depsMap, depsKey, depsValue, entryDepsSet, false, depsKey, parentDepsMap);\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\t// require id is a local file path\n\t\t\t\t\t_walkDeps(depsMap, depsKey, depsValue, entryDepsSet, isParentOurs, lastDirectDeps, parentDepsMap);\n\t\t\t\t}\n\t\t\t});\n\t\t}", "checkDependency(id) {\n if (id === this.id) return true;\n for (let i = 0; i < this.SubCircuit.length; i++) { if (this.SubCircuit[i].id === id) return true; }\n\n for (let i = 0; i < this.SubCircuit.length; i++) { if (scopeList[this.SubCircuit[i].id].checkDependency(id)) return true; }\n\n return false;\n }", "function add_deps(curr_deps) {\n for ( key in curr_deps ) {\n if (!(key in overall_deps)) {\n overall_deps[key] = [];\n }\n for (var q = 0; q < curr_deps[key].length; q++ ) {\n if ( !(curr_deps[key][q] in overall_deps[key] ) ) {\n overall_deps[key].push(curr_deps[key][q]);\n }\n }\n }\n}", "depend() {\n let i = this.deps.length\n while (i--) {\n this.deps[i].depend()\n }\n }", "function determineDependents({\n releases,\n packagesByName,\n dependencyGraph,\n preInfo,\n config\n}) {\n let updated = false; // NOTE this is intended to be called recursively\n\n let pkgsToSearch = [...releases.values()];\n\n while (pkgsToSearch.length > 0) {\n // nextRelease is our dependency, think of it as \"avatar\"\n const nextRelease = pkgsToSearch.shift();\n if (!nextRelease) continue; // pkgDependents will be a list of packages that depend on nextRelease ie. ['avatar-group', 'comment']\n\n const pkgDependents = dependencyGraph.get(nextRelease.name);\n\n if (!pkgDependents) {\n throw new Error(`Error in determining dependents - could not find package in repository: ${nextRelease.name}`);\n }\n\n pkgDependents.map(dependent => {\n let type;\n const dependentPackage = packagesByName.get(dependent);\n if (!dependentPackage) throw new Error(\"Dependency map is incorrect\");\n\n if (config.ignore.includes(dependent)) {\n type = \"none\";\n } else {\n const dependencyVersionRanges = getDependencyVersionRanges(dependentPackage.packageJson, nextRelease.name);\n\n for (const {\n depType,\n versionRange\n } of dependencyVersionRanges) {\n if (shouldBumpMajor({\n dependent,\n depType,\n versionRange,\n releases,\n nextRelease,\n preInfo,\n onlyUpdatePeerDependentsWhenOutOfRange: config.___experimentalUnsafeOptions_WILL_CHANGE_IN_PATCH.onlyUpdatePeerDependentsWhenOutOfRange\n })) {\n type = \"major\";\n } else {\n if ( // TODO validate this - I don't think it's right anymore\n (!releases.has(dependent) || releases.get(dependent).type === \"none\") && (config.___experimentalUnsafeOptions_WILL_CHANGE_IN_PATCH.updateInternalDependents === \"always\" || !semver__default['default'].satisfies(incrementVersion(nextRelease, preInfo), // to deal with a * versionRange that comes from workspace:* dependencies as the wildcard will match anything\n versionRange === \"*\" ? nextRelease.oldVersion : versionRange))) {\n switch (depType) {\n case \"dependencies\":\n case \"optionalDependencies\":\n case \"peerDependencies\":\n if (type !== \"major\" && type !== \"minor\") {\n type = \"patch\";\n }\n\n break;\n\n case \"devDependencies\":\n {\n // We don't need a version bump if the package is only in the devDependencies of the dependent package\n if (type !== \"major\" && type !== \"minor\" && type !== \"patch\") {\n type = \"none\";\n }\n }\n }\n }\n }\n }\n }\n\n if (releases.has(dependent) && releases.get(dependent).type === type) {\n type = undefined;\n }\n\n return {\n name: dependent,\n type,\n pkgJSON: dependentPackage.packageJson\n };\n }).filter(({\n type\n }) => type).forEach( // @ts-ignore - I don't know how to make typescript understand that the filter above guarantees this and I got sick of trying\n ({\n name,\n type,\n pkgJSON\n }) => {\n // At this point, we know if we are making a change\n updated = true;\n const existing = releases.get(name); // For things that are being given a major bump, we check if we have already\n // added them here. If we have, we update the existing item instead of pushing it on to search.\n // It is safe to not add it to pkgsToSearch because it should have already been searched at the\n // largest possible bump type.\n\n if (existing && type === \"major\" && existing.type !== \"major\") {\n existing.type = \"major\";\n pkgsToSearch.push(existing);\n } else {\n let newDependent = {\n name,\n type,\n oldVersion: pkgJSON.version,\n changesets: []\n };\n pkgsToSearch.push(newDependent);\n releases.set(name, newDependent);\n }\n });\n }\n\n return updated;\n}", "checkNodesForValidDependencies(bootConfig, allPreviousBootConfig, graph) {\n var isValidationError;\n var knownInThisStage;\n var knownInPreviousStages;\n var dependencyErrors = []; // record of path when looking for cicular dependency; reset each time\n for (let nodeName in this.graph.nodes) {\n let node = this.graph.nodes[nodeName];\n let index = node.dependencies.length;\n // walk backwards though the dependency array so can delete dependenies as needed\n while (index--) {\n let dependencyName = node.dependencies[index];\n knownInThisStage = this.checkForKnownDependency(dependencyName, bootConfig);\n if (!knownInThisStage) {\n knownInPreviousStages = this.checkForKnownDependency(dependencyName, allPreviousBootConfig);\n }\n // if only known in previous stages then can remove dependency from this stage\n if (!knownInThisStage && knownInPreviousStages) {\n logger_1.default.system.debug(`dependencyGraphy.checkNodesForValidDependencies removing dependency ${node.dependencies[index]} in node ${nodeName}`);\n // remove previous stage dependency\n node.dependencies.splice(index, 1);\n // else if not known anywhere, then error\n }\n else if (!knownInThisStage && !knownInPreviousStages) {\n isValidationError = true;\n dependencyErrors.push(`${nodeName} dependency \"${dependencyName}\" is unknown in this stage or previous stages`);\n }\n }\n }\n if (isValidationError) {\n this.errorDiag = new DGDiagnostics(`${this.context} illegal boot configuration`, dependencyErrors);\n this.graphState = \"error\";\n throw this.errorDiag.description;\n }\n }", "async resolveConflicts() {\n const neighbours = this.nodes;\n let newChain = undefined;\n\n // We're only looking for chains longer than ours\n let maxLength = this.chain.length;\n\n // Grab and verify the chains from all the nodes in our network\n for (const node of neighbours) {\n const response = await axios(`http://${ node }/chain`);\n\n if (response.status === 200) {\n const length = response.data.length;\n const chain = response.data.chain;\n\n // Check if the length is longer and the chain is valid\n if (length > maxLength && Blockchain.validChain(chain)) {\n maxLength = length;\n newChain = chain;\n }\n }\n }\n\n if (newChain) {\n this.chain = newChain;\n return true;\n }\n\n return false;\n }", "function collectTransitiveDependencies(collected, depGraph, fromName) {\n\t var immediateDeps = depGraph[fromName];\n\t if (immediateDeps) {\n\t Object.keys(immediateDeps).forEach(function (toName) {\n\t if (!collected[toName]) {\n\t collected[toName] = true;\n\t collectTransitiveDependencies(collected, depGraph, toName);\n\t }\n\t });\n\t }\n\t}", "function collectTransitiveDependencies(collected, depGraph, fromName) {\n var immediateDeps = depGraph[fromName];\n if (immediateDeps) {\n Object.keys(immediateDeps).forEach(function (toName) {\n if (!collected[toName]) {\n collected[toName] = true;\n collectTransitiveDependencies(collected, depGraph, toName);\n }\n });\n }\n}", "function collectTransitiveDependencies(collected, depGraph, fromName) {\n var immediateDeps = depGraph[fromName];\n if (immediateDeps) {\n Object.keys(immediateDeps).forEach(function (toName) {\n if (!collected[toName]) {\n collected[toName] = true;\n collectTransitiveDependencies(collected, depGraph, toName);\n }\n });\n }\n}", "checkLibraries() {\n const constructor = this;\n const regex = /__[^_]+_+/g;\n let unlinkedLibraries = constructor.binary.match(regex);\n\n if (unlinkedLibraries !== null) {\n unlinkedLibraries = unlinkedLibraries\n .map(\n (\n name // Remove underscores\n ) => name.replace(/_/g, \"\")\n )\n .sort()\n .filter((name, index, arr) => {\n // Remove duplicates\n if (index + 1 >= arr.length) {\n return true;\n }\n\n return name !== arr[index + 1];\n })\n .join(\", \");\n\n const error = `${constructor.contractName} contains unresolved libraries. You must deploy and link the following libraries before you can deploy a new version of ${constructor.contractName}: ${unlinkedLibraries}`;\n\n throw new Error(error);\n }\n }", "function collectTransitiveDependencies(collected, depGraph, fromName) {\n var immediateDeps = depGraph[fromName];\n\n if (immediateDeps) {\n for (var _i4 = 0, _Object$keys2 = Object.keys(immediateDeps); _i4 < _Object$keys2.length; _i4++) {\n var toName = _Object$keys2[_i4];\n\n if (!collected[toName]) {\n collected[toName] = true;\n collectTransitiveDependencies(collected, depGraph, toName);\n }\n }\n }\n}", "function collectTransitiveDependencies(collected, depGraph, fromName) {\n var immediateDeps = depGraph[fromName];\n\n if (immediateDeps) {\n for (var _i4 = 0, _Object$keys2 = Object.keys(immediateDeps); _i4 < _Object$keys2.length; _i4++) {\n var toName = _Object$keys2[_i4];\n\n if (!collected[toName]) {\n collected[toName] = true;\n collectTransitiveDependencies(collected, depGraph, toName);\n }\n }\n }\n}", "checkLibraries() {\n const constructor = this;\n const regex = /__[^_]+_+/g;\n let unlinkedLibraries = constructor.binary.match(regex);\n\n if (unlinkedLibraries !== null) {\n unlinkedLibraries = unlinkedLibraries\n .map((\n name // Remove underscores\n ) => name.replace(/_/g, \"\"))\n .sort()\n .filter((name, index, arr) => {\n // Remove duplicates\n if (index + 1 >= arr.length) {\n return true;\n }\n\n return name !== arr[index + 1];\n })\n .join(\", \");\n\n const error = `${\n constructor.contractName\n } contains unresolved libraries. You must deploy and link the following libraries before you can deploy a new version of ${\n constructor.contractName\n }: ${unlinkedLibraries}`;\n\n throw new Error(error);\n }\n }", "depend () {\n let i = this.deps.length\n while (i--) {\n this.deps[i].depend()\n }\n }", "resolveDependencies() {\n var _a;\n debug('resolveDependencies');\n const pluginNames = new Set(this._plugins.map((p) => p.name));\n // Handle `plugins` stanza\n this._plugins\n .filter(p => 'plugins' in p && p.plugins.length)\n .map(p => p)\n .forEach(parent => {\n parent.plugins\n .filter(p => !pluginNames.has(p.name))\n .forEach(p => {\n debug('adding missing plugin', p.name);\n // eslint-disable-next-line @typescript-eslint/strict-boolean-expressions\n if (parent.filter && !p.filter) {\n // Make child plugins inherit the parents filter if they don't have anything specified\n Object.defineProperty(p, 'filter', {\n get() {\n return parent.filter;\n }\n });\n }\n this.add(p);\n });\n });\n // Handle `dependencies` stanza\n const allDeps = new Map();\n this._plugins\n // Skip plugins without dependencies\n .filter(p => 'dependencies' in p && p.dependencies.size)\n .map(p => p.dependencies)\n .forEach(deps => {\n if (deps instanceof Set) {\n deps.forEach(k => allDeps.set(k, {}));\n }\n if (deps instanceof Map) {\n deps.forEach((v, k) => {\n allDeps.set(k, v); // Note: k,v => v,k\n });\n }\n });\n const missingDeps = new Map([...allDeps].filter(([k]) => !pluginNames.has(k)));\n if (!missingDeps.size) {\n debug('no dependencies are missing');\n return;\n }\n debug('dependencies missing', missingDeps);\n // Loop through all dependencies declared missing by plugins\n for (const [name, opts] of [...missingDeps]) {\n // Check if the dependency hasn't been registered as plugin already.\n // This might happen when multiple plugins have nested dependencies.\n if (this.names.includes(name)) {\n debug(`ignoring dependency '${name}', which has been required already.`);\n continue;\n }\n const hasFullName = name.startsWith('puppeteer-extra-plugin') ||\n name.startsWith('automation-extra-plugin');\n // We follow a plugin naming convention, but let's rather enforce it <3\n const requireNames = hasFullName\n ? [name]\n : [`automation-extra-plugin-${name}`, `puppeteer-extra-plugin-${name}`];\n const pkg = requirePackages(requireNames);\n if (!pkg) {\n throw new Error(`\n A plugin listed '${name}' as dependency,\n which is currently missing. Please install it:\n\n${requireNames\n .map(name => {\n return `yarn add ${name.split('/')[0]}`;\n })\n .join(`\\n or:\\n`)}\n\n Note: You don't need to require the plugin yourself,\n unless you want to modify it's default settings.\n `);\n }\n const plugin = pkg(opts);\n this.add(plugin);\n // Handle nested dependencies :D\n if ((_a = plugin.dependencies) === null || _a === void 0 ? void 0 : _a.size) {\n this.resolveDependencies();\n }\n }\n }", "function collectTransitiveDependencies(collected, depGraph, fromName) {\n var immediateDeps = depGraph[fromName];\n\n if (immediateDeps) {\n var _arr3 = Object.keys(immediateDeps);\n\n for (var _i3 = 0; _i3 < _arr3.length; _i3++) {\n var toName = _arr3[_i3];\n\n if (!collected[toName]) {\n collected[toName] = true;\n collectTransitiveDependencies(collected, depGraph, toName);\n }\n }\n }\n}", "async getIdsOfDepsInstalledAsPackages() {\n if (!this.options.objectsOnly) {\n // this is needed only when importing objects. we don't want these components to be written to the fs\n return [];\n }\n\n const authoredNonExportedComponentsIds = this.consumer.bitMap.getAuthoredNonExportedComponents();\n const {\n components: authoredNonExportedComponents\n } = await this.consumer.loadComponents(_bitId().BitIds.fromArray(authoredNonExportedComponentsIds), false);\n const dependencies = (0, _flatten2().default)(authoredNonExportedComponents.map(c => c.getAllDependenciesIds()));\n const missingDeps = [];\n await Promise.all(dependencies.map(async dep => {\n if (!dep.hasScope()) return;\n const isInScope = await this.scope.isComponentInScope(dep);\n if (!isInScope) missingDeps.push(dep);\n }));\n return missingDeps;\n }", "function buildDeps(arrDeps) {\n arrDeps.forEach(function (deps) {\n var depsId = deps, vmPath;\n\n var depsObj = map[depsId];\n if (!depsObj) {\n console.error('%s is not in map!!', depsId);\n return;\n }\n var hisDeps = depsObj['deps'] || [];\n if (hisDeps && hisDeps.length) {\n buildDeps(hisDeps);\n }\n\n var type = depsObj.type;\n var uri = depsObj.uri;\n\n switch (type) {\n case 'vm':\n\n // 检查deps中的js,添加到arrJsMod里\n // arrJsMod中只放每一个vm同名依赖的js模块,它的依赖已经打包在arrCombJs中提前加载了\n var depsIdPre = depsId.replace(/(.*?)(\\.vm)$/, '$1');\n hisDeps.map(function (item) {\n if (item === depsIdPre + '.js') {\n var modId = map[item] && map[item]['extras']['moduleId'];\n arrJsMod.push({\n moduleId: '\"' + modId + '\"',\n widgetId: deps.idf\n });\n }\n });\n\n break;\n case 'js':\n if (!~conf['arrGlobalJs'].indexOf(uri)) {\n arrCombJs.pushUnique(uri);\n }\n break;\n case 'css':\n if (!~conf['arrGlobalCss'].indexOf(uri)) {\n arrCombCss.pushUnique(uri);\n }\n break;\n default:\n break;\n } //end of switch\n }); //end of forEach\n\n }", "function _CheckDependencies(suppressAlert){\n\n\t\tvar dependencyMap = [\n\t\t\t{ key: 'datatables', name: 'jQuery Datatables plugin', testObject: $.fn.dataTable },\n\t\t\t{ key: 'mapevents', name: 'jQuery Map Events plugin', testObject: $.mapEvents },\n\t\t\t{ key: 'pubsub', name: 'jQuery Pub/Sub plugin', testObject: $.publish },\n\t\t\t{ key: 'bootstrap', name: 'jQuery Bootstrap plugin', testObject: $.fn.modal },\n\t\t\t{ key: 'jqueryui', name: 'jQuery UI', testObject: $.ui }\n\t\t];\n\n\t\t// Perform checks\n\t\tvar missingDependencies = [];\n\t\tvar dependencyResults = {};\n\n\t\tdependencyMap.forEach( function(element, index, array){\n\t\t\tvar hasDependency = true;\n\n\t\t\tif ( typeof element.testObject === 'undefined' ) {\n\t\t\t\tmissingDependencies.push( '-- ' + element.name );\n\t\t\t\thasDependency = false;\n\t\t\t}\n\n\t\t\tdependencyResults[element.key] = hasDependency;\n\n\t\t});\n\n\t\tif ( missingDependencies.length ) {\n\t\t\tvar message = 'The following dependencies are missing in ' + fileName + ': \\r\\n' + missingDependencies.join('\\n');\n\t\t\t(suppressAlert) ? console.log(message) : alert(message) ;\n\t\t}\n\n\t\treturn dependencyResults;\n\t}", "function checkUnknownDependencies(field, context) {\n\treturn field.dependencies // For all dependency fields...\n\t\t.map(d => isUnknown(context[d.name], d)) // ... check if value in context is unknown\n\t\t.some(d => d === true) // If any are unknown, return true\n}", "cleanupDeps() {\n let i = this.deps.length\n while (i--) {\n const dep = this.deps[i]\n if (!this.newDepIds.has(dep.id)) {\n dep.removeSub(this)\n }\n }\n let tmp = this.depIds\n this.depIds = this.newDepIds\n this.newDepIds = tmp\n this.newDepIds.clear()\n tmp = this.deps\n this.deps = this.newDeps\n this.newDeps = tmp\n this.newDeps.length = 0\n }", "cleanupDeps () {\n let i = this.deps.length\n while (i--) {\n const dep = this.deps[i]\n if (!this.newDepIds.has(dep.id)) {\n dep.removeSub(this)\n }\n }\n let tmp = this.depIds\n this.depIds = this.newDepIds\n this.newDepIds = tmp\n this.newDepIds.clear()\n tmp = this.deps\n this.deps = this.newDeps\n this.newDeps = tmp\n this.newDeps.length = 0\n }", "function isSameCircularDependency(actual, expected) {\n if (actual.length !== expected.length) {\n return false;\n }\n for (let i = 0; i < actual.length; i++) {\n if (actual[i] !== expected[i]) {\n return false;\n }\n }\n return true;\n}", "function collectConflicts(metadata) {\n var win = winningRev(metadata);\n var leaves = collectLeaves(metadata.rev_tree);\n var conflicts = [];\n for (var i = 0, len = leaves.length; i < len; i++) {\n var leaf = leaves[i];\n if (leaf.rev !== win && !leaf.opts.deleted) {\n conflicts.push(leaf.rev);\n }\n }\n return conflicts;\n }", "function resolve(graph) {\n var sorted = [], // sorted list of IDs ( returned value )\n visited = {}; // hash: id of already visited node => true\n\n // 2. topological sort\n Object.keys(graph).forEach(function visit(name, ancestors) {\n if (!Array.isArray(ancestors)) ancestors = [];\n ancestors.push(name);\n visited[name] = true;\n\n graph[name].forEach(function (dep) {\n if (ancestors.indexOf(dep) >= 0)\n // if already in ancestors, a closed chain exists.\n throw new Error(\n 'Circular dependency \"' +\n dep +\n '\" is required by \"' +\n name +\n '\": ' +\n ancestors.join(\" -> \")\n );\n\n // if already exists, do nothing\n if (visited[dep]) return;\n visit(dep, ancestors.slice(0)); // recursive call\n });\n\n if (sorted.indexOf(name) < 0) sorted.push(name);\n });\n\n return sorted;\n}", "function walkDeps(childs, path, tree) {\n for (var i = 0, size = childs.length; i < size; i++) {\n var cur = childs[i];\n // check if the path contains the child (a circular dependency)\n if (path.indexOf(cur) > -1) {\n path.push(cur);\n return true;\n }\n // walk the children of this child\n var curChilds = tree[cur];\n if (curChilds != null) {\n // push and pop the child before and after the sub-walk\n path.push(cur);\n // recursively walk children\n var res = walkDeps(curChilds, path, tree);\n if (res)\n return res;\n path.pop();\n }\n }\n return false;\n }", "function collectConflicts(metadata) {\n\t var win = winningRev(metadata);\n\t var leaves = collectLeaves(metadata.rev_tree);\n\t var conflicts = [];\n\t for (var i = 0, len = leaves.length; i < len; i++) {\n\t var leaf = leaves[i];\n\t if (leaf.rev !== win && !leaf.opts.deleted) {\n\t conflicts.push(leaf.rev);\n\t }\n\t }\n\t return conflicts;\n\t}", "function collectConflicts(metadata) {\n\t var win = winningRev(metadata);\n\t var leaves = collectLeaves(metadata.rev_tree);\n\t var conflicts = [];\n\t for (var i = 0, len = leaves.length; i < len; i++) {\n\t var leaf = leaves[i];\n\t if (leaf.rev !== win && !leaf.opts.deleted) {\n\t conflicts.push(leaf.rev);\n\t }\n\t }\n\t return conflicts;\n\t}", "depend () {\n var i = this.deps.length;\n while (i--) {\n this.deps[i].depend();\n }\n }", "cleanupDeps () {\n let i = this.deps.length\n while (i--) {\n const dep = this.deps[i]\n if (!this.newDepIds.has(dep.id)) {\n dep.removeSub(this)\n }\n }\n let tmp = this.depIds\n this.depIds = this.newDepIds\n this.newDepIds = tmp\n this.newDepIds.clear()\n tmp = this.deps\n this.deps = this.newDeps\n this.newDeps = tmp\n this.newDeps.length = 0\n }", "function check_program_trace_for_dependencies(){\n\t\n\tvar result = [];\n\n\t// Works for global level hoisting\n\t//Getting all the global function\n\t/*var global_fun = [];\n\tvar i = 0;\n\n\twhile(true){\n\n\t\tif(!program_stack[i].includes('declare_')){\n\t\t\tbreak;\n\t\t}\n\n\t\tif(function_list.indexOf(program_stack[i].split('_').splice(-1)[0]) > -1){\n\t\t\tglobal_fun.push(program_stack[i].split('_').splice(-1)[0]);\n\t\t}\n\n\t\ti++;\n\t}\n\n\tfor (var j = 0; j < global_fun.length; j++) {\n\t\tvar nf = get_nf_of_global_fun_f(global_fun[j]);\n\n\t\tvar write_list = get_write_list(global_fun[j]);\n\t\t//console.log(global_fun[j] + \" writes to: \" + write_list);\n\n\t\tvar dependent_flag = false;\n\t\tfor (var k = 0; k < nf.length; k++) {\n\n\t\t\tdependent_flag = false;\n\t\t\tvar read_list = get_read_list(nf[k]);\n\t\t\t//console.log(nf[k] + \" reads from: \" + read_list);\n\n\t\t\tfor (var l = 0; l < read_list.length; l++) {\n\t\t\t\t//console.log(read_list[l]);\n\t\t\t\tif(write_list.indexOf(read_list[l]) > -1){\n\t\t\t\t\tdependent_flag = true;\n\t\t\t\t}\n\t\t\t};\n\n\t\t\t//console.log(dependent_flag);\n\n\t\t\tif(dependent_flag === false){\n\t\t\t\tresult.push(nf[k]);\n\t\t\t}\n\t\t};\n\n\t};*/\n\n\t// Works for multi level hoisting\n\tfor(i=0; i<program_stack.length; i++){\n\t\tif(program_stack[i].includes('invoke-fun-pre')){\n\t\t\tvar f = program_stack[i].split('_').splice(-1)[0];\n\t\t\tvar nf = get_nested_functions(f, i);\n\t\t\t\n\t\t\t// Getting all the writes be the parent function f\n\t\t\tvar write_list = get_write_list(f);\n\t\t\t\n\t\t\tvar dependent_flag = false;\n\t\t\tfor (var k = 0; k < nf.length; k++) {\n\n\t\t\t\tdependent_flag = false;\n\t\t\t\t// Getting all the reads by the child function nf[k] of that function f\n\t\t\t\tvar read_list = get_read_list(nf[k]);\n\t\t\t\t\n\t\t\t\tfor (var l = 0; l < read_list.length; l++) {\n\t\t\t\t\tif(write_list.indexOf(read_list[l]) > -1){\n\t\t\t\t\t\tdependent_flag = true;\n\t\t\t\t\t}\n\t\t\t\t};\n\n\t\t\t\tif(dependent_flag === false){\n\t\t\t\t\tresult.push(nf[k]);\n\t\t\t\t}\n\t\t\t};\n\t\t}\n\t}\n\n\t//console.log(\"These Nested Functions can be hoisted based on first condition: [ \" + result + \" ]\");\n\treturn result;\n}", "depend () {\n let i = this.deps.length\n while (i--) {\n this.deps[i].depend()\n }\n }", "function dependenciesAreLoaded(dependencies) {\n\t\t\tfor ( var i = 0 ; i < dependencies.length ; i++ ) {\n\t\t\t\tvar libraryName = dependencies[i];\n\t\t\t\tif ( !(libraryStorage[libraryName]) ) {\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn true;\n\t\t}", "[_canPlacePeers] (dep, target, edge, ret, peerEntryEdge) {\n if (!dep.parent || peerEntryEdge)\n return ret\n\n for (const peer of dep.parent.children.values()) {\n if (peer !== dep) {\n const peerEdge = dep.edgesOut.get(peer.name) ||\n [...peer.edgesIn].find(e => e.peer)\n /* istanbul ignore else - pretty sure this is impossible, but just\n being cautious */\n if (peerEdge) {\n const canPlacePeer = this[_canPlaceDep](peer, target, peerEdge, edge)\n if (canPlacePeer === CONFLICT)\n return CONFLICT\n }\n }\n }\n\n return ret\n }", "function collectConflicts(metadata) {\n var win = winningRev(metadata);\n var leaves = collectLeaves(metadata.rev_tree);\n var conflicts = [];\n for (var i = 0, len = leaves.length; i < len; i++) {\n var leaf = leaves[i];\n if (leaf.rev !== win && !leaf.opts.deleted) {\n conflicts.push(leaf.rev);\n }\n }\n return conflicts;\n}", "function collectConflicts(metadata) {\n var win = winningRev(metadata);\n var leaves = collectLeaves(metadata.rev_tree);\n var conflicts = [];\n for (var i = 0, len = leaves.length; i < len; i++) {\n var leaf = leaves[i];\n if (leaf.rev !== win && !leaf.opts.deleted) {\n conflicts.push(leaf.rev);\n }\n }\n return conflicts;\n}", "function collectConflicts(metadata) {\n var win = winningRev(metadata);\n var leaves = collectLeaves(metadata.rev_tree);\n var conflicts = [];\n for (var i = 0, len = leaves.length; i < len; i++) {\n var leaf = leaves[i];\n if (leaf.rev !== win && !leaf.opts.deleted) {\n conflicts.push(leaf.rev);\n }\n }\n return conflicts;\n}", "function collectConflicts(metadata) {\n var win = winningRev(metadata);\n var leaves = collectLeaves(metadata.rev_tree);\n var conflicts = [];\n for (var i = 0, len = leaves.length; i < len; i++) {\n var leaf = leaves[i];\n if (leaf.rev !== win && !leaf.opts.deleted) {\n conflicts.push(leaf.rev);\n }\n }\n return conflicts;\n}", "function collectConflicts(metadata) {\n var win = winningRev(metadata);\n var leaves = collectLeaves(metadata.rev_tree);\n var conflicts = [];\n for (var i = 0, len = leaves.length; i < len; i++) {\n var leaf = leaves[i];\n if (leaf.rev !== win && !leaf.opts.deleted) {\n conflicts.push(leaf.rev);\n }\n }\n return conflicts;\n}", "function collectConflicts(metadata) {\n var win = winningRev(metadata);\n var leaves = collectLeaves(metadata.rev_tree);\n var conflicts = [];\n for (var i = 0, len = leaves.length; i < len; i++) {\n var leaf = leaves[i];\n if (leaf.rev !== win && !leaf.opts.deleted) {\n conflicts.push(leaf.rev);\n }\n }\n return conflicts;\n}", "function collectConflicts(metadata) {\n var win = winningRev(metadata);\n var leaves = collectLeaves(metadata.rev_tree);\n var conflicts = [];\n for (var i = 0, len = leaves.length; i < len; i++) {\n var leaf = leaves[i];\n if (leaf.rev !== win && !leaf.opts.deleted) {\n conflicts.push(leaf.rev);\n }\n }\n return conflicts;\n}", "function collectConflicts(metadata) {\n var win = winningRev(metadata);\n var leaves = collectLeaves(metadata.rev_tree);\n var conflicts = [];\n for (var i = 0, len = leaves.length; i < len; i++) {\n var leaf = leaves[i];\n if (leaf.rev !== win && !leaf.opts.deleted) {\n conflicts.push(leaf.rev);\n }\n }\n return conflicts;\n}", "function collectConflicts(metadata) {\n var win = winningRev(metadata);\n var leaves = collectLeaves(metadata.rev_tree);\n var conflicts = [];\n for (var i = 0, len = leaves.length; i < len; i++) {\n var leaf = leaves[i];\n if (leaf.rev !== win && !leaf.opts.deleted) {\n conflicts.push(leaf.rev);\n }\n }\n return conflicts;\n}", "function collectConflicts(metadata) {\n var win = winningRev(metadata);\n var leaves = collectLeaves(metadata.rev_tree);\n var conflicts = [];\n for (var i = 0, len = leaves.length; i < len; i++) {\n var leaf = leaves[i];\n if (leaf.rev !== win && !leaf.opts.deleted) {\n conflicts.push(leaf.rev);\n }\n }\n return conflicts;\n}", "cleanupDeps () {\n var i = this.deps.length;\n while (i--) {\n var dep = this.deps[i];\n if (!this.newDepIds.has(dep.id)) {\n dep.removeSub(this);\n }\n }\n var tmp = this.depIds;\n this.depIds = this.newDepIds;\n this.newDepIds = tmp;\n this.newDepIds.clear();\n tmp = this.deps;\n this.deps = this.newDeps;\n this.newDeps = tmp;\n this.newDeps.length = 0;\n }", "function _getDependencies (id, deps, circularDeps, i, j, d, subDeps, sd) {\n\n\t\tdeps = _dependencies[id] || [];\n\t\tcircularDeps = [];\n\n\t\tfor (i = 0; i < deps.length; i ++) {\n\t\t\td = deps[i];\n\t\t\tsubDeps = _dependencies[d];\n\t\t\tif (subDeps) {\n\t\t\t\tfor (j = 0; j < subDeps.length; j ++) {\n\t\t\t\t\tsd = subDeps[j];\n\t\t\t\t\tif (sd != id && deps.indexOf(sd) < 0) {\n\t\t\t\t\t\tdeps.push(sd);\n\t\t\t\t\t}\n\t\t\t\t\telse if(sd === id){\n\t\t\t\t\t\tcircularDeps.push(d);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn [deps, circularDeps];\n\t}", "getAllDependencies(exclude = []) {\n let dependencyMap = {};\n let dependencyStack = [...this.dependencies];\n //keep walking the dependency graph until we run out of unseen dependencies\n while (dependencyStack.length > 0) {\n let dependency = dependencyStack.pop();\n //if this is a new dependency and we aren't supposed to skip it\n if (!dependencyMap[dependency] && !exclude.includes(dependency)) {\n dependencyMap[dependency] = true;\n //get the node for this dependency\n let node = this.graph.nodes[dependency];\n if (node) {\n dependencyStack.push(...node.dependencies);\n }\n }\n }\n return Object.keys(dependencyMap);\n }", "getPaginatedOverAllCollectionMappedDependencies() {\n let graph = new DependencyGraph();\n let tagPrefix = TemplateMap.tagPrefix;\n let allNodeAdded = false;\n\n for (let entry of this.map) {\n if (\n this.isPaginationOverAllCollections(entry) &&\n this.getPaginationTagTarget(entry) === \"all\"\n ) {\n if (!allNodeAdded) {\n graph.addNode(tagPrefix + \"all\");\n allNodeAdded = true;\n }\n\n if (!graph.hasNode(entry.inputPath)) {\n graph.addNode(entry.inputPath);\n }\n\n if (!entry.data.eleventyExcludeFromCollections) {\n // Populates into collections.all\n // This is circular!\n graph.addDependency(tagPrefix + \"all\", entry.inputPath);\n\n // Note that `tags` are otherwise ignored here\n // TODO should we throw an error?\n }\n\n this.addDeclaredDependenciesToGraph(\n graph,\n entry.inputPath,\n entry.data.eleventyImport?.collections\n );\n }\n }\n\n return graph;\n }", "function depsBelongTo(deps, file, topLevel) {\n forOwn(deps, function(dep) {\n dep = modulesByID[dep];\n var id = dep.dedupe || dep.id;\n var belong = moduleBelongsTo[id];\n var count = belong[file] = topLevel ? Infinity : (belong[file] || 0) + 1;\n // stop at 3, otherwise it might be a cyclic dependency\n if (count <= 3 || topLevel) depsBelongTo(dep.deps, file);\n });\n }", "function visit(name) {\n var field = map[name];\n if (name in marked) {\n console.warn(\"Cyclic dependency among fields detected in %O\", fieldList);\n return fieldList;\n }\n if (!(name in visited)) {\n marked[name] = true;\n forEachDep(field, function(depName) {\n visit(depName);\n });\n delete marked[name];\n visited[name] = true;\n result.push(field);\n }\n }", "testOneNodeForCircularPath(dependencyPathTaken, nodeName) {\n logger_1.default.system.debug(`BootDependencyGraph.testOneNodeForCircularPath -- nodeName=${nodeName}`, dependencyPathTaken);\n var circular = false;\n // if node is already in the path previously walked, then must be circular\n if (dependencyPathTaken.includes(nodeName)) {\n dependencyPathTaken.push(nodeName);\n circular = true;\n // else everything okay so far....no circular dependencies yet\n }\n else {\n dependencyPathTaken.push(nodeName);\n let node = this.graph.nodes[nodeName];\n for (const index in node.dependencies) {\n circular = this.testOneNodeForCircularPath(dependencyPathTaken, node.dependencies[index]);\n if (circular) {\n break;\n }\n }\n }\n if (!circular) { // unwind path when not a circular path; otherwise side branches can be in circular dependencyPathTaken (which is used for diagnostics)\n dependencyPathTaken.pop();\n }\n logger_1.default.system.debug(`BootDependencyGraph.testOneNodeForCircularPath done for nodeName=${nodeName} with circular=${circular}`);\n return circular;\n }", "function dfsHelper(course) {\n // Base Case #1:\n // If the course has already been visited, we have detected\n // a circular dependency, which means the schedule cannot be completed\n if (visitedSet[course] === true) return false;\n\n // Base Case #2:\n // If the course has no dependencies, we know it can always be\n // completed no matter what\n if (prerequisitesMap[`${course}`].length < 1) return true;\n\n // If we get to here it means the course has prerequisites, so we want\n // to mark the course as visited and search through its prerequisites\n // until we hit our base cases\n visitedSet[course] = true;\n const coursePrerequisites = prerequisitesMap[`${course}`];\n for (let prereqIndex = 0; prereqIndex < coursePrerequisites.length; prereqIndex ++) {\n if (!dfsHelper(coursePrerequisites[prereqIndex])) return false;\n }\n\n visitedSet[course] = false;\n prerequisitesMap[`${course}`] = [];\n return true;\n }", "function checkForMissingReferences(rootNodes) {\n let nodes\n for (let i = 0; i < rootNodes.length; i++) {\n if (rootNodes[i] !== undefined) {\n nodes = UI.projects.foundations.utilities.hierarchy.getHiriarchyMap(rootNodes[i]) \n for (let [key, value] of nodes) {\n // Check nodes that have a saved reference parent\n if (value.savedPayload.referenceParent !== undefined) {\n // Highlight nodes that do not have an active reference connected to their referance parent\n if (value.payload.referenceParent === undefined) {\n console.log(\"[WARN] Reference Parent not found in the current workspace.\\n Node:\", value.name, \" Type:\", value.type, \" ID:\", key, \" Node Object:\", value)\n UI.projects.foundations.spaces.floatingSpace.inMapMode = true\n value.payload.uiObject.setWarningMessage('Reference Parent not found in the current workspace.', 10)\n }\n \n }\n }\n \n }\n }\n \n }", "static getUniqueDependencies() {\n if (!uniqueDependenciesCache.has(this)) {\n const filtered = this.dependencies.filter((dep, index, deps) => deps.indexOf(dep) === index);\n uniqueDependenciesCache.set(this, filtered);\n }\n return uniqueDependenciesCache.get(this) || [];\n }", "function traverse(config) {\n const tree = [];\n const stack = [config.filename];\n\n while (stack.length) {\n const dependency = stack.pop();\n debug(`traversing ${dependency}`);\n\n if (config.visited[dependency]) {\n populateFromCache(dependency);\n } else {\n traverseDependency(dependency);\n }\n }\n\n return tree;\n\n function traverseDependency(dependency) {\n const localConfig = config.clone();\n localConfig.filename = dependency;\n\n let dependencies = module.exports._getDependencies(localConfig);\n\n if (config.filter) {\n debug('using filter function to filter out dependencies');\n debug(`number of dependencies before filtering: ${dependencies.length}`);\n dependencies = dependencies.filter(function (filePath) {\n return localConfig.filter(filePath, localConfig.filename);\n });\n debug(`number of dependencies after filtering: ${dependencies.length}`);\n }\n\n debug('cabinet-resolved all dependencies: ', dependencies); // @ts-ignore AUTO-ADDED-AFTER-MIGRATION-PLEASE-FIX!\n\n tree[dependency] = dependencies;\n const filePathMap = config.pathMap.find(pathMapEntry => pathMapEntry.file === dependency);\n if (!filePathMap) throw new Error(`file ${dependency} is missing from PathMap`);\n config.visited[dependency] = {\n pathMap: filePathMap,\n missing: config.nonExistent[dependency],\n error: config.errors[dependency]\n };\n stack.push(...dependencies);\n }\n\n function populateFromCache(dependency) {\n debug(`already visited ${dependency}. Will try to find it and its dependencies in the cache`);\n const dependenciesStack = [dependency];\n\n while (dependenciesStack.length) {\n findAllDependenciesInCache(dependenciesStack);\n }\n }\n\n function findAllDependenciesInCache(dependenciesStack) {\n const dependency = dependenciesStack.pop();\n\n if (!config.visited[dependency]) {\n debug(`unable to find ${dependency} in the cache, it was probably filtered before`);\n return;\n }\n\n debug(`found ${dependency} in the cache`);\n const dependencies = config.visited[dependency].pathMap.dependencies.map(d => d.resolvedDep); // @ts-ignore AUTO-ADDED-AFTER-MIGRATION-PLEASE-FIX!\n\n tree[dependency] = dependencies;\n config.pathMap.push(config.visited[dependency].pathMap);\n\n if (config.visited[dependency].missing) {\n config.nonExistent[dependency] = config.visited[dependency].missing;\n }\n\n if (config.visited[dependency].error) {\n config.errors[dependency] = config.visited[dependency].error;\n }\n\n dependencies.forEach(d => {\n if (!tree[d]) dependenciesStack.push(d);\n });\n }\n}", "function checkDefs(table) {\n var errs = [];\n table.items().forEach(function(pair) {\n var name = pair[0],\n defs = pair[1];\n if ( defs.length > 1 ) {\n errs.push(warning('multiple definitions of symbol',\n defs[0].pos,\n {'positions': defs.slice(1).map(f_pos),\n 'name': name}));\n }\n if ( builtins.has(name) ) {\n errs.push(warning('redefinition of built-in symbol',\n defs[0].pos,\n {'name': name}));\n // TODO should this generate a warning for *each* of the\n // redefinitions ... or is that just yak-shaving?\n }\n });\n return errs;\n}", "function addCircular(system, parents) {\n var deps = system.remoteDependencies\n && Object.keys(system.remoteDependencies);\n\n if (!deps || !deps.length) {\n return;\n }\n \n deps.forEach(function (name) {\n var ref = system.remoteDependencies[name]['$ref'],\n list = Array.isArray(parents) ? parents.slice() : [],\n refName,\n match;\n\n if (!ref) {\n //\n // Create a copy of parents for this part of the\n // path iteration.\n //\n return addCircular(\n system.remoteDependencies[name],\n list.concat(system.name)\n );\n }\n\n if ((match = refPattern.exec(ref))) {\n refName = match[1];\n if (~list.indexOf(refName)) {\n addCycle(refName, system.name);\n }\n }\n });\n }", "function ___isCircular(dotName, key)\n\t{\n\t\tdotName = dotName instanceof Array ? dotName : (dotName + '').split('.')\n\t\tif (key != null)\n\t\t\tdotName.push(key);\n\t\tif (!dotName.length || dotName[0] === '')\n\t\t\treturn false;\n\t\tkey = dotName.pop();\n\t\treturn dotName.includes(key);\n\t}", "function checkConflicts() {\r\n // checks if a conflict exists\r\n var conflict = false;\r\n for (var i = 0; i < tempNodes.length; i++) {\r\n var tempNode = tempNodes[i];\r\n if (tempNode.checkIncomingLinks() === true) {\r\n conflict = true;\r\n }\r\n }\r\n if (conflict === true) {\r\n // todo conflict alert\r\n // actually conflicts are allowed to show problems\r\n confirmChanges(true);\r\n } else {\r\n confirmChanges(true);\r\n }\r\n }", "function getDependsOnOwnProps(mapToProps){return mapToProps.dependsOnOwnProps!==null&&mapToProps.dependsOnOwnProps!==undefined?Boolean(mapToProps.dependsOnOwnProps):mapToProps.length!==1;}// Used by whenMapStateToPropsIsFunction and whenMapDispatchToPropsIsFunction,", "function main () {\n if (process.platform === 'win32') {\n console.error('Sorry, check-deps only works on Mac and Linux')\n return\n }\n\n var usedDeps = findUsedDeps()\n var packageDeps = findPackageDeps()\n\n var missingDeps = usedDeps.filter(\n (dep) => !includes(packageDeps, dep) && !includes(BUILT_IN_DEPS, dep)\n )\n var unusedDeps = packageDeps.filter(\n (dep) => !includes(usedDeps, dep) && !includes(EXECUTABLE_DEPS, dep)\n )\n\n if (missingDeps.length > 0) {\n console.error('Missing package dependencies: ' + missingDeps)\n }\n if (unusedDeps.length > 0) {\n console.error('Unused package dependencies: ' + unusedDeps)\n }\n if (missingDeps.length + unusedDeps.length > 0) {\n process.exitCode = 1\n }\n}", "function isDependencySatisfied(dep) {\r\n let count = 0\r\n for (let key in dep) {\r\n if ($('#' + key).val() == dep[key]) {\r\n count++;\r\n }\r\n }\r\n if (count == Object.keys(dep).length) {\r\n return true;\r\n } else {\r\n return false;\r\n }\r\n}", "function detectCycleRecursive(inputObj) {\n if (visitedTypes[inputObj.name]) {\n return;\n }\n\n visitedTypes[inputObj.name] = true;\n fieldPathIndexByTypeName[inputObj.name] = fieldPath.length;\n var fields = Object(_polyfills_objectValues_mjs__WEBPACK_IMPORTED_MODULE_1__[\"default\"])(inputObj.getFields());\n\n for (var _i30 = 0; _i30 < fields.length; _i30++) {\n var field = fields[_i30];\n\n if (Object(_definition_mjs__WEBPACK_IMPORTED_MODULE_10__[\"isNonNullType\"])(field.type) && Object(_definition_mjs__WEBPACK_IMPORTED_MODULE_10__[\"isInputObjectType\"])(field.type.ofType)) {\n var fieldType = field.type.ofType;\n var cycleIndex = fieldPathIndexByTypeName[fieldType.name];\n fieldPath.push(field);\n\n if (cycleIndex === undefined) {\n detectCycleRecursive(fieldType);\n } else {\n var cyclePath = fieldPath.slice(cycleIndex);\n var pathStr = cyclePath.map(function (fieldObj) {\n return fieldObj.name;\n }).join('.');\n context.reportError(\"Cannot reference Input Object \\\"\".concat(fieldType.name, \"\\\" within itself through a series of non-null fields: \\\"\").concat(pathStr, \"\\\".\"), cyclePath.map(function (fieldObj) {\n return fieldObj.astNode;\n }));\n }\n\n fieldPath.pop();\n }\n }\n\n fieldPathIndexByTypeName[inputObj.name] = undefined;\n }", "function detectCycleRecursive(inputObj) {\n if (visitedTypes[inputObj.name]) {\n return;\n }\n\n visitedTypes[inputObj.name] = true;\n fieldPathIndexByTypeName[inputObj.name] = fieldPath.length;\n var fields = Object(_polyfills_objectValues_mjs__WEBPACK_IMPORTED_MODULE_2__[\"default\"])(inputObj.getFields());\n\n for (var _i30 = 0; _i30 < fields.length; _i30++) {\n var field = fields[_i30];\n\n if (Object(_definition_mjs__WEBPACK_IMPORTED_MODULE_11__[\"isNonNullType\"])(field.type) && Object(_definition_mjs__WEBPACK_IMPORTED_MODULE_11__[\"isInputObjectType\"])(field.type.ofType)) {\n var fieldType = field.type.ofType;\n var cycleIndex = fieldPathIndexByTypeName[fieldType.name];\n fieldPath.push(field);\n\n if (cycleIndex === undefined) {\n detectCycleRecursive(fieldType);\n } else {\n var cyclePath = fieldPath.slice(cycleIndex);\n var pathStr = cyclePath.map(function (fieldObj) {\n return fieldObj.name;\n }).join('.');\n context.reportError(\"Cannot reference Input Object \\\"\".concat(fieldType.name, \"\\\" within itself through a series of non-null fields: \\\"\").concat(pathStr, \"\\\".\"), cyclePath.map(function (fieldObj) {\n return fieldObj.astNode;\n }));\n }\n\n fieldPath.pop();\n }\n }\n\n fieldPathIndexByTypeName[inputObj.name] = undefined;\n }", "function resolveCircularModuleDependency(fn) {\n return fn();\n }", "function resolveCircularModuleDependency(fn) {\n return fn();\n }", "[_placeDep] (dep, node, edge, peerEntryEdge = null) {\n if (!edge.error && !this[_updateNames].includes(edge.name))\n return []\n\n // top nodes should still get peer deps from their parent or fsParent\n // if possible, and only install locally if there's no other option,\n // eg for a link outside of the project root.\n const start = edge.peer && !node.isRoot\n ? node.resolveParent || node\n : node\n\n let target\n let canPlace = null\n for (let check = start; check; check = check.resolveParent) {\n const cp = this[_canPlaceDep](dep, check, edge, peerEntryEdge)\n // anything other than a conflict is fine to proceed with\n if (cp !== CONFLICT) {\n canPlace = cp\n target = check\n } else\n break\n\n // nest packages like npm v1 and v2\n // very disk-inefficient\n if (this[_legacyBundling])\n break\n }\n\n if (!target) {\n throw Object.assign(new Error('unable to resolve dependency tree'), {\n package: edge.name,\n spec: edge.spec,\n type: edge.type,\n requiredBy: node.package._id,\n location: node.path,\n })\n }\n\n // Can only get KEEP here if the original edge was valid,\n // and we're checking for an update but it's already up to date.\n if (canPlace === KEEP) {\n dep.parent = null\n return []\n }\n\n // figure out which of this node's peer deps will get placed as well\n const virtualRoot = dep.parent\n\n const placed = [dep]\n const oldChild = target.children.get(edge.name)\n if (oldChild) {\n // if we're replacing, we should also remove any nodes for edges that\n // are now invalid, and where this (or its deps) is the only dependent,\n // and also recurse on that pruning. Otherwise leaving that dep node\n // around can result in spurious conflicts pushing nodes deeper into\n // the tree than needed in the case of cycles that will be removed\n // later anyway.\n const oldDeps = []\n for (const [name, edge] of oldChild.edgesOut.entries()) {\n if (!dep.edgesOut.has(name) && edge.to) {\n oldDeps.push(edge.to)\n }\n }\n dep.replace(oldChild)\n this[_pruneForReplacement](dep, oldDeps)\n } else\n dep.parent = target\n\n // If the edge is not an error, then we're updating something, and\n // MAY end up putting a better/identical node further up the tree in\n // a way that causes an unnecessary duplication. If so, remove the\n // now-unnecessary node.\n if (edge.valid && edge.to.parent !== target && dep.canReplace(edge.to)) {\n edge.to.parent = null\n }\n\n // visit any dependents who are upset by this change\n for (const edge of dep.edgesIn) {\n if (!edge.valid)\n this[_depsQueue].push(edge.from)\n }\n\n // in case we just made some duplicates that can be removed,\n // prune anything deeper in the tree that can be replaced by this\n if (this.idealTree) {\n\n for (const node of this.idealTree.inventory.query('name', dep.name)) {\n if (node !== dep &&\n node.isDescendantOf(target) &&\n !node.inShrinkwrap &&\n !node.inBundle &&\n node.canReplaceWith(dep)) {\n\n // don't prune if the is dupe necessary!\n // root (a, d)\n // +-- a (b, c2)\n // | +-- b (c2) <-- place c2 for b, lands at root\n // +-- d (e)\n // +-- e (c1, d)\n // +-- c1\n // +-- f (c2)\n // +-- c2 <-- pruning this would be bad\n\n const mask = node.parent !== target &&\n node.parent.parent !== target &&\n node.parent.parent.resolve(dep.name)\n\n if (!mask || mask === dep || node.canReplaceWith(mask))\n node.parent = null\n }\n }\n }\n\n // also place its unmet or invalid peer deps at this location\n // note that dep has now been removed from the virtualRoot set\n // by virtue of being placed in the target's node_modules.\n if (virtualRoot) {\n for (const peerEdge of dep.edgesOut.values()) {\n if (peerEdge.peer && !peerEdge.valid) {\n const peer = virtualRoot.children.get(peerEdge.name)\n const peerPlaced = this[_placeDep](\n peer, dep, peerEdge, peerEntryEdge || edge)\n placed.push(...peerPlaced)\n }\n }\n }\n\n return placed\n }", "function containsEnoughWeakMethods() {\n\n var weakMethodCount = 0;\n\n weakMethodCount+= isObjectKeyEmpty(serviceWorkerRegistrationInfo) ? 0 : 1;\n weakMethodCount+= isObjectKeyEmpty(workboxInfo) ? 0 : 1;\n weakMethodCount+= isObjectKeyEmpty(swEventListenersInfo) ? 0 : 1;\n weakMethodCount+= isObjectKeyEmpty(swMethodsInfo) ? 0 : 1;\n\n return weakMethodCount >= 2;\n}", "function getDependsOnOwnProps(mapToProps) {\n return mapToProps.dependsOnOwnProps !== null && mapToProps.dependsOnOwnProps !== undefined ? Boolean(mapToProps.dependsOnOwnProps) : mapToProps.length !== 1;\n} // Used by whenMapStateToPropsIsFunction and whenMapDispatchToPropsIsFunction,", "function getDependsOnOwnProps(mapToProps) {\n return mapToProps.dependsOnOwnProps !== null && mapToProps.dependsOnOwnProps !== undefined ? Boolean(mapToProps.dependsOnOwnProps) : mapToProps.length !== 1;\n} // Used by whenMapStateToPropsIsFunction and whenMapDispatchToPropsIsFunction,", "function getDependsOnOwnProps(mapToProps) {\n return mapToProps.dependsOnOwnProps !== null && mapToProps.dependsOnOwnProps !== undefined ? Boolean(mapToProps.dependsOnOwnProps) : mapToProps.length !== 1;\n} // Used by whenMapStateToPropsIsFunction and whenMapDispatchToPropsIsFunction,", "function getDependsOnOwnProps(mapToProps) {\n return mapToProps.dependsOnOwnProps !== null && mapToProps.dependsOnOwnProps !== undefined ? Boolean(mapToProps.dependsOnOwnProps) : mapToProps.length !== 1;\n} // Used by whenMapStateToPropsIsFunction and whenMapDispatchToPropsIsFunction,", "function getDependsOnOwnProps(mapToProps) {\n return mapToProps.dependsOnOwnProps !== null && mapToProps.dependsOnOwnProps !== undefined ? Boolean(mapToProps.dependsOnOwnProps) : mapToProps.length !== 1;\n} // Used by whenMapStateToPropsIsFunction and whenMapDispatchToPropsIsFunction,", "function getDependsOnOwnProps(mapToProps) {\n return mapToProps.dependsOnOwnProps !== null && mapToProps.dependsOnOwnProps !== undefined ? Boolean(mapToProps.dependsOnOwnProps) : mapToProps.length !== 1;\n} // Used by whenMapStateToPropsIsFunction and whenMapDispatchToPropsIsFunction,", "function getDependsOnOwnProps(mapToProps) {\n return mapToProps.dependsOnOwnProps !== null && mapToProps.dependsOnOwnProps !== undefined ? Boolean(mapToProps.dependsOnOwnProps) : mapToProps.length !== 1;\n} // Used by whenMapStateToPropsIsFunction and whenMapDispatchToPropsIsFunction,", "function getDependsOnOwnProps(mapToProps) {\n return mapToProps.dependsOnOwnProps !== null && mapToProps.dependsOnOwnProps !== undefined ? Boolean(mapToProps.dependsOnOwnProps) : mapToProps.length !== 1;\n} // Used by whenMapStateToPropsIsFunction and whenMapDispatchToPropsIsFunction," ]
[ "0.6668544", "0.6586864", "0.65442044", "0.6536909", "0.64989215", "0.6491818", "0.6366252", "0.62900925", "0.6215448", "0.6205266", "0.59345293", "0.59084374", "0.5782645", "0.57522196", "0.57522196", "0.573824", "0.5731477", "0.5723653", "0.5717823", "0.5668789", "0.5668728", "0.5664392", "0.56170577", "0.55422974", "0.55029714", "0.54994303", "0.54839176", "0.5451224", "0.54431725", "0.5430671", "0.5414743", "0.5402247", "0.5402247", "0.53912747", "0.5386646", "0.5386646", "0.53809756", "0.5376445", "0.5376315", "0.53760105", "0.5369828", "0.53547287", "0.53516614", "0.5329245", "0.5321237", "0.5320825", "0.531655", "0.5309152", "0.53052324", "0.53050935", "0.53010297", "0.53010297", "0.529747", "0.528024", "0.52630126", "0.52308595", "0.5230428", "0.52235", "0.52216876", "0.52216876", "0.52216876", "0.52216876", "0.52216876", "0.52216876", "0.52216876", "0.52216876", "0.52216876", "0.52216876", "0.5218976", "0.5188399", "0.514968", "0.514275", "0.5142442", "0.51355433", "0.5130453", "0.5128827", "0.5094692", "0.5083421", "0.50811476", "0.5076232", "0.50541157", "0.50437266", "0.50294614", "0.5021391", "0.5016477", "0.49975845", "0.4996913", "0.4996391", "0.49700195", "0.49700195", "0.49688783", "0.49635908", "0.4961274", "0.4961274", "0.4961274", "0.4961274", "0.4961274", "0.4961274", "0.4961274", "0.4961274" ]
0.71695656
0
recursively walk children, building a parent path as we go, return true when a circular path is encountered
function walkDeps(childs, path, tree) { for (var i = 0, size = childs.length; i < size; i++) { var cur = childs[i]; // check if the path contains the child (a circular dependency) if (path.indexOf(cur) > -1) { path.push(cur); return true; } // walk the children of this child var curChilds = tree[cur]; if (curChilds != null) { // push and pop the child before and after the sub-walk path.push(cur); // recursively walk children var res = walkDeps(curChilds, path, tree); if (res) return res; path.pop(); } } return false; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function isParent(thing, relative) {\n var i;\n var temp;\n if (thing === relative) {\n return true;\n }\n if (!thing.children) {\n return false;\n }\n for (i = 0; i < thing.children.length; i++) {\n if (isParent(thing.children[i], relative)) {\n return true;\n }\n }\n return false;\n }", "function checkChildren(menu, traversed, menus) {\n for (var j = 0; j < menu.child_ids.length; j++) { // Iterate over the children of this menu\n var childId = menu.child_ids[j];\n if (traversed.includes(childId)) { // We have already been to this node which means there is a cyclical reference\n return false;\n } else {\n traversed.push(childId); // Track that we have been to this menu\n return checkChildren(getMenuWithId(menus, childId), traversed, menus); // Recursively call this function to continue traversing through child menus\n }\n }\n return true; // We have no children left to traverse so this is a valid menu\n}", "function traverse(path, current, name) {\n if ((typeof(current) == \"object\") && (path.hasOwnProperty(name)) && (name != 'parent')) {\n return true;\n }\n return false;\n }", "isParent(path, another) {\n return path.length + 1 === another.length && Path.compare(path, another) === 0;\n }", "isParent(path, another) {\n return path.length + 1 === another.length && Path.compare(path, another) === 0;\n }", "function all(children, parent) {\n var length = children.length\n var index = -1\n var child\n\n stack.push(parent)\n\n while (++index < length) {\n child = children[index]\n\n if (child && one(child) === false) {\n return false\n }\n }\n\n stack.pop()\n\n return true\n }", "function all(children, parent) {\n var length = children.length\n var index = -1\n var child\n\n stack.push(parent)\n\n while (++index < length) {\n child = children[index]\n\n if (child && one(child) === false) {\n return false\n }\n }\n\n stack.pop()\n\n return true\n }", "function all(children, parent) {\n var length = children.length\n var index = -1\n var child\n\n stack.push(parent)\n\n while (++index < length) {\n child = children[index]\n\n if (child && one(child) === false) {\n return false\n }\n }\n\n stack.pop()\n\n return true\n }", "function all(children, parent) {\n var length = children.length\n var index = -1\n var child\n\n stack.push(parent)\n\n while (++index < length) {\n child = children[index]\n\n if (child && one(child) === false) {\n return false\n }\n }\n\n stack.pop()\n\n return true\n }", "function all(children, parent) {\n var length = children.length\n var index = -1\n var child\n\n stack.push(parent)\n\n while (++index < length) {\n child = children[index]\n\n if (child && one(child) === false) {\n return false\n }\n }\n\n stack.pop()\n\n return true\n }", "function all(children, parent) {\n var length = children.length\n var index = -1\n var child\n\n stack.push(parent)\n\n while (++index < length) {\n child = children[index]\n\n if (child && one(child) === false) {\n return false\n }\n }\n\n stack.pop()\n\n return true\n }", "function isCyclic(curr, courseDict, checked, path) {\n // bottom cases\n if (checked[curr]) {\n // this node has been checked, no cycle would be formed with this node\n return false\n }\n if (path[curr]) {\n // come across a previously visited node, ie. detected the cycle\n return true\n }\n // no following courses, no loop\n if (!courseDict.has(curr)) {\n return false\n }\n // before backtracking, mark the node in the path\n path[curr] = true\n \n let ret = false\n // postorder DFS, to visit all its children first\n const dependentCourses = courseDict.get(curr)\n for (let i = 0; i < dependentCourses.length; i++) {\n ret = isCyclic(dependentCourses[i], courseDict, checked, path)\n if (ret) break;\n }\n \n // after the visits of children, we come back to process the node itself\n // remove the node from the path\n path[curr] = false\n \n // now that we've visited the nodes in the downstream,\n // we complete the check of this node\n checked[curr] = true\n return ret\n}", "deleteIfOnlyOneChild () {\n let child\n\n if (this.left && !this.right) child = this.left\n if (!this.left && this.right) child = this.right\n if (!child) return false\n\n // Root\n if (!this.parent) {\n this.key = child.key\n this.data = child.data\n\n this.left = null\n if (child.left) {\n this.left = child.left\n child.left.parent = this\n }\n\n this.right = null\n if (child.right) {\n this.right = child.right\n child.right.parent = this\n }\n\n return true\n }\n\n if (this.parent.left === this) {\n this.parent.left = child\n child.parent = this.parent\n } else {\n this.parent.right = child\n child.parent = this.parent\n }\n\n return true\n }", "inPath(state) {\n if (state === this.state) {\n return true;\n }\n else if (this.parent === null) {\n return false;\n }\n else {\n return this.parent.inPath(state);\n }\n }", "function walkTree(tree) {\n if(tree.value === target) {\n result = true;\n }\n for(var i = 0; i < tree.children.length; i +=1) {\n walkTree(tree.children[i]);\n }\n return result;\n }", "isCyclic() {\n return !this.isEnd && this.descendants.every(desc => desc == this);\n }", "function all(children, parent) {\n var step = reverse ? -1 : 1;\n var max = children.length;\n var min = -1;\n var index = (reverse ? max : min) + step;\n var child;\n\n while (index > min && index < max) {\n child = children[index];\n\n if (child && one(child, index, parent) === false) {\n return false;\n }\n\n index += step;\n }\n\n return true;\n }", "function findChildren(parent, parents, children) {\n\n var childGroup = [];\n var cond = false;//condition\n\n\n for (var j in parents) {//looping through all parents\n\n if (parent == parents[j]) {\n cond = true;//condition filled\n childGroup.push(children[j]);\n }\n\n\n }\n\n if (cond) {//if 1 or more children\n for (var i = 0; i < childGroup.length; i++) {\n if (findChildren(childGroup[i], parents, children).length == 0) {//breaking at last child\n break;\n }\n findChildren(childGroup[i], parents, children);//recursion\n\n }\n\n }\n return childGroup;\n}", "function checkIfWeCanGoDeeper () {\n return trieRemainderPath.length > 0 && !isExternalLink(currentNode)\n }", "isChild(path, another) {\n return path.length === another.length + 1 && Path.compare(path, another) === 0;\n }", "isChild(path, another) {\n return path.length === another.length + 1 && Path.compare(path, another) === 0;\n }", "hasParent() {\n return this._ancestors.size() !== 0;\n }", "function isChild(_x2, _x3) {\n var _again = true;\n\n _function: while (_again) {\n _again = false;\n var thing = _x2,\n relative = _x3;\n\n if (thing === relative) {\n return true;\n }\n if (!thing.parent) {\n return false;\n }\n _x2 = thing.parent;\n _x3 = relative;\n _again = true;\n continue _function;\n }\n }", "hasCycleFrom(start) {\n const stack = [{ node: start, visited: new Set([start]), lastVisited: null }];\n while (stack.length) {\n const current = stack.pop();\n for (let node of current.node.adjacent.values()) {\n if (current.lastVisited != node) {\n if (current.visited.has(node)) return true;\n else {\n const visited = new Set([...current.visited]);\n visited.add(node);\n stack.push({ node: node, visited: visited, lastVisited: current.node });\n }\n }\n }\n }\n return false;\n }", "function isParentOf(parent,child){\n\tif(!parent || !child) return false;\n\tif(parent == child) return true;\n\tif(child.parentNode){\n\t\twhile(child = child.parentNode){\n\t\t\tif(parent == child) return true;\t\t\t\n\t\t}\n\t}\n\treturn false;\n}", "function checkChildren(target){\n if(target.selected)\n return true;\n else if(target.children){\n for(var i=0; i<target.children.length; i++){\n if(checkChildren(target.children[i]))\n return true\n }\n }\n else if(target._children){\n for(var i=0; i<target._children.length; i++){\n if(checkChildren(target._children[i]))\n return true\n }\n }\n return false;\n }", "async function dfs(node)\n{\n\tif(!found)\n\t{\n\t\tawait delay(10);\n\t\tif(node.isTraversed() || node.isWall())\n\t\t{\n\t\t\treturn;\n\t\t}\n\t\telse if(node.isEnd())\n\t\t{\n\t\t\tprint('END FOUND');\n\t\t\tfound = true;\n\t\t\tSTART.setStart();\n\t\t}\n\t\telse\n\t\t{\n\t\t\tnode.setTraversed();\n\n\t\t\tif(node.right != null && !node.right.isTraversed())\n\t\t\t{\n\t\t\t\tnode.right.parent = node;\n\t\t\t\tawait dfs(node.right);\n\t\t\t}\n\t\t\tif(node.bottom != null && !node.bottom.isTraversed())\n\t\t\t{\n\t\t\t\tnode.bottom.parent = node;\n\t\t\t\tawait dfs(node.bottom);\n\t\t\t}\n\t\t\tif(node.left != null && !node.left.isTraversed())\n\t\t\t{\n\t\t\t\tnode.left.parent = node;\n\t\t\t\tawait dfs(node.left);\n\t\t\t}\n\t\t\tif(node.top != null && !node.top.isTraversed())\n\t\t\t{\n\t\t\t\tnode.top.parent = node;\n\t\t\t\tawait dfs(node.top);\n\t\t\t}\n\t\t}\n\t}\n\n\tif(!node.isStart() && found && node.parent != null)\n\t{\n\t\tawait delay(15);\n\t\tif(!node.parent.isStart())node.parent.setPath();\n\t}\n}", "function isTree(vertex) {\n // I had this problem to whiteboard at outco, full disclosure\n // to be a tree, you can only be pointed to by one other node\n // so if we have a set of children that have been pointed to, we can check against that\n \n let seenNodes = new Set();\n let queue = [vertex];\n \n while (queue.length > 0) {\n let current = queue.shift();\n if (current.edges.length > 0) {\n current.edges.forEach( (node) => {\n if (seenNodes.has(node.value)) {\n return false; //this edge has already been pointed to by another vertex, not a tree\n } else {\n queue.push(node);\n seenNodes.add(node.value);\n }\n })\n }\n }\n \n //if we have made it through every vertex, checked its \n //edges and still never saw a duplicate child, we can \n // then know we have a valid tree\n return true;\n}", "function isChildOf(parent, child) { \r\n\r\n let node = child.parentNode; \r\n \r\n // keep iterating unless null \r\n while (node != null) { \r\n \tif (node == parent) { \r\n\r\n return true; \r\n } \r\n node = node.parentNode; \r\n } \r\n return false; \r\n}", "function dfsHelper(course) {\n // Base Case #1:\n // If the course has already been visited, we have detected\n // a circular dependency, which means the schedule cannot be completed\n if (visitedSet[course] === true) return false;\n\n // Base Case #2:\n // If the course has no dependencies, we know it can always be\n // completed no matter what\n if (prerequisitesMap[`${course}`].length < 1) return true;\n\n // If we get to here it means the course has prerequisites, so we want\n // to mark the course as visited and search through its prerequisites\n // until we hit our base cases\n visitedSet[course] = true;\n const coursePrerequisites = prerequisitesMap[`${course}`];\n for (let prereqIndex = 0; prereqIndex < coursePrerequisites.length; prereqIndex ++) {\n if (!dfsHelper(coursePrerequisites[prereqIndex])) return false;\n }\n\n visitedSet[course] = false;\n prerequisitesMap[`${course}`] = [];\n return true;\n }", "function treeForEachAncestor(tree, action, includeSelf) {\n var node = includeSelf ? tree : tree.parent;\n while (node !== null) {\n if (action(node)) {\n return true;\n }\n node = node.parent;\n }\n return false;\n}", "function checkLinks(nodes) {\n var _iterator139 = _createForOfIteratorHelper(nodes),\n _step139;\n\n try {\n for (_iterator139.s(); !(_step139 = _iterator139.n()).done;) {\n var node = _step139.value;\n\n var _iterator140 = _createForOfIteratorHelper(node.children),\n _step140;\n\n try {\n for (_iterator140.s(); !(_step140 = _iterator140.n()).done;) {\n var child = _step140.value;\n\n if (child.parent !== node) {\n // log.error('Dataflow graph is inconsistent.', node, child);\n return false;\n }\n }\n } catch (err) {\n _iterator140.e(err);\n } finally {\n _iterator140.f();\n }\n\n if (!checkLinks(node.children)) {\n return false;\n }\n }\n } catch (err) {\n _iterator139.e(err);\n } finally {\n _iterator139.f();\n }\n\n return true;\n }", "function have_any_children(relationship_type, relative) {\n\tif (relationship_type == 'father' || relationship_type == 'mother' || \n\t\t\trelationship_type == 'maternal_grandfather' || relationship_type == 'maternal_grandmother' || \n\t\t\trelationship_type == 'paternal_grandfather' || relationship_type == 'paternal_grandmother') return false;\n\t\t\t\n\tvar parent_status = false;\n\t$.each(personal_information, function (key, item) {\n\t\tif (item != null && item.parent_id != null && item.parent_id.hashCode() == relative.id.hashCode()) {\n\t\t\tparent_status = true;\n\t\t}\n\t});\n\treturn parent_status;\n}", "isPath(start, end) {\n let result = false;\n let visited = {};\n const adjacencyList = this.adjacencyList;\n\n const DFS = (start, end) => {\n if (!start) return null;\n if (start === end) return (result = true);\n visited[start] = true;\n adjacencyList[start].forEach((neighbor) => {\n if (!visited[neighbor]) {\n return DFS(neighbor, end);\n }\n });\n };\n DFS(start, end);\n\n return result;\n }", "function isChildOf(node, parent) {\n\t\twhile (node) {\n\t\t\tif (parent === node) {\n\t\t\t\treturn true;\n\t\t\t}\n\n\t\t\tnode = node.parentNode;\n\t\t}\n\n\t\treturn false;\n\t}", "function isChildOf(node, parent) {\n\t\twhile (node) {\n\t\t\tif (parent === node) {\n\t\t\t\treturn true;\n\t\t\t}\n\n\t\t\tnode = node.parentNode;\n\t\t}\n\n\t\treturn false;\n\t}", "function isChildOf(node, parent) {\n\t\twhile (node) {\n\t\t\tif (parent === node) {\n\t\t\t\treturn true;\n\t\t\t}\n\n\t\t\tnode = node.parentNode;\n\t\t}\n\n\t\treturn false;\n\t}", "function modify_child_Parent_relationship() {\n\t\n\tvar parent_index = 0, child_index = 1;\n\t\n\t\n\n\tparent = modify_Parent_Child_relationship_queue[parent_index].node,\n\tchild = modify_Parent_Child_relationship_queue[child_index].node;\n\t\n\t//If I get here no matter what I have to clear the queue\n\tmodify_Parent_Child_relationship_queue.length = 0;\n\t\n\tif ( parent === child ) {\n\t\t//If parent is child i'll delete the earliest clicked element\n\t\t//modify_Parent_Child_relationship_queue.splice(0);\n\t\tLog('Warning: Node ' + parent.id + ' cannot be a parent or child of itself');\n\t\t//modify_Parent_Child_relationship_queue.length = 0;\n\t\treturn;\n\t\t\n\t}\n\t\n\t\n\t//If you clicked on the two nodes and they are already\n\t//parent child but in the reverse order that you clicked\n\t//them break them up\n\tif ( child.animationChildren[parent.id] == parent ) {\n\t\t\n\t\tbreakConnection(child, parent);\t\n\t\t/*Log(\"Breaking Parent - Child ( \"+ parent.id + \" ---> \"\n\t\t + child.id + \" ) relationship\");\t*/\n\t\treturn; \n\t}\n\t\n\t//If they already parent child then break the relationship\n\tif (child.animationParent == parent ) {\n\t\tbreakConnection(parent, child);\t\n\t\t/*Log(\"Breaking Parent - Child ( \"+ parent.id + \" ---> \"\n\t\t + child.id + \" ) relationship\");*/\n\t\t \n\t\treturn; \n\t}\n\t\t\n\t//If child already has parent... See yaaaa\n\tif( (child.animationParent && child.animationParent != parent && max_number_of_parents<=1)){\n\t\tLog('Warning: No node including Node ' + child.id +\n\t\t ' can have more than one parent');\n\t\treturn;\t\n\t}\n\t\n\tif( Object.keys(parent.animationChildren).length \n\t\t>= max_number_of_children && parent.animationChildren[child.id]!=child ){\n\t\tLog('Warning: No node including Node ' + parent.id +\n\t\t ' can have more than '+ max_number_of_children + ' child(ren)');\n\t\t\treturn;\n\t\t\n\t\t}\n\t\t\n\t\n\tif ( parent.getLineConnectedToNode[child.id] ||\n\t child.getLineConnectedToNode[parent.id]) {\n\t\t\n\t\tbreakConnection( parent, child, true);\n\t\t//Lets disconnect them if theyre not parent-child\n\t\t\n\t\t \n\t\tLog(\"Breaking Connection from Node \"+ parent.id + \" to Node \"\n\t\t\t+ child.id );\n\t\t \n\t\t return;\n\t}\t\n\t\t\n\tcreateParent_Child_Relationship(parent, child); \n\t \n\t\n}", "function expandParents(node) {\n\t// set shortcut to the tree\n\tvar tree = Ext.getCmp(\"doctree\");\n\t// get rootnode for tree\n\tvar root = tree.getRootNode();\n\t// if node is equal to root, stop iteration\n\tif(node==root) {\n\t\treturn true;\n\t}\n\t// expand parent node\n\tnode.parentNode.expand();\n\t// recall function to recurse up the tree\n\texpandParents(node.parentNode);\n}", "function detectCycleBFS(graph) {\n if (!graph) return false\n const vertices = graph.getVerticeCount()\n const visited = Array(vertices).fill(false)\n // initialize every parent vertex to -1\n const parent = Array(vertices).fill(-1)\n // the outer loop here to handle disconnected graphs\n for (let i = 0; i < vertices; i++) {\n // when a current vertex hasn't been visited, we put into queue and start visiting this\n // vertex\n if (!visited[i]) {\n const queue = [i]\n while (queue.length > 0) {\n let curr = queue.shift()\n // visit this vertex\n visited[curr] = true\n let neighbour = graph.getEdges(curr)\n // go through the neighbours of this vertex\n while (neighbour !== null) {\n // if current neighbour hasn't been visited and is not in queue\n // we push current vertex to queue and set the parent relationship\n if (!visited[neighbour.data] && !queue.includes(neighbour.data)) {\n visited[neighbour.data] = true\n queue.push(neighbour.data)\n parent[neighbour.data] = curr\n } else if (neighbour.data !== parent[curr]) {\n // if current neighbour is already visited, because graph is undirected,\n // we check that this neighbour is not the parent vertex that found it\n // in the case that it's not the parent of 'curr', it means we are seeing\n // a neighbour that's been previously visited by a parent node. because\n // graph is undirected, we now have a cycle\n return true\n }\n neighbour = neighbour.next\n }\n }\n }\n }\n return false\n}", "function isChildRoute(parentRoute, childRoute) {\n let route = childRoute;\n while (route) {\n route = route.parent;\n if (route === parentRoute) {\n return true;\n }\n }\n return false;\n }", "function findChildren(person){\n let foundChildren = people.filter(function(person1){\n if (person1.parents.includes(person.id)){\n return true;\n }\n else{\n return false;\n }\n })\n return foundChildren + findChildren(foundChildren);\n\n }", "has_parent_node(){\n return this.parent_node != null;\n }", "get hasChildren() {}", "hasChildren() {\n return this.item.directories.length > 0;\n }", "function isChildRoute(parentRoute, childRoute) {\n let route = childRoute;\n while (route) {\n route = route.parent;\n if (route === parentRoute) {\n return true;\n }\n }\n return false;\n}", "function isChildRoute(parentRoute, childRoute) {\n let route = childRoute;\n while (route) {\n route = route.parent;\n if (route === parentRoute) {\n return true;\n }\n }\n return false;\n}", "function pointerAlreadyInPath(pointer, basePath, parent, specmap) {\n var _context4, _context6;\n\n var refs = specmapRefs.get(specmap);\n\n if (!refs) {\n // Stores all resolved references of a specmap instance.\n // Schema: path -> pointer (path's $ref value).\n refs = {};\n specmapRefs.set(specmap, refs);\n }\n\n var parentPointer = arrayToJsonPointer(parent);\n\n var fullyQualifiedPointer = _babel_runtime_corejs3_core_js_stable_instance_concat__WEBPACK_IMPORTED_MODULE_4___default()(_context4 = \"\".concat(basePath || '<specmap-base>', \"#\")).call(_context4, pointer); // dirty hack to strip `allof/[index]` from the path, in order to avoid cases\n // where we get false negatives because:\n // - we resolve a path, then\n // - allOf plugin collapsed `allOf/[index]` out of the path, then\n // - we try to work on a child $ref within that collapsed path.\n //\n // because of the path collapse, we lose track of it in our specmapRefs hash\n // solution: always throw the allOf constructs out of paths we store\n // TODO: solve this with a global register, or by writing more metadata in\n // either allOf or refs plugin\n\n\n var safeParentPointer = parentPointer.replace(/allOf\\/\\d+\\/?/g, ''); // Case 1: direct cycle, e.g. a.b.c.$ref: '/a.b'\n // Detect by checking that the parent path doesn't start with pointer.\n // This only applies if the pointer is internal, i.e. basePath === rootPath (could be null)\n\n var rootDoc = specmap.contextTree.get([]).baseDoc;\n\n if (basePath == rootDoc && pointerIsAParent(safeParentPointer, pointer)) {\n // eslint-disable-line\n return true;\n } // Case 2: indirect cycle\n // ex1: a.$ref: '/b' & b.c.$ref: '/b/c'\n // ex2: a.$ref: '/b/c' & b.c.$ref: '/b'\n // Detect by retrieving all the $refs along the path of parent\n // and checking if any starts with pointer or vice versa.\n\n\n var currPath = '';\n var hasIndirectCycle = parent.some(function (token) {\n var _context5;\n\n currPath = _babel_runtime_corejs3_core_js_stable_instance_concat__WEBPACK_IMPORTED_MODULE_4___default()(_context5 = \"\".concat(currPath, \"/\")).call(_context5, escapeJsonPointerToken(token));\n return refs[currPath] && refs[currPath].some(function (ref) {\n return pointerIsAParent(ref, fullyQualifiedPointer) || pointerIsAParent(fullyQualifiedPointer, ref);\n });\n });\n\n if (hasIndirectCycle) {\n return true;\n } // No cycle, this ref will be resolved, so stores it now for future detection.\n // No need to store if has cycle, as parent path is a dead-end and won't be checked again.\n\n\n refs[safeParentPointer] = _babel_runtime_corejs3_core_js_stable_instance_concat__WEBPACK_IMPORTED_MODULE_4___default()(_context6 = refs[safeParentPointer] || []).call(_context6, fullyQualifiedPointer);\n return undefined;\n}", "function pointerAlreadyInPath(pointer, basePath, parent, specmap) {\n var _context4, _context6;\n\n var refs = specmapRefs.get(specmap);\n\n if (!refs) {\n // Stores all resolved references of a specmap instance.\n // Schema: path -> pointer (path's $ref value).\n refs = {};\n specmapRefs.set(specmap, refs);\n }\n\n var parentPointer = arrayToJsonPointer(parent);\n\n var fullyQualifiedPointer = _babel_runtime_corejs3_core_js_stable_instance_concat__WEBPACK_IMPORTED_MODULE_4___default()(_context4 = \"\".concat(basePath || '<specmap-base>', \"#\")).call(_context4, pointer); // dirty hack to strip `allof/[index]` from the path, in order to avoid cases\n // where we get false negatives because:\n // - we resolve a path, then\n // - allOf plugin collapsed `allOf/[index]` out of the path, then\n // - we try to work on a child $ref within that collapsed path.\n //\n // because of the path collapse, we lose track of it in our specmapRefs hash\n // solution: always throw the allOf constructs out of paths we store\n // TODO: solve this with a global register, or by writing more metadata in\n // either allOf or refs plugin\n\n\n var safeParentPointer = parentPointer.replace(/allOf\\/\\d+\\/?/g, ''); // Case 1: direct cycle, e.g. a.b.c.$ref: '/a.b'\n // Detect by checking that the parent path doesn't start with pointer.\n // This only applies if the pointer is internal, i.e. basePath === rootPath (could be null)\n\n var rootDoc = specmap.contextTree.get([]).baseDoc;\n\n if (basePath === rootDoc && pointerIsAParent(safeParentPointer, pointer)) {\n // eslint-disable-line\n return true;\n } // Case 2: indirect cycle\n // ex1: a.$ref: '/b' & b.c.$ref: '/b/c'\n // ex2: a.$ref: '/b/c' & b.c.$ref: '/b'\n // Detect by retrieving all the $refs along the path of parent\n // and checking if any starts with pointer or vice versa.\n\n\n var currPath = '';\n var hasIndirectCycle = parent.some(function (token) {\n var _context5;\n\n currPath = _babel_runtime_corejs3_core_js_stable_instance_concat__WEBPACK_IMPORTED_MODULE_4___default()(_context5 = \"\".concat(currPath, \"/\")).call(_context5, escapeJsonPointerToken(token));\n return refs[currPath] && refs[currPath].some(function (ref) {\n return pointerIsAParent(ref, fullyQualifiedPointer) || pointerIsAParent(fullyQualifiedPointer, ref);\n });\n });\n\n if (hasIndirectCycle) {\n return true;\n } // No cycle, this ref will be resolved, so stores it now for future detection.\n // No need to store if has cycle, as parent path is a dead-end and won't be checked again.\n\n\n refs[safeParentPointer] = _babel_runtime_corejs3_core_js_stable_instance_concat__WEBPACK_IMPORTED_MODULE_4___default()(_context6 = refs[safeParentPointer] || []).call(_context6, fullyQualifiedPointer);\n return undefined;\n}", "function isCousin(relationshipData, includeSpouses){\n var path = relationshipData.path,\n isAncestor = false,\n isDescendant = false,\n isCousin = false;\n \n // Skip the first person because it's the start person \n for(var i = 1; i < path.length; i++){\n var relationship = path[i].rel;\n \n if(relationship === 'child'){\n \n // If the previous position in the path was an\n // ancestor (direct mother and father relationships)\n // then we know this person is a cousin.\n if(isAncestor){\n isAncestor = false;\n isCousin = true;\n }\n \n // If the person isn't a cousin then we must be\n // travelling down a direct descendant line\n if(!isCousin){\n isDescendant = true;\n }\n }\n \n else if(relationship === 'mother' || relationship === 'father'){ \n \n // Ignore ancestors of descendants and cousins. We \n // care about the ancestors of descendants that are \n // also our descendants but the path to them is more \n // direct therefore the only people we see here are \n // those ancestors of the descendant that are out of scope\n if(isDescendant || isCousin){\n return false;\n }\n \n // We are still traveling up the direct ancestral line\n isAncestor = true;\n }\n \n // If we see any other relationship (right now just\n // a spouse) then end. Direct ancestors, descendants,\n // and cousins can be visited through spouse relationships\n // but the most direct paths will never include them\n // therefore we can assume that anyone visited through\n // a spouse relationship is outside of our scope.\n // If we want to include spouses and we're at the end\n // then this person is valid; otherwise the person is invalid.\n else if(includeSpouses && i === path.length - 1){\n return true;\n } else {\n return false;\n }\n }\n \n // The person is valid if we get here because we\n // short circuit as soon as we know someone is invalid\n return true;\n}", "function cycleCheck(node, path) {\n if (!node) {\n return;\n }\n const children = [...node.loadDependencyNames, ...node.lazyDependencyNames];\n for (const child of children) {\n if (path.indexOf(child) !== -1) {\n throw new Error(`Cyclic dependency detected! Module ${node.name} has a dependency ${child} that is also a parent!`);\n }\n cycleCheck(moduleDefinitions[child], [...path, child]);\n }\n }", "detectLoop(){\n var walk = this.head.next;\n\n if (walk && walk.next) {\n var run = walk.next.next;\n }\n\n while (run) {\n\n if (walk === run) {\n return walk;\n }\n\n if (run.next) {\n walk = walk.next;\n run = run.next.next;\n } else {\n return false;\n }\n }\n }", "function checkCircular(type, found) {\n if (found[type]) {\n logger.throwArgumentError(\"circular type reference to \" + JSON.stringify(type), \"types\", types);\n }\n found[type] = true;\n Object.keys(links[type]).forEach(function (child) {\n if (!parents[child]) {\n return;\n }\n // Recursively check children\n checkCircular(child, found);\n // Mark all ancestors as having this decendant\n Object.keys(found).forEach(function (subtype) {\n subtypes[subtype][child] = true;\n });\n });\n delete found[type];\n }", "function checkParents (gobj) {\n var ret = {}, \n checkOneParent = function (index, parent) {\n var parentInfo = queueMap[parent.id],\n edgeType = getEdgeForParentAtIndex(gobj, index);\n \n if( parentInfo && !parentInfo.isSelectedZ) {\n //affected parent\n switch (edgeType) {\n case 'rEdge':\n //an rEdge parent must have this gobj as its controller or \n //its incompatible - even if it has no controller\n if (queueMap[parent.id].controller !== gobj) {\n ret.incompatibleParent = true;\n }\n break;\n case 'dEdge':\n case 'iEdge':\n case 'tEdge':\n if (parentInfo.transCode !== queueMap[gobj.id].transCode) {\n ret.incompatibleParent = true;\n }\n break;\n } \n \n if (ret[edgeType] === undefined) {\n ret[edgeType] = 'allAffected';\n } else if (ret[edgeType] === 'noneAffected') {\n ret[edgeType] = 'someAffected';\n }\n } else {\n //unaffected parent\n if (ret[edgeType] === undefined) {\n ret[edgeType] = 'noneAffected';\n } else if (ret[edgeType] === 'allAffected') {\n ret[edgeType] = 'someAffected';\n }\n }\n \n return true; //keep going\n };\n \n gobj.eachParent(checkOneParent, true);\n \n return ret;\n }", "hasCycle() {\n for (let node of this.nodes.values()) if (this.hasCycleFrom(node)) return true;\n return false;\n }", "function checkCircular(type, found) {\n if (found[type]) {\n logger.throwArgumentError(`circular type reference to ${JSON.stringify(type)}`, \"types\", types);\n }\n found[type] = true;\n Object.keys(links[type]).forEach((child) => {\n if (!parents[child]) {\n return;\n }\n // Recursively check children\n checkCircular(child, found);\n // Mark all ancestors as having this decendant\n Object.keys(found).forEach((subtype) => {\n subtypes[subtype][child] = true;\n });\n });\n delete found[type];\n }", "function checkCircular(type, found) {\n if (found[type]) {\n logger.throwArgumentError(`circular type reference to ${JSON.stringify(type)}`, \"types\", types);\n }\n found[type] = true;\n Object.keys(links[type]).forEach((child) => {\n if (!parents[child]) {\n return;\n }\n // Recursively check children\n checkCircular(child, found);\n // Mark all ancestors as having this decendant\n Object.keys(found).forEach((subtype) => {\n subtypes[subtype][child] = true;\n });\n });\n delete found[type];\n }", "_parentMarkedDirty(onlySelf) {\n const parentDirty = this._parent && this._parent.dirty;\n return !onlySelf && !!parentDirty && !this._parent._anyControlsDirty();\n }", "function isChild(parent, child) {\n\t\tvar node = child.parentNode;\n\t\t\n\t\twhile (node != null) {\n\t\t\tif(node == parent){\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\tnode = node.parentNode;\n\t\t}\n\t\treturn false;\n\t}", "function _handleChildParentRelationship(jQElement) {\n // If the selected node is a child:\n if ( _.isEmpty(_.toArray(jQElement.children('ul'))) ) {\n var childrenStatuses = _.uniq(\n _.map(jQElement.parent().find('input[type=\"checkbox\"]'), function(elem) {\n return $(elem).prop('checked');\n })\n );\n \n // Check to see if any children are checked.\n if (_.indexOf(childrenStatuses, true) !== -1) {\n // Check the parent node.\n jQElement.parent().parent().children('span').children('input[type=\"checkbox\"]').prop('checked', true);\n } else {\n // Uncheck the parent node.\n jQElement.parent().parent().children('span').children('input[type=\"checkbox\"]').prop('checked', false);\n }\n }\n }", "_parentMarkedDirty(onlySelf) {\n const parentDirty = this._parent && this._parent.dirty;\n return !onlySelf && !!parentDirty && !this._parent._anyControlsDirty();\n }", "_parentMarkedDirty(onlySelf) {\n const parentDirty = this._parent && this._parent.dirty;\n return !onlySelf && !!parentDirty && !this._parent._anyControlsDirty();\n }", "_parentMarkedDirty(onlySelf) {\n const parentDirty = this._parent && this._parent.dirty;\n return !onlySelf && !!parentDirty && !this._parent._anyControlsDirty();\n }", "_parentMarkedDirty(onlySelf) {\n const parentDirty = this._parent && this._parent.dirty;\n return !onlySelf && !!parentDirty && !this._parent._anyControlsDirty();\n }", "_parentMarkedDirty(onlySelf) {\n const parentDirty = this._parent && this._parent.dirty;\n return !onlySelf && !!parentDirty && !this._parent._anyControlsDirty();\n }", "_parentMarkedDirty(onlySelf) {\n const parentDirty = this._parent && this._parent.dirty;\n return !onlySelf && parentDirty && !this._parent._anyControlsDirty();\n }", "_parentMarkedDirty(onlySelf) {\n const parentDirty = this._parent && this._parent.dirty;\n return !onlySelf && parentDirty && !this._parent._anyControlsDirty();\n }", "function someRecursive(arr, cb) {\n if(arr.length === 0) return false;\n return cb(arr[0]) === true ? true : someRecursive(arr.slice(1), cb);\n}", "function getAncestry() {\n var path = this;\n var paths = [];\n do {\n paths.push(path);\n } while (path = path.parentPath);\n return paths;\n}", "function inType() {\n var path = this;\n while (path) {\n var _arr3 = arguments;\n\n for (var _i3 = 0; _i3 < _arr3.length; _i3++) {\n var type = _arr3[_i3];\n if (path.node.type === type) return true;\n }\n path = path.parentPath;\n }\n\n return false;\n}", "function hasParent(element, parent) {\n var elem = element;\n\n while (elem) {\n if (elem === parent) {\n return true;\n } else if (elem.parentNode) {\n elem = elem.parentNode;\n } else {\n return false;\n }\n }\n\n return false;\n}", "function hasParent(element, parent) {\n var elem = element;\n\n while (elem) {\n if (elem === parent) {\n return true;\n } else if (elem.parentNode) {\n elem = elem.parentNode;\n } else {\n return false;\n }\n }\n\n return false;\n}", "function FindPath (target : BuildingOnGrid) : boolean {\n\tif (target == null || !BuildingCheck(target)) // Check if building is a valid target\n\t\treturn false;\n\t\t\n\t// reset pathing variables and lists\n\tvar found : boolean = false;\n\tfoundPath.Clear();\n\topen.Clear();\n\tnextOpen.Clear();\n\tclosed.Clear();\n\t\n\tvar activeLinkedNeighbors;\n\tvar current : BuildingOnGrid = currentBuilding;\n\topen.Add(current);\n\t\n\twhile (!closed.Contains(target) && current != target && current != null)\n\t{\n\t\tPopulateNextOpen(target);\n\t\tif (nextOpen.Contains(target))\n\t\t{\n\t\t\tcurrent = target;\n\t\t\tcontinue;\n\t\t}\n\t\topen.Clear();\n\t\tfor (var i:int = 0; i < nextOpen.Count; i++)\n\t\t\topen.Add(nextOpen[i]);\n\t\tnextOpen.Clear();\n\t}\n\t\n\tif (current == target && target != null)\n\t{\n\t\tfoundPath.Add(current);\n\t\twhile (current.pathParent != null)\n\t\t{\n\t\t\tfoundPath.Add(current.pathParent);\n\t\t\tcurrent = current.pathParent;\n\t\t}\n\t\tfoundPath.Reverse();\n\t\tfoundPath.RemoveAt(0);\n\t\tfound = true;\n\t}\n\tSetLinkColors();\n\tClearAllPathVars ();\n\treturn found;\n}", "deleteIfLeaf () {\n if (this.left || this.right) return false\n\n // The leaf is itself a root\n if (!this.parent) {\n delete this.key\n this.data = []\n return true\n }\n\n if (this.parent.left === this) this.parent.left = null\n else this.parent.right = null\n\n return true\n }", "function loggedInUserIsParent() {\n if(!loggedInUser.data || !profile.data) return false;\n return _.includes(profile.data.parents, loggedInUser.data.id);\n }", "function tryAppendingOrphansToTree() {\n for (var ic = 0; ic < orphanedChildren.length; ic++) {\n var cleanParentPath = orphanedChildren[ic].cleanParentPath;\n var parentNode = getParentNodeFromPath(cleanParentPath);\n if (parentNode) {\n appendXmlToNode(parentNode, orphanedChildren[ic].dataXml);\n orphanedChildren.splice(ic, 1);\n\n // We just appended new nodes, so run this again. But, wait\n // a tick so the new nodes have time to expand\n setTimeout(function() {\n tryAppendingOrphansToTree();\n });\n return;\n }\n }\n\n // If we didn't find any parent nodes and all the folders have been\n // loaded, then it must mean the parent was collapsed\n if (numFoldersLoaded === _self.expandedNodes.length)\n return onFinish();\n }", "visitNode(visitedNodes, currentNodeStack, id, node) {\n if(currentNodeStack[id]) // If node is in current stack, cycle detected\n return true;\n \n if(visitedNodes[id]) // If node is not in current stack and has already been visited, no need to check it again\n return false;\n \n // Updates flags\n visitedNodes[id] = true;\n currentNodeStack[id] = true;\n\n // Visits node children that are not leaf nodes\n for (let child of node.children) {\n if (child.id && this.visitNode(visitedNodes, currentNodeStack, child.id, child))\n return true;\n }\n \n // After all children have been visited, removes node from stack\n currentNodeStack[id] = false;\n\n return false;\n }", "function detectCycleRecursive(fragment) {\n\t var fragmentName = fragment.name.value;\n\t visitedFrags[fragmentName] = true;\n\n\t var spreadNodes = context.getFragmentSpreads(fragment);\n\t if (spreadNodes.length === 0) {\n\t return;\n\t }\n\n\t spreadPathIndexByName[fragmentName] = spreadPath.length;\n\n\t for (var i = 0; i < spreadNodes.length; i++) {\n\t var spreadNode = spreadNodes[i];\n\t var spreadName = spreadNode.name.value;\n\t var cycleIndex = spreadPathIndexByName[spreadName];\n\n\t if (cycleIndex === undefined) {\n\t spreadPath.push(spreadNode);\n\t if (!visitedFrags[spreadName]) {\n\t var spreadFragment = context.getFragment(spreadName);\n\t if (spreadFragment) {\n\t detectCycleRecursive(spreadFragment);\n\t }\n\t }\n\t spreadPath.pop();\n\t } else {\n\t var cyclePath = spreadPath.slice(cycleIndex);\n\t context.reportError(new _error.GraphQLError(cycleErrorMessage(spreadName, cyclePath.map(function (s) {\n\t return s.name.value;\n\t })), cyclePath.concat(spreadNode)));\n\t }\n\t }\n\n\t spreadPathIndexByName[fragmentName] = undefined;\n\t }", "testOneNodeForCircularPath(dependencyPathTaken, nodeName) {\n logger_1.default.system.debug(`BootDependencyGraph.testOneNodeForCircularPath -- nodeName=${nodeName}`, dependencyPathTaken);\n var circular = false;\n // if node is already in the path previously walked, then must be circular\n if (dependencyPathTaken.includes(nodeName)) {\n dependencyPathTaken.push(nodeName);\n circular = true;\n // else everything okay so far....no circular dependencies yet\n }\n else {\n dependencyPathTaken.push(nodeName);\n let node = this.graph.nodes[nodeName];\n for (const index in node.dependencies) {\n circular = this.testOneNodeForCircularPath(dependencyPathTaken, node.dependencies[index]);\n if (circular) {\n break;\n }\n }\n }\n if (!circular) { // unwind path when not a circular path; otherwise side branches can be in circular dependencyPathTaken (which is used for diagnostics)\n dependencyPathTaken.pop();\n }\n logger_1.default.system.debug(`BootDependencyGraph.testOneNodeForCircularPath done for nodeName=${nodeName} with circular=${circular}`);\n return circular;\n }", "function is_parent(id, data) \n {\n for (key in data) {\n \n // for old response\n// var parentId = data[key].parentId;\n\n // for new response\n var parentId = data[key].parent_id;\n \n if(id == parentId)\n return true; \n }\n return false;\n }", "function check_with_parents(element, css, value, comparison) {\n\n var checkElements = element.add(element.parents());\n var animation_fill_mode, el, returnValue = true;\n\n checkElements.each(function () {\n\n el = $(this);\n\n animation_fill_mode = null;\n\n // Be sure there not have any element animating.\n if (el.hasClass(\"yp-animating\") === false) {\n\n // nowdays a lot website using animation on page loads.\n // the problem is a lot animations has transfrom, opacity etc.\n // This break the system and can't get real value.\n // So I will fix this issue : ).\n animation_fill_mode = el.css(\"animation-fill-mode\");\n\n // Disable it until we get real value.\n if (animation_fill_mode == 'forwards' || animation_fill_mode == 'both') {\n\n // Set none for animation-fill-mode and be sure. using promise.\n $.when(el.css(\"animation-fill-mode\", \"none\")).promise().always(function () {\n\n // Continue after done.\n returnValue = check_with_parents_last(el, css, value, comparison, animation_fill_mode);\n\n if (returnValue === true) {\n return false;\n }\n\n });\n\n } else {\n\n // Continue to last part.\n returnValue = check_with_parents_last(el, css, value, comparison);\n\n if (returnValue === true) {\n return false;\n }\n\n }\n\n } else {\n\n // Continue to last part.\n returnValue = check_with_parents_last(el, css, value, comparison);\n\n if (returnValue === true) {\n return false;\n }\n\n }\n\n });\n\n return returnValue;\n\n }", "hasChildren() {\n if (this.children !== undefined && this.children.length > 0) {\n return true;\n }\n return false;\n }", "isNodeOrChildOf(otherNode) {\n let current = this;\n while (current) {\n if (current === otherNode) {\n return true;\n }\n current = current.parent;\n }\n return false;\n }", "shouldRecurse(stats, maxDepthReached) {\n let { recurseFn } = this.options;\n if (maxDepthReached) {\n // We've already crawled to the maximum depth. So no more recursion.\n return false;\n }\n else if (!stats.isDirectory()) {\n // It's not a directory. So don't try to crawl it.\n return false;\n }\n else if (recurseFn) {\n try {\n // Run the user-specified recursion criteria\n return !!recurseFn(stats);\n }\n catch (err) {\n // An error occurred in the user's code.\n // In Sync and Async modes, this will return an error.\n // In Streaming mode, we emit an \"error\" event, but continue processing\n this.emit(\"error\", err);\n }\n }\n else {\n // No recursion function was specified, and we're within the maximum depth.\n // So crawl this directory.\n return true;\n }\n }", "function hasParent(node) {\n if (_.isEmpty(node.parentLink))\n return false;\n\n var link = node.parentLink;\n if (link.endsWith('workspace/vdbs'))\n return false;\n\n return true;\n }", "inorderTraversal(root) {\r\n const path = []\r\n const rootChildren = root.children\r\n if(rootChildren.length === 0)\r\n path.push(root.val)\r\n else {\r\n let preStack = new Stack();\r\n preStack.push(root)\r\n while(preStack.size!==0) {\r\n const currentNode = preStack.pop()\r\n const currentChildren = currentNode.children\r\n if(currentChildren.length > 0 && !currentNode.visited) {\r\n for (let i=currentChildren.length-1; i>=1; i--) {\r\n preStack.push(currentChildren[i])\r\n }\r\n currentNode.visited = true\r\n preStack.push(currentNode)\r\n preStack.push(currentChildren[0])\r\n } else {\r\n currentNode.visited = false\r\n path.push(currentNode.val)\r\n } \r\n }\r\n }\r\n return path\r\n }", "function detectCycleRecursive(fragment) {\n var fragmentName = fragment.name.value;\n visitedFrags[fragmentName] = true;\n\n var spreadNodes = context.getFragmentSpreads(fragment);\n if (spreadNodes.length === 0) {\n return;\n }\n\n spreadPathIndexByName[fragmentName] = spreadPath.length;\n\n for (var i = 0; i < spreadNodes.length; i++) {\n var spreadNode = spreadNodes[i];\n var spreadName = spreadNode.name.value;\n var cycleIndex = spreadPathIndexByName[spreadName];\n\n if (cycleIndex === undefined) {\n spreadPath.push(spreadNode);\n if (!visitedFrags[spreadName]) {\n var spreadFragment = context.getFragment(spreadName);\n if (spreadFragment) {\n detectCycleRecursive(spreadFragment);\n }\n }\n spreadPath.pop();\n } else {\n var cyclePath = spreadPath.slice(cycleIndex);\n context.reportError(new _error.GraphQLError(cycleErrorMessage(spreadName, cyclePath.map(function (s) {\n return s.name.value;\n })), cyclePath.concat(spreadNode)));\n }\n }\n\n spreadPathIndexByName[fragmentName] = undefined;\n }", "function circularReferenceCheck(shadows) {\n // if any of the current objects to process exist in the queue\n // then throw an error.\n shadows.forEach(function (item) {\n if (item instanceof Object && visited.indexOf(item) > -1) {\n throw new Error('Circular reference error');\n }\n });\n // if none of the current objects were in the queue\n // then add references to the queue.\n visited = visited.concat(shadows);\n }", "set hasChildren(value) {}", "function detectCycleRecursive(fragment) {\n var fragmentName = fragment.name.value;\n visitedFrags[fragmentName] = true;\n\n var spreadNodes = context.getFragmentSpreads(fragment.selectionSet);\n if (spreadNodes.length === 0) {\n return;\n }\n\n spreadPathIndexByName[fragmentName] = spreadPath.length;\n\n for (var i = 0; i < spreadNodes.length; i++) {\n var spreadNode = spreadNodes[i];\n var spreadName = spreadNode.name.value;\n var cycleIndex = spreadPathIndexByName[spreadName];\n\n if (cycleIndex === undefined) {\n spreadPath.push(spreadNode);\n if (!visitedFrags[spreadName]) {\n var spreadFragment = context.getFragment(spreadName);\n if (spreadFragment) {\n detectCycleRecursive(spreadFragment);\n }\n }\n spreadPath.pop();\n } else {\n var cyclePath = spreadPath.slice(cycleIndex);\n context.reportError(new _error.GraphQLError(cycleErrorMessage(spreadName, cyclePath.map(function (s) {\n return s.name.value;\n })), cyclePath.concat(spreadNode)));\n }\n }\n\n spreadPathIndexByName[fragmentName] = undefined;\n }", "previousSiblingHasChildren() {\t\n\t\tvar parent = this.__atom.parent;\n\t\tif (!parent) {\n\t\t\tthrow new Error('There is no parent atom.');\n\t\t}\n\n\t\tvar children = this.__atom.children;\n\t\tvar thisTreePath = this.__atom.treePath;\n\t\tvar thisIndex = -1;\n\t\tfor (var child of children) {\n\t\t\tvar treePath = child.treePath;\n\t\t\tvar isWantedChild = child.treePath === thisTreePath;\n\t\t\tif (isWantedChild) {\n\t\t\t\tthisIndex = children.indexof(child);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\t//get previous sibling\n\t\tvar previousSiblingIndex = thisIndex - 1;\n\t\tvar hasNoPreviousSibling = previousSiblingIndex < 0;\n\t\tif (hasNoPreviousSibling) {\n\t\t\tthrow new Error('There is no previous sibling.');\n\t\t}\n\t\tvar previousSibling = children[previousSiblingIndex];\t\t\n\n\t\treturn previousSibling.hasChildren;\n\t}", "function shouldAddParenthesesToChainElement(path) {\n // Babel, this was implemented before #13735, can use `path.match` as estree does\n const { node, parent, grandparent, key } = path;\n if (\n (node.type === \"OptionalMemberExpression\" ||\n node.type === \"OptionalCallExpression\") &&\n ((key === \"object\" && parent.type === \"MemberExpression\") ||\n (key === \"callee\" &&\n (parent.type === \"CallExpression\" ||\n parent.type === \"NewExpression\")) ||\n (parent.type === \"TSNonNullExpression\" &&\n grandparent.type === \"MemberExpression\" &&\n grandparent.object === parent))\n ) {\n return true;\n }\n\n // ESTree, same logic as babel\n if (\n path.match(\n () => node.type === \"CallExpression\" || node.type === \"MemberExpression\",\n (node, name) => name === \"expression\" && node.type === \"ChainExpression\",\n ) &&\n (path.match(\n undefined,\n undefined,\n (node, name) =>\n (name === \"callee\" &&\n ((node.type === \"CallExpression\" && !node.optional) ||\n node.type === \"NewExpression\")) ||\n (name === \"object\" &&\n node.type === \"MemberExpression\" &&\n !node.optional),\n ) ||\n path.match(\n undefined,\n undefined,\n (node, name) =>\n name === \"expression\" && node.type === \"TSNonNullExpression\",\n (node, name) => name === \"object\" && node.type === \"MemberExpression\",\n ))\n ) {\n return true;\n }\n\n // Babel treat `(a?.b!).c` and `(a?.b)!.c` the same, https://github.com/babel/babel/discussions/15077\n // Use this to align with babel\n if (\n path.match(\n () => node.type === \"CallExpression\" || node.type === \"MemberExpression\",\n (node, name) =>\n name === \"expression\" && node.type === \"TSNonNullExpression\",\n (node, name) => name === \"expression\" && node.type === \"ChainExpression\",\n (node, name) => name === \"object\" && node.type === \"MemberExpression\",\n )\n ) {\n return true;\n }\n\n // This function only handle cases above\n return false;\n}", "isRecursive(destFolder) {\n return destFolder.fullPath.startsWith(this.fullPath);\n }", "function detectCycleRecursive(fragment) {\n if (visitedFrags[fragment.name.value]) {\n return;\n }\n\n var fragmentName = fragment.name.value;\n visitedFrags[fragmentName] = true;\n var spreadNodes = context.getFragmentSpreads(fragment.selectionSet);\n\n if (spreadNodes.length === 0) {\n return;\n }\n\n spreadPathIndexByName[fragmentName] = spreadPath.length;\n\n for (var i = 0; i < spreadNodes.length; i++) {\n var spreadNode = spreadNodes[i];\n var spreadName = spreadNode.name.value;\n var cycleIndex = spreadPathIndexByName[spreadName];\n spreadPath.push(spreadNode);\n\n if (cycleIndex === undefined) {\n var spreadFragment = context.getFragment(spreadName);\n\n if (spreadFragment) {\n detectCycleRecursive(spreadFragment);\n }\n } else {\n var cyclePath = spreadPath.slice(cycleIndex);\n var fragmentNames = cyclePath.slice(0, -1).map(function (s) {\n return s.name.value;\n });\n context.reportError(new _error_GraphQLError__WEBPACK_IMPORTED_MODULE_0__[\"GraphQLError\"](cycleErrorMessage(spreadName, fragmentNames), cyclePath));\n }\n\n spreadPath.pop();\n }\n\n spreadPathIndexByName[fragmentName] = undefined;\n }", "function inType() {\n\t var path = this;\n\t while (path) {\n\t var _arr3 = arguments;\n\n\t for (var _i3 = 0; _i3 < _arr3.length; _i3++) {\n\t var type = _arr3[_i3];\n\t if (path.node.type === type) return true;\n\t }\n\t path = path.parentPath;\n\t }\n\n\t return false;\n\t}", "function inType() {\n\t var path = this;\n\t while (path) {\n\t var _arr3 = arguments;\n\n\t for (var _i3 = 0; _i3 < _arr3.length; _i3++) {\n\t var type = _arr3[_i3];\n\t if (path.node.type === type) return true;\n\t }\n\t path = path.parentPath;\n\t }\n\n\t return false;\n\t}", "_hasLeftChild(parentIndex) {\n const leftChildIndex = (parentIndex * 2) + 1;\n return leftChildIndex < this.size();\n }", "isPresent(data) {\n let current = this.root;\n\n // whille current is not null\n while (current) {\n \n if (data === current.data) {\n\n return true;\n }\n \n if (data < current.data){\n \n current = current.left;\n \n } else {\n \n current = current.right;\n }\n }\n\n return false;\n }", "function hasPath(graph, start, end) {\n\tconst stack = [];\n\tconst visited = new Set();\n\n\tstack.push(start);\n\tvisited.add(start);\n\n\twhile (!stack.length == 0) {\n\t\tlet currentNode = stack.pop();\n\t\t\n\t\tif (currentNode == end) {\n\t\t\treturn true;\n\t\t}\n\t\tlet neighbors = graph[currentNode] || [];\n\t\tfor (let neighbor of neighbors) {\n\t\t\tif (!visited.has(neighbor)) {\n\t\t\t\tstack.push(neighbor);\n\t\t\t\tvisited.add(neighbor);\n\t\t\t}\n\t\t}\n\t}\n\treturn false;\n}", "isElementContained(parent, event) {\n var node = event.target?.parentNode;\n while (node != null) {\n if (node === parent) {\n return true;\n }\n node = node.parentNode;\n }\n return false;\n }" ]
[ "0.65786517", "0.62632096", "0.6141144", "0.6136606", "0.6136606", "0.6067049", "0.6067049", "0.6067049", "0.6067049", "0.6067049", "0.6067049", "0.6026796", "0.59909034", "0.58907455", "0.57857996", "0.57372737", "0.5711421", "0.56910646", "0.5674979", "0.56487083", "0.56487083", "0.556804", "0.54794574", "0.5447713", "0.54424417", "0.539518", "0.53947514", "0.53638726", "0.53445303", "0.5337354", "0.53016114", "0.5299524", "0.52864766", "0.527578", "0.52687824", "0.52687824", "0.52687824", "0.52535945", "0.5248555", "0.52424526", "0.5242047", "0.52372694", "0.52294064", "0.52292067", "0.522812", "0.5225637", "0.5225637", "0.5215957", "0.5211127", "0.52069193", "0.5189222", "0.51877415", "0.5167033", "0.5159777", "0.5154053", "0.51406115", "0.51406115", "0.5119732", "0.5104579", "0.50967354", "0.5094073", "0.5094073", "0.5094073", "0.5094073", "0.5094073", "0.50840926", "0.50840926", "0.5077335", "0.5044807", "0.50421804", "0.5036873", "0.5036873", "0.50361097", "0.50333333", "0.5022483", "0.501794", "0.501455", "0.5009389", "0.5004116", "0.5003849", "0.5002765", "0.49968183", "0.49908844", "0.49873155", "0.49839258", "0.49763274", "0.49728462", "0.4964786", "0.49516144", "0.495025", "0.49465832", "0.49312705", "0.49235427", "0.49169868", "0.49159685", "0.49159685", "0.4915669", "0.49155858", "0.49154302", "0.49152717" ]
0.71117604
0
Given a set of 'options' objects, create a shallow copy, lefttoright, of the nonnull objects, or return the nonnull object if only one nonnull parameter is provided
function combineOpts() { var opts = []; for (var _i = 0; _i < arguments.length; _i++) { opts[_i] = arguments[_i]; } var validOpts = []; for (var i = 0, size = opts.length; i < size; i++) { if (opts[i] != null) { validOpts.push(opts[i]); } } if (validOpts.length < 2) { return validOpts[0]; } else { validOpts.unshift({}); return Object.assign.apply(null, validOpts); } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "static getOptions(options) {\n\n if(_.isNil(options)) {\n options = {};\n }\n\n if (_.isNil(options.items)) {\n options.items = 1;\n }\n\n if (_.isNil(options.delete)) {\n options.delete = false;\n }\n\n if (options.delete) {\n options.items = 1;\n }\n\n if (_.isNil(options.flatForSingle)) {\n options.flatForSingle = options.items === 1;\n }\n\n return options;\n }", "binClonePlus(noodle, obj, clone, map = {}, flatList = noodle.sList.new(noodle), flatClone = noodle.sList.new(noodle), flatMap = noodle.sList.new(noodle), path = [], func = function () { }, cond = function () { return true; }) {\n //Add unpassed parameters to arguments{\n [arguments[2], arguments[3], arguments[4], arguments[5], arguments[6], arguments[7], arguments[8], arguments[9]] = [clone, map, flatList, flatClone, flatMap, path, func, cond];\n if (arguments.length < 10) //This condition is necessary since arguments might be longer than 8\n arguments.length = 10;\n //}\n\n var args = Array.from(arguments);\n args.splice(7, 2);\n if (!cond.apply(undefined, args)) {\n return obj;\n }\n func.apply(undefined, args);\n\n //flatClone.push(clone);\n if (obj == null || obj == undefined)\n return obj;\n\n if (typeof obj == 'object') {\n //If clone is undefined, make it an empty array or object\n if (clone == undefined) {\n if (obj.constructor === Array) {\n clone = [];\n }\n else {\n clone = {};\n }\n }\n noodle.sList.add(noodle, flatList, obj);\n noodle.sList.add(noodle, flatClone, clone);\n noodle.sList.add(noodle, flatMap, path);\n\n var flatInd;\n //TODO: Find indices before loop\n //Go through obj to clone all its properties\n for (var i in obj) {\n [...path] = path; //Shallow clone path\n path.push(i);\n flatInd = noodle.sList.indexOf(noodle, flatList, obj[i]);\n //If we've found a new object, add it to flatList and clone it to clone and flatClone\n if (flatInd == -1) {\n //Set up map[i]{\n var mapVal;\n var isObj = true;\n //If obj[i] is not null or undefined, let mapVal be of the same type{\n if (obj[i] != undefined) {\n if (obj[i].constructor === Array)\n mapVal = [];\n else if (typeof obj[i] === 'object')\n mapVal = {};\n else {\n mapVal = obj[i];\n isObj = false;\n }\n }\n else {\n mapVal = obj[i];\n isObj = false;\n }\n //}\n map[i] = { recog: false, val: mapVal, isObj: isObj };\n //}\n //clone[i] = clone[i] || {};\n [...args] = arguments; //TODO: Guess I could place this line outside the loop?\n\n args[1] = obj[i];\n args[2] = clone[i];\n args[3] = map[i].val;\n clone[i] = noodle.object.binClonePlus.apply(undefined, args); //This works because flatList gets updated\n\n }\n //If we've seen obj[i] before, add the clone of it to clone\n else {\n clone[i] = noodle.sList.get(noodle, flatClone, flatInd);\n map[i] = { recog: true, path: noodle.sList.get(noodle, flatMap, flatInd) };\n }\n }\n return clone;\n }\n return obj;\n }", "static stripUndefinedProperties(options) {\n return Object.keys(options).reduce((object, key) => {\n if (options[key] !== undefined) {\n object[key] = options[key];\n }\n return object;\n }, {});\n }", "function deepObjectAssign() {\n var merged = deepObjectAssignNonentry.apply(void 0, arguments);\n stripDelete(merged);\n return merged;\n}", "function copyOptions(options) {\n var newOptions = {};\n for (var field in options) {\n if (options.hasOwnProperty(field)) {\n newOptions[field] = options[field];\n }\n }\n return newOptions;\n}", "function deepObjectAssignNonentry() {\n for (var _len2 = arguments.length, values = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {\n values[_key2] = arguments[_key2];\n }\n\n if (values.length < 2) {\n return values[0];\n } else if (values.length > 2) {\n var _context2;\n\n return deepObjectAssignNonentry.apply(void 0, concat$2(_context2 = [deepObjectAssign(values[0], values[1])]).call(_context2, toConsumableArray(slice$6(values).call(values, 2))));\n }\n\n var a = values[0];\n var b = values[1];\n\n var _iterator = _createForOfIteratorHelper(ownKeys$3(b)),\n _step;\n\n try {\n for (_iterator.s(); !(_step = _iterator.n()).done;) {\n var prop = _step.value;\n if (Object.prototype.propertyIsEnumerable.call(b, b[prop])) ;else if (b[prop] === DELETE) {\n delete a[prop];\n } else if (a[prop] !== null && b[prop] !== null && _typeof_1(a[prop]) === \"object\" && _typeof_1(b[prop]) === \"object\" && !isArray$3(a[prop]) && !isArray$3(b[prop])) {\n a[prop] = deepObjectAssignNonentry(a[prop], b[prop]);\n } else {\n a[prop] = clone(b[prop]);\n }\n }\n } catch (err) {\n _iterator.e(err);\n } finally {\n _iterator.f();\n }\n\n return a;\n}", "function deepObjectAssignNonentry() {\n for (var _len2 = arguments.length, values = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {\n values[_key2] = arguments[_key2];\n }\n\n if (values.length < 2) {\n return values[0];\n } else if (values.length > 2) {\n var _context2;\n\n return deepObjectAssignNonentry.apply(void 0, concat$2(_context2 = [deepObjectAssign(values[0], values[1])]).call(_context2, toConsumableArray(slice$3(values).call(values, 2))));\n }\n\n var a = values[0];\n var b = values[1];\n\n var _iterator = _createForOfIteratorHelper(ownKeys$3(b)),\n _step;\n\n try {\n for (_iterator.s(); !(_step = _iterator.n()).done;) {\n var prop = _step.value;\n if (Object.prototype.propertyIsEnumerable.call(b, b[prop])) ;else if (b[prop] === DELETE) {\n delete a[prop];\n } else if (a[prop] !== null && b[prop] !== null && _typeof_1(a[prop]) === \"object\" && _typeof_1(b[prop]) === \"object\" && !isArray$5(a[prop]) && !isArray$5(b[prop])) {\n a[prop] = deepObjectAssignNonentry(a[prop], b[prop]);\n } else {\n a[prop] = clone(b[prop]);\n }\n }\n } catch (err) {\n _iterator.e(err);\n } finally {\n _iterator.f();\n }\n\n return a;\n}", "function deepObjectAssignNonentry() {\n for (var _len2 = arguments.length, values = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {\n values[_key2] = arguments[_key2];\n }\n\n if (values.length < 2) {\n return values[0];\n } else if (values.length > 2) {\n var _context2;\n\n return deepObjectAssignNonentry.apply(void 0, concat$2(_context2 = [deepObjectAssign(values[0], values[1])]).call(_context2, toConsumableArray(slice$4(values).call(values, 2))));\n }\n\n var a = values[0];\n var b = values[1];\n\n var _iterator = _createForOfIteratorHelper(ownKeys$3(b)),\n _step;\n\n try {\n for (_iterator.s(); !(_step = _iterator.n()).done;) {\n var prop = _step.value;\n if (!Object.prototype.propertyIsEnumerable.call(b, prop)) ;else if (b[prop] === DELETE) {\n delete a[prop];\n } else if (a[prop] !== null && b[prop] !== null && _typeof_1(a[prop]) === \"object\" && _typeof_1(b[prop]) === \"object\" && !isArray$5(a[prop]) && !isArray$5(b[prop])) {\n a[prop] = deepObjectAssignNonentry(a[prop], b[prop]);\n } else {\n a[prop] = clone(b[prop]);\n }\n }\n } catch (err) {\n _iterator.e(err);\n } finally {\n _iterator.f();\n }\n\n return a;\n}", "function deepClone(o, opts) {\n // http://jsfiddle.net/masbicudo/u92bmgnn/1/\n if (typeof o === 'undefined' || o == null)\n return o;\n\n var r, isCloned = false;\n if (Array.isArray(o)) r = [];\n else if (o instanceof Object && !(opts && Object.isFrozen(o) && opts.ignoreFrozen === true)) {\n if (o.__proto__ === {}.__proto__) r = {};\n else {\n var fnClone = o.deepClone || o.clone;\n if (fnClone) {\n r = fnClone.call(o);\n isCloned = true;\n if (!opts || typeof opts.ignoreCloneableProps === 'undefined') return r;\n if (opts.ignoreCloneableProps === true)\n return r;\n }\n }\n }\n\n if (r) {\n for (var k in o)\n if (!isCloned || r[k] === o[k])\n r[k] = deepClone(o[k], opts);\n r.cloned = true;\n return r;\n }\n\n return o;\n}", "function prepareOptions(options){\n\n\n //if options isnt instance of GeneralOptions\n if (!(options instanceof GeneralOptions)) {\n \n\n //var generalOptions = new GeneralOptions\n var generalOptions = new GeneralOptions();\n //for each own property key,value in options\n var value=undefined;\n for ( var key in options)if (options.hasOwnProperty(key)){value=options[key];\n {\n //generalOptions.setProperty key, value\n generalOptions.setProperty(key, value);\n }\n \n }// end for each property\n //end for\n //options = generalOptions\n \n //options = generalOptions\n options = generalOptions;\n };\n\n\n //options.version = version\n options.version = module.exports.version;\n\n //return options\n return options;\n }", "function deepObjectAssign() {\n var merged = deepObjectAssignNonentry.apply(void 0, arguments);\n stripDelete(merged);\n console.log(merged);\n return merged;\n}", "function deepObjectAssign() {\n var merged = deepObjectAssignNonentry.apply(void 0, arguments);\n stripDelete(merged);\n console.log(merged);\n return merged;\n}", "function mergeIf() {\n\t\tvar a = arguments;\n\t\tif(a.length < 2) {\n\t\t\treturn;\n\t\t}\n\t\tfor(var i = 1; i < a.length; i++) {\n\t\t\tfor(var r in a[i]) {\n\t\t\t\tif(a[0][r] == null) {\n\t\t\t\t\ta[0][r] = a[i][r];\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn a[0];\n\t}", "function NonNullSet(){\n //constructor chaining\n //Set.apply(this, arguments);\n}", "function filterNull(opt) {\n const next = {}\n Object.keys(opt).forEach(key => {\n if (opt[key] !== null && opt[key] !== undefined) {\n next[key] = opt[key]\n }\n })\n return next\n}", "function merge() {\n\tvar i,\n\t\targs = arguments,\n\t\tlen,\n\t\tret = {},\n\t\tdoCopy = function (copy, original) {\n\t\t\tvar value, key;\n\n\t\t\t// An object is replacing a primitive\n\t\t\tif (typeof copy !== 'object') {\n\t\t\t\tcopy = {};\n\t\t\t}\n\n\t\t\tfor (key in original) {\n\t\t\t\tif (original.hasOwnProperty(key)) {\n\t\t\t\t\tvalue = original[key];\n\n\t\t\t\t\t// Copy the contents of objects, but not arrays or DOM nodes\n\t\t\t\t\tif (value && typeof value === 'object' && Object.prototype.toString.call(value) !== '[object Array]' &&\n\t\t\t\t\t\t\tkey !== 'renderTo' && typeof value.nodeType !== 'number') {\n\t\t\t\t\t\tcopy[key] = doCopy(copy[key] || {}, value);\n\t\t\t\t\n\t\t\t\t\t// Primitives and arrays are copied over directly\n\t\t\t\t\t} else {\n\t\t\t\t\t\tcopy[key] = original[key];\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn copy;\n\t\t};\n\n\t// If first argument is true, copy into the existing object. Used in setOptions.\n\tif (args[0] === true) {\n\t\tret = args[1];\n\t\targs = Array.prototype.slice.call(args, 2);\n\t}\n\n\t// For each argument, extend the return\n\tlen = args.length;\n\tfor (i = 0; i < len; i++) {\n\t\tret = doCopy(ret, args[i]);\n\t}\n\n\treturn ret;\n}", "function ObjectMergeOptions(opts) {\n 'use strict';\n opts = opts || {};\n this.depth = opts.depth || false;\n // circular ref check is true unless explicitly set to false\n // ignore the jslint warning here, it's pointless.\n this.throwOnCircularRef = 'throwOnCircularRef' in opts && opts.throwOnCircularRef === false ? false : true;\n}", "set(options) {\n\n if (\"point1\" in options) {\n var copyPoint = options[\"point1\"];\n this.point1.set({x: copyPoint.getX(), y: copyPoint.getY()});\n }\n if (\"point2\" in options) {\n var copyPoint = options[\"point2\"];\n this.point2.set({x: copyPoint.getX(), y: copyPoint.getY()});\n }\n if (\"line\" in options) {\n var copyLine = options[\"line\"];\n this.point1.set({x: copyLine.getPoint1().getX(), y: copyLine.getPoint1().getY()});\n this.point1.set({x: copyLine.getPoint2().getX(), y: copyLine.getPoint2().getY()});\n }\n }", "function mergeArguments(left, right) {\n if (typeof(right) === \"undefined\") {\n return left;\n }\n \n if (typeof(left) === \"undefined\") {\n left = {};\n }\n \n left.fields = right.fields || left.fields;\n left.queryProperty = right.queryProperty || left.queryProperty;\n left.propertyName = right.propertyName || left.propertyName;\n left.npmOptions = right.npmOptions || left.npmOptions;\n \n // for testing\n if (typeof(right.mocks) === \"object\") {\n left.mocks = right.mocks\n left.mocks.npmLoad = right.mocks.npmLoad || left.mocks.npmLoad;\n left.mocks.npmView = right.mocks.npmView || left.mocks.npmView;\n }\n \n return left;\n}", "function merge() {\n\t\tvar i,\n\t\t\targs = arguments,\n\t\t\tlen,\n\t\t\tret = {},\n\t\t\tdoCopy = function (copy, original) {\n\t\t\t\tvar value, key;\n\n\t\t\t\t// An object is replacing a primitive\n\t\t\t\tif (typeof copy !== 'object') {\n\t\t\t\t\tcopy = {};\n\t\t\t\t}\n\n\t\t\t\tfor (key in original) {\n\t\t\t\t\tif (original.hasOwnProperty(key)) {\n\t\t\t\t\t\tvalue = original[key];\n\n\t\t\t\t\t\t// Copy the contents of objects, but not arrays or DOM nodes\n\t\t\t\t\t\tif (value && typeof value === 'object' && Object.prototype.toString.call(value) !== '[object Array]' &&\n\t\t\t\t\t\t\t\tkey !== 'renderTo' && typeof value.nodeType !== 'number') {\n\t\t\t\t\t\t\tcopy[key] = doCopy(copy[key] || {}, value);\n\t\t\t\t\t\n\t\t\t\t\t\t// Primitives and arrays are copied over directly\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tcopy[key] = original[key];\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn copy;\n\t\t\t};\n\n\t\t// If first argument is true, copy into the existing object. Used in setOptions.\n\t\tif (args[0] === true) {\n\t\t\tret = args[1];\n\t\t\targs = Array.prototype.slice.call(args, 2);\n\t\t}\n\n\t\t// For each argument, extend the return\n\t\tlen = args.length;\n\t\tfor (i = 0; i < len; i++) {\n\t\t\tret = doCopy(ret, args[i]);\n\t\t}\n\n\t\treturn ret;\n\t}", "function merge() {\n var obj, name, copy,\n target = arguments[0] || {},\n i = 1,\n length = arguments.length;\n\n for (; i < length; i++) {\n if ((obj = arguments[i]) != null) {\n for (name in obj) {\n copy = obj[name];\n\n if (target === copy) {\n continue;\n }\n else if (copy !== undefined) {\n target[name] = copy;\n }\n }\n }\n }\n\n return target;\n}", "function merge() {\n\t\tvar i,\n\t\t\targs = arguments,\n\t\t\tlen,\n\t\t\tret = {},\n\t\t\tdoCopy = function (copy, original) {\n\t\t\t\tvar value, key;\n\n\t\t\t\t// An object is replacing a primitive\n\t\t\t\tif (typeof copy !== 'object') {\n\t\t\t\t\tcopy = {};\n\t\t\t\t}\n\n\t\t\t\tfor (key in original) {\n\t\t\t\t\tif (original.hasOwnProperty(key)) {\n\t\t\t\t\t\tvalue = original[key];\n\n\t\t\t\t\t\t// Copy the contents of objects, but not arrays or DOM nodes\n\t\t\t\t\t\tif (value && typeof value === 'object' && Object.prototype.toString.call(value) !== '[object Array]'\n\t\t\t\t\t\t\t\t&& key !== 'renderTo' && typeof value.nodeType !== 'number') {\n\t\t\t\t\t\t\tcopy[key] = doCopy(copy[key] || {}, value);\n\t\t\t\t\t\n\t\t\t\t\t\t// Primitives and arrays are copied over directly\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tcopy[key] = original[key];\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn copy;\n\t\t\t};\n\n\t\t// If first argument is true, copy into the existing object. Used in setOptions.\n\t\tif (args[0] === true) {\n\t\t\tret = args[1];\n\t\t\targs = Array.prototype.slice.call(args, 2);\n\t\t}\n\n\t\t// For each argument, extend the return\n\t\tlen = args.length;\n\t\tfor (i = 0; i < len; i++) {\n\t\t\tret = doCopy(ret, args[i]);\n\t\t}\n\n\t\treturn ret;\n\t}", "function cloneUtil(target, source) {\n if (source === void 0) {\n source = null;\n }\n\n if (!source) {\n source = target;\n target = {};\n }\n\n if (isObject(target) && isObject(source)) {\n for (var key in source) {\n if (isObject(source[key])) {\n if (!target[key]) Object.assign(target, (_a = {}, _a[key] = {}, _a));\n cloneUtil(target[key], source[key]);\n } else {\n Object.assign(target, (_b = {}, _b[key] = source[key], _b));\n }\n }\n }\n\n return target;\n\n var _a, _b;\n}", "function mergeOptions(obj1,obj2){var obj3={};var attrname;for(attrname in obj1){obj3[attrname]=obj1[attrname];}for(attrname in obj2){obj3[attrname]=obj2[attrname];}return obj3;}", "function merge() {\n var i,\n args = arguments,\n len,\n ret = {},\n doCopy = function (copy, original) {\n var value, key;\n \n // An object is replacing a primitive\n if (typeof copy !== 'object') {\n copy = {};\n }\n \n for (key in original) {\n if (original.hasOwnProperty(key)) {\n value = original[key];\n \n // Copy the contents of objects, but not arrays or DOM nodes\n if (value && typeof value === 'object' && Object.prototype.toString.call(value) !== '[object Array]'\n && key !== 'renderTo' && typeof value.nodeType !== 'number') {\n copy[key] = doCopy(copy[key] || {}, value);\n \n // Primitives and arrays are copied over directly\n } else {\n copy[key] = original[key];\n }\n }\n }\n return copy;\n };\n \n // If first argument is true, copy into the existing object. Used in setOptions.\n if (args[0] === true) {\n ret = args[1];\n args = Array.prototype.slice.call(args, 2);\n }\n \n // For each argument, extend the return\n len = args.length;\n for (i = 0; i < len; i++) {\n ret = doCopy(ret, args[i]);\n }\n \n return ret;\n }", "function cloneIt(o) {\n return ( $.extend(true, {}, o) );\n}", "function merge() {\n var i,\n args = arguments,\n len,\n ret = {},\n doCopy = function (copy, original) {\n var value, key;\n\n // An object is replacing a primitive\n if (typeof copy !== 'object') {\n copy = {};\n }\n\n for (key in original) {\n if (original.hasOwnProperty(key)) {\n value = original[key];\n\n // Copy the contents of objects, but not arrays or DOM nodes\n if (value && typeof value === 'object' && Object.prototype.toString.call(value) !== '[object Array]' &&\n key !== 'renderTo' && typeof value.nodeType !== 'number') {\n copy[key] = doCopy(copy[key] || {}, value);\n\n // Primitives and arrays are copied over directly\n } else {\n copy[key] = original[key];\n }\n }\n }\n return copy;\n };\n\n // If first argument is true, copy into the existing object. Used in setOptions.\n if (args[0] === true) {\n ret = args[1];\n args = Array.prototype.slice.call(args, 2);\n }\n\n // For each argument, extend the return\n len = args.length;\n for (i = 0; i < len; i++) {\n ret = doCopy(ret, args[i]);\n }\n\n return ret;\n }", "function mergeOptions() {\n\t\tvar $s = [];\n\t\tfor (var i = 0; i < arguments.length; i++) {\n\t\t\tvar arg = arguments[i];\n\t\t\tif (arg) {\n\t\t\t\t$s.push(arguments[i].$);\n\t\t\t}\n\t\t}\n\n\t\t/* Correct the first element, as if it is null or undefined the merge will throw an exception */\n\t\tif (!$s[0]) {\n\t\t\t$s[0] = {};\n\t\t}\n\n\t\tvar result = merge.apply(this, arguments);\n\t\tresult.$ = merge.apply(this, $s);\n\t\treturn result;\n\t}", "function cloneUtil(target, source) {\n if (source === void 0) { source = null; }\n if (!source) {\n source = target;\n target = {};\n }\n if (isObject(target) && isObject(source)) {\n for (var key in source) {\n if (isObject(source[key])) {\n if (!target[key])\n Object.assign(target, (_a = {}, _a[key] = {}, _a));\n cloneUtil(target[key], source[key]);\n }\n else {\n Object.assign(target, (_b = {}, _b[key] = source[key], _b));\n }\n }\n }\n return target;\n var _a, _b;\n}", "function copy(o) {\n return utils.apply(o, {});\n}", "function shallowCopy(src,dst){if(isArray(src)){dst=dst||[];for(var i=0,ii=src.length;i<ii;i++){dst[i]=src[i];}}else if(isObject(src)){dst=dst||{};for(var key in src){if(!(key.charAt(0)==='$'&&key.charAt(1)==='$')){dst[key]=src[key];}}}return dst||src;}", "function shallowCopy(src,dst){if(isArray(src)){dst=dst||[];for(var i=0,ii=src.length;i<ii;i++){dst[i]=src[i];}}else if(isObject(src)){dst=dst||{};for(var key in src){if(!(key.charAt(0)==='$'&&key.charAt(1)==='$')){dst[key]=src[key];}}}return dst||src;}", "function merge() {\n var i,\n args = arguments,\n len,\n ret = {},\n doCopy = function (copy, original) {\n var value, key;\n\n // An object is replacing a primitive\n if (typeof copy !== 'object') {\n copy = {};\n }\n\n for (key in original) {\n if (original.hasOwnProperty(key)) {\n value = original[key];\n\n // Copy the contents of objects, but not arrays or DOM nodes\n if (value && typeof value === 'object' && Object.prototype.toString.call(value) !== '[object Array]' &&\n key !== 'renderTo' && typeof value.nodeType !== 'number') {\n copy[key] = doCopy(copy[key] || {}, value);\n\n // Primitives and arrays are copied over directly\n } else {\n copy[key] = original[key];\n }\n }\n }\n return copy;\n };\n\n // If first argument is true, copy into the existing object. Used in setOptions.\n if (args[0] === true) {\n ret = args[1];\n args = Array.prototype.slice.call(args, 2);\n }\n\n // For each argument, extend the return\n len = args.length;\n for (i = 0; i < len; i++) {\n ret = doCopy(ret, args[i]);\n }\n\n return ret;\n }", "function flatten(options) {\n return (options === null || options === void 0 ? void 0 : options.xml)\n ? typeof options.xml === 'boolean'\n ? xmlModeDefault\n : { ...xmlModeDefault, ...options.xml }\n : options !== null && options !== void 0 ? options : undefined;\n}", "function opt(x, z) { return x !== undefined ? x : z }", "function deepCopy (obj, strictKeys) {\r\n var res;\r\n\r\n if ( typeof obj === 'boolean' ||\r\n typeof obj === 'number' ||\r\n typeof obj === 'string' ||\r\n obj === null ||\r\n (util.isDate(obj)) ) {\r\n return obj;\r\n }\r\n\r\n if (util.isArray(obj)) {\r\n res = [];\r\n obj.forEach(function (o) { res.push(deepCopy(o, strictKeys)); });\r\n return res;\r\n }\r\n\r\n if (typeof obj === 'object') {\r\n res = {};\r\n Object.keys(obj).forEach(function (k) {\r\n if (!strictKeys || (k[0] !== '$' && k.indexOf('.') === -1)) {\r\n res[k] = deepCopy(obj[k], strictKeys);\r\n }\r\n });\r\n return res;\r\n }\r\n\r\n return undefined; // For now everything else is undefined. We should probably throw an error instead\r\n}", "function deepCopy(obj, strictKeys) {\n var res;\n\n if (\n typeof obj === 'boolean' ||\n typeof obj === 'number' ||\n typeof obj === 'string' ||\n obj === null ||\n util.isDate(obj)\n ) {\n return obj;\n }\n\n if (util.isArray(obj)) {\n res = [];\n obj.forEach(function(o) {\n res.push(deepCopy(o, strictKeys));\n });\n return res;\n }\n\n if (typeof obj === 'object') {\n res = {};\n Object.keys(obj).forEach(function(k) {\n if (!strictKeys || (k[0] !== '$' && k.indexOf('.') === -1)) {\n res[k] = deepCopy(obj[k], strictKeys);\n }\n });\n return res;\n }\n\n return undefined; // For now everything else is undefined. We should probably throw an error instead\n}", "function _withDefaults(newOptions) {\n let extendedOptions = { ...options };\n if (typeof newOptions === 'object') {\n extendedOptions = Object.assign(extendedOptions, newOptions);\n }\n return extendedOptions;\n }", "function pr(n){if(n===null||n===undefined)throw new TypeError(\"Object.assign cannot be called with null or undefined\");return Object(n)}", "function clone (obj) {\n var copy;\n if (Array.isArray(obj)) {\n copy = new Array(obj.length);\n for (var i = 0; i < obj.length; i++) {\n copy[i] = clone(obj[i]);\n }\n return copy;\n }\n if (Object.prototype.toString.call(obj) === '[object Object]') {\n copy = {};\n var elems = Object.keys(obj);\n var elem;\n while (elem = elems.pop()) {\n // Accept camelCase options and convert them to snake_case\n var snake_case = elem;//.replace(/[A-Z][^A-Z]/g, '_$&').toLowerCase();\n // If camelCase is detected, pass it to the client, so all variables are going to be camelCased\n // There are no deep nested options objects yet, but let's handle this future proof\n if (snake_case !== elem.toLowerCase()) {\n camelCase = true;\n }\n copy[snake_case] = clone(obj[elem]);\n }\n return copy;\n }\n return obj;\n}", "function extendObject() {\n var i, options, key, value,\n target = arguments[0] || {},\n length = arguments.length;\n\n for( i = 1; i < length; i++ ) {\n // Ignore non-null/undefined values\n if( (options = arguments[ i ]) != null ) {\n // Extend the target object\n for( key in options ) {\n value = options[key]\n if( value )\n target[key] = value\n }\n }\n }\n\n return target\n }", "function merge_options(obj1){\n for (var attrname in obj1) { defaults[attrname] = obj1[attrname]; }\n return defaults;\n}", "function clone(a) {\n if (isArray$3(a)) {\n return map$2(a).call(a, function (value) {\n return clone(value);\n });\n } else if (_typeof_1(a) === \"object\" && a !== null) {\n return deepObjectAssignNonentry({}, a);\n } else {\n return a;\n }\n}", "function clone(a) {\n if (isArray$5(a)) {\n return map$2(a).call(a, function (value) {\n return clone(value);\n });\n } else if (_typeof_1(a) === \"object\" && a !== null) {\n return deepObjectAssignNonentry({}, a);\n } else {\n return a;\n }\n}", "function clone(a) {\n if (isArray$5(a)) {\n return map$2(a).call(a, function (value) {\n return clone(value);\n });\n } else if (_typeof_1(a) === \"object\" && a !== null) {\n return deepObjectAssignNonentry({}, a);\n } else {\n return a;\n }\n}", "function shallow_copy(src) {\n if ((typeof src === 'undefined' ? 'undefined' : _typeof(src)) === 'object') {\n var dst = {};\n for (var k in src) {\n if (Object.prototype.hasOwnProperty.call(src, k)) {\n dst[k] = src[k];\n }\n }\n return dst;\n }\n return src;\n }", "function shallow_copy(src) {\n if ((typeof src === 'undefined' ? 'undefined' : _typeof(src)) === 'object') {\n var dst = {};\n for (var k in src) {\n if (Object.prototype.hasOwnProperty.call(src, k)) {\n dst[k] = src[k];\n }\n }\n return dst;\n }\n return src;\n }", "function defaults(a,b,c){if(a!=null){return a;}if(b!=null){return b;}return c;}", "function defaults(a,b,c){if(a!=null){return a;}if(b!=null){return b;}return c;}", "function defaults(a,b,c){if(a!=null){return a;}if(b!=null){return b;}return c;}", "flatClone(noodle, flatList = noodle.object.flatList(obj), newList = new Array(flatList.length)) { //Kinda stupid to check lists for each recursion?\n for (var i in flatList) {\n var obj = flatList[i];\n if (typeof obj == 'object') {\n //Go through obj to find its properties in flatList and clone them to newList\n for (var j in obj) {\n var ind = flatList.indexOf(obj[i]);//Find obj[i] in flatList\n if (ind != -1) {\n if (newList[i] == undefined) {//If this object hasn't been found before\n newList[i] = shallowClone(); //TODO\n }\n }\n }\n }\n return $.extend(null, obj);\n }\n }", "function extend() {\n var options, name, src, copy, copyIsArray, clone,\n target = arguments[0] || {},\n i = 1,\n length = arguments.length;\n\n // Handle case when target is a string or something (possible in deep copy)\n if ( typeof target !== \"object\" && !_.isFunction(target) ) {\n target = {};\n }\n\n for ( ; i < length; i++ ) {\n // Only deal with non-null/undefined values\n if ( (options = arguments[ i ]) != null ) {\n // Extend the base object\n for ( name in options ) {\n src = target[ name ];\n copy = options[ name ];\n\n // Prevent never-ending loop\n if ( target === copy ) {\n continue;\n }\n\n // Recurse if we're merging plain objects or arrays\n if ( copy && isPlainObject(copy) ) {\n clone = src && isPlainObject(src) ? src : {};\n\n // Never move original objects, clone them\n target[ name ] = extend( clone, copy );\n // Don't bring in undefined values\n } else if ( copy !== undefined ) {\n target[ name ] = copy;\n }\n }\n }\n }\n // Return the modified object\n return target;\n }", "function _iSClone(input, mMap, options) {\n\n if (input === null) {\n return null;\n }\n\n if (Object(input) === input) {\n return _handleObjectClone(input, mMap, options);\n }\n\n // If the value is a primitive, simply return it.\n return input;\n }", "function invertOptions(options) {\n return options.reduce(function (acc, opt) {\n return chainOption(function (arr) {\n return mapOption(function (value) {\n return [].concat(_toConsumableArray(arr), [value]);\n })(opt);\n })(acc);\n }, some([]));\n}", "function mergeDefaultOptions(opts) {\n const copy = {};\n copyKeys(copy, _defaultOptions);\n copyKeys(copy, opts);\n Object.keys(_defaultOptions).forEach((key) => {\n const obj = _defaultOptions[key];\n if (typeof obj === 'object') {\n const objCopy = {};\n copyKeys(objCopy, obj);\n copyKeys(objCopy, copy[key]);\n copy[key] = objCopy;\n }\n });\n return copy;\n}", "function shallowCopy(src, dst) { // 986\n if (isArray(src)) { // 987\n dst = dst || []; // 988\n // 989\n for (var i = 0, ii = src.length; i < ii; i++) { // 990\n dst[i] = src[i]; // 991\n } // 992\n } else if (isObject(src)) { // 993\n dst = dst || {}; // 994\n // 995\n for (var key in src) { // 996\n if (!(key.charAt(0) === '$' && key.charAt(1) === '$')) { // 997\n dst[key] = src[key]; // 998\n } // 999\n } // 1000\n } // 1001\n // 1002\n return dst || src; // 1003\n} // 1004", "function bestCopyEver(src) {\n return Object.assign({}, src);\n}", "function b(a){if(null===a||a===void 0)throw new TypeError('Object.assign cannot be called with null or undefined');return Object(a)}", "function flatten(options) {\n return (options === null || options === void 0 ? void 0 : options.xml)\n ? typeof options.xml === 'boolean'\n ? xmlModeDefault\n : __assign(__assign({}, xmlModeDefault), options.xml)\n : options !== null && options !== void 0 ? options : undefined;\n}", "function va(t){if(null==t)throw new TypeError(\"Object.assign cannot be called with null or undefined\");return Object(t)}", "function cloneConfig(obj, isTopLevel) {\n\tvar clone;\n\tvar toString = Object.prototype.toString;\n\tvar hasOwnProperty = Object.prototype.hasOwnProperty;\n\n\tif (obj == null || typeof obj !== \"object\" || obj['isCloned']) {\n\t\treturn obj;\n\t}\n\n\tif (obj instanceof Array) {\n\t\tclone = [];\n\t\tfor (var i = 0, len = obj.length; i < len; i++) {\n\t\t\tclone[i] = cloneConfig(obj[i]);\n\t\t}\n\t\treturn clone;\n\t}\n\n\tif(obj instanceof Set) {\n\t\tclone = new Set();\n\t\tobj.forEach(function(item) {\n\t\t\tclone.add(item);\n\t\t});\n\t\treturn clone;\n\t}\n\n\t// instanceof fails to catch objects created with `null` as prototype\n\tif (obj instanceof Object || toString.call(obj) === \"[object Object]\") {\n\t\tclone = {};\n\t\tfor (var attr in obj) {\n\t\t\tobj['isCloned'] = true; // prevent infinite recursion\n\t\t\tif (\n\t\t\t\thasOwnProperty.call(obj, attr) &&\n\t\t\t\ttypeof Object.getOwnPropertyDescriptor(obj, attr).get !== 'function' // safari/iOS returns true for hasOwnProperty on getter properties in objects\n\t\t\t) {\n\t\t\t\tif (isTopLevel) {\n\t\t\t\t\t// exclude specific props and functions from top-level of config\n\t\t\t\t\tif (typeof obj[attr] !== 'function' &&\n\t\t\t\t\t\t!excludedConfigProps[attr]) {\n\t\t\t\t\t\tclone[attr] = cloneConfig(obj[attr]);\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tclone[attr] = cloneConfig(obj[attr]);\n\t\t\t\t}\n\t\t\t}\n\t\t\tdelete obj['isCloned'];\n\t\t}\n\t\treturn clone;\n\t}\n\n\tthrow new Error(\"Unable to copy obj! Its type isn't supported.\");\n}", "function clone(original) {\n return merge(true, {}, original);\n }", "function ct(t){if(null==t)throw new TypeError(\"Object.assign cannot be called with null or undefined\");return Object(t)}", "function flattenOptions(options) {\n // Add missing key\n function fillKey(list) {\n return (list || []).map(function (node) {\n var value = node.value,\n key = node.key,\n children = node.children;\n\n var clone = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_1__babel_runtime_helpers_esm_objectSpread2__[\"a\" /* default */])(__webpack_require__.i(__WEBPACK_IMPORTED_MODULE_1__babel_runtime_helpers_esm_objectSpread2__[\"a\" /* default */])({}, node), {}, {\n key: 'key' in node ? key : value\n });\n\n if (children) {\n clone.children = fillKey(children);\n }\n\n return clone;\n });\n }\n\n var flattenList = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_2_rc_tree_es_utils_treeUtil__[\"b\" /* flattenTreeData */])(fillKey(options), true);\n return flattenList.map(function (node) {\n return {\n key: node.data.key,\n data: node.data,\n level: getLevel(node)\n };\n });\n}", "getPopulated(options) {\n\n options = options || {};\n\n // Validate: Check Stage & Region\n if (!options.stage || !options.region) throw new SError('Both \"stage\" and \"region\" params are required');\n\n return {\n meta: this.meta.get(),\n project: this.project.getPopulated(options)\n }\n }", "function deepFillIn(target, defaults){\n\t var i = 0,\n\t n = arguments.length,\n\t obj;\n\n\t while(++i < n) {\n\t obj = arguments[i];\n\t if (obj) {\n\t // jshint loopfunc: true\n\t forOwn(obj, function(newValue, key) {\n\t var curValue = target[key];\n\t if (curValue == null) {\n\t target[key] = newValue;\n\t } else if (isPlainObject(curValue) &&\n\t isPlainObject(newValue)) {\n\t deepFillIn(curValue, newValue);\n\t }\n\t });\n\t }\n\t }\n\n\t return target;\n\t }", "__merge(opt,optDef){\n\t\tif(!opt || typeof opt !== 'object' ) opt = {};\n\t\tfor(var i in optDef){\n\t\t\tif(typeof optDef[i] == 'object' ) opt[i] = this.__merge(opt[i],optDef[i]);\n\t\t\telse if(typeof opt[i]=='undefined') opt[i] = optDef[i];\n\t\t}\n\t\treturn opt;\n\t}", "function extend(/*obj_1, [obj_2], [obj_N]*/) {\n if (arguments.length < 1 || typeof arguments[0] !== 'object') {\n return false;\n }\n\n if (arguments.length < 2) return arguments[0];\n\n var target = arguments[0];\n\n // convert arguments to array and cut off target object\n var args = Array.prototype.slice.call(arguments, 1);\n\n var key, val, src, clone;\n\n args.forEach(function (obj) {\n if (typeof obj !== 'object') return;\n\n for (key in obj) {\n if (obj[key] !== void 0) {\n src = target[key];\n val = obj[key];\n\n if (val === target) continue;\n\n if (typeof val !== 'object' || val === null || val instanceof RegExp) {\n target[key] = val;\n continue;\n }\n\n if (typeof src !== 'object') {\n clone = (Array.isArray(val)) ? [] : {};\n target[key] = extend(clone, val);\n continue;\n }\n\n if (Array.isArray(val)) {\n clone = (Array.isArray(src)) ? src : [];\n } else {\n clone = (!Array.isArray(src)) ? src : {};\n }\n\n target[key] = extend(clone, val);\n }\n }\n });\n\n return target;\n }", "clone(noodle, obj, clone, flatList = [], flatClone = []) {\n cloneCounter++;\n //flatClone.push(clone);\n if (obj == undefined)\n return obj;\n\n if (typeof obj == 'object') {\n //If clone is undefined, make it an empty array or object\n if (clone == undefined) {\n if (obj.constructor == Array) {\n clone = new Array(obj.length);\n }\n else {\n clone = {};\n }\n }\n flatList.push(obj);\n flatClone.push(clone);\n //Go through obj to clone all its properties\n for (var i in obj) {\n var flatInd = flatList.indexOf(obj[i]);\n //If we've found a new object, add it to flatList and clone it to clone and flatClone\n if (flatInd == -1) {\n //clone[i] = clone[i] || {};\n clone[i] = noodle.object.clone(noodle, obj[i], clone[i], flatList, flatClone); //This works because flatList gets updated\n }\n //If we've seen obj[i] before, add the clone of it to clone\n else {\n clone[i] = flatClone[flatInd];\n }\n }\n return clone;\n }\n return obj;\n }", "function mergeOptions(optionObjs){return util_1.mergeProps(optionObjs,complexOptions);}", "function merge(obj) {\n for (var i=1; i < arguments.length; i++) {\n var def = arguments[i];\n for (var n in def) {\n if (obj[n] === undefined) obj[n] = def[n];\n }\n }\n return obj;\n }", "function merge(obj) {\n for (var i=1; i < arguments.length; i++) {\n var def = arguments[i];\n for (var n in def) {\n if (obj[n] === undefined) obj[n] = def[n];\n }\n }\n return obj;\n }", "function flatClone(obj) {\n return Object.assign({}, obj);\n}", "function safeClone(source) {\n var destination = {};\n traversal_1.traversal(function (name, sourceValue) {\n if (typeof (sourceValue) !== 'function') {\n destination[name] = sourceValue;\n }\n }, destination, [source]);\n return destination;\n}", "function mergeInto(options, defaultOptions) {\n\tfor (var key in options) {\n\t\tdefaultOptions[key] = options[key];\n\t}\n\treturn defaultOptions;\n}", "function merge(obj) {\n\t for (var i = 1; i < arguments.length; i++) {\n\t var def = arguments[i];\n\t for (var n in def) {\n\t if (obj[n] === undefined) obj[n] = def[n];\n\t }\n\t }\n\t return obj;\n\t }", "function prepareAnimateOptions(options) {\n\t return isObject(options)\n\t ? options\n\t : {};\n\t}", "function prepareAnimateOptions(options) {\n\t return isObject(options)\n\t ? options\n\t : {};\n\t}", "function duplicate(ma) {\n return isNone(ma) ? none : some(ma);\n}", "function convertNewToReturnOriginal(options) {\n if ('new' in options) {\n options.returnOriginal = !options['new'];\n delete options['new'];\n }\n}", "function copy(obj) {\n\t var sources = [];\n\t for (var _i = 1; _i < arguments.length; _i++) {\n\t sources[_i - 1] = arguments[_i];\n\t }\n\t return assign.apply(void 0, [{}, obj].concat(sources));\n\t}", "Null(options = {}) {\r\n return { ...options, kind: exports.NullKind, type: 'null' };\r\n }", "function merge (obj) {\n for (var i = 1; i < arguments.length; i++) {\n var def = arguments[i]\n for (var n in def) {\n if (obj[n] === undefined) obj[n] = def[n]\n }\n }\n return obj\n }", "function merge (obj) {\n for (var i = 1; i < arguments.length; i++) {\n var def = arguments[i]\n for (var n in def) {\n if (obj[n] === undefined) obj[n] = def[n]\n }\n }\n return obj\n }", "function merge (obj) {\n for (var i = 1; i < arguments.length; i++) {\n var def = arguments[i]\n for (var n in def) {\n if (obj[n] === undefined) obj[n] = def[n]\n }\n }\n return obj\n }", "function merge (obj) {\n for (var i = 1; i < arguments.length; i++) {\n var def = arguments[i]\n for (var n in def) {\n if (obj[n] === undefined) obj[n] = def[n]\n }\n }\n return obj\n }", "function merge (obj) {\n for (var i = 1; i < arguments.length; i++) {\n var def = arguments[i]\n for (var n in def) {\n if (obj[n] === undefined) obj[n] = def[n]\n }\n }\n return obj\n }", "function merge (obj) {\n for (var i = 1; i < arguments.length; i++) {\n var def = arguments[i]\n for (var n in def) {\n if (obj[n] === undefined) obj[n] = def[n]\n }\n }\n return obj\n }", "function merge (obj) {\n for (var i = 1; i < arguments.length; i++) {\n var def = arguments[i]\n for (var n in def) {\n if (obj[n] === undefined) obj[n] = def[n]\n }\n }\n return obj\n }", "function merge (obj) {\n for (var i = 1; i < arguments.length; i++) {\n var def = arguments[i]\n for (var n in def) {\n if (obj[n] === undefined) obj[n] = def[n]\n }\n }\n return obj\n }", "function defaults(dst,src){forEach(src,function(value,key){if(!isDefined(dst[key])){dst[key]=value;}});}", "function merge(obj) {\n for (var i=1; i < arguments.length; i++) {\n var def = arguments[i]\n for (var n in def)\n if (obj[n] === undefined) obj[n] = def[n]\n }\n return obj\n }", "function merge(obj) {\n for (var i=1; i < arguments.length; i++) {\n var def = arguments[i]\n for (var n in def)\n if (obj[n] === undefined) obj[n] = def[n]\n }\n return obj\n }", "function merge(obj) {\n for (var i=1; i < arguments.length; i++) {\n var def = arguments[i]\n for (var n in def)\n if (obj[n] === undefined) obj[n] = def[n]\n }\n return obj\n }", "function merge(obj) {\n for (var i=1; i < arguments.length; i++) {\n var def = arguments[i]\n for (var n in def)\n if (obj[n] === undefined) obj[n] = def[n]\n }\n return obj\n }", "function merge(obj) {\n for (var i=1; i < arguments.length; i++) {\n var def = arguments[i]\n for (var n in def)\n if (obj[n] === undefined) obj[n] = def[n]\n }\n return obj\n }", "function merge(obj) {\n for (var i=1; i < arguments.length; i++) {\n var def = arguments[i]\n for (var n in def)\n if (obj[n] === undefined) obj[n] = def[n]\n }\n return obj\n }", "function merge(obj) {\n for (var i=1; i < arguments.length; i++) {\n var def = arguments[i]\n for (var n in def)\n if (obj[n] === undefined) obj[n] = def[n]\n }\n return obj\n }", "function merge(obj) {\n for (var i=1; i < arguments.length; i++) {\n var def = arguments[i]\n for (var n in def)\n if (obj[n] === undefined) obj[n] = def[n]\n }\n return obj\n }", "function merge(obj) {\n for (var i=1; i < arguments.length; i++) {\n var def = arguments[i]\n for (var n in def)\n if (obj[n] === undefined) obj[n] = def[n]\n }\n return obj\n }" ]
[ "0.59673554", "0.54036415", "0.54001105", "0.5350201", "0.53455365", "0.53293675", "0.5322498", "0.53205764", "0.5262921", "0.5247444", "0.5230417", "0.5230417", "0.5199346", "0.519535", "0.51921254", "0.51783097", "0.5164866", "0.51594085", "0.5146098", "0.5140963", "0.51351047", "0.51241493", "0.5099665", "0.506265", "0.5056372", "0.5056163", "0.5038366", "0.50370055", "0.5035717", "0.50346303", "0.50345623", "0.50345623", "0.5032185", "0.5019074", "0.5014605", "0.5008932", "0.50025487", "0.49967965", "0.49844787", "0.49823487", "0.49741745", "0.49638358", "0.49621335", "0.49376646", "0.49376646", "0.4929294", "0.4929294", "0.4929156", "0.4929156", "0.4929156", "0.49166802", "0.490736", "0.48862147", "0.4879522", "0.48685095", "0.48595458", "0.4855018", "0.4851192", "0.4840005", "0.4830688", "0.4817564", "0.4805364", "0.48026234", "0.47966057", "0.47825757", "0.4776405", "0.47540808", "0.47508308", "0.4749899", "0.47471008", "0.47395816", "0.47395816", "0.4729413", "0.4726135", "0.47256005", "0.4714727", "0.47144213", "0.47144213", "0.47134784", "0.47050092", "0.47008982", "0.4695695", "0.46947563", "0.46947563", "0.46947563", "0.46947563", "0.46947563", "0.46947563", "0.46947563", "0.46947563", "0.46914616", "0.46908945", "0.46908945", "0.46908945", "0.46908945", "0.46908945", "0.46908945", "0.46908945", "0.46908945", "0.46908945" ]
0.5500048
1
based on the examples available at
function createGraph(data){ var numNodes = 50; var nodes = data.map(function(d, i) { return { radius: sqrtScale(d.millions), category: Math.floor(i/10), airport: d.airport, total: d.passengers_2017, city: d.city_served, millions: d.milllions } }); /* - initialize a force layout, passing in a reference to the nodes -forceManyBody() creates a “many-body” force that acts on all nodes, meaning this can be used to either attract all nodes to each other or repel all nodes from each other. - apply a positive strngth value to attract. - forceX() centers each category around the respective x coordinate specified in the var XCenter - forceY() centers each category around the same specified y coordinate (190) */ var simulation = d3.forceSimulation(nodes) .force('charge', d3.forceManyBody().strength(7)) .force('x', d3.forceX().x(function(d) { return xCenter[d.category]; //return xScale(d.category); })) .force('y', d3.forceY().y(function(d) { return 190; })) .force('collision', d3.forceCollide().radius(d=> d.radius)) .on('tick', ticked); /* With on("tick", …), we are specifying how to take those updated coordinates and map them on to the visual elements in the DOM. */ function ticked() { var u = select('#numbers svg > g') .selectAll('circle') .data(nodes); var u2= u.enter() .append('circle') .attr('r', d =>d.radius) .attr("class", "node") .style('fill', function(d) { return colorScale[d.category]; }) .append('title') .text(d=>{return d.airport+" | City served: "+ d.city +" | Number of Passengers: "+d.total}); //on every tick through time, take the new x/y values for each circle and update them in the DOM //d3 calculates these x/y values and appends them to the existing objects in our original nodes dataset u2.merge(u) .attr('cx', d => d.x) .attr('cy',d => d.y) u.exit().remove(); // console.log(nodes); /* var text = select('#numbers svg > g') .append("text") .attr("x", 5) .attr("y", 400) .text( "Passenger Numbers in 2017 including terminal passengers .") .attr("dy", "1em") .attr("fill", "#333"); */ var legend = select("#numbers svg").selectAll(".legend") .data(ranges) .enter().append("g") .attr("class", "legend") .attr("transform", (d, i)=> { return "translate(0," + (i+2) * 24 + ")"; }); legend.append("rect") .attr("x", rangesWidth - 68) .attr("width", 20) .attr("height", 20) .style("fill", (d,i)=>colorScale[i]); legend.append("text") .attr("x", rangesWidth - 74) .attr("y", 12) .attr("dy", ".35em") .style("text-anchor", "end") .text(d=>d); } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "private public function m246() {}", "private internal function m248() {}", "obtain(){}", "protected internal function m252() {}", "static private internal function m121() {}", "transient protected internal function m189() {}", "transient private protected internal function m182() {}", "initialize() {}", "initialize() {}", "initialize() {}", "initialize() {}", "initialize() {}", "initialize() {}", "function _____SHARED_functions_____(){}", "transient private internal function m185() {}", "initialize()\n {\n }", "init() {\n }", "function test_candu_graphs_datastore_vsphere6() {}", "function setup() {}", "init() { }", "init() { }", "init() { }", "init() { }", "init() { }", "function setup() {\n\n\t\t\t\t\t}", "constructor () {\r\n\t\t\r\n\t}", "constructor (){}", "function setup() {\n\n\n}", "function setup() {\n\n\n}", "init () {}", "init () {}", "constructor() {\n \n\n \n \n\n \n\n \n }", "constructor() {\n \n\n \n \n\n \n\n \n }", "constructor() {\n \n\n \n \n\n \n\n \n }", "constructor() {\n \n\n \n \n\n \n\n \n }", "constructor() {\n \n\n \n \n\n \n\n \n }", "constructor() {\n \n\n \n \n\n \n\n \n }", "constructor() {\n \n\n \n \n\n \n\n \n }", "constructor() {\n \n\n \n \n\n \n\n \n }", "constructor() {\n \n\n \n \n\n \n\n \n }", "constructor() {\n \n\n \n \n\n \n\n \n }", "constructor() {\n \n\n \n \n\n \n\n \n }", "constructor() {\n \n\n \n \n\n \n\n \n }", "constructor() {\n \n\n \n \n\n \n\n \n }", "constructor() {\n \n\n \n \n\n \n\n \n }", "constructor() {\n \n\n \n \n\n \n\n \n }", "constructor() {\n \n\n \n \n\n \n\n \n }", "constructor() {\n \n\n \n \n\n \n\n \n }", "constructor() {\n \n\n \n \n\n \n\n \n }", "constructor() {\n \n\n \n \n\n \n\n \n }", "constructor() {\n \n\n \n \n\n \n\n \n }", "constructor() {\n \n\n \n \n\n \n\n \n }", "constructor() {\n \n\n \n \n\n \n\n \n }", "constructor() {\n \n\n \n \n\n \n\n \n }", "constructor() {\n \n\n \n \n\n \n\n \n }", "constructor() {\n \n\n \n \n\n \n\n \n }", "constructor() {\n \n\n \n \n\n \n\n \n }", "constructor() {\n \n\n \n \n\n \n\n \n }", "constructor() {\n \n\n \n \n\n \n\n \n }", "constructor() {\n \n\n \n \n\n \n\n \n }", "constructor() {\n \n\n \n \n\n \n\n \n }", "constructor() {\n \n\n \n \n\n \n\n \n }", "constructor() {\n \n\n \n \n\n \n\n \n }", "constructor() {\n \n\n \n \n\n \n\n \n }", "constructor() {\n \n\n \n \n\n \n\n \n }", "constructor() {\n \n\n \n \n\n \n\n \n }", "constructor() {\n \n\n \n \n\n \n\n \n }", "constructor() {\n \n\n \n \n\n \n\n \n }", "__previnit(){}", "initialize() {\n\n }", "static transient final private internal function m43() {}", "transient final protected internal function m174() {}", "function Adaptor() {}", "function DWRUtil() { }", "transient final private internal function m170() {}", "static final private internal function m106() {}", "static protected internal function m125() {}", "consructor() {\n }", "init () {\n }", "static private protected internal function m118() {}", "function init() {\n\t \t\n\t }", "function setup() {\n \n}", "function SeleneseMapper() {\n}", "function _construct()\n\t\t{;\n\t\t}", "init() {}", "init() {}", "init() {}", "init() {}", "init() {}", "init() {}", "init() {}", "init() {}", "init() {}", "init() {}", "init() {}", "init() {}", "init() {}", "init() {\n }", "init() {\n }", "init() {\n }", "init () {\n\n }" ]
[ "0.6249054", "0.61207354", "0.5688241", "0.5652461", "0.55740887", "0.5562143", "0.5559621", "0.5525219", "0.5525219", "0.5525219", "0.5525219", "0.5525219", "0.5525219", "0.5519751", "0.55109024", "0.54526246", "0.54324037", "0.5412216", "0.54038656", "0.5373169", "0.5373169", "0.5373169", "0.5373169", "0.5373169", "0.53618234", "0.5354301", "0.53035265", "0.52977484", "0.52977484", "0.52969265", "0.52969265", "0.52561396", "0.52561396", "0.52561396", "0.52561396", "0.52561396", "0.52561396", "0.52561396", "0.52561396", "0.52561396", "0.52561396", "0.52561396", "0.52561396", "0.52561396", "0.52561396", "0.52561396", "0.52561396", "0.52561396", "0.52561396", "0.52561396", "0.52561396", "0.52561396", "0.52561396", "0.52561396", "0.52561396", "0.52561396", "0.52561396", "0.52561396", "0.52561396", "0.52561396", "0.52561396", "0.52561396", "0.52561396", "0.52561396", "0.52561396", "0.52561396", "0.52561396", "0.52561396", "0.52363056", "0.5227998", "0.51719326", "0.51639104", "0.51557165", "0.51545817", "0.51519257", "0.5144616", "0.5140348", "0.5139069", "0.51101", "0.5098182", "0.50980496", "0.50911987", "0.5090687", "0.5084479", "0.50687855", "0.50687855", "0.50687855", "0.50687855", "0.50687855", "0.50687855", "0.50687855", "0.50687855", "0.50687855", "0.50687855", "0.50687855", "0.50687855", "0.50687855", "0.5064265", "0.5064265", "0.5064265", "0.50443745" ]
0.0
-1
The addPhraseToDisplay method: Creates a list item element for each letter and space in the given phrase. Adds the list items to the UL in the 'phrase' div.
addPhraseToDisplay() { for (let i = 0; i < this.phrase.length; i++) { let listItem = document.createElement('li'); (/\s/g.test(this.phrase.charAt(i))) ? listItem.className = 'space' : listItem.classList.add('hide', 'letter', `${this.phrase.charAt(i)}`); //If the character is a space, it is given a different class name. listItem.innerHTML = `${this.phrase.charAt(i)}`; document.getElementById('phrase').children[0].appendChild(listItem); } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "addPhraseToDisplay() {\r\n const phraseDiv = document.querySelector(\"#phrase\");\r\n const ul = phraseDiv.querySelector(\"ul\");\r\n for (let i = 0; i < this.phrase.length; i++) {\r\n const li = document.createElement(\"li\");\r\n li.textContent = this.phrase[i];\r\n if (this.phrase[i] !==' ') {\r\n li.className = 'letter';\r\n } else {\r\n li.className = 'space';\r\n }\r\n ul.appendChild(li);\r\n }\r\n }", "addPhraseToDisplay () {\n const phraseList = document.querySelector('#phrase ul');\n for (let i = 0, n = this.phrase.length; i < n; i++) {\n const listItem = document.createElement('li');\n if (/^\\w{1}$/.test(this.phrase[i])) {\n listItem.classList.add('hide', 'letter', this.phrase[i]);\n listItem.textContent = this.phrase[i];\n } else if (/^\\s{1}$/.test(this.phrase[i])) {\n listItem.className = 'space';\n }\n phraseList.appendChild(listItem)\n }\n this.addLineBreak();\n }", "addPhraseToDisplay() {\n\t\tconst ul = document.querySelector('UL');\n\t\tfor (let i = 0; i < this.phrase.length; i += 1) {\n\t\t\tlet newLi = document.createElement('LI');\n\t\t\tif (this.phrase[i] == ' ') {\n\t\t\t\tnewLi.className = `hide space`;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tnewLi.className = `hide letter ${this.phrase[i]}`;\n\t\t\t\tnewLi.innerText = `${this.phrase[i]}`;\n\t\t\t}\n\t\t\tul.appendChild(newLi);\n\t\t}\n\t}", "function addPhraseToDisplay() {\n phraseUl.innerHTML = \"\";\n const chars = getRandomPhraseAsArray(phrases);\n for (i = 0; i < chars.length; i++) {\n const char = chars[i];\n const phraseLi = document.createElement('li');\n phraseLi.textContent = char;\n if (char !== \" \") {\n phraseLi.className = 'letter';\n } else {\n phraseLi.className = 'space';\n }\n phraseUl.appendChild(phraseLi);\n };\n}", "function addPhraseToDisplay(phraseChoice) {\n for (let i = 0; i < phraseChoice.length; i++) {\n let letter = phraseChoice[i];\n let li = document.createElement(\"li\");\n li.textContent = letter;\n if (letter !== \" \") {\n li.className = \"letter\";\n phraseUl.appendChild(li);\n } else {\n li.className = \"space\";\n phraseUl.appendChild(li);\n }\n }\n}", "addPhraseToDisplay() {\n const phraseList = document.querySelector('#phrase ul');\n // Iterates through each character and sets the appropiate class names and text content\n for (let i = 0; i < this.phrase.length; i++) {\n const li = document.createElement('li');\n phraseList.appendChild(li);\n if (this.phrase[i] === ' ') {\n li.className = 'space';\n li.textContent = ' ';\n } else {\n li.className = `hide letter ${this.phrase[i]}`;\n li.textContent = this.phrase[i];\n }\n };\n }", "addPhraseToDisplay(){\n\t\tthis.phrase.split('').forEach(phraseLetter => {\n\t\t\tconst li = document.createElement('li');\n\t\t\tdocument.querySelector(\"#phrase ul\").appendChild(li);\n\t\t\tli.textContent = phraseLetter;\n\t\t\tif (phraseLetter !== ' ') {\n li.classList.add('letter', 'hide', phraseLetter)\n } else {\n li.classList.add('space');\n }\n\t\t})\n }", "addPhraseToDisplay()\r\n {\r\n // get DOM element for phrase\r\n\r\n const $divPhrase = $('#phrase');\r\n\r\n // setup class constants\r\n\r\n const letterClass = 'hide letter ';\r\n const spaceClass = 'space';\r\n\r\n // create new unordered list DOM element\r\n\r\n var newUL = document.createElement(\"ul\");\r\n \r\n // create var to hold the new LI and characters of the phrase\r\n\r\n var newLI = null;\r\n var phraseCharacter = null;\r\n\r\n // loop through all characters in the phrase\r\n\r\n for (let index = 0; index < this.phrase.length; index++) \r\n {\r\n // get character at index\r\n\r\n phraseCharacter = this.phrase[index];\r\n\r\n // create new list element and sets its text to the chracter\r\n\r\n newLI = document.createElement('li');\r\n newLI.textContent = phraseCharacter;\r\n\r\n // if the character is a space\r\n\r\n if (phraseCharacter === ' ') \r\n {\r\n // set the class name to spaceClass\r\n\r\n newLI.className = spaceClass;\r\n } \r\n else \r\n {\r\n // set the class name to letter class + character \r\n\r\n newLI.className = letterClass + phraseCharacter;\r\n }\r\n\r\n // append the new LI DOM element to the UL element\r\n\r\n newUL.appendChild(newLI);\r\n }\r\n\r\n // replace the exisiting UL element in the phrase with the new one\r\n\r\n $divPhrase.html(newUL.outerHTML);\r\n\r\n }", "addPhraseToDisplay() {\n //Targets the phrase\n const phraseElement = document.querySelector('#phrase ul');\n const splitPhrase = this.phrase.split('');\n splitPhrase.forEach(character => {\n const liElementChar = document.createElement('li');\n liElementChar.innerHTML = (`${character}`);\n phraseElement.append(liElementChar);\n liElementChar.classList.add('hide');\n if (character === ' ') {\n liElementChar.classList.add('space');\n } else {\n liElementChar.classList.add('letter');\n }\n });\n }", "addPhraseToDisplay() {\r\n const phraseDivUl = document.getElementById('phrase').firstElementChild;\r\n\r\n for (let i = 0; i < this.phrase.length; i++) {\r\n let newLetter = document.createElement('li');\r\n newLetter.textContent = this.phrase[i];\r\n if (this.phrase[i] === ' ') {\r\n newLetter.setAttribute('class', 'space');\r\n } else {\r\n newLetter.setAttribute('class', `hide letter ${this.phrase[i]}`);\r\n }\r\n phraseDivUl.appendChild(newLetter);\r\n }\r\n }", "addPhraseToDisplay() {\r\n let phrase = document.getElementById('phrase');\r\n phrase.removeChild(phrase.firstElementChild);\r\n let newUl = document.createElement('ul');\r\n phrase.append(newUl);\r\n\r\n //now print the new phrase\r\n for (let i=0; i<this.phrase.length; i++){\r\n let li = document.createElement('li');\r\n li.textContent = this.phrase[i];\r\n if (this.phrase[i]!==\" \"){\r\n li.classList.add('letter');\r\n li.classList.add('hide');\r\n } else {\r\n li.classList.add('space');\r\n }\r\n let phraseUl = document.querySelector('#phrase ul');\r\n phraseUl.appendChild(li);\r\n }\r\n }", "addPhraseToDisplay() {\r\n let eachLetter = this.phrase.split('');\r\n const phraseUL = document.querySelector('#phrase ul');\r\n for (let i = 0; i < eachLetter.length; i++) {\r\n let li = document.createElement('li');\r\n let text = document.createTextNode(eachLetter[i]);\r\n li.appendChild(text);\r\n phraseUL.appendChild(li);\r\n if (eachLetter[i] != ' ') {\r\n li.className = 'hide letter';\r\n li.classList.add(eachLetter[i]);\r\n } else {\r\n li.className = 'space';\r\n }\r\n }\r\n }", "addPhraseToDisplay(){\n //this adds letter placeholders to the display when the game starts.\n const divPhrase = document.querySelector('div#phrase');\n const ulElemPhrase = document.createElement('ul');\n for (let i = 0; i < this.phrase.length; i++){\n let liElem = document.createElement('li');\n if(/\\s/.test(this.phrase[i])){\n liElem.setAttribute('class', 'space');\n }else {\n liElem.classList += 'hide letter js-letter';\n liElem.textContent = this.phrase[i];\n }\n\n ulElemPhrase.appendChild(liElem);\n }\n\n divPhrase.appendChild(ulElemPhrase);\n }", "addPhraseToDisplay() {\n const phraseDiv = document.getElementById('phrase');\n const phraseUl = phraseDiv.firstElementChild;\n\n for ( let i = 0; i < this.phrase.length; i++) {\n const letter = document.createElement('li');\n letter.innerHTML = this.phrase[i]\n\n if (letter.innerHTML === ' ') {\n letter.className = 'space'\n } else {\n letter.className = `hide letter ${this.phrase[i]}`\n }\n\n phraseUl.appendChild(letter);\n }\n }", "addPhraseToDisplay() {\n const UL = document.querySelector('ul');\n const splittedPhrase = this.phrase.split('');\n\n splittedPhrase.forEach(letter => {\n const li = document.createElement('li')\n if (letter === ' ') {\n li.setAttribute('class', 'space');\n li.textContent = ' ';\n UL.appendChild(li);\n } else {\n li.setAttribute('class', 'hide letter')\n li.textContent = `${letter}`;\n UL.appendChild(li);\n }\n });\n }", "addPhraseToDisplay() {\r\n // select the ul in the phrase section\r\n const phraseSection = document.querySelector('#phrase ul');\r\n\r\n // loopinng through characters in the phrase, checks for space\r\n for (let i = 0; i < this.phrase.length; i ++) {\r\n let phraseChar = this.phrase.charAt([i]);\r\n\r\n // create the li\r\n const charLi = document.createElement('li');\r\n\r\n // create necessary list items\r\n if (phraseChar === \" \") {\r\n charLi.className = \"space\";\r\n charLi.innerText = \" \";\r\n } else {\r\n const charClass = `hide letter ${phraseChar}`;\r\n charLi.className = charClass;\r\n charLi.innerText = phraseChar;\r\n }\r\n // append to the ul\r\n phraseSection.appendChild(charLi);\r\n }\r\n }", "addPhraseToDisplay() {\n const parent = document.getElementById('phrase').firstElementChild;\n for (let i = 0; i < this.phrase.length; i++) {\n let text;\n const liElement = document.createElement('LI');\n if (this.phrase[i] === ' ') {\n liElement.className = 'space';\n text = document.createTextNode(' ');\n liElement.appendChild(text);\n } else {\n liElement.className = 'hide letter ' + this.phrase[i];\n text = document.createTextNode(this.phrase[i]);\n }\n liElement.appendChild(text);\n parent.appendChild(liElement);\n }\n\n }", "addPhraseToDisplay() {\r\n // Get phrase and split into letters\r\n const letters = this.phrase.split('');\r\n const ul = document.querySelector('ul');\r\n // Create li's and classes and append to the ul\r\n letters.forEach(letter => {\r\n const li = document.createElement('li');\r\n const item = document.createTextNode(`${letter}`);\r\n letter === ' '\r\n ? (li.className = 'space')\r\n : (li.className = `hide letter ${letter}`);\r\n\r\n li.appendChild(item);\r\n ul.appendChild(li);\r\n });\r\n }", "addPhraseToDisplay() {\n const ul = document.querySelector('#phrase ul');\n let phraseTemplate = '';\n for(let i = 0; i < this.phrase.length; i++) {\n if(this.phrase[i] == ' ') {\n phraseTemplate += `<li class=\"space\"> </li>`;\n } else {\n phraseTemplate += `<li class=\"hide letter ${this.phrase[i]}\">${this.phrase[i]}</li>`\n }\n }\n ul.innerHTML = phraseTemplate;\n }", "addPhraseToDisplay() {\n // Where the phrase will go.\n const targetElement = document.querySelector('#phrase > ul');\n\n // Starts the 'ul' for the first word.\n let html = '<ul>';\n [...this.phrase].forEach((char) => {\n if (char === ' ') {\n // Closes the 'ul' for the previous word.\n html += '</ul>';\n // Creates an 'li' for the space.\n html += '<li class=\"space\"> </li>';\n // Opens the 'ul' for the next word.\n html += '<ul>';\n } else {\n // Creates each 'li'.\n html += `<li class=\"hide letter ${char}\">${char}</li>`;\n }\n });\n // Closes the 'ul' for the last word.\n html += '</ul>';\n // Adds an extra 'li' to keep the display aligned evenly.\n html += '<li class=\"space\"> </li>';\n targetElement.innerHTML = html;\n }", "addPhraseToDisplay() {\n const phraseContainer = document.querySelector('#phrase ul');\n phraseContainer.className = 'phrase';\n\n //split the phrase into indivudiual letters\n const letters = this.phrase.split('');\n const regex = new RegExp(/[a-z]/);\n\n /** compare the letters to the RegEx\n if those letters match then add classname of letter\n If not then add classname of space\n append each new element \n */\n letters.forEach(letter => {\n if (regex.test(letter)) {\n const newListItem = document.createElement('li');\n newListItem.className = 'letter hide'\n newListItem.innerHTML = `${letter}`;\n phraseContainer.appendChild(newListItem);\n } else {\n const newListItem = document.createElement('li');\n newListItem.className = 'space'\n phraseContainer.appendChild(newListItem);\n }\n });\n }", "addPhraseToDisplay(){\r\n\r\n const phraseSection = document.getElementById('phrase');\r\n const phraseArr = this.phrase.split(' ');\r\n\r\n // Creates letters placeholders with spaces between each word\r\n let html = `<ul>`;\r\n phraseArr.forEach( word => {\r\n for (let i = 0; i < word.length; i += 1){\r\n html += \r\n `<li class=\"hide letter ${word.charAt(i)}\">${word.charAt(i)}</li>`;\r\n }\r\n if (phraseArr.indexOf(word) != phraseArr.length-1){\r\n html +=`<li class=\"space\"> </li>`;\r\n }\r\n });\r\n html+= `</ul>`;\r\n phraseSection.innerHTML = html;\r\n }", "addPhraseToDisplay() {\n let displayHTML = ``;\n for (let i = 0; i < this.phrase.length; i++) {\n if (this.phrase[i] === \" \") {\n displayHTML += `<li class=\"hide show\"></li>`;\n } else {\n displayHTML += `<li class=\"hide letter ${this.phrase[i]}\">${this.phrase[i]}</li>`;\n }\n }\n $(\"#phrase ul\").append(displayHTML);\n }", "addPhraseToDisplay() {\n\n const ul = document.getElementById('phrase').firstElementChild;\n\n for (let i = 0; i < this.phrase.length; i++) {\n\n let li = document.createElement('li');\n li.textContent = this.phrase[i];\n\n if (li.textContent === ' ') {\n li.classList.add('hide', 'space');\n } else {\n li.classList.add('hide', 'letter');\n }\n\n ul.appendChild(li);\n }\n }", "addPhraseToDisplay() {\n let thisPhrase = this.phrase.split('');\n let thisUl = $('#phrase ul');\n for (var i = 0; i < thisPhrase.length; i++) {\n if (thisPhrase[i] === ' ') {\n thisUl.append('<li class = \"hide space\"> </li>');\n } else {\n thisUl.append(`<li class = \"hide letter ${thisPhrase[i]}\">${thisPhrase[i]}</li>`);\n }\n }\n }", "addPhraseToDisplay() {\n const ul = document.getElementById('phrase').firstElementChild;\n for (let item of this.phrase) {\n if (item !== ' ') {\n ul.innerHTML += `<li class=\"hide letter ${item}\">${item}</li>`;\n } else {\n ul.innerHTML += `<li class=\"space\"> </li>`;\n }\n }\n }", "function addPhraseToDisplay(arr) {\n\tfor (i = 0; i < arr.length; i++) {\n\t\tconst listItem = document.createElement('li');\n\t\tlistItem.textContent = arr[i];\n\t\tvisbilePhrase.appendChild(listItem);\n\t\tif (arr[i] !== \" \") {\n\t\t\tlistItem.className = 'letter';\n\t\t} else {\n\t\t\tlistItem.className = 'space';\n\t\t}\n\t}\n}", "addPhraseToDisplay() {\n let chars = this.phrase.split('');\n const phraseUl = document.getElementById('phrase').children[0];\n\n chars.forEach(char => {\n if(char != ' ') {\n let li = document.createElement('li');\n li.setAttribute('class', `hide letter ${char}`);\n li.textContent = char;\n phraseUl.appendChild(li);\n }else {\n let li = document.createElement('li');\n li.setAttribute('class', `space`);\n li.textContent = char;\n phraseUl.appendChild(li);\n }\n })\n }", "addPhraseToDisplay() {\n const ul = document.querySelector('ul');\n\n for (let i = 0; i < this.phrase.length; i++) {\n let li = document.createElement('li');\n li.textContent = this.phrase[i];\n\n if (li.textContent === ' ') {\n li.classList.add('space');\n } else {\n li.classList.add('letter');\n li.classList.add('hide');\n }\n\n ul.appendChild(li);\n }\n }", "addPhraseToDisplay() {\n const ul = document.querySelector('#phrase ul');\n\n for(let i = 0; i < this.phrase.length; i++) {\n const li = document.createElement('li');\n \n if (this.phrase[i] === ' ') {\n li.textContent = this.phrase[i];\n li.classList.add('space'); //add class 'space' to CSS if space\n ul.appendChild(li);\n } else {\n li.textContent = this.phrase[i];\n li.classList.add('hide'); //hides all letters\n li.classList.add('letter'); //add class 'letter' to CSS if letter\n li.classList.add(this.phrase[i]);\n ul.appendChild(li); \n }\n } \n}", "function addPhraseToDisplay(arr) {\n // loop through array of characters\n for (let i = 0; i < arr.length; i++) {\n const letter = arr[i];\n // For each character, create a list item\n const item = document.createElement('li');\n // Put each character inside the list item\n item.textContent = letter;\n\n // Add the appropriate class to the list items\n if (letter !== \" \") {\n item.className = 'letter';\n } else {\n item.className = 'space';\n }\n\n // Append the list item to the DOM (specifically to the #phrase ul )\n ul.appendChild(item);\n }\n}", "addPhraseToDisplay(){\n const ul = document.getElementById('phrase').querySelector('ul');\n for (let i = 0; i < this.phrase.length; i++){\n const li = document.createElement('li');\n li.textContent = this.phrase[i];\n if(this.phrase[i] === ' '){\n li.className = 'space';\n }\n else{\n li.className = `hide letter ${this.phrase[i]}`;\n }\n \n ul.appendChild(li);\n }\n }", "addPhraseToDisplay() {\n const unorderedList = document.querySelector('ul');\n [...this.phrase].forEach(letter => {\n const listItem = document.createElement('li');\n if(letter !== ' '){ \n listItem.classList.add(`hide`);\n listItem.classList.add(`letter`);\n listItem.classList.add(`${letter}`);\n listItem.innerHTML = letter;\n unorderedList.appendChild(listItem);\n } else {\n listItem.classList.add(`space`);\n listItem.innerHTML = ' ';\n unorderedList.appendChild(listItem);\n }\n })\n }", "addPhraseToDisplay(){\r\n const ul = document.getElementById('phrase').querySelector('ul');\r\n for(let i = 0; i < this.phrase.length; i++){\r\n const li = document.createElement('li');\r\n if(this.phrase.charAt(i) === ' '){\r\n li.setAttribute('class','space');\r\n }else {\r\n li.setAttribute('class',`hide letter ${this.phrase.charAt(i)}`);\r\n }\r\n li.innerText = `${this.phrase.charAt(i)}`;\r\n ul.appendChild(li);\r\n \r\n }\r\n }", "function addPhraseToDisplay(arr) {\n for (let i = 0; i < phraseArray.length; i++) {\n const li = document.createElement('li');\n li.textContent = phraseArray[i];\n if (phraseArray[i] !== ' ') {\n li.className = 'letter';\n } else {\n li.className = 'space';\n }\n const ul = document.querySelector('ul');\n ul.appendChild(li);\n }\n}", "addPhraseToDisplay() {\n const ul = document.querySelector(\"ul\");\n let disPhrase = this.phrase;\n //this will add the phrase to the display\n for (let i = 0; i < disPhrase.length; i++) {\n if (disPhrase[i] !== \" \") {\n let li = document.createElement(\"li\");\n li.classList.add(\"letter\");\n li.classList.add(\"hide\");\n li.textContent = disPhrase.charAt(i);\n ul.appendChild(li);\n } else if (disPhrase[i] === \" \") {\n let liSpace = document.createElement(\"li\");\n liSpace.classList.add(\"space\");\n liSpace.textContent = disPhrase.charAt(i);\n ul.appendChild(liSpace);\n }\n }\n return ul;\n }", "addPhraseToDisplay(){\n const phraseSection = document.getElementById('phrase');\n const ul = phraseSection.querySelector('ul');\n for (let i = 0; i < this.phrase.length; i++) {\n if(this.phrase[i] !== \" \"){\n ul.innerHTML += `<li class=\"hide letter\">${this.phrase[i]}</li>`;\n } else {\n ul.innerHTML += `<li class=\"space\">${this.phrase[i]}</li>`;\n }\n }\n }", "addPhraseToDisplay() {\r\n //str.match(/[a-z]/i\r\n let ul = document.querySelector('UL'),\r\n li;\r\n let displayPhrase = this.phrase;\r\n for (let i = 0; i < displayPhrase.length; i++) {\r\n if (displayPhrase[i].match(/[a-z]/i)) {\r\n li = document.createElement('LI');\r\n li.classList.add('hide', 'letter');\r\n li.innerText = displayPhrase[i];\r\n ul.appendChild(li);\r\n } else if (displayPhrase[i].match('')) {\r\n li = document.createElement('LI');\r\n li.classList.add('space');\r\n li.innerText = displayPhrase[i];\r\n ul.appendChild(li);\r\n }\r\n }\r\n }", "function addPhraseToDisplay(arr) {\n for (let i = 0; i < arr.length; i++) {\n const listItem = document.createElement('LI');\n listItem.textContent = arr[i];\n if (arr[i] != \" \") {\n listItem.classList = \"letter\";\n } else {\n listItem.classList = \"space\";\n }\n phrase.appendChild(listItem)\n }\n }", "addPhraseToDisplay() {\n const phraseDiv = document.querySelector('#phrase ul');\n\n\n for (let i = 0; i < this.phrase.length; i++) {\n\n if (this.phrase.charAt(i) === ' ') {\n const newSpaceLi = document.createElement('li');\n newSpaceLi.setAttribute('class', 'space');\n newSpaceLi.textContent = ' ';\n phraseDiv.appendChild(newSpaceLi);\n\n } else {\n\n const newLetterLi = document.createElement('li');\n newLetterLi.setAttribute('class', `hide letter ${this.phrase.charAt(i)}`);\n newLetterLi.textContent = `${this.phrase.charAt(i)}`;\n phraseDiv.appendChild(newLetterLi);\n\n }\n }\n\n }", "addPhraseToDisplay() {\n const phraseUl = document\n .getElementById(\"phrase\")\n .getElementsByTagName(\"ul\")[0];\n const splitPhrase = this.phrase.split(\"\");\n let htmlLetters = [];\n splitPhrase.forEach(letter => {\n let li = document.createElement(\"li\");\n phraseUl.append(li);\n li.innerHTML = letter;\n htmlLetters.push(li);\n if (letter === \" \") {\n li.className = \"space\";\n } else {\n li.className = \"letter\";\n }\n });\n }", "function addPhraseToDisplay (arr) {\n for (let i = 0; i < arr.length; i++) {\n const li = document.createElement('li');\n const character = arr[i];\n const ul = document.querySelector('#phraseList');\n\n li.appendChild(document.createTextNode(character));\n ul.appendChild(li);\n if (character !== \" \") {\n li.className = 'letter';\n } else {\n li.className = 'space';\n }\n }\n}", "addPhraseToDisplay() {\r\n const ul = document.querySelector('#phrase ul');\r\n const letter = this.phrase.split(\"\");\r\n console.log(letter);\r\n for (let i = 0; i < letter.length; i += 1) {\r\n if (letter[i] !== \" \") {\r\n const li = document.createElement('li');\r\n li.textContent = letter[i];\r\n li.classList.add('letter');\r\n ul.appendChild(li);\r\n } else {\r\n const li = document.createElement('li');\r\n li.classList.add('space');\r\n ul.appendChild(li);\r\n }\r\n }\r\n }", "addPhraseToDisplay() {\r\r let phraseUl = document.getElementsByTagName(\"ul\");\r\r for (let i = 0; i < this.phrase.length; i++) {\r\r let li = document.createElement(\"li\");\r\r if (this.phrase[i] == ' ') {\r li.classList.add(\"space\");\r\n let space = document.createTextNode(\" \");\r\n li.appendChild(space);\r\n }\r else {\r li.classList.add(\"hide\");\r\n li.classList.add(\"letter\");\r\n li.classList.add(this.phrase[i]);\r\n let letter = document.createTextNode(this.phrase[i]);\r\n li.appendChild(letter);\r\n }\r\r phraseUl[0].appendChild(li);\r\r }\r }", "function addPhraseToDisplay(arr) {\n for ( let i = 0; i < arr.length; i++ ) {\n const letter = arr[i];\n const li = document.createElement('li');\n const ul = document.querySelector('#phrase ul');\n li.textContent = letter;\n ul.appendChild(li);\n if(letter !== ' ') {\n li.className = 'letter';\n }\n else {\n li.className = 'space';\n }\n }\n}", "function addPhraseToDisplay(arr) {\n const ul = document.getElementById('phrase').firstElementChild;\n\n for (let i = 0; i < arr.length; i += 1) {\n const characterValue = arr[i];\n const li = document.createElement('li');\n\n li.textContent = characterValue;\n \n if (li.textContent != ' ') {\n li.className = 'letter';\n ul.appendChild(li);\n } else {\n li.className = 'space';\n ul.appendChild(li);\n }\n }\n}", "addPhraseToDisplay() {\n let splitPhrase = this.phrase.split(\"\");\n for (let i = 0; i < splitPhrase.length; i++) {\n let currentPhraseLi = document.createElement(\"li\");\n if (splitPhrase[i] === \" \") {\n currentPhraseLi.className = \"space\"\n currentPhraseLi.innerText = splitPhrase[i]\n phraseUl.appendChild(currentPhraseLi);\n\n } else {\n currentPhraseLi.classList.add(\"hide\", \"letter\", splitPhrase[i]);\n currentPhraseLi.innerText = splitPhrase[i]\n phraseUl.appendChild(currentPhraseLi);\n\n\n };\n };\n }", "function addPhraseToDisplay(array) {\n // loop through array of characters\n\n for (let i = 0; i < array.length; i++) {\n // create list items\n\n const characters = array[i];\n const displayList = document.createElement('li');\n displayList.textContent = characters;\n phraseUl.appendChild(displayList);\n\n // add appropriate classes\n\n if (displayList.textContent !== ' ') {\n displayList.classList.add('letter');\n } else {\n displayList.classList.add('space');\n }\n }\n}", "function addPhraseToDisplay(arr) {\n for (i = 0; i < arr.length; i += 1) {\n var li = document.createElement('li');\n li.appendChild(document.createTextNode(arr[i]));\n ul.appendChild(li);\n if (li.textContent != \" \") {\n li.className = 'letter';\n } else {\n li.className = 'space';\n }\n }\n}", "addPhraseToDisplay() {\n\n const phraseUl = document.querySelector('#phrase ul');\n\n for (let letter of this.phrase) {\n const li = document.createElement('li');\n\n if (letter !== ' ') {\n // li.appendChild(divCon);\n // console.log(li);\n li.className = `hide letter ${letter}`;\n li.textContent = `${letter}`\n phraseUl.appendChild(li);\n } else {\n li.className = 'space';\n li.textContent = ' ';\n phraseUl.appendChild(li);\n }\n }\n\n }", "addPhraseToDisplay() {\n const letters = this.phrase.split(\"\");\n const ul = document.getElementById(\"phrase\");\n\n let html = ``;\n letters.forEach((letter) => {\n if (letter === \" \") {\n html += `<li class=\"space\"> </li>`;\n } else {\n html += `<li class=\"hide letter ${letter}\">${letter}</li>`;\n }\n });\n\n ul.insertAdjacentHTML(\"beforeend\", html);\n }", "function addPhraseToDisplay(array) {\n for (let i = 0; i < array.length; i += 1) {\n let li = document.createElement('li');\n li.textContent = array[i];\n if (array[i] === ' ') {\n li.className = 'space';\n } else {\n li.className = 'letter';\n };\n ul.appendChild(li);\n };\n}", "function addPhraseToDisplay (arr) {\n\n // Loop through picked phrase array and set as li elements (letters)\n for (let i = 0; i < arr.length; i++ ) {\n const li = document.createElement('li');\n li.innerHTML = arr[i];\n ul.appendChild(li);\n\n // If character is not a space add class of letter\n if (li.textContent !== ' ' ) {\n li.className = 'letter';\n } else {\n li.className = 'space';\n }\n }\n}", "addPhraseToDisplay() {\n //seperates the letters and spacing\n let letters = this.phrase.split('');\n //set empty template literal to variable\n let phraseUl = ``;\n\n //iterates through letters and creates a list object while simultaneously adding it to the template literal\n letters.forEach(letter => {\n if (letter.charAt(0) === ' ') {\n phraseUl += `<li class=\"space\"> </li>`;\n } else {\n phraseUl += `<li class=\"hide letter ${letter}\">${letter}</li>`;\n }\n });\n //adds phraseUl to html\n $('#phrase ul').append(phraseUl);\n }", "function addPhraseToDisplay (arr) {\n for (i = 0; i < arr.length; i++){\n let li = document.createElement('li');\n phrase.appendChild(li);\n li.textContent = arr[i];\n if (li.textContent === ' ') {\n li.className = 'space'\n li.style.display = 'block'\n } else {\n li.className = 'letter'\n }\n }\n}", "function addPhraseToDisplay(arr) {\n for (let i = 0; i < arr.length; i++) {\n\n let letter = arr[i];\n let li = document.createElement('li');\n\n li.textContent = letter;\n phrase_container.appendChild(li);\n\n if (li.textContent !== \" \") {\n li.className = \"letter\";\n } else {\n li.className = \"space\";\n }\n }\n}", "function addPhraseToDisplay(arr) {\n for (let i = 0; i < arr.length; i += 1) {\n let li = document.createElement('li');\n li.textContent = arr[i];\n if (li.textContent != \" \") {\n li.className = 'letter';\n } else {\n li.className = 'space';\n }\n ul.appendChild(li);\n }\n}", "function addPhraseToDisplay(arr) {\n for (let i = 0; i < arr.length; i++) {\n const li = document.createElement('li');\n li.textContent = arr[i];\n ul.appendChild(li);\n if (arr[i] !== ' ') {\n li.className = 'letter';\n } else {\n li.className = 'space';\n }\n }\n}", "function addPhraseToDisplay(arr) {\n const ul = phrase.querySelector(\"ul\");\n for (let i = 0; i < arr.length; i++) {\n let item = document.createElement(\"li\");\n ul.appendChild(item);\n item.innerHTML = arr[i];\n if (arr[i] === \" \") {\n item.classList.add(\"space\");\n } else {\n item.classList.add(\"letter\");\n }\n }\n}", "function addPhraseToDisplay(arr){\n\n for (let i = 0; i < arr.length; i++) {\n const letter = document.querySelector(\"#phrase ul\");\n const li = document.createElement(\"li\");\n \n letter.appendChild(li);\n li.textContent = arr[i].toUpperCase();\n\n if (li.textContent !== \" \") {\n li.className = \"letter\";\n } else {\n li.className = \"space\";\n }\n }\n}", "function addPhraseToDisplay(arr){\n for (let i=0; i < arr.length; i++) {\n const letter = document.createElement('li');\n letter.textContent = arr[i];\n ul.appendChild(letter);\n if (letter.textContent === \" \") {\n letter.className = \"space\";\n } else {\n letter.className = \"letter\";\n }\n };\n }", "addPhraseToDisplay(){\r\n const phraseUl = document.querySelector('#phrase ul');\r\n const phraseArr = this.phrase.split('');\r\n let html = '';\r\n// go thru each letter of the phraseArr and create and <Li>\r\n// added the respective class to each item\r\n// then appended to the dom\r\n phraseArr.forEach(character => {\r\n if(character !== ' '){\r\n html += `<li class=\"hide letter ${character}\">${character}</li>`;\r\n } else {\r\n html += `<li class=\"hide space\">${character}</li>`;\r\n }\r\n });\r\n phraseUl.innerHTML = html;\r\n return phraseUl;\r\n }", "function addPhraseToDisplay(arr){\n let phrase = document.querySelector('#phrase ul');\n // do stuff any arr that is passed in, and add to `#phrase ul`\n for (let i = 0; i < arr.length; i++) {\n let ul = document.querySelector('#phrase ul');\n let li = document.createElement('li');\n phrase.appendChild(li);\n li.append(arr[i]);\n\n if (arr[i] === ' ') {\n li.classList.add('space');\n } else {\n li.classList.add('letter');\n\n }\n\n\n }\n}", "addPhraseToDisplay() {\n const $phraseUL = $('#phrase ul');\n let charArr = this.phrase.split('');\n charArr.forEach(char => {\n if( char === ' ' ) {\n $phraseUL.append(`<li class=\"space\"> </li>`);\n }\n else {\n $phraseUL.append(`<li class=\"hide letter ${char}\">${char}</li>`);\n }\n });\n }", "function addPhraseToDisplay () {\n var letter=getRandomPhraseAsArray();\n for (var i= 0; i<letter.length; i++){\n if (letter[i] !== \" \"){\n var li=document.createElement(\"li\");\n li.appendChild(document.createTextNode(letter[i]));\n li.classList.add(\"letter\");\n ul.appendChild(li);\n } else {\n var li=document.createElement(\"li\");\n li.appendChild(document.createTextNode(letter[i]));\n li.classList.add(\"space\");\n ul.appendChild(li);\n }\n }\n return letter;\n}", "addPhraseToDisplay() {\r\n let phraseToLetters = [...this.phrase];\r\n let htmlPhrase = ``;\r\n phraseToLetters.forEach((i) => {\r\n htmlPhrase += `<li class=\"hide ${i !== \" \" ? \"letter\": \"space\"} ${i}\">${i}</li>`\r\n })\r\n document.getElementById('phrase').children[0].innerHTML = htmlPhrase;\r\n }", "addPhraseToDisplay() {\r\n //display the number of letters in the activePhrase, each letters gets a box\r\n //store the phrase div\r\n const phraseDiv = document.querySelector('#phrase');\r\n const ul = phraseDiv.firstElementChild;\r\n // console.log(ul);\r\n\r\n //create a loop to go through the number of leters in the activePhrase\r\n // console.log(`active phrase has ${this.phrase.length} letters`);\r\n\r\n for(let i = 0; i < this.phrase.length; i++){\r\n // console.log(`in for loop`);\r\n //create li elements\r\n const li = document.createElement('li');\r\n ul.appendChild(li);\r\n\r\n //if there is a space\r\n if(this.phrase.charAt(i) === ' '){\r\n li.setAttribute('class', `hide space`);\r\n } else{\r\n li.setAttribute('class', `hide letter ${this.phrase.charAt(i)}`);\r\n li.textContent = this.phrase.charAt(i);\r\n }\r\n };\r\n }", "addPhraseToDisplay() {\r\n const characters = this.phrase.split('');\r\n const phraseDiv = document.querySelector('#phrase ul')\r\n characters.forEach(character => {\r\n const letter = document.createElement('li');\r\n if (character == ' ') {\r\n letter.setAttribute(\"class\", \"space\");\r\n } else {\r\n letter.setAttribute(\"class\", ` hide letter ${character}`);\r\n }\r\n letter.innerHTML = character;\r\n phraseDiv.appendChild(letter);\r\n });\r\n return characters\r\n }", "function adPhraseToDisplay(){\n let length = phraseArray.length;\n let letters = phraseArray.split('');\n const ul = phrase.firstElementChild;\n \n for (let i = 0; i < length; i++) {\n let li = document.createElement(\"li\");\n li.textContent = letters[i];\n \n if(letters[i] === \" \" ) {\n li.classList.add('space');\n } else {\n li.classList.add('letter');\n }\n\n ul.appendChild(li);\n \n }\n}", "addPhraseToDisplay() {\n const keyboard = this.phrase.split('');\n for (let i = 0; i < keyboard.length; i++){\n let li = document.createElement('li');\n li.textContent = keyboard[i];\n keyboard[i] === ' ' ? li.className = 'hide space' : li.className = `hide letter ${keyboard[i]}`\n document.querySelector('#phrase ul').appendChild(li);\n }\n }", "addPhraseToDisplay() {\r\n\r\n /* add letter placeholders to the display when the game starts */\r\n let phraseArray = this.phrase.split(\"\");\r\n const phraseBody = document.getElementById(\"phrase\")\r\n\r\n let arrayNew = phraseArray.map(letter => {\r\n /* hide the phrase if it is a letter and not empty space */\r\n if (letter !== \" \") {\r\n return `<li class=\"hide letter ${letter}\">${letter}</li>`\r\n }\r\n else {\r\n return `<li class=\"space\"> </li>`\r\n }\r\n })\r\n\r\n phraseBody.innerHTML = '<ul>' + arrayNew.join(\"\") + '</ul>';\r\n }", "addPhraseToDisplay() {\n let html = '';\n let letter = '';\n\n for (let i = 0; i < this.phrase.length; i++) {\n letter = this.phrase.charAt(i);\n if (letter === ' ') {\n html += `<li class =\"space\"> ${letter}</li>`;\n } else {\n html += `<li class=\"hide letter ${letter}\">${letter}</li>`;\n }\n }\n ul.innerHTML = (html);\n }", "function addPhraseToDisplay(arr) {\n const ul = document.querySelector('#phrase ul');\n // loop to add space or letter to the list items \n for (let i = 0; i < arr.length; i += 1) {\n // create list items\n let li = document.createElement('li'); \n // set the text content of li to the corespondind array index\n li.textContent = arr[i];\n // add list items to ul phrase\n ul.appendChild(li);\n if (arr[i] === ' ') {\n // if a space is clicked, add class space\n li.className = 'space'; \n }\n // otherwise, add class letter\n else {\n li.className = 'letter';\n }\n }\n}", "addPhraseToDisplay() {\n //let html_word = \"<ul>\"\n const temporary = this.phrase; \n // get the html div element\n let phrase_html_div = document.getElementById(\"phrase\");\n //phrase_html_div.removeChild(phrase_html_div.firstChild);\n let phrase_ul = document.createElement(\"UL\")\n \n\n for (let i = 0; i < temporary.length; i++){\n const character = temporary[i]; \n \n let single_li = document.createElement(\"LI\");\n let text = null;\n //Putting a space where there is a space, and not a letter.\n if (character === \" \"){ \n \n text = document.createTextNode(\" \"); \n single_li.setAttribute(\"class\",\"space\");\n \n }else{ \n //If it is a character, set the class attribute to hide letter.\n \n text = document.createTextNode(character); \n single_li.setAttribute(\"class\",`hide letter ${character}`); \n }\n single_li.appendChild(text);\n phrase_ul.appendChild(single_li); \n \n }\n phrase_html_div.appendChild(phrase_ul);\n }", "function addPhraseToDisplay (characterArray) {\n /*\n <ul>\n <li class=\"letter\">A</li>\n <li class=\"letter\">n</li>\n <li class=\"letter\">d</li>\n <li class=\"letter\">y</li>\n </ul>\n \n */\n\nfor (i = 0; i < characterArray.length; i++) {\n const li = document.createElement(\"LI\");\n const character = characterArray[i]\n li.textContent = character;\nif (character !== \" \") {\n li.classList.add('letter');\n} else {\n li.classList.add('space');\n}\n const ul = phrase.getElementsByTagName('ul')[0];\n ul.appendChild(li);\n} \n\n/*\ninput: randomCharacterArray\ninstructions: \nStep 1: Loops through an array of characters.\n a. Inside the loop, for each character in the array, you’ll create a list item, \n b. put the character inside of the list item, \n c. and append that list item to the #phrase ul in your HTML. \n step 2: If the character in the array is a letter and not a space, the function should add the class “letter” to the list item.\n\n*/\n\n}", "function addPhraseToDisplay(arr) {\n let letters = \"\";\n\n for (var i = 0; i < arr.length; i += 1 ) {\n if (arr[i] !== \" \") {\n letters += '<li class=\"letter\">' + arr[i] + '</li>';\n } else {\n letters += '<li class=\"space\">' + arr[i] + '</li>';\n }\n }\n phraseUl.innerHTML = letters;\n}", "addPhraseToDisplay() {\n let divUl = document.querySelector(\"#phrase ul\");\n let html = \"\";\n\n //Split the phrase into an array of characters then check each letter and assign it a class\n //If the letter is a space, it is assigned a different class\n let arr = this.phrase.split(\"\")\n arr.forEach(character => {\n let test = /[a-z]/.test(character);\n if (test) {\n html += `<li class=\"hide letter ${character}\">${character}</li>`;\n } else {\n html += '<li class=\"space\"> </li>'\n }\n\n });\n\n divUl.innerHTML = html;\n return divUl;\n }", "addPhraseToDisplay() {\r\n const pDiv = document.querySelector(\"#phrase\");\r\n const ul = document.querySelector(\"ul\");\r\n const splitPhrase = this.phrase.split(\"\");\r\n console.log(splitPhrase);\r\n\r\n splitPhrase.forEach((letter) => {\r\n const li = document.createElement(\"li\");\r\n li.textContent = letter;\r\n if (!/^[a-z]$/.test(letter)) {\r\n li.className = \"space\";\r\n } else {\r\n li.className = `hide letter ${letter}`;\r\n }\r\n ul.appendChild(li);\r\n });\r\n console.log(pDiv);\r\n }", "function addPhrasetoDisplay (chosenPhrase) {\r\n for ( let i = 0; i < chosenPhrase.length; i++){\r\n const li = document.createElement(\"li\");\r\n li.textContent = chosenPhrase[i];\r\n ul.appendChild(li);\r\n if ( li.textContent == \" \") {\r\n li.className = \"space\"\r\n }else {\r\n li.className =\"letter\"\r\n }\r\n }\r\n}", "function addPhraseToDisplay() {\n let array = movieTitleToArray();\n\n for (let letters of array) {\n if (letters == \" \") {\n phrase.innerHTML += `<li class=\"space\">${letters}</li>`\n } else {\n phrase.innerHTML += `<li class=\"letter\">${letters}</li>`\n }\n }\n}", "addPhraseToDisplay() {\n let phraseDisplay = document.querySelector(\"#phrase\");\n let output = `<div id=\"phrase\" class=\"section\"><ul>`;\n\n //loop through each phrase letter\n for (let i = 0; i < this.phrase.length; i++){\n if (this.phrase[i] === \" \") {\n output += `<li class=\"space\"> </li>`;\n } else {\n output += `<li class=\"hide letter ${this.phrase[i]}\">${this.phrase[i]}</li>`;\n }\n }\n output += `</ul></div>`\n\n //should override any <li> elements from the previous game\n phraseDisplay.innerHTML = output;\n }", "addPhraseToDisplay() {\n\n for(let i = 0; i < this.phrase.length; i++){\n let li = document.createElement('li');\n li.textContent = this.phrase[i];\n \n if(li.textContent === ' '){\n li.setAttribute('class', 'hide space');\n \n } else {\n li.setAttribute('class', `hide letter ${this.phrase[i]}`);\n }\n\n document.querySelector(\"#phrase ul\").appendChild(li);\n \n }\n }", "function addPhraseToDisplay(array) {\r\n for (let i = 0; i < array.length; i++) {\r\n var arri = array[i];\r\n var liLetter = document.createElement('li');\r\n randomUl.appendChild(liLetter);\r\n liLetter.innerHTML = arri;\r\n\r\n if (arri === ' ') {\r\n liLetter.className = 'space';\r\n } else {\r\n liLetter.className = 'letter';\r\n }\r\n }\r\n}", "addPhraseToDisplay() {\r\n const addLi = this.phrase.split(\"\");\r\n let addUl = '<ul>';\r\n for (let i = 0; i < addLi.length; i++) {\r\n if (addLi[i] !== \" \") {\r\n addUl += `<li class=\"hide letter ${addLi[i]}\">${addLi[i]}</li>`;\r\n } else {\r\n addUl += `<li class=\"space show\"> </li>`;\r\n }\r\n }\r\n addUl += '</ul>';\r\n document.querySelector('#phrase').innerHTML = addUl;\r\n}", "addPhraseToDisplay(phraseObj) {\n const banner = document.getElementById('banner');\n const pressEnter = document.createElement('h3');\n pressEnter.className = 'header reset';\n pressEnter.textContent = 'Press Return/Enter to Reset Game';\n banner.appendChild(pressEnter);\n\n\n const ul = document.querySelector('.main-container ul');\n\n const phrase = phraseObj.phrase;\n let phraseArr = [];\n for (let i = 0; i < phrase.length; i++) {\n phraseArr.push(phrase[i]);\n }\n\n phraseArr.forEach((char) => {\n const isAlpha = (ch) => {\n return /^[A-Z]$/i.test(ch);\n }; // https://stackoverflow.com/questions/40120915/javascript-function-that-returns-true-if-a-letter\n\n const createLi = (string) => {\n const li = document.createElement('li');\n li.className = string;\n li.textContent = char;\n ul.appendChild(li);\n };\n\n isAlpha(char) ? createLi(`hide letter ${char}`) : createLi('space');\n });\n }", "addPhraseToDisplay() {\nlet randomString = this.phrase.toString();\nfor (let i=0; i<randomString.length; i++) {\n\tconst result = /^[A-Za-z]+$/.test(randomString[i]);\n\tif (result) {\n\t\t$('#phrase').append(`<li class=\"hide letter ${randomString[i]}\">${randomString[i]}</li>`);\n\t} else {\n\t\t$('#phrase').append(`<li class=\"space\"></li>`);\t}\n}\n$('#phrase').append(` </ul>\n</div>`);\n}", "addPhraseToDisplay() {\n const arr = this.phrase.split('');\n //console.log(arr);\n arr.forEach((letter) => { \n const regex = /\\w/;\n if (regex.test(letter)) {\n const phrase = document.getElementById('phrase');\n const space = document.createElement('li');\n space.className = `hide letter ${letter}`;\n space.textContent = letter;\n phrase.firstElementChild.appendChild(space);\n } else {\n const phrase = document.getElementById('phrase');\n const space = document.createElement('li');\n space.className = 'space';\n phrase.firstElementChild.appendChild(space);\n }\n \n });\n }", "addphrasetoDisplay(){\n const phraseUL = document.querySelector('#phrase ul');\n this.phrase.forEach(letter => {\n if(letter.match(/^\\s+$/)){\n phraseUL.innerHTML += `\n <li class=\"space\"> </li>\n `;\n } else{\n phraseUL.innerHTML += `\n <li class=\"hide letter ${letter}\">${letter.toUpperCase()}</li>`;\n }\n })\n }", "setupLetterToBeDisplayed(){\r\n // Check if character is alphabet letter\r\n const matchAlphabetCharacter = /[a-z]/i\r\n const matchSpace = /\\s/g\r\n let textNode\r\n let li\r\n\r\n for (var i =0; i < this.phrase.length; i++){\r\n li = document.createElement('LI');\r\n if (this.phrase.charAt(i).match(matchAlphabetCharacter)){\r\n textNode = document.createTextNode(this.phrase.charAt(i))\r\n li.className = 'letter'\r\n li.setAttribute('id', this.phrase.charAt(i))\r\n li.appendChild(textNode)\r\n phraseDisplayUL.appendChild(li)\r\n } else if (this.phrase.charAt(i).match(matchSpace)){\r\n textNode = document.createTextNode(' ')\r\n li.className = 'space'\r\n li.appendChild(textNode)\r\n phraseDisplayUL.appendChild(li)\r\n }\r\n }\r\n }", "addPhraseToDisplay() {\n //select the correct div\n let phraseContainer = $('#phrase ul');\n //split the string into single letters/spaces\n let letters = this.phrase.split(\"\");\n\n //format and append each letter to the ul\n letters.forEach((letter) => {\n //check if letter is a white space\n if (letter !== ' ') {\n phraseContainer.append('<li class=\"hide letter ' + letter + '\">' + letter + '</li>');\n }\n else {\n phraseContainer.append('<li class=\"space\"> </li>');\n }\n });\n //show li element fading in subsuquently\n $('#phrase ul li').hide();\n $('#phrase ul li').each(function(i){\n let _this = this;\n setTimeout(function() {\n $(_this).fadeIn(2000);\n }, 50*i);\n });\n }", "addPhraseToDisplay(){\r\n this.setupLetterToBeDisplayed()\r\n }", "function appendToWordList(){\n word = $(\"#word-guess\").val();\n $(\"#word-list\").append(`<li>${word}</li>`)\n}", "function displayRandom(){\n\t\tvar showWord = document.getElementById(\"displayWord\");\n\t\tvar correct = document.createElement(\"ul\");\n\t\tcorrect.setAttribute('id', 'the-word');\n\n\t\t// need to give each letterPlace a unique ID\n\t\tfor (var i=0;i<randomWord.length;i++) {\n\t\t\tletterPlace = document.createElement(\"li\");\n\t\t\tletterPlace.setAttribute('class','letterPlace');\n\t\t\tletterPlace.setAttribute('id',randomWord[i]);\n\t\t\tif (randomWord != \"-\") {\n\t\t\t\tletterPlace.innerHTML = \"_\";\n\t\t\t}\n\t\t\tshowWord.appendChild(correct);\n\t\t\tcorrect.appendChild(letterPlace);\n\t\t};\n\t}", "function addPhrasetoDisplay(arr) {\n for (let i = 0; i < arr.length; i +=1) {\n const li = document.createElement('li');\n li.textContent = arr[i];\n ul.appendChild(li);\n if ( arr[i] !== ' '){\n li.className = 'letter';\n } else {\n li.className = 'space';\n }\n }\n }", "function addElement (word){\r\n var elementNew = $(\".template li\").clone();\r\n elementNew.prepend('<span> ' + word + '</span>');\r\n list.append(elementNew);\r\n }", "function displayPhraseAsBlanks(phrase) {\n\t// select phrase div \n\tconst phraseDiv = document.querySelector('.phrase');\n\tphraseDiv.innerHTML = '';\n\t// start with empty word div \n\tlet wordDiv = createElement('div', 'className', 'word');\n\tlet letterDiv;\n\tlet spaceDiv;\n\n\t// loop over each letter in phrase\n\tfor (let c = 0; c < phrase.length; c++) {\n\t\tif (phrase[c] === ' ') {\n\t\t\t// end of word, add word to phrase div \n\t\t\tphraseDiv.append(wordDiv);\n\n\t\t\t// append space to phrase div \n\t\t\tspaceDiv = createElement('div', 'className', 'space');\n\t\t\tspaceDiv.classList.add('letter');\n\t\t\tphraseDiv.append(spaceDiv);\n\n\t\t\t// create new word div \n\t\t\twordDiv = createElement('div', 'className', 'word');\n\t\t} else {\n\t\t\t// create letter\n\t\t\tletterDiv = createElement('div', 'className', 'letter');\n\n\t\t\t// add letter to word div\n\t\t\twordDiv.append(letterDiv);\n\t\t}\n\t}\n\n\tphraseDiv.append(wordDiv);\n}", "function wordList() {\r\n\tlet word;\r\n\tfor (let i = 0; i < startingWords.length; i++) {\r\n\t\tword = startingWords[i];\r\n\t\tlet para = document.createElement(\"li\");\r\n\t\tlet node = document.createTextNode(word);\r\n\t\tpara.appendChild(node);\t\t\r\n\t\tlet element = document.getElementById(\"output\");\r\n\t\telement.appendChild(para);\r\n\t}\r\n}", "function createElements( sentence )\n{\n var el;\n var elements = [];\n var phrases = sentence.split( \"\\n\" );\n\t\n for( i in phrases )\n {\n el = document.createElement( \"div\" );\n $( el ).addClass( \"phrase\" ).text( phrases[i] );\n elements.push( el );\n }\n return elements;\n}", "function addGuess() {\n guess = $('#text').val();\n $('#ul').append($(`<li>${guess}</li>`));\n }", "function displayWords() {\n chrome.storage.local.get(['words'], function(object) {\n let pageList = document.getElementById('displayWords');\n if (object.words) {\n searchWords = object.words\n for (var i = 0; i < searchWords.length; i++){\n let listItem = document.createElement('li');\n listItem.innerText = searchWords[i]\n pageList.appendChild(listItem);\n }\n }\n });\n}" ]
[ "0.8781155", "0.85506594", "0.85143125", "0.8478631", "0.8404208", "0.8370243", "0.83626145", "0.8360786", "0.8346124", "0.8333358", "0.82848793", "0.82636285", "0.8241474", "0.8240428", "0.82289034", "0.8222986", "0.8217039", "0.8215389", "0.8209101", "0.81878376", "0.8164752", "0.81536686", "0.81041694", "0.80752367", "0.8073255", "0.80726254", "0.80669355", "0.80575716", "0.80475605", "0.80421525", "0.8029196", "0.8024873", "0.8019941", "0.8013051", "0.8005685", "0.80029416", "0.7989159", "0.7980227", "0.79746974", "0.7940854", "0.79234403", "0.7911006", "0.7898189", "0.7888942", "0.7869691", "0.7865521", "0.78626484", "0.7843139", "0.784218", "0.7841098", "0.78228134", "0.78221524", "0.777699", "0.7764254", "0.77590036", "0.7758363", "0.7739639", "0.77329373", "0.77326035", "0.7712931", "0.77091724", "0.7705492", "0.76784277", "0.7639148", "0.76262045", "0.7623609", "0.75900054", "0.7580763", "0.7574017", "0.75641125", "0.7563723", "0.7535508", "0.7510891", "0.7461705", "0.7456322", "0.74253154", "0.7419288", "0.73778045", "0.73551285", "0.73540634", "0.7348042", "0.7326297", "0.7308624", "0.7243998", "0.71870023", "0.7162804", "0.70558685", "0.70013165", "0.6898838", "0.6895503", "0.6510317", "0.6074538", "0.5965582", "0.5961414", "0.58892345", "0.5889162", "0.5798432", "0.5754568", "0.57391745", "0.570838" ]
0.7979117
38
The checkLetter method: Accepts a letter as a parameter. If the active phrase includes the given letter, it returns true.
checkLetter(letter) { if (this.phrase.includes(letter)) { return true; } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "checkLetter(letter) {\n if (this.phrase.includes(letter)) {\n return true;\n } else {\n return false;\n }\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 } else {\n return false;\n }\n }", "checkLetter(letter) {\n if (this.phrase.includes(letter)) {\n return true;\n }\n return false;\n }", "checkLetter(letter) {\n if ( this.phrase.includes(letter.toLowerCase()) ) {\n return true;\n } else {\n return false;\n }\n }", "checkLetter(letter) {\n if ( this.phrase.includes(letter) ) {\n return true;\n }\n else {\n return false;\n }\n }", "checkLetter(letter) {\n let phrase = this.phrase\n if (phrase.includes(letter)) {\n return true;\n } else {\n return false;\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) {\r\n return this.phrase.toLowerCase().includes(letter);\r\n }", "checkLetter(letter) {\n return this.phrase.includes(letter);\n }", "checkLetter(letter) {\n return this.phrase.includes(letter);\n }", "checkLetter(letter) {\n return this.phrase.includes(letter.textContent);\n }", "checkLetter(letter) {\r\n return this.phrase.includes(letter);\r\n }", "checkLetter(letter) { \n const phrase = this.phrase.toLowerCase();\n return phrase.includes(letter) ? true : false;\n }", "checkLetter(letter) {\r\n return this.phrase.includes(letter)\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) {\n return this.phrase.includes(letter);\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) {\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 return this.phrase.match(letter);\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 }", "function letterCheck(str, letter) { return str.includes(letter) }", "checkIfWordHasLetter(letter) {\r\n return this.text.includes(letter);\r\n }", "checkLetter(letter){\r\n if( this.phrase.indexOf(letter) > -1 ){\r\n this.showMatchedLetter(letter);\r\n return true; \r\n }\r\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 return this.phrase.includes(letter);\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(letterToCheck) {\n if(this.phrase.split(\"\").includes(letterToCheck)) {\n return true;\n }\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) {\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 return !(this.phrase.indexOf(letter) == -1);\r\n }", "checkLetter(guess) {\n if (this.phrase.includes(guess.toLowerCase())) {\n return true;\n } else {\n return false;\n }\n }", "checkLetter(letter) {\n return this.phrase.includes(letter);\n }", "function checkLetter (letter)\r\n{\r\n\tif (letter.match(/[a-z]/i) || letter.match(/[A-Z]/i) || letter.match(/[0-9]/i))\r\n\t\treturn true;\r\n\treturn false;\r\n}", "checkLetter(letter){\n return this.phrase.includes(letter);\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(target){\n if (this.phrase.includes(target)) {\n return true;\n } else {\n return false;\n }\n }", "checkLetter(e){\n const phraseJoin = this.phrase.join('');\n return phraseJoin.includes(e.toLowerCase()) ? true : false;\n }", "function correctLetterCheck(letter) {\n if (character.indexOf(letter.key) > -1) {\n correctLetter(letter);\n } else {\n incorrectLetter(letter);\n }\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}", "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 }", "checkLetter(letter) {\r\n //return matching letters\r\n return this.phrase.includes(letter);\r\n}", "function letterCheck(letter) {\n if (lettersArray.indexOf(letter.key) > -1) {\n correctLetterCheck(letter);\n }\n}", "checkLetter(letter, phrase){\r\n let letterMatchFilter = new RegExp(letter)\r\n let matched = letterMatchFilter.test(phrase)\r\n return matched\r\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 isLetterInWord(word,letter){\r\n \r\n for (var i=0; i<word.length; i++){\r\n if (word[i] == letter) return true;\r\n }\r\n \r\n return false;\r\n}", "checkLetter(phrase, guess) {\r\n\t\tlet correctGuess = false;\r\n\t\tfor (var i = 0; i < phrase.length; i++) {\r\n\t\t\tif (guess === phrase.charAt(i)) {\r\n\t\t\t\tcorrectGuess = true;\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn correctGuess;\r\n\t}", "function checkLetter(letter){\n\tvar match = false;\n\tfor (var i=0; i<secretWord.length; i++) {\n\t\tif(letter === secretWord[i]){\n\t\t\tif (blank[i] === blankSpace) {\n\t\t\t\tblank[i] = letter;\n\t\t\t\tmatch = true;\n\t\t\t\twordSize--;\n\t\t\t}\t\n\t\t}\n\t}\n\tif(match === false) {\n\t\tguesses--;\n\t\tcheckNumGuess();\n\t}\n\treturn match;\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) { //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 }", "function checkLetter(letter) {\n if (movieTitleToArray().includes(letter)) {\n return true;\n } else {\n return false;\n }\n}", "function checkLetter(letter){\n for (let x in letters){\n if (x === letter){\n return true;\n }\n }\n return false;\n}", "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(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(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 }", "checkLetter(char) {\r\n if (this.phrase.includes(char)) {\r\n return char;\r\n }\r\n return null;\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 }", "function checkWords(letter) {\n let regex = /^[a-z]{1}$/;\n let bon = regex.test(letter);\n if (!bon) {\n return false;\n } else if (bon) {\n return true;\n }\n}", "function isLetter(char) {\n const alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';\n return alphabet.includes(char);\n }", "function isLetter( character ) {\n\treturn character.toLowerCase() != character.toUpperCase();\n}", "function isLetter(char) {\n return char.toLowerCase() != char.toUpperCase();\n}", "checkIfLetterHasbeenGuessed(letter) {\r\n return this.guessedLetters.includes(letter);\r\n }", "function checkLetters(letter) {\n\n\tvar lettersInWord = false;\n\tvar letter = event.key;\n\n\t// Check if a letter exists insidethe array at all\n\tfor (var i = 0; i < underscores; i++) {\n\t\t\n\t\tif (word[i] === letter) {\n\t\t\tconsole.log('word[i] ' + word[i])\n\t\t\tlettersInWord = true;\n\t\t}\n\t}\n// If the letter exists in the word, find which index\n\tif (lettersInWord) {\n\t\t\n\t\tfor (var j = 0; j < underscores; j++) {\n\t\t//Populate the blanksAndSuccesses with every correct letter.\n\t\t\tif (word[j] === letter) {\n\t\t\t// This is where the specfic space in blanks is set and letter is equal to the letter when there is a match.\n\t\t\tblanksAndSuccesses[j] = letter;\n\t\t\t}\n\t\t}\t\n\t}\n\t\n\telse {\n\t\twrongLetter.push(letter);\n\t\tguesses--;\n\t}\n}", "function isAlphabetCharacter(letter) {\n return (letter.length === 1) && /[a-z]/i.test(letter);\n}", "function checkLetter(letter)\n{\n\tvar isInWord;\n\tfor (i = 0; i < targetWordArray.length; i++)\n\t{\n\t\tif(letter == targetWordArray[i])\n\t\t{\n\t\t\tisInWord = true;\n\t\t\treplaceLetter(letter);\n\t\t\tcorrectLetters.push(letter);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tisInWord = false;\n\t\t}\n\t}\n\tif(isInWord === false)\n\t{\n\t\twrongLetters.push(letter);\n\t\tremainingGuesses = remainingGuesses - 1;\n\t}\n\telse\n\t{\t\n\t}\n\tdocument.getElementById(\"array-box\").innerHTML = displayWord.join(\"\");\n}", "function isLetter (c)\r\n{ return ( ((c >= \"a\") && (c <= \"z\")) || ((c >= \"A\") && (c <= \"Z\")) )\r\n}", "function isLetter (c)\r\n{ return ( ((c >= \"a\") && (c <= \"z\")) || ((c >= \"A\") && (c <= \"Z\")) )\r\n}", "function allLetter(parameter){ \n\tvar letters = /^[A-Za-z]+$/.test(parameter);\n\tif(letters == true){ \n\t\treturn true; \n\t}else{ \n\t\treturn false; \n\t} \n}", "function checkForLetter(str) {\r\n\tfor (char of str) {\r\n\t\tif (isLetter(char)) {\r\n\t\t\treturn true;\r\n\t\t}\r\n\t}\r\n\treturn false;\r\n}", "function guessLetter() {\n //gets value of the letter guess\n\n guess = document.getElementById(\"playerGuess\").value;\n guess = guess.toLowerCase();\n //Check to see if input is valid or blank\n if (!guess || guess.length > 1 || !(guess.match(/[a-z]/i))){\n alert('Please enter a letter.');\n document.getElementById(\"playerGuess\").value = \"\";\n \n } else {\n //check to see if letter has been guessed\n letterGuessCheck();\n \n //check to see if the letter is in the word\n //isInWord();\n\n }; \n}", "function checkForLetter(letter) {\r\n var foundLetter = false;\r\n\r\n // Search string for letter\r\n for (var i=0; i < randomNumber.length; i++) {\r\n if (letter === randomNumber[i]) {\r\n guesses[i] = letter\r\n foundLetter = true;\r\n}\r\n}\r\n}", "function isLetter(c) {\n return (c.toUpperCase() != c.toLowerCase());\n}", "function isLetter(ch) {\n if (ch.match(/[a-zA-Z]/i)) {\n return true;\n } else {\n return false;\n }\n}", "function isLetter(character) {\n if (character.length > 1) {\n return false;\n }\n var regex = /[A-Za-z]/;\n //character.search returns -1 if not found\n return character.search(regex) > -1;\n}", "function inCompWord(letter){\n\t//see if the letter is in the word-\n\t//if it is add letter to the user's word to display on the screen\n\tvar inWord=false;\n\tfor (var i = 0; i < comp.word.length; i++) {\n\t\t//the guesser's letter is in the computer's word\n\t\t//add letter to the user's word to be later display on the screen\n\t\tif(comp.word[i].toLowerCase()===letter.toLowerCase()){\n\t\t\tif(i===0){\n\t\t\t\tguesser.word[i]=letter.toUpperCase();\n\t\t\t\t//console.log(\"found first letter: \" +guesser.word.join(\"\"));\n\t\t\t}\n\t\t\telse{\n\t\t\t\tguesser.word[i]=letter.toLowerCase();\n\t\t\t\t//console.log(\"found letter: \" +guesser.word.join(\"\"));\n\t\t\t}\n\t\t\tinWord=true;\n\t\t\t\n\t\t}\n\t}\n/*\tif(!inWord)\n\t{\n\t\t//console.log(\"letter not found\");\n\t}*/\n\treturn inWord;\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 }", "checkClickedLetters(letter) {\n\t\treturn !this.letters.includes(letter);\n\t}", "function newLetter(letter){\n\tvar valid = true;\n\tfor( i = 0 ; i < HangMan[curObjName].guesses.length ; i++){\n\t\tif(letter === HangMan[curObjName].guesses[i]){\n\t\t\tvalid = false;\n\t\t\tbreak;\n\t\t};\n\t};\n\treturn valid;\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 isLetter(char){\n\treturn char.match(/[a-z]/i);\n}", "function lettersAllowed(allowed) {\n // Iterate through alphabet\n for (var i = 0; i < alphabet.length; i++) {\n // Checks if input letter is contained in alphabet\n if (alphabet[i] === allowed) {\n console.log(allowed);\n return false;\n }\n }\n\n return true;\n}", "function isLetter(str) {\r\n\tif (str.length === 1 && str.match(/[a-z]/i)) {\r\n\t\treturn true;\r\n\t} else {\r\n\t\treturn false;\r\n\t}\r\n}", "function isLetter(char) {\r\n return char.match(/[a-z]/i);\r\n}", "function checkLetters(letter) {\n\t// check if letter exists in word at all\n\tvar isLetterInWord = false;\n\tfor (var i=0; i<hiddenWord.length; i++) {\n\t\tif (hiddenWord[i]===letter) {\n\t\t\tisLetterInWord= true;\n\t\t\tconsole.log('Letter found');\n\t\t}\n\t}\n\n\tif (isLetterInWord) {\n\t\t// check where in the word the letter exists\n\t\tfor (i=0; i<hiddenWord.length; i++) {\n\t\t\tif(hiddenWord[i]===letter) {\n\t\t\t\tdashes[i] = letter;\n\n\t\t\t}\n\t\t}\n\t\t$('#hiddenWord').html(dashes);\n\t} else {\n\t\twrongGuesses.push(letter+' ');\n\t\tguessesLeft--;\n\t\t$('#guessesLeft').html(guessesLeft);\n\t\t$('#wrongGuesses').html(wrongGuesses);\n\t}\n}", "function wordCheck(letter) {\n var WordLetters = false;\n for (var i = 0; i < nameLength; i++) {\n if (chosenName[i] === letter) {\n WordLetters = true;\n }\n }\n\n if (WordLetters) {\n for (var i = 0; i < nameLength; i++) {\n if (chosenName[i] === letter) {\n emptyWord[i] = letter;\n }\n }\n }\n\n else (chosenName[i] !== letter); {\n incorrectGuess.push(letter);\n incorrect--;\n }\n\n \n}", "function isLetter(key) {\n if (key.toLowerCase() != key.toUpperCase() && key.length === 1) {\n return true;\n } else {\n return false;\n }\n}", "function isLetter(c) {\r\n return isUppercase(c) || isLowercase(c);\r\n}", "function checkLetters(letter) {\n\n\t// a boolean which will be toggled based on whether \n\tvar letterInWord = false;\n\n\tfor (var i=0; i < numBlanks; i++) {\n\t\tif (chosenWord[i] === letter) {\n\t\t\t// If the letter exists then change this to true\n\t\t\t// It will be used in the next step\n\t\t\tletterInWord = true;\n\t\t}\n\t}\n\n\t// If the letter exists somewhere in the word\n\t// then figure out exactly where (what index)\n\tif (letterInWord) {\n\t\t// Loop throught the word\n\t\tfor (var j=0; j < numBlanks; j++) {\n\t\t\t//Populate the blanksAndSuccesses with every\n\t\t\t//instance of the letter\n\t\t\tif (chosenWord[j] === letter) {\n\t\t\t\t//set specific blank spaces to equal the correct\n\t\t\t\t// letter when there is a match\n\t\t\t\tblanksAndSuccesses[j] = letter;\n\t\t\t}\n\t\t}\n\t\t// Log for testing purposes\n\t\tconsole.log(blanksAndSuccesses);\n\t} \n\n\t// If the letter doesn't exist at all...\n\telse {\n\t\t// Then we add the letter at the list of wrong letters\n\t\twrongGuesses.push(letter);\n\t\t// We also subtract one of the guesses\n\t\tnumGuesses--;\n\t}\n}", "function checkLetters(letter) {\n\n\n var letterInWord = false;\n\n for (var i = 0; i < blanks; i++) {\n if (word[i] === letter) {\n letterInWord = true;\n\n }\n }\n\n if (letterInWord) {\n for (var i = 0; i < blanks; i++) {\n if (word[i] === letter) {\n correctLetters[i] = letter;\n }\n\n }\n } else {\n guessesLeft--;\n wrongLetters.push(letter)\n }\n\n\n}", "function gimmiTrue(inputString, letter) {\n var x = false;\n inputString.split('').forEach(function (e) {\n if (e === letter) {\n x = true;\n }\n });\n return x;\n}", "function checkLetter(input){\n\t\t// Check if word has been used before\n\t\tvar counter = 0; // counts how many times the letter appears in the word\n\t\tfor(l=0; l< word.length; l++){\n\t\t\tvar currentGuess = input;\n\t\t\tvar currentCheck = word.charAt(l);\n\t\t\tif(currentGuess === currentCheck){\n\t\t\t\tcorrectGuesses++;\n\t\t\t\tcounter++;\n\t\t\t}\n\t\t}\n\n\t\tif(counter === 0){\n\t\t\t\tincorrectGuesses++;\n\t\t\t\tplayVideo();\n\t\t\t}\n\n\t\tfor(k=0; k < word.length; k++){\n\t\t\tvar currentGuess = input;\n\t\t\tvar currentCheck = word.charAt(k);\n\t\t\tif(input === word.charAt(k)){\n\t\t\t\tanswerMask[k] = input;\n\t\t\t\t// correctGuesses++;\n\t\t\t}\n\t\t}\n\t\theartbeat = chances - incorrectGuesses;\n\t\t// log(\"incorrectGuesses \" + incorrectGuesses);\n\t\t// log(\"correctGuesses\" + correctGuesses);\n\n\t\tguessedLetters.push(input);\n\t}", "function isLatinLetter(letter) {\n // Combining marks are a subset of non-spacing-mark.\n if (!pL_regexp.test(letter) && !pMn_regexp.test(letter)) {\n return false;\n }\n\n return latinLetterRegexp.test(letter);\n}", "function isLatinLetter(letter) {\n // Combining marks are a subset of non-spacing-mark.\n if (!pL_regexp.test(letter) && !pMn_regexp.test(letter)) {\n return false;\n }\n\n return latinLetterRegexp.test(letter);\n}", "function isLatinLetter(letter) {\n // Combining marks are a subset of non-spacing-mark.\n if (!pL_regexp.test(letter) && !pMn_regexp.test(letter)) {\n return false;\n }\n\n return latinLetterRegexp.test(letter);\n}", "function inWord(letter, wordArray) {\n for (var i = 0; i < wordArray.length; i++) {\n if (wordArray.indexOf(letter) >= 0) {\n return true;\n }\n else {\n return false;\n }\n }\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 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}", "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 isLetter(input) {\n if (input === 'Y' || input === 'y' || input === 'n' || input === 'N') {\n return true;\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}" ]
[ "0.87091476", "0.86987036", "0.86860406", "0.8622862", "0.8615918", "0.85853875", "0.8554518", "0.85086244", "0.84589833", "0.8450262", "0.8450262", "0.84481806", "0.8430045", "0.8416407", "0.836383", "0.83588785", "0.83105826", "0.82785594", "0.82606035", "0.8249057", "0.8214584", "0.8209889", "0.8140029", "0.81026834", "0.80774975", "0.804233", "0.8016387", "0.79965603", "0.799152", "0.7963256", "0.7931801", "0.7912324", "0.78952116", "0.7876828", "0.7841323", "0.7836911", "0.77776086", "0.772472", "0.77079046", "0.7703793", "0.7637256", "0.7621939", "0.76188004", "0.7600951", "0.7589698", "0.7540877", "0.74977666", "0.7413047", "0.73950446", "0.73491293", "0.7290001", "0.7285031", "0.72380733", "0.72361183", "0.7227584", "0.7160173", "0.7153703", "0.71346855", "0.71323335", "0.70822066", "0.7008712", "0.69852614", "0.6982984", "0.69748145", "0.6964117", "0.6941077", "0.6941077", "0.6922696", "0.6920711", "0.691227", "0.6897995", "0.68828756", "0.6881025", "0.6878718", "0.68759406", "0.6851331", "0.6786762", "0.67771274", "0.6763608", "0.67553335", "0.6713527", "0.67041993", "0.6698573", "0.6693524", "0.6663202", "0.66611105", "0.6661055", "0.6655396", "0.6630024", "0.6608602", "0.65938145", "0.6590098", "0.6590098", "0.6590098", "0.658774", "0.65709907", "0.65699244", "0.65687925", "0.6553968", "0.6553164" ]
0.8268021
18
The showMatchedLetter method: Accepts a letter as a parameter. Removes the 'hide' class and adds the 'show' class to all the matching letters in the phrase.
showMatchedLetter(letter) { let letters = document.getElementsByClassName(letter); for (let i = 0; i < letters.length; i++) { if (letters[i].innerHTML === letter) { letters[i].classList.remove('hide'); letters[i].classList.add('show'); } } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "showMatchedLetter(letter) {\r\n const letters = Array.from(document.getElementsByClassName(letter));\r\n letters.forEach(match => {\r\n match.classList.remove('hide');\r\n match.classList.add('show');\r\n });\r\n }", "showMatchedLetter(letter) {\r\n\r\n // Get the matchedLetters that have a class name letter\r\n const matchedLetters = document.getElementsByClassName(letter);\r\n\r\n // Loop through the matchedLetters and replace the hide class with show\r\n for (let k = 0; k < matchedLetters.length; k++) {\r\n matchedLetters[k].className = matchedLetters[k].className.replace(/\\bhide\\b/g, \"show\");\r\n } \r\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) {\r\n const letters = document.querySelectorAll(`.hide.${letter}`);\r\n for (let i=0; i<letters.length; i+=1) {\r\n if (letter === letters[i].textContent.toLowerCase()) {\r\n letters[i].className = `show letter ${letter}`;\r\n }\r\n }\r\n }", "showMatchedLetter(letter) {\n $(\".letter\").each(function(index) {\n if (this.innerText === letter) {\n $(this).removeClass('hide');\n $(this).addClass('show');\n }\n });\n }", "showMatchedLetter(letter) {\n const displayedLetters = document.querySelectorAll('.letter')\n\n displayedLetters.forEach(item => {\n if (item.classList.contains('letter') && item.innerHTML === letter) {\n item.classList.add('show');\n item.classList.remove('hide');\n item.innerHTML = `${letter}`;\n }\n })\n }", "showMatchedLetter(letter) {\r\n const matchingLetterNodes = document.querySelectorAll(`li.hide.letter.${letter}`)\r\n for (let node of matchingLetterNodes) {\r\n node.className = node.className.replace(\"hide\", \"show\");\r\n }\r\n }", "showMatchedLetter(letter) {\n for (let i = 0; i < ul.children.length; i++) {\n let letterVisible = document.querySelector(`#phrase > ul > li.hide.letter.${letter}`);\n // if letter matches set class to show letter\n if (letterVisible !== null) {\n letterVisible.className = `show letter ${letter}`;\n }\n }\n }", "showMatchedLetter(letter) {\n const listOfLetters = document.getElementsByClassName(`hide letter ${letter}`);\n this.listOfLettersLenght = listOfLetters.length;\n \n while (listOfLetters.length) {\n listOfLetters[0].className = \"show\";\n }\n }", "showMatchedLetter(letter) {\n const hiddenLetters = document.querySelectorAll('li.hide.letter');\n hiddenLetters.forEach(hiddenLetter => {\n if (letter.toLowerCase() === hiddenLetter.textContent) {\n hiddenLetter.classList.remove('hide');\n hiddenLetter.classList.add('show');\n }\n })\n }", "showMatchedLetter(letter) {\n\t\tlet liMatches = document.querySelectorAll('LI.letter');\n\t\tfor (let i = 0; i < liMatches.length; i += 1) {\n\t\t\tif (liMatches[i].className[12] === letter) {\n\t\t\t\tliMatches[i].className = 'show';\n\t\t\t}\n\t\t}\n\n\t}", "showMatchedLetter(letter) {\n let matches = document\n .getElementById(\"phrase\")\n .getElementsByClassName(letter);\n //must make collection into an array to use array methods\n //learned from https://stackoverflow.com/questions/3871547/js-iterating-over-result-of-getelementsbyclassname-using-array-foreach\n Array.from(matches).forEach((match) => {\n match.classList.replace(\"hide\", \"show\");\n });\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 }", "showMatchedLetter(letter) {\n const letterElements = document.getElementsByClassName(letter);\n for (let i = 0; i < letterElements.length; i ++) {\n letterElements[i].classList.add('show');\n }\n }", "showMatchedLetter(char) {\r\n const letters = document.getElementsByClassName('letter');\r\n for (let i = 0; i < letters.length; i++) {\r\n if (char === letters[i].textContent) {\r\n letters[i].classList.add(\"show\");\r\n }\r\n }\r\n }", "showMatchedLetter(guess) {\r\n\t\t// selects all the elements with the class matching the letter guessed\r\n\t\tlet classSelector = `.${guess}`;\r\n\t\t// removes the hide class and adds the show class\r\n\t\t$(classSelector).removeClass(\"hide\").addClass(\"show\");\r\n\t}", "showMatchedLetter(correctLetter){\n correctLetter.classList.remove('hide');\n correctLetter.classList.add('show');\n }", "showMatchedLetter(letter) {\r\n const listItem = document.querySelectorAll('.letter');\r\n // Add 'show' class if passed letter mathces\r\n for (let li of listItem) {\r\n if (li.innerText === letter) {\r\n li.classList.remove('hide');\r\n li.classList.add('show');\r\n }\r\n }\r\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 }", "showMatchedLetter(letter) {\r\n const phraseDivUl = document.getElementById('phrase').firstElementChild.children;\r\n for (let i = 0; i < phraseDivUl.length; i++) {\r\n if (letter === phraseDivUl[i].textContent) {\r\n phraseDivUl[i].className = `show letter ${phraseDivUl[i].textContent}`;\r\n }\r\n }\r\n }", "showMatchedLetter(letter) {\n const letterSpace = document.getElementsByClassName(`hide letter ${letter}`);\n\n // keeps the length of letterSpace array value constant\n const letterLength = letterSpace.length;\n \n /* loops through all classes with the 'hide letter (letter parameter)' \n and changes the class name to 'show letter (letter parameter)'*/\n for (let i = 0; i < letterLength; i++) {\n letterSpace[0].className = `show letter ${letter}`;\n }\n }", "showMatchedLetter(letter) {\n let matchedLetters = document.getElementsByClassName(letter); \n let i;\n for (i = 0; i < matchedLetters.length;i++) {\n matchedLetters[i].classList.remove(\"hide\");\n matchedLetters[i].classList.add(\"show\");\n }\n\n }", "showMatchedLetter(letter)\r\n {\r\n // create letter class constant\r\n\r\n const letterClass = 'hide letter ' + letter;\r\n\r\n // get all li elements with that class name\r\n\r\n var allLIWithLetterClassNodeList = document.getElementsByClassName(letterClass);\r\n var allLIWithLetterClassArray = Array.from(allLIWithLetterClassNodeList);\r\n\r\n // loop through all li elements found and set class to show\r\n \r\n for (let index = 0; index < allLIWithLetterClassArray.length; index++) \r\n {\r\n allLIWithLetterClassArray[index].className = 'show';\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 }", "showMatchedLetter(letter) {\n const list = document.getElementsByClassName('hide letter');\n for (const li of list) {\n if (li.textContent === letter.textContent) {\n li.className = 'show';\n letter.classList.add(\"chosen\");\n letter.disabled = true;\n }\n }\n // called twice to fix bug: the same consecutive letter was not being revealed, i.e., in the word `call` guessing l would only display the first l.\n for (const li of list) {\n if (li.textContent === letter.textContent) {\n li.className = 'show';\n letter.classList.add(\"chosen\");\n letter.disabled = true;\n }\n }\n }", "showMatchedLetter(letter) {\n let li = document.querySelectorAll('li')\n for (let i = 0; i < li.length; i++) {\n if (li[i].className === `hide letter ${letter}`) {\n li[i].className = `show letter ${letter}`;\n } else {\n }\n }\n }", "showMatchedLetter(letter) {\n let matchedLetterLIs = $(`.${letter}`);\n matchedLetterLIs.removeClass('hide').addClass('show');\n\n }", "showMatchedLetter(letter){\r\n $(letter).addClass('show');\r\n // display the char of the corresponding letters check if game is won\r\n }", "showMatchedLetter(e) {\n \t\t$('li').parent().children(`.${this.letterGuess}`).removeClass('hide').addClass('show');\n\n\t}", "showMatchedLetter(l) {\r\n\r\n let letterToBeShown = game.activePhrase.toLowerCase().split(\"\").find(i => i === l);\r\n let listOfDOMElementLetters = document.getElementsByClassName(letterToBeShown);\r\n for (let i = 0; i < listOfDOMElementLetters.length; i++) {\r\n listOfDOMElementLetters[i].className = \"show letter \" + letterToBeShown;\r\n }\r\n }", "showMatchedLetter(letter) {\n const selectedLetter = document.querySelectorAll(\".letter\");\n selectedLetter.forEach(element => {\n if (element.innerHTML === letter) {\n element.className = \"show\";\n }\n });\n }", "showMatchedLetter(letter) {\n let letterToShow = document.querySelector(`.hide.letter.${letter}`);\n letterToShow.className = `show letter ${letter}`\n }", "showMatchedLetter(letter) {\n document.querySelectorAll('ul > li').forEach(liElement => {\n if(liElement.className.slice(-1) === letter && liElement.className !== 'space'){\n liElement.classList.remove('hide');\n liElement.classList.add('show');\n }\n })\n }", "showMatchedLetter(letter) {\r\n const reference = `.hide.letter.${letter}`;\r\n const correctLetters = document.querySelectorAll(reference);\r\n for (let each of correctLetters) {\r\n each.classList.remove('hide');\r\n each.classList.add('show');\r\n }\r\n}", "showMatchedLetter(letter) {\n \n const letterLiCollection = document.getElementById('phrase').firstElementChild;\n \n for ( let i = 0; i < letterLiCollection.childElementCount; i++) {\n \n const currentLi = letterLiCollection.children[i];\n\n if (currentLi.innerHTML === letter ) {\n currentLi.className = `show letter ${letter}`;\n }\n }\n }", "showMatchedLetter(keyPressed){\n let letters = document.getElementsByClassName('js-letter');\n for (let j = 0; j < letters.length; j++){\n if(letters[j].textContent === keyPressed){\n letters[j].classList.remove('hide');\n letters[j].classList.add('show');\n }\n }\n }", "showMatchedLetter(letter) {\n const matchedLetter = document.getElementsByClassName(letter);\n\n for (let i = 0; i < matchedLetter.length; i++) {\n matchedLetter[i].classList.remove('hide');\n matchedLetter[i].classList.add('show');\n }\n}", "showMatchedLetter(e) {\n let lettersToCheck = document.getElementsByClassName(e.target.innerText)\n for (i = 0; i < lettersToCheck.length; i++) {\n\n lettersToCheck[i].classList.remove(\"hide\")\n lettersToCheck[i].classList.add(\"show\")\n };\n }", "showMatchedLetter(letter) {\n document.querySelectorAll(`.${letter}`).forEach((element) => {\n element.classList.remove('hide');\n element.classList.add('show', 'animated', 'flipInY');\n });\n }", "showMatchedLetter(letter) {\r\n const matchLetterElement = document.querySelectorAll('.letter');\r\n matchLetterElement.forEach(letterElement =>{\r\n // console.log(letterElement);\r\n // console.log(letterElement.textContent);\r\n if(letterElement.innerHTML === letter.textContent){\r\n letterElement.classList.remove('hide');\r\n console.log(letterElement);\r\n letterElement.classList.add('show');\r\n }\r\n });\r\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 }", "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 }", "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 }", "showMatchedLetter(letter) {\n const letters = document.querySelectorAll(`.${letter}`);\n letters.forEach((buttons) => {\n buttons.classList.remove('hide');\n buttons.classList.add('show');\n });\n }", "showMatchedLetter(guess){\n //phrase colors \n let phraseLetter = document.querySelectorAll('li.hide.letter');\n phraseLetter.forEach(letter =>{\n if(guess == letter.textContent.toLowerCase()){\n letter.classList.add('show');\n letter.classList.remove('hide');\n }\n })\n }", "showMatchedLetter(letter) {\r\n const list = document.querySelectorAll('li');\r\n for (let i = 0; i < list.length; i+=1) {\r\n if (letter === list[i].textContent){\r\n list[i].classList.add('show');\r\n }\r\n }\r\n }", "showMatchedLetter(letter) {\n const appendedLI = document.querySelectorAll('#phrase ul li');\n\n appendedLI.forEach((element) => {\n if (element.textContent === letter) {\n element.className = 'letter show';\n }\n });\n }", "showMatchedLetter(letter){\n\n const phrases = document.querySelector('#phrase ul').children;\n\n\n\n for (let i = 0; i < phrases.length; i++) {\n if (phrases[i].textContent === letter) {\n phrases[i].setAttribute('class', `show letter ${letter}`);\n\n }\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 LetterShow(letter, found) {\n\tthis.letter = letter;\n\tthis.found = false;\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}", "showMatchedLetter(e){\n const matchedLi = document.querySelectorAll(`.${e}`);\n for(let i =0; i < matchedLi.length; i++){\n matchedLi[i].classList.remove('hide');\n matchedLi[i].classList.add('show');\n this.flipAnimation(matchedLi[i]);\n }\n }", "showMatchedLetter(letter) {\n const liElement = document.getElementsByClassName('letter');\n for (let i = 0; i < liElement.length; i++) {\n if (liElement[i].innerHTML === letter) {\n liElement[i].className = 'letter show';\n console.log('Success'); //track if letter is matched in the console\n\n } else {\n console.log('Fail'); //track if letter is not matched in the console\n }\n }\n }", "function checkLetter(letter) {\n let match = false;\n const letters = ul.getElementsByClassName('letter');\n for (let i = 0; i < letters.length; i += 1) {\n if (letters[i].textContent == letter) {\n letters[i].classList.add('show', 'fade');\n match = true;\n };\n };\n if (match) {\n return letter;\n } else {\n return null;\n };\n}", "showMatchedLetter(letter) { //method receives the letter the user selected as a parameter and if the letter is in the phrase it will reveal the letter on the game board\r\n console.log('in showMatchedLetter method'); \r\n let matchedLettersLi = document.querySelectorAll('#phrase ul li');// selects LI's that represent each character in the phrase\r\n matchedLettersLi.forEach(li => { //iterates through each LI element\r\n if (li.innerHTML === letter) { //if LI element's innerHTML is the same as the letter the user selected\r\n li.classList.add('show'); //show the LI on the page(by changing it's css class)\r\n }\r\n });\r\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(guess) {\n const letterAnswers = document.querySelectorAll('.letter');\n const li = document.querySelectorAll('.letter');\n let match;\n for (let i = 0; i < letterAnswers.length; i +=1) {\n let show = letterAnswers[i].textContent;\n if (show === guess) {\n li[i].classList.add('spin');\n li[i].className += ' show';\n match = show;\n }\n }\n return match;\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 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}", "showMatchedLetter(){\n $('.correct').css('color', 'black');\n $('.correct').css('background-color', 'green');\n $('.correct').css('text-shadow', '4px black');\n }", "checkLetter(letter){\r\n if( this.phrase.indexOf(letter) > -1 ){\r\n this.showMatchedLetter(letter);\r\n return true; \r\n }\r\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}", "function letters() {\n //don't display letter until it is checked\n word.showLetter = false;\n this.displayLetter = function(letter) {\n //check the entire word\n for (var i = 0; i < word.wordChoice.underScore.length; i++) {\n //if letter is in the word then show it\n if (letter === word.wordChoice.wordToUse[i]) {\n word.showLetter = true;\n }\n }\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}", "function displayCorrectLetter() {\n\tvar parentH1 = document.getElementById('letter-display-text');\n\t//Remove all child spans of parentH1\n\twhile (parentH1.firstChild) {\n \tparentH1.removeChild(parentH1.firstChild);\n\t}\n\tfor ( var i = 0; i < selectedWordArray.length; i++ ) {\n\t\tvar childSpan = document.createElement('span');\n\t\tfor(var j=0; j< guessedLetters.length; j++){\n\t\t\t//Populate the letter-display div if letters match.\n\t\t\tif(selectedWordArray[i] == guessedLetters[j]) {\n\t\t\t\tchildSpan.innerHTML = guessedLetters[j];\n\t\t\t}\n\t\t}\n\t\t//Populate the letter-display div with a space if letters don't match.\n\t\tif(childSpan.innerHTML == \"\"){\n\t\t\tchildSpan.innerHTML = '&nbsp;';\n\t\t}\n\t\tparentH1.appendChild(childSpan);\n\t\t//Add a spacing class in the letter has no value.\n\t\tif(selectedWordArray[i] == \" \"){\n\t\t\tchildSpan = parentH1.lastChild;\n\t\t\tchildSpan.className = \"space\";\n\t\t}\n\t}\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}", "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 }", "function checkLetter(letter) {\n // Get all li elements with class: letter\n const liLetters = document.getElementsByClassName('letter');\n // Other variables used in function \n let letterFound = null;\n \n // Loop through all li letters and check if match with pressed letter\n for (let i = 0; i < liLetters.length; i++) {\n if (liLetters[i].textContent === letter) {\n liLetters[i].className += ' ' + 'show';\n letterFound = liLetters[i].textContent;\n }\n } \n // If the letter is guessed return the letter or otherwise null\n return letterFound;\n}", "revealPhrase() {\n for (const node of letterNodes) { // for all the letter nodes\n for (const className of node.classList) { // for all class names in each letter\n if (className === 'hide') {\n node.classList.add('show');\n node.classList.add('reveal');\n node.classList.remove('hide');\n }\n }\n }\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}", "showMatchedLetter(letterToCheck) {\n if (this.checkLetter(letterToCheck)) {\n //count to select the correct li\n let count = 0;\n this.phrase.split(\"\").forEach((letter) => {\n if (letter === letterToCheck) {\n //select the corresponding li\n $('ul li:eq('+count+')').removeClass().addClass('show letter ' + letter).attr('value', 'guessed');\n }\n count += 1;\n });\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}", "function checkLetter(target) {\n const letter = document.querySelectorAll(\".letter\");\n const clickedLetter = target.textContent;\n let letterFound = null;\n\n for (let i = 0; i < letter.length; i++) {\n if (letter[i].textContent.toLocaleLowerCase() === clickedLetter) {\n letter[i].classList.add(\"show\");\n letterFound = letter[i].textContent;\n }\n }\n return letterFound;\n }", "function filterByLetter() {\n clearSearchbar();\n const letter = this.innerText;\n const allTerms = Array.from(document.querySelectorAll(\".term\"));\n allTerms.forEach(term => {\n if (term.textContent[0] !== letter) {\n term.parentElement.parentElement.parentElement.classList.add(\"hidden\");\n }\n else(term.parentElement.parentElement.parentElement.classList.remove(\"hidden\"));\n });\n checkAllTermsHidden();\n}", "function checkLetter (clickedButton) {\r\n const checkLetter = document.querySelectorAll('li');\r\n let match = null;\r\n for ( i = 0; i < checkLetter.length; i++) {\r\n if ( checkLetter[i].textContent.toLowerCase() == clickedButton.textContent.toLowerCase() ) {\r\n checkLetter[i].classList.add(\"show\");\r\n match = checkLetter[i].textContent;\r\n }\r\n }\r\n return match;\r\n}", "checkLetter(index){\r\n\r\n letter = index.innerHTML;\r\n\r\n let check = \".letter.\" + letter;\r\n\r\n if($('.letter').hasClass(letter)){\r\n this.showMatchedLetter(check);\r\n index.classList.add('chosen');\r\n } else {\r\n index.classList.add('wrong');\r\n game.removeALife();\r\n }\r\n\r\n game.checkForWin();\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}", "function checkLetter(clickedButton) {\n var letters = document.getElementsByClassName(\"letter\");\n for ( i = 0; i < letters.length; i++) {\n var letter = letters[i].innerText;\n if (clickedButton == letter) {\n letters[i].classList.add(\"show\");\n var letterFound = letter;\n }\n }\n\n if (letterFound) {\n return letterFound;\n\n } else {\n missed += 1;\n return null;\n }\n\n}", "function checkLetter(keyLetter) {\n let list = document.querySelectorAll('.letter');\n let correctLetter = false;\n \n for (let i = 0; i < list.length; i++) {\n \n let listLetter = list[i].textContent;\n \n if (listLetter === keyLetter) {\n correctLetter = true;\n list[i].classList.add('show');\n // CSS transistion added for exceed expectations\n list[i].style.transition = 'all 2s';\n } \n }\n \n if (correctLetter === false) {\n missed += 1;\n } if (missed == 1) {\n life[0].style.display = 'none';\n } if (missed == 2) {\n life[1].style.display = 'none';\n } if (missed == 3) {\n life[2].style.display = 'none';\n } if (missed == 4) {\n life[3].style.display = 'none';\n } if (missed == 5) {\n life[4].style.display = 'none';\n }\n \n return correctLetter;\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}", "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 }", "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", "function match(a,b) {\n\t//if the letter input matches the current string\n\tif(a==b){\n\t\t\n\t\tfinalDisplay(i,guess);\n\t\tmatched++;\t\n\t}\n\n\n\t\n}", "function showLetter() {\n\n a.style.visibility = \"visible\";\n b.style.visibility = \"visible\";\n c.style.visibility = \"visible\";\n d.style.visibility = \"visible\";\n e.style.visibility = \"visible\";\n f.style.visibility = \"visible\";\n g.style.visibility = \"visible\";\n h.style.visibility = \"visible\";\n i.style.visibility = \"visible\";\n j.style.visibility = \"visible\";\n k.style.visibility = \"visible\";\n l.style.visibility = \"visible\";\n m.style.visibility = \"visible\";\n n.style.visibility = \"visible\";\n o.style.visibility = \"visible\";\n p.style.visibility = \"visible\";\n q.style.visibility = \"visible\";\n r.style.visibility = \"visible\";\n s.style.visibility = \"visible\";\n t.style.visibility = \"visible\";\n u.style.visibility = \"visible\";\n v.style.visibility = \"visible\";\n w.style.visibility = \"visible\";\n x.style.visibility = \"visible\";\n y.style.visibility = \"visible\";\n z.style.visibility = \"visible\";\n\n\n notLetters.innerHTML = \"\";\n\n\n\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 }", "function displayLetter(letter) {\n\t// for each char in wordAsDashes, if matches currentWord --> display\n\tfor (i = 0; i < currentWord.length; i++) {\n\t\tif (letter == wordAsArr[i]) {\n\t\t\tdashesArray[i * 2] = letter;\n\t\t\tconsole.log(dashesArray);\n\t\t}\n\t}\n\tdocument.getElementById(\"currentWord\").innerHTML = dashesArray.join(\"\");\n\tcheckForWin();\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 checkLetter(guessBtn) {\n // Loop through the characters in the phrase\n for (let i = 0; i < li.length; i++) {\n // Make sure a letter is chosen\n if ( li[i].classList.contains('letter') ) {\n\n // Check the textContent of the button to see if there's a match\n if (li[i].textContent === guessBtn) {\n // Add the 'show' class\n li[i].classList.add('show');\n // Save the correct guess\n letterFound = guessBtn;\n }\n }\n }\n\n // Return the matching letter guessed correct;\n // Otherwise, return null for incorrect guess\n return letterFound;\n}", "function letterMatched() {\n for (var i = 0; i < randomWords.length; i++) {\n if (letterClicked === randomWords[i]) {\n emptySpacesForDashes[i] = letterClicked;\n }\n $('#underscore').text(emptySpacesForDashes.join(' '));\n } \n}", "addPhraseToDisplay(){\n\t\tthis.phrase.split('').forEach(phraseLetter => {\n\t\t\tconst li = document.createElement('li');\n\t\t\tdocument.querySelector(\"#phrase ul\").appendChild(li);\n\t\t\tli.textContent = phraseLetter;\n\t\t\tif (phraseLetter !== ' ') {\n li.classList.add('letter', 'hide', phraseLetter)\n } else {\n li.classList.add('space');\n }\n\t\t})\n }", "checkSpace(letters, correctLetters) {\n \n if(correctLetters.indexOf(letters) >= 0) {\n return \"show letter\";\n } else if (letters === \" \") {\n return 'space';\n } else {\n return 'hide letter'\n }\n }", "function displayLetter(myword, letter, word){ // by jaguar\r\n let display = \"\";\r\n let mywordarr = myword.split(\"\")\r\n for(let i = 0; i < myword.length; i++){\r\n if(i != myword.length){\r\n if(letter === word.charAt(i)){\r\n display = display + letter + \" \";\r\n mywordarr[i] = letter\r\n } else {\r\n display += myword.charAt(i) + \" \";\r\n }\r\n } else {\r\n display += myword.charAt(i);\r\n }\r\n }\r\n displayed = mywordarr.join(\"\")\r\n document.getElementById(\"display\").innerHTML = display;\r\n checkWincondition(display, word)\r\n}", "addPhraseToDisplay() {\n const phraseContainer = document.querySelector('#phrase ul');\n phraseContainer.className = 'phrase';\n\n //split the phrase into indivudiual letters\n const letters = this.phrase.split('');\n const regex = new RegExp(/[a-z]/);\n\n /** compare the letters to the RegEx\n if those letters match then add classname of letter\n If not then add classname of space\n append each new element \n */\n letters.forEach(letter => {\n if (regex.test(letter)) {\n const newListItem = document.createElement('li');\n newListItem.className = 'letter hide'\n newListItem.innerHTML = `${letter}`;\n phraseContainer.appendChild(newListItem);\n } else {\n const newListItem = document.createElement('li');\n newListItem.className = 'space'\n phraseContainer.appendChild(newListItem);\n }\n });\n }", "function displayGuesses(letter) {\n\tvar newguess = document.getElementById(letter.toLowerCase());\n\tconsole.log(\"newguess: \" + newguess);\n\tnewguess.style.opacity = 1;\n}", "function revealWord(letter, answer_word, masked_word, incorrect_letter_guesses){\n var new_word = '';\n\n if (! isLetter(letter)){\n $(\".letter_alert\").text(letter + \" Invalid Letter\");\n return masked_word;\n }\n\n if (incorrect_letter_guesses.has(letter) || masked_word.indexOf(letter) != -1){\n $(\".letter_alert\").text(letter + \" Already Guessed\");\n return masked_word;\n }\n\n if (answer_word.indexOf(letter) === -1){\n guess_count -= 1;\n incorrect_letter_guesses.add(letter);\n $(\".your_letters\").append(letter);\n $(\".panel-title\").text(\"You have \" + guess_count + \" guesses left\");\n return masked_word;\n }\n\n for (var i = 0; i < answer_word.length; i++){\n if (letter == answer_word[i]){\n new_word += letter;\n }\n else {\n new_word += masked_word[i];\n }\n }\n return new_word;\n}", "function getLetter(word,letter,display){\r\n var newdisp = '';\r\n \r\n for (var i=0; i<word.length; i++){\r\n if (word[i] == letter) {\r\n newdisp += letter;\r\n } \r\n else {\r\n newdisp += display[i];\r\n }\r\n }\r\n \r\n return newdisp;\r\n}", "addPhraseToDisplay() {\r\n //str.match(/[a-z]/i\r\n let ul = document.querySelector('UL'),\r\n li;\r\n let displayPhrase = this.phrase;\r\n for (let i = 0; i < displayPhrase.length; i++) {\r\n if (displayPhrase[i].match(/[a-z]/i)) {\r\n li = document.createElement('LI');\r\n li.classList.add('hide', 'letter');\r\n li.innerText = displayPhrase[i];\r\n ul.appendChild(li);\r\n } else if (displayPhrase[i].match('')) {\r\n li = document.createElement('LI');\r\n li.classList.add('space');\r\n li.innerText = displayPhrase[i];\r\n ul.appendChild(li);\r\n }\r\n }\r\n }", "addPhraseToDisplay() {\nlet randomString = this.phrase.toString();\nfor (let i=0; i<randomString.length; i++) {\n\tconst result = /^[A-Za-z]+$/.test(randomString[i]);\n\tif (result) {\n\t\t$('#phrase').append(`<li class=\"hide letter ${randomString[i]}\">${randomString[i]}</li>`);\n\t} else {\n\t\t$('#phrase').append(`<li class=\"space\"></li>`);\t}\n}\n$('#phrase').append(` </ul>\n</div>`);\n}", "showLetter() {\n if(this.isGuessed) {\n return this.character;\n } else {\n return \"_\"\n }\n }" ]
[ "0.8513973", "0.850368", "0.8430845", "0.8408163", "0.8275841", "0.8239807", "0.82377994", "0.8217139", "0.8179612", "0.8159915", "0.81547004", "0.812789", "0.80718374", "0.80426794", "0.8040258", "0.80238235", "0.8021834", "0.7997904", "0.79789376", "0.7977448", "0.79643834", "0.7926564", "0.7921003", "0.7872754", "0.78583187", "0.77554744", "0.7743252", "0.7729099", "0.7710614", "0.76917404", "0.7689254", "0.76872", "0.7677486", "0.7640197", "0.76401055", "0.76218045", "0.75833166", "0.75720066", "0.7560165", "0.7526291", "0.7494819", "0.7395559", "0.73728704", "0.7362079", "0.73061764", "0.71550965", "0.7154537", "0.70929915", "0.7020409", "0.70203024", "0.69472253", "0.68986475", "0.68973625", "0.6884218", "0.682403", "0.6690819", "0.6599517", "0.6538696", "0.64968145", "0.6495397", "0.64913315", "0.6478288", "0.6475794", "0.64711726", "0.64523613", "0.64404064", "0.6427715", "0.63738084", "0.63226116", "0.6302319", "0.6285898", "0.6247625", "0.6204956", "0.61927986", "0.6153863", "0.614866", "0.6117222", "0.6093151", "0.6082827", "0.6082594", "0.60743994", "0.6018624", "0.60038704", "0.5894102", "0.58652997", "0.5857353", "0.5854839", "0.5845978", "0.58344746", "0.5830976", "0.5818155", "0.5817605", "0.57961595", "0.57495403", "0.57451826", "0.57404894", "0.572992", "0.5718813", "0.56973153", "0.56856203" ]
0.7976782
20
todo generate a random place
set visit(visitor){ if(!this.visiting){ this.visiting = { current: this.clock.date, occupants: [] }; } this.visiting.occupants.push(visitor); // todo check trigger events }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function getRandomLocation() {\n\n}", "function randomPosition() {\n var random = Math.floor(Math.random() * 10);\n return random;\n}", "function randomLocation(){\n var max = 400;\n var min = 0;\n return Math.floor(Math.random() * (max - min + 1)) + min;\n}", "function randomOffset() {\n\t\t\treturn ( Math.random() - 0.5 ) * 2 * 1e-6;\n\t\t}", "function randomOffset() {\r\n\r\n\t\treturn ( Math.random() - 0.5 ) * 2 * 1e-6;\r\n\r\n\t}", "function randomPosition() {\r\n let position = randomNumber(0, 90)\r\n return `${position}%`\r\n}", "function locRnd() {\n return (Math.random() - 0.5) / 50;\n}", "function randomOffset() {\n return ( Math.random() - 0.5 ) * 2 * 1e-6;\n }", "function setLoc() {\n xLoc = random(60, width - 60);\n yLoc = random(60, height - 60);\n}", "function random_location() {\n latTest = {\n lat: Math.round(Math.acos(2*Math.random() - 1)*180/Math.PI) - 90,\n lng: Math.floor(Math.random()*360) - 180\n }\n console.log(latTest)\n}", "function changeLoc() {\n swap(locs, 0, floor(random(1, numlocs)));\n}", "function randomLat() {\n return randomNumber(90, -90);\n}", "function randomPos(bound) {\n return Math.random() * bound;\n}", "function placeBombRandomLoc() {\n bombPlaced = false;\n while (!bombPlaced) {\n with (Math) {\n i = floor(random() * (maxX+1));\n j = floor(random() * (maxY+1)); }\n bombPlaced = (placeBomb(i,j)) } }", "function randPlace(image) {\n var temp = getRandomInt(0, gw - image.width);\n image.style.left = temp + \"px\";\n temp = getRandomInt(0, gh - image.height);\n image.style.top = temp + \"px\";\n}", "function randomLng() {\n return randomNumber(180, -180);\n}", "function randomPosition ()\n{\n\treturn { \"x\": Math.ceil(Math.random() * CANVAS_WIDTH), \"y\": Math.ceil(Math.random() * CANVAS_HEIGHT) };\n}", "function randomPlace(gameWidth, gameHeight){\n\t\treturn {\n\t\t\tx: Math.floor(Math.random()*gameWidth),\n\t\t\ty: Math.floor(Math.random()*gameHeight)\n\t\t}\n\t}", "function generateRandomLat() {\n var num = (Math.random()*90);\n var posorneg = Math.round(Math.random());\n if (posorneg === 0) {\n num = num * -1;\n }\n return num;\n}", "function randomPosition() {\n\tvar rnd = Math.round(Math.random()*ps.length);\n\treturn ps[rnd];\n}", "function pickPos(){\r\n return Math.floor((Math.random()*300)+100) + \"px\";\r\n}", "function generateEnemyLocation(){\n return new Loc(-100, getRandomInt(1, 3)*73);\n\n}", "generateRandomLocation(){\n let x = Math.floor(Math.random() * this.height + 1);\n let y = Math.floor(Math.random() * this.width + 1);\n if (this.mine[x][y] === 0) {\n return [x,y];\n } else {\n return this.generateRandomLocation();\n }\n }", "function getRandomPosition(){\n min = 0;\n var [width, height] = getResolution();\n a = Math.floor(Math.random()*(width-min+1)+min);\n b = Math.floor(Math.random()*(height-min+1)+min);\n return([a, b]);\n}", "function offsetNum() {\n return Math.floor(Math.random()*80);\n }", "function randPoint () {\n\t\treturn allPoints[Math.floor(Math.random() * allPoints.length)];\n\t}", "function getRandomPositions() {\n\tlet longStr = '';\n\tfor(let i = 0; i < 30; i++) {\n\t\tconst x = getRandomInt(); const y = getRandomInt();\n\t\tif(longStr.match(new RegExp(`\\/${y}-${x}\\/`)) !== null) {\n\t\t\ti = i - 1;\n\t\t} else {\n\t\t\tlongStr += `/${y}-${x}/`\n\t\t}\n\t}\n\treturn longStr;\n}", "function pickLocForFood() {\n\tvar cols = floor(windowWidth/s.sWidth);\n\tvar rows = floor(windowHeight/s.sHeight);\n\tfoodPosition =createVector(floor (random(cols)), floor(random(rows)));\n\tfoodPosition.x = constrain (foodPosition.x * s.sWidth, 20, windowWidth-s.sWidth-60);\n\tfoodPosition.y = constrain (foodPosition.y * s.sHeight, 20, windowWidth-s.sHeight-20);\n}", "function random_position()\t\t\t\t\t\t\t\t\r\n{\r\n\tgate_pos=document.getElementById(\"gate\");\t\t\t\t//getting gate\r\n\tobj_out=document.getElementById(\"field\");\t\t\t\t//getting field\r\n\tvar y = obj_out.offsetHeight-gate_pos.clientHeight;\t\t//vertical variable inside the field height range\r\n\tvar x = obj_out.offsetWidth-gate_pos.clientWidth;\t\t//horizontal variable inside the field width range\r\n\tvar randomX = Math.ceil((Math.random()*x)/10)*10;\t\t//random horizontal position in multiply of 10\r\n\tvar randomY = Math.ceil((Math.random()*y)/10)*10;\t\t//random vertical position in multiply of 10\r\n\t\r\n\tgate_pos.style.left=randomX+'px';\t\t\t\t\t\t\t//attribution of hor.pos.\r\n\tgate_pos.style.top=randomY+'px';\t\t\t\t\t\t\t//attribution of vert.pos.\r\n\tgate_pos.style.position= \"absolute\";\t\t\t\t\t\t//reset position value\r\n\tgate_pos_hor=parseInt(gate_pos.style.left);\t\t\t\t\t//gate margin left in pixels\r\n\tgate_pos_ver=parseInt(gate_pos.style.top);\t\t\t\t\t//gate margin top in pixels\r\n\tgate_pos_hor+=40;\r\n\tgate_pos_ver+=40;\r\n\tdocument.getElementById(\"goal_counter\").innerHTML=\"Score: \"+goal_counter+\"\";\r\n}", "getRandomCoordinateAtStart() {\n\t\tlet space = 80, width = window.innerWidth, height = this.gameHeight;\n\t\tlet searching = true, attempts = 0, maxAttempts = 10, xy;\n\n\t\twhile (searching && attempts < maxAttempts) {\n\t\t\txy = getRandomCoordinateAtStartHelper(this.util.randomInt);\n\t\t\tif (!this.isLocationOccupiedByGameObject(xy, this.util.getDistanceBetweenPoints)) {\n\t\t\t\tsearching = false;\n\t\t\t\tbreak;\n\t\t\t} else {\n\t\t\t\tattempts++;\n\t\t\t}\n\t\t}\n\t\treturn xy;\n\n\t\tfunction getRandomCoordinateAtStartHelper(randomIntFunc) {\n\t\t\treturn { x: randomIntFunc(-width * 3 / 4, width * 3 / 4), y: randomIntFunc(-height / 3 - space, height) };\n\t\t}\n\t}", "function foodLocation() {\n let x = floor(random(w));\n let y = floor(random(h));\n food = createVector(x, y);\n}", "function randomNova() {\n var randomPlace = novaJson.novaPlaces[Math.floor(Math.random() * novaJson.novaPlaces.length)];\n return randomPlace;\n}", "function randGPS() {\n\t // Set bounding constraints\n\t var bottomLng = -76.936569;\n\t var topLng = -76.950603;\n\t var leftLat = 38.994052;\n\t var rightLat = 38.981376;\n\t var TypeConvFactor = 1000000; // To account for the int based getRandomArbitrary function\n\t // Create random coordinates\n\t function getRandomArbitrary(min, max) {\n\t\treturn Math.random() * (max - min) + min;\n\t }\n\t var randCoordinates = {\n\t\tlat: (getRandomArbitrary(leftLat * TypeConvFactor, rightLat *\n\t\t TypeConvFactor) / TypeConvFactor),\n\t\tlng: (getRandomArbitrary(bottomLng * TypeConvFactor, topLng *\n\t\t TypeConvFactor) / TypeConvFactor)\n\t };\n\t return randCoordinates;\n }", "function getRandom() {\n const rand = Math.ceil(Math.random() * (sizeX * sizeY));\n if (mineMap.hasOwnProperty(rand)) {\n return getRandom();\n }\n return rand;\n }", "function randomPoint(){\n\tx =(Math.random()*200)-100;\n\ty =(Math.random()*200)-100;\n\n\treturn new Point(x,y);\n}", "function gener(){\r\n posX = length*Math.floor(8*Math.random());\r\n}", "function get_spawn_pos() {\n return outlap.spawn_zone[Math.floor(Math.random() * outlap.spawn_zone.length)];\n }", "function randomGridVariablePosition() {\n return Math.floor(Math.random() * 10);\n}", "place() { \n\n //decides the random direction of the spot\n var randomDirection = floor(random(0,4));\n\n //alter this placement & direction based on the direction\n if(randomDirection === 0) { //east\n this.x = 0;\n this.y = (floor(random(0,3)) * (platformSize + 10) + HEIGHT/2 - movement);\n this.direction = 0;\n } else if(randomDirection === 1) { //west\n this.x = WIDTH;\n this.y = (floor(random(0,3)) * (platformSize + 10) + HEIGHT/2 - movement);\n this.direction = 1;\n } else if(randomDirection === 2) { //south\n this.x = (floor(random(0,3)) * (platformSize + 10) + WIDTH/2 - movement);\n this.y = 0;\n this.direction = 2;\n } else if(randomDirection === 3) { //north\n this.x = (floor(random(0,3)) * (platformSize + 10) + WIDTH/2 - movement);\n this.y = HEIGHT;\n this.direction = 3;\n }\n }", "function createMap(){\n return Math.floor(Math.random()*(mapNumber)+1);\n}", "function randomDir(){\r\n\treturn Math.floor(Math.random()*3)-1;\r\n}", "function randomVodafone() {\n var randomPlace = vodafoneJson.vodafonePlaces[Math.floor(Math.random() * vodafoneJson.vodafonePlaces.length)];\n return randomPlace;\n}", "function randomize (){\n\t\thole = Math.floor(Math.random()* 9)+1;\n\t}", "generateRandomCoords () {\n const randomX = Math.floor(Math.random() * 5) * 90 + 25\n const randomY = Math.floor(Math.random() * 5) * 100 + 25\n return { x: randomX, y: randomY }\n }", "static randomPosition(count) {\n\t\treturn [random(-width, width), random(-height, height), random(width)].slice(0, count === undefined ? 3 : count);\n\t}", "setRandomSpawnPoint() {\n // leer\n }", "randomPositionGenerator(){\n let x = Math.floor(Math.random() * BOARD_WIDTH);\n let y = Math.floor(Math.random() * BOARD_HEIGHT);\n x -= (x % this.cellWidth);\n y -= (y % this.cellWidth);\n return([x, y]);\n }", "function randomTwoForOne() {\n var randomPlace = twoForOneJson.twoForOnePlaces[Math.floor(Math.random() * twoForOneJson.twoForOnePlaces.length)];\n return randomPlace;\n}", "function randomLocation(array) {\n let choice = Math.floor(Math.random() * array.length);\n return array[choice];\n}", "function random_destination(items){\n \n return items[Math.floor(Math.random() * items.length)];\n \n}", "function addRandom() {\n var start = arr.length;\n var end = start + 10;\n if (end > 63) {\n end = 63;\n }\n if (start < 63) {\n for (var index = start; index < end; index++) {\n var x = new key(Math.ceil(Math.random() * 99));\n\n arr[index] = x;\n updateLocation(20);\n }\n }\n}", "function randomRobot(state) {\n return {direction: randomPick(roadGraph[state.place])};\n}", "handleNext() {\n let randomRes = (this.state.potential)[Math.floor(Math.random() * (this.state.potential).length)];\n this.setState({ curr: randomRes });\n let location = randomRes.location.display_address.join(' ');\n this.setState({ location: location })\n }", "genNextSpot() {\r\n let countFreeSpaces = this.gameState.board.filter((i) => i === 0).length;\r\n if (countFreeSpaces === 0) {\r\n this.checkLose();\r\n } else {\r\n let locationToAdd = Math.floor(Math.random() * Math.floor(countFreeSpaces));\r\n let numEmptyTraversed = 0;\r\n for (let i = 0; i < this.gameState.board.length; i++) {\r\n if (this.gameState.board[i] === 0) {\r\n if (numEmptyTraversed === locationToAdd) {\r\n this.gameState.board[i] = this.gen2or4();\r\n break;\r\n } else {\r\n numEmptyTraversed++;\r\n }\r\n }\r\n }\r\n } \r\n }", "function displace(num) {\n\t\tvar max = num / (map.mapSize + map.mapSize) * map.roughness;\n\t\treturn (Math.random() - 0.5) * max;\n}", "function generateNewCoords() {\n\tlet x = Math.floor(Math.random() * (canvas_width - client_start_size));\n\tlet y = Math.floor(Math.random() * (canvas_height - client_start_size));\n\treturn {x, y};\n}", "move() {\n\t\tthis.x = this.x + random(-2, 2);\n\t\tthis.y = this.y + random(-2, 2);\n\t\tthis.width = this.width + random(-3, 3);\n\t\tthis.height = this.height + random(-3, 3);\n\t}", "function updateRandomGeoposition(geoposition) {\n geoposition.timestamp = new Date().getTime();\n geoposition.coords.latitude += Math.random() * 1e-4 - 1e-4 / 2;\n geoposition.coords.longitude += Math.random() * 1e-4 - 1e-4 / 2;\n}", "function randomPos(a) {\n a.style.top = `${getRange(100)}%`;\n a.style.right = `${getRange(100)}%`;\n a.style.left = `${getRange(100)}%`;\n a.style.bottom = `${getRange(100)}%`;\n }", "generatePOI() {\n this.poi = Math.floor(Math.random() * this.numPoints); //point we want to select \n }", "placeRandomTile(tile) {\n let pos = this.floor.get(randInt(this.floor.length));\n this.tiles[pos.y][pos.x] = tile;\n this.removeRadius(pos.x, pos.y, 1);\n this.placeStatue(pos.x, pos.y);\n }", "function position() {\n var x = Math.random() * $(window).width();\n var y = Math.random() * $(window).height();\n $('#downstairs').offset({\n // position: 'absolute',\n top: y,\n left: x\n });\n}", "function randomX() {\n let xLocation = [0, 100, 200, 300, 400, 500, 600, 700, 800];\n return xLocation[Math.floor(Math.random() * xLocation.length)] * -1;\n}", "function getRandomPosition(element) {\n\tvar x = document.body.offsetHeight-element.clientHeight\n\tvar y = document.body.offsetWidth-element.clientWidth\n\tvar randomX = Math.floor(Math.random()*x)\n\tvar randomY = Math.floor(Math.random()*y)\n\treturn [randomX,randomY]\n}", "function randomFoodPosition() {\n let num = Math.floor(Math.random() * 500);\n if (num % 20 == 0) {\n return num;\n } else {\n return randomFoodPosition();\n }\n}", "constructor(){\n this.x = random(0, width); //x-coordinate is randomized\n this.y = random(0, -height/2);//y-coordinate is randomized as well\n }", "function randomindex() {\n return Math.floor(Math.random() * Busmall.allimg.length);\n}", "function AddRandom() {\n\n\n var location = [];\n\n for (var j = 0; j < 5; j++) {\n for (var i = 0; i < 5; i++) {\n\n if (grid[j][i].name == \"empty\") {\n\n location.push([i, j]);\n }\n }\n }\n\n if (location.length > 0) {\n\n var random = location[Math.floor(Math.random() * location.length)];\n scene.remove(grid[random[1]][random[0]]);\n\n grid[random[1]][random[0]] = Blocks[0].clone();\n\n grid[random[1]][random[0]].position.x = random[0];\n grid[random[1]][random[0]].position.y = random[1];\n grid[random[1]][random[0]].scale.x = 0.1;\n grid[random[1]][random[0]].scale.y = 0.1;\n scene.add(grid[random[1]][random[0]]);\n \n return 0;\n }\n \n return 1;\n\n}", "function randStart() {\n return Math.random() - .5;\n}", "move() {\n this.x = this.x + random(-2, 2);\n this.y = this.y + random(-2, 2);\n }", "function generate_random_pattern() {\n var j;\n while(generated_tile_ids.length < trial.loading_magnitude) {\n j = Math.floor(Math.random() * trial.grid_size);\n // valuex = 'tile_' + j;\n var index = generated_tile_ids.indexOf(j);\n if (index == -1) {\n generated_tile_ids.push(j);\n }\n }\n }", "function generateStartPos(){\n firstPlayerStartPos = randomInteger(0, 39);\n secondPlayerStartPos = randomInteger(50, 89);\n}", "function getRandomPosition() {\n const flowerContainer = document.getElementById(\"flower-container\");\n const containerWidth = flowerContainer.offsetWidth;\n const containerHeight = flowerContainer.offsetHeight;\n const flowerWidth = 60; // Width of the flower element\n const flowerHeight = 250; // Height of the flower element\n\n const maxX = containerWidth - flowerWidth;\n const maxY = containerHeight - flowerHeight;\n\n const randomX = Math.floor(Math.random() * maxX);\n const randomY = Math.floor(Math.random() * maxY);\n\n return { x: randomX, y: randomY };\n}", "getFoodLocation() {\n let x = Utils.rand(MARGIN, document.body.clientWidth - MARGIN, SIZE);\n let y = Utils.rand(MARGIN, document.body.clientHeight - MARGIN, SIZE);\n // If random spot is already filled, pick a new one\n // Pick until you find an empty spot\n // ..... nothing can go wrong with this\n if (Locations.has(x, y)) {\n [x, y] = this.getFoodLocation();\n }\n return [x, y];\n }", "function placeX() {\r\n let ranX = Math.floor(Math.random() * randMultiply) + xX;\r\n let ranY = Math.floor(Math.random() * randMultiply) + xY;\r\n for (let i = 0; i < xLength; i++) {\r\n let newXOb = {\r\n x: (ranX + i) * moveUnit,\r\n y: (ranY + i) * moveUnit\r\n };\r\n if (i != xLength % 5)\r\n xOb.unshift(newXOb);\r\n }\r\n for (let i = 0; i < xLength; i++) {\r\n let newXOb = {\r\n x: (ranX + 8 - i) * moveUnit,\r\n y: (ranY + i) * moveUnit\r\n };\r\n if (i != xLength % 5)\r\n xOb.unshift(newXOb);\r\n }\r\n }", "function getRandomPosition() {\n const flowerContainer = document.getElementById(\"flower-container\");\n const containerWidth = flowerContainer.offsetWidth;\n const containerHeight = flowerContainer.offsetHeight;\n const flowerWidth = 60; // Width of the flower element\n const flowerHeight = 250; // Height of the flower element\n\n // Calculate the maximum position values to keep the flower fully visible within the container\n const maxX = containerWidth - flowerWidth;\n const maxY = containerHeight - flowerHeight;\n\n // Generate random x and y coordinates within the valid range\n const x = Math.floor(Math.random() * maxX);\n const y = Math.floor(Math.random() * maxY);\n\n return { x, y };\n }", "move() {\n this.x = this.x + random(-10,10);\n this.y = this.y + random(-10,10);\n }", "function startingPositionZombie() {\n\n yZombiePos = Math.floor(Math.random() * 7);\n xZombiePos = Math.floor(Math.random() * 7);;\n}", "function pickLocation(){\n var cols = floor(width/scl);\n var rows = floor(height/scl);\n food = createVector(floor(random(cols)), floor(random(rows)));\n food.mult(scl);\n}", "function random() {\n random1 = Math.floor((Math.random() * startupX.length));\n random2 = Math.floor((Math.random() * startupY.length));\n\n}", "function findTile(){\n var oneTile = parseInt(Math.random() * 14);\n console.log(oneTile);\n return oneTile;\n }", "function getRandomPosition(min, max) {\n min = Math.ceil(min);\n max = Math.floor(max);\n return Math.floor(Math.random() * (max - min + 1)) + min;\n}", "function randomTop() {\n return Math.floor(Math.random()*30)+30;\n}", "function randElementPos(e, buffer) {\n $(e).each(function(index) {\n // creates a random int between 0 and document width /2\n $(this).css('top', randY(buffer)+'px');\n $(this).css('left', randX(buffer)+'px');\n }); \n}", "function generateNewTile(){\n\t\tvar openLocations = checkOpenLocations();\n\t\tif(openLocations.length > 0){\n\t\t\t// CN get random location string and format into valid coordinates\n\t\t\tvar randomIndex = Math.floor(Math.random() * openLocations.length);\n\t\t\tvar newCol = parseInt(openLocations[randomIndex].split('(')[1]);\n\t\t\tvar newRow = parseInt(openLocations[randomIndex].split(',')[1]);\n\t\t\tvar newTileValue = Math.random() > 0.33 ? 2 : 4;\n\t\t\tnew Tile(newTileValue, newCol, newRow);\n\t\t}\n\t}", "generateRandom() {\n const { x, y } = this.getRandomPixelCoordinate();\n this.create('hero', x, y);\n }", "function pickLocation() {\n var cols = floor(width/scl);\n var rows = floor(height/scl);\n food = createVector(floor(random(1,cols-1)), floor(random(1,rows-1)));\n food.mult(scl);\n}", "function randStart() {\n return Math.floor(Math.random() * Math.floor(13)) + 1;\n}", "function determineStartingPlayer()\n{\n // @TODO: Random laten bepalen welke speler aan de beurt is of mag beginnen\n \n}", "generateStartingPositions() {\n\t\tlet array = [];\n\t\tlet manhattanPositions = [6, 13, 66, 91, 207, 289, 352];\n\t\tlet londonPositions = [11, 48, 57, 108, 167, 330, 390];\n\t\tlet seoulPositions = [12, 17, 32, 42, 89, 134, 174, 294, 316];\n\t\tif (this.game.cityName === \"Manhattan\") {\n\t\t\tlet r = Math.floor((Math.random() * 7));\n\t\t\tarray.push(manhattanPositions[r]);\n\t\t\t// r = Math.floor((Math.random() * 3) + 4);\n\t\t\t// array.push(manhattanPositions[r]);\n\t\t}\n\t\telse if (this.game.cityName === \"London\") {\n\t\t\tlet r = Math.floor((Math.random() * 7));\n\t\t\tarray.push(londonPositions[r]);\n\t\t\t// r = Math.floor((Math.random() * 3) + 4);\n\t\t\t// array.push(londonPositions[r]);\n\t\t}\n\t\telse {\n\t\t\tlet r = Math.floor((Math.random() * 9));\n\t\t\tarray.push(seoulPositions[r]);\n\t\t\t// r = Math.floor((Math.random() * 4) + 5);\n\t\t\t// array.push(seoulPositions[r]);\n\t\t}\n\t\treturn array;\n\t}", "function makeRandomMove() {\n log(\"stockfish made a random move\", \"stockfish\");\n var moves = board.moves({ verbose: true });\n var move = moves[Math.floor(Math.random() * moves.length)];\n board.move(move);\n highlightLastOpponentMove({ from: move.from, to: move.to });\n updateBoardUI();\n }", "function pickRandomTile(){\n\tvar randomX = Math.floor(( Math.random() * dim_x));\n\tvar randomY = Math.floor(( Math.random() * dim_y));\n\treturn (randomX + '-' + randomY);\n}", "function assignNewPosition() {\n\tvar pos = {};\n\tdo {\n\t\tpos.x = Math.floor(Math.random() * gridW);\n\t\tpos.y = Math.floor(Math.random() * gridH);\n\t} while (filledPositions[pos.x][pos.y]);\n\t\n\tfilledPositions[pos.x][pos.y] = true;\n\t\n\tpos.x=pos.x*40+30+Math.floor(Math.random()*26-13);\n\tpos.y=pos.y*40+30+Math.floor(Math.random()*26-13);\n\t\n\treturn pos;\n}", "function pickLocation(){\n\n var cols = floor(width/sz);\n var rows = floor(height/sz);\n//create a spot on the canvas for the food to fill\n food= createVector(floor(random(cols)),floor(random(rows)));\n food.mult(sz);\n }", "function getRandomPosition(radius)\r\n{\r\n\tvar v = document.getElementById(\"offenseVis1\");\r\n\r\n\tvar minX = radius;\r\n\tvar minY = radius;\r\n\r\n\tvar maxX = (v ? v.clientWidth : 800) - radius - 60;\r\n\tvar maxY = (v ? v.clientHeight : 300) - radius - 60;\r\n\t\r\n\tvar position = {\r\n\t x: Math.floor(Math.random() * (maxX - minX) + minX),\r\n\t y: Math.floor(Math.random() * (maxY - minY) + minY),\r\n\t r: radius\r\n\t };\r\n\r\n\treturn position;\r\n}", "function getRandomFoodPosition() {\n\tlet newFoodPosition;\n\n\t// a loop that contiously checks to make sure the food doesn't relocate anywhere on the snake\n\twhile (newFoodPosition == null || onSnake(newFoodPosition)) {\n\t\tnewFoodPosition = randomGridPosition();\n\t}\n\treturn newFoodPosition;\n}", "getRandomDirection(){\n this.setDirection(Math.floor(Math.random() * 4));\n }", "function randomise() {\r\n const randomNumber = Math.random();\r\n\r\n const randomTile = randomNumber * 100 * quantityOfTiles;\r\n\r\n const rounding = Math.floor(randomTile);\r\n\r\n const assignedTile = (rounding % quantityOfTiles) + 1;\r\n\r\n return assignedTile;\r\n}", "function CreateLottoValues() {\r\n return Math.floor(Math.random() * 90 + 1);\r\n }", "getRandomTileCoordinate() {\n // get random tile coords\n const x = Math.round(Math.random() * this.xTiles);\n const y = Math.round(Math.random() * this.yTiles);\n\n return { x, y }\n }", "getRandomTileCoordinate() {\n // get random tile coords\n const x = Math.round(Math.random() * this.xTiles);\n const y = Math.round(Math.random() * this.yTiles);\n\n return { x, y }\n }" ]
[ "0.79621756", "0.73283", "0.73054934", "0.7095919", "0.70851237", "0.7065577", "0.70507455", "0.7016517", "0.7016194", "0.70055014", "0.69878066", "0.6960531", "0.6940205", "0.6929497", "0.6900161", "0.6872857", "0.6843588", "0.67999643", "0.67841136", "0.6773233", "0.66895175", "0.66825086", "0.6674522", "0.6663463", "0.66589004", "0.66170007", "0.66144764", "0.66075796", "0.6557668", "0.65330917", "0.65284514", "0.6517718", "0.6517667", "0.6517099", "0.65158546", "0.65130657", "0.65125823", "0.649597", "0.64927113", "0.6481661", "0.6477305", "0.647724", "0.6469875", "0.6462363", "0.6456656", "0.6456006", "0.6437228", "0.6426022", "0.64231086", "0.64144635", "0.6413605", "0.63997525", "0.63987345", "0.6393358", "0.6392663", "0.6390015", "0.6388734", "0.63833326", "0.63825935", "0.63801724", "0.6378545", "0.63784564", "0.6377429", "0.6374218", "0.63728786", "0.6368457", "0.6367636", "0.63663423", "0.6364902", "0.6360858", "0.6353149", "0.6337469", "0.6335535", "0.6321872", "0.6320476", "0.6317074", "0.63077295", "0.629856", "0.6296288", "0.6292815", "0.6287106", "0.6287064", "0.6284611", "0.62772524", "0.6271127", "0.62708694", "0.62699085", "0.6267308", "0.6266413", "0.6260553", "0.626009", "0.62562686", "0.62533104", "0.62498534", "0.62483186", "0.62476605", "0.6246087", "0.6244659", "0.6243405", "0.62426007", "0.6239773" ]
0.0
-1
Call update in loop
update (delta) { if (this.mixer) { this.mixer.update(delta) } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "async update() {}", "function update() {}", "function updateLoop(){\n\t\t\t\t\tvar time = this.update();\n\n\t\t\t\t\t// set timer for next update\n\t\t\t\t\tthis.updateTimer = setTimeout(updateLoop.bind(this), 1000 - time.getMilliseconds());\n\t\t\t\t}", "function runUpdate(){\n people.forEach(function(element){\n element.update();\n });\n }", "update() {}", "update() {}", "update() {}", "update() {}", "update() {}", "update() {}", "update() {}", "update() {}", "update() {}", "doUpdate() {\n if (!this.interval) return;\n this.viss.forEach(v => v.doUpdate());\n }", "update () {}", "_update() {\n }", "function update(){\r\n updateBackground();\r\n //extractData();\r\n loop();\r\n // checkStatus();\r\n \r\n}", "function update() {\n\t\t\n\t}", "loopUpdate(){\n setInterval(()=>{\n this.updateNow();\n },updateSecs*1000);\n }", "update() {\n for(let i=0; i<Simulation.speed; i++) {\n globalUpdateCount += 1\n this.fields.forEach(f => f.update())\n this.sender.auto()\n this.sender.update()\n this.updateR()\n this.chart.update(this.fields, this.sender)\n }\n }", "update() { }", "update() { }", "async update_loop() {\n try {\n let update_loop_promises = [];\n let time = Date.now();\n\n for (let i = 0; i < this.simulations.length; i++) {\n update_loop_promises.push(this.single_update(i));\n }\n\n await Promise.all(update_loop_promises);\n\n logger.info(\n `Backtest strategies updated, count: ${\n this.simulations.length\n } , time: ${time} last_candle: ${\n this.simulations[0].emulator.last_update.time\n } `\n );\n\n await this.sync_performance();\n\n return;\n } catch (e) {\n logger.error(\"Backtest Emulator update loop error \", e);\n }\n }", "function updateAll(delta)\n{\n univ.update(delta);\n}", "update(){}", "update(){}", "update(){}", "runUpdate() {\n this.utils.log(\"\");\n this.utils.log(\"******************* Running update ******************* \");\n this.utils.log(\"\");\n\n // Reset update flags\n this.updateTweets = false;\n this.updateStatus = false;\n\n // Process any new tweets before performing other operations\n this.checkTrackedTweets().then(() => {\n // Process any mentions\n this.checkMentions().then(() => {\n // Save the status file if needed\n if (this.updateTweets || this.updateStatus) {\n this.dataHandler.saveStatus(this.botStatus);\n }\n });\n\n // Post a normal tweet\n this.actionHandler.postTweet(this.generator.generateResponse());\n\n });\n }", "update()\n {\n \n }", "function update() {\n // ... no implementation required\n }", "function update() {\n updaters.forEach(function (f) { f(); });\n }", "update()\n {\n let entitiesCount = this.entities.length;\n\n for (let i = 0; i < entitiesCount; i++)\n {\n let entity = this.entities[i];\n\n entity.update();\n }\n }", "CallUpdates()\n {\n this.Debug(\">START CallUpdates\");\n\n for(var i = 0; i < this.gameObjects.length; i++)\n {\n this.Debug(\"Updating: \" + this.gameObjects[i].object.type);\n \n this.gameObjects[i].object.UpdateGameObject();\n }\n \n for(var i = 0; i < this.scripts.length; i++)\n {\n this.scripts[i].Update();\n }\n\n for(var i = 0; i < this.interface.length; i++)\n {\n this.interface[i].UpdateGameObject();\n }\n\n this.level.Update();\n\n this.Debug(\">END CallIpdates\");\n }", "update(startingData) {}", "onUpdate() {\n let game = this;\n for (let player in this.players) {\n this.getClientData(player).then(data => {\n if (game.players[player].update)\n game.players[player].update(data)\n }).catch(err => {\n logger.error(err);\n });\n }\n }", "update() {\n }", "update() {\n }", "update() {\n }", "function update() {\n if (!perfUpdate) {\n return;\n }\n perfUpdate = false;\n withinLoop = true;\n try {\n checkInjectedStyles();\n updateStatBox();\n pimpAnswers();\n pimpKeyboardShortcuts();\n } catch (e) {\n alert('ERROR: ' + e.message);\n logDate('ERROR: ' + e.message);\n }\n withinLoop = false;\n}", "function update() {\n\t\tfor (let i = 0; i < loop.update.length; i++) {\n\t\t\tloop.update[i](tickCounter);\n\t\t}\n\t\tfor (let i = 0; i < loop.updateLast.length; i++) {\n\t\t\tloop.updateLast[i](tickCounter);\n\t\t}\n\t\ttickCounter++;\n\t\tmouseClicked = false;\n\t}", "updateLoop() {\n this.retrieveEvents();\n this.updateID = Mainloop.timeout_add_seconds(this.delay * 60, Lang.bind(this, this.updateLoop));\n }", "function updateAll() {\n updateForces();\n updateDisplay();\n}", "update() {\n\n }", "update() {\n\n }", "update() {\n\n }", "update() {\n\n }", "update() {\n\n }", "update() {\n\n }", "update() {\n\n }", "update() {\n // ...\n }", "update() {\n \n }", "function update() {\n \n}", "update(delta) {}", "function update() {\n\t\n\n\n\n}", "update() {\n console.log(\"Abstract loop.\");\n }", "update() {\n this.poll();\n }", "update() {\r\n for (let i = 0; i < this.boids.length; i++) {\r\n let neighbours = this.neighbours(i).slice();\r\n \r\n this.cohesion(i, neighbours);\r\n this.alignment(i, neighbours);\r\n this.separation(i, neighbours);\r\n this.boids[i].update();\r\n }\r\n }", "update () {\n /* istanbul ignore else */\n if (this.lazy) {\n this.dirty = true;\n } else if (this.sync) {\n this.run();\n } else {\n queueWatcher(this);\n }\n }", "update() {\n\n }", "update() {\n\n }", "update() {\n\n }", "update() {\n\n }", "update() {\n\n }", "update() {\n\n }", "update() {\n\n }", "function updateAll() {\n validate();\n calculate();\n updateDose();\n DrawDose();\n}", "function update()\n{\n\n}", "updateToAll() {}", "update() {\n }", "update() {\n }", "function updateBalls() {\r\n for (let i = 0; i < ballArray.length; i++) {\r\n ballArray[i].update();\r\n }\r\n}", "update(...args) {\n this.__notify(EV.BEFORE_UPDATE);\n this._update(...args);\n this.__notify(EV.UPDATED);\n }", "function update(time)\n {\n\t //console.log(\"UPDATE\");\n\t // calculation\n }", "function nextUpdate() {\n\tUPDATING = false;\n\trefreshTimeout = setTimeout(function(){ \n\t\tstartDrawingData(); \n\t}, UPDATE_INTERVAL * 1000);\n}", "update () {\n }", "function loop(start, test, update, body) {\n for (let value = start; test(value); value = update(value)) {\n body(value);\n }\n}", "updatePlayers(){\n var players = this.getAllPlayers();\n for(var i = 0; i < players.length; i++){\n var player = players[i];\n player.update();\n }\n }", "static update()\n {\n // Update game timer if there's a current game\n if (RPM.game)\n {\n RPM.game.playTime.update();\n }\n\n // Update songs manager\n RPM.songsManager.update();\n\n // Repeat keypress as long as not blocking\n let continuePressed;\n for (let i = 0, l = RPM.keysPressed.length; i < l; i++)\n {\n continuePressed = RPM.onKeyPressedRepeat(RPM.keysPressed[i]);\n if (!continuePressed)\n {\n break;\n }\n }\n\n // Update the top of the stack\n RPM.gameStack.update();\n }", "function updateValues () {\n setInterval(function () {\n console.log('Starts updating job');\n\n getAllCoins()\n .then(function (object) {\n console.log('Finished updating');\n return saveToDatabase(object);\n })\n .catch(function (err) {\n console.log(err);\n });\n\n }, 60000);\n}", "updateItems() {\n\t\tthis.callItemR('update');\n\t}", "function scheduleUpdate() {\n if (!_nextUpdateHandle) {\n _nextUpdateHandle = setImmediate(processUpdate);\n }\n}", "update() {\n this.weapons.forEach(weapon => {\n weapon.update();\n });\n }", "function startUpdate(){\n updating = true;\n }", "_updateAllEntities() {\n for (let i = this._entities.length - 1; i >= 0; i--) {\n this._entities[i].update();\n }\n }", "function updateAll() {\n refreshSliderDimensions();\n ngModelRender();\n redrawTicks();\n }", "function update() {\n\tIPC.sendToHost('api-call', '/daemon/version', 'version');\n\t\n\tupdating = setTimeout(update, 50000);\n}", "update() {\n setTimeout(this._update.bind(this));\n }", "_update () {\n if (this.destroyed) return\n\n // update wires in random order for better request distribution\n const ite = randomIterate(this.wires)\n let wire\n while ((wire = ite())) {\n this._updateWireWrapper(wire)\n }\n }", "_update () {\n if (this.destroyed) return\n\n // update wires in random order for better request distribution\n const ite = randomIterate(this.wires)\n let wire\n while ((wire = ite())) {\n this._updateWireWrapper(wire)\n }\n }", "async function update() {\r\n\tvar result = await client.query(\"select * from poe_ladder_data where (league = 'Abyss') order by rank\");\r\n\t//console.log(result);\r\n\r\n\tvar date_1 = new Date().toUTCString();\r\n\r\n\tfor(var i = 0; i < result.rows.length; i++)\r\n\t{\r\n\t\tconsole.log(i + \" : \" + result.rows[i].account_name + \" \" + result.rows[i].name);\r\n\t\tawait get_items(result.rows[i].account_name, result.rows[i].name);\r\n\t\tawait sleep(1000);\r\n\t}\r\n\r\n\tvar date_2 = new Date().toUTCString();\r\n\t\r\n\tconsole.log('start: ' + date_1);\r\n\tconsole.log('end: ' + date_2);\r\n\r\n\tawait client.end();\r\n}", "onUpdate() {\r\n const server = this; //Set a reference to 'this' (the 'Server' class)\r\n\r\n //Update each lobby\r\n for (const id in server.lobbys) {\r\n server.lobbys[id].onUpdate(); //Run the update method for the lobby. The functionality of this can vary depending on the type of lobby.\r\n }\r\n }", "update(t) {}", "update(){\n\n }", "update(dt) {\n\n }", "update () {\n\n\n }", "async update_() {\n if (this.lockingUpdate_) {\n if (this.pendingUpdate_) {\n return;\n }\n this.pendingUpdate_ = (async () => {\n while (this.lockingUpdate_) {\n try {\n await this.lockingUpdate_;\n } catch (e) {\n // Ignore exception from waiting for existing update.\n }\n }\n this.lockingUpdate_ = this.pendingUpdate_;\n this.pendingUpdate_ = null;\n await this.doUpdate_();\n this.lockingUpdate_ = null;\n })();\n } else {\n this.lockingUpdate_ = (async () => {\n await this.doUpdate_();\n this.lockingUpdate_ = null;\n })();\n }\n }", "function loop(value, testFn, updateFn, bodyFn) {}", "function updateAll()\n{\n\twindow.clearTimeout( timeID );\n\tgetUserList();\n\tsetTimers();\n}", "_runAfterUpdateCallbacks() {\n var self = this;\n var callbacks = self._afterUpdateCallbacks;\n self._afterUpdateCallbacks = [];\n callbacks.forEach((c) => {\n c();\n });\n }", "update(){\n }", "update(){\n }" ]
[ "0.8181664", "0.7915289", "0.76474386", "0.75155884", "0.748881", "0.748881", "0.748881", "0.748881", "0.748881", "0.748881", "0.748881", "0.748881", "0.748881", "0.7451391", "0.7385", "0.72858834", "0.7233399", "0.71712804", "0.710433", "0.7066083", "0.70589", "0.70589", "0.7054925", "0.7040844", "0.699274", "0.699274", "0.699274", "0.6990665", "0.6985995", "0.6968654", "0.69025064", "0.6872909", "0.6872254", "0.686257", "0.6847948", "0.6828136", "0.6828136", "0.6828136", "0.68262583", "0.68088585", "0.6802197", "0.6795378", "0.6761588", "0.6761588", "0.6761588", "0.6761588", "0.6761588", "0.6761588", "0.6761588", "0.6747602", "0.67474586", "0.6711717", "0.67043126", "0.67036086", "0.669637", "0.6663825", "0.6659101", "0.6632431", "0.66294175", "0.66294175", "0.66294175", "0.66294175", "0.66294175", "0.66294175", "0.66294175", "0.66233385", "0.66130036", "0.6592287", "0.6586467", "0.6586467", "0.6519476", "0.6506477", "0.6492846", "0.64914083", "0.64655954", "0.6461871", "0.6459359", "0.6453708", "0.6452859", "0.6450712", "0.6427388", "0.6418976", "0.6413297", "0.64125144", "0.6401134", "0.6395779", "0.639204", "0.63869005", "0.63869005", "0.6385403", "0.63844806", "0.638194", "0.63783216", "0.637763", "0.63620555", "0.63616216", "0.6360325", "0.63585776", "0.63518137", "0.63479805", "0.63479805" ]
0.0
-1
from Django docs to get csrf token using jQuery
function getCookie(name) { var cookieValue = null; if (document.cookie && document.cookie !== '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = jQuery.trim(cookies[i]); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) === (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function getCSRFToken() {\r\n var csrfToken = $('#forgeryToken').val();\r\n return csrfToken;\r\n }", "function authToken() {\n return $('meta[name=\"csrf-token\"]').attr('content');\n}", "function ajaxCsrfToken() {\n\t$.ajaxSetup({\n\t headers: { 'X-CSRF-Token' : $('meta[name=_token]').attr('content') }\n\t});\n}", "function handleCsrfToken(){\n var token = $(\"meta[name='_csrf']\").attr(\"content\");\n var header = $(\"meta[name='_csrf_header']\").attr(\"content\");\n $(document).ajaxSend(function(e, xhr, options) {\n xhr.setRequestHeader(header, token);\n });\n }", "function getCSRFToken()\n\t{\n\t\tvar input = document.getElementById(\"csrftoken\");\n\t\treturn input.value;\n\t\t\n\t}", "static token() {\n return document.querySelector('meta[name=\"csrf-token\"]').content\n }", "function getToken() {\n var meta = document.querySelector(\"meta[name=\\\"csrf-token\\\"]\");\n return meta && meta.getAttribute('content');\n}", "function getCSRFToken() {\n var cookieValue = null;\n if (document.cookie && document.cookie != '') {\n var cookies = document.cookie.split(';');\n for (var i = 0; i < cookies.length; i++) {\n var cookie = jQuery.trim(cookies[i]);\n if (cookie.substring(0, 10) == ('csrftoken' + '=')) {\n cookieValue = decodeURIComponent(cookie.substring(10));\n break;\n }\n }\n }\n return cookieValue;\n}", "_getCSRFToken() {\n let that = this;\n return that._request('GET', that._getUrl('simplecsrf/token.json'), {}, that.localHeaders)\n .then(function (res) {\n console.log(\"CSRF\",res.body);\n that.csrf = res.body.token;\n });\n }", "csrfToken() {\n let selector = document.querySelector('meta[name=\"csrf-token\"]');\n\n if (this.options.csrfToken) {\n return this.options.csrfToken;\n } else if (selector) {\n return selector.getAttribute('content');\n }\n\n return null;\n }", "function getCSRFToken() {\n var cookieValue = null;\n if (document.cookie && document.cookie != '') {\n var cookies = document.cookie.split(';');\n for (var i = 0; i < cookies.length; i++) {\n var cookie = jQuery.trim(cookies[i]);\n if (cookie.substring(0, 10) == ('csrftoken' + '=')) {\n cookieValue = decodeURIComponent(cookie.substring(10));\n break;\n }\n }\n }\n return cookieValue;\n }", "function getCSRF() {\n var metas = document.getElementsByTagName(\"meta\");\n for (var i = 0; i < metas.length; i++) {\n if (metas[i].getAttribute(\"name\") == \"csrf_token\") {\n return metas[i].getAttribute(\"content\");\n }\n }\n}", "function csrfcookie() {\n var cookieValue = null,\n name = 'csrftoken';\n if (document.cookie && document.cookie !== '') {\n var cookies = document.cookie.split(';');\n for (var i = 0; i < cookies.length; i++) {\n var cookie = cookies[i].trim();\n if (cookie.substring(0, name.length + 1) == (name + '=')) {\n cookieValue = decodeURIComponent(cookie.substring(name.length + 1));\n break;\n }\n }\n }\n return cookieValue;\n}", "csrfToken() {\n if (!this.isSafe() && !this.isCrossOrigin()) {\n return up.protocol.csrfToken()\n }\n }", "function csrfcookie () {\n var cookieValue = null,\n name = 'csrftoken';\n if (document.cookie && document.cookie !== '') {\n var cookies = document.cookie.split(';');\n for (var i = 0; i < cookies.length; i++) {\n var cookie = cookies[i].trim();\n if (cookie.substring(0, name.length + 1) == (name + '=')) {\n cookieValue = decodeURIComponent(cookie.substring(name.length + 1));\n break;\n }\n }\n }\n return cookieValue;\n}", "function status()\n{\n $.ajax({url:\"/status\",type:\"get\",async:false}).done(function(r)\n {\n if(r!=\"\")\n {\n csrf_token=r;\n $(\"_csrf_token\").val(r);\n }\n })\n}", "function setCSRF_Token_ajax(){\n $.ajaxSetup({\n headers: {\n 'X-CSRF-TOKEN': $('meta[name=\"csrf-token\"]').attr('content')\n }\n });\n }", "function csrfPOST(action, form_el, success) {\n var csrftoken = getCookie(\"csrftoken\");\n if (csrftoken === null) {\n console.log(\"CSRF cookie not found!\");\n return;\n }\n $.ajax({\n url: action,\n type: \"POST\",\n headers: {\"X-CSRFToken\": csrftoken},\n data: form_el.serialize(),\n dataType: \"json\",\n success: success\n });\n}", "function getTokenFromDocument (csrf) {\n if (!document) return\n const selector = isString(csrf) ? csrf : DEFAULT_CSRF_SELECTOR\n const meta = document.querySelector(`meta[name=\"${ selector }\"]`)\n if (meta && (meta instanceof window.HTMLMetaElement)) return meta.content\n}", "function antiForgeryToken() {\n return $('#anti-forgery-token input').val();\n}", "function getCsrfToken(request) {\n return request.headers['x-xsrf-token'];\n}", "function appendCsrfTokenToForm() {\r\n\tif (window.redcap_csrf_token) {\r\n\t\tsetTimeout(function(){ \r\n\t\t\t$('form').each(function(){ \r\n\t\t\t\t$(this).append('<input type=\"hidden\" name=\"redcap_csrf_token\" value=\"'+redcap_csrf_token+'\">') \r\n\t\t\t});\r\n\t\t},100); \r\n\t}\r\n}", "function csrfDELETE(URL, success) {\n var csrftoken = getCookie(\"csrftoken\");\n if (csrftoken === null) {\n console.log(\"CSRF cookie not found!\");\n return;\n }\n $.ajax({\n url: URL,\n type: \"DELETE\",\n headers: {\"X-CSRFToken\": csrftoken},\n dataType: \"json\",\n success: success\n });\n}", "function getCSRFToken(name) {\n\t/* Django has cross site request forgery protection, so we have to\n\tsend a unique token along with certain requests or the web server\n\twill flat-out reject the request.\n\n\tWhen a form is submitted our template will store this special token\n\tin a cookie named \"csrftoken\". The getCSRFToken function will get\n\tthe token from the cookie so it can be sent along with any request\n\tthat needs a CSRF token to work.*/\n\n\tlet tokenValue = null;\n\n\t// If the cookie exists, grab the data inside of it\n\tif (document.cookie && document.cookie !== '') {\n\t\tconst tokens = document.cookie.split(';');\n\t\t// Cycle through the token's characters\n\t\tfor (let i = 0; i < tokens.length; i++) {\n\t\t\t// Remove whitespace\n\t\t\tconst token = tokens[i].trim();\n\t\t\t// Verify that this is a valid CSRF token generated by Django\n\t\t\tif (token.substring(0, name.length + 1) === (name + '=')) {\n\t\t\t\t// Decode the token and store it in tokenValue\n\t\t\t\ttokenValue = decodeURIComponent(token.substring(name.length + 1));\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\n\treturn tokenValue;\n}", "function setCsrfToken(request, response, next) {\n response.cookie('XSRF-TOKEN', request.csrfToken());\n next();\n}", "function initialiseHeader(){\n $.ajaxSetup({\n headers: {\n 'X-CSRF-TOKEN': $('meta[name=\"csrf-token\"]').attr('content')\n } \n });\n}", "function getTokenedRequest (cb) {\n request({\n url: getUrl('frcsTkn'),\n headers: {\n 'X-CSRF-Token': 'Fetch'\n },\n json: true\n }, function (err, res, body) {\n if (err) return cb(err)\n var cookie = res.headers &&\n res.headers['set-cookie'] &&\n res.headers['set-cookie'][0].split(';')[0]\n var tokenedRequest = request.defaults({\n headers: {\n 'X-CSRF-Token': body.data.token,\n 'Cookie': cookie\n },\n json: true\n })\n cb(null, tokenedRequest)\n })\n}", "function csrfSafeSend(xhr, settings){\n if (!csrfSafeMethod(settings.type) && !this.crossDomain) {\n xhr.setRequestHeader(\"X-CSRFToken\", csrftoken);\n }\n\n}", "function AddAntiForgeryToken(data) {\n data.__RequestVerificationToken = $('#__AjaxAntiForgeryForm input[name=__RequestVerificationToken]').val();\n return data;\n }", "function ajaxBookPurchaseDeadlineDestroy() {\n let csrfToken = $('meta[name=\"csrf-token\"]').attr('content');\n\n $.ajax({\n type : \"POST\",\n url : `/book-purchases/ajax-payment-deadline`,\n data : { '_token' : csrfToken },\n dataType: \"JSON\",\n success : function (response) {\n console.log(response);\n },\n });\n}", "function setNewToken() {\r\n $.ajax({\r\n type: \"post\",\r\n async:true,\r\n contentType: \"application/json;charset=UTF-8\",\r\n url: basePath + \"/personalController/createNewToken\",\r\n success: function(response) {\r\n if(response.success){\r\n $(\"#token\").val(response.obj);\r\n }\r\n }\r\n });\r\n}", "function setGlobalSessionInfo(res, jqXHR){\n\tCSRF_ParamName = jqXHR.getResponseHeader('X-CSRF-PARAM');\n\tCSRF_token = jqXHR.getResponseHeader('X-CSRF-TOKEN');\n}", "getToken() {\n return this.cookies.get('token', {\n signed: true,\n encrypt: true\n });\n }", "function includeCSRFToken ({ method, csrf=true, headers }) {\n if (!csrf || !CSRF_METHODS.includes(method)) return\n const token = getTokenFromDocument(csrf)\n if (!token) return\n return {\n headers: { ...headers, 'X-CSRF-Token': token }\n }\n}", "function setCsrfToken () {\n return function* setCsrfCookieMidleware (next) {\n yield next\n if (this.session)\n this.cookies.set('XSRF-TOKEN', this.csrf, {httpOnly: false})\n }\n}", "async function get_travel_form_token() {\n var res = await agent.get(recent_travels_url)\n var token_string = res.text.match(/antiForgeryToken = '<input name=\"__RequestVerificationToken.*/)[0]\n var token = token_string.match(/value=\".*\"/)[0].slice(7, 99)\n travel_token = token\n}", "function ignoreCsrfProtection(){\n function csrfSafeMethod(method){\n // these HTTP methods do not require CSRF protection\n return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));\n }\n $.ajaxSetup({\n beforeSend: function(xhr, settings){\n if (!csrfSafeMethod(settings.type) && !this.crossDomain){\n xhr.setRequestHeader(\"X-CSRFToken\", Cookies.get('csrftoken'));\n }\n }\n });\n }", "function alertInvalidCsrfToken() {\n\tvalidate_alert( _(\"invalidTokenTitle\"), _(\"invalidTokenMsg\"));\n}", "function resetCsrfToken () {\n getCsrfToken.token = false;\n }", "function getToken() {\n $.post(appServerUrl + \"/user\", null, (data, status) => {\n console.log(\"got response from /user\", data, status);\n token = data.token;\n initializeSession();\n });\n}", "getToken() {\n return Cookies.get(\"cTok\");\n }", "function csrf($httpProvider) {\n // CSRF Support\n $httpProvider.defaults.xsrfCookieName = 'csrftoken';\n $httpProvider.defaults.xsrfHeaderName = 'X-CSRFToken';\n}", "function csrf($httpProvider) {\n // CSRF Support\n $httpProvider.defaults.xsrfCookieName = 'csrftoken';\n $httpProvider.defaults.xsrfHeaderName = 'X-CSRFToken';\n}", "function newToken() {\n $.ajaxSetup({\n dataType: \"json\",\n contentType: \"application/json\",\n headers: {\n Authorization: \"Bearer \" + localStorage.getItem(\"TOKEN\")\n }\n });\n}", "function attachCSRF(req, csrftoken) {\n if (shouldSendCSRF(req.method)) {\n req.headers['X-CSRFToken'] = csrftoken\n }\n return req\n}", "function showMeYourJqXHR(title, jqXHR) {\n\tif (jqXHR) {\n\t\tconsole.log('>>>>> ' + title + ' jqXHR X-CSRF-TOKEN = ' + jqXHR.getResponseHeader('X-CSRF-TOKEN'));\n\t} else {\n\t\tconsole.error('>>>>> ' + title + ' no jqXHR is defined... That\\'s not normal at all...');\n\t}\n}", "function goToVT() {\n location.href = \"../vt/showVT.htm?csrfToken=\" + csrfToken;\n}", "function appendCSRF(url) {\n if (lastCsrfToken) {\n url = (url.indexOf('?') === -1) ? url + '?' : url + '&';\n url += 'csrf_token=' + lastCsrfToken;\n }\n return url;\n}", "function onSuccess(data) {\n \n var csrf_token = $('#csrfToken').val();\n \n $.ajax({\n url: domain + \"/req/ajax_post_linkedin\",\n type: 'post',\n dataType: 'json',\n data:{ response:JSON.stringify(data),csrf_token:csrf_token },\n \n success: function (data) {\n window.location = domain + '/web/Dashboard';\n },error : function (data) {\n console.log('error linkedin');\n } \n });\n \n}", "function serverCsrfCheck (req, res) {\n assert.ok(isReq(req), 'is req')\n assert.ok(isRes(res), 'is res')\n\n const header = req.headers['x-csrf-token']\n if (!header) return false\n\n const cookies = new Cookies(req, res)\n const cookie = cookies.get('CSRF_token')\n if (!cookie) return false\n\n return header === cookie\n}", "function validaLogin() {\n \n $.ajax({\n type: \"POST\",\n url: url + \"usuarios/validatoken\", \n headers: {\n 'Accept': 'application/json',\n 'Content-Type': 'application/json',\n 'Authorization': \"Bearer \" + localStorage.getItem(\"token\")\n },\n success: function (data) { \n },\n error: function (x, exception) { \n location.href = \"index\";\n }\n });\n}", "stripeTokenHandler(token) {\n // Insert the token ID into the form so it gets submitted to the server\n var form = this.formTarget;\n var hiddenInput = document.createElement('input');\n hiddenInput.setAttribute('type', 'hidden');\n hiddenInput.setAttribute('name', 'stripeToken');\n hiddenInput.setAttribute('value', token.id);\n form.appendChild(hiddenInput);\n\n //prevent overclicking.\n this.submitButtonTarget.classList.add(\"hidden\");\n\n // Submit the form\n form.submit();\n }", "get HTMLToken() {\n return document.getElementById(this.id)\n }", "function stripeTokenHandler(token) {\n // Insert the token ID into the form so it gets submitted to the server\n var form = document.getElementById('payment-form');\n var hiddenInput = document.createElement('input');\n hiddenInput.setAttribute('type', 'hidden');\n hiddenInput.setAttribute('name', 'stripeToken');\n hiddenInput.setAttribute('value', token.id);\n form.appendChild(hiddenInput);\n\n\n // Submit the form\n form.submit();\n \n\n}", "function parseCsrfToken(body) {\n if (!body || body.indexOf('csrf_token') === -1) {\n return;\n }\n\n var matches = body.match(/\\'csrf_token\\',\\n\\'(.*)\\',/);\n\n if (matches && matches[1] && matches[1].length >= 20) {\n lastCsrfToken = matches[1];\n }\n}", "function stripeTokenHandler(token, form) {\n // Insert the token ID into the form so it gets submitted to the server\n // var form = document.getElementById('stripe-payment-form');\n var hiddenInput = document.createElement('input');\n hiddenInput.setAttribute('type', 'hidden') ;\n hiddenInput.setAttribute('name', 'stripeToken');\n hiddenInput.setAttribute('value', token.id);\n form.appendChild(hiddenInput);\n\n // Submit the form\n form.submit();\n }", "function setupXHR() {\n const csrfUnsafeMethod = method => !(/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));\n\n $.ajaxSetup({\n beforeSend: (xhr, settings) => {\n if (csrfUnsafeMethod(settings.type)) {\n xhr.setRequestHeader('X-CSRFToken', Cookies.get('csrftoken'));\n }\n },\n });\n }", "function getUsrAutToken() {\n $.ajax({\n //url: '@Url.Action(\"getNewCAMid\", \"cognosUtils\")',\n url: '/cognosUtils/getNewCAMid',\n method: \"GET\",\n cache: false,\n dataType: \"text\",\n //data: { cft_id: 123, end_eff_date: newEndEffDate },\n error: function (jqXHR, textStatus, errorThrown) {\n alert(\"Failed to Get a New Passport Id from the Cognos Server: \" + errorThrown); //<-- Trap and alert of any errors if they occurred\n }\n }).done(function (d) {\n //alert(\"ajax CAMid = \" + d);\n window.localStorage.setItem(\"CAMid\", d);\n window.localStorage.setItem(\"CAMidDt\", new Date());\n });\n\n //return localStorage.getItem(\"CAMid\");\n}", "function fbConnect() {\n\n var authenticity_token = ge(\"authenticity_token\").getAttribute(\"authenticity_token\");\n var params = \"authenticity_token=\" + authenticity_token ;\n ajax(\"/home/connect\", params, null)\n\n}", "function stripeTokenHandler(token) {\n // Insert the token ID into the form so it gets submitted to the server\n var form = document.getElementById('payment-form');\n var hiddenInput = document.createElement('input');\n hiddenInput.setAttribute('type', 'hidden');\n hiddenInput.setAttribute('name', 'stripeToken');\n hiddenInput.setAttribute('value', token.id);\n form.appendChild(hiddenInput);\n\n // Submit the form\n form.submit();\n}", "function goToCPM() {\n location.href = \"../profile/showSearch.htm?csrfToken=\" + csrfToken;\n}", "function stripeTokenHandler(token) {\n // Insert the token ID into the form so it gets submitted to the server\n var hiddenInput = document.createElement(\"input\");\n hiddenInput.setAttribute(\"type\", \"hidden\");\n hiddenInput.setAttribute(\"name\", \"stripeToken\");\n hiddenInput.setAttribute(\"value\", token.id);\n form.appendChild(hiddenInput);\n\n // Submit the form\n form.submit();\n}", "function fetchToken() {\n $.getJSON(buildTokenUrl(), {command: 'request'}, response => {\n token = response.token;\n console.log(`session token fetched: ${token}`);\n });\n}", "function checkValidToken() {\n $('form#reset-token').submit(function(e) {\n e.preventDefault()\n e.stopImmediatePropagation();\n var userResetToken = $('#user-reset-token');\n $.ajax({\n url: \"process/ajaxHandler.php\",\n method: \"POST\",\n dataType: \"JSON\",\n data: {\n action: \"checkToken\",\n userToken: userResetToken.val()\n },\n success: function(response) {\n if (response.status == \"success\") {\n $('form#reset-token').remove();\n $('#container').append(response.passForm)\n $('input#user-reset-pass').focus();\n resetPass();\n } else if (response.status == \"error\") {\n alert(response.description)\n }\n }\n })\n })\n}", "function refreshLogginInfo(callback){\n\t $.ajax({\n url: 'feature/refreshLogin',\n dataType: 'text',\n type: 'post',\n contentType: 'application/x-www-form-urlencoded',\n data: CSRF_ParamName+\"=\"+CSRF_token,\n success: function( data, textStatus, jQxhr ){\n callback(JSON.parse(data));\n },\n error: function( jqXhr, textStatus, errorThrown ){\n \t console.log( errorThrown );\n }\n });\n}", "function ObtenerToken() {\n\tvar respuestaToken = null;\n\n\tvar dataJSON = {\n\t\t\"ClienteId\": \"sample string 1\",\n\t\t\"ClienteLlave\": \"AD64KCYPIWKQ0KPVO2FC\"\n\t}\n\n\t$.ajax({\n\t\ttype: 'POST',\n\t\turl: urlPQRS + \"Token\",\n\t\tdata: JSON.stringify(dataJSON),\n\t\tcrossDomain: true,\n\t\tcontentType: 'application/json',\n\t\tdataType: 'json',\n\t\tasync: false,\n\t\tsuccess: function (data) {\n\t\t\trespuestaToken = data;\n\t\t},\n\t\terror: function (data) {\n\t\t\trespuestaToken = null;\n\t\t},\n\t});\n\n\treturn respuestaToken;\n}", "function ObtenerToken() {\n\tvar respuestaToken = null;\n\n\tvar dataJSON = {\n\t\t\"ClienteId\": \"sample string 1\",\n\t\t\"ClienteLlave\": \"AD64KCYPIWKQ0KPVO2FC\"\n\t}\n\n\t$.ajax({\n\t\ttype: 'POST',\n\t\turl: urlPQRS + \"Token\",\n\t\tdata: JSON.stringify(dataJSON),\n\t\tcrossDomain: true,\n\t\tcontentType: 'application/json',\n\t\tdataType: 'json',\n\t\tasync: false,\n\t\tsuccess: function (data) {\n\t\t\trespuestaToken = data;\n\t\t},\n\t\terror: function (data) {\n\t\t\trespuestaToken = null;\n\t\t},\n\t});\n\n\treturn respuestaToken;\n}", "function stripeTokenHandler(token) {\n // Insert the token ID into the form so it gets submitted to the server\n var form = document.getElementById('payment-form');\n var hiddenInput = document.createElement('input');\n hiddenInput.setAttribute('type', 'hidden');\n hiddenInput.setAttribute('name', 'stripeToken');\n hiddenInput.setAttribute('value', token.id);\n form.appendChild(hiddenInput);\n\n// Submit the form\n form.submit();\n}", "function getToken() {\n var token = document.cookie.replace(/(?:(?:^|.*;\\s*)token\\s*\\=\\s*([^;]*).*$)|^.*$/, \"$1\");\n return token;\n}", "function stripeTokenHandler(token) {\n // Insert the token ID into the form so it gets submitted to the server\n var form = document.getElementById('payment-form');\n var hiddenInput = document.createElement('input');\n hiddenInput.setAttribute('type', 'hidden');\n hiddenInput.setAttribute('name', 'stripeToken');\n hiddenInput.setAttribute('value', token.id);\n form.appendChild(hiddenInput);\n // Submit the form\n form.submit();\n }", "function update_wp_setting_html(){\r\n $.post(BASE_PATH + 'wp/setting_html', {'other_token' : $(\"#other-csrf\").val()}, function(result){\r\n if(result.code != 1600){\r\n $(\"#user-info-wp-tab\").html('<BR><div class=\"alert alert-danger\" role=\"alert\"><p class=\"text-center\">(' + result.code + '):' + result.msg + '</p></div>');\r\n }else {\r\n $(\"#user-info-wp-tab\").html(result.data);\r\n }\r\n }, 'json');\r\n}", "function getToken(){\n return localStorage.getItem(\"token\");\n}", "function addRestCsrfCustomHeader(xhr, settings) {\n// if (settings.url == null || !settings.url.startsWith('/webhdfs/')) {\n\t if (settings.url == null ) {\n return;\n }\n var method = settings.type;\n if (restCsrfCustomHeader != null && !restCsrfMethodsToIgnore[method]) {\n // The value of the header is unimportant. Only its presence matters.\n if (restCsrfToken != null) {\n xhr.setRequestHeader(restCsrfCustomHeader, restCsrfToken);\n } else {\n xhr.setRequestHeader(restCsrfCustomHeader, '\"\"');\n }\n }\n }", "function __set_token_in_all_forms()\n{\n let temp_token = $(\"#main-js\").data(\"token\");\n let form = $(\"form\");\n (\n form.length === 0\n ||\n $.postJSON(\n api_url + \"get/token/\",\n {\n \"temp_token\":temp_token\n },\n function(data){\n token = data[\"token\"];\n for(let i = 0;i < form.length;i++)\n {\n form.eq(i).append(\n $(\"<input>\",\n {\n type:\"hidden\",\n name:\"token\",\n value:token\n }\n )\n );\n }\n }\n )\n );\n}", "function fixAjax(event, xhr, settings) {\n function getCookie(name) {\n var cookieValue = null;\n if (document.cookie && document.cookie != '') {\n var cookies = document.cookie.split(';');\n for (var i = 0; i < cookies.length; i++) {\n var cookie = jQuery.trim(cookies[i]);\n // Does this cookie string begin with the name we want?\n if (cookie.substring(0, name.length + 1) == (name + '=')) {\n cookieValue = decodeURIComponent(cookie.substring(name.length + 1));\n break;\n }\n }\n }\n return cookieValue;\n }\n function sameOrigin(url) {\n // url could be relative or scheme relative or absolute\n var host = document.location.host; // host + port\n var protocol = document.location.protocol;\n var sr_origin = '//' + host;\n var origin = protocol + sr_origin;\n // Allow absolute or scheme relative URLs to same origin\n return (url == origin || url.slice(0, origin.length + 1) == origin + '/') ||\n (url == sr_origin || url.slice(0, sr_origin.length + 1) == sr_origin + '/') ||\n // or any other URL that isn't scheme relative or absolute i.e relative.\n !(/^(\\/\\/|http:|https:).*/.test(url));\n }\n function safeMethod(method) {\n return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));\n }\n\n if (!safeMethod(settings.type) && sameOrigin(settings.url)) {\n xhr.setRequestHeader(\"X-CSRFToken\", getCookie('csrftoken'));\n }\n}", "static post(option) {\n \n return $.ajax({\n\n type: 'POST',\n url: option.url,\n data: JSON.stringify(option.data),\n dataType: 'json',\n contentType: 'application/json',\n beforeSend: (xhr) => {\n xhr.setRequestHeader('Authorization', `Bearer ${localStorage.getItem('auth_token')}`);\n }\n });\n }", "function stripeTokenHandler(token) {\n // Insert the token ID into the form so it gets submitted to the server\n var form = document.getElementById('payment-form');\n var hiddenInput = document.createElement('input');\n hiddenInput.setAttribute('type', 'hidden');\n hiddenInput.setAttribute('name', 'stripeToken');\n hiddenInput.setAttribute('value', token.id);\n form.appendChild(hiddenInput);\n\n // Submit the form\n form.submit();\n}", "function update_user_info_html(){\r\n $.post(BASE_PATH + 'user/user_info_html', {'other_token' : $(\"#other-csrf\").val()}, function(result){\r\n if(result.code != 0){\r\n $(\"#user-info-tab\").html('<BR><div class=\"alert alert-danger\" role=\"alert\"><p class=\"text-center\">(' + result.code + '):' + result.msg + '</p></div>');\r\n }else {\r\n $(\"#user-info-tab\").html(result.data);\r\n }\r\n }, 'json');\r\n}", "getToken() {\n return localStorage.getItem(\"id_token\");\n }", "function tokenHandler (result)\n{\n\tlocalStorage.registrationId = result;\n\tvar jqxhr = $.ajax(\n\t{\t\t\t\n\t\turl: localStorage.registerPushnotificationRegIDURL + result,\n\t\ttype:\"GET\",\n\t\tdataType: \"json\"\n\t});\n}", "function delToken() {\n noToken = \"Token Removed\";\n $.ajax({\n type: 'POST',\n url: '/savetoken',\n data: { token: noToken },\n success: function() {\n console.log('Removed token from SP database: ' + noToken);\n window.location.reload();\n }\n });\n}", "getToken() {\n\t\treturn this.qdacityTokenAuthenticationProvider.getToken();\n\t}", "getToken() {\n return localStorage.getItem('id_token');\n }", "token(value){ window.localStorage.setItem('token', value)}", "function getSession() {\n $.ajax({\n url: '/Cart/getSession',\n type: 'get',\n success: function (tokenID) {\n //alert(tokenID);\n cartsView(tokenID);\n \n }\n })\n}", "function getToken(){\n var token = localStorage.getItem('token', token);\n if (token != ''){\n document.getElementById(\"token\").value = token;\n }\n return token;\n}", "function fetchWithCSRFToken(url, otherParts, headers = {}) {\n const csrfToken = getCookie(\"csrftoken\");\n const defaultHeaders = {\n \"X-CSRFToken\": csrfToken\n };\n const combinedHeaders = Object.assign({}, defaultHeaders, headers);\n return fetch(\n url,\n Object.assign({}, otherParts, { headers: combinedHeaders })\n );\n}", "function mdGamify(userCSRFToken) {\n csrfToken = userCSRFToken;\n $(\".gamify_fancybox\").fancybox();\n $(\"form#gamify_org_selector_form\").append('<div id=\"authorize_loader\" class=\"pull-right form-loading\"></div>');\n $(\"form#gamify_org_selector_form\").submit(function(event) {\n var url = $(this).attr('action');\n var data = $(this).serialize();\n $(this).find('.btn-submit').attr('disabled', true);\n $('#authorize_loader').show();\n $.post(url, data, function(data, textStatus, xhr) {\n var form = $(\"form#gamify_org_selector_form\");\n $('#authorize_loader').hide();\n if (data.success === true) {\n setBenefitingChurch(data.organization, true);\n } else {\n var form = $(\"form#gamify_org_selector_form\");\n var alerts = form.find('div.alert');\n if (alerts.length > 0) {\n alerts.fadeOut('slow', function() {\n form.prepend('<div class=\"alert alert-danger\"> <strong>Sorry</strong> you need to select a valid organization.</div>');\n $(this).remove();\n });\n } else {\n form.prepend('<div class=\"alert alert-danger\"> <strong>Sorry</strong> you need to select a valid organization.</div>'); \n };\n };\n });\n return false;\n });\n checkHasBenefitingChurch();\n}", "function getUserToken(){\n\t\treturn $cookies.get('user.token');\n\t}", "function requestToken() {\n return !tokenExpired()\n ? Promise.resolve(_token)\n : request(METHOD_GET, '/auth/token', null, { 'X-CSRF-TOKEN': _csrf })\n .then(function (xhr) {\n var json = JSON.parse(xhr.response);\n _token = json.data;\n\n return _token;\n });\n }", "requestToken() {\n return this.get('request-token');\n }", "stripeTokenHandler(token) {\n let form = this.element\n const fields = ['stripe_token', 'last4', 'exp_month', 'exp_year', 'brand']\n fields.forEach((string) => {\n let input = document.createElement('input')\n const name = string === 'stripe_token' ? string : `card_${string}`\n const value = string === 'stripe_token' ? token.id : token.card[string]\n input.setAttribute('type', 'hidden')\n input.setAttribute('name', `subscription[${name}]`)\n input.setAttribute('value', value)\n form.appendChild(input)\n })\n\n // Submit the form\n form.submit()\n }", "function myFormSubmit(action, method, input) {\n 'use strict';\n var form;\n form = $('<form />', {\n action: action,\n method: method,\n style: 'display: none;'\n });\n if (typeof input !== 'undefined' && input !== null) {\n $.each(input, function (name, value) {\n $('<input />', {\n type: 'hidden',\n name: name,\n value: value\n }).appendTo(form);\n });\n }\n var csrf_input;\n csrf_input = $('<input />', {\n type: 'hidden',\n name: 'csrfmiddlewaretoken',\n value: csrftoken\n });\n \n form.append(csrf_input);\n form.appendTo('body').submit();\n}", "static getToken() {\n return localStorage.getItem('token');\n }", "static getToken() {\n return localStorage.getItem('token');\n }", "function fnGroupeAjax() {\n var url = \"/Groupes/Create\";\n var data = {\n NomGroupe: $(\"#NomGroupe2\").val(),\n };\n $.ajax({\n data: JSON.stringify(data),\n type: \"POST\",\n url: url,\n datatype: \"text/plain\",\n contentType: \"application/json; charset=utf-8\",\n beforeSend: function (request) {\n request.setRequestHeader(\"RequestVerificationToken\", $(\"input[name='__RequestVerificationToken']\").val());\n },\n success: function (result) {\n // alert(result);\n },\n error: function (xhr, status) { alert(\"erreur:\" + status); }\n });\n return false;\n}", "function submitForm()\n{\n\n var email_login = $(\"#email_login\").val();\n var password_login = $(\"#password_login\").val();\n var post_data = {\n 'email_login': email_login,\n 'password_login': password_login,\n// csrf_token_name: csrf_hash\n }\n $.ajax({\n type: 'POST',\n url: base_url + 'registration/check_login',\n data: post_data,\n dataType: \"json\",\n beforeSend: function ()\n {\n $(\"#error\").fadeOut();\n $(\"#btn1\").html('Login ...');\n },\n success: function (response)\n {\n if (response.data == \"ok\") {\n // alert(\"login\");\n $(\"#btn1\").html('<img src=\"' + base_url + 'images/btn-ajax-loader.gif\" /> &nbsp; Login ...');\n window.location = base_url + \"freelance-Work/home\";\n } else if (response.data == \"password\") {\n $(\"#errorpass\").html('<label for=\"email_login\" class=\"error\">Please enter a valid password.</label>');\n document.getElementById(\"password_login\").classList.add('error');\n document.getElementById(\"password_login\").classList.add('error');\n $(\"#btn1\").html('Login');\n } else {\n $(\"#errorlogin\").html('<label for=\"email_login\" class=\"error\">Please enter a valid email.</label>');\n document.getElementById(\"email_login\").classList.add('error');\n document.getElementById(\"email_login\").classList.add('error');\n $(\"#btn1\").html('Login');\n }\n }\n });\n return false;\n}", "getToken() {\n return localStorage.getItem(\"token\") || null\n }", "function getToken() {\n return sessionStorage.getItem('auth');\n }", "function validCustomerID(){\n $.ajax({\n headers:{'X-CSRF-TOKEN': csrfToken},\n url:baseUrl + 'admin/customer/maxCustomerID',\n type:'post',\n data:{\n 'Type':$('#Type').val(),\n 'Provision':$('#Provision').val(),\n },\n success:function(response){\n $('#CustomerID').val(response)\n },\n error:function(response){\n console.log(response)\n }\n })\n}", "function getToken() {\n if(window.localStorage.getItem('token') != null){\n return window.localStorage.getItem('token')\n } \n return ''\n}" ]
[ "0.79845357", "0.79074097", "0.7589329", "0.7508163", "0.7481506", "0.744485", "0.74270856", "0.7418959", "0.74079454", "0.74018127", "0.7293658", "0.7286877", "0.7210181", "0.7185028", "0.7154946", "0.70151967", "0.6964115", "0.69359493", "0.6709752", "0.65040374", "0.649025", "0.6429465", "0.63763064", "0.6372857", "0.6357648", "0.6334866", "0.6087249", "0.6086145", "0.6039053", "0.6034927", "0.5899219", "0.58937156", "0.5845185", "0.58271444", "0.5815385", "0.577391", "0.5740507", "0.5739709", "0.5718694", "0.5708203", "0.56951016", "0.5682474", "0.5682474", "0.5648628", "0.56402206", "0.56049156", "0.5599925", "0.55954593", "0.5531981", "0.5525526", "0.5503076", "0.55020034", "0.54870176", "0.5485054", "0.54733235", "0.54494125", "0.5448942", "0.54212886", "0.5409082", "0.54041076", "0.54010004", "0.53953624", "0.5388589", "0.53840697", "0.5381474", "0.5379192", "0.5379192", "0.5376908", "0.53661394", "0.5354416", "0.5350041", "0.5346547", "0.53355837", "0.53324735", "0.53255814", "0.5324666", "0.5310187", "0.53092986", "0.52982056", "0.52877825", "0.5285082", "0.52732176", "0.52645934", "0.52612245", "0.52598655", "0.5259577", "0.52520216", "0.5246966", "0.52441204", "0.52430826", "0.5232518", "0.5202567", "0.5163733", "0.5156427", "0.5156427", "0.5146183", "0.5130653", "0.5128989", "0.5102261", "0.5097716", "0.50788283" ]
0.0
-1
Component Lifecycle Functions ComponentWillMount ComponentDidMount ! ComponentWillRecieveProps ComponentWillUpdate ComponentDidUpdate
componentDidMount() { // Materialize Component Initialization // $('#select').materialize-select(); // Ajax Calls To Grab Component Data $.ajax({ type: 'GET', url: '/boards', dataType: 'JSON' }).success( boards => { // once we have data back, we set state this.setState({ boards, loading: false }); // named same, so you dont need to put data after boards: }).fail( data => { // handle with alert or flash this.setState({ loading: false }); console.log(data); }); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "componentDidMount() { this.props.events.on('update', this.forceUpdate); }", "componentDidMount() {\n this.componentDidUpdate();\n }", "componentDidMount(){\n this.componentDidUpdate();\n }", "componentDidMount(props) {\n\n }", "componentDidMount() {\n this.update(this.props)\n }", "componentDidMount() {\n if (super.componentDidMount) super.componentDidMount();\n\n this.checkForStateChange(undefined, this.state);\n }", "componentDidMount() {\n this.forceUpdate()\n }", "componentDidMount() {\n this.forceUpdate();\n }", "componentDidUpdate(props_) {}", "componentDidUpdate(prevProps) { \n //console.log(\"componentDidUpdate:START--------------------------------\");\n this.handleUpdateReactApp(prevProps);\n this.updateReactAppWithError(prevProps);\n //console.log(\"componentDidUpdate:end--------------------------------\");\n }", "componentDidUpdate(prevProps) {}", "componentDidMount() {\n console.log('componentDidMoun');\n }", "componentDidMount() {\n this.updateStateFromProps(this.props);\n }", "componentDidMount() {}", "componentDidMount() {}", "componentDidMount() {}", "componentDidMount() {}", "componentDidMount() {}", "componentDidMount() {}", "componentDidMount() {}", "componentDidMount() {}", "componentDidMount() {}", "componentDidMount() {}", "componentDidMount() {}", "componentDidMount() {}", "componentDidMount() {}", "componentDidMount() {}", "componentDidMount() {}", "componentDidMount() {}", "componentDidMount() {\n this.props.onMount();\n }", "componentDidUpdate(prevProps, prevState) {\n if (this.props !== prevProps) {\n this.callRender();\n }\n }", "componentDidMount(){\n console.log('Life Cycle A - componentDidMount');\n }", "componentWillMount() { //First method in the lifecycle hook that gets update.\n console.log(\"Component will mount\"); //if you cann setState in here then new render will take it into account. \n }", "componentDidMount(){\n \n }", "componentWillMount() {\n \n }", "componentDidMount(){ //Cuando un compoennte se monta y se muestra en pantalla se llama este método\n console.log(\"did Mount\");\n }", "componentDidMount() {\n console.info(\"componentDidMount()\");\n }", "componentDidMount() {\n \n }", "componentDidMount() {\n \n }", "componentDidMount(){\n console.log('component did mount...');\n }", "componentDidMount() {\n console.log(\"component did mount\");\n }", "componentDidUpdate(prevProps) {\n if (this.props === prevProps) {\n return;\n }\n this.forceUpdate();\n }", "componentDidMount() {\n this.componentLoaded = true;\n }", "componentDidMount(){\n console.log(\"ComponentdidMount\"); \n }", "componentDidMount() { \n \n }", "componentDidMount(){\n console.log(\">>>>in componentDidMount<<<<<\")\n }", "componentDidUpdate(prevProps, prevState) { }", "componentDidMount() {\n\t\t\n\t\t\n\t\tlet metas = [\n\t\t\t{name: \"description\", content: \"Profile Description\"},\n\t\t\t{property: \"og:type\", content: \"article\"}\n\t\t];\n\t\tthis.props.dispatch(appUpdate({title:'Profile',metas: metas}))\n\t\t\n\t\t\n\t\t// start a timer for the clock:\n\t\tthis.timer = setInterval(this.updateTime, 1000);\n\t\tthis.updateTime();\n\n\t\t// every time we get remounted, increment a counter:\n\t\tthis.setState({ count: this.state.count+1 });\n\t}", "componenetDidMount() { }", "componentDidMount(){\n console.log('Component Did Mount')\n }", "componentDidMount() {\n console.log('component did mount')\n }", "onComponentMount() {\n\n }", "componentDidMount()\n {\n\n }", "componentDidMount() {\n\n }", "componentDidMount() {\n\n }", "componentDidMount() {\n\n }", "componentDidMount () {\n\n }", "componentDidMount() {\n \n }", "componentWillMount(){\n console.log(\"ComponentWillMount Execution\");\n }", "componentDidMount () {\n\n }", "componentDidMount () {\n }", "componentDidMount() {\n }", "componentDidMount() {\n }", "componentDidMount() {\n }", "componentDidMount() {\n\t}", "componentDidMount() {\n\t}", "componentDidMount() {\n\t}", "componentWillMount() {\n console.log('Before mount...');\n }", "componentDidMount() {\n\n }", "componentDidMount() {\n\n }", "componentDidMount() {\n\n }", "componentDidMount() {\n\n }", "componentDidUpdate(prevProps, prevState){\n console.log(\"componentDidUpdate\");\n }", "componentDidMount() {\n console.log(\"component mounted\");\n }", "componentDidMount(){\n console.log(\"ComponentDidMount Execution\");\n\n }", "componentDidMount() {\n\n\t}", "componentDidMount() {\n console.log(\"Component mounted\");\n }", "componentDidUpdate(prevProps, prevState) {\n console.log(\"componentDidUpdate\");\n }", "componentDidMount(){\n console.log('componentDidMount');\n }", "componentDidMount(){\n console.log(\"component DID MOUNT!\")\n }", "componentDidMount(){\n\n }", "componentDidMount(){\n\n }", "componentWillMount(){}", "componentWillMount() {}", "componentWillMount() {}", "componentWillMount() {}", "componentWillMount() {}", "componentWillMount() {}", "componentWillUpdate() {\n\t\tsetInterval(() => {\n\t\t\tthis.forceUpdate(this.componentDidMount);\n\t\t}, 3000);\n\t}", "componentDidMount(){\n\n }", "componentDidMount(){\n\n }", "componentDidMount(){\n }", "componentDidMount() {\n console.log('--------------------------- componentDidMount -----------------------------');\n }", "componentDidMount() {\n console.log('Component Did Mount');\n console.log('-------------------');\n\n }", "componentWillMount() {\n \n \n }", "componentDidMount(){\n }", "componentDidMount() {\n console.log('componentDidMount')\n }", "componentDidMount () {\n\n\t}", "componentDidMount () {\n\n\t}", "componentDidUpdate(prevProps, prevState) {\n // console.log(\"=========================> componentDidUpdate\", prevProps, prevState);\n }", "componentDidUpdate(prevProps, prevState) {\n console.log('algo cambio')\n }" ]
[ "0.7613408", "0.7522502", "0.7448238", "0.7443576", "0.7367286", "0.73608565", "0.7341249", "0.73318285", "0.7317524", "0.7292225", "0.724198", "0.7239525", "0.7238141", "0.7229315", "0.7229315", "0.7229315", "0.7229315", "0.7229315", "0.7229315", "0.7229315", "0.7229315", "0.7229315", "0.7229315", "0.7229315", "0.7229315", "0.7229315", "0.7229315", "0.7229315", "0.7229315", "0.72064453", "0.71998674", "0.71980417", "0.71961135", "0.7172748", "0.7159782", "0.71566683", "0.71543556", "0.71523154", "0.71523154", "0.71277624", "0.7122734", "0.7114473", "0.7110471", "0.7106934", "0.7097735", "0.70875204", "0.7084397", "0.7080858", "0.70800775", "0.7077622", "0.706972", "0.7063131", "0.7060532", "0.7055216", "0.7055216", "0.7055216", "0.70537144", "0.70462084", "0.70460653", "0.7045642", "0.70447046", "0.7039381", "0.7039381", "0.7039381", "0.70354086", "0.70354086", "0.70354086", "0.70351315", "0.70348233", "0.70348233", "0.70348233", "0.70348233", "0.70301557", "0.7029069", "0.70260507", "0.70254016", "0.7019966", "0.7018661", "0.7016953", "0.7016644", "0.7015308", "0.7015308", "0.7014439", "0.7014088", "0.7014088", "0.7014088", "0.7014088", "0.7014088", "0.7012711", "0.7007344", "0.7007344", "0.7001901", "0.7000132", "0.6998449", "0.69980794", "0.6996954", "0.699127", "0.6991191", "0.6991191", "0.69814384", "0.697871" ]
0.0
-1
(Internal) converts a percentage (`0..1`) to a bar translateX percentage (`100%..0%`).
function toBarPerc(n) { return (-1 + n) * 100; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function barXFunc (d, i) { return (i * barwidth)+\"%\" ; }", "function xValFromPct(percent) {\n return percent * canvas.width / 100;\n}", "function toBarPerc(n) {\nreturn (-1 + n) * 100;\n}", "function pctFromXVal(xValue) {\n return xValue * 100 / canvas.width;\n}", "setPercentage(percentage) {\n const value = percentage * this.valueWidth + this.minValue;\n this.setValue(value);\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}", "function hundredPercent(evt) {\n\twb.cm_percent = 1;\n\twb.drawRectForViewPort();\n\tvar element = document.querySelector('.code_map');\n\tvar transfromString = (\"scale(1, 1)\");\n // now attach that variable to each prefixed style\n element.style.webkitTransform = transfromString;\n element.style.MozTransform = transfromString;\n element.style.msTransform = transfromString;\n element.style.OTransform = transfromString;\n element.style.transform = transfromString;\n}", "function pctChange(val){\r\n if(val > 0){\r\n return '' + val + '%';\r\n }else if(val < 0){\r\n return '' + val + '%';\r\n }\r\n return val;\r\n }", "function pctChange(val){\r\n if(val > 0){\r\n return '' + val + '%';\r\n }else if(val < 0){\r\n return '' + val + '%';\r\n }\r\n return val;\r\n }", "function pctChange(val){\r\n if(val > 0){\r\n return '' + val + '%';\r\n }else if(val < 0){\r\n return '' + val + '%';\r\n }\r\n return val;\r\n }", "function pctChange(val){\r\n if(val > 0){\r\n return '' + val + '%';\r\n }else if(val < 0){\r\n return '' + val + '%';\r\n }\r\n return val;\r\n }", "function pctChange(val){\r\n if(val > 0){\r\n return '' + val + '%';\r\n }else if(val < 0){\r\n return '' + val + '%';\r\n }\r\n return val;\r\n }", "function pctChange(val){\r\n if(val > 0){\r\n return '' + val + '%';\r\n }else if(val < 0){\r\n return '' + val + '%';\r\n }\r\n return val;\r\n }", "percentageBar (score) {\n var styles = {\n height: '5px',\n backgroundColor: 'black',\n borderRadius: '15px'\n };\n styles.width = (score / 5 * 100) + '%';\n return styles;\n }", "function getPositivePercentValue(val) { return val / currentSerie.maxRange * 100; }", "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 setProgressBar(curStep){\n var percent = parseFloat(50 / steps) * curStep;\n percent = percent.toFixed();\n $(\".barrafinal\")\n .css(\"width\",percent+\"%\")\n .html(percent+\"%\"); \n }", "function convertToPercent(index, val) {\n\n if (index == \"Above4\" || index == \"Above5\") {\n\n return Math.round(val * 100) + \"%\";\n\n }\n\n return val;\n\n}", "function toPercentage(range, value) {\n return fromPercentage(range, range[0] < 0 ?\n\t\t\t\tvalue + Math.abs(range[0]) :\n\t\t\t\t\tvalue - range[0]);\n }", "function toPercentage(range, value) {\n return fromPercentage(range, range[0] < 0 ? value + Math.abs(range[0]) :\n value - range[0]);\n }", "function percentage() {\n return percent;\n}", "function fromPercentage ( range, value ) {\r\n\t\treturn (value * 100) / ( range[1] - range[0] );\r\n\t}", "function fromPercentage ( range, value ) {\r\n\t\treturn (value * 100) / ( range[1] - range[0] );\r\n\t}", "function fromPercentage ( range, value ) {\r\n\t\t\treturn (value * 100) / ( range[1] - range[0] );\r\n\t\t}", "function toBarPerc(n) {\n return (-1 + n) * 100;\n }", "function toBarPerc(n) {\n return (-1 + n) * 100;\n }", "function toBarPerc(n) {\n return (-1 + n) * 100;\n }", "function toPercentage ( range, value ) {\r\n\t\t\treturn fromPercentage( range, range[0] < 0 ?\r\n\t\t\t\tvalue + Math.abs(range[0]) :\r\n\t\t\t\t\tvalue - range[0] );\r\n\t\t}", "function fromPercentage(range, value) {\n return (value * 100) / (range[1] - range[0]);\n }", "function generatePercentBar(percent) {\n return \"<span class='coverage-bar'>\" +\n \"<span class='coverage-bar-inner' style='width:\" + percent + \"px'>\" +\n \"</span></span>\";\n}", "function toBarPerc(n) {\n\t return (-1 + n) * 100;\n\t }", "function toBarPerc(n) {\n\t return (-1 + n) * 100;\n\t }", "function toBarPerc(n) {\n\t return (-1 + n) * 100;\n\t }", "function toBarPerc(n) {\n\t return (-1 + n) * 100;\n\t }", "function fromPercentage ( range, value ) {\n\t\treturn (value * 100) / ( range[1] - range[0] );\n\t}", "function fromPercentage ( range, value ) {\n\t\treturn (value * 100) / ( range[1] - range[0] );\n\t}", "function fromPercentage ( range, value ) {\n\t\treturn (value * 100) / ( range[1] - range[0] );\n\t}", "function fromPercentage ( range, value ) {\n\t\treturn (value * 100) / ( range[1] - range[0] );\n\t}", "function fromPercentage ( range, value ) {\n\t\treturn (value * 100) / ( range[1] - range[0] );\n\t}", "function fromPercentage ( range, value ) {\n\t\treturn (value * 100) / ( range[1] - range[0] );\n\t}", "function fromPercentage ( range, value ) {\n\t\treturn (value * 100) / ( range[1] - range[0] );\n\t}", "function fromPercentage ( range, value ) {\n\t\treturn (value * 100) / ( range[1] - range[0] );\n\t}", "function fromPercentage ( range, value ) {\n\t\treturn (value * 100) / ( range[1] - range[0] );\n\t}", "function fromPercentage ( range, value ) {\n\t\treturn (value * 100) / ( range[1] - range[0] );\n\t}", "function fromPercentage ( range, value ) {\n\t\treturn (value * 100) / ( range[1] - range[0] );\n\t}", "function fromPercentage ( range, value ) {\n\t\treturn (value * 100) / ( range[1] - range[0] );\n\t}", "function fromPercentage ( range, value ) {\n\t\treturn (value * 100) / ( range[1] - range[0] );\n\t}", "function fromPercentage ( range, value ) {\n\t\treturn (value * 100) / ( range[1] - range[0] );\n\t}", "function toPercentage ( range, value ) {\n\t\t\treturn fromPercentage( range, range[0] < 0 ?\n\t\t\t\tvalue + Math.abs(range[0]) :\n\t\t\t\t\tvalue - range[0] );\n\t\t}", "function toPercentage ( range, value ) {\r\n\t\treturn fromPercentage( range, range[0] < 0 ?\r\n\t\t\tvalue + Math.abs(range[0]) :\r\n\t\t\t\tvalue - range[0] );\r\n\t}", "function toPercentage ( range, value ) {\r\n\t\treturn fromPercentage( range, range[0] < 0 ?\r\n\t\t\tvalue + Math.abs(range[0]) :\r\n\t\t\t\tvalue - range[0] );\r\n\t}", "function fromPercentage ( range, value ) {\n\t\t\treturn (value * 100) / ( range[1] - range[0] );\n\t\t}", "percentage() {\n const { value } = this.state;\n const numt = Number(value) / 100;\n this.setState({ value: `${numt}` });\n }", "function toPercentage(range, value) {\n return fromPercentage(range, range[0] < 0 ? value + Math.abs(range[0]) : value - range[0]);\n }", "function fromPercentage(range, value) {\n return (value * 100) / (range[1] - range[0]);\n }", "function formatPercentage(aPerc100x)\n{\n return (aPerc100x / 100).toFixed(2) + \"%\";\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 }", "function convertToPercentage(n) {\n if (n <= 1) {\n n = n * 100 + \"%\";\n }\n\n return n;\n }", "function convertToPercentage(n) {\n\t if (n <= 1) {\n\t n = (n * 100) + \"%\";\n\t }\n\t\n\t return n;\n\t}", "function convertToPercentage(n) {\n\t if (n <= 1) {\n\t n = (n * 100) + \"%\";\n\t }\n\t\n\t return n;\n\t}", "function convertToPercentage(n) {\n\t if (n <= 1) {\n\t n = (n * 100) + \"%\";\n\t }\n\t\n\t return n;\n\t}", "function toPercentage(range, value) {\n return fromPercentage(range, range[0] < 0 ? value + Math.abs(range[0]) : value - range[0], 0);\n }", "function toPercentage(range, value) {\n return fromPercentage(range, range[0] < 0 ? value + Math.abs(range[0]) : value - range[0], 0);\n }", "function toPercentage(range, value) {\n return fromPercentage(range, range[0] < 0 ? value + Math.abs(range[0]) : value - range[0], 0);\n }", "function toPercentage(range, value) {\n return fromPercentage(range, range[0] < 0 ? value + Math.abs(range[0]) : value - range[0], 0);\n }" ]
[ "0.6634575", "0.653026", "0.6516677", "0.6515595", "0.6494832", "0.64742875", "0.64114827", "0.6394538", "0.6394538", "0.6394538", "0.6394538", "0.6394538", "0.6394538", "0.6376479", "0.6370016", "0.6367201", "0.6324211", "0.6291986", "0.62890375", "0.6282405", "0.6278994", "0.6276092", "0.6276092", "0.626888", "0.62685996", "0.62685996", "0.62685996", "0.6268094", "0.6267564", "0.62642294", "0.6263645", "0.6263645", "0.6263645", "0.6263645", "0.6246252", "0.6246252", "0.6246252", "0.6246252", "0.6246252", "0.6246252", "0.6246252", "0.6246252", "0.6246252", "0.6246252", "0.6246252", "0.6246252", "0.6246252", "0.6246252", "0.62429816", "0.6237745", "0.6237745", "0.62303084", "0.6229504", "0.62195474", "0.6218229", "0.6217919", "0.6208242", "0.6200246", "0.6194874", "0.6194874", "0.6194874", "0.61941427", "0.61941427", "0.61941427", "0.61941427" ]
0.6299756
51
(Internal) returns the correct CSS for changing the bar's position given an n percentage, and speed and ease from Settings
function barPositionCSS(n, speed, ease) { var barCSS; if (Settings.positionUsing === 'translate3d') { barCSS = { transform: 'translate3d('+toBarPerc(n)+'%,0,0)' }; } else if (Settings.positionUsing === 'translate') { barCSS = { transform: 'translate('+toBarPerc(n)+'%,0)' }; } else { barCSS = { 'margin-left': toBarPerc(n)+'%' }; } barCSS.transition = 'all '+speed+'ms '+ease; return barCSS; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function barPositionCSS(n, speed, ease) {\nvar barCSS;\nif (Settings.positionUsing === 'translate3d') {\nbarCSS = { transform: 'translate3d('+toBarPerc(n)+'%,0,0)' };\n} else if (Settings.positionUsing === 'translate') {\nbarCSS = { transform: 'translate('+toBarPerc(n)+'%,0)' };\n} else {\nbarCSS = { 'margin-left': toBarPerc(n)+'%' };\n}\nbarCSS.transition = 'all '+speed+'ms '+ease;\nreturn barCSS;\n}", "function barPositionCSS(n, speed, ease) {\n\t var barCSS;\n\n\t if (Settings.positionUsing === 'translate3d') {\n\t barCSS = { transform: 'translate3d(' + toBarPerc(n) + '%,0,0)' };\n\t } else if (Settings.positionUsing === 'translate') {\n\t barCSS = { transform: 'translate(' + toBarPerc(n) + '%,0)' };\n\t } else {\n\t barCSS = { 'margin-left': toBarPerc(n) + '%' };\n\t }\n\n\t barCSS.transition = 'all ' + speed + 'ms ' + ease;\n\n\t return barCSS;\n\t }", "function barPositionCSS(n, speed, ease) {\n var barCSS;\n\n if (Settings.positionUsing === 'translate3d') {\n barCSS = { transform: 'translate3d(' + toBarPerc(n) + '%,0,0)' };\n } else if (Settings.positionUsing === 'translate') {\n barCSS = { transform: 'translate(' + toBarPerc(n) + '%,0)' };\n } else {\n barCSS = { 'margin-left': toBarPerc(n) + '%' };\n }\n\n barCSS.transition = 'all ' + speed + 'ms ' + ease;\n\n return barCSS;\n }", "function barPositionCSS(n, speed, ease) {\n\t var barCSS;\n\n\t if (Settings.positionUsing === 'translate3d') {\n\t barCSS = { transform: 'translate3d('+toBarPerc(n)+'%,0,0)' };\n\t } else if (Settings.positionUsing === 'translate') {\n\t barCSS = { transform: 'translate('+toBarPerc(n)+'%,0)' };\n\t } else {\n\t barCSS = { 'margin-left': toBarPerc(n)+'%' };\n\t }\n\n\t barCSS.transition = 'all '+speed+'ms '+ease;\n\n\t return barCSS;\n\t }", "function barPositionCSS(n, speed, ease) {\n\t var barCSS;\n\n\t if (Settings.positionUsing === 'translate3d') {\n\t barCSS = { transform: 'translate3d('+toBarPerc(n)+'%,0,0)' };\n\t } else if (Settings.positionUsing === 'translate') {\n\t barCSS = { transform: 'translate('+toBarPerc(n)+'%,0)' };\n\t } else {\n\t barCSS = { 'margin-left': toBarPerc(n)+'%' };\n\t }\n\n\t barCSS.transition = 'all '+speed+'ms '+ease;\n\n\t return barCSS;\n\t }", "function barPositionCSS(n, speed, ease) {\n\t var barCSS;\n\t\n\t if (Settings.positionUsing === 'translate3d') {\n\t barCSS = { transform: 'translate3d('+toBarPerc(n)+'%,0,0)' };\n\t } else if (Settings.positionUsing === 'translate') {\n\t barCSS = { transform: 'translate('+toBarPerc(n)+'%,0)' };\n\t } else {\n\t barCSS = { 'margin-left': toBarPerc(n)+'%' };\n\t }\n\t\n\t barCSS.transition = 'all '+speed+'ms '+ease;\n\t\n\t return barCSS;\n\t }", "function barPositionCSS(n, speed, ease) {\n var barCSS;\n\n if (Settings.positionUsing === 'translate3d') {\n barCSS = { transform: 'translate3d('+toBarPerc(n)+'%,0,0)' };\n } else if (Settings.positionUsing === 'translate') {\n barCSS = { transform: 'translate('+toBarPerc(n)+'%,0)' };\n } else {\n barCSS = { 'margin-left': toBarPerc(n)+'%' };\n }\n\n barCSS.transition = 'all '+speed+'ms '+ease;\n\n return barCSS;\n }", "function barPositionCSS(n, speed, ease) {\n var barCSS;\n\n if (Settings.positionUsing === 'translate3d') {\n barCSS = { transform: 'translate3d('+toBarPerc(n)+'%,0,0)' };\n } else if (Settings.positionUsing === 'translate') {\n barCSS = { transform: 'translate('+toBarPerc(n)+'%,0)' };\n } else {\n barCSS = { 'margin-left': toBarPerc(n)+'%' };\n }\n\n barCSS.transition = 'all '+speed+'ms '+ease;\n\n return barCSS;\n }", "function getBarSpeed() {\n if (level > 3) {\n barSpeed = timer[3];\n } else {\n barSpeed = timer[level];\n }\n return barSpeed;\n }", "percentAnimation(num, ele) {\n this.state.percentBoxs.forEach((tab) => {\n tab.style.color = \"#8BAEC2\";\n });\n if (num === 0) {\n this.setState({ percent: 0 });\n document.getElementById(\"percent_animation_box\").style.left = \"0px\";\n } else if (num === 25) {\n this.setState({ percent: 25 });\n document.getElementById(\"percent_animation_box\").style.left = \"80px\";\n } else if (num === 50) {\n this.setState({ percent: 50 });\n document.getElementById(\"percent_animation_box\").style.left = \"163px\";\n } else if (num === 75) {\n this.setState({ percent: 75 });\n document.getElementById(\"percent_animation_box\").style.left = \"245px\";\n } else if (num === 100) {\n this.setState({ percent: 100 });\n document.getElementById(\"percent_animation_box\").style.left = \"328px\";\n }\n this.allocToSubTokenSize();\n ele.style.color = \"#fff\";\n }", "function updateShotsOffGoal()\n{\n totalShotsOff = T1.shotsOffGoal + T2.shotsOffGoal;\n\n var t1_bar = Math.floor((T1.shotsOffGoal / totalShotsOff) * 100);\n var t2_bar = 100 - t1_bar;\n\n document.querySelector(\".t1-shots-off-num\").innerHTML = \"<b>\" + T1.shotsOffGoal + \"</b>\";\n document.querySelector(\".t2-shots-off-num\").innerHTML = \"<b>\" + T2.shotsOffGoal + \"</b>\";\n\n var bar1 = document.getElementsByClassName(\"t1-shots-off-bar\")[0].style;\n var bar2 = document.getElementsByClassName(\"t2-shots-off-bar\")[0].style;\n\n updateBarColor(t1_bar, t2_bar, bar1, bar2);\n\n bar1.width = t1_bar.toString() + \"%\";\n bar2.width = t2_bar.toString() + \"%\";\n}", "function posBar(pos) {\n /* jshint validthis:true */\n if (this.bar) {\n $(this.bar).css(this.origin.pos, +pos + 'px');\n }\n }", "function updateElem_youGet(pos, value) {\n var sp = (value < 10) ? 4 : 2;\n\n elem_aboveSliderVal_youGet.innerHTML = Math.round(value);\n if (pos > 0) {\n elem_aboveSliderVal_youGet.style.left = pos + sp + \"px\";\n }\n elem_infoyougetval.innerHTML = Math.round(value);\n elem_youget_bar.style.width = Math.round(value) + \"px\";\n }", "function updateShotsOnGoal()\n{\n totalShotsOn = T1.shotsOnGoal + T2.shotsOnGoal;\n\n var t1_bar = Math.floor((T1.shotsOnGoal / totalShotsOn) * 100);\n var t2_bar = 100 - t1_bar;\n\n document.querySelector(\".t1-shots-on-num\").innerHTML = \"<b>\" + T1.shotsOnGoal + \"</b>\";\n document.querySelector(\".t2-shots-on-num\").innerHTML = \"<b>\" + T2.shotsOnGoal + \"</b>\";\n\n var bar1 = document.getElementsByClassName(\"t1-shots-on-bar\")[0].style;\n var bar2 = document.getElementsByClassName(\"t2-shots-on-bar\")[0].style;\n\n updateBarColor(t1_bar, t2_bar, bar1, bar2);\n\n bar1.width = t1_bar.toString() + \"%\";\n bar2.width = t2_bar.toString() + \"%\";\n}", "gasSpeedAnimation(speed, ele) {\n this.state.gasSpeedCosts.forEach((tab) => {\n tab.style.color = \"#8BAEC2\";\n });\n if (speed === \"slow\") {\n this.setState({ speed: \"slow\" });\n document.getElementById(\"gas_speed_box\").style.left = \"0px\";\n } else if (speed === \"medium\") {\n this.setState({ speed: \"medium\" });\n document.getElementById(\"gas_speed_box\").style.left = \"161px\";\n } else if (speed === \"fast\") {\n this.setState({ speed: \"fast\" });\n document.getElementById(\"gas_speed_box\").style.left = \"323px\";\n }\n ele.style.color = \"#fff\";\n }", "function mapProgressToSpeed(progress) {\n\tif (progress <= 0.5) return progress * 2;\n\telse if(progress <= 0.75) return (progress * 4) - 1;\n\telse return -1/((progress - 1) * 2)\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 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 changeSpeed(e) {\n const y = e.pageY - this.offsetTop;\n const percent = y / this.offsetHeight;\n const [max, min] = [4, 0.4];\n const playbackRate = (percent * (max - min) + min).toFixed(2);\n console.log(playbackRate);\n speedBar.style.height = `${Math.round(percent * 100)}%`;\n speedBar.textContent = `${playbackRate} ×`;\n video.playbackRate = playbackRate;\n}", "function xBar(dir, // direction, 'ltr', 'rtl', 'ttb', or 'btt'\r\n conStyle, barStyle) // container and bar style class names\r\n{\r\n //// Public Properties\r\n\r\n this.value = 0; // current value, read-only\r\n\r\n //// Public Methods\r\n\r\n // Update current value\r\n this.update = function(v)\r\n {\r\n if (v < 0) v = 0;\r\n else if (v > this.inMax) v = this.inMax;\r\n this.con.title = this.bar.title = this.value = v;\r\n switch(this.dir) {\r\n case 'ltr': // left to right\r\n v = this.scale(v, this.w);\r\n xLeft(this.bar, v - this.w);\r\n break;\r\n case 'rtl': // right to left\r\n v = this.scale(v, this.w);\r\n xLeft(this.bar, this.w - v);\r\n break;\r\n case 'btt': // bottom to top\r\n v = this.scale(v, this.h);\r\n xTop(this.bar, this.h - v);\r\n break;\r\n case 'ttb': // top to bottom\r\n v = this.scale(v, this.h);\r\n xTop(this.bar, v - this.h);\r\n break;\r\n }\r\n };\r\n\r\n // Change position and/or size\r\n this.paint = function(x, y, // container position\r\n w, h) // container size\r\n {\r\n if (xNum(x)) this.x = x;\r\n if (xNum(y)) this.y = y;\r\n if (xNum(w)) this.w = w;\r\n if (xNum(h)) this.h = h;\r\n xResizeTo(this.con, this.w, this.h);\r\n xMoveTo(this.con, this.x, this.y);\r\n xResizeTo(this.bar, this.w, this.h);\r\n xMoveTo(this.bar, 0, 0);\r\n };\r\n\r\n // Change scale and/or start value\r\n this.reset = function(max, start) // non-scaled values\r\n {\r\n if (xNum(max)) this.inMax = max;\r\n if (xNum(start)) this.start = start;\r\n this.update(this.start);\r\n };\r\n\r\n //// Private Methods\r\n \r\n this.scale = function(v, outMax)\r\n {\r\n return Math.round(xLinearScale(v, 0, this.inMax, 0, outMax));\r\n };\r\n\r\n //// Private Properties\r\n\r\n this.dir = dir;\r\n this.x = 0;\r\n this.y = 0;\r\n this.w = 100;\r\n this.h = 100;\r\n this.inMax = 100;\r\n this.start = 0;\r\n this.conStyle = conStyle;\r\n this.barStyle = barStyle;\r\n\r\n //// Constructor\r\n\r\n // Create container\r\n this.con = document.createElement('DIV');\r\n this.con.className = this.conStyle;\r\n // Create bar\r\n this.bar = document.createElement('DIV');\r\n this.bar.className = this.barStyle;\r\n // Insert in object tree\r\n this.con.appendChild(this.bar);\r\n document.body.appendChild(this.con);\r\n\r\n} // end xBar", "function changePos(pos, speed) {\n var time = speed?speed+'ms':'';\n\n scrollerBlock.style.webkitTransitionDuration =\n scrollerBlock.style.MozTransitionDuration =\n scrollerBlock.style.msTransitionDuration =\n scrollerBlock.style.OTransitionDuration =\n scrollerBlock.style.transitionDuration = time;\n\n setPos(Math.floor(pos));\n }", "function OnGUI(){ // set the speedometer top-left corner var pos = Vector2(Screen.width - 90, Screen.height - 50); // get the speed in mph: var mph = rigidbody.velocity.magnitude * 2.237; // draw the bars: each bar means 5 mph, no bar if speed < 1: for (var v: float = 1;\n }", "function updatebar(){\r\n \tif (width > 168){\r\n \t\tif (width < 220){\r\n \t\t\ttakeoff = 21\r\n \t\t\twidth = width - takeoff\r\n }else if (width < 350){\r\n takeoff = 42\r\n width = width - takeoff\r\n }else if (width < 400){\r\n \ttakeoff = 80\r\n \twidth = width - takeoff\r\n }else if (width < 500){\r\n \ttakeoff = 140\r\n \twidth = width - takeoff\r\n \r\n }\r\n document.getElementById('barcum').style.width = width + 'px'\r\n \t}else if (width < 168){\r\n \t\twidth = 168\r\n \t\tdocument.getElementById('barcum').style.width = width + 'px'\r\n \t\r\n\r\n }}", "percentageBar (score) {\n var styles = {\n height: '5px',\n backgroundColor: 'black',\n borderRadius: '15px'\n };\n styles.width = (score / 5 * 100) + '%';\n return styles;\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 }", "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}", "animationHelper(animations, speedF) {\n const arrayBars = document.getElementsByClassName(\"array-bar\");\n\n this.postAnimation(animations.length, speedF);\n\n for (let i = 0; i < animations.length; i++) {\n const [barOneIndex, barTwoIndex] = animations[i];\n const barOneStyle = arrayBars[barOneIndex].style;\n const barTwoStyle = arrayBars[barTwoIndex].style;\n if (i % 2 === 0) {\n setTimeout(() => {\n animations.pop();\n barOneStyle.backgroundColor = \"yellowgreen\";\n barTwoStyle.backgroundColor = \"yellowgreen\";\n let tempHeight = barOneStyle.height;\n barOneStyle.height = barTwoStyle.height;\n barTwoStyle.height = tempHeight;\n }, (i + 1) * speedF);\n }\n else {\n setTimeout(() => {\n animations.pop();\n barOneStyle.backgroundColor = \"#20232a\";\n barTwoStyle.backgroundColor = \"#20232a\";\n }, (i + 1) * speedF);\n }\n }\n }", "function setBar (value) {\n return fill.style.width = `${(value/max)*100}%`\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 }", "function refresh_box() {\r\n bar_w = container.offsetWidth;\r\n speed_box.style.left = Math.round(((bar_w - 14) * (speed_slider.value) / 60) - 21, 0) + 'px';\r\n set_speed();\r\n}", "function updateOffsides()\n{\n totalOffsides = T1.offsides + T2.offsides;\n\n var t1_bar = Math.floor((T1.offsides / totalOffsides) * 100);\n var t2_bar = 100 - t1_bar;\n\n document.querySelector(\".t1-off-num\").innerHTML = \"<b>\" + T1.offsides + \"</b>\";\n document.querySelector(\".t2-off-num\").innerHTML = \"<b>\" + T2.offsides + \"</b>\";\n\n var bar1 = document.getElementsByClassName(\"t1-off-bar\")[0].style;\n var bar2 = document.getElementsByClassName(\"t2-off-bar\")[0].style;\n\n updateBarColor(t1_bar, t2_bar, bar1, bar2);\n\n bar1.width = t1_bar.toString() + \"%\";\n bar2.width = t2_bar.toString() + \"%\";\n}", "animateProgressBar() {\n const\n cardLen = this.props.cards.length, // get cardsLength\n current = this.state.current, // get current\n calcPer = (lg, sm) => lg && sm ? (sm / lg) * 100 : 0, // create func that return precentage\n currPer = calcPer(cardLen, current), // current percentage\n nextPer = calcPer(cardLen, current + 1), // percentage of the next step\n progres = document.getElementById(\"run-test__progress\"), // the progress bar element\n oneStep = (nextPer - currPer) / 10; // the amount progress bar goes in one step (10 step anim)\n\n let counter = 0,\n currWidth = currPer;\n\n // create a timer for progressbar width grow\n const progressTimer = setInterval(() => {\n currWidth += oneStep; // increase width by 1 unit\n\n progres.style.width = currWidth + \"%\"; // set width\n\n if (++counter === 9) clearInterval(progressTimer); // increment and clear \n }, 150); // end of progressTimer\n }", "setStyles(){\n let style ; \n let fxDur = this.props.fxDuration+\"s\"\n\n if(this.state.isActive){\n style = {\n position: 'fixed',\n width: '100%',\n zIndex: '9999',\n animationDuration: fxDur,\n animationFillMode: 'both',\n left: '0'\n }\n // According to props \"position\", we add style.top or style.bottom\n this.props.position === 'top' ? style.top = '0' : style.bottom = '0'\n\n\n }\n return style;\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 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 movePlayerBar(){\n\t\t\tvar position=texture.getPosition();\n\t\t\tvar y1=position.y;\n\t\t\tvar y2=position.y+size.height;\n\t\t\tvar y1_aux=(dir!=1?y1+speed:y1-speed);\n\t\t\tvar y2_aux=(dir!=1?y2+speed:y2-speed);\n\t\t\t\n\t\t\t//Comprobamos que la bola no rebasaria los limites verticales\n\t\t\tif(y1_aux<y_min || y2_aux>y_max){\n\t\t\t\ty1_aux=(y1_aux<y_min)?y_min:y_max-size.height;\n\t\t\t\tstopMove(dir);\n\t\t\t}\n\t\t\ttexture.move(x,y1_aux);\n\t\t\ttexture.fireOnChangeEvent();\n\t\t}", "function animate_bars(elementList) {\r\n elementList.forEach(element => {\r\n let distance_to_top = element.getBoundingClientRect().top;\r\n let scrht = window.innerHeight;\r\n let id = element.id;\r\n\r\n if (distance_to_top < scrht) {\r\n element.style.width = `${vals[id]}%`;\r\n }\r\n else\r\n element.style.width = `${0}%`;\r\n });\r\n}", "function updateBlockedShots()\n{\n totalBlock = T1.blockedShots + T2.blockedShots;\n\n var t1_bar = Math.floor((T1.blockedShots / totalBlock) * 100);\n var t2_bar = 100 - t1_bar;\n\n document.querySelector(\".t1-block-shot-num\").innerHTML = \"<b>\" + T1.blockedShots + \"</b>\";\n document.querySelector(\".t2-block-shot-num\").innerHTML = \"<b>\" + T2.blockedShots + \"</b>\";\n\n var bar1 = document.getElementsByClassName(\"t1-block-shot-bar\")[0].style;\n var bar2 = document.getElementsByClassName(\"t2-block-shot-bar\")[0].style;\n\n updateBarColor(t1_bar, t2_bar, bar1, bar2);\n\n bar1.width = t1_bar.toString() + \"%\";\n bar2.width = t2_bar.toString() + \"%\";\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 updateHealthbar() {\n let redPos = redBar.components.position;\n redPos.width = (health - currHealth) / health * redPos.height * 4;\n\n let greenPos = greenBar.components.position;\n greenPos.width = greenPos.height * 4 - redPos.width;\n }", "function init_progressBar(duration) {\n $('.progress').each(function() {\n var value = $(this).find('.progress__bar').attr('data-level');\n var result = value + '%';\n if(duration) {\n $(this).find('.progress__current').animate({width : value + '%'}, duration);\n }\n else {\n $(this).find('.progress__current').css({'width' : value + '%'});\n }\n \n });\n }", "function updateGoalAttempts()\n{\n totalGoalAttempts = T1.totalShots + T2.totalShots;\n\n var t1_bar = Math.floor((T1.totalShots / totalGoalAttempts) * 100);\n var t2_bar = 100 - t1_bar;\n\n document.querySelector(\".t1-goal-att-num\").innerHTML = \"<b>\" + T1.totalShots + \"</b>\";\n document.querySelector(\".t2-goal-att-num\").innerHTML = \"<b>\" + T2.totalShots + \"</b>\";\n\n var bar1 = document.getElementsByClassName(\"t1-goal-att-bar\")[0].style;\n var bar2 = document.getElementsByClassName(\"t2-goal-att-bar\")[0].style;\n\n updateBarColor(t1_bar, t2_bar, bar1, bar2);\n\n bar1.width = t1_bar.toString() + \"%\";\n bar2.width = t2_bar.toString() + \"%\";\n}", "function updateThrows()\n{\n totalThrows = T1.throwIns + T2.throwIns;\n\n var t1_bar = Math.floor((T1.throwIns / totalThrows) * 100);\n var t2_bar = 100 - t1_bar;\n\n document.querySelector(\".t1-throws-num\").innerHTML = \"<b>\" + T1.throwIns + \"</b>\";\n document.querySelector(\".t2-throws-num\").innerHTML = \"<b>\" + T2.throwIns + \"</b>\";\n\n var bar1 = document.getElementsByClassName(\"t1-throws-bar\")[0].style;\n var bar2 = document.getElementsByClassName(\"t2-throws-bar\")[0].style;\n\n updateBarColor(t1_bar, t2_bar, bar1, bar2);\n\n bar1.width = t1_bar.toString() + \"%\";\n bar2.width = t2_bar.toString() + \"%\";\n}", "function Pssbar(pr) {\n elem.style.width = pr + '%';\n elem.innerHTML = pr * 1 + '%';\n}", "function updateBar() {\n\n // total points left in game\n let pointsAvailable = score + updateRemaining();\n\n let winningScore = (pointsAvailable%2 === 0) ?\n (pointsAvailable/2)+1 :\n Math.ceil(pointsAvailable/2);\n\n let pointsUntilWin = winningScore - score;\n let winningPosition = winningScore/maxPoints*100;\n\n //update CSS with new values:\n\n pointsBar.style.width = `${score/maxPoints*100}%`;\n remainingBar.style.width = `${updateRemaining()/maxPoints*100}%`;\n pointer.style.marginLeft = `${winningPosition}%`;\n\n untilWin.innerText = (pointsUntilWin > 0) ?\n `win in ${pointsUntilWin} points` :\n `win achieved`;\n\n if (pointsUntilWin < 0){\n untilWin.style.color = \"white\";\n }\n\n}", "makeBar() {\r\n const percentage = this.timeLeft / this.MAX_TIME;\r\n const progress = Math.round((this.BAR_SIZE * percentage));\r\n const emptyProgress = this.BAR_SIZE - progress;\r\n const progressText = '▇'.repeat(progress);\r\n const emptyProgressText = ' '.repeat(emptyProgress);\r\n const bar = '```' + this.DISP_TEXT + '\\n' + progressText + emptyProgressText + '```';\r\n return bar;\r\n }", "function updateFoulsReceived()\n{\n totalFoulsRec = T1.foulsOn + T2.foulsOn;\n\n var t1_bar = Math.floor((T1.foulsOn / totalFoulsRec) * 100);\n var t2_bar = 100 - t1_bar;\n\n document.querySelector(\".t1-foul-rec-num\").innerHTML = \"<b>\" + T1.foulsOn + \"</b>\";\n document.querySelector(\".t2-foul-rec-num\").innerHTML = \"<b>\" + T2.foulsOn + \"</b>\";\n\n var bar1 = document.getElementsByClassName(\"t1-foul-rec-bar\")[0].style;\n var bar2 = document.getElementsByClassName(\"t2-foul-rec-bar\")[0].style;\n\n updateBarColor(t1_bar, t2_bar, bar1, bar2);\n\n bar1.width = t1_bar.toString() + \"%\";\n bar2.width = t2_bar.toString() + \"%\";\n}", "setBar(val){\n\t\tthis.status = val;\n\t\tthis.clampScale();\n\t\tthis.blueBar.scale.setTo(this.status, .617);\n\t}", "function initProgressBars() {\n if ($('.fantom-progress').length > 0) {\n $('.fantom-progress').each(function() {\n var $this = $(this);\n $this.appear(function() {\n var $percentage = $this.find('.progress-bar').data('precentage');\n $this.find('.progress-bar').animate({\n 'width': $percentage + '%'\n }, {\n duration: 1000,\n easing: 'swing',\n }), 'slow';\n $this.find('.progress-value').countTo({\n from: 0,\n to: $percentage,\n speed: 1300,\n refreshInterval: 50\n })\n }, {\n accX: 0,\n accY: -100\n })\n })\n };\n}", "function barXFunc (d, i) { return (i * barwidth)+\"%\" ; }", "function barUpdate() {\n\t// changes the color of the background depending on the percent\n\tif (Math.abs(($bar.width()/$statusBar.width()) - percentCorrect) == 100 ) {\n\t\tcolorChange(2000);\n\t\t}\n\telse if (Math.abs(($bar.width()/$statusBar.width()) - percentCorrect) >= 30) {\n\t\tcolorChange(1500);\n\t\t}\n\telse {\n\t\tcolorChange(900);\n\t};\n}", "function buildPercBars() {\n\n\treturn [\n\t {value: .45, index: .5, init:0},\n\t\t{value: .23, index: .4, init:0},\n\t];\n\t\n}", "function setAnimationSpeedFactor(speed){\n if (speed >= 0.5 && speed <= 2){\n speedFactor = speed;\n }\n // Speed range to be within 0.5 to 2\n // Just a precaution\n else{\n console.log(\"Please set speed within 0.5 and 2\");\n }\n}", "function handleMove(e) {\r\n const y = e.pageY - this.offsetTop; //showing where we are when we hover over the bar\r\n const percent = y / this.offsetHeight;\r\n const min = 0.4;\r\n const max = 4;\r\n const height = Math.round(percent * 100) + '%'; //turning it into percentage\r\n const playbackRate = percent * (max - min) + min;\r\n bar.style.height = height; //styling the bar -> showing where we are when we hover over the bar\r\n bar.textContent = playbackRate.toFixed(2) + '×'; //update the number that is inside of the bar as 0.00x\r\n video.playbackRate = playbackRate; //applying value to the video\r\n}", "function animateBars() {\n\n\tuserRegisteredAmount();\n\tAmountofAdv();\n\t\n\tuserProgressBar();\n\tretailerProgressBar();\n\tadsProgressBar();\n\t\n}", "function specialBar(bar, count) {\n if (count === 1) {\n bar.setAttribute(\"style\", \"width: 33%\");\n } else if (count === 2) {\n bar.setAttribute(\"style\", \"width: 66%\");\n } else if (count === 3) {\n bar.setAttribute(\"style\", \"width: 100%\");\n bar.className += \" glow\";\n } else if (count === 0) {\n bar.setAttribute(\"style\", \"width: 0%\");\n bar.classList.remove(\"glow\");\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 }", "_setWrapperPosition() {\n this.wrapper.style.left = this.percentPosition.x + '%';\n this.wrapper.style.top = this.percentPosition.y + '%';\n }", "function toBarPerc(n) {\n\t return (-1 + n) * 100;\n\t }", "function toBarPerc(n) {\n\t return (-1 + n) * 100;\n\t }", "function toBarPerc(n) {\n\t return (-1 + n) * 100;\n\t }", "function toBarPerc(n) {\n\t return (-1 + n) * 100;\n\t }", "function moveBar() {\n var width = 1;\n var padding = 0;\n var id = setInterval(frame, 30);\n function frame() {\n if (width >= 100) {\n clearInterval(id);\n increaseGold();\n loadingTab.style.display = \"none\";\n loadingTabShip.style.display = \"none\";\n } else {\n width += Math.random();\n padding += 6;\n loadingAmount.style.width = width + '%';\n loadingAmountShip.style.paddingLeft = padding.toString() + 'px';\n }\n }\n}", "function progress($element) {\n \t$this=$element;\n \tprWidth = $(this).data(\"value\")* $element.width() / 100;\n \t$this.find('.bar_filling').each(function(){\n \t\tvar progressBarVal = $(this).find('.bar_value').data('value');\n \t\t$(this).find('.bar_value').text(progressBarVal + \"% \");\n\n \t\tvar progressBarWidth = progressBarVal*$element.width()/100;\n \t\t$(this).animate({ width: progressBarWidth }, progressBarWidth*5); /* change 'progressBarWidth*5' to 2500 (for example) if we want constant speed */ \n \t}) \t\n }", "function updateFoulsCommited()\n{\n totalFoulsComm = T1.foulsBy + T2.foulsBy;\n\n var t1_bar = Math.floor((T1.foulsBy / totalFoulsComm) * 100);\n var t2_bar = 100 - t1_bar;\n\n document.querySelector(\".t1-foul-comm-num\").innerHTML = \"<b>\" + T1.foulsBy + \"</b>\";\n document.querySelector(\".t2-foul-comm-num\").innerHTML = \"<b>\" + T2.foulsBy + \"</b>\";\n\n var bar1 = document.getElementsByClassName(\"t1-foul-comm-bar\")[0].style;\n var bar2 = document.getElementsByClassName(\"t2-foul-comm-bar\")[0].style;\n\n updateBarColor(t1_bar, t2_bar, bar1, bar2);\n\n bar1.width = t1_bar.toString() + \"%\";\n bar2.width = t2_bar.toString() + \"%\";\n}" ]
[ "0.84420997", "0.84033936", "0.83595365", "0.8358633", "0.8358633", "0.8349349", "0.8310954", "0.8310954", "0.65682817", "0.6027478", "0.5938657", "0.59359753", "0.59084064", "0.5865465", "0.57943", "0.5786332", "0.57675296", "0.5726657", "0.5726514", "0.5720939", "0.5716786", "0.5682546", "0.56754607", "0.56733596", "0.5655682", "0.56529295", "0.5638212", "0.5616963", "0.56044006", "0.55862963", "0.5573614", "0.55726534", "0.55719614", "0.55652213", "0.55427027", "0.55341756", "0.55313265", "0.5531293", "0.55247813", "0.5519482", "0.55192417", "0.5507906", "0.5505508", "0.54962385", "0.5484972", "0.5484438", "0.54812413", "0.5469221", "0.54467094", "0.54409975", "0.54381335", "0.5435778", "0.5433735", "0.54314137", "0.5424513", "0.54235035", "0.54095197", "0.5396937", "0.5388268", "0.5388268", "0.5388268", "0.5388268", "0.5387994", "0.53864527", "0.53816205" ]
0.83148575
38
(Internal) Determines if an element or space separated list of class names contains a class name.
function hasClass(element, name) { var list = typeof element == 'string' ? element : classList(element); return list.indexOf(' ' + name + ' ') >= 0; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function hasClass(element, name) {\n\t var list = typeof element == 'string' ? element : classList(element);\n\t return list.indexOf(' ' + name + ' ') >= 0;\n\t }", "function hasClass(element, name) {\n\t var list = typeof element == 'string' ? element : classList(element);\n\t return list.indexOf(' ' + name + ' ') >= 0;\n\t }", "function hasClass(element, name) {\n\t var list = typeof element == 'string' ? element : classList(element);\n\t return list.indexOf(' ' + name + ' ') >= 0;\n\t }", "function hasClass(element, name) {\n\t var list = typeof element == 'string' ? element : classList(element);\n\t return list.indexOf(' ' + name + ' ') >= 0;\n\t }", "function hasClass(element, name) {\n var list = typeof element == 'string' ? element : classList(element);\n return list.indexOf(' ' + name + ' ') >= 0;\n }", "function hasClass(element, name) {\n var list = typeof element == 'string' ? element : classList(element);\n return list.indexOf(' ' + name + ' ') >= 0;\n }", "function hasClass(element, name) {\n var list = typeof element == 'string' ? element : classList(element);\n return list.indexOf(' ' + name + ' ') >= 0;\n }", "function classContains(element, name) {\n var names, i,\n className = element.className;\n if (className === '' || className === null || className === undefined) {\n return false;\n }\n names = className.split(/\\s+/);\n for (i = names.length-1; i >= 0; --i) {\n if (names[i] === name) {\n return true;\n }\n }\n return false;\n }", "function hasClass( ele, class_name ) {\n\treturn ele.className.match( new RegExp( '(\\\\s|^)' + class_name + '(\\\\s|$)' ) );\n}", "function hasClass(element, clas)\n{\n return (' ' + element.className + ' ').indexOf(' ' + clas + ' ') > -1;\n}", "function class_exists(ele,className){return new RegExp(' '+className+' ').test(' '+ele.className+' ');}", "function hasClass(element, className)\n{\n\treturn element.className.split(' ').indexOf(className);\n}", "function classCheck(element, classesToCheck) {\n\t\tvar newClasses = classesToCheck.replace(/\\s+/g,'').split(\",\");\n\t\tvar currentClasses = element.className.trim().replace(/\\s+/g,' ') + ' ';\n\t\tvar ind = newClasses.length;\n\t\tvar hasClass = true;\n\n while(ind--) {\n\t\t\tvar testTerm = new RegExp(newClasses[ind] +' ');\n if (!testTerm.test(currentClasses)) {\n hasClass = false;\n break;\n } \n \t\t}\n \t\treturn hasClass;\n \t}", "function verifyIsClass(element, nameOfClass){\n if(element != null){\n if(element.attr('class').indexOf(nameOfClass) == -1){\n return false;\n }else{\n return true;\n }\n }\n\n}", "function hasClass(elem, className) {\n return new RegExp(' ' + className + ' ').test(' ' + elem.className + ' ');\n }", "function hasClass(elem, className) {\n return new RegExp(' ' + className + ' ').test(' ' + elem.className + ' ')\n}", "function hasClass(elem, className) {\n return new RegExp(' ' + className + ' ').test(' ' + elem.className + ' ');\n }", "function hasClass(elem, className) {\r\n\treturn new RegExp(' ' + className + ' ').test(' ' + elem.className + ' ');\r\n}", "function conteClass(element, nomClass) {\n return (' ' + element.classList + ' ').indexOf(' ' + nomClass + ' ') > -1;\n }", "function hasClass(elem, className) {\n\treturn new RegExp(' ' + className + ' ').test(' ' + elem.className + ' ');\n}", "function hasClass(elem, className) {\n\treturn new RegExp(' ' + className + ' ').test(' ' + elem.className + ' ');\n}", "function hasClass(elem, className) {\n\treturn new RegExp(' ' + className + ' ').test(' ' + elem.className + ' ');\n}", "function hasClass(element, cls) {\n var classes = element.className;\n if (!classes) return false;\n var l = classes.split(' ');\n for (var i = 0; i < l.length; i++) {\n if (l[i] == cls) {\n return true;\n }\n }\n return false;\n}", "function hasClass(element, className) {\n return (' ' + element.className + ' ').indexOf(' ' + className + ' ') > -1;\n}", "function hasClassName(el, name)\r\n{\r\n\tvar list = el.className.split(\" \");\r\n\tfor (var i = 0; i < list.length; i++)\r\n\t\tif (list[i] == name)\r\n\t\t\treturn true;\r\n\r\n\treturn false;\r\n}", "function hasClass(element, className){\n var classes = element.className;\n return classes && new RegExp(\"(^| )\" + className + \"($| )\").test(classes);\n}", "function has_class(o, cn) {\n var parts = o.className.split(' ');\n for (x=0; x<parts.length; x++) {\n if (parts[x] == cn)\n return true;\n }\n return false;\n}", "function hasClass (elem, cls) {\n\tvar str = \" \" + elem.className + \" \";\n\tvar testCls = \" \" + cls + \" \";\n\treturn (str.indexOf(testCls) != -1);\n}", "function hasClass(elem, className) {\n return elem.className && new RegExp(\"(^|\\\\s)\" + className + \"(\\\\s|$)\").test(elem.className);\n}", "function hasClass(element, cls) {\n return (' ' + element.className + ' ').indexOf(' ' + cls + ' ') > -1;\n}", "function hasClass(element, cls) {\n return (' ' + element.className + ' ').indexOf(' ' + cls + ' ') > -1;\n}", "function hasClass(element, cls) {\n return (' ' + element.className + ' ').indexOf(' ' + cls + ' ') > -1;\n}", "async hasClass(name) {\n await this._stabilize();\n const classes = (await this.getAttribute('class')) || '';\n return new Set(classes.split(/\\s+/).filter(c => c)).has(name);\n }", "hasClass(ele, str) {\n return ele.className.trim().split(/ +/).indexOf(str) >= 0;\n }", "function HasClassName(element, className) {\n\tif (typeof element == 'string') element = $(element);\n\tvar elementClassName = element.className;\n\tif (typeof elementClassName == 'undefined') return false;\n\treturn (elementClassName.length > 0 && (elementClassName == className || new RegExp(\"(^|\\\\s)\" + className + \"(\\\\s|$)\").test(elementClassName)));\n}", "function hasClass(element, cls) {\n\treturn (' ' + element.className + ' ').indexOf(' ' + cls + ' ') > -1;\n}", "function hasClass(el, c) {\r\n return el.classList ?\r\n el.classList.contains(c) :\r\n (el.className.split(\" \").indexOf(c) != -1);\r\n }", "function hasClass(elem, cls) {\n // adapted from http://stackoverflow.com/a/5085587/233608\n return (\" \" + elem.className + \" \").replace(/[\\n\\t]/g, \" \").indexOf(\" \" + cls + \" \") > -1;\n}", "function hasClass(element, cls) {\n\t\treturn (' ' + element.className + ' ').indexOf(' ' + cls + ' ') > -1;\n\t}", "function hasClass(ele,cls) {\n return ele.className.match(new RegExp('(\\\\s|^)'+cls+'(\\\\s|$)'));\n}", "function hasClass(node, name) {\n return classRegex(name).test(node.className);\n }", "function hasClass(element, cls) {\n return (' ' + element.className + ' ').indexOf(' ' + cls + ' ') > -1;\n }", "function hasClass(element, cls) {\n return (' ' + element.className + ' ').indexOf(' ' + cls + ' ') > -1;\n }", "function hasClass(elm, cls) {\n var classes = elm.className.split(' ');\n for (var i = 0; i < classes.length; i++) {\n if (classes[i].toLowerCase() === cls.toLowerCase()) {\n return true;\n }\n }\n return false;\n}", "function hasClass( elem, klass ) {\n\t\t\t return (\" \" + elem.className + \" \" ).indexOf( \" \"+klass+\" \" ) > -1;\n\t\t\t}", "function hasClass(ele, cls) {\n return ele.className.match(new RegExp('(\\\\s|^)' + cls + '(\\\\s|$)'));\n }", "function hasClass(element, className) {\n return classMatchingRegex(className).test(element.className);\n}", "function hasClass(elm, cls) {\n\t var classes = elm.className.split(' ');\n\t for (var i = 0; i < classes.length; i++) {\n\t if (classes[i].toLowerCase() === cls.toLowerCase()) {\n\t return true;\n\t }\n\t }\n\t return false;\n\t}", "function hasClass(ele,cls) {\n\treturn ele.className.match(new RegExp('(\\\\s|^)'+cls+'(\\\\s|$)'));\n}", "function hasClass(element, cls) {\n return !!element.className.match(new RegExp('(\\\\s|^)' + cls + '(\\\\s|)'));\n }", "function hasClass(element, cls) {\n return element.classList.contains(cls);\n}", "function hasCssClass(el, name) {\n var classes = el.className.split(/\\s+/g);\n return classes.indexOf(name) !== -1;\n }", "function hasClass(ele, cls) {\n if(ele) return ele.className.match(new RegExp('(\\\\s|^)'+cls+'(\\\\s|$)'));\n }", "function hasClass(el, classname) {\n return el && el.getAttribute('class') && el.getAttribute('class').indexOf(classname) > -1;\n }", "function hasClass(el, classname) {\n return el && el.getAttribute('class') && el.getAttribute('class').indexOf(classname) > -1;\n }", "function hasClass(element, className) {\n return element.classList.contains(className);\n }", "function hasClass(className) {\n var i, val;\n for(i = 0;i < this.length;i++) {\n val = this.get(i).getAttribute(attr);\n val = val ? val.split(/\\s+/) : [];\n if(~val.indexOf(className)) {\n return true;\n }\n }\n return false;\n}", "function hasClass(css_class, element) {\r\n checkParams(css_class, element, 'hasClass');\r\n var className = ' ' + css_class + ' ';\r\n return ((' ' + element.className + ' ').replace(rclass, ' ').indexOf(className) > -1);\r\n }", "function hasClass(className) {\n var callback = function(element) {\n return element.classList.contains(className);\n }\n\n return $.some(this.elements, callback);\n }", "function hasClass(ele,cls) {\n return !!ele.className.match(new RegExp('(\\\\s|^)'+cls+'(\\\\s|$)'));\n}", "function hasClass(target, cName) {\n var regex = new RegExp(\"(?:^|\\\\s)\" + cName + \"(?!\\\\S)\");\n return target.className.match(regex);\n }", "function hasClass(element, className) {\n if (element.classList) return !!className && element.classList.contains(className);\n return (\" \" + (element.className.baseVal || element.className) + \" \").indexOf(\" \" + className + \" \") !== -1;\n}", "function hasCssClass(el, name)\n {\n var classes = el.className.split(/\\s+/g);\n return classes.indexOf(name) !== -1;\n }", "function hasClass(el, name) {\n\tif(el)\n\t\treturn new RegExp(name).test(el.className);\n\n\treturn false;\n}", "function hasClass(e,clazz) {\n\t if(e.className==null)\n\t return false;\n\t \n\t var list = e.className.split(/\\s+/);\n\t for( var i=0; i<list.length; i++ ) {\n\t if(list[i]==clazz) return true;\n\t }\n\t return false;\n\t }", "function uuklasshas(node, // @param Node:\r\n classNames) { // @param String: \"class1 class2 ...\" (joint space)\r\n // @return Boolean:\r\n var m, ary, cn = node.className;\r\n\r\n if (!classNames || !cn) {\r\n return false;\r\n }\r\n if (classNames.indexOf(\" \") < 0) {\r\n return (\" \" + cn + \" \").indexOf(\" \" + classNames + \" \") >= 0; // single\r\n }\r\n ary = uusplit(classNames); // multi\r\n m = cn.match(_classNameMatcher(ary));\r\n return m && m.length >= ary.length;\r\n}" ]
[ "0.83630496", "0.83630496", "0.83630496", "0.83630496", "0.83361906", "0.83361906", "0.83361906", "0.81867284", "0.8118611", "0.8019984", "0.80107343", "0.79360753", "0.7923158", "0.7831756", "0.7820544", "0.7813132", "0.78125554", "0.7802387", "0.77726287", "0.77571684", "0.77571684", "0.77571684", "0.77297807", "0.7715519", "0.7696343", "0.76301193", "0.76114225", "0.7575704", "0.75515056", "0.7547158", "0.7547158", "0.7547158", "0.75319546", "0.7515763", "0.75108683", "0.7503705", "0.74793285", "0.74691397", "0.7461369", "0.74613374", "0.74556357", "0.7432772", "0.7432772", "0.7430021", "0.74229145", "0.74094766", "0.7401127", "0.7400129", "0.7379086", "0.73630923", "0.73525345", "0.73437595", "0.7321652", "0.7301773", "0.7289791", "0.728715", "0.727134", "0.7264198", "0.7251425", "0.7241821", "0.7213814", "0.7203535", "0.7201961", "0.71995556", "0.7196371", "0.71593904" ]
0.83775866
30
(Internal) Adds a class to an element.
function addClass(element, name) { var oldList = classList(element), newList = oldList + name; if (hasClass(oldList, name)) return; // Trim the opening space. element.className = newList.substring(1); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function addClass(element, classname) {\n\tvar classes = getClassList(element);\n\tif (indexOf(classname, classes) < 0) {\n\t\tclasses[classes.length] = classname;\n\t\tsetClassList(element,classes);\n\t}\n}", "function addClass (element, classname) {\n if (element.classList) {\n element.classList.add(classname);\n } else {\n element.className += ' ' + classname;\n }\n }", "function addClass(element, cls) {\n element.classList.add(cls);\n}", "function addingClass(element, addedClass) {\n element.classList.add(addedClass);\n }", "function addClass(element, clas)\n{\n if (! hasClass(element, clas))\n element.className += ' ' + clas;\n}", "function _addClass(element, className) {\n var classes;\n classes = element.className.split(' ');\n\n if (classes.indexOf(className) === -1) {\n classes.push(className);\n element.className = classes.join(' ').trim();\n }\n }", "function addClass(element, className) {\n var classes = element.className.split(' ');\n if (classes.indexOf(className) == -1) {\n classes.push(className);\n }\n element.className = classes.join(' ');\n }", "function addClass(element, cls) {\n element.className +=cls+' ';\n}", "setClass(el, classname) {\n el.className += ' ' + classname;\n }", "function addClassToElement(element, className) {\n element.classList.add(className);\n}", "function addClass(element, newClass) {\n element.classList.add(newClass);\n}", "function addClass(element, newClass)\n {\n \telement.className = element.className + \" \" + newClass;\n }", "function addClass(el,cls){/* istanbul ignore if */if(!cls||!cls.trim()){return;}/* istanbul ignore else */if(el.classList){if(cls.indexOf(' ')>-1){cls.split(/\\s+/).forEach(function(c){return el.classList.add(c);});}else{el.classList.add(cls);}}else{var cur=' '+el.getAttribute('class')+' ';if(cur.indexOf(' '+cls+' ')<0){el.setAttribute('class',(cur+cls).trim());}}}", "function addClass(el,cls){/* istanbul ignore if */if(!cls||!(cls=cls.trim())){return;}/* istanbul ignore else */if(el.classList){if(cls.indexOf(' ')>-1){cls.split(/\\s+/).forEach(function(c){return el.classList.add(c);});}else{el.classList.add(cls);}}else{var cur=\" \"+(el.getAttribute('class')||'')+\" \";if(cur.indexOf(' '+cls+' ')<0){el.setAttribute('class',(cur+cls).trim());}}}", "function addClass(el,cls){/* istanbul ignore if */if(!cls||!(cls=cls.trim())){return;}/* istanbul ignore else */if(el.classList){if(cls.indexOf(' ')>-1){cls.split(/\\s+/).forEach(function(c){return el.classList.add(c);});}else{el.classList.add(cls);}}else{var cur=\" \"+(el.getAttribute('class')||'')+\" \";if(cur.indexOf(' '+cls+' ')<0){el.setAttribute('class',(cur+cls).trim());}}}", "function addClass(element, cls) {\n if (hasClass(element, cls))\n return;\n var old_cls = element.className;\n if (old_cls) cls = cls + ' ' + old_cls;\n element.className = cls;\n}", "function addClass(element,newClassName)\n{\n var oldClassName = element.className;\n element.className = oldClassName === \"\" ? newClassName:oldClassName + \" \" + newClassName;\n}", "function elementAddClass(className, selector) {\n$(selector).addClass(className);\n}", "function addClass(element, className) {\n if (hasClass(element, className)) return; // Element already has the class - so do not add it\n element.className = element.className === \"\" ? className : element.className + \" \" + className;\n}", "function classAdd(element, name) {\n var className;\n if (classContains(element, name)) {\n return;\n }\n className = element.className;\n if (className === '' || className === null || className === undefined) {\n element.className = name;\n } else {\n element.className = className + ' ' + name;\n }\n }", "function addClass(elem, className) {\r\n elem.addClass(className);\r\n }", "function addClass(_class, _element) {\n\t// variables\n\tvar className = \"\", // string to hold className to add\n\t\t\tclassExists = false; // boolean to check if the class already exists\n\tvar classes = _element.className.split(\" \");\n\n\n\tif (classes[0] === \"\") { /* element has no classes. add class name */ }\n\telse {\n\t\t/* element has existing classes */\n\t\tclassName += \" \"; // for appropriate spacing\n\t\t/* check if the class already exists */\n\t\tfor (var i = 0; i < classes.length; i++) {\n\t\t\tif (classes[i] === _class) { classExists = true; } // class exists, do nothing\n\t\t}\n\t}\n\n\t// if className does not exist, add new className\n\tif (!classExists) {\n\t\tclassName += _class;\n\t\t_element.className += className;\n\t}\n}", "function addClass(element, className) {\n if (!element) {\n return;\n }\n if (element.classList) {\n element.classList.add(className);\n }\n else {\n var currentClassName = element.getAttribute(\"class\");\n if (currentClassName) {\n element.setAttribute(\"class\", currentClassName.split(\" \").filter(function (item) {\n return item !== className;\n }).join(\" \") + \" \" + className);\n }\n else {\n element.setAttribute(\"class\", className);\n }\n //element.className = element.className.replace(new RegExp(\"^\" + className + \"| \" + className), \"\") + \" \" + className;\n }\n}", "function addClass(element, value) \n{\n if (!element.className) \n {\n element.className = value;\n } \n else \n {\n var newClassName = element.className;\n newClassName += \" \";\n newClassName += value;\n element.className = newClassName;\n }\n}", "function addClass(elem, className) {\n\t\tif (elem.classList)\n\t\t\telem.classList.add(className)\n\t\telse {\n\t\t\tvar oldClassName = elem.getAttribute('class');\n\t\t\telem.setAttribute('class', oldClassName.replace(className,'')+' '+className );\n\t\t}\n\t}", "function addClass (el, cls) {\n /* istanbul ignore else */\n if (el.classList) {\n if (cls.indexOf(' ') > -1) {\n cls.split(/\\s+/).forEach(function (c) { return el.classList.add(c); });\n } else {\n el.classList.add(cls);\n }\n } else {\n var cur = ' ' + el.getAttribute('class') + ' ';\n if (cur.indexOf(' ' + cls + ' ') < 0) {\n el.setAttribute('class', (cur + cls).trim());\n }\n }\n}", "function addClass(el, cls) {\n var classes = el.className.split(' ');\n classes.push(cls);\n el.className = classes.join(' ');\n}", "function addClass(css_class, element) {\r\n checkParams(css_class, element, 'addClass');\r\n var class_element = element.className;\r\n\r\n if (!hasClass(css_class, element)) {\r\n if (class_element.length) {\r\n class_element += ' ' + css_class;\r\n } else {\r\n class_element = css_class;\r\n }\r\n }\r\n element.className = class_element;\r\n }", "function addClass(el, cls) {\n\t\t /* istanbul ignore else */\n\t\t if (el.classList) {\n\t\t if (cls.indexOf(' ') > -1) {\n\t\t cls.split(/\\s+/).forEach(function (c) {\n\t\t return el.classList.add(c);\n\t\t });\n\t\t } else {\n\t\t el.classList.add(cls);\n\t\t }\n\t\t } else {\n\t\t var cur = ' ' + el.getAttribute('class') + ' ';\n\t\t if (cur.indexOf(' ' + cls + ' ') < 0) {\n\t\t el.setAttribute('class', (cur + cls).trim());\n\t\t }\n\t\t }\n\t\t}", "function addClass(ele, cls) {\n\tif (!hasClass(ele, cls)) ele.className += \" \" + cls;\n}", "function nbAddCssClass(element, cssClass) {\n var className = element.className;\n if (className.indexOf(cssClass) !== -1) {\n // already has this class\n return;\n }\n element.className = (element.className.trim() + ' ' + cssClass);\n}", "function addClass(className) {\n var callback = function(element) {\n element.classList.add(className);\n }\n\n $.forEach(this.elements, callback);\n \n return this;\n }", "function addClass(el, cls) {\n /* istanbul ignore else */\n if (el.classList) {\n if (cls.indexOf(' ') > -1) {\n cls.split(/\\s+/).forEach(function (c) {\n return el.classList.add(c);\n });\n } else {\n el.classList.add(cls);\n }\n } else {\n var cur = ' ' + el.getAttribute('class') + ' ';\n if (cur.indexOf(' ' + cls + ' ') < 0) {\n el.setAttribute('class', (cur + cls).trim());\n }\n }\n}", "function addClass(element, classToAdd) {\n var currentClassValue = element.className;\n\n if (currentClassValue.indexOf(classToAdd) == -1) {\n if (currentClassValue == null || currentClassValue === \"\") {\n element.className = classToAdd;\n } else {\n element.className += \" \" + classToAdd;\n }\n }\n}", "function addClass (el, cls) {\n\t /* istanbul ignore else */\n\t if (el.classList) {\n\t if (cls.indexOf(' ') > -1) {\n\t cls.split(/\\s+/).forEach(function (c) { return el.classList.add(c); })\n\t } else {\n\t el.classList.add(cls)\n\t }\n\t } else {\n\t var cur = ' ' + el.getAttribute('class') + ' '\n\t if (cur.indexOf(' ' + cls + ' ') < 0) {\n\t el.setAttribute('class', (cur + cls).trim())\n\t }\n\t }\n\t}", "function addClass (el, cls) {\n\t /* istanbul ignore else */\n\t if (el.classList) {\n\t if (cls.indexOf(' ') > -1) {\n\t cls.split(/\\s+/).forEach(function (c) { return el.classList.add(c); });\n\t } else {\n\t el.classList.add(cls);\n\t }\n\t } else {\n\t var cur = ' ' + el.getAttribute('class') + ' ';\n\t if (cur.indexOf(' ' + cls + ' ') < 0) {\n\t el.setAttribute('class', (cur + cls).trim());\n\t }\n\t }\n\t}", "function addClass(element, className) {\n if (element.classList) element.classList.add(className);else if (!hasClass(element, className)) if (typeof element.className === 'string') element.className = element.className + \" \" + className;else element.setAttribute('class', (element.className && element.className.baseVal || '') + \" \" + className);\n}", "function addClass(element, classesToAdd) {\t\t\n\t\tvar newClasses = classesToAdd.replace(/\\s+/g,'').split(\",\");\t\t\n\t\tvar newClassName = element.className.trim().replace(/\\s+/g,' ') + ' ';\n var len = newClasses.length;\n var ind = 0;\n\t\twhile(ind < len) { \n\t\t\tvar testTerm = new RegExp(newClasses[ind] + ' ');\n if (!testTerm.test(newClassName)) {\n\t\t\t\t//current className doesn't contain class - add it\n\t\t\t\tnewClassName += newClasses[ind] + ' ';\t\t\t\n \t\t\t}\n ind++;\n \t\t}\n\n\t\telement.className = newClassName.trim();\n \t}", "function addClass(element, className) {\n if (element.classList) element.classList.add(className);else if (!(0, _hasClass.default)(element, className)) if (typeof element.className === 'string') element.className = element.className + \" \" + className;else element.setAttribute('class', (element.className && element.className.baseVal || '') + \" \" + className);\n}", "function addClass(element, className) {\n if (element.classList) element.classList.add(className);else if (!(0, _hasClass.default)(element, className)) if (typeof element.className === 'string') element.className = element.className + \" \" + className;else element.setAttribute('class', (element.className && element.className.baseVal || '') + \" \" + className);\n}", "function addClass(ele, cls) {\n if (!hasClass(ele,cls)) ele.className += \" \"+cls;\n ele.className = cleanClasses(ele.className);\n }", "function addClass(element, classToAdd) {\n var currentClassValue = element.className;\n \n if (currentClassValue.indexOf(classToAdd) == -1) {\n if ((currentClassValue === null) || (currentClassValue === \"\")) {\n element.className = classToAdd;\n } else {\n element.className += \" \" + classToAdd;\n }\n }\n}", "function addClass(el, className) { \n el.className += className;\n }", "function addClass(_element, className, classContained) {\n let el = document.querySelectorAll(_element);\n el.forEach((e) => { \n e.classList.contains(classContained) \n ? e.classList.add(className) \n : (e.classList.add(classContained)); });\n}", "function addClass(element, className) {\n if (element.classList) element.classList.add(className);else if (!(0,_hasClass__WEBPACK_IMPORTED_MODULE_0__.default)(element, className)) if (typeof element.className === 'string') element.className = element.className + \" \" + className;else element.setAttribute('class', (element.className && element.className.baseVal || '') + \" \" + className);\n}", "function addClass(element, className) {\n if (element.classList) element.classList.add(className);else if (!(0,_hasClass__WEBPACK_IMPORTED_MODULE_0__.default)(element, className)) if (typeof element.className === 'string') element.className = element.className + \" \" + className;else element.setAttribute('class', (element.className && element.className.baseVal || '') + \" \" + className);\n}", "function xAddClass(e, c) {\r\n e = xGetElementById(e);\r\n if (!e)\r\n return false;\r\n if (!xHasClass(e, c))\r\n e.className += ' '+c;\r\n return true;\r\n}", "function addClass(element, className) {\n if (element.classList) element.classList.add(className);else if (!Object(_hasClass__WEBPACK_IMPORTED_MODULE_0__[\"default\"])(element, className)) if (typeof element.className === 'string') element.className = element.className + \" \" + className;else element.setAttribute('class', (element.className && element.className.baseVal || '') + \" \" + className);\n}", "function addClass (el, cls) {\r\n /* istanbul ignore if */\r\n if (!cls || !(cls = cls.trim())) {\r\n return\r\n }\r\n\r\n /* istanbul ignore else */\r\n if (el.classList) {\r\n if (cls.indexOf(' ') > -1) {\r\n cls.split(/\\s+/).forEach(function (c) { return el.classList.add(c); });\r\n } else {\r\n el.classList.add(cls);\r\n }\r\n } else {\r\n var cur = \" \" + (el.getAttribute('class') || '') + \" \";\r\n if (cur.indexOf(' ' + cls + ' ') < 0) {\r\n el.setAttribute('class', (cur + cls).trim());\r\n }\r\n }\r\n}", "function _addClass(element, className, classRegExp) {\n if (element.className) {\n _removeClass(element, classRegExp);\n element.className += \" \" + className;\n } else {\n element.className = className;\n }\n }", "function _addClass(element, className, classRegExp) {\n if (element.className) {\n _removeClass(element, classRegExp);\n element.className += \" \" + className;\n } else {\n element.className = className;\n }\n }", "function addClass(el, className) {\n if (el.classList)\n el.classList.add(className);\n else\n el.className += ' ' + className;\n}", "function addClass (el, cls) {\n /* istanbul ignore if */\n if (!cls || !(cls = cls.trim())) {\n return\n }\n\n /* istanbul ignore else */\n if (el.classList) {\n if (cls.indexOf(' ') > -1) {\n cls.split(/\\s+/).forEach(function (c) { return el.classList.add(c); });\n } else {\n el.classList.add(cls);\n }\n } else {\n var cur = \" \" + (el.getAttribute('class') || '') + \" \";\n if (cur.indexOf(' ' + cls + ' ') < 0) {\n el.setAttribute('class', (cur + cls).trim());\n }\n }\n}", "function addClass (el, cls) {\n /* istanbul ignore if */\n if (!cls || !(cls = cls.trim())) {\n return\n }\n\n /* istanbul ignore else */\n if (el.classList) {\n if (cls.indexOf(' ') > -1) {\n cls.split(/\\s+/).forEach(function (c) { return el.classList.add(c); });\n } else {\n el.classList.add(cls);\n }\n } else {\n var cur = \" \" + (el.getAttribute('class') || '') + \" \";\n if (cur.indexOf(' ' + cls + ' ') < 0) {\n el.setAttribute('class', (cur + cls).trim());\n }\n }\n}", "function addClass (el, cls) {\n /* istanbul ignore if */\n if (!cls || !(cls = cls.trim())) {\n return\n }\n\n /* istanbul ignore else */\n if (el.classList) {\n if (cls.indexOf(' ') > -1) {\n cls.split(/\\s+/).forEach(function (c) { return el.classList.add(c); });\n } else {\n el.classList.add(cls);\n }\n } else {\n var cur = \" \" + (el.getAttribute('class') || '') + \" \";\n if (cur.indexOf(' ' + cls + ' ') < 0) {\n el.setAttribute('class', (cur + cls).trim());\n }\n }\n}", "function addClass (el, cls) {\n /* istanbul ignore if */\n if (!cls || !(cls = cls.trim())) {\n return\n }\n\n /* istanbul ignore else */\n if (el.classList) {\n if (cls.indexOf(' ') > -1) {\n cls.split(/\\s+/).forEach(function (c) { return el.classList.add(c); });\n } else {\n el.classList.add(cls);\n }\n } else {\n var cur = \" \" + (el.getAttribute('class') || '') + \" \";\n if (cur.indexOf(' ' + cls + ' ') < 0) {\n el.setAttribute('class', (cur + cls).trim());\n }\n }\n}", "function addClass (el, cls) {\n /* istanbul ignore if */\n if (!cls || !(cls = cls.trim())) {\n return\n }\n\n /* istanbul ignore else */\n if (el.classList) {\n if (cls.indexOf(' ') > -1) {\n cls.split(/\\s+/).forEach(function (c) { return el.classList.add(c); });\n } else {\n el.classList.add(cls);\n }\n } else {\n var cur = \" \" + (el.getAttribute('class') || '') + \" \";\n if (cur.indexOf(' ' + cls + ' ') < 0) {\n el.setAttribute('class', (cur + cls).trim());\n }\n }\n}", "function addClass (el, cls) {\n /* istanbul ignore if */\n if (!cls || !(cls = cls.trim())) {\n return\n }\n\n /* istanbul ignore else */\n if (el.classList) {\n if (cls.indexOf(' ') > -1) {\n cls.split(/\\s+/).forEach(function (c) { return el.classList.add(c); });\n } else {\n el.classList.add(cls);\n }\n } else {\n var cur = \" \" + (el.getAttribute('class') || '') + \" \";\n if (cur.indexOf(' ' + cls + ' ') < 0) {\n el.setAttribute('class', (cur + cls).trim());\n }\n }\n}", "function addClass (el, cls) {\n /* istanbul ignore if */\n if (!cls || !(cls = cls.trim())) {\n return\n }\n\n /* istanbul ignore else */\n if (el.classList) {\n if (cls.indexOf(' ') > -1) {\n cls.split(/\\s+/).forEach(function (c) { return el.classList.add(c); });\n } else {\n el.classList.add(cls);\n }\n } else {\n var cur = \" \" + (el.getAttribute('class') || '') + \" \";\n if (cur.indexOf(' ' + cls + ' ') < 0) {\n el.setAttribute('class', (cur + cls).trim());\n }\n }\n}", "function addClass (el, cls) {\n /* istanbul ignore if */\n if (!cls || !(cls = cls.trim())) {\n return\n }\n\n /* istanbul ignore else */\n if (el.classList) {\n if (cls.indexOf(' ') > -1) {\n cls.split(/\\s+/).forEach(function (c) { return el.classList.add(c); });\n } else {\n el.classList.add(cls);\n }\n } else {\n var cur = \" \" + (el.getAttribute('class') || '') + \" \";\n if (cur.indexOf(' ' + cls + ' ') < 0) {\n el.setAttribute('class', (cur + cls).trim());\n }\n }\n}", "function addClass (el, cls) {\n /* istanbul ignore if */\n if (!cls || !(cls = cls.trim())) {\n return\n }\n\n /* istanbul ignore else */\n if (el.classList) {\n if (cls.indexOf(' ') > -1) {\n cls.split(/\\s+/).forEach(function (c) { return el.classList.add(c); });\n } else {\n el.classList.add(cls);\n }\n } else {\n var cur = \" \" + (el.getAttribute('class') || '') + \" \";\n if (cur.indexOf(' ' + cls + ' ') < 0) {\n el.setAttribute('class', (cur + cls).trim());\n }\n }\n}", "function addClass (el, cls) {\n /* istanbul ignore if */\n if (!cls || !(cls = cls.trim())) {\n return\n }\n\n /* istanbul ignore else */\n if (el.classList) {\n if (cls.indexOf(' ') > -1) {\n cls.split(/\\s+/).forEach(function (c) { return el.classList.add(c); });\n } else {\n el.classList.add(cls);\n }\n } else {\n var cur = \" \" + (el.getAttribute('class') || '') + \" \";\n if (cur.indexOf(' ' + cls + ' ') < 0) {\n el.setAttribute('class', (cur + cls).trim());\n }\n }\n}", "function addClass (el, cls) {\n /* istanbul ignore if */\n if (!cls || !(cls = cls.trim())) {\n return\n }\n\n /* istanbul ignore else */\n if (el.classList) {\n if (cls.indexOf(' ') > -1) {\n cls.split(/\\s+/).forEach(function (c) { return el.classList.add(c); });\n } else {\n el.classList.add(cls);\n }\n } else {\n var cur = \" \" + (el.getAttribute('class') || '') + \" \";\n if (cur.indexOf(' ' + cls + ' ') < 0) {\n el.setAttribute('class', (cur + cls).trim());\n }\n }\n}", "function addClass (el, cls) {\n /* istanbul ignore if */\n if (!cls || !(cls = cls.trim())) {\n return\n }\n\n /* istanbul ignore else */\n if (el.classList) {\n if (cls.indexOf(' ') > -1) {\n cls.split(/\\s+/).forEach(function (c) { return el.classList.add(c); });\n } else {\n el.classList.add(cls);\n }\n } else {\n var cur = \" \" + (el.getAttribute('class') || '') + \" \";\n if (cur.indexOf(' ' + cls + ' ') < 0) {\n el.setAttribute('class', (cur + cls).trim());\n }\n }\n}", "function addClass (el, cls) {\n /* istanbul ignore if */\n if (!cls || !(cls = cls.trim())) {\n return\n }\n\n /* istanbul ignore else */\n if (el.classList) {\n if (cls.indexOf(' ') > -1) {\n cls.split(/\\s+/).forEach(function (c) { return el.classList.add(c); });\n } else {\n el.classList.add(cls);\n }\n } else {\n var cur = \" \" + (el.getAttribute('class') || '') + \" \";\n if (cur.indexOf(' ' + cls + ' ') < 0) {\n el.setAttribute('class', (cur + cls).trim());\n }\n }\n}", "function addClass (el, cls) {\n /* istanbul ignore if */\n if (!cls || !(cls = cls.trim())) {\n return\n }\n\n /* istanbul ignore else */\n if (el.classList) {\n if (cls.indexOf(' ') > -1) {\n cls.split(/\\s+/).forEach(function (c) { return el.classList.add(c); });\n } else {\n el.classList.add(cls);\n }\n } else {\n var cur = \" \" + (el.getAttribute('class') || '') + \" \";\n if (cur.indexOf(' ' + cls + ' ') < 0) {\n el.setAttribute('class', (cur + cls).trim());\n }\n }\n}", "function addClass (el, cls) {\n /* istanbul ignore if */\n if (!cls || !(cls = cls.trim())) {\n return\n }\n\n /* istanbul ignore else */\n if (el.classList) {\n if (cls.indexOf(' ') > -1) {\n cls.split(/\\s+/).forEach(function (c) { return el.classList.add(c); });\n } else {\n el.classList.add(cls);\n }\n } else {\n var cur = \" \" + (el.getAttribute('class') || '') + \" \";\n if (cur.indexOf(' ' + cls + ' ') < 0) {\n el.setAttribute('class', (cur + cls).trim());\n }\n }\n}", "function addClass (el, cls) {\n /* istanbul ignore if */\n if (!cls || !(cls = cls.trim())) {\n return\n }\n\n /* istanbul ignore else */\n if (el.classList) {\n if (cls.indexOf(' ') > -1) {\n cls.split(/\\s+/).forEach(function (c) { return el.classList.add(c); });\n } else {\n el.classList.add(cls);\n }\n } else {\n var cur = \" \" + (el.getAttribute('class') || '') + \" \";\n if (cur.indexOf(' ' + cls + ' ') < 0) {\n el.setAttribute('class', (cur + cls).trim());\n }\n }\n}", "function addClass (el, cls) {\n /* istanbul ignore if */\n if (!cls || !(cls = cls.trim())) {\n return\n }\n\n /* istanbul ignore else */\n if (el.classList) {\n if (cls.indexOf(' ') > -1) {\n cls.split(/\\s+/).forEach(function (c) { return el.classList.add(c); });\n } else {\n el.classList.add(cls);\n }\n } else {\n var cur = \" \" + (el.getAttribute('class') || '') + \" \";\n if (cur.indexOf(' ' + cls + ' ') < 0) {\n el.setAttribute('class', (cur + cls).trim());\n }\n }\n}", "function addClass (el, cls) {\n /* istanbul ignore if */\n if (!cls || !(cls = cls.trim())) {\n return\n }\n\n /* istanbul ignore else */\n if (el.classList) {\n if (cls.indexOf(' ') > -1) {\n cls.split(/\\s+/).forEach(function (c) { return el.classList.add(c); });\n } else {\n el.classList.add(cls);\n }\n } else {\n var cur = \" \" + (el.getAttribute('class') || '') + \" \";\n if (cur.indexOf(' ' + cls + ' ') < 0) {\n el.setAttribute('class', (cur + cls).trim());\n }\n }\n}", "function addClass (el, cls) {\n /* istanbul ignore if */\n if (!cls || !(cls = cls.trim())) {\n return\n }\n\n /* istanbul ignore else */\n if (el.classList) {\n if (cls.indexOf(' ') > -1) {\n cls.split(/\\s+/).forEach(function (c) { return el.classList.add(c); });\n } else {\n el.classList.add(cls);\n }\n } else {\n var cur = \" \" + (el.getAttribute('class') || '') + \" \";\n if (cur.indexOf(' ' + cls + ' ') < 0) {\n el.setAttribute('class', (cur + cls).trim());\n }\n }\n}", "function addClass (el, cls) {\n /* istanbul ignore if */\n if (!cls || !(cls = cls.trim())) {\n return\n }\n\n /* istanbul ignore else */\n if (el.classList) {\n if (cls.indexOf(' ') > -1) {\n cls.split(/\\s+/).forEach(function (c) { return el.classList.add(c); });\n } else {\n el.classList.add(cls);\n }\n } else {\n var cur = \" \" + (el.getAttribute('class') || '') + \" \";\n if (cur.indexOf(' ' + cls + ' ') < 0) {\n el.setAttribute('class', (cur + cls).trim());\n }\n }\n}", "function addClass (el, cls) {\n /* istanbul ignore if */\n if (!cls || !(cls = cls.trim())) {\n return\n }\n\n /* istanbul ignore else */\n if (el.classList) {\n if (cls.indexOf(' ') > -1) {\n cls.split(/\\s+/).forEach(function (c) { return el.classList.add(c); });\n } else {\n el.classList.add(cls);\n }\n } else {\n var cur = \" \" + (el.getAttribute('class') || '') + \" \";\n if (cur.indexOf(' ' + cls + ' ') < 0) {\n el.setAttribute('class', (cur + cls).trim());\n }\n }\n}", "function addClass (el, cls) {\n /* istanbul ignore if */\n if (!cls || !(cls = cls.trim())) {\n return\n }\n\n /* istanbul ignore else */\n if (el.classList) {\n if (cls.indexOf(' ') > -1) {\n cls.split(/\\s+/).forEach(function (c) { return el.classList.add(c); });\n } else {\n el.classList.add(cls);\n }\n } else {\n var cur = \" \" + (el.getAttribute('class') || '') + \" \";\n if (cur.indexOf(' ' + cls + ' ') < 0) {\n el.setAttribute('class', (cur + cls).trim());\n }\n }\n}", "function addClass (el, cls) {\n /* istanbul ignore if */\n if (!cls || !(cls = cls.trim())) {\n return\n }\n\n /* istanbul ignore else */\n if (el.classList) {\n if (cls.indexOf(' ') > -1) {\n cls.split(/\\s+/).forEach(function (c) { return el.classList.add(c); });\n } else {\n el.classList.add(cls);\n }\n } else {\n var cur = \" \" + (el.getAttribute('class') || '') + \" \";\n if (cur.indexOf(' ' + cls + ' ') < 0) {\n el.setAttribute('class', (cur + cls).trim());\n }\n }\n}", "function addClass (el, cls) {\n /* istanbul ignore if */\n if (!cls || !(cls = cls.trim())) {\n return\n }\n\n /* istanbul ignore else */\n if (el.classList) {\n if (cls.indexOf(' ') > -1) {\n cls.split(/\\s+/).forEach(function (c) { return el.classList.add(c); });\n } else {\n el.classList.add(cls);\n }\n } else {\n var cur = \" \" + (el.getAttribute('class') || '') + \" \";\n if (cur.indexOf(' ' + cls + ' ') < 0) {\n el.setAttribute('class', (cur + cls).trim());\n }\n }\n}", "function addClass (el, cls) {\n /* istanbul ignore if */\n if (!cls || !(cls = cls.trim())) {\n return\n }\n\n /* istanbul ignore else */\n if (el.classList) {\n if (cls.indexOf(' ') > -1) {\n cls.split(/\\s+/).forEach(function (c) { return el.classList.add(c); });\n } else {\n el.classList.add(cls);\n }\n } else {\n var cur = \" \" + (el.getAttribute('class') || '') + \" \";\n if (cur.indexOf(' ' + cls + ' ') < 0) {\n el.setAttribute('class', (cur + cls).trim());\n }\n }\n}", "function addClass (el, cls) {\n /* istanbul ignore if */\n if (!cls || !(cls = cls.trim())) {\n return\n }\n\n /* istanbul ignore else */\n if (el.classList) {\n if (cls.indexOf(' ') > -1) {\n cls.split(/\\s+/).forEach(function (c) { return el.classList.add(c); });\n } else {\n el.classList.add(cls);\n }\n } else {\n var cur = \" \" + (el.getAttribute('class') || '') + \" \";\n if (cur.indexOf(' ' + cls + ' ') < 0) {\n el.setAttribute('class', (cur + cls).trim());\n }\n }\n}", "function addClass (el, cls) {\n /* istanbul ignore if */\n if (!cls || !(cls = cls.trim())) {\n return\n }\n\n /* istanbul ignore else */\n if (el.classList) {\n if (cls.indexOf(' ') > -1) {\n cls.split(/\\s+/).forEach(function (c) { return el.classList.add(c); });\n } else {\n el.classList.add(cls);\n }\n } else {\n var cur = \" \" + (el.getAttribute('class') || '') + \" \";\n if (cur.indexOf(' ' + cls + ' ') < 0) {\n el.setAttribute('class', (cur + cls).trim());\n }\n }\n}", "function addClass (el, cls) {\n /* istanbul ignore if */\n if (!cls || !(cls = cls.trim())) {\n return\n }\n\n /* istanbul ignore else */\n if (el.classList) {\n if (cls.indexOf(' ') > -1) {\n cls.split(/\\s+/).forEach(function (c) { return el.classList.add(c); });\n } else {\n el.classList.add(cls);\n }\n } else {\n var cur = \" \" + (el.getAttribute('class') || '') + \" \";\n if (cur.indexOf(' ' + cls + ' ') < 0) {\n el.setAttribute('class', (cur + cls).trim());\n }\n }\n}", "function addClass (el, cls) {\n /* istanbul ignore if */\n if (!cls || !(cls = cls.trim())) {\n return\n }\n\n /* istanbul ignore else */\n if (el.classList) {\n if (cls.indexOf(' ') > -1) {\n cls.split(/\\s+/).forEach(function (c) { return el.classList.add(c); });\n } else {\n el.classList.add(cls);\n }\n } else {\n var cur = \" \" + (el.getAttribute('class') || '') + \" \";\n if (cur.indexOf(' ' + cls + ' ') < 0) {\n el.setAttribute('class', (cur + cls).trim());\n }\n }\n}", "function addClass (el, cls) {\n /* istanbul ignore if */\n if (!cls || !(cls = cls.trim())) {\n return\n }\n\n /* istanbul ignore else */\n if (el.classList) {\n if (cls.indexOf(' ') > -1) {\n cls.split(/\\s+/).forEach(function (c) { return el.classList.add(c); });\n } else {\n el.classList.add(cls);\n }\n } else {\n var cur = \" \" + (el.getAttribute('class') || '') + \" \";\n if (cur.indexOf(' ' + cls + ' ') < 0) {\n el.setAttribute('class', (cur + cls).trim());\n }\n }\n}", "function addClass (el, cls) {\n /* istanbul ignore if */\n if (!cls || !(cls = cls.trim())) {\n return\n }\n\n /* istanbul ignore else */\n if (el.classList) {\n if (cls.indexOf(' ') > -1) {\n cls.split(/\\s+/).forEach(function (c) { return el.classList.add(c); });\n } else {\n el.classList.add(cls);\n }\n } else {\n var cur = \" \" + (el.getAttribute('class') || '') + \" \";\n if (cur.indexOf(' ' + cls + ' ') < 0) {\n el.setAttribute('class', (cur + cls).trim());\n }\n }\n}", "function addClass (el, cls) {\n /* istanbul ignore if */\n if (!cls || !(cls = cls.trim())) {\n return\n }\n\n /* istanbul ignore else */\n if (el.classList) {\n if (cls.indexOf(' ') > -1) {\n cls.split(/\\s+/).forEach(function (c) { return el.classList.add(c); });\n } else {\n el.classList.add(cls);\n }\n } else {\n var cur = \" \" + (el.getAttribute('class') || '') + \" \";\n if (cur.indexOf(' ' + cls + ' ') < 0) {\n el.setAttribute('class', (cur + cls).trim());\n }\n }\n}", "function addClass (el, cls) {\n /* istanbul ignore if */\n if (!cls || !(cls = cls.trim())) {\n return\n }\n\n /* istanbul ignore else */\n if (el.classList) {\n if (cls.indexOf(' ') > -1) {\n cls.split(/\\s+/).forEach(function (c) { return el.classList.add(c); });\n } else {\n el.classList.add(cls);\n }\n } else {\n var cur = \" \" + (el.getAttribute('class') || '') + \" \";\n if (cur.indexOf(' ' + cls + ' ') < 0) {\n el.setAttribute('class', (cur + cls).trim());\n }\n }\n}", "function addClass (el, cls) {\n /* istanbul ignore if */\n if (!cls || !(cls = cls.trim())) {\n return\n }\n\n /* istanbul ignore else */\n if (el.classList) {\n if (cls.indexOf(' ') > -1) {\n cls.split(/\\s+/).forEach(function (c) { return el.classList.add(c); });\n } else {\n el.classList.add(cls);\n }\n } else {\n var cur = \" \" + (el.getAttribute('class') || '') + \" \";\n if (cur.indexOf(' ' + cls + ' ') < 0) {\n el.setAttribute('class', (cur + cls).trim());\n }\n }\n}", "function addClass (el, cls) {\n /* istanbul ignore if */\n if (!cls || !(cls = cls.trim())) {\n return\n }\n\n /* istanbul ignore else */\n if (el.classList) {\n if (cls.indexOf(' ') > -1) {\n cls.split(/\\s+/).forEach(function (c) { return el.classList.add(c); });\n } else {\n el.classList.add(cls);\n }\n } else {\n var cur = \" \" + (el.getAttribute('class') || '') + \" \";\n if (cur.indexOf(' ' + cls + ' ') < 0) {\n el.setAttribute('class', (cur + cls).trim());\n }\n }\n}", "function addClass (el, cls) {\n /* istanbul ignore if */\n if (!cls || !(cls = cls.trim())) {\n return\n }\n\n /* istanbul ignore else */\n if (el.classList) {\n if (cls.indexOf(' ') > -1) {\n cls.split(/\\s+/).forEach(function (c) { return el.classList.add(c); });\n } else {\n el.classList.add(cls);\n }\n } else {\n var cur = \" \" + (el.getAttribute('class') || '') + \" \";\n if (cur.indexOf(' ' + cls + ' ') < 0) {\n el.setAttribute('class', (cur + cls).trim());\n }\n }\n}", "function addClass (el, cls) {\n /* istanbul ignore if */\n if (!cls || !(cls = cls.trim())) {\n return\n }\n\n /* istanbul ignore else */\n if (el.classList) {\n if (cls.indexOf(' ') > -1) {\n cls.split(/\\s+/).forEach(function (c) { return el.classList.add(c); });\n } else {\n el.classList.add(cls);\n }\n } else {\n var cur = \" \" + (el.getAttribute('class') || '') + \" \";\n if (cur.indexOf(' ' + cls + ' ') < 0) {\n el.setAttribute('class', (cur + cls).trim());\n }\n }\n}", "function addClass (el, cls) {\n /* istanbul ignore if */\n if (!cls || !(cls = cls.trim())) {\n return\n }\n\n /* istanbul ignore else */\n if (el.classList) {\n if (cls.indexOf(' ') > -1) {\n cls.split(/\\s+/).forEach(function (c) { return el.classList.add(c); });\n } else {\n el.classList.add(cls);\n }\n } else {\n var cur = \" \" + (el.getAttribute('class') || '') + \" \";\n if (cur.indexOf(' ' + cls + ' ') < 0) {\n el.setAttribute('class', (cur + cls).trim());\n }\n }\n}", "function addClass (el, cls) {\n /* istanbul ignore if */\n if (!cls || !(cls = cls.trim())) {\n return\n }\n\n /* istanbul ignore else */\n if (el.classList) {\n if (cls.indexOf(' ') > -1) {\n cls.split(/\\s+/).forEach(function (c) { return el.classList.add(c); });\n } else {\n el.classList.add(cls);\n }\n } else {\n var cur = \" \" + (el.getAttribute('class') || '') + \" \";\n if (cur.indexOf(' ' + cls + ' ') < 0) {\n el.setAttribute('class', (cur + cls).trim());\n }\n }\n}", "function addClass (el, cls) {\n /* istanbul ignore if */\n if (!cls || !(cls = cls.trim())) {\n return\n }\n\n /* istanbul ignore else */\n if (el.classList) {\n if (cls.indexOf(' ') > -1) {\n cls.split(/\\s+/).forEach(function (c) { return el.classList.add(c); });\n } else {\n el.classList.add(cls);\n }\n } else {\n var cur = \" \" + (el.getAttribute('class') || '') + \" \";\n if (cur.indexOf(' ' + cls + ' ') < 0) {\n el.setAttribute('class', (cur + cls).trim());\n }\n }\n}", "function addClass (el, cls) {\n /* istanbul ignore if */\n if (!cls || !(cls = cls.trim())) {\n return\n }\n\n /* istanbul ignore else */\n if (el.classList) {\n if (cls.indexOf(' ') > -1) {\n cls.split(/\\s+/).forEach(function (c) { return el.classList.add(c); });\n } else {\n el.classList.add(cls);\n }\n } else {\n var cur = \" \" + (el.getAttribute('class') || '') + \" \";\n if (cur.indexOf(' ' + cls + ' ') < 0) {\n el.setAttribute('class', (cur + cls).trim());\n }\n }\n}", "function addClass (el, cls) {\n /* istanbul ignore if */\n if (!cls || !(cls = cls.trim())) {\n return\n }\n\n /* istanbul ignore else */\n if (el.classList) {\n if (cls.indexOf(' ') > -1) {\n cls.split(/\\s+/).forEach(function (c) { return el.classList.add(c); });\n } else {\n el.classList.add(cls);\n }\n } else {\n var cur = \" \" + (el.getAttribute('class') || '') + \" \";\n if (cur.indexOf(' ' + cls + ' ') < 0) {\n el.setAttribute('class', (cur + cls).trim());\n }\n }\n}", "function addClass (el, cls) {\n /* istanbul ignore if */\n if (!cls || !(cls = cls.trim())) {\n return\n }\n\n /* istanbul ignore else */\n if (el.classList) {\n if (cls.indexOf(' ') > -1) {\n cls.split(/\\s+/).forEach(function (c) { return el.classList.add(c); });\n } else {\n el.classList.add(cls);\n }\n } else {\n var cur = \" \" + (el.getAttribute('class') || '') + \" \";\n if (cur.indexOf(' ' + cls + ' ') < 0) {\n el.setAttribute('class', (cur + cls).trim());\n }\n }\n}", "function addClass (el, cls) {\n /* istanbul ignore if */\n if (!cls || !(cls = cls.trim())) {\n return\n }\n\n /* istanbul ignore else */\n if (el.classList) {\n if (cls.indexOf(' ') > -1) {\n cls.split(/\\s+/).forEach(function (c) { return el.classList.add(c); });\n } else {\n el.classList.add(cls);\n }\n } else {\n var cur = \" \" + (el.getAttribute('class') || '') + \" \";\n if (cur.indexOf(' ' + cls + ' ') < 0) {\n el.setAttribute('class', (cur + cls).trim());\n }\n }\n}", "function addClass (el, cls) {\n /* istanbul ignore if */\n if (!cls || !(cls = cls.trim())) {\n return\n }\n\n /* istanbul ignore else */\n if (el.classList) {\n if (cls.indexOf(' ') > -1) {\n cls.split(/\\s+/).forEach(function (c) { return el.classList.add(c); });\n } else {\n el.classList.add(cls);\n }\n } else {\n var cur = \" \" + (el.getAttribute('class') || '') + \" \";\n if (cur.indexOf(' ' + cls + ' ') < 0) {\n el.setAttribute('class', (cur + cls).trim());\n }\n }\n}", "function addClass (el, cls) {\n /* istanbul ignore if */\n if (!cls || !(cls = cls.trim())) {\n return\n }\n\n /* istanbul ignore else */\n if (el.classList) {\n if (cls.indexOf(' ') > -1) {\n cls.split(/\\s+/).forEach(function (c) { return el.classList.add(c); });\n } else {\n el.classList.add(cls);\n }\n } else {\n var cur = \" \" + (el.getAttribute('class') || '') + \" \";\n if (cur.indexOf(' ' + cls + ' ') < 0) {\n el.setAttribute('class', (cur + cls).trim());\n }\n }\n}", "function addClass (el, cls) {\n /* istanbul ignore if */\n if (!cls || !(cls = cls.trim())) {\n return\n }\n\n /* istanbul ignore else */\n if (el.classList) {\n if (cls.indexOf(' ') > -1) {\n cls.split(/\\s+/).forEach(function (c) { return el.classList.add(c); });\n } else {\n el.classList.add(cls);\n }\n } else {\n var cur = \" \" + (el.getAttribute('class') || '') + \" \";\n if (cur.indexOf(' ' + cls + ' ') < 0) {\n el.setAttribute('class', (cur + cls).trim());\n }\n }\n}", "function addClass (el, cls) {\n /* istanbul ignore if */\n if (!cls || !(cls = cls.trim())) {\n return\n }\n\n /* istanbul ignore else */\n if (el.classList) {\n if (cls.indexOf(' ') > -1) {\n cls.split(/\\s+/).forEach(function (c) { return el.classList.add(c); });\n } else {\n el.classList.add(cls);\n }\n } else {\n var cur = \" \" + (el.getAttribute('class') || '') + \" \";\n if (cur.indexOf(' ' + cls + ' ') < 0) {\n el.setAttribute('class', (cur + cls).trim());\n }\n }\n}", "function addClass (el, cls) {\n /* istanbul ignore if */\n if (!cls || !(cls = cls.trim())) {\n return\n }\n\n /* istanbul ignore else */\n if (el.classList) {\n if (cls.indexOf(' ') > -1) {\n cls.split(/\\s+/).forEach(function (c) { return el.classList.add(c); });\n } else {\n el.classList.add(cls);\n }\n } else {\n var cur = \" \" + (el.getAttribute('class') || '') + \" \";\n if (cur.indexOf(' ' + cls + ' ') < 0) {\n el.setAttribute('class', (cur + cls).trim());\n }\n }\n}" ]
[ "0.78299135", "0.7782592", "0.7721232", "0.7686917", "0.7636375", "0.760742", "0.760149", "0.7600813", "0.75741833", "0.75349927", "0.7521864", "0.7503874", "0.7490196", "0.74850684", "0.74850684", "0.74472296", "0.74158365", "0.7412106", "0.74026066", "0.7391322", "0.7379696", "0.7369364", "0.7366317", "0.73633075", "0.735974", "0.73367524", "0.73210657", "0.7298521", "0.7297875", "0.729603", "0.7293054", "0.72871953", "0.7285412", "0.7285326", "0.728311", "0.727829", "0.72553664", "0.72543275", "0.7243345", "0.7243345", "0.72398216", "0.72389346", "0.7237774", "0.7227103", "0.72049916", "0.72049916", "0.7201907", "0.7192967", "0.7188945", "0.71873087", "0.71873087", "0.7175998", "0.71473384", "0.71473384", "0.71473384", "0.71473384", "0.71473384", "0.71473384", "0.71473384", "0.71473384", "0.71473384", "0.71473384", "0.71473384", "0.71473384", "0.71473384", "0.71473384", "0.71473384", "0.71473384", "0.71473384", "0.71473384", "0.71473384", "0.71473384", "0.71473384", "0.71473384", "0.71473384", "0.71473384", "0.71473384", "0.71473384", "0.71473384", "0.71473384", "0.71473384", "0.71473384", "0.71473384", "0.71473384", "0.71473384", "0.71473384", "0.71473384", "0.71473384", "0.71473384", "0.71473384", "0.71473384", "0.71473384", "0.71473384", "0.71473384", "0.71473384", "0.71473384", "0.71473384", "0.71473384", "0.71473384", "0.71473384", "0.71473384" ]
0.0
-1
(Internal) Removes a class from an element.
function removeClass(element, name) { var oldList = classList(element), newList; if (!hasClass(element, name)) return; // Replace the class name. newList = oldList.replace(' ' + name + ' ', ' '); // Trim the opening and closing spaces. element.className = newList.substring(1, newList.length - 1); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function removeClass(element, classname) {\n\tvar classes = getClassList(element);\n\tvar index = indexOf(classname,classes);\n\tif (index >= 0) {\n\t\tclasses.splice(index,1);\n\t\tsetClassList(element, classes);\n\t}\n}", "function removeClass(_element, _class) {\n\t// variables\n\tvar classExists = false, // boolean to check if the class already exists\n\t\t\tclassRef; // will hold the array reference if the element exits\n\tvar classes = _element.className.split(\" \");\n\n\n\tif (classes[0] === \"\") { /* element has no classes. do nothing */ }\n\telse {\n\t\t/* element has existing classes, check if the class exists */\n\t\tfor (var i = 0; i < classes.length; i++) {\n\t\t\tif (classes[i] === _class) {\n\t\t\t\tclassExists = true;\n\t\t\t\tclassRef = i;\n\t\t\t}\n\t\t}\n\t}\n\n\t// if className exists, remove the className\n\tif (classExists) {\n\t\tclasses.splice(classRef);\n\t\t_element.className = classes;\n\t}\n}", "function removeClass(element, cls) {\n element.classList.remove(cls);\n}", "function removeClass(element, cls) {\n var classes = element.className;\n if (!classes) return;\n var l = classes.split(' ');\n for (var i = 0; i < l.length; i++) {\n if (l[i] == cls) {\n l.splice(i, 1);\n break;\n }\n }\n element.className = l.join(' ');\n}", "function removeClass(element, className) {\n var classes = element.className.split(' ');\n var index = classes.indexOf(className);\n if (index != -1) {\n classes.splice(index, 1);\n }\n element.className = classes.join(' ');\n }", "function removeClass(element, deleteClass)\n {\n \tvar reg = new RegExp(\" \" + deleteClass,\"g\");\n \telement.className = element.className.replace(reg, '');\n }", "function removeClassFromElement(element, className) {\n element.classList.remove(className);\n}", "function delClass(element, clas)\n{\n element.className = element.className.replace(clas, '').replace(' ', ' ');\n}", "function removeClass (element, class_name) {\n\tvar class_names = element.className.split ( ' ' ), //class_name splits $html class names at spaces\n\t\tlen = class_names.length, //len = Number of class names in array\n\t\tkept_classes = []; //kept_classes = Empty array\n\twhile (len--) {\n\t\tif (class_names[len] != class_name){\n\t\t\tkept_classes.push (class_name[len]);\n\t\t}\n\t}\n\telement.className = kept_classes.join ( ' ' );\n}", "function removingClass(element, removedClass) {\n element.classList.remove(removedClass);\n }", "function removeClass(elem, className) {\t\t\n\t\tif (elem.classList)\n\t\t\telem.classList.remove(className)\n\t\telse \n\t\t\telem.setAttribute('class', elem.getAttribute('class').replace(className,'') );\n\t}", "function removeClass(css_class, element) {\r\n checkParams(css_class, element, 'removeClass');\r\n var regexp = new RegExp('(\\\\s' + css_class + ')|(' + css_class + '\\\\s)|' + css_class, 'i');\r\n element.className = trim(element.className.replace(regexp, ''));\r\n }", "function removeClass(elem, className) {\r\n elem.removeClass(className);\r\n }", "unsetClass(el, classname) {\n el.className = el.className.replace(' ' + classname, '');\n }", "function removeClass(element, className) {\n if (!hasClass(element, className)) return; // Element already does not have this class - so nothing to remove\n element.className = element.className.replace(classMatchingRegex(className), \"\").trim();\n}", "function removeClass(ele, cls) {\n if (hasClass(ele,cls)) {\n var reg = new RegExp('(\\\\s|^)'+cls+'(\\\\s|$)');\n ele.className = cleanClasses(ele.className.replace(reg,' '));\n }\n }", "function removeClass(ele, cls) {\n\tif (hasClass(ele, cls)) {\n\t\tele.className = ele.className.replace(getClassRegex(cls), \" \");\n\t}\n}", "function classRemove(element, name) {\n var names, newNames, i;\n if (!classContains(element, name)) {\n return;\n }\n names = element.className.split(/\\s+/);\n newNames = [];\n for (i = names.length-1; i >= 0; --i) {\n if (names[i] !== name) {\n newNames.push(names[i]);\n }\n }\n element.className = newNames.join(' ');\n }", "function removeClass(elem, classN){\n\tvar myClassName=classN;\n\telem.className=elem.className.replace(myClassName,'');\n}", "function removeClass(element, className) {\n if (!element) {\n return;\n }\n if (element.classList) {\n element.classList.remove(className);\n }\n else {\n var currentClassName = element.getAttribute(\"class\");\n if (currentClassName) {\n element.setAttribute(\"class\", currentClassName.split(\" \").filter(function (item) {\n return item !== className;\n }).join(\" \"));\n }\n //element.className = element.className.replace(new RegExp(\"^\" + className + \"| \" + className), \"\");\n }\n}", "function removeClass(element, name) {\n\t var oldList = classList(element),\n\t newList;\n\n\t if (!hasClass(element, name)) return;\n\n\t // Replace the class name.\n\t newList = oldList.replace(' ' + name + ' ', ' ');\n\n\t // Trim the opening and closing spaces.\n\t element.className = newList.substring(1, newList.length - 1);\n\t }", "function removeClass(element, name) {\n\t var oldList = classList(element),\n\t newList;\n\n\t if (!hasClass(element, name)) return;\n\n\t // Replace the class name.\n\t newList = oldList.replace(' ' + name + ' ', ' ');\n\n\t // Trim the opening and closing spaces.\n\t element.className = newList.substring(1, newList.length - 1);\n\t }", "function removeClass(element, name) {\n\t var oldList = classList(element),\n\t newList;\n\n\t if (!hasClass(element, name)) return;\n\n\t // Replace the class name.\n\t newList = oldList.replace(' ' + name + ' ', ' ');\n\n\t // Trim the opening and closing spaces.\n\t element.className = newList.substring(1, newList.length - 1);\n\t }", "function removeClass(el, className) {\n var classes = el.className.split(' ');\n var existingIndex = classes.indexOf(className);\n\n if (existingIndex >= 0) {\n classes.splice(existingIndex, 1);\n el.className = classes.join(' ');\n }\n\n}", "function removeClass(el,cls){/* istanbul ignore if */if(!cls||!cls.trim()){return;}/* istanbul ignore else */if(el.classList){if(cls.indexOf(' ')>-1){cls.split(/\\s+/).forEach(function(c){return el.classList.remove(c);});}else{el.classList.remove(cls);}}else{var cur=' '+el.getAttribute('class')+' ';var tar=' '+cls+' ';while(cur.indexOf(tar)>=0){cur=cur.replace(tar,' ');}el.setAttribute('class',cur.trim());}}", "function removeClass(element, name) {\n\t var oldList = classList(element),\n\t newList;\n\t\n\t if (!hasClass(element, name)) return;\n\t\n\t // Replace the class name.\n\t newList = oldList.replace(' ' + name + ' ', ' ');\n\t\n\t // Trim the opening and closing spaces.\n\t element.className = newList.substring(1, newList.length - 1);\n\t }", "function removeClass(element, className) {\n if (element.classList) element.classList.remove(className);\n else if (typeof element.className === 'string') element.className = replaceClassName(element.className, className);\n else element.setAttribute('class', replaceClassName(element.className && element.className.baseVal || '', className));\n}", "function removeClass$1(element, className) {\n if (element.classList) {\n element.classList.remove(className);\n } else if (typeof element.className === 'string') {\n element.className = replaceClassName(element.className, className);\n } else {\n element.setAttribute('class', replaceClassName(element.className && element.className.baseVal || '', className));\n }\n}", "function removeClass(el,cls){/* istanbul ignore if */if(!cls||!(cls=cls.trim())){return;}/* istanbul ignore else */if(el.classList){if(cls.indexOf(' ')>-1){cls.split(/\\s+/).forEach(function(c){return el.classList.remove(c);});}else{el.classList.remove(cls);}if(!el.classList.length){el.removeAttribute('class');}}else{var cur=\" \"+(el.getAttribute('class')||'')+\" \";var tar=' '+cls+' ';while(cur.indexOf(tar)>=0){cur=cur.replace(tar,' ');}cur=cur.trim();if(cur){el.setAttribute('class',cur);}else{el.removeAttribute('class');}}}", "function removeClass(el,cls){/* istanbul ignore if */if(!cls||!(cls=cls.trim())){return;}/* istanbul ignore else */if(el.classList){if(cls.indexOf(' ')>-1){cls.split(/\\s+/).forEach(function(c){return el.classList.remove(c);});}else{el.classList.remove(cls);}if(!el.classList.length){el.removeAttribute('class');}}else{var cur=\" \"+(el.getAttribute('class')||'')+\" \";var tar=' '+cls+' ';while(cur.indexOf(tar)>=0){cur=cur.replace(tar,' ');}cur=cur.trim();if(cur){el.setAttribute('class',cur);}else{el.removeAttribute('class');}}}", "function removeClass(element, name) {\n var oldList = classList(element),\n newList;\n\n if (!hasClass(element, name)) return;\n\n // Replace the class name.\n newList = oldList.replace(' ' + name + ' ', ' ');\n\n // Trim the opening and closing spaces.\n element.className = newList.substring(1, newList.length - 1);\n }", "function removeClass(element, name) {\n var oldList = classList(element),\n newList;\n\n if (!hasClass(element, name)) return;\n\n // Replace the class name.\n newList = oldList.replace(' ' + name + ' ', ' ');\n\n // Trim the opening and closing spaces.\n element.className = newList.substring(1, newList.length - 1);\n }", "function removeClass(element, name) {\n var oldList = classList(element),\n newList;\n\n if (!hasClass(element, name)) return;\n\n // Replace the class name.\n newList = oldList.replace(' ' + name + ' ', ' ');\n\n // Trim the opening and closing spaces.\n element.className = newList.substring(1, newList.length - 1);\n }", "function removeClass(el, rmClass) {\n if(!el) { return };\n var array = el.className.split(' ');\n\n // The `array.filter` callback.\n function filterMe(name) {\n return name !== rmClass;\n }\n\n el.className = array.filter(filterMe).join(' ');\n}", "function removeClass(element, name) {\n var className = element.className;\n if(className.indexOf(name) == -1) {\n return;\n }\n else {\n element.className = className.replace(name, '');\n }\n}", "function removeClass(elementName, newClass) {\n const element = document.querySelectorAll(elementName)\n\n element.forEach(el => {\n el.classList.remove(newClass)\n })\n}", "function removeClass(el, name) {\n if (el.classList !== undefined) {\n el.classList.remove(name);\n } else {\n setClass(el, trim((' ' + getClass(el) + ' ').replace(' ' + name + ' ', ' ')));\n }\n } // @function setClass(el: HTMLElement, name: String)", "function nbRemoveCssClass(element, cssClass) {\n element.className = element.className.replace(cssClass, '').trim();\n}", "function removeClass(element, name) {\n\tlet oldClasses = element.className.split(\" \");\n\tlet newClasses = name.split(\" \");\n\n\tfor (let i = 0; i < newClasses.length; i++) {\n\t\twhile (oldClasses.indexOf(newClasses[i]) > -1) {\n\t\t\toldClasses.splice(oldClasses.indexOf(newClasses[i]), 1);\n\t\t}\n\t}\n\telement.className = oldClasses.join(\" \");\n}", "function removeClass(element, classesToRemove) { \n\t\tvar classes = classesToRemove.replace(/\\s+/g,'').split(\",\");\n\t\tvar ind = classes.length;\n\t\tvar newClass = element.className.trim().replace(/\\s+/g,' ') + ' ';\n\t\twhile(ind--) { \n //remove class\n\t\t\tnewClass = newClass.replace(classes[ind] + ' ','');\n\t\t}\n\t\telement.className = newClass.trim();\n \t}", "function removeClass(element, className) {\n if (element.classList) {\n element.classList.remove(className);\n } else if (typeof element.className === 'string') {\n element.className = replaceClassName(element.className, className);\n } else {\n element.setAttribute('class', replaceClassName(element.className && element.className.baseVal || '', className));\n }\n}", "function removeClass(element, className) {\n if (element.classList) {\n element.classList.remove(className);\n } else if (typeof element.className === 'string') {\n element.className = replaceClassName(element.className, className);\n } else {\n element.setAttribute('class', replaceClassName(element.className && element.className.baseVal || '', className));\n }\n}", "function removeClass(element, className) {\n if (element.classList) {\n element.classList.remove(className);\n } else if (typeof element.className === 'string') {\n element.className = replaceClassName(element.className, className);\n } else {\n element.setAttribute('class', replaceClassName(element.className && element.className.baseVal || '', className));\n }\n}", "function removeClass(element, className) {\n if (element.classList) {\n element.classList.remove(className);\n } else if (typeof element.className === 'string') {\n element.className = replaceClassName(element.className, className);\n } else {\n element.setAttribute('class', replaceClassName(element.className && element.className.baseVal || '', className));\n }\n}", "function removeClass(element, className) {\n if (element.classList) {\n element.classList.remove(className);\n } else if (typeof element.className === 'string') {\n element.className = replaceClassName(element.className, className);\n } else {\n element.setAttribute('class', replaceClassName(element.className && element.className.baseVal || '', className));\n }\n}", "function removeClass (el, cls) {\n\t /* istanbul ignore else */\n\t if (el.classList) {\n\t if (cls.indexOf(' ') > -1) {\n\t cls.split(/\\s+/).forEach(function (c) { return el.classList.remove(c); })\n\t } else {\n\t el.classList.remove(cls)\n\t }\n\t } else {\n\t var cur = ' ' + el.getAttribute('class') + ' '\n\t var tar = ' ' + cls + ' '\n\t while (cur.indexOf(tar) >= 0) {\n\t cur = cur.replace(tar, ' ')\n\t }\n\t el.setAttribute('class', cur.trim())\n\t }\n\t}", "function RemoveClassName(objElement, strClass){\n // if there is a class\n if ( objElement.className ){\n // the classes are just a space separated list, so first get the list\n var arrList = objElement.className.split(' ');\n // get uppercase class for comparison purposes\n var strClassUpper = strClass.toUpperCase();\n // find all instances and remove them\n for ( var i = 0; i < arrList.length; i++ ){\n // if class found\n if ( arrList[i].toUpperCase() == strClassUpper ){\n // remove array item\n arrList.splice(i, 1);\n // decrement loop counter as we have adjusted the array's contents\n i--;\n }\n }\n // assign modified class name attribute\n objElement.className = arrList.join(' ');\n }\n // if there was no class\n // there is nothing to remove\n}", "function RemoveClass(element, name) {\r\n var i, arr1, arr2;\r\n arr1 = element.className.split(\" \");\r\n arr2 = name.split(\" \");\r\n for (i = 0; i < arr2.length; i++) {\r\n while (arr1.indexOf(arr2[i]) > -1) {\r\n arr1.splice(arr1.indexOf(arr2[i]), 1);\r\n }\r\n }\r\n element.className = arr1.join(\" \");\r\n}", "function removeClass(el, cls) {\n\t\t /* istanbul ignore else */\n\t\t if (el.classList) {\n\t\t if (cls.indexOf(' ') > -1) {\n\t\t cls.split(/\\s+/).forEach(function (c) {\n\t\t return el.classList.remove(c);\n\t\t });\n\t\t } else {\n\t\t el.classList.remove(cls);\n\t\t }\n\t\t } else {\n\t\t var cur = ' ' + el.getAttribute('class') + ' ';\n\t\t var tar = ' ' + cls + ' ';\n\t\t while (cur.indexOf(tar) >= 0) {\n\t\t cur = cur.replace(tar, ' ');\n\t\t }\n\t\t el.setAttribute('class', cur.trim());\n\t\t }\n\t\t}", "function RemoveClass(element, name) {\r\n var i, arr1, arr2;\r\n arr1 = element.className.split(\" \");\r\n arr2 = name.split(\" \");\r\n for (i = 0; i < arr2.length; i++) {\r\n while (arr1.indexOf(arr2[i]) > -1) {\r\n arr1.splice(arr1.indexOf(arr2[i]), 1); \r\n }\r\n }\r\n element.className = arr1.join(\" \");\r\n}", "function removeClass (el, cls) {\n\t /* istanbul ignore else */\n\t if (el.classList) {\n\t if (cls.indexOf(' ') > -1) {\n\t cls.split(/\\s+/).forEach(function (c) { return el.classList.remove(c); });\n\t } else {\n\t el.classList.remove(cls);\n\t }\n\t } else {\n\t var cur = ' ' + el.getAttribute('class') + ' ';\n\t var tar = ' ' + cls + ' ';\n\t while (cur.indexOf(tar) >= 0) {\n\t cur = cur.replace(tar, ' ');\n\t }\n\t el.setAttribute('class', cur.trim());\n\t }\n\t}", "rem_class(e, c)\n\t{\n\t\te && c && e.classList.remove(c);\n\t}", "function removeClass(element, classToRemove) {\n var currentClassValue = element.className;\n \n // removing a class value when there is more than one class value present\n // and the class you want to remove is not the first one\n if (currentClassValue.indexOf(\" \" + classToRemove) != -1) {\n element.className = element.className.replace(\" \" + classToRemove, \"\");\n return;\n }\n \n // removing the first class value when there is more than one class\n // value present\n if (currentClassValue.indexOf(classToRemove + \" \") != -1) {\n element.className = element.className.replace(classToRemove + \" \", \"\");\n return;\n }\n \n // removing the first class value when there is only one class value \n // present\n if (currentClassValue.indexOf(classToRemove) != -1) {\n element.className = element.className.replace(classToRemove, \"\");\n return;\n }\n}", "function removeClass (el, cls) {\n /* istanbul ignore else */\n if (el.classList) {\n if (cls.indexOf(' ') > -1) {\n cls.split(/\\s+/).forEach(function (c) { return el.classList.remove(c); });\n } else {\n el.classList.remove(cls);\n }\n } else {\n var cur = ' ' + el.getAttribute('class') + ' ';\n var tar = ' ' + cls + ' ';\n while (cur.indexOf(tar) >= 0) {\n cur = cur.replace(tar, ' ');\n }\n el.setAttribute('class', cur.trim());\n }\n}", "function removeClass(el, className) { \n el.className = el.className.replace(className, '');\n }", "function removeClass(el, className) {\n if (el.classList)\n el.classList.remove(className);\n else\n el.className = el.className.replace(new RegExp('(^|\\\\b)' +\n className.split(' ').join('|') + '(\\\\b|$)', 'gi'), ' ');\n}", "function removeClass(el, cls) {\n /* istanbul ignore else */\n if (el.classList) {\n if (cls.indexOf(' ') > -1) {\n cls.split(/\\s+/).forEach(function (c) {\n return el.classList.remove(c);\n });\n } else {\n el.classList.remove(cls);\n }\n } else {\n var cur = ' ' + el.getAttribute('class') + ' ';\n var tar = ' ' + cls + ' ';\n while (cur.indexOf(tar) >= 0) {\n cur = cur.replace(tar, ' ');\n }\n el.setAttribute('class', cur.trim());\n }\n}", "function removeClass(className) {\n var callback = function(element) {\n element.classList.remove(className);\n }\n\n $.forEach(this.elements, callback);\n \n return this;\n }", "function rmvClass(el, cl) {\r\n el.classList.remove(cl)\r\n}", "function removeClass(at, cls) {\n at.classList.remove(cls);\n}", "function removeClass(at, cls) {\n at.classList.remove(cls);\n}", "function removeClass (el, cls) {\n\t /* istanbul ignore if */\n\t if (!cls || !(cls = cls.trim())) {\n\t return\n\t }\n\t\n\t /* istanbul ignore else */\n\t if (el.classList) {\n\t if (cls.indexOf(' ') > -1) {\n\t cls.split(/\\s+/).forEach(function (c) { return el.classList.remove(c); });\n\t } else {\n\t el.classList.remove(cls);\n\t }\n\t } else {\n\t var cur = \" \" + (el.getAttribute('class') || '') + \" \";\n\t var tar = ' ' + cls + ' ';\n\t while (cur.indexOf(tar) >= 0) {\n\t cur = cur.replace(tar, ' ');\n\t }\n\t el.setAttribute('class', cur.trim());\n\t }\n\t}", "function removeClass (el, cls) {\n\t /* istanbul ignore if */\n\t if (!cls || !(cls = cls.trim())) {\n\t return\n\t }\n\t\n\t /* istanbul ignore else */\n\t if (el.classList) {\n\t if (cls.indexOf(' ') > -1) {\n\t cls.split(/\\s+/).forEach(function (c) { return el.classList.remove(c); });\n\t } else {\n\t el.classList.remove(cls);\n\t }\n\t } else {\n\t var cur = \" \" + (el.getAttribute('class') || '') + \" \";\n\t var tar = ' ' + cls + ' ';\n\t while (cur.indexOf(tar) >= 0) {\n\t cur = cur.replace(tar, ' ');\n\t }\n\t el.setAttribute('class', cur.trim());\n\t }\n\t}", "function removeClass (el, cls) {\n\t /* istanbul ignore if */\n\t if (!cls || !(cls = cls.trim())) {\n\t return\n\t }\n\t\n\t /* istanbul ignore else */\n\t if (el.classList) {\n\t if (cls.indexOf(' ') > -1) {\n\t cls.split(/\\s+/).forEach(function (c) { return el.classList.remove(c); });\n\t } else {\n\t el.classList.remove(cls);\n\t }\n\t } else {\n\t var cur = \" \" + (el.getAttribute('class') || '') + \" \";\n\t var tar = ' ' + cls + ' ';\n\t while (cur.indexOf(tar) >= 0) {\n\t cur = cur.replace(tar, ' ');\n\t }\n\t el.setAttribute('class', cur.trim());\n\t }\n\t}", "function removeClass (el, cls) {\n\t /* istanbul ignore if */\n\t if (!cls || !(cls = cls.trim())) {\n\t return\n\t }\n\t\n\t /* istanbul ignore else */\n\t if (el.classList) {\n\t if (cls.indexOf(' ') > -1) {\n\t cls.split(/\\s+/).forEach(function (c) { return el.classList.remove(c); });\n\t } else {\n\t el.classList.remove(cls);\n\t }\n\t } else {\n\t var cur = \" \" + (el.getAttribute('class') || '') + \" \";\n\t var tar = ' ' + cls + ' ';\n\t while (cur.indexOf(tar) >= 0) {\n\t cur = cur.replace(tar, ' ');\n\t }\n\t el.setAttribute('class', cur.trim());\n\t }\n\t}", "function RemoveClass(element, name) {\n //Split elements and name\n var arr1 = element.className.split(\" \");\n var arr2 = name.split(\" \");\n //Itereate and remove the class name\n for (var i = 0; i < arr2.length; i++) {\n while (arr1.indexOf(arr2[i]) > -1) {\n arr1.splice(arr1.indexOf(arr2[i]), 1);\n }\n }\n //Join elements\n element.className = arr1.join(\" \");\n}" ]
[ "0.8250715", "0.81225693", "0.8054095", "0.8019471", "0.8018517", "0.8002591", "0.79266113", "0.79038703", "0.78412026", "0.7821953", "0.78212357", "0.77817875", "0.77571857", "0.7691068", "0.76683384", "0.7624005", "0.76120305", "0.7611323", "0.7599885", "0.7593325", "0.7560255", "0.7560255", "0.7560255", "0.7546507", "0.75367415", "0.75257444", "0.7496986", "0.7482596", "0.74624616", "0.74624616", "0.74554586", "0.74554586", "0.74554586", "0.7453132", "0.74454916", "0.74396", "0.73828846", "0.7378194", "0.7370092", "0.73669153", "0.7356861", "0.7356861", "0.7356861", "0.7356861", "0.7356861", "0.7348311", "0.7339317", "0.73381096", "0.7332891", "0.7327219", "0.73230666", "0.731789", "0.7316333", "0.7313966", "0.73030037", "0.72715783", "0.7258745", "0.7249197", "0.72490484", "0.724632", "0.724632", "0.72316676", "0.72316676", "0.72316676", "0.72316676", "0.7230267" ]
0.74823475
61
(Internal) Gets a space separated list of the class names on the element. The list is wrapped with a single space on each end to facilitate finding matches within the list.
function classList(element) { return (' ' + (element.className || '') + ' ').replace(/\s+/gi, ' '); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function classList(element) {\n\t return (' ' + (element.className || '') + ' ').replace(/\\s+/gi, ' ');\n\t }", "function classList(element) {\n\t return (' ' + (element.className || '') + ' ').replace(/\\s+/gi, ' ');\n\t }", "function classList(element) {\n\t return (' ' + (element.className || '') + ' ').replace(/\\s+/gi, ' ');\n\t }", "function classList(element) {\n\t return (' ' + (element.className || '') + ' ').replace(/\\s+/gi, ' ');\n\t }", "function classList(element) {\n return (' ' + (element.className || '') + ' ').replace(/\\s+/gi, ' ');\n }", "function classList(element) {\n return (' ' + (element && element.className || '') + ' ').replace(/\\s+/gi, ' ');\n }", "function classList(element) {\n return (' ' + (element && element.className || '') + ' ').replace(/\\s+/gi, ' ');\n }", "function classList(element) {\n return (' ' + (element && element.className || '') + ' ').replace(/\\s+/gi, ' ');\n }", "get classList() {\n if (!this.hasAttribute(\"class\")) {\n return new DOMTokenList(null, null);\n }\n const classes = this.getAttribute(\"class\", true)\n .filter((attr) => attr.isStatic)\n .map((attr) => attr.value)\n .join(\" \");\n return new DOMTokenList(classes, null);\n }", "getClassNames() {\n let classNames = ['thread-ListItem'];\n\n return classNames.join(' ');\n }", "function _getClasses($el){\n var cls = $el.attr('class')\n if (cls)\n return cls.split(/\\s+/)\n return []\n }", "function effect_get_classes(element) {\n var str = $(element).attr('class');\n var stringArray = str.split(/(\\s+)/).filter( function(e) { return e.trim().length > 0; } );\n return stringArray;\n}", "function getClassList(element) {\n\tif (element.className && element.className != \"\") {\n\t\treturn element.className.split(' ');\n\t}\n\treturn [];\n}", "function get_classes(elem) {\n \"use strict\";\n return $(elem).attr('class').split(/\\s+/);\n}", "function classes() {\n var classes = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n classes[_i] = arguments[_i];\n }\n return classes.filter(function (c) { return !!c; }).join(' ');\n}", "function classes() {\n var classes = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n classes[_i] = arguments[_i];\n }\n return classes.filter(function (c) { return !!c; }).join(' ');\n}", "function classes() {\n var classes = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n classes[_i] = arguments[_i];\n }\n return classes.filter(function (c) { return !!c; }).join(' ');\n}", "function classList(classes) {\n return Object\n .entries(classes)\n .filter(entry => entry[1])\n .map(entry => entry[0])\n .join(' ');\n}", "function classNames(_classes) {\n var classes = [];\n var hasOwn = {}.hasOwnProperty;\n for (var i = 0; i < arguments.length; i++) {\n var arg = arguments[i];\n if (!arg)\n continue;\n var argType = typeof arg;\n if (argType === 'string' || argType === 'number') {\n classes.push(arg);\n }\n else if (Array.isArray(arg)) {\n classes.push(classNames.apply(null, arg));\n }\n else if (argType === 'object') {\n for (var key in arg) {\n if (hasOwn.call(arg, key) && arg[key]) {\n classes.push(key);\n }\n }\n }\n }\n return classes.join(' ');\n }", "function classNames() {\n\t\tvar classes = '';\n\t\tvar arg;\n\n\t\tfor (var i = 0; i < arguments.length; i++) {\n\t\t\targ = arguments[i];\n\t\t\tif (!arg) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif ('string' === typeof arg || 'number' === typeof arg) {\n\t\t\t\tclasses += ' ' + arg;\n\t\t\t} else if (Object.prototype.toString.call(arg) === '[object Array]') {\n\t\t\t\tclasses += ' ' + classNames.apply(null, arg);\n\t\t\t} else if ('object' === typeof arg) {\n\t\t\t\tfor (var key in arg) {\n\t\t\t\t\tif (!arg.hasOwnProperty(key) || !arg[key]) {\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tclasses += ' ' + key;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn classes.substr(1);\n\t}", "function classNames() {\n\t\tvar classes = '';\n\t\tvar arg;\n\n\t\tfor (var i = 0; i < arguments.length; i++) {\n\t\t\targ = arguments[i];\n\t\t\tif (!arg) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif ('string' === typeof arg || 'number' === typeof arg) {\n\t\t\t\tclasses += ' ' + arg;\n\t\t\t} else if (Object.prototype.toString.call(arg) === '[object Array]') {\n\t\t\t\tclasses += ' ' + classNames.apply(null, arg);\n\t\t\t} else if ('object' === typeof arg) {\n\t\t\t\tfor (var key in arg) {\n\t\t\t\t\tif (!arg.hasOwnProperty(key) || !arg[key]) {\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tclasses += ' ' + key;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn classes.substr(1);\n\t}", "function classNames() {\n\t\t\tvar classes = '';\n\t\t\tvar arg;\n\n\t\t\tfor (var i = 0; i < arguments.length; i++) {\n\t\t\t\targ = arguments[i];\n\t\t\t\tif (!arg) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tif ('string' === typeof arg || 'number' === typeof arg) {\n\t\t\t\t\tclasses += ' ' + arg;\n\t\t\t\t} else if (Object.prototype.toString.call(arg) === '[object Array]') {\n\t\t\t\t\tclasses += ' ' + classNames.apply(null, arg);\n\t\t\t\t} else if ('object' === typeof arg) {\n\t\t\t\t\tfor (var key in arg) {\n\t\t\t\t\t\tif (!arg.hasOwnProperty(key) || !arg[key]) {\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tclasses += ' ' + key;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn classes.substr(1);\n\t\t}", "function classNames() {\n\t\t\tvar classes = '';\n\t\t\tvar arg;\n\n\t\t\tfor (var i = 0; i < arguments.length; i++) {\n\t\t\t\targ = arguments[i];\n\t\t\t\tif (!arg) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tif ('string' === typeof arg || 'number' === typeof arg) {\n\t\t\t\t\tclasses += ' ' + arg;\n\t\t\t\t} else if (Object.prototype.toString.call(arg) === '[object Array]') {\n\t\t\t\t\tclasses += ' ' + classNames.apply(null, arg);\n\t\t\t\t} else if ('object' === typeof arg) {\n\t\t\t\t\tfor (var key in arg) {\n\t\t\t\t\t\tif (!arg.hasOwnProperty(key) || !arg[key]) {\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tclasses += ' ' + key;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn classes.substr(1);\n\t\t}", "function classNames() {\n\t\tvar classes = '';\n\t\tvar arg;\n\t\n\t\tfor (var i = 0; i < arguments.length; i++) {\n\t\t\targ = arguments[i];\n\t\t\tif (!arg) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\n\t\t\tif ('string' === typeof arg || 'number' === typeof arg) {\n\t\t\t\tclasses += ' ' + arg;\n\t\t\t} else if (Object.prototype.toString.call(arg) === '[object Array]') {\n\t\t\t\tclasses += ' ' + classNames.apply(null, arg);\n\t\t\t} else if ('object' === typeof arg) {\n\t\t\t\tfor (var key in arg) {\n\t\t\t\t\tif (!arg.hasOwnProperty(key) || !arg[key]) {\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tclasses += ' ' + key;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn classes.substr(1);\n\t}", "function classNames() {\n\t\tvar classes = '';\n\t\tvar arg;\n\t\n\t\tfor (var i = 0; i < arguments.length; i++) {\n\t\t\targ = arguments[i];\n\t\t\tif (!arg) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\n\t\t\tif ('string' === typeof arg || 'number' === typeof arg) {\n\t\t\t\tclasses += ' ' + arg;\n\t\t\t} else if (Object.prototype.toString.call(arg) === '[object Array]') {\n\t\t\t\tclasses += ' ' + classNames.apply(null, arg);\n\t\t\t} else if ('object' === typeof arg) {\n\t\t\t\tfor (var key in arg) {\n\t\t\t\t\tif (!arg.hasOwnProperty(key) || !arg[key]) {\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tclasses += ' ' + key;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn classes.substr(1);\n\t}", "function classNames() {\n\t\t\t\tvar classes = '';\n\t\t\t\tvar arg;\n\n\t\t\t\tfor (var i = 0; i < arguments.length; i++) {\n\t\t\t\t\targ = arguments[i];\n\t\t\t\t\tif (!arg) {\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\tif ('string' === typeof arg || 'number' === typeof arg) {\n\t\t\t\t\t\tclasses += ' ' + arg;\n\t\t\t\t\t} else if (Object.prototype.toString.call(arg) === '[object Array]') {\n\t\t\t\t\t\tclasses += ' ' + classNames.apply(null, arg);\n\t\t\t\t\t} else if ('object' === typeof arg) {\n\t\t\t\t\t\tfor (var key in arg) {\n\t\t\t\t\t\t\tif (!arg.hasOwnProperty(key) || !arg[key]) {\n\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tclasses += ' ' + key;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn classes.substr(1);\n\t\t\t}", "function classNames() {\n\tvar classes = '';\n\tvar arg;\n\n\tfor (var i = 0; i < arguments.length; i++) {\n\t\targ = arguments[i];\n\t\tif (!arg) {\n\t\t\tcontinue;\n\t\t}\n\n\t\tif ('string' === typeof arg || 'number' === typeof arg) {\n\t\t\tclasses += ' ' + arg;\n\t\t} else if (Object.prototype.toString.call(arg) === '[object Array]') {\n\t\t\tclasses += ' ' + classNames.apply(null, arg);\n\t\t} else if ('object' === typeof arg) {\n\t\t\tfor (var key in arg) {\n\t\t\t\tif (!arg.hasOwnProperty(key) || !arg[key]) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tclasses += ' ' + key;\n\t\t\t}\n\t\t}\n\t}\n\treturn classes.substr(1);\n}", "function classNames() {\n\tvar classes = '';\n\tvar arg;\n\n\tfor (var i = 0; i < arguments.length; i++) {\n\t\targ = arguments[i];\n\t\tif (!arg) {\n\t\t\tcontinue;\n\t\t}\n\n\t\tif ('string' === typeof arg || 'number' === typeof arg) {\n\t\t\tclasses += ' ' + arg;\n\t\t} else if (Object.prototype.toString.call(arg) === '[object Array]') {\n\t\t\tclasses += ' ' + classNames.apply(null, arg);\n\t\t} else if ('object' === typeof arg) {\n\t\t\tfor (var key in arg) {\n\t\t\t\tif (!arg.hasOwnProperty(key) || !arg[key]) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tclasses += ' ' + key;\n\t\t\t}\n\t\t}\n\t}\n\treturn classes.substr(1);\n}", "function elementComponentIdsFromClasses (element) {\n return (element.className || '').split(' ');\n }", "function classNames(CLASSES) {\n return function (attrs) {\n if (!attrs || (!attrs.class && !attrs.className)) {\n return;\n }\n var string = (attrs.class || attrs.className).trim();\n var split = string.split(' ');\n var str = '';\n for (var i = 0; i < split.length; i++) {\n var className = split[i];\n if (className) {\n var hash = CLASSES[className];\n str += ((hash == null) ? className : hash) + \" \";\n }\n }\n if (attrs.class) {\n attrs.class = str;\n }\n else {\n attrs.className = str;\n }\n };\n}", "function getClassNames() {\n let classNames = [];\n for (var i = 0; i < classList.length; i++) {\n classNames.push(classList[i].name);\n }\n getPointsToAdd(classNames);\n}", "function getClassList(type) {\n\t\t\tvar classList = davinci.ve.metadata.queryDescriptor(type, 'class');\n\t\t\tif (classList) {\n\t\t\t\tclassList = classList.split(/\\s+/);\n\t\t\t\tclassList.push(type);\n\t\t\t\treturn classList;\n\t\t\t}\n\t\t\treturn [type];\n\t\t}", "function classNames () {\n\t\t'use strict';\n\n\t\tvar classes = '';\n\n\t\tfor (var i = 0; i < arguments.length; i++) {\n\t\t\tvar arg = arguments[i];\n\t\t\tif (!arg) continue;\n\n\t\t\tvar argType = typeof arg;\n\n\t\t\tif ('string' === argType || 'number' === argType) {\n\t\t\t\tclasses += ' ' + arg;\n\n\t\t\t} else if (Array.isArray(arg)) {\n\t\t\t\tclasses += ' ' + classNames.apply(null, arg);\n\n\t\t\t} else if ('object' === argType) {\n\t\t\t\tfor (var key in arg) {\n\t\t\t\t\tif (arg.hasOwnProperty(key) && arg[key]) {\n\t\t\t\t\t\tclasses += ' ' + key;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn classes.substr(1);\n\t}", "function cleanClasses(classList) {\n classList = classList.replace(/\\s{2,}/g, ' ').trim();\n //remove single white space; hoping no css classes of 1 char exists\n if(classList.length === 1) classList = null;\n return classList;\n }", "function getClassesOfElement(element){\n var tab = [];\n for(var i =0; i< element.length;i++){\n tab.push(element[i]);\n }\n return tab;\n}", "function classes() {\n var classes = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n classes[_i] = arguments[_i];\n }\n return classes\n .map(function (c) { return c && typeof c === 'object' ? Object.keys(c).map(function (key) { return !!c[key] && key; }) : [c]; })\n .reduce(function (flattened, c) { return flattened.concat(c); }, [])\n .filter(function (c) { return !!c; })\n .join(' ');\n}", "getClasses() {\n let classes = ['indicator-pip'];\n\n if (this.props.final) {\n classes.push('final');\n }\n\n if (this.props.taken) {\n classes.push('taken');\n }\n\n return classes.join(' ');\n }", "function classNames(){for(var e=\"\",t,n=0;n<arguments.length;n++){if(!(t=arguments[n]))continue;if(\"string\"==typeof t||\"number\"==typeof t)e+=\" \"+t;else if(\"[object Array]\"===Object.prototype.toString.call(t))e+=\" \"+classNames.apply(null,t);else if(\"object\"==typeof t)for(var r in t){if(!t.hasOwnProperty(r)||!t[r])continue;e+=\" \"+r}}return e.substr(1)}", "function classNames(){for(var e=\"\",t,n=0;n<arguments.length;n++){if(!(t=arguments[n]))continue;if(\"string\"==typeof t||\"number\"==typeof t)e+=\" \"+t;else if(\"[object Array]\"===Object.prototype.toString.call(t))e+=\" \"+classNames.apply(null,t);else if(\"object\"==typeof t)for(var r in t){if(!t.hasOwnProperty(r)||!t[r])continue;e+=\" \"+r}}return e.substr(1)}", "function classNames(){for(var e=\"\",t,n=0;n<arguments.length;n++){if(!(t=arguments[n]))continue;if(\"string\"==typeof t||\"number\"==typeof t)e+=\" \"+t;else if(\"[object Array]\"===Object.prototype.toString.call(t))e+=\" \"+classNames.apply(null,t);else if(\"object\"==typeof t)for(var r in t){if(!t.hasOwnProperty(r)||!t[r])continue;e+=\" \"+r}}return e.substr(1)}", "function classNames(){for(var e=\"\",t,n=0;n<arguments.length;n++){if(!(t=arguments[n]))continue;if(\"string\"==typeof t||\"number\"==typeof t)e+=\" \"+t;else if(\"[object Array]\"===Object.prototype.toString.call(t))e+=\" \"+classNames.apply(null,t);else if(\"object\"==typeof t)for(var r in t){if(!t.hasOwnProperty(r)||!t[r])continue;e+=\" \"+r}}return e.substr(1)}", "function classNames(){for(var e=\"\",t,n=0;n<arguments.length;n++){if(!(t=arguments[n]))continue;if(\"string\"==typeof t||\"number\"==typeof t)e+=\" \"+t;else if(\"[object Array]\"===Object.prototype.toString.call(t))e+=\" \"+classNames.apply(null,t);else if(\"object\"==typeof t)for(var r in t){if(!t.hasOwnProperty(r)||!t[r])continue;e+=\" \"+r}}return e.substr(1)}", "function getClass(element) {\n return Array.from(element.classList);\n}", "get classList() {\n return this.element.classList\n }", "_getClassNames(_id) {\n const _elem = this._elements[_id];\n if (this._isSVGElem(_elem)) {\n return _elem.className.baseVal;\n }\n else {\n return _elem.className;\n }\n }", "_getClassNames(_id) {\n const _elem = this._elements[_id];\n if (this._isSVGElem(_elem)) {\n return _elem.className.baseVal;\n }\n else {\n return _elem.className;\n }\n }", "function setClassList(element, classlist) {\n\telement.className = classlist.join(' ');\n}", "get className() {\n return this.classList.toString();\n }", "get classes() {\n const result = {};\n const element = this.nativeElement;\n // SVG elements return an `SVGAnimatedString` instead of a plain string for the `className`.\n const className = element.className;\n const classes = typeof className !== 'string' ? className.baseVal.split(' ') : className.split(' ');\n classes.forEach((value) => result[value] = true);\n return result;\n }", "function get_classes_array(classes) {\n\n var classesArray = [];\n\n // Clean\n classes = $.trim(classes);\n\n // Clean multispaces\n classes = classes.replace(/\\s\\s+/g, ' ');\n\n // Check if still there have another class\n if (classes.indexOf(\" \") != -1) {\n\n // Split with space\n $.each(classes.split(\" \"), function (i, v) {\n\n // Clean\n v = $.trim(v);\n\n // Push\n classesArray.push(v);\n\n });\n\n } else {\n\n // Push if single.\n classesArray.push(classes);\n\n }\n\n return classesArray;\n\n }", "function classList(e) {\n if (e.classList) return e.classList; // Return e.classList if it exists\n else return new CSSClassList(e); // Otherwise try to fake it\n}", "getCSSClassesNames() {\n var classNames = 'article__textarea article__textarea--style';\n switch (this.state.cssCheck) {\n case 'OK':\n classNames += ' article__textarea--correct';\n break;\n case 'KO':\n classNames += ' article__textarea--wrong';\n break;\n default:\n classNames += ' article__textarea--idle';\n break;\n }\n return classNames;\n }", "function getStyleClasses( style ) {\n\t\tvar attrs = style.getDefinition().attributes,\n\t\t\tclasses = attrs && attrs[ 'class' ];\n\n\t\treturn classes ? classes.split( /\\s+/ ) : null;\n\t}", "function index_module_classNames() {\n var args = [];\n\n for (var _i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n }\n\n return args.filter(function (value) {\n if (typeof value === 'string' && value.length > 0) {\n return true;\n }\n\n return false;\n }).join(' ').trim();\n}", "function remClass(clist,cls) {\n\treturn fold(function(v, acc) {if(v != cls) return acc + (acc == '' ? '' : ' ') + v; else return acc;},'',clist.split(' '));\n}", "getClassNames(){return this.__classNames}", "function className(name) {\n\treturn document.getElementsByClassName(name);\n}", "function get_cleaned_classes(el, oldArray) {\n\n var resultArray = [];\n\n // Element Classes\n var classes = el.attr(\"class\");\n\n // Is defined?\n if (isDefined(classes)) {\n\n // Cleaning all Yellow Pencil classes.\n classes = class_cleaner(classes);\n\n // Clean spaces\n classes = space_cleaner(classes);\n\n // If not empty\n if (classes.length >= 1) {\n\n var classesArray = get_classes_array(classes);\n\n // Be sure there have more class then one.\n if (classesArray.length > 0) {\n\n // Each\n for (var io = 0; io < classesArray.length; io++) {\n\n // Clean spaces\n var that = space_cleaner(classesArray[io]);\n\n // continue If not have this class in data\n if (resultArray.indexOf(that) == -1 && oldArray.indexOf(that) == -1 && that.length >= 1) {\n\n // Push.\n resultArray.push(that);\n\n }\n\n }\n\n } else {\n\n // continue If not have this class in data\n if (resultArray.match(classes) == -1 && oldArray.indexOf(classes) == -1) {\n\n // Push\n resultArray.push(classes);\n\n } // If\n\n } // else\n\n } // not empty.\n\n } // IsDefined\n\n // return.\n return resultArray;\n\n }", "function getClass(obj) {\n return obj.className.split(/\\s+/);\n}", "set className(names) {\n for (const name of names.split(/ /)) {\n this.classList.add(name);\n }\n }", "function addClasses() {\r\n\t\t\t\tvar str, firstChar, spl, $this, hasPrefixes = (opts.prefixes.length > 0);\r\n\t\t\t\t$($list).children().each(function() {\r\n\t\t\t\t\t$this = $(this), firstChar = '', str = $.trim($this.text()).toLowerCase();\r\n\t\t\t\t\tif (str) {\r\n\t\t\t\t\t\tif (hasPrefixes) {\r\n\t\t\t\t\t\t\tspl = str.split(' ');\r\n\t\t\t\t\t\t\tif ((spl.length > 1) && ($.inArray(spl[0], opts.prefixes) > -1)) {\r\n\t\t\t\t\t\t\t\tfirstChar = spl[1].charAt(0);\r\n\t\t\t\t\t\t\t\taddLetterClass(firstChar, $this, true);\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\tfirstChar = str.charAt(0);\r\n\t\t\t\t\t\taddLetterClass(firstChar, $this);\r\n\t\t\t\t\t}\r\n\t\t\t\t});\r\n\t\t\t}", "function classList(props) {\n\t var _classes;\n\n\t var spin = props.spin,\n\t pulse = props.pulse,\n\t fixedWidth = props.fixedWidth,\n\t inverse = props.inverse,\n\t border = props.border,\n\t listItem = props.listItem,\n\t flip = props.flip,\n\t size = props.size,\n\t rotation = props.rotation,\n\t pull = props.pull; // map of CSS class names to properties\n\n\t var classes = (_classes = {\n\t 'fa-spin': spin,\n\t 'fa-pulse': pulse,\n\t 'fa-fw': fixedWidth,\n\t 'fa-inverse': inverse,\n\t 'fa-border': border,\n\t 'fa-li': listItem,\n\t 'fa-flip-horizontal': flip === 'horizontal' || flip === 'both',\n\t 'fa-flip-vertical': flip === 'vertical' || flip === 'both'\n\t }, _defineProperty(_classes, \"fa-\".concat(size), typeof size !== 'undefined' && size !== null), _defineProperty(_classes, \"fa-rotate-\".concat(rotation), typeof rotation !== 'undefined' && rotation !== null), _defineProperty(_classes, \"fa-pull-\".concat(pull), typeof pull !== 'undefined' && pull !== null), _defineProperty(_classes, 'fa-swap-opacity', props.swapOpacity), _classes); // map over all the keys in the classes object\n\t // return an array of the keys where the value for the key is not null\n\n\t return Object.keys(classes).map(function (key) {\n\t return classes[key] ? key : null;\n\t }).filter(function (key) {\n\t return key;\n\t });\n\t}", "function css() {\n var args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n }\n var classes = [];\n for (var _a = 0, args_1 = args; _a < args_1.length; _a++) {\n var arg = args_1[_a];\n if (arg) {\n if (typeof arg === 'string') {\n classes.push(arg);\n }\n else if (arg.hasOwnProperty('toString') && typeof arg.toString === 'function') {\n classes.push(arg.toString());\n }\n else {\n // tslint:disable-next-line:no-any\n for (var key in arg) {\n // tslint:disable-next-line:no-any\n if (arg[key]) {\n classes.push(key);\n }\n }\n }\n }\n }\n return classes.join(' ');\n}", "function css() {\n var args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n }\n var classes = [];\n for (var _a = 0, args_1 = args; _a < args_1.length; _a++) {\n var arg = args_1[_a];\n if (arg) {\n if (typeof arg === 'string') {\n classes.push(arg);\n }\n else if (arg.hasOwnProperty('toString') && typeof arg.toString === 'function') {\n classes.push(arg.toString());\n }\n else {\n // tslint:disable-next-line:no-any\n for (var key in arg) {\n // tslint:disable-next-line:no-any\n if (arg[key]) {\n classes.push(key);\n }\n }\n }\n }\n }\n return classes.join(' ');\n}", "function getClassStr(classes) {\n var str = '';\n\n for( var i = 0; i < classes.length; i++ ) {\n var className = classes[i];\n str += className;\n if(i !== classes.length - 1) {\n str += ' ';\n }\n }\n\n return str;\n }", "showClasses(classElements) {\n const props = this.props\n classElements.forEach(item => {\n props.classListElement.appendChild(item)\n })\n }", "function css() {\n var args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n }\n var classes = [];\n for (var _a = 0, args_1 = args; _a < args_1.length; _a++) {\n var arg = args_1[_a];\n if (arg) {\n if (typeof arg === 'string') {\n classes.push(arg);\n }\n else if (arg.hasOwnProperty('toString') && typeof arg.toString === 'function') {\n classes.push(arg.toString());\n }\n else {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n for (var key in arg) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n if (arg[key]) {\n classes.push(key);\n }\n }\n }\n }\n }\n return classes.join(' ');\n}" ]
[ "0.8214511", "0.8214511", "0.8214511", "0.8214511", "0.81789786", "0.8097902", "0.80877435", "0.80877435", "0.79918617", "0.7832867", "0.7622634", "0.7500801", "0.7420251", "0.72718614", "0.70544827", "0.70544827", "0.70544827", "0.69790417", "0.69193625", "0.6815024", "0.6815024", "0.6800837", "0.6800837", "0.6772637", "0.6772637", "0.67717934", "0.6766965", "0.6766965", "0.6753591", "0.67133135", "0.6703748", "0.66781497", "0.667179", "0.6643274", "0.6561606", "0.65461344", "0.65296215", "0.65057325", "0.65057325", "0.65057325", "0.65057325", "0.65057325", "0.647235", "0.6419066", "0.6409483", "0.6409483", "0.64076144", "0.6356303", "0.6352049", "0.63436514", "0.63156253", "0.63058037", "0.6304863", "0.62902296", "0.62857956", "0.6278985", "0.6268997", "0.62499714", "0.62288636", "0.62273383", "0.6201966", "0.61718386", "0.6169585", "0.6169585", "0.6154306", "0.61490095", "0.6146647" ]
0.8207224
33
(Internal) Removes an element from the DOM.
function removeElement(element) { element && element.parentNode && element.parentNode.removeChild(element); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "removeElement() {\n this.el.parentNode.removeChild(this.el);\n }", "static deleteDomElement(element) {\n element.parentNode.removeChild(element);\n }", "function removeElement(elem){ if (elem) elem.parentNode.removeChild(elem) }", "function removeElement(elem){ if (elem) elem.parentNode.removeChild(elem) }", "remove() {\n this.element.remove();\n }", "remove() {\n try { this.element.remove(); }\n catch (e) {}\n }", "function removeElement() {\n if(this instanceof HTMLCollection || this instanceof NodeList) {\n for(var i = 0; i < this.length; i++) {\n this[i].parentNode.removeChild(this);\n }\n }\n else if(this instanceof HTMLElement) {\n this.parentNode.removeChild(this);\n }\n }", "function removeElement(element) {\n\n element.outerHTML = \"\";\n delete element;\n\n}", "function removeElement(element) {\n element.parentNode.removeChild(element);\n}", "function removeElement (el) {\n if (el.parentNode) {\n el.parentNode.removeChild(el);\n }\n }", "function removeElement(elem) {\n\telem.parentNode.removeChild(elem);\n}", "remove () {\n $(this.element).remove ();\n }", "function removeElement(elm) {\n elm.parentNode.removeChild(elm);\n}", "function removeElement(elem) {\r\n\telem.parentNode.removeChild(elem);\r\n}", "function removeDeletedElementFromDOM(domElement){\n domElement.remove();\n }", "function removeElement(selector) {\n$(selector).remove();\n}", "function removeElement(element) {\n element.parentElement.removeChild(element);\n}", "function removeElement(element) {\n\t element && element.parentNode && element.parentNode.removeChild(element);\n\t }", "function removeElement(element) {\n\t element && element.parentNode && element.parentNode.removeChild(element);\n\t }", "function removeElement(element) {\n\t element && element.parentNode && element.parentNode.removeChild(element);\n\t }", "function removeElement(element) {\n\t element && element.parentNode && element.parentNode.removeChild(element);\n\t }", "function removeElement (element) {\n if(element != null)\n //Does not work (improperly used)\n //$($pageDiv).remove(element);\n //Thes two work for some reason\n element.remove();\n //pageDivElem.removeChild(element);\n}", "function Remove( Element ) {\r\n Element.parentNode.removeChild( Element );\r\n}", "remove() {\n this.#el.remove();\n }", "function removeElement(elementId) {\n var myNode = document.getElementById(elementId);\n myNode.innerHTML = '';\n}", "function remove(element) {\n element.parentNode.removeChild(element);\n\n}", "function remove(el) {\r\n el.parentNode.removeChild(el);\r\n }", "function removeElement(element) {\n element && element.parentNode && element.parentNode.removeChild(element);\n }", "function removeElement(element) {\n element && element.parentNode && element.parentNode.removeChild(element);\n }", "function removeElement(element) {\n element && element.parentNode && element.parentNode.removeChild(element);\n }", "remove() {\n\t\tif (this.$element) {\n\t\t\tthis.$element.remove();\n\t\t}\n\t}", "function remove(el) {\n var parent = el.parentNode;\n\n if (parent) {\n parent.removeChild(el);\n }\n } // @function empty(el: HTMLElement)", "function removeElement(selector) {\n const el = document.querySelector(selector);\n if (el) el.parentElement.removeChild(el);\n }", "function removeElement(elementId) {\n // Removes an html element from the document\n var element = document.getElementById(elementId);\n element.parentNode.removeChild(element);\n}", "remove() {\n\t\tthis.outerElement.style.display = \"none\";\n\t\tthis.removed = true;\n\t}", "function removeElement(element) {\n element && element.parentNode && element.parentNode.removeChild(element);\n}", "function removeElement(el) {\n if (typeof el.remove !== 'undefined') {\n el.remove()\n } else {\n el.parentNode.removeChild(el)\n }\n}", "function removeElement(node) {\n\tif (typeof node.remove === \"function\") {\n\t\tnode.remove();\n\t} else if (node.parentNode) {\n\t\tnode.parentNode.removeChild(node);\n\t}\n}", "function removeElement(item) {\n container.removeChild(item);\n}", "removeElement(element) {\n this.node.removeChild(element.node);\n return this;\n }", "function clearElement(elem) {\n\t//console.log(elem);\n\tif (isString(elem)) elem = document.getElementById(elem);\n\tif (window.jQuery == undefined) { elem.innerHTML = ''; return elem; }\n\twhile (elem.firstChild) {\n\t\t$(elem.firstChild).remove();\n\t}\n\treturn elem;\n}", "remove () {\n this.html.remove();\n }", "function removeElement(elementId) {\n var element = document.getElementById(elementId);\n element.parentNode.removeChild(element);\n}", "function removeElement(elementId) {\n var element = document.getElementById(elementId);\n element.parentNode.removeChild(element);\n}", "function removeElement(e) {\n $(e.currentTarget).remove();\n}", "function removeElementById(id) {\n\tlet existingElement = document.getElementById(id);\n\tif(existingElement !== null) {\n\t\texistingElement.outerHTML = '';\n\t}\n}", "function deleteElement(element){\n\telement.parentNode.remove(element.parentElement);\n}", "function removeElement(elementId) {\n // Removes an element from the document\n let element = document.getElementById(elementId);\n if(element.parentNode != null)\n element.parentNode.removeChild(element);\n}", "function removeElement(ElementXpath)\r\n {\r\n var alltags = document.evaluate(ElementXpath,document,null,XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE,null);\r\n for (i=0; i<alltags.snapshotLength; i++)\r\n {\r\n element = alltags.snapshotItem(i);\r\n element.parentNode.removeChild(element); // Remove this element from its parent.\r\n }\r\n }", "function eliminar(elemento){\n elemento.parentNode.remove();\n}", "function Display_removeElement(_parent, _child) {\n\t_parent.removeChild(_child);\n}", "remove() {\n if (this.div) {\n this.div.parentNode.removeChild(this.div);\n this.div = null;\n }\n }", "function domClear(el, index) {\n var nodes = el.childNodes,\n curr = nodes.length;\n while (curr > index) el.removeChild(nodes[--curr]);\n return el;\n }", "remove() {\r\n manipulation_1.removeClausedNodeChild(this);\r\n }", "function removeElement(elementId) {\n // Removes an element from the document\n var element = document.getElementById(elementId);\n console.log(elementId);\n element.parentNode.removeChild(element);\n}", "function removeElement(elementId)\n{\n var checkElement = document.getElementById(elementId);\n if (checkElement!==null)\n {\n checkElement.parentNode.removeChild(checkElement);\n }\n}", "function domClear(el, index) {\n var nodes = el.childNodes,\n curr = nodes.length;\n while (curr > index) el.removeChild(nodes[--curr]);\n return el;\n}", "function domClear(el, index) {\n var nodes = el.childNodes,\n curr = nodes.length;\n while (curr > index) el.removeChild(nodes[--curr]);\n return el;\n}", "function removeElement(element) {\n while (element.lastChild) {\n element.removeChild(element.lastChild);\n }\n}", "del(_id) {\n const _elem = this._elements[_id];\n const i = this._elemTodo.indexOf(_id);\n if (i !== -1) {\n this._elemTodo.splice(i, 1);\n }\n delete this._styleCache[_id];\n delete this._elemTodoH[_id];\n delete this._elements[_id];\n this._freeElemIds.push(_id);\n const _parent = _elem.parentNode;\n if (_parent) {\n _parent.removeChild(_elem);\n }\n else {\n console.warn('ELEM.del(', _id,\n '): Invalid parent: ', _parent,\n 'for elem:', _elem);\n }\n }", "del(_id) {\n const _elem = this._elements[_id];\n const i = this._elemTodo.indexOf(_id);\n if (i !== -1) {\n this._elemTodo.splice(i, 1);\n }\n delete this._styleCache[_id];\n delete this._elemTodoH[_id];\n delete this._elements[_id];\n this._freeElemIds.push(_id);\n const _parent = _elem.parentNode;\n if (_parent) {\n _parent.removeChild(_elem);\n }\n else {\n console.warn('ELEM.del(', _id,\n '): Invalid parent: ', _parent,\n 'for elem:', _elem);\n }\n }", "function removeItem(elementId)\n{\n document.getElementById(elementId).remove()\n}", "function remove_element() {\n let element = document.getElementById(\"reading_time_element\");\n element.parentNode.removeChild(element);\n}", "function clearElement(element) {\n while (element.childNodes.length > 0) {\n element.removeChild(element.childNodes[0]);\n }\n }", "function remove(el) {\n\t if (!el) return;\n\t var p = el.parentNode;\n\t if (p) {\n\t p.removeChild(el);\n\t if (!p.childNodes || !p.childNodes.length) remove(p);\n\t }\n\t}", "function deleteItem(element){\n element.parentNode.remove();\n}" ]
[ "0.77578187", "0.7495747", "0.7429648", "0.7429648", "0.7335784", "0.7306875", "0.7275354", "0.7228177", "0.71998936", "0.71019304", "0.70701003", "0.7066649", "0.70618546", "0.7054232", "0.7050688", "0.6950629", "0.6940447", "0.6923647", "0.6923647", "0.6923647", "0.6923647", "0.690903", "0.6906823", "0.6888238", "0.6875881", "0.68559414", "0.6848587", "0.6841186", "0.6841186", "0.6841186", "0.6811087", "0.6789638", "0.6775701", "0.6768236", "0.67564714", "0.6680866", "0.66778195", "0.66439843", "0.6628751", "0.661288", "0.6606616", "0.65942764", "0.655294", "0.655294", "0.6536075", "0.6522195", "0.6500078", "0.6490649", "0.6467248", "0.6465824", "0.6463295", "0.6449399", "0.6387701", "0.6386849", "0.63798857", "0.6373397", "0.63559884", "0.63559884", "0.6350576", "0.63435715", "0.63435715", "0.6334857", "0.6329708", "0.6327114", "0.6319332", "0.6312035" ]
0.6841415
55
Ecma International makes this code available under the terms and conditions set forth on (the "Use Terms"). Any redistribution of this code must retain the above copyright and this notice and otherwise comply with the Use Terms. / es5id: 15.2.3.54285 description: > Object.create one property in 'Properties' is a Date object that uses Object's [[Get]] method to access the 'set' property (8.10.5 step 8.a) includes: [runTestCase.js]
function testcase() { var dateObj = new Date(); var data = "data"; dateObj.set = function (value) { data = value; }; var newObj = Object.create({}, { prop: dateObj }); var hasProperty = newObj.hasOwnProperty("prop"); newObj.prop = "overrideData"; return hasProperty && data === "overrideData"; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function testcase() {\n function base() {}\n var b = new base();\n var prop = new Object();\n var d = Object.create(b);\n\n if (typeof d === 'object') {\n return true;\n }\n }", "static createProperty(e,t=defaultPropertyDeclaration){// Do not generate an accessor if the prototype already has one, since\n// it would be lost otherwise and that would never be the user's intention;\n// Instead, we expect users to call `requestUpdate` themselves from\n// user-defined accessors. Note that if the super has an accessor we will\n// still overwrite it\nif(this._ensureClassProperties(),this._classProperties.set(e,t),t.noAccessor||this.prototype.hasOwnProperty(e))return;const n=\"symbol\"==typeof e?Symbol():`__${e}`;Object.defineProperty(this.prototype,e,{// tslint:disable-next-line:no-any no symbol in index\nget(){return this[n]},set(t){const r=this[e];this[n]=t,this._requestUpdate(e,r)},configurable:!0,enumerable:!0})}", "static getNewProperties() {\n return {};\n }", "function getTest() {\n var proto = { inherited: 'inherited' };\n var obj = Object.create(proto, {\n own: { value: 'own' },\n magic: {\n get: function() { print('get'); return 'magic'; }\n }\n });\n\n // Reflect.get() looks at own as well as inherited properties.\n print(Reflect.get(obj, 'own'));\n print(Reflect.get(obj, 'inherited'));\n\n // It also invokes getters.\n print(Reflect.get(obj, 'magic'));\n\n // Nonexistent properties return 'undefined' as you'd expect.\n print(Reflect.get(obj, 'nonexistent'));\n}", "static createProperty(name,options=defaultPropertyDeclaration){// Note, since this can be called by the `@property` decorator which\n// is called before `finalize`, we ensure storage exists for property\n// metadata.\nthis._ensureClassProperties();this._classProperties.set(name,options);// Do not generate an accessor if the prototype already has one, since\n// it would be lost otherwise and that would never be the user's intention;\n// Instead, we expect users to call `requestUpdate` themselves from\n// user-defined accessors. Note that if the super has an accessor we will\n// still overwrite it\nif(options.noAccessor||this.prototype.hasOwnProperty(name)){return}const key=\"symbol\"===typeof name?Symbol():`__${name}`;Object.defineProperty(this.prototype,name,{// tslint:disable-next-line:no-any no symbol in index\nget(){return this[key]},set(value){const oldValue=this[name];this[key]=value;this._requestUpdate(name,oldValue)},configurable:!0,enumerable:!0})}", "function PropertyDate(id, date) {\n this._id = id;\n this._date = date;\n this._properties = [];\n}", "function makeObj() {\n return {\n propA: 10,\n propB: 20,\n };\n}", "function testcase() {\n var o = {};\n\n var desc = { value: 1 };\n Object.defineProperty(o, \"foo\", desc);\n \n var propDesc = Object.getOwnPropertyDescriptor(o, \"foo\");\n \n if (propDesc.value === 1 && // this is the value that was set\n propDesc.writable === false && // false by default\n propDesc.enumerable === false && // false by default\n propDesc.configurable === false) { // false by default\n return true;\n }\n }", "function canDefineNonEnumerableProperties() {\n var testObj = {};\n var testPropName = \"t\";\n\n try {\n Object.defineProperty(testObj, testPropName, {\n enumerable: false,\n value: testObj\n });\n\n for (var k in testObj) {\n if (k === testPropName) {\n return false;\n }\n }\n } catch (e) {\n return false;\n }\n\n return testObj[testPropName] === testObj;\n }", "function create(prototype, properties) {\n\t var object;\n\t if (prototype === null) {\n\t object = { '__proto__' : null };\n\t }\n\t else {\n\t if (typeof prototype !== 'object') {\n\t throw new TypeError(\n\t 'typeof prototype[' + (typeof prototype) + '] != \\'object\\''\n\t );\n\t }\n\t var Type = function () {};\n\t Type.prototype = prototype;\n\t object = new Type();\n\t object.__proto__ = prototype;\n\t }\n\t if (typeof properties !== 'undefined' && Object.defineProperties) {\n\t Object.defineProperties(object, properties);\n\t }\n\t return object;\n\t}", "function create(prototype, properties) {\n\t var object;\n\t if (prototype === null) {\n\t object = { '__proto__' : null };\n\t }\n\t else {\n\t if (typeof prototype !== 'object') {\n\t throw new TypeError(\n\t 'typeof prototype[' + (typeof prototype) + '] != \\'object\\''\n\t );\n\t }\n\t var Type = function () {};\n\t Type.prototype = prototype;\n\t object = new Type();\n\t object.__proto__ = prototype;\n\t }\n\t if (typeof properties !== 'undefined' && Object.defineProperties) {\n\t Object.defineProperties(object, properties);\n\t }\n\t return object;\n\t}", "function test() {\n var obj = {};\n var pd;\n\n Object.defineProperty(obj, 'prop1', {\n set: function() { print('prop1 set'); }\n });\n\n Object.defineProperty(obj, 'prop2', {\n get: function() { print('prop2 get'); }\n });\n\n function printDesc(prop) {\n pd = Object.getOwnPropertyDescriptor(obj, prop);\n print('set', 'set' in pd, typeof pd.set);\n print('get', 'get' in pd, typeof pd.get);\n print('enumerable', 'enumerable' in pd, typeof pd.enumerable, pd.enumerable);\n print('configurable', 'configurable' in pd, typeof pd.configurable, pd.configurable);\n }\n\n printDesc('prop1');\n printDesc('prop2');\n}", "function testcase() {\n var obj = {};\n var firstArg = 12;\n var secondArg = 12;\n\n var setFunc = function (a, b) {\n firstArg = a;\n secondArg = b;\n };\n Object.defineProperty(obj, \"prop\", {\n set: setFunc\n });\n obj.prop = 100;\n var desc = Object.getOwnPropertyDescriptor(obj, \"prop\");\n\n return obj.hasOwnProperty(\"prop\") && desc.set === setFunc && firstArg === 100 && typeof secondArg === \"undefined\";\n }", "makeProp(prop, value) {\n\t\tObject.defineProperty(this, prop, {\n\t\t\tvalue,\n\t\t\tenumerable: false,\n\t\t\twritable: true,\n\t\t\tconfigurable: true\n\t\t});\n\t}", "function objectName(prperty1, property2) {\n let objectName = Object.create(objectName.prototype);\n\n objectName.property1 = \"test\";\n objectName.property2 = \"test2\";\n\n objectName.prototype.doSomething1 = function name(params) {\n console.log(\"do something1\");\n };\n objectName.prototype.doSomething2 = function name(params) {\n console.log(\"do something2\");\n }\n return objectName;\n}", "function prop (start,end,tabmonth) {\nvar scriptProperties = PropertiesService.getScriptProperties();\n var newProperties = {start_date:start,end_date:end,tab:tabmonth};\nscriptProperties.setProperties(newProperties);\nvar test=1;\n}", "function callCreate(object){ object.create(); }", "static createRandomObject() {\n let o = new TestClass();\n o.value4 = new Date();\n o.value1 = o.value4.toDateString() + \"_\" + TestClass.counter.toString();\n o.value2 = o.value4.getMilliseconds() + TestClass.counter;\n let rnd;\n o.value3 = new Array(5);\n for (let i = 0; i < 5; i++) {\n rnd = Math.random();\n if (rnd > 0.5) {\n o.value3[i] = true;\n }\n else {\n o.value3[i] = false;\n }\n }\n TestClass.counter++;\n return o;\n }", "function VerifyToPropertyKey(key) {\n var obj = {};\n console.log(obj.hasOwnProperty(key));\n\n try {\n Object.defineProperty(obj, key, {\n value: 'something',\n enumerable: true\n });\n } catch (e) {\n ;\n }\n\n console.log(obj.hasOwnProperty(key));\n console.log(obj.propertyIsEnumerable(key));\n console.log(undefined, Object.getOwnPropertyDescriptor(obj, key));\n obj = {};\n\n obj.__defineGetter__(key, () => {\n return 2;\n });\n\n console.log(obj.hasOwnProperty(key));\n obj = {};\n\n obj.__defineSetter__(key, () => {\n return 2;\n });\n\n console.log(obj.hasOwnProperty(key));\n var count = 0;\n obj = Object.defineProperty({}, key, {\n set(v) {\n console.log(v);\n count++;\n }\n\n });\n\n var set = obj.__lookupSetter__(key);\n\n console.log('function', typeof set);\n set('abc');\n console.log(1, count);\n obj = Object.defineProperty({}, key, {\n get() {\n return 'abc';\n }\n\n });\n\n var get = obj.__lookupGetter__(key);\n\n console.log('function', typeof get);\n console.log('abc', get());\n obj = {};\n\n try {\n Reflect.set(obj, key, 'abc');\n } catch (e) {\n ;\n }\n\n console.log('abc', Reflect.get(obj, key));\n console.log(Reflect.deleteProperty(obj, key));\n console.log(Reflect.has(obj, key));\n\n try {\n Reflect.defineProperty(obj, key, {\n value: 'def',\n enumerable: true\n });\n } catch (e) {\n ;\n }\n\n console.log('def', Reflect.get(obj, key));\n console.log(undefined, Reflect.getOwnPropertyDescriptor(obj, key));\n obj = {};\n\n try {\n obj[key] = 123;\n } catch (e) {\n ;\n }\n\n console.log(123, obj[key]);\n console.log(obj.hasOwnProperty(key));\n}", "function testConstructString() {\r\n\tvar prop1 = new ORYX.Core.StencilSet.Property(jsonPropString, \"testNS\", stencil);\r\n\tassertEquals(\"testid\", prop1.id());\r\n\tassertEquals(\"string\", prop1.type());\r\n\tassertEquals(\"oryx\", prop1.prefix());\r\n\tassertEquals(\"testTitle\", prop1.title());\r\n\tassertEquals(\"testValue\", prop1.value());\r\n\tassertEquals(\"testDescription\", prop1.description());\r\n\tassertEquals(false, prop1.readonly());\r\n\tassertEquals(true, prop1.optional());\r\n\tassertEquals(\"testRef\", prop1.refToView()[0]);\r\n\tassertEquals(100, prop1.length());\r\n\tassertEquals(true, prop1.wrapLines());\r\n}", "function createAttrsNativeProps( properties, attrSpecs ){\n\t if( properties === false ){\n\t return {};\n\t }\n\t\n\t properties || ( properties = {} );\n\t\n\t return Object.transform( properties, attrSpecs, function( attrSpec, name ){\n\t if( !properties[ name ] && attrSpec.createPropertySpec ){\n\t return attrSpec.createPropertySpec();\n\t }\n\t } );\n\t}", "create() {}", "create() {}", "function create(prototype, properties) {\n var object;\n if (prototype === null) {\n object = { '__proto__' : null };\n }\n else {\n if (typeof prototype !== 'object') {\n throw new TypeError(\n 'typeof prototype[' + (typeof prototype) + '] != \\'object\\''\n );\n }\n var Type = function () {};\n Type.prototype = prototype;\n object = new Type();\n object.__proto__ = prototype;\n }\n if (typeof properties !== 'undefined' && Object.defineProperties) {\n Object.defineProperties(object, properties);\n }\n return object;\n}", "function create(prototype, properties) {\n var object;\n if (prototype === null) {\n object = { '__proto__' : null };\n }\n else {\n if (typeof prototype !== 'object') {\n throw new TypeError(\n 'typeof prototype[' + (typeof prototype) + '] != \\'object\\''\n );\n }\n var Type = function () {};\n Type.prototype = prototype;\n object = new Type();\n object.__proto__ = prototype;\n }\n if (typeof properties !== 'undefined' && Object.defineProperties) {\n Object.defineProperties(object, properties);\n }\n return object;\n}", "function create(prototype, properties) {\n var object;\n if (prototype === null) {\n object = { '__proto__' : null };\n }\n else {\n if (typeof prototype !== 'object') {\n throw new TypeError(\n 'typeof prototype[' + (typeof prototype) + '] != \\'object\\''\n );\n }\n var Type = function () {};\n Type.prototype = prototype;\n object = new Type();\n object.__proto__ = prototype;\n }\n if (typeof properties !== 'undefined' && Object.defineProperties) {\n Object.defineProperties(object, properties);\n }\n return object;\n}", "function create(prototype, properties) {\n var object;\n if (prototype === null) {\n object = { '__proto__' : null };\n }\n else {\n if (typeof prototype !== 'object') {\n throw new TypeError(\n 'typeof prototype[' + (typeof prototype) + '] != \\'object\\''\n );\n }\n var Type = function () {};\n Type.prototype = prototype;\n object = new Type();\n object.__proto__ = prototype;\n }\n if (typeof properties !== 'undefined' && Object.defineProperties) {\n Object.defineProperties(object, properties);\n }\n return object;\n}", "function create(prototype, properties) {\n var object;\n if (prototype === null) {\n object = { '__proto__' : null };\n }\n else {\n if (typeof prototype !== 'object') {\n throw new TypeError(\n 'typeof prototype[' + (typeof prototype) + '] != \\'object\\''\n );\n }\n var Type = function () {};\n Type.prototype = prototype;\n object = new Type();\n object.__proto__ = prototype;\n }\n if (typeof properties !== 'undefined' && Object.defineProperties) {\n Object.defineProperties(object, properties);\n }\n return object;\n}", "function create(prototype, properties) {\n var object;\n if (prototype === null) {\n object = { '__proto__' : null };\n }\n else {\n if (typeof prototype !== 'object') {\n throw new TypeError(\n 'typeof prototype[' + (typeof prototype) + '] != \\'object\\''\n );\n }\n var Type = function () {};\n Type.prototype = prototype;\n object = new Type();\n object.__proto__ = prototype;\n }\n if (typeof properties !== 'undefined' && Object.defineProperties) {\n Object.defineProperties(object, properties);\n }\n return object;\n}", "function create(prototype, properties) {\n var object;\n if (prototype === null) {\n object = { '__proto__' : null };\n }\n else {\n if (typeof prototype !== 'object') {\n throw new TypeError(\n 'typeof prototype[' + (typeof prototype) + '] != \\'object\\''\n );\n }\n var Type = function () {};\n Type.prototype = prototype;\n object = new Type();\n object.__proto__ = prototype;\n }\n if (typeof properties !== 'undefined' && Object.defineProperties) {\n Object.defineProperties(object, properties);\n }\n return object;\n}", "function create(prototype, properties) {\n var object;\n if (prototype === null) {\n object = { '__proto__' : null };\n }\n else {\n if (typeof prototype !== 'object') {\n throw new TypeError(\n 'typeof prototype[' + (typeof prototype) + '] != \\'object\\''\n );\n }\n var Type = function () {};\n Type.prototype = prototype;\n object = new Type();\n object.__proto__ = prototype;\n }\n if (typeof properties !== 'undefined' && Object.defineProperties) {\n Object.defineProperties(object, properties);\n }\n return object;\n}", "function create(prototype, properties) {\n var object;\n if (prototype === null) {\n object = { '__proto__' : null };\n }\n else {\n if (typeof prototype !== 'object') {\n throw new TypeError(\n 'typeof prototype[' + (typeof prototype) + '] != \\'object\\''\n );\n }\n var Type = function () {};\n Type.prototype = prototype;\n object = new Type();\n object.__proto__ = prototype;\n }\n if (typeof properties !== 'undefined' && Object.defineProperties) {\n Object.defineProperties(object, properties);\n }\n return object;\n}", "function create(prototype, properties) {\n var object;\n if (prototype === null) {\n object = { '__proto__' : null };\n }\n else {\n if (typeof prototype !== 'object') {\n throw new TypeError(\n 'typeof prototype[' + (typeof prototype) + '] != \\'object\\''\n );\n }\n var Type = function () {};\n Type.prototype = prototype;\n object = new Type();\n object.__proto__ = prototype;\n }\n if (typeof properties !== 'undefined' && Object.defineProperties) {\n Object.defineProperties(object, properties);\n }\n return object;\n}", "function create(prototype, properties) {\n var object;\n if (prototype === null) {\n object = { '__proto__' : null };\n }\n else {\n if (typeof prototype !== 'object') {\n throw new TypeError(\n 'typeof prototype[' + (typeof prototype) + '] != \\'object\\''\n );\n }\n var Type = function () {};\n Type.prototype = prototype;\n object = new Type();\n object.__proto__ = prototype;\n }\n if (typeof properties !== 'undefined' && Object.defineProperties) {\n Object.defineProperties(object, properties);\n }\n return object;\n}", "function create(prototype, properties) {\n var object;\n if (prototype === null) {\n object = { '__proto__' : null };\n }\n else {\n if (typeof prototype !== 'object') {\n throw new TypeError(\n 'typeof prototype[' + (typeof prototype) + '] != \\'object\\''\n );\n }\n var Type = function () {};\n Type.prototype = prototype;\n object = new Type();\n object.__proto__ = prototype;\n }\n if (typeof properties !== 'undefined' && Object.defineProperties) {\n Object.defineProperties(object, properties);\n }\n return object;\n}", "function create(prototype, properties) {\n var object;\n if (prototype === null) {\n object = { '__proto__' : null };\n }\n else {\n if (typeof prototype !== 'object') {\n throw new TypeError(\n 'typeof prototype[' + (typeof prototype) + '] != \\'object\\''\n );\n }\n var Type = function () {};\n Type.prototype = prototype;\n object = new Type();\n object.__proto__ = prototype;\n }\n if (typeof properties !== 'undefined' && Object.defineProperties) {\n Object.defineProperties(object, properties);\n }\n return object;\n}", "function CreateDataProperty(O, P, V) { // eslint-disable-line no-unused-vars\n\t\t// 1. Assert: Type(O) is Object.\n\t\t// 2. Assert: IsPropertyKey(P) is true.\n\t\t// 3. Let newDesc be the PropertyDescriptor{ [[Value]]: V, [[Writable]]: true, [[Enumerable]]: true, [[Configurable]]: true }.\n\t\tvar newDesc = {\n\t\t\tvalue: V,\n\t\t\twritable: true,\n\t\t\tenumerable: true,\n\t\t\tconfigurable: true\n\t\t};\n\t\t// 4. Return ? O.[[DefineOwnProperty]](P, newDesc).\n\t\ttry {\n\t\t\tObject.defineProperty(O, P, newDesc);\n\t\t\treturn true;\n\t\t} catch (e) {\n\t\t\treturn false;\n\t\t}\n\t}", "static get properties() {\n return {\n prop1: {type: String}\n };\n }", "function dataViewConstructorPropertiesTest() {\n var props = [\n 'name',\n 'length',\n 'prototype'\n ];\n\n props.forEach(function (propname) {\n try {\n var obj = DataView;\n var val = obj[propname];\n print(propname, propname in obj, typeof val, encValue(val));\n } catch (e) {\n print(e.stack || e);\n }\n });\n\n print(DataView.prototype.constructor === DataView);\n}", "function test() {\n var obj = {};\n Object.defineProperty(obj, 'prop', {\n get: Math.random,\n set: function() { throw Error('setter'); }\n });\n\n var val = obj.prop;\n if (typeof val === 'number') {\n print('val is a number');\n } else {\n print('val is not a number');\n }\n}", "function CreateMethodProperty(O, P, V) { // eslint-disable-line no-unused-vars\n\t// 1. Assert: Type(O) is Object.\n\t// 2. Assert: IsPropertyKey(P) is true.\n\t// 3. Let newDesc be the PropertyDescriptor{[[Value]]: V, [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: true}.\n\tvar newDesc = {\n\t\tvalue: V,\n\t\twritable: true,\n\t\tenumerable: false,\n\t\tconfigurable: true\n\t};\n\t// 4. Return ? O.[[DefineOwnProperty]](P, newDesc).\n\tObject.defineProperty(O, P, newDesc);\n}", "function property(value, isWritable, isEnumberable) {\n return {\n enumerable: isEnumberable || true,\n writable: isWritable || false,\n value: value\n };\n}", "function CreateMethodProperty(O, P, V) { // eslint-disable-line no-unused-vars\n\t\t// 1. Assert: Type(O) is Object.\n\t\t// 2. Assert: IsPropertyKey(P) is true.\n\t\t// 3. Let newDesc be the PropertyDescriptor{[[Value]]: V, [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: true}.\n\t\tvar newDesc = {\n\t\t\tvalue: V,\n\t\t\twritable: true,\n\t\t\tenumerable: false,\n\t\t\tconfigurable: true\n\t\t};\n\t\t// 4. Return ? O.[[DefineOwnProperty]](P, newDesc).\n\t\tObject.defineProperty(O, P, newDesc);\n\t}", "function createTestObject() {\n 'use strict';\n return { '@id': 'http://bogus.domain.com/bogus1',\n '@type': 'http:/bogus.domain.com/type#Bogus',\n 'http:bogus.domain.com/prop#name': 'heya' };\n}", "function createValue(data) {\n //console.log('Properties updated!');\n return Object.assign(data, { \"timestamp\": utils.isoTimestamp() });\n}", "create () {}", "create () {}", "function testcase() {\n var obj = {};\n\n function get_func() {\n return 10;\n }\n\n var resultSetFun = false;\n function set_func() {\n resultSetFun = true;\n }\n\n Object.defineProperty(obj, \"foo\", {\n get: get_func,\n set: set_func,\n enumerable: true,\n configurable: true\n });\n\n Object.freeze(obj);\n var res1 = obj.hasOwnProperty(\"foo\");\n delete obj.foo;\n var res2 = obj.hasOwnProperty(\"foo\");\n var resultConfigurable = (res1 && res2);\n\n var resultGetFun = (obj.foo === 10);\n obj.foo = 12;\n\n var resultEnumerable = false;\n for (var prop in obj) {\n if (prop === \"foo\") {\n resultEnumerable = true;\n }\n }\n\n var desc = Object.getOwnPropertyDescriptor(obj, \"foo\");\n var result = resultConfigurable && resultEnumerable && resultGetFun && resultSetFun;\n\n return desc.configurable === false && result;\n }", "function CreateDataProperty(O, P, V) { // eslint-disable-line no-unused-vars\n // 1. Assert: Type(O) is Object.\n // 2. Assert: IsPropertyKey(P) is true.\n // 3. Let newDesc be the PropertyDescriptor{ [[Value]]: V, [[Writable]]: true, [[Enumerable]]: true, [[Configurable]]: true }.\n var newDesc = {\n value: V,\n writable: true,\n enumerable: true,\n configurable: true\n };\n // 4. Return ? O.[[DefineOwnProperty]](P, newDesc).\n try {\n Object.defineProperty(O, P, newDesc);\n return true;\n } catch (e) {\n return false;\n }\n }", "_initializeProperties() {}", "function test1() {\r\n var sc4 = WScript.LoadScript('function test(){ obj2.prop4 = {needMarshal:true}; }', 'samethread');\r\n var obj1 = new Proxy({}, { set: function (target, property, value) { Reflect.set(value); } })\r\n sc4.obj2 = obj1;\r\n sc4.test();\r\n obj1.prop4 = { needMarshal: false };\r\n obj1.prop5 = { needMarshal: false };\r\n}", "static get properties(){return{}}", "static get properties(){return{}}", "function createProperty(attr) {\n\tvar name, value, isAttr;\n\n\t// using a map to find the correct case of property name\n\tif (propertyMap[attr.name]) {\n\t\tname = propertyMap[attr.name];\n\t} else {\n\t\tname = attr.name;\n\t}\n\t// special cases for data attribute, we default to properties.attributes.data\n\tif (name.indexOf('data-') === 0 || name.indexOf('aria-') === 0) {\n\t\tvalue = attr.value;\n\t\tisAttr = true;\n\t} else {\n\t\tvalue = attr.value;\n\t}\n\n\treturn {\n\t\tname: name\n\t\t, value: value\n\t\t, isAttr: isAttr || false\n\t};\n}", "function testcase(){\n Object.defineProperty(Object.prototype, \"x\", { get: function () { \"use strict\"; return this; } }); \n if(!(typeof (5).x === \"number\")) return false;\n return true;\n}", "function Nt(t,e){for(var n=0;n<e.length;n++){var i=e[n];i.enumerable=i.enumerable||!1,i.configurable=!0,\"value\"in i&&(i.writable=!0),Object.defineProperty(t,i.key,i)}}", "function CreateMethodProperty(O, P, V) { // eslint-disable-line no-unused-vars\n // 1. Assert: Type(O) is Object.\n // 2. Assert: IsPropertyKey(P) is true.\n // 3. Let newDesc be the PropertyDescriptor{[[Value]]: V, [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: true}.\n var newDesc = {\n value: V,\n writable: true,\n enumerable: false,\n configurable: true\n };\n // 4. Return ? O.[[DefineOwnProperty]](P, newDesc).\n Object.defineProperty(O, P, newDesc);\n }", "newBasicProp(...args){\n let newProp = new BasicProperty(...args);\n this.addProperty(newProp);\n }", "static createProperty(name, options = defaultPropertyDeclaration) {\n // Note, since this can be called by the `@property` decorator which\n // is called before `_finalize`, we ensure storage exists for property\n // metadata.\n this._ensureClassProperties();\n this._classProperties.set(name, options);\n if (!options.noAccessor) {\n const superDesc = descriptorFromPrototype(name, this.prototype);\n let desc;\n // If there is a super accessor, capture it and \"super\" to it\n if (superDesc !== undefined && (superDesc.set && superDesc.get)) {\n const { set, get } = superDesc;\n desc = {\n get() { return get.call(this); },\n set(value) {\n const oldValue = this[name];\n set.call(this, value);\n this.requestUpdate(name, oldValue);\n },\n configurable: true,\n enumerable: true\n };\n }\n else {\n const key = typeof name === 'symbol' ? Symbol() : `__${name}`;\n desc = {\n get() { return this[key]; },\n set(value) {\n const oldValue = this[name];\n this[key] = value;\n this.requestUpdate(name, oldValue);\n },\n configurable: true,\n enumerable: true\n };\n }\n Object.defineProperty(this.prototype, name, desc);\n }\n }", "function make_event(name, props) {\n var evt = document.createEvent('Event');\n evt.initEvent(name, true, true);\n if (props) {\n for (var prop in props) {\n evt[prop] = props[prop];\n }\n }\n return evt;\n }", "function makePropertyMetadata(key) {\n if (key === '__proto__') {\n throw new Error(\n '__proto__ has a special meaning that is incompatible with POJOs');\n }\n const rawProperty = rawProperties[key];\n const property = {};\n setPrototypeOf(property, null);\n properties[key] = property;\n\n const hasDefault = hasOwn(rawProperty, 'default');\n const defaultValue = hasDefault ? rawProperty.default : null;\n if (hasDefault) {\n defaultKeys.push(key);\n property.default = defaultValue;\n }\n\n property.required = hasOwn(rawProperty, 'required') ?\n rawProperty.required === true :\n !hasDefault;\n if (property.required) {\n requiredKeys.push(key);\n }\n\n if (hasOwn(rawProperty, 'value')) {\n property.value = rawProperty.value;\n }\n\n if (hasOwn(rawProperty, 'recurse') ?\n rawProperty.recurse === true :\n // Do not recurse by default to fields with mandated values.\n !hasOwn(rawProperty, 'value')) {\n recurseToKeys.push(key);\n }\n\n let rawConvert = hasOwn(rawProperty, 'convert') ?\n rawProperty.convert : null;\n if (typeof rawConvert !== 'function') {\n rawConvert = null;\n }\n\n const hasInnocuous = hasOwn(rawProperty, 'innocuous');\n const requireTrusted = hasOwn(rawProperty, 'trusted') ?\n rawProperty.trusted === true :\n hasInnocuous;\n\n let type = hasOwn(rawProperty, 'type') ?\n rawProperty.type : null;\n if (typeof type !== 'string' && typeof type !== 'function') {\n type = null;\n }\n\n const requiresValue = hasOwn(rawProperty, 'value');\n const requiredValue = requiresValue && rawProperty.value;\n\n const innocuous = hasInnocuous ?\n rawProperty.innocuous : defaultValue;\n\n if (requireTrusted || type || requiresValue) {\n property.convert = function convert(value, trusted, userContext, notApplicable) {\n if (requiresValue) {\n // TODO: NaN\n if (requiredValue !== value) {\n return notApplicable;\n }\n } else if (type) {\n switch (typeof type) {\n case 'string':\n if (type !== typeof value) {\n return notApplicable;\n }\n break;\n case 'function':\n // TODO: substitute Array for isArray, etc.\n if (!(value && value instanceof type)) {\n return notApplicable;\n }\n break;\n default:\n }\n }\n const tvalue = requireTrusted && !trusted ? innocuous : value;\n return (rawConvert) ?\n rawConvert(tvalue, trusted, userContext, notApplicable) : tvalue;\n };\n } else if (rawConvert) {\n property.convert = rawConvert;\n }\n if (property.convert) {\n convertKeys.push(key);\n }\n }", "function CreateDataProperty(O, P, V) {\n Object.defineProperty(O, P, {\n value: V,\n writable: true,\n enumerable: true,\n configurable: true\n });\n }", "function CreateDataProperty(O, P, V) {\n Object.defineProperty(O, P, {\n value: V,\n writable: true,\n enumerable: true,\n configurable: true\n });\n }", "_setInitialDate(initialDate){\n const date = this._stringify(initialDate);\n const objectDate = new Date(date);\n return objectDate;\n }", "function objectMaker(value1, value2) {\n return {\n key1: value1,\n key2: value2\n }\n}", "function makeProperty( obj, name, predicate ) {\r\n\tvar value; // this is the property value, current goal in this application.\r\n\t\r\n\tobj[\"get\" + name] = function() {\r\n\t\treturn value; \r\n\t};\r\n\t\r\n\tobj[\"set\" + name] = function(v) {\r\n\t\tif ( predicate && !predicate(v))\r\n\t\t\tthrow \"set\" + name + \": invalid value \" + v;\r\n\t\telse\t\r\n\t\t\tvalue = v;\r\n\t};\r\n\t\t\r\n}", "static createProperty(name, options = defaultPropertyDeclaration) {\n // Note, since this can be called by the `@property` decorator which\n // is called before `finalize`, we ensure storage exists for property\n // metadata.\n this._ensureClassProperties();\n this._classProperties.set(name, options);\n // Do not generate an accessor if the prototype already has one, since\n // it would be lost otherwise and that would never be the user's intention;\n // Instead, we expect users to call `requestUpdate` themselves from\n // user-defined accessors. Note that if the super has an accessor we will\n // still overwrite it\n if (options.noAccessor || this.prototype.hasOwnProperty(name)) {\n return;\n }\n const key = typeof name === 'symbol' ? Symbol() : `__${name}`;\n Object.defineProperty(this.prototype, name, {\n // tslint:disable-next-line:no-any no symbol in index\n get() {\n return this[key];\n },\n set(value) {\n const oldValue = this[name];\n this[key] = value;\n this._requestUpdate(name, oldValue);\n },\n configurable: true,\n enumerable: true\n });\n }", "function createData(property, content) {\n return { property, content };\n}", "function randomPropTest() {\n var obj = {};\n var i, j;\n var k, v;\n\n for (i = 0; i < 10000000; i++) {\n if (i % 1000000 === 0) {\n print(i);\n //print(Duktape.enc('jx', obj));\n }\n\n k = Math.floor(Math.random() * 10000);\n if (k < 1000) { k = k; }\n else { k = \"key-\" + String(k); }\n\n v = Math.floor(Math.random() * 100);\n if (v < 10) { v = undefined; }\n else if (v < 50) { v = i; }\n else if (v < 80) { v = { foo: i }; }\n else { v = \"value-\" + i; }\n\n if (v === undefined) {\n delete obj[k];\n } else {\n obj[k] = v;\n }\n }\n}", "function tta(a,b,c){var d=a.constructor;if(!c&&(c=d.getPropertyDescriptor(b,\"__\"+b),!c))throw Error(\"@ariaProperty must be used after a @property decorator\");var e=c,f=\"\";if(!e.set)throw Error(\"@ariaProperty requires a setter for \"+b);a={configurable:!0,enumerable:!0,set:function(g){\"\"===f&&(f=d.getPropertyOptions(b).attribute);this.hasAttribute(f)&&this.removeAttribute(f);e.set.call(this,g)}};e.get&&(a.get=function(){return e.get.call(this)});return a}", "constructor() {\n\t\tproperties.set(this, Object.setPrototypeOf({}, null));\n\t}", "function getPropertiesDate(obj) {\n return obj.properties.date.getValue();\n}", "static get properties() {\n return {};\n }", "static get properties() {\n return {};\n }", "static get properties() {\n return {};\n }", "static get properties() {\n return { ...super.properties };\n }", "function setDummyScriptPropsData() {\n var props = PropertiesService.getScriptProperties();\n props.setProperty('#K#2020-01-07T21:54:02.589Z', '#O#Davis Jones#F#Meg Media Inc.#C#4');\n props.setProperty('#K#2020-02-07T21:54:02.589Z', '#O#Sandra Smith#F#Judo Law Firm#C#1');\n props.setProperty('#K#2020-02-07T20:54:02.589Z', '#O#Bill Paxton#F#Coffee Legal Inc.#C#1');\n props.setProperty('#K#2020-03-07T22:54:02.589Z', '#O#Dolly Parton#F#Hippy Law LLC#C#6');\n props.setProperty('#K#2020-03-07T23:54:02.589Z', '#O#Johnny Cash#F#BBQ Legal Fund#C#7');\n props.setProperty('#K#2020-03-07T23:55:02.589Z', '#O#Willie Nelson#F#Sushi Legal International#C#1');\n props.setProperty('#K#2020-04-07T10:54:02.589Z', '#O#Jimi Hendrix#F#Jones Day Legal#C#1');\n props.setProperty('#K#2020-04-07T11:54:02.589Z', '#O#John Medeski#F#San Antonio Law LLC#C#1');\n}", "function createPerson()\n{ \n var person = new Object();\n person.name = \"siri\";\n person.age =\"28\";\n person.designation=\"trainer\";\n person.Phno = 9998788667;\n return person;\n}", "function _get(e,t,n){return(_get=\"undefined\"!=typeof Reflect&&Reflect.get?Reflect.get:function(e,t,n){var r=_superPropBase(e,t);if(r){var i=Object.getOwnPropertyDescriptor(r,t);return i.get?i.get.call(n):i.value}})(e,t,n||e)}", "function create(obj) {\n return Object.create(obj || null);\n}", "function createObj(a, b)\n{\n //var newObject = {}; // Not needed ctor function\n this.a = a; //newObject.a = a;\n this.b = b; //newObject.b = b;\n //return newObject; // Not needed for ctor function\n}", "function t13() {\n var a = make_point(1, 2);\n var b = make_point(3, 4);\n Object.defineProperty(a, \"y\", {\n get: function () {\n return 7;\n },\n enumerable: true,\n configurable: true\n });\n var y = Object.create(a);\n var x = Object.create(y);\n\n function print(o) {\n helpers.writeln(o.x + \", \" + o.y);\n }\n\n helpers.writeln(\"Before change\");\n print(x);\n helpers.writeln(\"After change\");\n y.__proto__ = b;\n print(x);\n}", "function createPropertyGetter(nonDefinedValue) {\n return function getProperty(object, propertyName, originalContextObject) {\n var boxedObject,\n privates = getPrivates(object),\n propertyPointer;\n\n propertyName = redirectName(object, propertyName);\n\n if (object === null || object === undef) {\n if (originalContextObject !== undef) {\n return nonDefinedValue;\n }\n\n throw new Error('Cannot read property \"' + propertyName + '\" of ' + object);\n }\n\n if (privates && !hasOwn.call(object, propertyName) && privates.prototypeOverride !== undef) {\n return getProperty(privates.prototypeOverride, propertyName, object);\n }\n\n // Ensure any primitives are autoboxed using the correct native type classes, eg. Number/Boolean\n /*jshint newcap:false */\n boxedObject = ScopeObject(object);\n\n if (!(propertyName in boxedObject)) {\n return nonDefinedValue;\n }\n\n propertyPointer = boxedObject[propertyName];\n\n // Can only be 'undefined' if the last property in chain is not defined,\n // in which case return undefined to throw error\n if (!propertyPointer || propertyPointer.secret !== secret) {\n return propertyPointer;\n }\n\n // A null descriptor is used as a special internal indicator of an undefined property\n // (Only applicable to JScript, where properties of the global object cannot be deleted)\n if (!propertyPointer.descriptor) {\n return nonDefinedValue;\n }\n\n return getValue(originalContextObject || object, propertyPointer.descriptor);\n };\n }", "function e(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,\"value\"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}", "function accessorsarentconstructors() {\n try {\n new (Object.getOwnPropertyDescriptor({get a(){}}, 'a')).get;\n } catch(e) {\n return true;\n }\n}", "function constructObject (value) {\n return {'Type': OBJECT,\n 'Value': value};\n}", "function makePerson(name, age) {\r\n\t// add code here\r\n\tlet personObj = Object.create(null);\r\n personObj.name = name;\r\n personObj.age = age;\r\n \r\n return personObj;\r\n\r\n}", "function newPerson(name) {\n let obj = {}\n Object.defineProperties(obj, {\n log: {\n value: function() {\n console.log(name);\n },\n writable: false,\n },\n });\n return obj;\n}", "create(props){\n const obj = {type: this.name};\n\n Object.keys(this.props).forEach((prop) => {\n obj[prop] = props[prop];\n\n // If not primitive type\n // if(this.props[prop].rel !== undefined){\n // types[this.props[prop].type].create(props[prop]);\n // }\n // // Create new instance of type and add relationship\n // this.props[prop].create = (obj) => types[prop.type].create(obj);\n //\n // // Fetch existing instance of type and add relationship\n // this.props[prop].link = (obj) => types[prop.type].link(obj);\n // }\n });\n\n return obj;\n }", "function DateProperty(name, defaultValue) {\n Property.call(this, name, defaultValue);\n}", "create (props) {\n const { clone, dynamic } = props || {}\n Schema.prototype.create.call(this, props)\n setKeyAndName(this, clone, dynamic)\n }", "createEntityFrom(...properties) {\n const src = this.slice(...properties)\n return entity(toJS(src))\n }", "function create(prototype, props) {\n var result = baseCreate(prototype);\n if (props) extendOwn(result, props);\n return result;\n }", "function create(prototype, props) {\n var result = baseCreate(prototype);\n if (props) extendOwn(result, props);\n return result;\n }", "function create(prototype, props) {\n var result = baseCreate(prototype);\n if (props) extendOwn(result, props);\n return result;\n }", "function create(prototype, props) {\n var result = baseCreate(prototype);\n if (props) extendOwn(result, props);\n return result;\n }", "function create(prototype, props) {\n var result = baseCreate(prototype);\n if (props) extendOwn(result, props);\n return result;\n }", "function create(prototype, props) {\n var result = baseCreate(prototype);\n if (props) extendOwn(result, props);\n return result;\n }", "function create(prototype, props) {\n var result = baseCreate(prototype);\n if (props) extendOwn(result, props);\n return result;\n }", "function create(prototype, props) {\n var result = baseCreate(prototype);\n if (props) extendOwn(result, props);\n return result;\n }" ]
[ "0.63572955", "0.62582314", "0.58445114", "0.58234966", "0.5691528", "0.5673719", "0.5670011", "0.55162007", "0.5464216", "0.54375297", "0.54375297", "0.54008764", "0.53765005", "0.53755003", "0.5353464", "0.5338823", "0.52940845", "0.52899784", "0.52817965", "0.52784115", "0.52734154", "0.52675295", "0.52675295", "0.52605563", "0.52605563", "0.52605563", "0.52605563", "0.52605563", "0.52605563", "0.52605563", "0.52605563", "0.52605563", "0.52605563", "0.52605563", "0.52605563", "0.52605563", "0.52552783", "0.5249257", "0.5243139", "0.52412915", "0.5223119", "0.5205629", "0.5200783", "0.51999426", "0.5196196", "0.51910496", "0.51910496", "0.5176374", "0.51755875", "0.5164597", "0.5138672", "0.5133912", "0.5133912", "0.5124983", "0.51192707", "0.51107085", "0.5090888", "0.50635797", "0.50497884", "0.5049339", "0.5048582", "0.5046469", "0.5046469", "0.5045704", "0.504429", "0.50423336", "0.5038297", "0.50300103", "0.5029132", "0.5025056", "0.50077516", "0.50024617", "0.49933273", "0.49933273", "0.49933273", "0.49886635", "0.49822778", "0.4972822", "0.4966368", "0.4961664", "0.49550942", "0.49521926", "0.494566", "0.49455234", "0.49345928", "0.49244598", "0.49139282", "0.49105498", "0.49086085", "0.49058664", "0.48991725", "0.4897699", "0.4896896", "0.4896896", "0.4896896", "0.4896896", "0.4896896", "0.4896896", "0.4896896", "0.4896896" ]
0.7358187
0
Register a new folder to sync. All files are added to the database recursively.
static addNewFolder(username, syncPath) { const directory = path.resolve(process.env.PD_FOLDER_PATH, username, syncPath); const fileList = metaUtils.getFileList(directory); _.each(fileList, (file) => { Databases.fileMetaDataDb.insert(metaUtils.getFileMetadata(username, file)); }); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "addFolder(path) {\r\n addCustomFolder(path);\r\n }", "function updateFolder(iid, type){\n if(currentFolder == \"root\") return;\n var folder = JSON.parse(localStorage.getItem(\"_Folders__\"+currentFolder));\n\n if(type == -1)\n folder.id.splice(folder.id.indexOf(iid),1);\n \n else \n folder.id.push(iid);\n \n var jsonfile = {};\n jsonfile[\"_Folders__\"+currentFolder] = JSON.stringify(folder);\n\n chrome.storage.sync.set(jsonfile,function(){\n console.log(\"_Folders__\"+currentFolder + \" Synced\");\n });\n\n localStorage.setItem(\"_Folders__\"+currentFolder, JSON.stringify(folder));\n}", "function registerFolder(name, folder, suggested, force) {\n var registry = exports.folderRegistry;\n if (name in registry && !force)\n throw new Error(\"Folder \" + name + \" already registered\");\n exports.defaultOption[name] = false;\n exports.suggestedOption[name] = !!suggested;\n registry[name] = folder;\n }", "addFolder(folder, metadataPath) {\n this.zipFolders.push({\n path: folder,\n metadataPath\n });\n }", "onUpdateFolder() {\n this.onUpdateFolder();\n }", "function syncFolder(item) {\r\n\t\t\t\tfunction folderSynced() {\r\n\t\t\t\t\tTi.API.info('Folder ' + folders[item.index].name + ' synced.');\r\n\r\n\t\t\t\t\tvar emailFolderMessages = require('ui/handheld/tizen/platform/messaging/email_folder_messages');\r\n\r\n\t\t\t\t\t// Open selected folder\r\n\t\t\t\t\targs.containingTab.open(new emailFolderMessages({\r\n\t\t\t\t\t\temailService: emailService, \r\n\t\t\t\t\t\tfolderName: item.rowData.title, \r\n\t\t\t\t\t\tfolderId: folders[item.index].id, \r\n\t\t\t\t\t\tcontainingTab: args.containingTab}\r\n\t\t\t\t\t));\r\n\t\t\t\t}\r\n\r\n\t\t\t\ttry {\r\n\t\t\t\t\tTi.API.info('Start to sync ' + item.rowData.title + ' folder.');\r\n\r\n\t\t\t\t\t// Sync selected folder\r\n\t\t\t\t\temailService.syncFolder(folders[item.index], folderSynced, errorCB, 30);\r\n\t\t\t\t} catch (exc) {\r\n\t\t\t\t\tTi.API.info('Exception has been thrown.');\r\n\t\t\t\t\terrorCB(exc); \r\n\t\t\t\t}\r\n\t\t\t}", "function addFolder(folder) {\n $folderList.append(templates.folder(folder));\n}", "refresh () {\n const provider = this.fileProviderOf('/')\n // emit folderAdded so that File Explorer reloads the file tree\n provider.event.emit('folderAdded', '/')\n }", "function sync() {\n syncDocuments({\n uri: {\n fsPath: path.join(rootPath, dir)\n }\n });\n }", "async saveFolder() {\n if (this.state.state !== 'LOADED_PINBOARD') {\n return;\n }\n let folder = this.state.folderBuffer.join('');\n if (this.state.predictedFolder !== 'undefined' && typeof this.state.predictedFolder !== 'undefined') {\n folder += this.state.predictedFolder;\n }\n const store = this.state.store;\n const bookmark = await store.getBookmark(this.state.cursor);\n await store.addFolder(new Folder(bookmark.href, folder));\n }", "async function addFolder(data) {\n const res = await fetch('/api/addFolder', {\n method: 'POST',\n body: JSON.stringify(data),\n headers: {\n 'content-type': 'application/json'\n }\n });\n \n await res.json();\n //add folder to options dropdown list\n updateFolderList();\n //add to folder tab\n renderFolderTabs();\n }", "_register() {\n // let relativeStartIndex = this.root.length + 1\n // let pathRelativeToRoot = (absolutePath) => {\n // return absolutePath.substr(relativeStartIndex)\n // }\n \n let watcher = this.watcher\n // add\n watcher.on(\"add\", (filepath) => {\n \n invokeNodeChildEventCallback.call(this, filepath, \"child.addFile\")\n })\n \n // addDir\n watcher.on(\"addDir\", (filepath) => {\n invokeNodeChildEventCallback.call(this, filepath, \"child.addDir\")\n })\n \n // unlink\n watcher.on(\"unlink\", (filepath) => {\n \n invokeNodeChildEventCallback.call(this, filepath, \"child.removeFile\")\n invokeNodeEventCallback.call(this, filepath, \"remove\")\n })\n \n // unlinkDir\n watcher.on(\"unlinkDir\", (filepath) => {\n \n invokeNodeChildEventCallback.call(this, filepath, \"child.removeDir\")\n invokeNodeEventCallback.call(this, filepath, \"remove\")\n })\n \n \n watcher.on(\"change\", (filepath) => {\n // on file change, we also need to update the file in model to mark it dirty\n this.rootDirectory.markFileDirty(filepath)\n invokeNodeChildEventCallback.call(this, filepath, \"child.change\")\n invokeNodeEventCallback.call(this, filepath, \"change\")\n })\n }", "function assignmentsAddFolder() {\n\tvar defaultName = \"New folder\";\n\tvar newId = assignmentsGetNewId();\n\tvar assignment = {\n\t\tid: newId,\n\t\ttype: \"folder\",\n\t\tname: defaultName,\n\t\tpath: \"\",\n\t\tfolder: true,\n\t\tfiles: [],\n\t\thomework_id: null,\n\t\thidden: false,\n\t\tauthor: authorName,\n\t\tlevel: 1,\n\t\tvisible: 1,\n\t\tselected: 1\n\t};\n\t\n\tassignments.push(assignment);\n\t\n\t// Test if name already exists\n\tvar idx = assignments.length - 1;\n\tvar nr = 1;\n\twhile (!assignmentValidateName(idx, false)) {\n\t\tassignments[idx].name = defaultName + \" \" + nr;\n\t\tnr++;\n\t}\n\t\n\tassignmentsRender();\n\tassignmentsClickOn(newId);\n\tassignmentsSendToServer();\n}", "async function addNewFolder() {\n const folderName = path + \"/\" + document.getElementById(\"new-folder-name\").value\n const data = {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json'\n },\n body: JSON.stringify({\n info: {\n folderName: folderName,\n }\n })\n }\n const response = await fetch('/api/newFolder', data);\n closeNewFolderWindow()\n}", "defaultFolder(folder){\n if (!fs.existsSync(folder)){\n // fs.mkdirSync(folder, {recursive: true});\n shell.mkdir('-p', folder)\n }\n }", "async createFolders() {\n this.filesPath = path.join(this.storagePath, 'files');\n this.tempPath = path.join(this.storagePath, 'tmp');\n await fse.ensureDir(this.filesPath);\n await fse.ensureDir(this.tempPath);\n }", "function CreateFolderApi() {\n function lookupFolder(name, callback) {\n var url = restApi(\"get_account_tree\",\n \"folder_id=0&params[]=nofiles&params[]=nozip&params[]=onelevel\");\n\n $.get(url, function(data, textStatus, jqXHR) {\n var json = goessner.parseXmlStringToJsonObj(jqXHR.responseText);\n\n var tree = json.response.tree;\n\n // tree.folder = root id = 0\n tree.root = tree.folder;\n\n if (!tree.root.folders) {\n boxApi.dbg(\"No folders in root!\");\n return callback(null);\n }\n\n // Force an array if there is only one child of the root folde\n if (!tree.root.folders.folder.length) {\n tree.root.folders.folder = [tree.root.folders.folder];\n }\n\n // select where folder.name == name\n var foldersLen = tree.root.folders.folder.length;\n for (var f=0; f < foldersLen; f += 1) {\n var folder = tree.root.folders.folder[f];\n if (folder['@name'] == name) {\n return callback(folder);\n }\n }\n\n return callback(null);\n });\n }\n\n function createFolder(name, callback) {\n var urlSafeName = encodeURIComponent(name);\n var url = restApi(\"create_folder\",\n \"parent_id=0&share=0&name=\" + urlSafeName);\n\n $.get(url, function(data, textStatus, jqXHR) {\n var json = goessner.parseXmlStringToJsonObj(jqXHR.responseText);\n\n if (!json) {\n boxApi.dbg(\"Couldn't create folder \" + name);\n return;\n }\n\n callback(json.response.folder);\n });\n }\n\n /**\n * Find folder or create it, then send it to the callback method\n */\n function getOrCreateFolder(name, callback) {\n lookupFolder(name, function(folder){\n if (folder == null) {\n createFolder(name, callback);\n return;\n }\n\n callback(folder);\n });\n }\n\n function uploadFilesToFolder(evt, folderName, callback) {\n var files = extractFiles(evt);\n\n // No folder requested, just upload into root\n if (!folderName) {\n postFiles(files, {}, callback);\n return;\n }\n\n getOrCreateFolder(folderName, function(folder) {\n postFiles(files, folder, callback);\n });\n }\n\n // Public methods exposed for folder API\n return {\n uploadFilesToFolder : uploadFilesToFolder\n };\n }", "addFolder() {\n var node = /** @type {KMLNode} */ (this.scope['item']);\n if (node) {\n createOrEditFolder(/** @type {!FolderOptions} */ ({\n 'parent': node\n }));\n }\n }", "function createNewFolder(name) {\n this.name = name;\n this.messages = [];\n this.id = idCounter;\n idCounter++;\n}", "uploadFolder(folderData, callback) {\n\t\taxios.post(`${apiIdeUrl}${uploadFolder}${folderData.ProjectId}/resourceUpload`, {\n\t\t\tUserEmail : store.state.app.UserEmail,\n\t\t\tIsStatic: folderData.IsStatic,\n\t\t\tSourcePath : folderData.SourcePath,\n\t\t\tFileContent : folderData.FileContent\n\t\t})\n\t\t\t.then(res => {\n\t\t\t\tcallback(true, res);\n\t\t\t})\n\t\t\t.catch( err => {\n\t\t\t\tcallback(false, err);\n\t\t\t})\n\t}", "async createFolder(name) {\n this.requireHasToken();\n const path = `${this.fullPath}${path_1.sep}${name}`.split(path_1.sep);\n for (let i = 1; i <= path.length; i++) {\n const segment = path.slice(0, i).join(path_1.sep);\n if (segment && !await util_1.promisify(fs_1.exists)(segment)) {\n await util_1.promisify(fs_1.mkdir)(segment);\n this.context.socketService.notifyRefresh(this.path.replace(/\\\\/g, '/').replace(/\\/$/, \"\"));\n }\n }\n }", "async function addToCatalog (folderName) {\n const fileName = config.get('archiver.fileNames.catalog');\n var data;\n try {\n data = JSON.parse(await readFile(fileName));\n if (!data.folderNames || data.folderNames.length < 1) {\n throw new Error('folderNames array is empty')\n }\n } catch (err) {\n console.log(`ERROR: could not read existing catalog. Regenerating (${err})`);\n data = await generateCatalog({writeFile: false});\n }\n data.timeStamp = moment().utc().toISOString();\n if (!data.folderNames.includes(folderName)) {\n data.folderNames.push(folderName);\n }\n\n await writeJSON(fileName, data);\n}", "function setData(data, directory = \"\") {\n database.ref(\"groups/\" + localStorage.getItem(\"groupKey\") + \"/\" + directory).set(data);\n}", "'serve_directory'(path) {\n this.served_directories.push({\n 'name': path\n });\n }", "addFolder() {\n try {\n let isDirectory = fs.lstatSync(this.filePath).isDirectory();\n if (!isDirectory) {\n this.parent.logger.warn(\n \"[VelopServer][Route] addStaticFolder() - path:\" +\n this.filePath +\n \" - does not exist or is not a folder\"\n );\n return;\n } else {\n this.parent.router.api.all(\n path.join(this.servePath, \"/\", \"*\"),\n (ctx, next) => this.authMiddleware(passport, ctx, next),\n this.serveFolder(path.resolve(this.filePath))\n );\n }\n } catch (e) {\n this.parent.logger.warn(\"[VelopServer][Router] addStaticFolder()\");\n this.parent.logger.warn(e);\n }\n }", "function syncDirectory(dir = '') {\n // helper function to wrap the directory as a TextDocument\n function sync() {\n syncDocuments({\n uri: {\n fsPath: path.join(rootPath, dir)\n }\n });\n }\n\n // if syncmate.dirty...\n if (config.dirty) {\n // pause all syncs until we finish saving...\n allPaused = true;\n // save all open files...\n vscode.workspace.saveAll().then(() => {\n // unpause\n allPaused = false;\n // then sync\n sync();\n });\n } else {\n // otherwise, just sync now\n sync();\n }\n }", "enqueue(folderId){\n this.sheet.getRange(\n this.sheet.getLastRow() + 1,\n this.colNum\n ).setValue(folderId);\n }", "async function AddingFolder(e) {\r\n e.preventDefault();\r\n let NewFolderName = e.target.Fname.value;\r\n\r\n try {\r\n await axios.post(`/addingFolder`, { NewFolderName, FolderID })\r\n .then(res => {\r\n console.log(res.data.doc);\r\n const TempFile = {\r\n label: res.data.doc.metadata.label,\r\n id: res.data.doc.metadata.id,\r\n parentId: FolderID,\r\n items: null,\r\n file: false\r\n }\r\n seTtreeNodes(treeNodes => [...treeNodes, TempFile])\r\n })\r\n\r\n }\r\n catch (err) { console.log(err) }\r\n\r\n }", "createRouteFolder() {\n // check if folder `Routes` already exists\n if (!fs.existsSync(`${this.route}`)) {\n // create `Routes` folder\n fs.mkdirSync(`${this.route}`);\n return;\n }\n\n console.error(`${this.route} folder already exists`);\n }", "function addFolder(folder, isTrash) {\n if (isTrash) {\n var folderParent = folder.parents[0];\n\n folder.originPath = {\n path: getOriginPath(folder).html.join(' / '),\n tooltip: getOriginPath(folder).tooltip.join(' / '),\n isApp: folderParent.type === 'app',\n appIcon: appIcons.get(folderParent.data.id)\n };\n }\n\n folder.formattedDate = formatDate(folder.createdAt);\n\n if (folder.deletedAt !== null) {\n folder.deletedAt = formatDate(folder.deletedAt);\n }\n\n currentFolders.push(folder);\n folders.push(folder);\n\n $('.empty-state').removeClass('active');\n // Toggle checkbox header to false\n $('.file-table-header input[type=\"checkbox\"]').prop('checked', false);\n $selectAllCheckbox.css({ 'opacity': '1', 'visibility': 'visible' });\n}", "function createNewFolder(nameFolder, fatherNode) {\n\t$(\"#failPolicy\").hide();\n\tif (fatherNode != null && fatherNode != \"\" && nameFolder != null\n\t\t\t&& nameFolder != \"\") {\n\t\t$(\"#errorCreatePolicyToken\").hide();\n\t\tvar sJWT = generateRequestToken(\"POST\", policyService, fatherNode + \"/\"\n\t\t\t\t+ nameFolder, username);\n\t\trequestToken(\"createPolicies\", sJWT, null);\n\t\tvar tokenGetPolicies = sessionStorage.getItem(\"createPoliciesToken\");\n\t\tvar deferedRequest = $.Deferred();\n\t\tif (tokenGetPolicies == null) {\n\t\t\t$(\"#errorCreatePolicyToken\").show();\n\t\t\treturn;\n\t\t}\n\t\texecuteService(tokenGetPolicies, deferedRequest, JSON.stringify({\n\t\t\t'username' : username,\n\t\t\t'type' : 'Directory'\n\t\t}));\n\t\t$.when(deferedRequest).done(function(response) {\n\t\t\tif (response.code == 201) {\n\t\t\t\t$(\"#successFolder\").show();\n\t\t\t\t$.unblockUI();\n\t\t\t} else {\n\t\t\t\t$(\"#failPolicy\").show();\n\t\t\t\t$.unblockUI();\n\t\t\t}\n\t\t}).fail(function() {\n\t\t\t$(\"#failPolicy\").show();\n\t\t\t$.unblockUI();\n\t\t});\n\t}\n}", "defaultFolder(folder){\n if (!fs.existsSync(folder)){\n shell.mkdir('-p', folder)\n }\n }", "addFolder(folder) {\n const folderId = this.providerFileToId(folder);\n const state = this.plugin.getPluginState();\n const folders = { ...state.selectedFolders\n };\n\n if (folderId in folders && folders[folderId].loading) {\n return;\n }\n\n folders[folderId] = {\n loading: true,\n files: []\n };\n this.plugin.setPluginState({\n selectedFolders: { ...folders\n }\n }); // eslint-disable-next-line consistent-return\n\n return this.listAllFiles(folder.requestPath).then(files => {\n let count = 0; // If the same folder is added again, we don't want to send\n // X amount of duplicate file notifications, we want to say\n // the folder was already added. This checks if all files are duplicate,\n // if that's the case, we don't add the files.\n\n files.forEach(file => {\n const id = this.providerFileToId(file);\n\n if (!this.plugin.uppy.checkIfFileAlreadyExists(id)) {\n count++;\n }\n });\n\n if (count > 0) {\n files.forEach(file => this.addFile(file));\n }\n\n const ids = files.map(this.providerFileToId);\n folders[folderId] = {\n loading: false,\n files: ids\n };\n this.plugin.setPluginState({\n selectedFolders: folders\n });\n let message;\n\n if (count === 0) {\n message = this.plugin.uppy.i18n('folderAlreadyAdded', {\n folder: folder.name\n });\n } else if (files.length) {\n message = this.plugin.uppy.i18n('folderAdded', {\n smart_count: count,\n folder: folder.name\n });\n } else {\n message = this.plugin.uppy.i18n('emptyFolderAdded');\n }\n\n this.plugin.uppy.info(message);\n }).catch(e => {\n const state = this.plugin.getPluginState();\n const selectedFolders = { ...state.selectedFolders\n };\n delete selectedFolders[folderId];\n this.plugin.setPluginState({\n selectedFolders\n });\n this.handleError(e);\n });\n }", "async registerSync() {\n if ('sync' in self.registration) {\n try {\n await self.registration.sync.register(`${TAG_PREFIX}:${this._name}`);\n } catch (err) {\n // This means the registration failed for some reason, possibly due to\n // the user disabling it.\n {\n logger_js.logger.warn(`Unable to register sync event for '${this._name}'.`, err);\n }\n }\n }\n }", "function createFolder(currentNode){\n\tdocument.location.href = \"#bpm/dms/showFolderPage\";\n\t_execute('user-grid','parentNodeId='+currentNode);\n}", "function populateJSONObjFolder(action, jsonObject, folderPath) {\n var myitems = fs.readdirSync(folderPath);\n myitems.forEach((element) => {\n var statsObj = fs.statSync(path.join(folderPath, element));\n var addedElement = path.join(folderPath, element);\n if (statsObj.isDirectory() && !/(^|\\/)\\.[^\\/\\.]/g.test(element)) {\n if (irregularFolderArray.includes(addedElement)) {\n var renamedFolderName = \"\";\n if (action !== \"ignore\" && action !== \"\") {\n if (action === \"remove\") {\n renamedFolderName = removeIrregularFolders(element);\n } else if (action === \"replace\") {\n renamedFolderName = replaceIrregularFolders(element);\n }\n jsonObject[\"folders\"][renamedFolderName] = {\n type: \"local\",\n folders: {},\n files: {},\n path: addedElement,\n action: [\"new\", \"renamed\"],\n };\n element = renamedFolderName;\n }\n } else {\n jsonObject[\"folders\"][element] = {\n type: \"local\",\n folders: {},\n files: {},\n path: addedElement,\n action: [\"new\"],\n };\n }\n populateJSONObjFolder(\n action,\n jsonObject[\"folders\"][element],\n addedElement\n );\n } else if (statsObj.isFile() && !/(^|\\/)\\.[^\\/\\.]/g.test(element)) {\n jsonObject[\"files\"][element] = {\n path: addedElement,\n description: \"\",\n \"additional-metadata\": \"\",\n type: \"local\",\n action: [\"new\"],\n };\n }\n });\n}", "createBaseFolder() {\n\n // check if base folder `Server` already exists\n if (!fs.existsSync(this.server)) {\n // create `Server` folder\n fs.mkdirSync(this.server);\n return;\n }\n\n console.error(`${this.server} folder already exists`);\n }", "async function createFolder (ctx, next) {\n const body = ctx.request.body\n const newFolder = new Folder(body)\n try {\n ctx.body = await newFolder.save()\n } catch (e) {\n if (e.code === 11000) {\n ctx.throw(400, 'This user already exists')\n }\n if (e.name === 'ValidationError') {\n ctx.throw(400, 'Incorrect data')\n }\n throw new Error()\n }\n}", "function insertRosterItem(aAuth, aPath, aFolder, aName, aGroup) {\n if (!aFolder) return;\n var arr = queryXmppBookmark(aAuth, aPath);\n if (arr.length) {\n arr.forEach(function(id) {\n if (aFolder != BookmarksService.getFolderIdForItem(id)) {\n BookmarksService.moveItem(id, aFolder, -1);\n }\n });\n } else {\n var uri = Cc[\"@mozilla.org/network/simple-uri;1\"].\n createInstance(Ci.nsIURI);\n uri.spec = makeXmppURI(aAuth.fulljid, aPath.barejid);\n BookmarksService.insertBookmark(aFolder, uri, -1, aName);\n }\n}", "function folderCheck() {\n if (!fs.existsSync(`${process.env.LOCALAPPDATA}/gamiTask`))\n fs.mkdir(`${process.env.LOCALAPPDATA}/gamiTask`, err => {\n if (err) console.log(err.message);\n else console.log(\"Folder Successfully Created!\");\n });\n}", "async function createFeedFolder(feed) {\r\n const folder = await browser.bookmarks.create({\r\n \"parentId\": feed.parentFolderId,\r\n \"title\": feed.name\r\n });\r\n // TODO: need to handle if the parent folder doesn't exist\r\n // add the folder id to the feeds config\r\n feed.folderId = folder.id;\r\n addFolderIdToFeedSettings(feed);\r\n\r\n folder.children = [];\r\n // poll the feed folder\r\n pollFeed(folder, feed);\r\n}", "async function createFolder(parentID, name, userID) {\n const id = uuidv4();\n\n await db.createDataPromise('file', {\n id: id,\n name: name,\n comment: \"\",\n owner: userID,\n tags: [],\n fileSize: null,\n expires: null,\n parent: parentID,\n isFolder: true,\n downloads: 0,\n maxDownloads: null\n });\n\n return true;\n}", "function appendFolder(obj) {\n\n const folder = newElement('li', 'folder', obj.name);\n folderList.appendChild(folder);\n\n const messageList = newElement('ul', 'message-list', null, obj.id);\n const content = document.querySelector('.content');\n content.appendChild(messageList);\n\n /*\n if there are some messages in the array, it means that\n they were stored in localStorage\n */\n if (obj.messages.length > 0) {\n obj.messages.map(msg => {\n const storedMessages = newElement('li', 'message', msg);\n messageList.appendChild(storedMessages);\n })\n }\n\n // assign event handlers to fresh new folders\n folder.addEventListener('click', showActiveFolder);\n folder.addEventListener('click', changeCurrentFolder);\n folder.addEventListener('click', changeMessageList)\n}", "function addWatcher (newPath) {\n fileWatcher = chokidar.watch(newPath, {\n persistent: true,\n ignored: /(^|[/\\\\])\\../ //For .DS_Store on MacOS\n });\n // console.log(newPath)\n //Signals to setMovieFolder that a watcher exists\n isWatching = true;\n fileWatcher.on('ready', async () => {\n // Retrieve files being watched\n let watched = fileWatcher.getWatched();\n watched = watched[newPath]\n // console.log(watched)\n // Calls sync function\n await onReadySync(watched);\n fileWatcher.on('add', filePath => insertMovie(filePath));\n fileWatcher.on('unlink', filePath => removeMovie(filePath));\n fileWatcher.on('error', error => {\n console.error(`FILEWATCHER ERROR: ${error}`)\n }); \n });\n}", "handleFolderCreation () {\n this.props.handleFolderCreation(this.state.folderName);\n this.handleClose();\n }", "function setFolder(url){\n\tfolder = url;\n}", "createConfigFolder() {\n // check if folder `Config` already exists\n if (!fs.existsSync(`${this.config}`)) {\n // create `Config` folder\n fs.mkdirSync(`${this.config}`);\n return;\n }\n\n console.error(`${this.config} folder already exists`);\n }", "createModelFolder() {\n // check if folder `Models` already exists\n if (!fs.existsSync(`${this.model}`)) {\n // create `Models` folder\n fs.mkdirSync(`${this.model}`);\n return;\n }\n\n console.error(`${this.model} folder already exists`);\n }", "function createDataFolder(){\t\n\tif(!fs.existsSync('./data')){\n\tconsole.log('Creating data folder');\n\tfs.mkdirSync('./data');\n\t}\n}", "function InitCollectionFolder(collection){\n if(!fs.existsSync(path.join(_dataPath, collection))) fs.mkdirSync(path.join(_dataPath, collection));\n}", "makeDirectory(folder) {\n // return promise\n return new Promise((resolve, reject) => {\n folder = path_1.default.join(process.cwd(), folder);\n fs_1.default.exists(folder, (exist) => {\n if (exist) {\n return resolve();\n }\n else {\n // create this folder\n fs_1.default.mkdir(folder, (err) => {\n if (err) {\n return reject(err);\n }\n else {\n return resolve();\n }\n });\n }\n });\n });\n }", "save() {\n // Check if the form is valid\n if (!this.isValid()) {\n // TODO show an error message to user for insert a folder name\n // TODO mark the field as invalid\n return;\n }\n\n // Create the directory\n this.$store.dispatch('createDirectory', {\n name: this.folder,\n parent: this.$store.state.selectedDirectory,\n });\n this.reset();\n }", "async function register_a_tutor(o) {\n const {name, app_instance, xray} = o;\n const {tutor_name =name, label, data} = o;\n _assert(tutor_name, o, \"Missing tutor name\")\n _assert(label, o, \"Missing tutor label\")\n _assert(app_instance, o, \"Missing app_instance\")\n const {package_id, app_folder,\n tutors_folder} = app_instance;\n _assert(package_id, o, \"Missing package_id\")\n _assert(app_folder, o, \"Missing app_folder\")\n _assert(tutors_folder, o, \"Missing tutors_folder\")\n\n /*\n lookup for an existing tutor.\n */\n\n const _tutors = app_instance._tutors;\n let tutor = _tutors && _tutors[tutor_name];\n\n if (!tutor) {\n await api.content_folder__new({\n parent_id: tutors_folder,\n name: tutor_name,\n label,\n package_id,\n context_id: tutors_folder\n })\n .then(folder_id =>{\n// _assert(folder_id, o, 'fatal@38')\n tutor = {\n folder_id,\n name: tutor_name,\n label: label\n }\n })\n .catch(err =>{\n if (err.code != 23505) throw err;\n console.log(`ALERT tutor@42 : `, err.detail)\n })\n }\n\n//console.log(`@51:`,{tutor})\n\n if (!tutor) {\n // already exists.\n tutor = await db.query(`\n select *\n from cr_folders, cr_items i\n left join cr_revisions on (revision_id = latest_revision)\n where (i.item_id = folder_id)\n and (parent_id = $(parent_id))\n and (name = $(name));\n `,{parent_id:tutors_folder, name: tutor_name},{single:true});\n }\n\n\n const {folder_id:tutor_id} = tutor;\n _assert(tutor_id, tutor, 'fatal@53')\n\n if (o.data) { // check latest_revision checksum\n await api.content_revision__new({\n item_id: tutor_id,\n data\n })\n .catch(err =>{\n if (err.code != 23505) throw err;\n console.log(`api.content_revision__new =>`,err.detail)\n })\n }\n\n\n\n/*\n await db.query(`\n update cr_items set content_type = 'tapp.contract'\n where (item_id = ${folder_id})\n `, {folder_id},{single:true})\n\n await db.query(`\n update acs_objects set object_type = 'tapp.contract'\n where (object_id = ${folder_id})\n `, {folder_id},{single:true})\n\n\n if (xray) {\n await tapp.xray_folder({folder_id})\n }\n\n*/\n\n\n\n //const {item_id:tutor_id} = tutor;\n\n await db.query(`\n update acs_objects\n set object_type = 'tapp.tutor'\n where object_id = $(tutor_id);\n `, {tutor_id}, {single:true});\n\n\n return tutor;\n\n}", "refresh() {\n this.changefolder(); //changefolder with empty folder - just refresh\n }", "function actionNewDirectory(newDir){\n\n//\tvar newDir = prompt(\"Nom du nouveau dossier : \");\n\tif(newDir == null){\n\t//\tlog_(\"NEWDIR CANCELED BY USER\");\n\t\treturn false;\n\t}\n\n\tvar get = $.ajax({\n\t\turl: 'helper/action',\n\t\tdata: {'action':'newdir', 'src':folder+'/'+newDir},\n\t\tdataType: 'json'\n\t});\n\t\n\tget.done(function(r){\n\t\t\n\t\tif(r.success == 'true'){\n\n\t\t\tcollection.push({\n\t\t\t\t'name'\t: newDir,\n\t\t\t\t'tags'\t: 'isDir',\n\t\t\t\t'type'\t: 'dir',\n\t\t\t\t'url'\t: folder+'/'+newDir\n\t\t\t});\n\t\t\t\n\t\t\tlast = collection[collection.length - 1];\n\t\t\tnd = folderlElement(last, (collection.length-1));\n\t\t\tgtp = $('#main div.parent');\n\n\t\t\tif(gtp.length > 0){\n\t\t\t\tnd.appendTo(gtp.eq(0));\n\t\t\t}else{\n\t\t\t\tnd.prependTo('#main');\n\t\t\t}\n\t\t\tspreadGrid();\n\t\t\tmakeDragAndDrop();\n\t\t\tfolderView(true);\n\t\t}\n\t});\n\n}", "static createFolderStructure(completePath) {\n var path = '';\n completePath.split(pathSeparator).map(function (folder) {\n if (folder == '.') {\n path += folder + pathSeparator;\n } else if (folder.indexOf('.') == -1) {\n path += folder + pathSeparator;\n try {\n if (!fs.existsSync(path)) {\n fs.mkdirSync(path);\n }\n } catch (ex) {\n logger.error(\"There was an exception during the creation of the '\" + path + \"' folder: \" + ex);\n }\n }\n });\n }", "function AddFolder(form){\n\t$.ajax({\n\t\tasync:true,\n\t\turl: 'fileStorage/addFolder.php',\n\t\ttype: 'get',\n\t\tdata: {'folderName': form.folderName.value},\n\t\tsuccess: function (tmp) {\n\t\t\tdata = eval ('('+tmp+')');\n\t\t\tif (data.ok == 'OK') {\n\t\t\t\talert (\"Folder added\");\n\t\t\t} else {\n\t\t\t\talert (data.message);\n\t\t\t}\n\t\t}\n\t});\n\tOpenFilesDialog();\n\t$(\"#folder-form\").dialog(\"close\");\n}", "function createFolder(folderName)\n{\n\n createAssociationCase7Options = {\n \"displayText\": folderName,\n \"itemName\": folderName,\n \"isGroupingItem\": true\n };\n\n // createAssociationCase1Options = {\n // displayText: folderName\n // };\n\n //need to define the new location of the association.\n sub_itemMirrorOption = {\n groupingItemURI: folderName+'/',\n xooMLUtility: dropboxXooMLUtility,\n itemUtility: dropboxItemUtility,\n syncUtility: mirrorSyncUtility,\n createIfDoesNotExist: true\n };\n\n dropboxClient.authenticate(function (error, client) {\n if (error) {\n throw error;\n }\n constructNewItemMirrorForFolder();\n });\n\n function constructNewItemMirrorForFolder() {\n\n\n //case pair of 3_7\n new ItemMirror(itemMirrorOptions[3], function (error, itemMirror) {\n if (error) { throw error; }\n\n createAssociation(itemMirror, createAssociationCase7Options);\n //This nested constructor is to create a new itemMirror for the new folder just created.\n dropboxClient.authenticate(function (error,client){\n if(error){\n throw error;\n }\n new ItemMirror(sub_itemMirrorOption, function(error, sub_itemMirror){\n if (error) { throw error; }\n \n });\n\n });\n \n });\n };\n\n function createAssociation(itemMirror, options) {\n itemMirror.createAssociation(options, function (error, GUID) {\n if (error) {\n throw error;\n }\n console.log(\"A new folder and related Xooml2 file are created.\");\n \n });\n }; \n}", "function __createDir(rootDirEntry, folders, success, error) {\n rootDirEntry.getDirectory(folders[0], { create: true }, function (dirEntry) {\n // Recursively add the new subfolder (if we still have another to create).\n if (folders.length > 1) {\n __createDir(dirEntry, folders.slice(1), success, error);\n } else {\n success(dirEntry);\n }\n }, error);\n }", "function MakeDirectories() {\r\n}", "changefolder(folder,dir) {\n if (!this.lock) {\n this.lock = true;\n if (folder) {\n if (folder == '..') this.cdup();\n else if (folder == '/') this.cdroot();\n else this.cddown(folder,dir);\n }\n this.pa.getFiles(this.path)\n .then(data => {\n this.populateFiles(data);\n this.lock = false;\n }).catch(error => {\n if (error.status === 403) {\n this.lock = false;\n this.path = this.lastpath;\n this.ea.publish(new HandleLogin(this.panelid));\n } else {\n console.log('Error');\n console.log(error);\n alert('Sorry, response: ' + error.status + ':' + error.statusText + ' when trying to get: ' + this.serviceurl + this.path);\n this.lock = false;\n this.path = this.lastpath;\n }\n });\n } //else doubleclick when the previous operation didn't finished\n }", "function installWatcher (startingFolder, callback) {\n bs.init({\n server: config.commands.build.output,\n port: config.commands.build.port,\n ui: false,\n open: false,\n logLevel: 'silent'\n })\n\n const watcher = createWatcher(path.join(startingFolder, '**/data.xml'))\n\n watcher.on('change', () => {\n callback()\n bs.reload()\n })\n}", "initialize() {\n this.localEntries = new Map();\n this.onlineEntries = new Map();\n\n if (!fs.existsSync(this.localDirectory)) {\n shelljs.mkdir('-p', this.localDirectory);\n }\n this.loadDirectory(this.localDirectory, this.localEntries);\n\n // online database disabled for now\n //this.onlineDirectory = BASE_FOLDER_ONLINE_DB + '/' + this.subFolder;\n //this.loadDirectory(this.onlineDirectory, this.onlineEntries);\n }", "async setup() {\n if (this.type == \"file\") this.addFile();\n else this.addFolder();\n }", "add(url) {\r\n return this.clone(Folders_1, `add('${url}')`).postCore().then((data) => {\r\n return {\r\n data,\r\n folder: this.getByName(url),\r\n };\r\n });\r\n }", "function createFolder (BTN) {\n let path = BN_path(BTN.parentId);\n openPropPopup(\"new\", BTN.id, path, BTN.type, BTN.title, undefined, BTN.dateAdded);\n\n // Don't call refresh search, it is already called through bkmkCreatedHandler\n}", "function addFoldersAction(state) {\n api.setAddFoldersMenu(state);\n}", "createDataDirectory() {\n const dir = `./${this.config.directory}`;\n\n if (!fs.existsSync(dir)){\n fs.mkdirSync(dir);\n }\n }", "function createDirs(next) {\n var dirs = directories.normalize(root,\n JSON.parse(fs.readFileSync(path.join(scaffold, 'directories.json'), 'utf8'))\n );\n\n Object.keys(dirs).forEach(function (name) {\n app.log.info('Creating directory ' + name.grey);\n });\n\n directories.create(dirs, next);\n }", "static storeData(path, data) {\n path = pathHelper.resolve(path);\n logger.info('Storing data to: ' + path);\n if (typeof data == 'object') {\n data = JSON.stringify(data);\n }\n this.createFolderStructure(path);\n fs.writeFileSync(path, data);\n }", "loadFolder(folder) {\n const { path } = folder;\n this._get(path, (contents)=>{\n if (Array.isArray(contents)) {\n folder.contents= this.readContents(path, contents);\n }\n });\n }", "function setFolder(req, res, next) {\n logger.trace('setFolder', req.sessionID);\n mySessionStore.checkP({sid: req.sessionID, user: req.user}).then(function(dirName) {\n req.session.folder = dirName;\n next(); \n }, function(e) { res.json(500, e); });\n}", "newFolderButtonClickCallback() {\n if(this.selectionList[0] !== undefined) {\n let el = document.getElementById(this.selectionList[this.selectionList.length - 1]);\n fs.lstat(el.id, (err, stat) => {\n if(err) throw err;\n if(stat && stat.isDirectory()) {\n this.nameInputFunc(el.parentElement, `calc(${el.style.paddingLeft} + 0.5cm)`, (nameInput) => {\n fs.mkdir(path.join(el.id, nameInput.value), (err) => {\n if(err) {\n alert(err);\n try {nameInput.remove()} catch(err) {};\n }\n else {\n try {nameInput.remove()} catch(err) {};\n this.refreshDirectory(el.id, el.parentElement);\n }\n });\n })\n }\n else if(stat && stat.isFile()) {\n let elFolder = document.getElementById(path.dirname(el.id));\n let anchorNode = null;\n if(elFolder === null) {\n anchorNode = this.fatherNode;\n }\n else {\n anchorNode = elFolder.parentElement;\n }\n this.nameInputFunc(anchorNode, el.style.paddingLeft, (nameInput) => {\n fs.mkdir(path.join(path.dirname(el.id), nameInput.value), (err) => {\n if(err) {\n alert(err);\n try {nameInput.remove()} catch(err) {};\n }\n else {\n try {nameInput.remove()} catch(err) {};\n this.refreshDirectory(path.dirname(el.id), anchorNode);\n }\n });\n })\n }\n })\n }\n else {\n this.nameInputFunc(this.fatherNode, '0.5cm', (nameInput) => {\n fs.mkdir(path.join(this.processCWD, nameInput.value), (err) => {\n if (err) {\n alert(err);\n try {nameInput.remove()} catch(err) {};\n }\n else {\n try {nameInput.remove()} catch(err) {};\n this.refreshDirectory(this.processCWD, this.fatherNode);\n }\n });\n })\n }\n while(this.selectionList.length > 0) {\n document.getElementById(this.selectionList.pop()).classList.remove('selected');\n }\n }", "async _ensureFolder() {\n const dir = this._absoluteConfigDir();\n\n await ensureDirectoryExists(dir);\n }", "function createFolder(folder) {\n\n if(!queryResource(1, 1, folder, '', '')) return false;\n\n d_resources.folders_teaching_resource++;\n jQuery('#folders').prepend(\n '<div id=\"folder_' + d_resources.folders_teaching_resource + '\" class=\"col s12 m6\">' +\n '<div class=\"card horizontal hoverable\">' +\n '<div class=\"card-image fontCircle\" style=\"background-color: ' + d_settings.color_i + '\">' +\n '<i class=\"material-icons medium\">folder</i>' +\n '</div>' +\n '<div class=\"card-stacked\">' +\n '<div class=\"card-content\">' +\n '<span id=\"folder_title_' + d_resources.folders_teaching_resource + '\">' + folder + '</span>' +\n '<a href=\"#\" class=\"right dropdown-button\" data-activates=\"dropdown_' + d_resources.folders_teaching_resource + '\"><i class=\"material-icons\">more_vert</i></a href=\"#\">' +\n '</div>' +\n '</div>' +\n '</div>' +\n '<ul id=\"dropdown_' + d_resources.folders_teaching_resource + '\" class=\"dropdown-content\">' +\n '<li><a href=\"#!\" onclick=\"loadFolder(' + d_resources.folders_teaching_resource + ',\\'' + folder + '\\');\"><i class=\"material-icons\">folder</i>Abrir</a></li>' +\n '<li class=\"divider\"></li>' +\n '<li><a href=\"#!\" onclick=\"actionFolder(\\'update\\',\\''+ d_resources.folders_teaching_resource +'\\');\"><i class=\"material-icons\">mode_edit</i>Editar</a></li>' +\n '<li><a href=\"#!\" onclick=\"actionFolder(\\'delete\\',\\''+ d_resources.folders_teaching_resource +'\\');\"><i class=\"material-icons\">delete</i>Borrar</a></li>' +\n '</ul>' +\n '</div>'\n );\n jQuery('#tab_2').append('<div id=\"folder_resources_' + d_resources.folders_teaching_resource + '\" class=\"portfolio-list col s12\" style=\"display: none;\"></div>');\n jQuery('.dropdown-button').dropdown({\n inDuration: 300,\n outDuration: 225,\n constrainWidth: false, // Does not change width of dropdown to that of the activator\n hover: true, // Activate on hover\n alignment: 'right', // Displays dropdown with edge aligned to the left of button\n stopPropagation: true // Stops event propagation\n });\n\n return true;\n}", "function syncPhotos(){\n sync('photos', {}, Photos, 'photo_id');\n}", "createControllerFolder() {\n\n // check if folder `Controllers` already exists\n if (!fs.existsSync(`${this.controller}`)) {\n // create `Controllers` folder\n fs.mkdirSync(`${this.controller}`);\n return;\n }\n\n console.error(`${this.controller} folder already exists`);\n }", "addDirectory(){\n let dir = dialog.showOpenDialog({properties : ['openDirectory']});\n this.setState({\n direc: dir\n });\n ipcRenderer.send('directory', dir)\n }", "static ensureFolder(folderPath) {\n FileSystem._wrapException(() => {\n fsx.ensureDirSync(folderPath);\n });\n }", "deleteFolder(path){\n rimraf.sync(path)\n }", "function __createDir(rootDirEntry, folders, success,error) {\n rootDirEntry.getDirectory(folders[0], {create: true}, function(dirEntry) {\n // Recursively add the new subfolder (if we still have another to create).\n if (folders.length > 1) {\n __createDir(dirEntry, folders.slice(1),success,error);\n } else {\n success(dirEntry);\n }\n }, error);\n}", "function writeFileSyncCreatingDirectories(filePath,data,encoding) {\n\tcreateFileDirectories(filePath);\n\tfs.writeFileSync(filePath,data,encoding);\t\n}", "function getOrCreateFolder(name, callback) {\n lookupFolder(name, function(folder){\n if (folder == null) {\n createFolder(name, callback);\n return;\n }\n\n callback(folder);\n });\n }", "function createFolderAction(folderName,folderArrayString){\n\t//for the root\n\tif(folderArrayString===\"\"){\n\t\tfileCreateFolderDivPage(folderName,\"\");\n\t}\n\telse{\n\t\tvar folderArray=folderArrayString.split(\"||\");\n\t\tfor (var i=0;i<folderArray.length;i++){\n\t\t\tfileCreateFolderDivPage(folderName,folderArray[i])\t;\n\t\t}\n\t}\n\t//erase elements on display\n\t$('#fileSysDiplayPageDiv').html(\"\");\n\t//redo menus and files\n\tbuild_files(project.userFiles,'#fileSysDiplayPageDiv','','');\n}", "startMonitor(userId, path) {\n console.log(`start monitor folder ${path} for user # ${userId}`);\n let watcher = this._watchers[userId];\n if (watcher) { // check if watcher already running, in this case stop it and run new one\n watcher.stopMonitor();\n }\n watcher = new FolderWatcher(userId, path);\n this._watchers[userId] = watcher;\n watcher.startMonitor();\n // update in db also\n return this._dbAdapter.startMonitorFolder(userId, path);\n }", "SetSelectedFolder(folder) {\n console.debug(`ContaplusModel::SetSelectedFolder(${folder})`)\n // Remove companies if folder is being changed or cleared\n let config = this.config\n let currentFolder = this.GetSelectedFolder()\n if (!folder || (currentFolder && (folder != currentFolder))) {\n config.delete(\"companies\")\n }\n if (folder) {\n config.set(\"folder\", folder)\n } else {\n config.delete(\"folder\")\n }\n }", "function AddNoteToFolder() {\n var selects = document.querySelectorAll('li.selected');\n var idFolder = document.querySelector('.folder-section__title h2').innerHTML;\n\n // GET FOLDER ARRAY\n var foldersArray = getFoldersArray();\n\n // FIND SELECTED FOLDER \n var folder = foldersArray.find(obj => obj.title == idFolder);\n \n \n for (let i = 0; i < selects.length; i++) {\n const select = selects[i];\n\n // ID OF NOTE \n var idNote = select.getAttribute('id');\n\n // PUSH NOTE ID INTO FOLDER LIST \n folder.list.push(idNote);\n\n }\n \n // SAVE FOLDERS ARRAY BACK INTO LOCALSTORAGE\n localStorage.setItem('foldersArray', JSON.stringify(foldersArray));\n location.reload();\n\n }", "save() {\n\t\tlet dir = `./polls/${this.server}`;\n\t\tif (!fs.existsSync(dir)) fs.mkdirSync(dir);\n\t\tfs.writeFile(`${dir}/${this.number}.json`, JSON.stringify(this), function(err) {\n\t\t\tif (err) {\n\t\t\t\tconsole.log(err);\n\t\t\t\tthrow err;\n\t\t\t}\n\t\t});\n\t}", "function registerFolderEventLogHelper() {\n // Bail if there's no one on the other end who cares about our very\n // expensive log additions.\n // This stuff might be useful for straight console debugging, but it'll\n // be costly in the success case, so no go for now.\n if (!logHelperHasInterestedListeners())\n return;\n\n let mailSession = Cc[\"@mozilla.org/messenger/services/session;1\"].\n getService(Ci.nsIMsgMailSession);\n mailSession.AddFolderListener(_folderEventLogHelper_folderListener,\n Ci.nsIFolderListener.propertyFlagChanged |\n Ci.nsIFolderListener.event);\n let notificationService =\n Cc[\"@mozilla.org/messenger/msgnotificationservice;1\"]\n .getService(Ci.nsIMsgFolderNotificationService);\n notificationService.addListener(_folderEventLogHelper_msgFolderListener,\n Ci.nsIMsgFolderNotificationService.msgAdded |\n Ci.nsIMsgFolderNotificationService.msgsClassified |\n Ci.nsIMsgFolderNotificationService.msgsDeleted |\n Ci.nsIMsgFolderNotificationService.msgsMoveCopyCompleted |\n Ci.nsIMsgFolderNotificationService.folderDeleted |\n Ci.nsIMsgFolderNotificationService.folderMoveCopyCompleted |\n Ci.nsIMsgFolderNotificationService.folderRenamed |\n Ci.nsIMsgFolderNotificationService.itemEvent);\n}", "updateFolderData({lastFilePath=null, recentFilePaths=null}){\n this.send(\"folder-data-update\", {lastFilePath, recentFilePaths})\n }", "updateFolder(folderId) {\n this.setState({folder_id: folderId})\n }", "function startWatcher(rootPath) {\n fs.readdir(rootPath, function (err, files) {\n if (err) {\n console.error(err);\n watcher_notification.dismiss();\n messenger.error(\n ModuleMessage.WATCHER_ERROR,\n true,\n err\n );\n process.exit(1);\n }\n //Processing each directory for watcher.\n files.forEach((item) => {\n\n if (DIR_AVOID.indexOf(item) == -1) {\n //creating full path to current file item.\n let fullPath = Path.join(rootPath, item);\n\n //stats for file to check is directory or is file.\n fs.stat(fullPath, function (error, stat) {\n if (error) {\n console.error(error);\n }\n\n //Add watcher if this is a directory.\n if (stat.isDirectory()) {\n let watcher = fs.watch(fullPath, (eventType, filename) => {\n\n if (filename) {\n if (FILE_AVOID.indexOf(filename) == -1 && !isInvalidFile(filename)) {\n let filePath = Path.join(fullPath, filename);\n\n setTimeout(function () {\n VltService.push(new PayloadModel(filePath), true);\n }, 2000);\n\n }\n }\n\n });\n WATCHERS.push(watcher);\n //Search for more directories inside current directory.\n startWatcher(fullPath);\n }\n });\n }\n\n }, this);\n\n watcher_notification.dismiss();\n });\n}", "async function handleUpdateFolder() {\n try {\n setLoading(true);\n await updateFolder(\n props.courseId,\n props.folder.id,\n folderRenameRef.current.value\n );\n } catch (error) {\n console.log(error);\n }\n setLoading(false);\n setShowUpdateFolder(false);\n }", "async function checkFolderExists() {\n const data_path = path.resolve(path.join(__dirname, '../static-data/'))\n\n folders.map(folder => {\n fs.stat(`${data_path}/${folder}`, (err, stats) => {\n if (err && err.errno === -2) {\n fs.mkdir(`${data_path}/${folder}`, (err) => {\n if(err) throw err\n console.log(`> the folder : ${folder} was succesfully created`)\n });\n }\n })\n }) \n}", "createDB() {\n const files = ['authorize', 'info', 'friends', 'news'];\n const dirs = ['messages', 'dropbox'];\n\n return new Promise(resolve => {\n fs.access('data', err => {\n if (err) {\n fs.mkdir('data', err => this.checkError(err));\n }\n });\n\n for (const file of files) {\n fs.access('data/' + file, err => {\n if (err) {\n fs.writeFile('data/' + file, '', err => this.checkError(err));\n }\n });\n }\n\n for (const dir of dirs) {\n fs.access('data/' + dir, err => {\n if (err) {\n fs.mkdir('data/' + dir, err => this.checkError(err));\n }\n });\n }\n\n resolve();\n });\n }", "function saveSyncData(data) {\n\tconsole.log(\"Saving data to sunjer_data for sync\");\n if (!data)\n return false;\n var url = getURLFromData(data);\n if (!syncId) {\n var create = function(id) {\n createBookmark(syncBookmarkName, url, id, function(bookmark) {\n syncId = bookmark.id;\n syncFolderId = bookmark.parentId;\n });\n }\n // create folder to contain the bookmark\n createBookmark(syncName + \"Sync\", null, null, function(folder) {\n create(folder.id);\n });\n }\n else {\n saveSyncDataWasCalled = true;\n saveBookmark(syncId, url, function(bookmark){\n saveSyncDataWasCalled = false;\n // some develish power deleted the bookmark. reset syncId and create a new bookmark\n if (!bookmark) {\n syncId = null;\n syncFolderId = null;\n saveSyncData(elements.styles);\n }\n });\n }\n}", "function syncLocalRings() {\n\tvar db = window.openDatabase(window.dbName, window.dbVersion, window.dbName, window.dbSize);\n\t$.getJSON(window.serviceURL + window.apiFile + window.apiKey + 'appsyncrings', function (data) {\n\t\tvar rings = data.items;\n\t\tdb.transaction(\n\t\t\tfunction (transaction) {\n\t\t\t\t$.each(rings, function (index, ring) {\n\t\t\t\t\ttransaction.executeSql(\n\t\t\t\t\t\t'INSERT INTO dpAppRingtones (folder, filename, name, type, distribution, device, version) VALUES (?, ?, ?, ?, ?, ?, ?)',\n\t\t\t\t\t\t[ring.folder, ring.filename, ring.name, ring.type, ring.distribution, ring.device, ring.version],\n\t\t\t\t\t\tcheckSyncFinished(index, rings.length, 'rings')\n\t\t\t\t\t);\n\t\t\t\t});\n\t\t\t},\n\t\t\terrorHandlerSqlTransaction\n\t\t);\n\t}).fail(function () { apiErrorHandler($('#infoSync'), \"appsyncrings\"); });\n\treturn true;\n}", "function updateFolder(id, name, new_name) {\n\n if(!queryResource(2, 1, name, new_name, '')) return false;\n\n jQuery('#folder_title_'+id).text(new_name);\n\n return true;\n}", "handleFolderActivate(event, folder) {\n this.props.actions.gallery.setFolder(folder.id);\n }", "async checkFolders() {\n if (this.foldersCreated) return;\n const folders = [pendingFolder, resultsFolder, historyFolder];\n try {\n await accessAsync(this.path, fs.constants.F_OK);\n } catch (err) {\n await handleENOENTError(err);\n }\n for (const folder of folders) {\n try {\n await accessAsync(`${this.path}/${folder}`, fs.constants.F_OK);\n } catch (err) {\n await handleENOENTError(err);\n }\n }\n this.foldersCreated = true;\n }" ]
[ "0.6373083", "0.62828857", "0.6152957", "0.6028344", "0.60235107", "0.5921698", "0.5913805", "0.5884406", "0.5847943", "0.5842436", "0.57973343", "0.57706654", "0.5747422", "0.5683525", "0.5660866", "0.5628417", "0.56211436", "0.55424845", "0.55224746", "0.55138564", "0.5496249", "0.5490929", "0.5474725", "0.5465697", "0.5456777", "0.54490286", "0.54441804", "0.5435309", "0.5397481", "0.53911877", "0.5376232", "0.5339235", "0.53215516", "0.5318912", "0.53117365", "0.52936774", "0.52839214", "0.52736455", "0.5271761", "0.5269755", "0.5238382", "0.5229237", "0.52034765", "0.52002347", "0.5197458", "0.519522", "0.5187564", "0.5176814", "0.51474977", "0.51418376", "0.5127152", "0.5119191", "0.511356", "0.51115584", "0.50989926", "0.5087031", "0.50550747", "0.5050798", "0.50458074", "0.5041101", "0.50330716", "0.5023977", "0.50135475", "0.49974617", "0.49878013", "0.49874687", "0.49601215", "0.49565083", "0.49529597", "0.49501014", "0.49421293", "0.49286035", "0.4928445", "0.49277136", "0.4922941", "0.4921953", "0.49219012", "0.49093354", "0.49039274", "0.4898935", "0.48952726", "0.4892794", "0.48800865", "0.48791993", "0.48785058", "0.4877221", "0.48763412", "0.4875886", "0.48734614", "0.48696518", "0.48695883", "0.48694345", "0.48609328", "0.48513347", "0.4844598", "0.48431537", "0.48226807", "0.4819312", "0.48182908", "0.48131755" ]
0.71834916
0
Add new single file to sync.
static addNewFile(username, fullPath) { const entry = metaUtils.getFileMetadata(username, fullPath); Databases.fileMetaDataDb.update({path: entry.path}, entry, {upsert: true}, (err, doc) => { if (err) { console.log("could not insert : " + err); } else { console.log('Inserted'); } }); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function addFile(fileentry)\n {\n fileentry.peer = \"\" // File is shared by us\n fileentry.name = fileentry.file.name\n\n db.files_put(fileentry, function(error, result)\n {\n if(error)\n console.error(error)\n\n // Notify that the file have been hashed\n else if(self.onhashed)\n self.onhashed(fileentry);\n });\n }", "function addFile(json) {\n reactor[\"a\" /* default */].dispatch(ADD, json);\n}", "function fileAdded(file) {\n // Prepare the temp file data for file list\n var uploadingFile = {\n id : file.uniqueIdentifier,\n file : file,\n type : '',\n owner : 'Emily Bennett',\n size : '',\n modified : moment().format('MMMM D, YYYY'),\n opened : '',\n created : moment().format('MMMM D, YYYY'),\n extention: '',\n location : 'Insurance Manuals > Medical',\n offline : false,\n preview : 'assets/images/etc/sample-file-preview.jpg'\n };\n\n // Append it to the file list\n vm.files.push(uploadingFile);\n }", "function add(file) {\n var self = this;\n\n if (typeof file === 'string') {\n file = vfile$2(file);\n }\n\n // Prevent files from being added multiple times.\n if (self.origins.indexOf(file.history[0]) !== -1) {\n return self\n }\n\n self.origins.push(file.history[0]);\n\n // Add.\n self.valueOf().push(file);\n self.expected++;\n\n // Force an asynchronous operation.\n // This ensures that files which fall through the file pipeline immediately\n // (such as, when already fatally failed) still queue up correctly.\n setImmediate(add);\n\n return self\n\n function add() {\n self.emit('add', file);\n }\n}", "async function handleAddFile() {\n try {\n setLoading(false);\n props.setAddFileName(fileInputRef.current.files[0].name);\n props.setShowUploader(true);\n await addFile(\n props.courseId,\n props.folder,\n fileInputRef.current.files[0],\n props.setUploaderProgress\n );\n } catch (error) {\n console.log(error);\n }\n setLoading(false);\n }", "function addStoredFile (src) {\n\t// Get the stored files object \n\tvar storedFilesObj = getStoredFilesObject()\n\n\t// Add the new file to the files array \n\tstoredFilesObj.files.push(src)\n\n\t// Convert the file to JSON\n\tvar storedFilesJSON = JSON.stringify(storedFilesObj)\n\n\t// Save the file in browser's local storage\n\twindow.localStorage.setItem('joe_storedFiles', storedFilesJSON)\n}", "addFileX(event) {\n let aFile = event.target.files[0];\n if (aFile.type === \"text/plain\"){\n this.files[0] = aFile;\n } \n }", "function ui_multi_add_file(id, file)\n{\n var template = $('#files-template').text();\n template = template.replace('%%filename%%', file.name);\n template = template.replace('%%remove%%', \"data-attach-id=\"+id)\n\n template = $(template);\n template.prop('id', 'uploaderFile' + id);\n template.data('file-id', id);\n\n $('#files').find('li.empty').fadeOut(); // remove the 'no files yet'\n $('#files').prepend(template);\n console.log(\"file added\");\n $(\"button[data-attach-id=\"+id+\"]\").click({\"id\":id}, removeFileElement);\n}", "function addFile(path) {\n db.run(\"INSERT INTO paths VALUES (null, (?))\", path, function (err) {\n if (err) {\n console.log(err);\n return;\n }\n console.log(\"INSERT: \"+this.lastID);\n });\n}", "addFile() {\n this.addCustom('type', {\n inputLabel: 'Property value'\n });\n const index = this.model.length - 1;\n const item = this.model[index];\n item.schema.isFile = true;\n item.schema.inputType = 'file';\n this.requestUpdate();\n }", "static addNewFolder(username, syncPath) {\n const directory = path.resolve(process.env.PD_FOLDER_PATH, username, syncPath);\n const fileList = metaUtils.getFileList(directory);\n\n _.each(fileList, (file) => {\n Databases.fileMetaDataDb.insert(metaUtils.getFileMetadata(username, file));\n });\n }", "addFile(file, metadataPath) {\n let mpath = metadataPath;\n if (!mpath) {\n mpath = path.basename(file);\n }\n this.zipFiles.push({\n path: file,\n metadataPath: mpath\n });\n }", "async function addFile(user, file) {\n // New file reference\n const fileRef = storageRef.child(user + '/' + file.name);\n\n // Send file to the storage\n const req = await fileRef.put(file).then((snapshot) => {\n return true;\n });\n\n return req;\n}", "function fileAdded(file)\n {\n\t\t\t\n // Prepare the temp file data for media list\n var uploadingFile = {\n id : file.uniqueIdentifier,\n file: file,\n type: 'uploading'\n };\n\t\t\t\n\t\t\tvar fileReader = new FileReader();\n fileReader.readAsDataURL(file.file);\n fileReader.onload = function (event)\n {\n vm.user.profilePic= event.target.result;\n\t\t\t\t\t\t//alert(vm.user.media.url);\n };\n\t\t\t\t\t\n // Append it to the media list\n //vm.user.images.unshift(uploadingFile);\n }", "function addFile(fileInfo)\n{\n\tvar $FileObj = $(\"#FileTemplate\").clone();\n\n\t$FileObj.attr(\"id\", \"file-\" + globalFileCount);\n\n\tglobalFileCount++;\n\n\tif(fileInfo.name)\n\t\t$FileObj.find(\".file-name\").html(fileInfo.name);\n\n\tif(fileInfo.size)\n\t\t$FileObj.find(\".file-size\").html(fileInfo.size);\n\n\tif(fileInfo.chunks)\n\t\t$FileObj.find(\".file-chunk\").html(fileInfo.chunks);\n\n\t$(\".file-list-container\").append($FileObj);\n}", "function addFiles() {\n return files.length > 0 ? data.addFiles(files) : Promise.resolve(undefined);\n }", "function addFile(req, res, next) {\n var generateResponse = Api_Response(req, res, next);\n var riskId = req.params.id;\n var fileData = req.body;\n Risk.update(\n {\n _id: riskId\n },\n {\n $push: {\n _files: fileData\n }\n },\n function (error) {\n if (error) {\n return generateResponse(error);\n }\n\n Risk\n .findById(riskId)\n .exec(function (error, risk) {\n if (error) {\n return;\n }\n\n var activity = new Activity({\n action: 'activityFeed.addFileToRisk',\n project: risk.project,\n user: req.user._id,\n risk: risk._id,\n riskName: risk.name\n });\n activity.save(function (error) {});\n\n // Send socket.io message.\n socket.addFileToRisk(risk, fileData, req.user._id);\n });\n\n generateResponse(null);\n }\n );\n}", "function addFile() {\n document.getElementById(\"chronovisor-converter-container\").appendChild(fileTemplate.cloneNode(true));\n maps.push(null);\n files.push(null);\n data.push(null);\n og_data.push(null);\n }", "add(url, content, shouldOverWrite = true) {\r\n return new Files_1(this, `add(overwrite=${shouldOverWrite},url='${url}')`)\r\n .postCore({\r\n body: content,\r\n }).then((response) => {\r\n return {\r\n data: response,\r\n file: this.getByName(url),\r\n };\r\n });\r\n }", "function addFile(file, isTrash) {\n if (isTrash) {\n var fileParent = file.parents[0];\n\n file.originPath = {\n path: getOriginPath(file).html.join(' / '),\n tooltip: getOriginPath(file).tooltip.join(' / '),\n isApp: fileParent.type === 'app',\n appIcon: appIcons.get(fileParent.data.id)\n };\n }\n\n file.formattedDate = formatDate(file.createdAt);\n\n if (file.deletedAt !== null) {\n file.deletedAt = formatDate(file.deletedAt);\n }\n\n currentFiles.push(file);\n\n $('.empty-state').removeClass('active');\n $('.new-menu').removeClass('active');\n\n // Toggle checkbox header to false\n $('.file-table-header input[type=\"checkbox\"]').prop('checked', false);\n $selectAllCheckbox.css({ 'opacity': '1', 'visibility': 'visible' });\n}", "function addNewFile(fileProps, scrollToBottom = false) {\n const newFile = newStudyFileObj(serverState.study._id.$oid)\n Object.assign(newFile, fileProps)\n\n setFormState(prevFormState => {\n const newState = _cloneDeep(prevFormState)\n newState.files.push(newFile)\n return newState\n })\n if (scrollToBottom) {\n window.setTimeout(() => scroll({ top: document.body.scrollHeight, behavior: 'smooth' }), 100)\n }\n }", "addEntry(entry) {\n if (this.getFileId(entry.name) == null) {\n this.entries.push(entry);\n this.content += entry.text;\n\n Net.updateFile(this.id, btoa(this.content));\n\n return true;\n } else {\n return false;\n }\n }", "addFileToClientFiles(fileId, folderName) {\n this.set({\n addFileModal: false\n });\n this.save({\n clientFiles: this.get('clientFiles').concat([{\n ___class: 'ClientFiles',\n folderName: folderName,\n files: {\n ___class: 'Files',\n objectId: fileId,\n }\n }]),\n }, {\n success: (response) => {\n console.log('file added to clientFiles');\n store.files.trigger('change');\n },\n error: (xhr) => {\n console.log('error saving clientFile', xhr);\n }\n });\n }", "function pushFile(file, thumbContext) {\n var fileSize = viewModel.getFileSize(file.size);\n //var codec = getCodec(file);\n viewModel.uploadFilesInfo.push({ name: file.name, size: fileSize, type: file.type, thumbcontext: thumbContext });\n viewModel.uploadFiles.push(file);\n }", "async function add ({\n dir,\n gitdir = path__WEBPACK_IMPORTED_MODULE_0___default.a.join(dir, '.git'),\n fs: _fs,\n filepath\n}) {\n const fs = new FileSystem(_fs);\n const type = 'blob';\n const object = await fs.read(path__WEBPACK_IMPORTED_MODULE_0___default.a.join(dir, filepath));\n if (object === null) throw new Error(`Could not read file '${filepath}'`)\n const oid = await GitObjectManager.write({ fs, gitdir, type, object });\n await GitIndexManager.acquire(\n { fs, filepath: `${gitdir}/index` },\n async function (index) {\n let stats = await fs._lstat(path__WEBPACK_IMPORTED_MODULE_0___default.a.join(dir, filepath));\n index.insert({ filepath, stats, oid });\n }\n );\n // TODO: return oid?\n}", "function _addf( endpoint ){\n\n\tvar files = commander.rawArgs.slice(4);\n\n\tconsole.log(\"_addf\", \"endpoint:\", endpoint, \"files:\", files );\n\n\tvar app = endpoint.split('/')[1];\n\tconsole.log('@addf app', app);\n\t\n\treturn;\n\n\tvar file = path.normalize(scriptfile);\n\tvar info = path.parse(file);\n\n\tif( !cloudfn.utils.is_readable(file) ) return false;\n\tif( !cloudfn.utils.is_javascript(file)) return false;\n\n\tprepareSecureRequest( (userconfig, hash) => {\n\n\t\tvar url = [remote, '@', 'a', userconfig.username, hash].join('/');\n\t\tconsole.log('@add url', url);\n\n\t\tvar formData = {file:fs.createReadStream( file ), name:info.name};\n\n\t\tconsole.log( chalk.green(\"Adding \") + chalk.blue(file)+ \" to server...\" );\n\n\t\trequest.post({url:url, formData: formData}, (err, httpResponse, body) => {\n\t\t\tparse_net_response(err, httpResponse, body, (body) => {\n\t\t\t\tconsole.log('OK Server response:', body);\n\t\t\t\t// TODO: Parse response to determine success\n\t\t\t\t// TODO: Print test instructions (curl or httpie) \n\t\t\t});\n\t\t});\n\t\t\n\t});\n}", "add(name, content) {\r\n return this.clone(AttachmentFiles_1, `add(FileName='${name}')`, false).postCore({\r\n body: content,\r\n }).then((response) => {\r\n return {\r\n data: response,\r\n file: this.getByName(name),\r\n };\r\n });\r\n }", "function addFile()\r\n{\r\n\tvar name = \"file-\" + maxID++;\r\n\t\r\n\tvar input = $('<input type=\"file\">')\r\n\t\t.attr('name', name)\r\n\t\t.attr('id', name);\r\n\t\r\n\tvar close = $('<a>')\r\n\t\t.addClass('close')\r\n\t\t.attr('href', 'javascript: removeFile(\"' + name + '\")')\r\n\t\t.html('&times;');\r\n\t\t\r\n\tvar status = $('<span>')\r\n\t\t.addClass('file-status');\r\n\t\t\r\n\tvar inputDiv = $('<div>')\r\n\t\t.addClass('file-item')\r\n\t\t.append(input)\r\n\t\t.append(status)\r\n\t\t.append(close);\r\n\t\r\n\tconsole.log(\"Adding file input\", input);\r\n\t\r\n\t$('#file-list').append(inputDiv);\r\n\t\r\n\t// Enable the upload button\r\n\t$('#submit-button').removeAttr('disabled');\r\n}", "addFile() {\n let isFile = fs.lstatSync(this.filePath).isFile();\n if (!isFile) {\n this.parent.logger.warn(\n \"[VelopServer][Router] addStaticFile() - path:\" +\n this.filePath +\n \" - is not a file\"\n );\n return;\n }\n\n try {\n var servePath = this.servePath;\n\n let publicPath =\n servePath == \"\"\n ? path.posix.join(\"/\", path.basename(this.filePath))\n : path.posix.join(\"/\", servePath);\n\n this.parent.router.api.get(\n publicPath,\n (ctx, next) => this.authMiddleware(passport, ctx, next),\n async (ctx, next) => {\n await send(ctx, path.basename(this.filePath), {\n root: path.dirname(this.filePath)\n });\n }\n );\n } catch (e) {\n this.parent.logger.warn(\"[VelopServer][Router] addStaticFile()\");\n this.parent.logger.warn(e);\n }\n }", "async add(item) {\n let items = await this.load();\n let idx = items.indexOf(item);\n if (idx !== -1)\n items.splice(idx, 1);\n items.unshift(item);\n fs_1.default.writeFileSync(this.file, items.join('\\n'), 'utf8');\n }", "function createNewFile() {\n file = {\n name: 'novo-arquivo.txt',\n content: '',\n saved: false,\n path: app.getPath('documents') + '/novo-arquivo.txt'\n }\n\n mainWindow.webContents.send('set-file', file)\n}", "function _add( scriptfile ){\n\t\n\tvar file = path.normalize(scriptfile);\n\tvar info = path.parse(file);\n\n\tif( !cloudfn.utils.is_readable(file) ) return false;\n\tif( !cloudfn.utils.is_javascript(file)) return false;\n\n\tprepareSecureRequest( (userconfig, hash) => {\n\n\t\tvar url = [remote, '@', 'a', userconfig.username, hash].join('/');\n\t\tconsole.log('@add url', url);\n\n\t\tvar formData = {file:fs.createReadStream( file ), name:info.name};\n\n\t\tconsole.log( chalk.green(\"Adding \") + chalk.blue(file)+ \" to server...\" );\n\n\t\trequest.post({url:url, formData: formData}, (err, httpResponse, body) => {\n\t\t\tparse_net_response(err, httpResponse, body, (body) => {\n\t\t\t\tconsole.log('OK Server response:', body);\n\t\t\t\t// TODO: Parse response to determine success\n\t\t\t\t// TODO: Print test instructions (curl or httpie) \n\t\t\t});\n\t\t});\n\t\t\n\t});\n}", "add(filename) {\n if (this.index.length == this.max)\n this.remove(this.index.shift());\n this.index.push(filename);\n if (DEBUG) console.log(`Added ${join(this.path, filename)}`);\n }", "function pushFile(file, query) {\n // console.log(file,query)\n // hidden file?\n if (path.basename(file)[0] === '.') {\n // not explicitly asking for hidden files?\n if (!options.all && !(path.basename(query)[0] === '.' && path.basename(query).length > 1))\n return false;\n }\n\n if (platform() === 'win')\n file = file.replace(/\\\\/g, '/');\n\n list.push(file);\n return true;\n }", "createFile(text){\n this.model.push({text});\n\n // This change event can be consumed by other components which\n // can listen to this event via componentWillMount method.\n this.emit(\"change\")\n }", "function syncFile() {\n var insertAtText = '<files>';\n \n for (var i = 0; i < allMissingFiles.length; i++) {\n if (allMissingFiles[i].length) {\n var missingText = '';\n \n for (var x = 0; x < allMissingFiles[i].length; x++) {\n missingText += split + ' <file>/' + allMissingFiles[i][x] + '</file>';\n }\n var index = fileData[i].indexOf(insertAtText);\n fileData[i] = fileData[i].slice(0, (index + insertAtText.length)) + missingText + fileData[i].slice((index + insertAtText.length));\n var fullPath = root + bundleLocation + fileNames[i];\n dialog.logSomething('Writing to location', fullPath);\n file.writeFile(fullPath, fileData[i]);\n }\n }\n \n return ('And done.' + ((allowDialog)?' Please press enter to exit.':''));\n}", "function sync(cb) {\n\t\tvar file_id = $('.file-builder').attr('data-file-id');\n\t\t$.ajax({\n\t\t\turl: '/api/v1/files/' + file_id + '/sync',\n\t\t\tmethod: 'post',\n\t\t\tdataType: 'json',\n\t\t\tcache: false,\n\t\t\tsuccess: function(data) {\n\t\t\t\tif(data.status !== 'success') {\n\t\t\t\t\t//$('#add_section_modal .error-msg').text(data.message);\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tif(typeof cb === 'function') cb(data);\n\n\t\t\t\t\tsetTimeout(function() {\n\t\t\t\t\t\t//window.location.href = '/dashboard';\n\t\t\t\t\t}, 800);\n\t\t\t\t}\n\t\t\t},\n\t\t\terror: function(err) {\n\t\t\t\tif(typeof ShopifyApp !== 'undefined') ShopifyApp.flashError(err.message);\n\t\t\t}\n\t\t});\n\t}", "function addEntry(entry){\n jsfile.readFile(dbFile,(err,data)=>{\n if(!err){\n console.log(\"Read DB Success!\");\n data.push(entry);\n jsfile.writeFile(dbFile,data,(err)=>{\n if(err){\n console.log(\"Added Entry Failure!\");\n }else{\n console.log(\"Added Entry Success!\");\n }\n });\n }else{\n console.log(\"Read DB Failure!\");\n }\n })\n}", "function addFile(filename, filesize){\n\tvar query = connection.query('insert into filelist(school_patch_id, filename, filesize, download_status) values ('+schoolPatchId+',\"'+filename+'\", \"'+filesize+'\",\"0\" ) ', function(err, rows) {\n\t\tif (err)\n\t\t\tthrow err;\n\n\t\tconsole.log(\"file added \"+filename+\" in db after compression\");\n\t});\n}", "function pushFile(file, query) {\n // hidden file?\n if (path.basename(file)[0] === '.') {\n // not explicitly asking for hidden files?\n if (!options.all && !(path.basename(query)[0] === '.' && path.basename(query).length > 1))\n return false;\n }\n \n if (common.platform === 'win')\n file = file.replace(/\\\\/g, '/');\n \n list.push(file);\n return true;\n }", "function add_file_of_point(uid, fobj) {\n var tmp={\"uid\":uid,\"file\":fobj.name};\n ucvm_point_file_list.push(tmp);\n}", "async function addTag(fileID, tag) {\n var file = await getFile(fileID);\n if (file.tags.includes(tag)) {\n // File already has tag -> tag already has file\n console.log(`tag: '${tag}' already linked to ${fileID}`);\n return;\n }\n\n var error, result = await db.readDataPromise('tag', { name: tag });\n if (error)\n console.error(error.stack);\n\n var tagExists = result.length > 0;\n\n if (tagExists) {\n var error2, result2 = await db.updateDataPromise('tag', { name: tag }, { $push: { files: fileID } });\n if (error2)\n console.error(error2.stack);\n\n console.log(\"tag updated\");\n } else {\n // If tag doesnt exist\n var error3, result3 = await db.createDataPromise('tag', {\n name: tag,\n files: [fileID]\n });\n if (error3)\n console.error(error3.stack);\n\n console.log(\"tag created\");\n }\n\n // update file tags\n var error4, result4 = await db.updateData('file', { id: fileID }, { $push: { tags: tag } });\n if (error4)\n console.error(error4.stack);\n\n console.log(\"file tags updated\");\n}", "function addFile(){\n\n let elem = document.getElementById(\"addBox\");\n \n /*\n * adds either a file or directory depending \n */\n if(elem.value.toString().indexOf('.') !== -1){\n console.log(elem.value.toString().indexOf('.') !== -1)\n fs.open(path.join(homedir,elem.value,'/'),'w',function(err) {\n if(err) throw err;\n document.getElementById(\"addBox\").remove();\n objectClick(homedir);\n });\n }else{\n try{\n \n fs.mkdirSync(path.join(homedir,elem.value))\n document.getElementById(\"addBox\").remove();\n objectClick(homedir);\n \n }catch(err) {\n if(err) throw alert(err);\n }\n \n }\n}", "addFile(name, bytes) {\r\n return this.postCore({\r\n body: jsS({\r\n \"@odata.type\": \"#microsoft.graph.fileAttachment\",\r\n contentBytes: bytes,\r\n name: name,\r\n }),\r\n });\r\n }", "addData(filename) {\n let tempArray = []; tempArray.push(filename);\n this.directory = tempArray;\n }", "createFile(path) {\n touch.sync(path.absolute);\n }", "function addFile(target, file) {\n const isImage = file.type.match(\"image.*\"),\n objectURL = URL.createObjectURL(file);\n\n const clone = isImage\n ? imageTempl.content.cloneNode(true)\n : fileTempl.content.cloneNode(true);\n\n clone.querySelector(\"h1\").textContent = file.name;\n clone.querySelector(\"li\").id = objectURL;\n clone.querySelector(\".delete\").dataset.target = objectURL;\n clone.querySelector(\".size\").textContent =\n file.size > 1024\n ? file.size > 1048576\n ? Math.round(file.size / 1048576) + \"mb\"\n : Math.round(file.size / 1024) + \"kb\"\n : file.size + \"b\";\n\n isImage &&\n Object.assign(clone.querySelector(\"img\"), {\n src: objectURL,\n alt: file.name\n });\n\n empty.classList.add(\"hidden\");\n target.prepend(clone);\n\n FILES[objectURL] = file;\n}", "function doFileSynced(id) {\r\n var transaction = db.transaction([\"reqfile\"], (IDBTransaction.READ_WRITE ? IDBTransaction.READ_WRITE : 'readwrite'));\r\n var objectStore = transaction.objectStore(\"reqfile\");\r\n var reqfile = objectStore.get(id);\r\n\r\n reqfile.onsuccess = function(event) {\r\n var data = event.target.result;\r\n data.isSynced = true;\r\n\r\n var reqFileUpdate = objectStore.put(data);\r\n reqFileUpdate.onerror = function(event) {\r\n // Do something with the error\r\n };\r\n reqFileUpdate.onsuccess = function(event) {\r\n // Success - the data is updated!\r\n };\r\n }\r\n\r\n reqfile.onerror = function (event) {\r\n // Do something with the error\r\n };\r\n}", "function addFileToQueue (f) {\n\tfor (var i = 0; i < stats.fileQueue.length; i++) { //see if it's already on the queue\n\t\tif (stats.fileQueue [i].f == f) {\n\t\t\treturn;\n\t\t\t}\n\t\t}\n\tstats.fileQueue [stats.fileQueue.length] = {\n\t\tf: f\n\t\t}\n\t}", "function onItemFileDrop( event ){\n ctrl.addFile( event.dataTransfer.files[0] );\n }", "function addFile(options, name, data)\n{\n if(!options.tree) options.tree = [];\n options.tree.push({path:name, content:JSON.stringify(data, null, 2)});\n}", "moduleAppendFile(file) {\n var moduleFile = path.join(this.srcDir, this.module.dir, this.module.dir)+'-module.js';\n var file = file.replace(/\\\\/g, '/');// no matter win or unix we use unix style\n var str = \"require('./\"+file+\"');\";\n\n var data = fs.readFileSync(moduleFile);\n if(data.indexOf(str) < 0){\n fs.appendFileSync(moduleFile, \"\\n\"+str);\n this.log.info(str, 'appended to', moduleFile);\n } else {\n this.log.info(str, 'already exists in', moduleFile);\n }\n }", "function createRef(file){\n\n\t\t// Create a new fileRef\n\t\tvar pointer = new fileRef({\n\t\t\tname : file.name,\n\t\t\ttype : file.type,\n\t\t\tfile : file\n\t\t}, current_network, current_bucket, true);\n\n\t\tref.push( pointer );\n\n\t\tif(current_folder===\"local\"){\n\t\t\treadFile(file, function(dataURL){\n\n\t\t\t\t// Update list\n\t\t\t\tpointer.update({\n\t\t\t\t\tthumbnail : dataURL,\n\t\t\t\t\tpicture : dataURL\n\t\t\t\t});\n\t\t\t});\n\t\t}\n\t\telse{\n\t\t\t// Upload the files to the current directory\n\t\t\thello.api(current_folder, \"post\", {file: file}, function(r){\n\t\t\t\t// Once the files have been successfully upload lets update the pointer\n\t\t\t\tpointer.update({\n\t\t\t\t\tid : r.id,\n\t\t\t\t\tthumbnail : r.source,\n\t\t\t\t\tpicture : r.source\n\t\t\t\t});\n\t\t\t});\n\t\t}\n\t}", "function appendJSONFile(request) {\n fs.readFile(dbPath, function (err, data) {\n var json = JSON.parse(data);\n request.id = uuidv4();\n json.push(request);\n fs.writeFile(dbPath, JSON.stringify(json), function (err) {\n if (err) throw err;\n console.log('The \"data to append\" was appended to file!');\n });\n });\n}", "function addFileMetadata(filename, done) {\n\tvar params = {\n\t\tTableName : \"AutocareFiles\",\n\t\tItem: {\n\t\t\tObjectKey: filename\n\t\t}\n\t};\n\tvar client = createClient();\n\tclient.put(params, done);\n}", "function addFile(event) {\n const list = document.getElementById('info-files');\n\n const item = document.createElement('li');\n item.classList.add('img_name');\n item.innerHTML = event.match(/[\\/\\\\]([\\w\\d\\s\\.\\-\\(\\)]+)$/)[1];\n\n var buttons = document.createElement('span');\n buttons.classList.add('buttons');\n\n var remove = document.createElement('button');\n remove.classList.add('remove');\n remove.innerHTML = removeButton;\n\n remove.addEventListener('click', removeItem);\n\n buttons.appendChild(remove);\n item.appendChild(buttons);\n\n list.insertBefore(item, list.childNodes[0]);\n}", "function uploadSavedataPending(file) {\n runCommands.push(function () { \n gba.loadSavedataFromFile(file) \n });\n }", "function writeToDB(file1, songName) {\n var transaction = db.transaction([\"audioFiles\"], \"readwrite\");\n var store = transaction.objectStore(\"audioFiles\");\n console.log(file1);\n var request = store.add(file1, songName);\n\n }", "add(uri, content) {\n // Make sure not to override existing content with undefined\n if (content !== undefined || !this.files.has(uri)) {\n this.files.set(uri, content);\n }\n // Add to directory tree\n const filePath = utilities_1.uri2path(uri);\n const components = filePath.split(/[\\/\\\\]/).filter(c => c);\n let node = this.rootNode;\n for (const [i, component] of components.entries()) {\n const n = node.children.get(component);\n if (!n) {\n if (i < components.length - 1) {\n const n = { file: false, children: new Map() };\n node.children.set(component, n);\n node = n;\n }\n else {\n node.children.set(component, { file: true, children: new Map() });\n }\n }\n else {\n node = n;\n }\n }\n this.emit(\"add\", uri, content);\n }", "function filesIncrement() {\n counter = counter + 1;\n\n roamingFolder.createFileAsync(filename, Windows.Storage.CreationCollisionOption.replaceExisting)\n .then(function (file) {\n return Windows.Storage.FileIO.writeTextAsync(file, counter);\n }).done(function () {\n filesDisplayOutput();\n });\n }", "function addWatcher (newPath) {\n fileWatcher = chokidar.watch(newPath, {\n persistent: true,\n ignored: /(^|[/\\\\])\\../ //For .DS_Store on MacOS\n });\n // console.log(newPath)\n //Signals to setMovieFolder that a watcher exists\n isWatching = true;\n fileWatcher.on('ready', async () => {\n // Retrieve files being watched\n let watched = fileWatcher.getWatched();\n watched = watched[newPath]\n // console.log(watched)\n // Calls sync function\n await onReadySync(watched);\n fileWatcher.on('add', filePath => insertMovie(filePath));\n fileWatcher.on('unlink', filePath => removeMovie(filePath));\n fileWatcher.on('error', error => {\n console.error(`FILEWATCHER ERROR: ${error}`)\n }); \n });\n}", "addTemplateFile(fileUrl, templateFileType) {\r\n return this.clone(Files_1, `addTemplateFile(urloffile = '${fileUrl}', templatefiletype = ${templateFileType})`, false)\r\n .postCore().then((response) => {\r\n return {\r\n data: response,\r\n file: this.getByName(fileUrl),\r\n };\r\n });\r\n }", "function addNewTrack() {\n\tlet filename = document.getElementById('newTrack').value.split('\\\\');\n\tfilename = filename[filename.length - 1];\n\tsound.trackInfo.push({fileName: filename, trackName: filename.split('.')[0], input: null, reversed: false, gain: null, min: 0, max: 1, pinToData: true},)\n\n\n\tconst mixer = document.getElementById('mixerBox');\n\tmixer.insertAdjacentHTML('beforeend', `\n\t\t\t<td id='Track${sound.trackInfo.length - 1}' class='mixerTrack'>Track ${sound.trackInfo.length - 1}</td>\n\t\t\t`)\n\n\tsetUpTrack(sound.trackInfo.length - 1);\n}", "addMultiple(files) {\r\n // add the files in series so we don't get update conflicts\r\n return files.reduce((chain, file) => chain.then(() => this.clone(AttachmentFiles_1, `add(FileName='${file.name}')`, false).postCore({\r\n body: file.content,\r\n })), Promise.resolve());\r\n }", "function putFile(file, path) {\n filename = '/';\n if (path !== undefined && !path.startsWith('/')) {\n filename += path;\n }else if (path !== undefined && path.startsWith('/')) {\n filename = path;\n }else if(file.name !== undefined){\n filename = file.name.replace(/^.*?([^\\\\\\/]*)$/, '$1');\n\n }\n var url = 'https://content.dropboxapi.com/2/files/upload';\n var dropboxApiArg = {\n path: filename,\n mode: 'overwrite'\n };\n var fd = new FormData();\n fd.append('file', file, filename);\n return $.ajax({\n type: 'POST',\n url: url,\n data: fd,\n dataType: 'JSON',\n processData: false,\n contentType: false,\n beforeSend: function(request) {\n request.setRequestHeader(\"Authorization\", 'Bearer ' + access_token);\n request.setRequestHeader(\"Dropbox-API-Arg\", JSON.stringify(dropboxApiArg));\n request.setRequestHeader(\"Content-Type\", 'application/octet-stream');\n }\n });\n }", "function fileToUpload(e){\n let files = Files;\n let file = e.target.files[0]\n let category = e.target.name;\n //Check if file already exists or (incase of eventImage) is already bound to input\n let found = false;\n let i;\n for(i = 0; i < files.length; i++){\n if(e.target.name === \"eventImage\" && \n files[i].bound === e.target.name){\n found = true;\n break;\n }\n else if(file && files[i].file.name === file.name){\n found = true;\n break;\n }\n }\n if(found){\n //console.log(\"Dup found\")\n files.splice(i,1);\n }\n else{\n //console.log(\"dup not found\")\n }\n files.push(\n {\n category: category,\n file: file,\n bound: e.target.name\n }\n );\n\n setFiles(files)\n //console.log(Files)\n }", "function addToIpfs (path, cb) {\n return exec(`ipfs add -q ${path} | tail -n1`, (err, hash) => {\n if (hash)\n hash=hash.trim()\n cb(err, hash)\n })\n}", "async function addToClient(client, file, output) {\n\tconst path = require('path');\n\n\tlet c = require(path.join(__dirname, file));\n\tclient.command_list.set(c.name, c);\n\tconsole.log(`* Command ${c.name} successfully loaded.`);\n\toutput ? client.say(target, `Command ${c.name} successfully loaded.`) : null;\n}", "async function addSong(song){\n \n}", "function gotFileEntry(fileEntry) {\n\t\t\tvar d = new Date();\n\t\t\tvar nome_arquivo = d.getTime().toString() + '.jpg';\n\t\t\tfileEntry.moveTo(fs.root, nome_arquivo , fsSuccess, deuerro);\n\t\t}", "function addToFile(data) {\n var promise = new Promise(function (fulfill, reject) {\n // always new line\n var newNote = '\\n';\n var jsonString = JSON.stringify(data);\n\n newNote += jsonString;\n \n // string has been created than can leave\n fulfill();\n \n // append new line out of of chain\n fs.appendFile(path, newNote, function (err) {\n if (err) {\n return reject(err);\n }\n console.log(data)\n });\n\n });\n \n return promise;\n}", "function createFile() {\n var message = 'create file randomly',\n params = {\n message: message,\n committer: {\n name: 'yukihirai0505',\n email: '[email protected]'\n },\n content: Utilities.base64Encode(message)\n },\n data = fetchJson(FILE_URL.replace(FILE_PATH_PLACEHOLDER, getRandomString()), 'PUT', params);\n Logger.log(data);\n}", "addMediaFile(narrationId, filename, tmpPath, type) {\n const filesDir = path.join(config.files.path, narrationId.toString());\n const typeDir = type === \"backgroundImages\" ?\n \"background-images\" : type;\n const finalDir = path.join(filesDir, typeDir);\n\n return getFinalFilename(finalDir, filename).then(finalPath => {\n return Q.nfcall(fs.move, tmpPath, finalPath).then(() => ({\n name: path.basename(finalPath),\n type: type\n }));\n });\n }", "function synchronise(file, fn) {\n var full = path.join(content + file.filename);\n\n // Get file content\n mongo.fetch(file, function save(err, data) {\n if (err) return fn(err);\n\n // Check if we need to do mkdir -p\n mkdirp(path.dirname(full), function(err, created) {\n if (err) return fn(err);\n if (created) console.log([\n ' +++'.magenta,\n created.replace(content, ''),\n 'directory created'\n ].join(' '));\n\n // Write the content to disk.\n fs.writeFile(full, data, function saved(err) {\n if (err) return fn(err);\n\n console.log(' +++ '.green + file.filename + ' synced to drone');\n fn();\n });\n });\n });\n }", "function appendUpload (mediaId) {\n return makePost('media/upload', {\n command : 'APPEND',\n media_id : mediaId,\n media : mediaData,\n segment_index: 0\n }).then(data => mediaId);\n }", "function addEntry(entry){\n jsfile.readFile(dbFile,(err,data)=>{\n if(!err){\n console.log(\"Read DB Success!\");\n data.push(entry);\n jsfile.writeFile(dbFile,data,(err)=>{\n if(err){\n res.writeHead(200, {'Content-Type': 'text/html'});\n res.write(pug.renderFile('erro.pug',{e: \"Erro: não foi possivel escrever na Base de dados!\"}));\n res.end();\n console.log(\"Added Entry Failure!\");\n }else{\n console.log(\"Added Entry Success!\");\n }\n });\n }else{\n res.writeHead(200, {'Content-Type': 'text/html'});\n res.write(pug.renderFile('erro.pug',{e: \"Erro: na leitura da base de dados!\"}));\n res.end();\n console.log(\"Read DB Failure!\");\n }\n })\n}", "function addToModels(file){\n\tvar model = JSON.parse(fse.readFileSync(file, 'utf8'));\t\n\tconsole.log(\"Model Created\" + model.name);\n\tu.enhance(model);\n\tapp.models.push(model);\t\n}", "set file(value) { this._file = value; }", "function insertFile(file) {\n uploadFile(file, function (url) {\n var text = \"[img]\" + url + \"[/img]\";\n typeInTextarea(text);\n });\n }", "function addFile(row, col, action) {\n\t\t\tconsole.log(\"add file example\", row);\n\t\t\tvar d = new Date();\n\t\t\tvar modifyItem = row.entity;\n\t\t\tif(modifyItem != undefined){\n\t\t\t\tmodifyItem.filename='newfile.jpg';\n\t\t\t\tmodifyItem.serial=10;\n\t\t\t\tmodifyItem.date = d;\n\t\t\t}\n\t\t\t//update actions\n\t\t\tvar showButton = (modifyItem.filename && modifyItem.filename != \"\") ? false : true;\n\t\t\tmodifyItem.actions = [\n\t\t\t\t{field: modifyItem.filename, actionFieldType: enums.actionFieldType.getName(\"Text\"), cssClass: \"\"},\n\t\t\t\t{field: 'fa fa-search', actionFieldType: enums.actionFieldType.getName(\"Icon\"), function: searchFunc, showControl: !showButton},\n\t\t\t\t{field: 'fa fa-eye', actionFieldType: enums.actionFieldType.getName(\"Icon\"), function: editFunc, showControl: !showButton},\n\t\t\t\t{field: '/ignoreImages/si_close_entity_normal.png', actionFieldType: enums.actionFieldType.getName(\"Image\"), height: \"16\", width: \"16\", function: deleteFunc, cssClass: \"\", showControl: !showButton},\n\t\t\t\t{field: 'Add File', title: 'Add File', actionFieldType: enums.actionFieldType.getName(\"Button\"), function: addFile, showControl: showButton}\n\t\t\t]\n\t\t\tvar showRowLock = modifyItem.isSelected;\n\t\t\tmodifyItem.lock = [\n\t\t\t\t{field: 'fa fa-check', actionFieldType: enums.actionFieldType.getName(\"Icon\"), showControl: showRowLock}\n\t\t\t]\n\t\t}", "putFile(path,data,callback) { this.engine.putFile(path,data,callback); }", "static createFile(evt, {path=null, str=\"\"}){\n // must have file path\n if(!path){\n let err = \"No file name provided (path is null).\";\n IpcResponder.respond(evt, \"file-create\", {err});\n return;\n }\n\n // figure file path data from file string \n let fileName = path.split(\"/\").pop();\n let dir = path.split(`/${fileName}`)[0];\n let knownFolder = FolderData.folderPaths.includes(path);\n\n // create the file \n FileUtils.createFile(path, str)\n .then(() => {\n // file created\n IpcResponder.respond(evt, \"file-create\", {dir, fileName, knownFolder});\n\n // update recent files \n FolderData.updateRecentFiles([path]);\n })\n .catch(err => {\n // error\n IpcResponder.respond(evt, \"file-create\", {err: err.message});\n });\n }", "async function appendFileAsyncAwait(fileName) {\r\n try {\r\n await fs.promises.appendFile(archivo, \"\\n Nueva linea con appendFile con la forma async await\");\r\n let info = await fs.promises.readFile(fileName, \"utf8\");\r\n console.log(info);\r\n } catch (err) {\r\n console.log(err);\r\n }\r\n}", "add(url, track) {\n this.queue.push(url);\n this.trackInfo.push(track);\n return this.emit('song added', url, track);\n }", "addChunked(url, content, progress, shouldOverWrite = true, chunkSize = 10485760) {\r\n const adder = this.clone(Files_1, `add(overwrite = ${shouldOverWrite}, url = '${url}')`, false);\r\n return adder.postCore()\r\n .then(() => this.getByName(url))\r\n .then(file => file.setContentChunked(content, progress, chunkSize));\r\n }", "async uploadFile(file, createdId){ \n \n let fileName = file.name\n let ext = fileName.slice( fileName.lastIndexOf('.') ) \n \n // -- Add Original file in firebase storage -- //\n let storageRef = firebase.storage().ref()\n let imagesRef = storageRef.child('gallery/'+createdId+ext) \n\n let uploadState = await imagesRef.put(file).then( function(snapshot) { \n console.log('Uploaded !'); \n return true \n }).catch( (error) => {\n console.log(error)\n return false\n });\n \n return uploadState;\n\n // -- //\n \n }", "function reqFilePut(file, requestId) {\r\n var transaction = db.transaction([\"reqfile\"], \"readwrite\");\r\n var objectStore = transaction.objectStore(\"reqfile\");\r\n\r\n\tvar data = {\r\n isSynced: false,\r\n\t\trequestId: requestId,\r\n\t\tfile: file\r\n\t}\r\n\r\n var putRequest = objectStore.put(data);\r\n putRequest.onsuccess = function(event) {\r\n console.log(\"success file put in db\")\r\n uploadFile(file, event.target.result, requestId)\r\n }\r\n\r\n putRequest.onerror = function(event) {\r\n console.log(\"putRequest.onerror fired in reqFileUpdate() - error code: \" + (event.target.error ? event.target.error : event.target.errorCode));\r\n }\r\n}", "addFiles(e) {\n\n this.updateDataTransfer(e);\n\n this.updateUserInterface();\n\n if(this.options.get(\"uploadOnDrop\")) this.form.submit();\n }", "async function addToNext(uri){\n \tconst newTrack = {\n \turi: uri[0],\n \tprovider: \"queue\",\n metadata: {\n is_queued: true, \n }\n }\n const currentQueue = Spicetify.Queue?.next_tracks\n currentQueue.unshift(newTrack)\n await Spicetify.CosmosAsync.put(\"sp://player/v2/main/queue\", {\n revision: Spicetify.Queue?.revision,\n next_tracks: currentQueue,\n prev_tracks: Spicetify.Queue?.prev_tracks\n }).catch( (err) => {\n \tconsole.error(\"Failed to add to queue\",err);\n \t Spicetify.showNotification(\"Unable to Add\");\n \t})\n \tSpicetify.showNotification(\"Added to Play Next\");\n }", "pushTrack() {\n console.log('pushing a song to the local DB')\n }", "function _add( filepath, options ) {\n try {\n var config = require(filepath);\n if( config['defaults'] || config[props.env] ) {\n _merge(config['defaults'], options);\n if( props.env ) {\n _merge(config[props.env], options);\n var fileObj = {\n name: ( config[props.env] && config[props.env].name ) ? config[props.env].name :\n ( config['defaults'] ? config['defaults'].name : undefined ),\n path: filepath\n };\n props.files.push(fileObj);\n }\n } else if( options.flat && config['_type'] !== 'tree' ) {\n // We support flat files that do not have 'default', 'production' and 'development' subsections\n _merge(config, options);\n props.files.push({path: filepath});\n }\n } catch( e ) {\n console.log(\"Error reading config file: %s\", e);\n throw new Error(e);\n }\n}", "put(file) {\n if (file.data.size > this.opts.maxFileSize) {\n return Promise.reject(new Error('File is too big to store.'));\n }\n\n return this.getSize().then(size => {\n if (size > this.opts.maxTotalSize) {\n return Promise.reject(new Error('No space left'));\n }\n\n return this.ready;\n }).then(db => {\n const transaction = db.transaction([STORE_NAME], 'readwrite');\n const request = transaction.objectStore(STORE_NAME).add({\n id: this.key(file.id),\n fileID: file.id,\n store: this.name,\n expires: Date.now() + this.opts.expires,\n data: file.data\n });\n return waitForRequest(request);\n });\n }", "function fileSuccess(file, message) {\n // Iterate through the file list, find the one we\n // are added as a temp and replace its data\n // Normally you would parse the message and extract\n // the uploaded file data from it\n angular.forEach(vm.files, function (item, index)\n {\n if ( item.id && item.id === file.uniqueIdentifier )\n {\n // Normally you would update the file from\n // database but we are cheating here!\n\n // Update the file info\n item.name = file.file.name;\n item.type = 'document';\n\n // Figure out & upddate the size\n if ( file.file.size < 1024 )\n {\n item.size = parseFloat(file.file.size).toFixed(2) + ' B';\n }\n else if ( file.file.size >= 1024 && file.file.size < 1048576 )\n {\n item.size = parseFloat(file.file.size / 1024).toFixed(2) + ' Kb';\n }\n else if ( file.file.size >= 1048576 && file.file.size < 1073741824 )\n {\n item.size = parseFloat(file.file.size / (1024 * 1024)).toFixed(2) + ' Mb';\n }\n else\n {\n item.size = parseFloat(file.file.size / (1024 * 1024 * 1024)).toFixed(2) + ' Gb';\n }\n }\n });\n }", "async duplicateFile(filePath, newFilePath) {\n const die = getDier(this, \"duplicating file\", {\n projectId: this.projectId,\n originalFilePath: filePath,\n filePath: newFilePath\n })\n await this.loadOrDie(die)\n\n const file = this.getFile(filePath) || die(\"File not found.\")\n let contents\n try {\n contents = await file.load()\n } catch (e) {\n die(\"Server error loading file\", e)\n }\n return this.createFile(newFilePath, contents, file.file, die)\n }", "async uploadFile(importFilePath) {\n }", "async uploadFile(importFilePath) {\n }", "function pushToDatabaseWithFile(name, email, message, fileURL) {\n let date = getDate();\n db.collection(\"requests\")\n .add({\n to: \"[email protected]\",\n message: {\n subject: \"New CSB Capstone Request\",\n html:\n \"<div class=”body”><b>Name:</b> \" +\n name +\n \"<br><b>Email:</b> \" +\n email +\n \"<br><b>Message:</b> \" +\n message +\n \"<br><b>File Upload:</b> \" +\n fileURL +\n \"<br><b>Date:</b> \" +\n date +\n \"</div>\",\n },\n })\n .then(function (docRef) {\n console.log(\"Document written with ID: \", docRef.id);\n })\n .catch(function (error) {\n console.error(\"Error adding document: \", error);\n });\n // console.log(\"Successfully updated database.\");\n}", "function addTask(todo) {\n\tconst content = fs.readFileSync('tasks.txt', 'utf-8');\n\tif (content.length === 0) {\n\t\tfs.appendFileSync('tasks.txt', todo);\n\t} else {\n\t\tfs.appendFileSync('tasks.txt', '\\n' + todo);\n\t}\n}", "create() {\n this.proc.args.file = null;\n\n this.emit('new-file');\n\n this.updateWindowTitle();\n }", "async function addFile(content) {\n return await $.ajax({\n url: domain + \"/file\",\n method: \"POST\",\n contentType: \"application/base64\",\n data: content,\n });\n }" ]
[ "0.7210007", "0.68760765", "0.6780189", "0.6696433", "0.64591885", "0.645249", "0.6372322", "0.6353797", "0.6321917", "0.6291319", "0.628938", "0.6272218", "0.6258834", "0.6249308", "0.6246933", "0.6205831", "0.6072826", "0.6072212", "0.60287434", "0.60208046", "0.60112035", "0.6009928", "0.5962396", "0.59506774", "0.59213275", "0.59212714", "0.59005606", "0.5873426", "0.5837784", "0.5793729", "0.5791786", "0.5781739", "0.57809997", "0.5769751", "0.57677084", "0.5704484", "0.56818205", "0.5657016", "0.56524825", "0.5649328", "0.56391233", "0.5631409", "0.56193924", "0.55800885", "0.55765957", "0.55722106", "0.5557585", "0.555642", "0.5554094", "0.5512813", "0.550629", "0.5504033", "0.5481464", "0.5469351", "0.5468826", "0.5460778", "0.54561996", "0.5454638", "0.5439711", "0.5394607", "0.5380482", "0.53786683", "0.5358403", "0.53476274", "0.53432095", "0.53397214", "0.5336252", "0.53286606", "0.53191227", "0.5315448", "0.5302514", "0.52988607", "0.52928185", "0.5277561", "0.5277232", "0.52722836", "0.5271317", "0.52661765", "0.5265023", "0.52510655", "0.5247679", "0.5239991", "0.5230032", "0.5224484", "0.5216969", "0.521579", "0.52154475", "0.5207527", "0.5192488", "0.51923645", "0.51880497", "0.5186793", "0.5182959", "0.51802516", "0.51736146", "0.51736146", "0.5172238", "0.51616365", "0.51577985", "0.5154425" ]
0.6781218
2
Update the current checksum field of an existing entry.
static updateCurrentCheckSum(fullPath, checkSum) { const path = _.replace(fullPath, process.env.PD_FOLDER_PATH, ''); Databases.fileMetaDataDb.update({path: path}, {$set: {current_cs: checkSum}}, {}, (err, numReplaced) => { }); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function checksum() {\n const buf = this.buffer();\n if (buf.length !== 4340) {\n throw new Error('Can only checksum a save block');\n }\n\n // Exclude the existing checksum, then CRC the block\n const dbuf = new Buffer(4336);\n buf.copy(dbuf, 0, 4);\n this.set('checksum', ~crc.crc16ccitt(dbuf) & 0xFFFF);\n}", "function updateCrc(crc,buf,len){for(let n=0;n<len;n++){crc=crc>>>8^crcTable[(crc^buf[n])&255]}return crc}", "function checksum(data) {\n\tvar result = 0;\n\n\tfor (var i = 0; i < 13; i++) {\n\t\tresult += parseInt(data[i]) * (3 - i % 2 * 2);\n\t}\n\n\treturn Math.ceil(result / 10) * 10 - result;\n}", "addChecksum(data) {\n var hash = this.computeChecksum(data)\n // Get first byte of sha256\n var firstChecksumByte = hash[0]\n\n // len() is in bytes so we divide by 4\n var checksumBitLength = data.length / 4\n\n // For each bit of check sum we want we shift the data one the left\n // and then set the (new) right most bit equal to checksum bit at that index\n // staring from the left\n var dataBigInt = new bn(data)\n\n for (var i = 0; i < checksumBitLength; i++) {\n dataBigInt = dataBigInt.mul(bigTwo)\n }\n\n // Set rightmost bit if leftmost checksum bit is set\n if (firstChecksumByte & (1 << (7 - i)) > 0) {\n dataBigInt = dataBigInt.or(bigOne)\n }\n return dataBigInt.toArray(\"be\")\n }", "function __hsbase_MD5Update(ctx, s, n) {\n ctx.md5 = md51(s, n);\n}", "update(crc, data) {\n for (let shift = 8; shift < 16; shift++) {\n const isOne = ((crc ^ (data << shift)) & 0x8000) !== 0;\n crc <<= 1;\n if (isOne) {\n crc ^= this.generator;\n }\n }\n return crc & 0xFFFF;\n }", "async UpdateAsset(ctx, id, color, size, owner, appraisedValue) {\r\n const exists = await this.AssetExists(ctx, id);\r\n if (!exists) {\r\n throw new Error(`The asset ${id} does not exist`);\r\n }\r\n\r\n // overwriting original asset with new asset\r\n const updatedAsset = {\r\n ID: id,\r\n Color: color,\r\n Size: size,\r\n Owner: owner,\r\n AppraisedValue: appraisedValue,\r\n };\r\n return ctx.stub.putState(id, Buffer.from(JSON.stringify(updatedAsset)));\r\n }", "function replaceItemsAndChecksum(comp, config) {\n gw.ext.Util.replaceItems(comp, config);\n comp.checksum = config.checksum;\n}", "function checksumL(filepath){\n\treturn getFileSizeBytes(filepath) % 10000;\n}", "add(entry) {\n this.amount.add(entry.amount);\n this.count += 1;\n this.dbUpdater.update();\n }", "function checksumP(directory){\n\treturn checksum(directory);\n}", "function checksum(text) {\n var a = 1, b = 0;\n for (var index = 0; index < text.length; ++index) {\n a = (a + text.charCodeAt(index)) % 65521;\n b = (b + a) % 65521;\n }\n return (b << 16) | a;\n }", "setContent(data, checksum) {\n if (typeof data === 'object') {\n if (checksum === void 0 || (checksum && checksum !== this.checksum)) {\n this.content = JSON.stringify(data)\n }\n } else {\n this.content = data\n }\n if (checksum === void 0) {\n checksum = this.generateChecksum(this.content)\n }\n const changed = checksum !== this.checksum\n this.checksum = checksum\n return changed\n }", "function updateFee() {\n\t\t// Check for amount errors\n\t\tif(undefined === $(\"#amount\").val() || !nem.utils.helpers.isTextAmountValid($(\"#amount\").val())) return alert('Invalid amount !');\n\n\t\t// Set the cleaned amount into transfer transaction object\n\t\ttransferTransaction.amount = nem.utils.helpers.cleanTextAmount($(\"#amount\").val());\n\n\t\t// Set the message into transfer transaction object\n\t\ttransferTransaction.message = $(\"#message\").val();\n\n\t\t// Prepare the updated transfer transaction object\n\t\tvar transactionEntity = nem.model.transactions.prepare(\"mosaicTransferTransaction\")(common, transferTransaction, mosaicDefinitionMetaDataPair, nem.model.network.data.testnet.id);\n\n\t\t// Format fee returned in prepared object\n\t\tvar feeString = nem.utils.format.nemValue(transactionEntity.fee)[0] + \".\" + nem.utils.format.nemValue(transactionEntity.fee)[1];\n\n\t\t//Set fee in view\n\t\t$(\"#fee\").html(feeString);\n\t}", "function crcUpdateLookup(value, crc) {\n var tmp = crc ^ value;\n crc = (crc >> 8) ^ crc16Lookup[tmp & 0xff];\n return crc;\n }", "function crcUpdateLookup(value, crc) {\n var tmp = crc ^ value;\n crc = (crc >> 8) ^ crc16Lookup[tmp & 0xff];\n return crc;\n }", "async UpdateAsset(ctx, key, value) {\n const exists = await this.AssetExists(ctx, key);\n if (!exists) {\n throw new Error(`The asset ${key} does not exist`);\n }\n\n // overwriting original asset with new asset\n return ctx.stub.putState(key, Buffer.from(value));\n }", "sub(entry) {\n this.amount.sub(entry.amount);\n this.count -= 1;\n this.dbUpdater.update();\n }", "function getElementChecksum(el) {\n var info = nodeToInfoString(el).join(\"\");\n return crc32(info).toString(16);\n }", "function getElementChecksum(el) {\n var info = nodeToInfoString(el).join(\"\");\n return crc32(info).toString(16);\n }", "completeEdit(updatedInfo, entryKey) {\n updatedInfo.searchString = updatedInfo.producer + updatedInfo.origin + updatedInfo.tastingNotes + updatedInfo.text + \"date:\" + updatedInfo.date + updatedInfo.barName;\n updatedInfo.tastingNotes = updatedInfo.tastingNotes ? updatedInfo.tastingNotes : \"(None)\";\n firebase.database().ref('userData/' + this.props.user.uid + '/userJournalEntries/' + entryKey).update(updatedInfo);\n }", "function getElementChecksum(el) {\n var info = nodeToInfoString(el).join(\"\");\n return crc32(info).toString(16);\n }", "markEverythingDirty() {\n this.versionHash++;\n }", "update() {\n\t this.value = this.originalInputValue;\n\t }", "update(){}", "update(){}", "update(){}", "getAddressChecksumString () {\n return secUtil.toChecksumAddress(this.getAddressString())\n }", "function crc_update(crc_in, incr) {\n\n var xor, out, CRC_POLY = 0x1021;\n\n xor = (crc_in >> 15) & 65535;\n out = (crc_in << 1) & 65535;\n\n if (incr > 0) {\n out += 1;\n }\n\n if (xor > 0) {\n out ^= CRC_POLY;\n }\n\n return out;\n\n }", "update() {\n this.$nonces.textContent = this.nonces;\n this.$hashes.textContent = this.totalHashes;\n this.$hashrate.textContent = this.hashrate || 'N/A';\n }", "function update() {\n // Extract from the object id the corresponding index of the array\n let index = checkIndex(this.id)[0];\n\n // Update the array based on the existing value of the array\n if (binaryNumbers[index]) {\n binaryNumbers[index] = 0;\n } else {\n binaryNumbers[index] = 1;\n }\n\n setIconAndNumbers();\n setDecimal();\n}", "modifyMD5Progess(val){\n this.setState({ 'md5Progress': val });\n }", "static async update(query, changes, hash = false) { // (NOT FINISHED - missing the checks for already existing username and email and the changing of role)\n if(!this.validate()) return new Error('VALIDATION')\n\n if (hash) changes = await this.hashPassword(changes)\n\n return await super.update(query, changes)\n }", "enableChecksums(checksum) {\n if (typeof checksum === \"object\") {\n this.checksums = new Set([\n ...this.checksums,\n ...Array.from(checksum).filter((c) => {\n return this.isValidChecksum(c);\n }),\n ]);\n }\n else if (this.isValidChecksum(checksum)) {\n this.checksums.add(checksum);\n }\n return this;\n }", "function getLocalFileCheckSum(bytesperchunk, file) {\n\n var blobSlice = File.prototype.slice || File.prototype.mozSlice || File.prototype.webkitSlice;\n //var blobSlice = file.slice;\n\n // Size of the file\n var SIZE = file.size;\n\n // The total number of file chunks\n var chunks = Math.ceil(file.size / bytesperchunk);\n var currentChunk = 0;\n\n var fileReader = new FileReader();\n\n // SparkMD5 MD5 checksum generator variable\n var spark = new SparkMD5.ArrayBuffer();\n\n fileReader.onload = function (e) {\n\n spark.append(e.target.result); \n currentChunk++;\n\n if (currentChunk < chunks) {\n loadNext();\n }\n else {\n\n // Update the UI with the checksum\n var md5hash = spark.end();\n self.postMessage({ 'action': 'localchecksum', 'checksum': md5hash.toUpperCase() });\n self.postMessage({ 'action': 'localchecksumcompleted' });\n }\n };\n\n fileReader.onerror = function () {\n self.postMessage({ 'action': 'error', 'message': e.message });\n };\n\n function loadNext() {\n\n var start = currentChunk * bytesperchunk,\n end = ((start + bytesperchunk) >= file.size) ? file.size : start + bytesperchunk;\n\n fileReader.readAsArrayBuffer(blobSlice.call(file, start, end));\n }\n\n loadNext();\n\n\n }", "function updateTotalField(totalFieldId, inputAmount) {\n // debugger;\n //get current deposite\n const totalField = document.getElementById(totalFieldId);\n const pretotal = parseFloat(totalField.innerText);\n //get updated deposite\n totalField.innerText = pretotal + inputAmount;\n}", "function sha256_update(data, inputLen) {\n var i, index, curpos = 0;\n /* Compute number of bytes mod 64 */\n index = ((count[0] >> 3) & 0x3f);\n var remainder = (inputLen & 0x3f);\n\n /* Update number of bits */\n if ((count[0] += (inputLen << 3)) < (inputLen << 3)) count[1]++;\n count[1] += (inputLen >> 29);\n\n /* Transform as many times as possible */\n for (i = 0; i + 63 < inputLen; i += 64) {\n for (var j = index; j < 64; j++)\n buffer[j] = data.charCodeAt(curpos++);\n sha256_transform();\n index = 0;\n }\n\n /* Buffer remaining input */\n for (var j = 0; j < remainder; j++)\n buffer[j] = data.charCodeAt(curpos++);\n}", "function calcDigest(){\n\n var digestM = hex_sha1(document.SHAForm.SourceMessage.value);\n\n document.SHAForm.MessageDigest.value = digestM;\n\n }", "function update(chunk) {\n if (typeof chunk === \"string\") return updateString(chunk);\n var length = chunk.length;\n totalLength += length * 8;\n for (var i = 0; i < length; i++) {\n write(chunk[i]);\n }\n }", "function update(chunk) {\n if (typeof chunk === \"string\") return updateString(chunk);\n var length = chunk.length;\n totalLength += length * 8;\n for (var i = 0; i < length; i++) {\n write(chunk[i]);\n }\n }", "function update(chunk) {\n if (typeof chunk === \"string\") return updateString(chunk);\n var length = chunk.length;\n totalLength += length * 8;\n for (var i = 0; i < length; i++) {\n write(chunk[i]);\n }\n }", "function put (_super, key, val, cb) {\n if (!val) {\n this.del(key, cb)\n } else {\n var hash = ethUtil.sha3(key)\n _super(hash, val, cb)\n }\n}", "function updaterSum(){\n\t\t\tlet x = outputSum + bulbSum;\n\t\t\treturn outputSum = x;\n\t\t}", "function editEntry(entry){\n // making entry the variable that represents the entry id which includes amount, name,type\n let ENTRY = ENTRY_LIST[entry.id];\n // if the entry type is an input, we are going to update the item name and cost in the input section\n if (ENTRY.type == \"inputs\"){\n itemTitle.value = ENTRY.title;\n itemAmount.value = ENTRY.amount;\n }\n deleteEntry(entry);\n \n}", "function sha256_update(data, inputLen) {\n var i, index, curpos = 0;\n /* Compute number of bytes mod 64 */\n index = ((count[0] >> 3) & 0x3f);\n var remainder = (inputLen & 0x3f);\n\n /* Update number of bits */\n if ((count[0] += (inputLen << 3)) < (inputLen << 3)) count[1]++;\n count[1] += (inputLen >> 29);\n\n /* Transform as many times as possible */\n for (i = 0; i + 63 < inputLen; i += 64) {\n for (var j = index; j < 64; j++)\n buffer[j] = data.charCodeAt(curpos++);\n sha256_transform();\n index = 0;\n }\n\n /* Buffer remaining input */\n for (var j = 0; j < remainder; j++)\n buffer[j] = data.charCodeAt(curpos++);\n}", "update(chain, chainoffset) {\n\t\tthis.coins = [];\n\t\tthis.searchForCoins(chain, chainoffset);\n\t\tthis.countBalance();\n\t\tthis.lastUpdated = new Date().getTime();\n\t}", "function sha256_update(data, inputLen) {\n var i;\n var index;\n var curpos = 0;\n /* Compute number of bytes mod 64 */\n\n index = count[0] >> 3 & 0x3f;\n var remainder = inputLen & 0x3f;\n /* Update number of bits */\n\n if ((count[0] += inputLen << 3) < inputLen << 3) count[1]++;\n count[1] += inputLen >> 29;\n /* Transform as many times as possible */\n\n for (i = 0; i + 63 < inputLen; i += 64) {\n for (var j = index; j < 64; j++) {\n buffer[j] = data.charCodeAt(curpos++);\n }\n\n sha256_transform();\n index = 0;\n }\n /* Buffer remaining input */\n\n\n for (var j = 0; j < remainder; j++) {\n buffer[j] = data.charCodeAt(curpos++);\n }\n}", "setEntry(entry) {\n this.stream.writeString(entry.filename);\n this.stream.writeFixedString(entry.method);\n this.stream.writeInt(entry.originalSize);\n this.stream.writeInt(entry.reserved);\n this.stream.writeInt(entry.timestamp);\n this.stream.writeInt(entry.dataSize);\n }", "update({ senderWallet, recipient, amount }) {\n if (amount > this.outputMap[senderWallet.publicKey]) {\n throw new Error('Amount exceeds balance')\n }\n\n if (!this.outputMap[recipient]) {\n this.outputMap[recipient] = amount\n } else {\n this.outputMap[recipient] += amount\n }\n\n this.outputMap[senderWallet.publicKey] -= amount\n\n this.input = this.createInput({ senderWallet, outputMap: this.outputMap })\n }", "function addDigest(/* ByteBuffer */ src) {\n\n // Process the message in successive 512-bit (64 byte) chunks:\n // break message into 512-bit (64 byte) chunks\n // Break chunk into sixteen 32-bit big-endian words w[i], 0 <= i <= 15.\n let i = 0;\n for (i = 0; i < 16; i++) {\n w[i] = src.getInt(i*4);\n }\n\n for (i = 16; i < 80; i++) {\n w[i] = 0;\n }\n\n // Compute/add 1 digest line.\n // Extend the sixteen 32-bit (4 byte) words into eighty 32-bit (4 byte) words:\n for (i = 16; i < 80; i++) {\n w[i] = Integer.rotateLeft(w[i-3] ^ w[i-8] ^ w[i-14] ^ w[i-16], 1);\n }\n\n // Initialize hash value for this chunk:\n f = k = temp = 0;\n a = h0;\n b = h1;\n c = h2;\n d = h3;\n e = h4;\n\n for (i = 0; i < 20; i++) {\n f = (b & c) | ((~b) & d);\n k = 0x5A827999;\n finishValues(i);\n }\n\n for (i = 20; i < 40; i++) {\n f = b ^ c ^ d;\n k = 0x6ED9EBA1;\n finishValues(i);\n }\n\n for (i = 40; i < 60; i++) {\n f = (b & c) | (b & d) | (c & d);\n k = 0x8F1BBCDC;\n finishValues(i);\n }\n\n for (i = 60; i < 80; i++) {\n f = b ^ c ^ d;\n k = 0xCA62C1D6;\n finishValues(i);\n }\n\n // Add this chunk's hash to result so far:\n h0 += a;\n h1 += b;\n h2 += c;\n h3 += d;\n h4 += e;\n checkNum(a, b, c, d, e);\n }", "function updateEntry (req, res) {\n logger.debug('Request recieved update entry by id', {loggerModule, URL: req.originalUrl, id: req.params.id})\n _performDatabaseUpdate(req, res, req.body)\n }", "syncInputFieldValue() {\n const me = this,\n input = me.input;\n\n // If we are updating from internalOnInput, we must not update the input field\n if (input && !me.inputting) {\n // Subclasses may implement their own read only inputValue property.\n me.input.value = me.inputValue;\n\n // If it's being manipulated from the outside, highlight it\n if (!me.isConfiguring && !me.containsFocus && me.highlightExternalChange) {\n input.classList.remove('b-field-updated');\n me.clearTimeout('removeUpdatedCls');\n me.highlightChanged();\n }\n }\n me.updateEmpty();\n me.updateInvalid();\n }", "function checksum(array) {\r\n\tvar MODULUS = 65535;\r\n\tvar sum = 0;\r\n\tfor (var i in array) {\r\n\t\tsum = (sum + i) % MODULUS;\r\n\t}\r\n\treturn sum;\r\n}", "function sha256_update(data, inputLen) {\n var i;\n var index;\n var curpos = 0;\n /* Compute number of bytes mod 64 */\n\n index = count[0] >> 3 & 0x3f;\n var remainder = inputLen & 0x3f;\n /* Update number of bits */\n\n if ((count[0] += inputLen << 3) < inputLen << 3) count[1]++;\n count[1] += inputLen >> 29;\n /* Transform as many times as possible */\n\n for (i = 0; i + 63 < inputLen; i += 64) {\n for (var j = index; j < 64; j++) {\n buffer[j] = data.charCodeAt(curpos++);\n }\n\n sha256_transform();\n index = 0;\n }\n /* Buffer remaining input */\n\n\n for (var _j = 0; _j < remainder; _j++) {\n buffer[_j] = data.charCodeAt(curpos++);\n }\n}", "get podfileChecksum() {\n return this.internalData['PODFILE CHECKSUM'];\n }", "updateMetafile (old_position, entry, callback) {\n this.appendMetafile(entry, (err) => {\n if (err) {\n callback(err)\n } else {\n this.deleteFileEntry(old_position, (err) => {\n callback(err)\n })\n }\n })\n }", "function updateDigest(cnode, view) {\n if (cnode.view.parentNode === undefined) throw new Error(`cnode has not been initial digested ${cnode.type.displayName}`);\n cnode.patch = handlePatchVnodeChildren(cnode.patch, cnode.view.parentNode, null, [], cnode, view);\n // CAUTION toDestroyPatch should be reset after update digest.\n cnode.toDestroyPatch = {};\n}", "function manuallyUpdateTotal(silent, cb) {\n if (!silent) {\n nodecg.log.info('Manual donation total update button pressed, invoking update...');\n }\n updateTotal().then(updated => {\n if (updated) {\n nodecg.sendMessage('total:manuallyUpdated', total.value);\n nodecg.log.info('Donation total successfully updated');\n }\n else {\n nodecg.log.info('Donation total unchanged, not updated');\n }\n if (cb && !cb.handled) {\n cb(null, updated);\n }\n }).catch(error => {\n if (cb && !cb.handled) {\n cb(error);\n }\n });\n}", "function updateTotalField(totalFieldId, amount) {\n const totalElement = document.getElementById(totalFieldId);\n const prevTotal = parseFloat(totalElement.innerText);\n totalElement.innerText = prevTotal + amount;\n // console.log(depositTotalText);\n}", "function update() {\n // Update user account\n Lottery.inpUserAddress.value = web3.eth.defaultAccount\n\n // Update Contract\n if (!web3.isAddress(Lottery.inpContractAddress.value)) {\n setErrorMessage(\"Invalid contract address\")\n return false;\n }\n Lottery.contractAddress = Lottery.inpContractAddress.value\n Lottery.contractInstance = web3.eth.contract(Lottery.abi).\n at(Lottery.contractAddress)\n Lottery.contractInstance.defaultAccount = web3.eth.defaultAccount;\n\n setErrorMessage(\"\")\n return true\n}", "function calculateChecksum(sval) {\n var checksum = 0;\n for (var i = 0; i < sval.length; ++i) {\n checksum += parseInt(sval.charAt(i)) * (ACCOUNT_NUMBER_LENGTH - i);\n }\n return checksum;\n }", "update(id, receipt) {\n return 1;\n }", "_onWrite(entry) {\n this._markEntryAsRead(entry)\n this._updateEntries([entry])\n this._decrementSendingMessageCounter()\n }", "update(startingData) {}", "function updateItem(row, data) {\n // Recalculate totals\n var oldTotal = parseFloat(row.children(\".row-total\").text());\n var newTotal = parseFloat(data.price) * parseFloat(data.quantity);\n var sumTotal = parseFloat($(\"#valueSum\").text());\n\n // Update row\n row.children(\".row-product\")\n .children(\"span\")\n .text(data.product);\n\n row.children(\".row-quantity\")\n .text(data.quantity);\n\n row.children(\".row-price\")\n .text(data.price);\n\n row.children(\".row-total\")\n .text(newTotal);\n\n row.data(\"item\", data);\n\n // Update total\n $(\"#valueSum\")\n .text( (sumTotal - oldTotal) + newTotal );\n}", "updateToBit9() {}", "update(dt) {\n logID(1007);\n }", "update() {\n\t if (this.originalInputValue === '') {\n\t this._reset();\n\t }\n\t }", "updateUpload(uploadInfo, completed=false, failed=false){\n var stateToSet = {};\n if (completed){\n stateToSet.uploadStatus = 'Upload complete';\n stateToSet.upload = null;\n stateToSet.file = null;\n this.finishRoundTwo();\n this.setState(stateToSet);\n }else if(failed){\n var destination = this.state.keyComplete[this.state.currKey];\n var payload = JSON.stringify({'status':'upload failed'});\n // set status to upload failed for the file\n ajax.promise(destination, 'PATCH', {}, payload).then((data) => {\n // doesn't really matter what response is\n stateToSet.uploadStatus = 'Upload failed';\n stateToSet.upload = null;\n this.setState(stateToSet);\n });\n }else{ // must be the initial run\n // Calculate the md5sum for the file held in state and save it to the md5\n // field of the current key's context (this can only be a file due to the\n // submission process). Resets file and md5Progess in state after running.\n var file = this.state.file;\n // md5 calculation should ONLY occur when current type is file\n if(file === null) return;\n getLargeMD5(file, this.modifyMD5Progess).then((hash) => {\n // perform async patch to set md5sum field of the file\n var destination = this.state.keyComplete[this.state.currKey];\n var payload = JSON.stringify({ 'md5sum': hash });\n ajax.promise(destination, 'PATCH', {}, payload).then((data) => {\n if(data.status && data.status == 'success'){\n console.info('HASH SET TO:', hash, 'FOR', destination);\n stateToSet.upload = uploadInfo;\n stateToSet.md5Progress = null;\n stateToSet.uploadStatus = null;\n this.setState(stateToSet);\n }else if(data.status && data.title && data.status == 'error' && data.title == 'Conflict'){\n // md5 key conflict\n stateToSet.uploadStatus = 'MD5 conflicts with another file';\n stateToSet.md5Progress = null;\n this.setState(stateToSet);\n }else{\n // error setting md5\n stateToSet.uploadStatus = 'MD5 calculation error';\n stateToSet.md5Progress = null;\n this.setState(stateToSet);\n }\n });\n\n }).catch((error) => {\n stateToSet.uploadStatus = 'MD5 calculation error';\n stateToSet.file = null;\n stateToSet.md5Progress = null;\n this.setState(stateToSet);\n });\n }\n }", "async __updateItem(event) {\n\n\t \thijackEvent(event);\n\n\t \ttry {\n\n\t\t \tconst {item} = event.detail;\n\t\t \t\n\t\t \tawait this.__updateContentDisposition(item);\n\n\t\t \tawait set({\n\t\t coll: this.coll,\n\t\t doc: item.uid,\n\t\t data: item\n\t\t });\n\t \t}\n\t \tcatch (error) {\n\t \t\tconsole.error(error);\n\t \t\tawait warn('An error occured while updating the file.');\n\t \t}\n\t \tfinally {\n\t \t\tthis.__hideSpinner();\t \t\t\n\t \t}\n\t }", "function updateStorageAmount(){\t\t\r\n\t\tstorage.getBytesInUse(function(bytesInUse){\r\n\t\t\tvar bytesAvailable = storage.MAX_ITEMS ? MAX_SYNC_DATA_SIZE : MAX_LOCAL_DATA_SIZE;\r\n\t\t\r\n\t\t\t// set current bytes\r\n\t\t\t$(\".currentBytes\").html(roundByteSizeWithPercent(bytesInUse, bytesAvailable));\r\n\r\n\t\t\t// set total bytes available\r\n\t\t\t$(\".bytesAvailable\").html(roundByteSize(bytesAvailable));\r\n\t\t});\r\n\t}", "function updateTotalField(totalFieldId, amount) {\n const totalElement = document.getElementById(totalFieldId);\n const totalText = totalElement.innerText;\n const previousTotal = parseFloat(totalText);\n totalElement.innerText =previousTotal + amount;\n}", "function updateHexInput(hex) {\r\n\t$('#hex').val(hex);\r\n}", "_updateLastWrittenByte () {\n if (this.offset > this._lastWrittenByte) {\n this._lastWrittenByte = this.offset\n }\n }", "function updateField(event) {\n const val = event.target.value;\n changeAct(val);\n }", "addEntry(entry) {\n if (this.getFileId(entry.name) == null) {\n this.entries.push(entry);\n this.content += entry.text;\n\n Net.updateFile(this.id, btoa(this.content));\n\n return true;\n } else {\n return false;\n }\n }", "function checksum(number) {\n\tvar result = 0;\n\n\tvar i;\n\tfor (i = 0; i < 7; i += 2) {\n\t\tresult += parseInt(number[i]) * 3;\n\t}\n\n\tfor (i = 1; i < 7; i += 2) {\n\t\tresult += parseInt(number[i]);\n\t}\n\n\treturn (10 - result % 10) % 10;\n}", "function checksum(number) {\n\tvar result = 0;\n\n\tvar i;\n\tfor (i = 0; i < 12; i += 2) {\n\t\tresult += parseInt(number[i]);\n\t}\n\tfor (i = 1; i < 12; i += 2) {\n\t\tresult += parseInt(number[i]) * 3;\n\t}\n\n\treturn (10 - result % 10) % 10;\n}", "function updateValue()/*:void*/ {\n if (this.valueDirty$nJmn) {\n this.computeAndTrack$nJmn();\n }\n }", "update() {\n if (this.originalInputValue === '') {\n this._reset();\n }\n }", "_updateLastWrittenByte() {\n if (this.offset > this._lastWrittenByte) {\n this._lastWrittenByte = this.offset;\n }\n }", "function updatetotalField(totalFieldId, Amount){\n const totalElement = document.getElementById(totalFieldId);\n const TotalText = totalElement.innerText;\n const previousTotal = parseFloat(TotalText);\n totalElement.innerText = previousTotal + Amount;\n}", "function checksum(number) {\n\tvar result = 0;\n\n\tvar i;\n\tfor (i = 1; i < 11; i += 2) {\n\t\tresult += parseInt(number[i]);\n\t}\n\tfor (i = 0; i < 11; i += 2) {\n\t\tresult += parseInt(number[i]) * 3;\n\t}\n\n\treturn (10 - result % 10) % 10;\n}", "function checksum(number) {\n\tvar result = 0;\n\n\tvar i;\n\tfor (i = 1; i < 11; i += 2) {\n\t\tresult += parseInt(number[i]);\n\t}\n\tfor (i = 0; i < 11; i += 2) {\n\t\tresult += parseInt(number[i]) * 3;\n\t}\n\n\treturn (10 - result % 10) % 10;\n}", "updateSelfData(ro) {}", "update(newData: Object) {\n this.dbUpdater.checkOkToUpdate();\n\n if (!this.db.transactionIsValid(newData)) {\n throw \"invalid transaction\";\n }\n\n if (newData.guid) {\n if (newData.guid != this.data.guid) {\n throw \"Cannot change transaction GUID.\";\n }\n } else {\n // Specifying GUID in new data is not necessary.\n // TODO: should we extend this to all properties; ie. automatically merge\n // and remove properties with {property: null}?\n newData.guid = this.data.guid;\n }\n\n let oldDate = this.data.date;\n let oldByTimeKey = this._byTimeKey();\n\n // Validation complete, commit change.\n\n Object.freeze(newData);\n this.data = newData;\n\n this.db.atomic(() => {\n if (oldDate != newData.date) {\n this.db.transactionsByTime.delete(oldByTimeKey);\n this.db.transactionsByTime.add(this._byTimeKey(), this);\n }\n\n this._subtractEntries(oldDate);\n this._createEntries(true);\n this.dbUpdater.update();\n });\n }", "fullUpdate() {\n return __awaiter(this, void 0, void 0, function* () {\n const keyrings = yield Promise.all(privates.get(this).keyring.keyrings.map((keyring, index) => __awaiter(this, void 0, void 0, function* () {\n const keyringAccounts = yield keyring.getAccounts();\n const accounts = Array.isArray(keyringAccounts)\n ? keyringAccounts.map((address) => util_1.toChecksumHexAddress(address))\n : /* istanbul ignore next */ [];\n return {\n accounts,\n index,\n type: keyring.type,\n };\n })));\n this.update({ keyrings: [...keyrings] });\n return privates.get(this).keyring.fullUpdate();\n });\n }", "function updateOneFieldTask(id, field, data){\n $cordovaSQLite.execute(db,\n 'UPDATE tasks SET '+ field +' = ? WHERE id = ?',\n [data, id])\n .then(function(result) {}, function(error) {\n console.error('updateOneFieldTask(): ' + error);\n });\n }", "async UpdateAsset(ctx, id, owner, quantity, execution_date, ISIN, rt, clino, settlement_price, status) {\n const exists = await this.AssetExists(ctx, id);\n if (!exists) {\n throw new Error(`The asset ${id} does not exist`);\n }\n\n // overwriting original asset with new asset\n const updatedAsset = {\n ID: id,\n Owner: owner,\n Quantity: quantity,\n Execution_date: execution_date,\n ISIN: ISIN,\n RT: rt,\n CLINO: clino,\n Settlement_price: settlement_price,\n Status: status\n };\n\n return ctx.stub.putState(id, Buffer.from(JSON.stringify(updatedAsset)));\n }", "async update(sourceFile, data){\n const existing = this._storage.getItem(this._key(sourceFile));\n\n if (existing){\n const cmd = JSON.parse(existing);\n if (cmd.type === SourceChange.CREATE || cmd.type == SourceChange.UPDATE){\n // For CREATE, we retain the original info, and ONLY update the data\n // (as though it had been created with this data originally)\n cmd.timestamp = Date.now();\n this._put(sourceFile, cmd);\n this._putData(sourceFile, data);\n } else if (cmd.type === SourceChange.MOVE){\n // TODO promote to UPDATE with new path?\n throw 'TODO: update move';\n } else {\n throw cmd.type;\n }\n } else {\n const cmd = {timestamp: Date.now(), file: sourceFile.simple, type:SourceChange.UPDATE};\n this._put(sourceFile, cmd);\n this._putData(sourceFile, data);\n }\n }", "update(newData: Object) {\n this.dbUpdater.checkOkToUpdate();\n\n if (!Account.isValid(newData)) {\n throw \"invalid account\";\n }\n\n if (this.data.guid == rootForType(this.data.type)) {\n throw \"Cannot update a root account.\";\n }\n\n if (newData.guid) {\n if (newData.guid != this.data.guid) {\n throw \"Cannot change account GUID.\";\n }\n } else {\n // Specifying GUID in new data is not necessary.\n // TODO: should we extend this to all properties; ie. automatically merge\n // and remove properties with {property: null}?\n newData.guid = this.data.guid;\n }\n\n // Reparent the account.\n var newParentGuid = newData.parent_guid || rootForType(newData.type);\n var newParent = this.db.getAccountByGuid(newParentGuid);\n var oldParent = this.parent;\n\n if (!newParent) {\n throw \"parent account does not exist.\";\n }\n\n if (oldParent !== newParent || this.data.name != newData.name) {\n if (newParent.children.has(newData.name)) {\n throw \"account already exists with this name\";\n }\n\n if (!oldParent) {\n throw \"cannot reparent root account.\";\n }\n\n oldParent.children.delete(this.data.name);\n newParent.children.set(newData.name, this);\n\n oldParent._notifySubscribers();\n newParent._notifySubscribers();\n\n this.parent = newParent;\n\n // TODO(haberman) update sums.\n }\n\n Object.freeze(newData);\n\n this.data = newData;\n this.dbUpdater.update();\n }", "function updateSumField(){\r\n var idForSumField = \"sumField\";\r\n\r\n // Create a new node for displaying the sum and the description text\r\n var sum = countSum();\r\n var sumLine = document.createElement(\"p\");\r\n sumLine.setAttribute(\"id\", idForSumField);\r\n var text = document.createTextNode(\"Sum of work to log: \"+sum);\r\n sumLine.appendChild(text);\r\n\r\n // Try to reach the existing sum field element\r\n // If exsting, replace it with the new one, else create it \r\n // below(/above) the table where the numbers reside.\r\n //\r\n var oldField = document.getElementById(idForSumField);\r\n if(oldField){\r\n oldField.parentNode.replaceChild(sumLine,oldField);\r\n }else{\r\n var theTable = getTheTable();\r\n //theTable.parentNode.insertBefore(sumLine, theTable); // inserting before\r\n theTable.parentNode.insertBefore(sumLine, theTable.nextSibling); // inserting after\r\n }\r\n}", "_addToSums() {\n for (let sum of this.sums) { sum.add(this); }\n this.txn.db._invalidateEntryLists(this.account, this.txn.data.date);\n }", "function ballot_updateExistingEntry(existingEntry, items, form){\n if(existingEntry.length === items.length){\n for(var i = 0; i < existingEntry.length; i++){\n gen_updateItem(existingEntry[i], items[i]);\n }\n }\n else if (existingEntry.length > items.length){\n //has image where update does not\n // update section\n gen_updateItem(existingEntry[0], items[0]);\n // update description\n gen_updateItem(existingEntry[2], items[1]);\n // update question\n gen_updateItem(existingEntry[3], items[2]);\n // leave existing image\n }\n else if (existingEntry.length < items.length){\n //does not have image where update does\n // update section\n gen_updateItem(existingEntry[0], items[0]);\n // update description\n gen_updateItem(existingEntry[1], items[2]);\n // update question\n gen_updateItem(existingEntry[3], items[3]);\n // add image and move to section\n var imageItem = gen_addItem(items[1], form);\n form.moveItem(imageItem.getIndex(), existingEntry[0].getIndex() + 1);\n }\n}", "update(item) {\n\t\tthis._cache[item._id] = item;\n\t\tthis.emit(events.CHANGE, item, this);\n\t}", "update(data) {\n return this.ref.update(data);\n }", "update(data) {\n this.data = data || this.data;\n this._updateID++;\n }", "triggerUpdate() {\n let fileId = this.fileNode.id\n this.context.editorSession.transaction((tx) => {\n tx.set([fileId, '__changed__'], '')\n }, { history: false })\n }", "function checksum(number){\n\tvar result = 0;\n\n\tvar i;\n\tfor(i = 0; i < 7; i += 2){\n\t\tresult += parseInt(number[i]) * 3;\n\t}\n\n\tfor(i = 1; i < 7; i += 2){\n\t\tresult += parseInt(number[i]);\n\t}\n\n\treturn (10 - (result % 10)) % 10;\n}", "function checksumC(filepath){\n\treturn checksum(fs.readFileSync(filepath).toString());\n}" ]
[ "0.627834", "0.50350267", "0.5029998", "0.5013496", "0.5000467", "0.49606872", "0.49074638", "0.48740715", "0.4869144", "0.4863068", "0.48421544", "0.47997972", "0.47446272", "0.47335356", "0.47234735", "0.47234735", "0.47167933", "0.47102267", "0.47031474", "0.47031474", "0.46959493", "0.46931583", "0.4672284", "0.46544445", "0.46482977", "0.46482977", "0.46482977", "0.46369347", "0.46349293", "0.46302298", "0.4621508", "0.46065578", "0.4599388", "0.45967218", "0.45923412", "0.45801458", "0.45756215", "0.45451856", "0.4540316", "0.4540316", "0.4540316", "0.45374832", "0.45350257", "0.45192486", "0.451038", "0.4497805", "0.449484", "0.44846615", "0.44815108", "0.44739214", "0.44682148", "0.4466758", "0.44639888", "0.4460451", "0.44523138", "0.44364044", "0.4435866", "0.44308287", "0.44267082", "0.442422", "0.4400102", "0.439822", "0.4392267", "0.43869406", "0.43861952", "0.43793848", "0.43775553", "0.43708846", "0.4362444", "0.43449593", "0.43444207", "0.4337071", "0.43352664", "0.43350744", "0.43335754", "0.43287152", "0.4326482", "0.43198574", "0.4318392", "0.431618", "0.43155864", "0.43101808", "0.4307876", "0.4307876", "0.4299395", "0.4297445", "0.429536", "0.4295056", "0.42942193", "0.4293108", "0.42871132", "0.42804393", "0.4280379", "0.4276191", "0.42749372", "0.4274179", "0.42569938", "0.42563948", "0.42505202", "0.42333356" ]
0.6017338
1
Update the path field of existing entries when renamed.
static updateMetadataForRenaming(oldPath, newPath) { let regex = new RegExp(oldPath); Databases.fileMetaDataDb.find({path: {$regex: regex}}, (err, docs) => { _.each(docs, (doc) => { const newPath = (doc.path).replace(regex, newPath); doc.oldPath = doc.path; doc.path = newPath; Databases.fileMetaDataDb.update({path: doc.oldPath}, doc, {}, (err, numReplaced) => { }); }); }); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "[_changePath] (newPath) {\n // have to de-list before changing paths\n this[_delistFromMeta]()\n const oldPath = this.path\n this.path = newPath\n const namePattern = /(?:^|\\/|\\\\)node_modules[\\\\/](@[^/\\\\]+[\\\\/][^\\\\/]+|[^\\\\/]+)$/\n const nameChange = newPath.match(namePattern)\n if (nameChange && this.name !== nameChange[1])\n this.name = nameChange[1].replace(/\\\\/g, '/')\n\n // if we move a link target, update link realpaths\n if (!this.isLink) {\n this.realpath = newPath\n for (const link of this.linksIn) {\n link[_delistFromMeta]()\n link.realpath = newPath\n link[_refreshLocation]()\n }\n }\n // if we move /x to /y, then a module at /x/a/b becomes /y/a/b\n for (const child of this.fsChildren)\n child[_changePath](resolve(newPath, relative(oldPath, child.path)))\n for (const [name, child] of this.children.entries())\n child[_changePath](resolve(newPath, 'node_modules', name))\n\n this[_refreshLocation]()\n }", "async rename(oldPath, newPath) {\n const changedModel = await this.contentsManager.rename(oldPath, newPath);\n return changedModel;\n }", "rename(oldPath, newPath) {\n return this.services.contents.rename(oldPath, newPath);\n }", "function renameCategory(path, newName) {\n let newPath = util.replaceCategoryNameAtPath(path, newName);\n let parentPath, oldName;\n return CategoryModel.findOne({ path: path })\n .populate('_parent')\n .then((category) => {\n oldName = category.name;\n parentPath = category._parent.path;\n\n category.name = newName;\n category.path = newPath;\n return category.save()\n })\n .then(() => { \n return CategoryModel.findOne({ path: parentPath })\n })\n .then((parent) => {\n let index = parent.childrenNames.indexOf(oldName);\n parent.childrenNames = parent.childrenNames.map((item, i) => {\n if (i === index)\n item = newName;\n return item;\n })\n return parent.save();\n })\n .then(() => {\n return fixPathToChildren(path, newPath);\n });\n}", "function getNewPath(oldPath, newName){\n var i = oldPath.lastIndexOf(\"/\");\n if (i !== -1){\n return oldPath.substr(0, i + 1) + newName;\n } \n else{\n return newName;\n }\n}", "updatePath(newPath) {\n return this.props.convertPathToUrl(newPath)\n .then(\n url => this.setState({path: url})\n )\n .catch(\n e => this.setState({path: null})\n )\n ;\n }", "function changeName(path, ele, isDirectory) {\n var re = new RegExp(oldName, \"g\");\n var oldPath = path + \"/\" + ele;\n var newPath = path + \"/\" + ele.replace(re, newName);\n //修改文件名称\n fs.rename(oldPath, newPath, function (err) {\n if (!err) {\n log.info(oldPath + ' replace ' + newPath);\n if (isDirectory) {\n readDir(newPath);\n } else {\n editFile(newPath);\n }\n } else {\n log.error(err)\n }\n })\n}", "function renameIdentifier(path) {\n // console.log(path.type, path.node.name)\n // console.log(path)\n if (!firstDef && path.scope.bindings[name]) {\n firstDef = path.scope.bindings[name]\n }\n if (path.node.name === name && getDef(path.node.name, path.scope) === firstDef) {\n path.node.name = newName\n }\n }", "function _onFileNameChange(e, oldName, newName) {\n var oldRelPath = ProjectManager.makeProjectRelativeIfPossible(oldName),\n currentPath = $(\"#img-path\").text();\n\n if (currentPath === oldRelPath) {\n var newRelName = ProjectManager.makeProjectRelativeIfPossible(newName);\n $(\"#img-path\").text(newRelName)\n .attr(\"title\", newRelName);\n }\n }", "function updateObject(object, newValue, path){\n var stack = path.split('.');\n while(stack.length>1){object = object[stack.shift()];}\n object[stack.shift()] = newValue;\n }", "_onFileChanged(sender, change) {\n var _a, _b, _c;\n if (change.type !== 'rename') {\n return;\n }\n let oldPath = change.oldValue && change.oldValue.path;\n let newPath = change.newValue && change.newValue.path;\n if (newPath && this._path.indexOf(oldPath || '') === 0) {\n let changeModel = change.newValue;\n // When folder name changed, `oldPath` is `foo`, `newPath` is `bar` and `this._path` is `foo/test`,\n // we should update `foo/test` to `bar/test` as well\n if (oldPath !== this._path) {\n newPath = this._path.replace(new RegExp(`^${oldPath}/`), `${newPath}/`);\n oldPath = this._path;\n // Update client file model from folder change\n changeModel = {\n last_modified: (_a = change.newValue) === null || _a === void 0 ? void 0 : _a.created,\n path: newPath\n };\n }\n this._path = newPath;\n void ((_b = this.sessionContext.session) === null || _b === void 0 ? void 0 : _b.setPath(newPath));\n const updateModel = Object.assign(Object.assign({}, this._contentsModel), changeModel);\n const localPath = this._manager.contents.localPath(newPath);\n void ((_c = this.sessionContext.session) === null || _c === void 0 ? void 0 : _c.setName(PathExt.basename(localPath)));\n this._updateContentsModel(updateModel);\n this._ycontext.set('path', this._path);\n }\n }", "function replacePathInField(path) {\n return \"\" + splitAccessPath(path).map(function (p) { return p.replace('.', '\\\\.'); }).join('\\\\.');\n }", "function replacePathInField(path) {\n\t return `${splitAccessPath(path)\n .map(p => p.replace('.', '\\\\.'))\n .join('\\\\.')}`;\n\t}", "function updateActivePath(path){\r\n\t\tg_activePath = path;\r\n\t\tg_objWrapper.find(\".uc-assets-activepath .uc-pathname\").text(\"..\"+path);\r\n\t}", "function replacePathInField(path) {\n return \"\".concat(splitAccessPath(path).map(escapePathAccess).join('\\\\.'));\n }", "function updateRenameForms() {\n\tdocument.renameFileForm.renamedFile = selectedFile;\n\tdocument.renameFileForm.originalFile = selectedFile;\n}", "function editFile(path) {\n fs.readFile(path, 'utf-8', function (err, data) {\n if (err) {\n log.error(\"Read file error:\" + err);\n } else {\n if (data.indexOf(oldName)) {\n var re = new RegExp(oldName, \"g\");\n if (data.indexOf(oldName) !== -1) {\n fs.writeFile(path, data.replace(re, newName), function (err) {\n if (err) {\n log.error('Modify file failure' + err);\n } else {\n log.info('Modify file success' + path);\n }\n });\n }\n }\n }\n });\n}", "function updateFilePathToIdMap(oldFilePath, newFilePath) {\n \n\t//get the file/dir id based on the old path\n var id = pathToIdMap[oldFilePath];\n \n //delete the mapping from the old path \n delete pathToIdMap[oldFilePath];\n \n //create a new mapping from the new file/dir path to the id \n pathToIdMap[newFilePath] = id;\n}", "function fixPathToChildren(oldPath, newPath) {\n return CategoryModel.find({ path: { $regex: '\\^' + oldPath } })\n .then((categories) => {\n let categoryPromises = categories.map((category) => {\n category.path = category.path.replace(new RegExp('^' + oldPath), newPath);\n return category.save(); \n });\n return Promise.all(categoryPromises);\n })\n .then(() => ArticleModel.find({ path: { $regex: '\\^' + oldPath } }) )\n .then((articles) => {\n let articlePromises = articles.map((article) => {\n article.path = article.path.replace(new RegExp('^' + oldPath), newPath);\n return article.save();\n });\n return Promise.all(articlePromises);\n })\n}", "function updateAllPathToIdMap(oldDirPath, newDirPath) {\n\t\n //add the ending separator if necessary\n oldDirPath = addEndingPathSeparator(oldDirPath);\n newDirPath = addEndingPathSeparator(newDirPath);\n\n\t//holds all the new paths and ids of the files/dirs that have moved \n\tvar movedPaths = {};\n \n //holds all of the paths that need to be deleted from pathToIdMap\n\tvar deletePaths = [];\n\t\n //go through all of the existing path to id mappings \n for(var path in pathToIdMap) {\n if(pathToIdMap.hasOwnProperty(path)) {\n\t\t\n\t\t\t//if the old path is at the beginning of another path\n if(path.startsWith(oldDirPath)) {\n\n\t\t\t\t//get the new updated path\n\t\t\t\tvar updatedPath = path.replace(oldDirPath, newDirPath);\n\t\t\t\t\n //add the new updated path and the id associated with it to a temporary object \n //we don't want to change the object it in the middle of a loop through the properties\n\t\t\t\tmovedPaths[updatedPath] = pathToIdMap[path];\n\n\t\t\t\t//store the path to remove from the pathToId map later \n\t\t\t\tdeletePaths.push(path);\n\t\t\t}\n }\n }\n\n\t//delete the mapping (don't want to add to the object in the middle of a loop\n\t//iterating over the properties)\n\tfor(var i = 0;i < deletePaths.length;i++) {\t\t\n\n //get rid of old mapping\n\t\tdelete pathToIdMap[deletePaths[i]];\n\t}\n\n //now add the new mappings back to the object\n\t//go through all of the moved paths \n for(var path in movedPaths) {\n if(movedPaths.hasOwnProperty(path)) {\n\n\t\t\t//add the new path to id mapping back to the original \n\t\t\tpathToIdMap[path] = movedPaths[path];\n\t\t}\n\t}\n}", "onRename(modelCopy, nameNew, nameOld) {\n\n // Reconstruct the matchers\n var matchers = {};\n for (var name in modelCopy.matchers) {\n if (name === nameOld)\n matchers[nameNew] = modelCopy.matchers[name];\n else\n matchers[name] = modelCopy.matchers[name];\n }\n modelCopy.matchers = matchers;\n\n // Rename references from index field names to the old matcher name\n for (var i in modelCopy.indices) {\n var index = modelCopy.indices[i];\n for (var f in index.fields) {\n var field = index.fields[f];\n if (field.matcher === nameOld)\n modelCopy.indices[i].fields[f].matcher = nameNew;\n }\n }\n\n return modelCopy;\n }", "save() {\n // Check if the form is valid\n if (!this.isValid()) {\n // TODO mark the field as invalid\n return;\n }\n let newName = this.$refs.nameField.value;\n if (this.extension.length) {\n newName += `.${this.item.extension}`;\n }\n\n let newPath = this.item.directory;\n if (newPath.substr(-1) !== '/') {\n newPath += '/';\n }\n\n // Rename the item\n this.$store.dispatch('renameItem', {\n path: this.item.path,\n newPath: newPath + newName,\n newName,\n });\n }", "function move(newPath) {\n fetchData(false);\n }", "set path(value){\r\n\t\tvalue = this.resolvePathVars(this.resolveDotPath(value))\r\n\r\n\t\tvar l = this.location\r\n\r\n\t\tif(value == l || value == ''){\r\n\t\t\treturn }\r\n\r\n\t\t// old...\r\n\t\tvar otitle = this.title\r\n\t\tvar odir = this.dir\r\n\r\n\t\tif(this.exists(l)){\r\n\t\t\tthis.__wiki_data[value] = this.__wiki_data[l] }\r\n\t\tthis.location = value\r\n\r\n\t\t// new...\r\n\t\tvar ntitle = this.title\r\n\t\tvar ndir = this.dir\r\n\r\n\t\tvar redirect = false\r\n\r\n\t\t// update links to this page...\r\n\t\tthis.pages(function(page){\r\n\t\t//this.get('**').map(function(page){\r\n\t\t\t// skip the old page...\r\n\t\t\tif(page.location == l){\r\n\t\t\t\treturn }\r\n\t\t\tpage.raw = page.raw.replace(page.__wiki_link__, function(lnk){\r\n\t\t\t\tvar from = lnk[0] == '[' ? lnk.slice(1, -1) : lnk\r\n\r\n\t\t\t\t// get path/title...\r\n\t\t\t\tvar p = path2lst(from)\r\n\t\t\t\tvar t = p.pop()\r\n\t\t\t\tp = normalizePath(p)\r\n\r\n\t\t\t\tvar target = page.get(p).acquire('./'+t)\r\n\t\t\t\t// page target changed...\r\n\t\t\t\t// NOTE: this can happen either when a link was an orphan\r\n\t\t\t\t// \t\tor if the new page path shadowed the original \r\n\t\t\t\t// \t\ttarget...\r\n\t\t\t\t// XXX should we report the exact condition here???\r\n\t\t\t\tif(target == value){\r\n\t\t\t\t\tconsole.log('Link target changed:', lnk, '->', value)\r\n\t\t\t\t\treturn lnk\r\n\r\n\t\t\t\t// skip links that do not resolve to target...\r\n\t\t\t\t} else if(page.get(p).acquire('./'+t) != l){\r\n\t\t\t\t\treturn lnk }\r\n\r\n\t\t\t\t// format the new link...\r\n\t\t\t\tvar to = p == '' ? ntitle : p +'/'+ ntitle\r\n\t\t\t\tto = lnk[0] == '[' ? '['+to+']' : to\r\n\r\n\t\t\t\t// explicit link change -- replace...\r\n\t\t\t\tif(from == l){\r\n\t\t\t\t\t//console.log(lnk, '->', to)\r\n\t\t\t\t\treturn to\r\n\r\n\t\t\t\t// path did not change -- change the title...\r\n\t\t\t\t} else if(ndir == odir){\r\n\t\t\t\t\t// conflict: the new link will not resolve to the \r\n\t\t\t\t\t// \t\ttarget page...\r\n\t\t\t\t\tif(page.get(p).acquire('./'+ntitle) != value){\r\n\t\t\t\t\t\tconsole.log('ERR:', lnk, '->', to,\r\n\t\t\t\t\t\t\t'is shadowed by:', page.get(p).acquire('./'+ntitle))\r\n\t\t\t\t\t\t// XXX should we add a note to the link???\r\n\t\t\t\t\t\tredirect = true\r\n\r\n\t\t\t\t\t// replace title...\r\n\t\t\t\t\t} else {\r\n\t\t\t\t\t\t//console.log(lnk, '->', to)\r\n\t\t\t\t\t\treturn to }\r\n\r\n\t\t\t\t// path changed -- keep link + add redirect page...\r\n\t\t\t\t} else {\r\n\t\t\t\t\tredirect = true }\r\n\r\n\t\t\t\t// no change...\r\n\t\t\t\treturn lnk }) })\r\n\r\n\t\t// redirect...\r\n\t\t//\r\n\t\t// XXX should we use a template here???\r\n\t\t// \t\t...might be a good idea to set a .redirect attr and either\r\n\t\t// \t\tdo an internal/transparent redirect or show a redirect \r\n\t\t// \t\ttemplate\r\n\t\t// \t\t...might also be good to add an option to fix the link from\r\n\t\t// \t\tthe redirect page...\r\n\t\tif(redirect){\r\n\t\t\tconsole.log('CREATING REDIRECT PAGE:', l, '->', value, '')\r\n\t\t\tthis.__wiki_data[l].raw = 'REDIRECT TO: ' + value\r\n\t\t\t\t+'<br>'\r\n\t\t\t\t+'<br><i>NOTE: This page was created when renaming the target '\r\n\t\t\t\t\t+'page that resulted new link being broken (i.e. resolved '\r\n\t\t\t\t\t+'to a different page from the target)</i>'\r\n\t\t\tthis.__wiki_data[l].redirect = value\r\n\r\n\t\t// cleaup...\r\n\t\t} else {\r\n\t\t\tdelete this.__wiki_data[l] } }", "set path(path) {\n this._path = path;\n this.setAttribute('path', path);\n }", "function rename(oldpath, newpath) {\n // debug('rename', oldpath, newpath);\n return syscall(x86_64_linux_1.SYS.rename, oldpath, newpath);\n}", "function editLineName(lineToEdit, oldName, j, i){\n let newName = newNamesArray[j]\n let newLine = lineToEdit.replace(oldName, newName);\n arrayOfLinesStrings[i] = newLine\n // console.log(arrayOfLinesStrings[i])\n}", "set path(value) {}", "addPathAttributeToFiles(where) {\n\t\tthis.getStores().forEach((store) => {\n\t\t\tconst files = store.getCollection();\n\n\t\t\t// By default update only files with no path set\n\t\t\tfiles.find(where || { path: null }, { fields: { _id: 1 } }).forEach((file) => {\n\t\t\t\tfiles.direct.update(file._id, { $set: { path: store.getFileRelativeURL(file._id) } });\n\t\t\t});\n\t\t});\n\t}", "set transformPaths(value) {}", "appendPath(path) {\n if (path) {\n let currentPath = this.getPath();\n if (currentPath) {\n if (!currentPath.endsWith(\"/\")) {\n currentPath += \"/\";\n }\n if (path.startsWith(\"/\")) {\n path = path.substring(1);\n }\n path = currentPath + path;\n }\n this.set(path, \"PATH\");\n }\n }", "appendPath(path) {\n if (path) {\n let currentPath = this.getPath();\n if (currentPath) {\n if (!currentPath.endsWith(\"/\")) {\n currentPath += \"/\";\n }\n if (path.startsWith(\"/\")) {\n path = path.substring(1);\n }\n path = currentPath + path;\n }\n this.set(path, \"PATH\");\n }\n }", "async rename(srcPath, destPath) {\n const validSrc = await this.protectWhitespace(srcPath);\n const validDest = await this.protectWhitespace(destPath);\n await this.send(\"RNFR \" + validSrc);\n return this.send(\"RNTO \" + validDest);\n }", "function changePropertyName(obj, old, _new) {\n obj[_new] = obj[old];\n delete obj[old];\n}", "async renameLocalFile(path, newPath){\n const response = fs.promises.rename(path, newPath).then(async (msg) => {\n return true;\n }).catch(error => {\n Logger.log(error);\n return false;\n });\n\n return response;\n }", "function updateAttr(attr) {\n var newPath = path + $(this).attr(attr).replace(/^recursos/, '');\n return $(this).attr(attr, newPath);\n }", "function renameDir(newDirPath, newDirName, oldDirPath, timestamp) {\n\n //if this should be ignored due to the st-ignore.json file\n if(!ignoreThisFileOrDir(newDirPath)) {\n\n //get the id of the renamed dir\n var dirId = getIdFromDirPath(oldDirPath);\n\n //if the directory is being tracked\n if(dirId) {\n\n //get the old name of the dir\n var oldDirName = allDirs[dirId].currentName;\n\n //update the current name of the dir in the collection of all dirs\n allDirs[dirId].currentName = newDirName;\n\n //create a rename directory event\n var renameDirectoryEvent = {\n id: \"ev_\" + branchId + \"_\" + autoGeneratedEventId, \n timestamp: timestamp,\n type: \"Rename Directory\",\n directoryId: dirId,\n newDirectoryName: newDirName,\n oldDirectoryName: oldDirName,\n createdByDevGroupId: currentDeveloperGroup.id\n };\n \n //increase the id so the next event has a unique id\n autoGeneratedEventId++;\n \n //add the event to the collection of all events\n codeEvents.push(renameDirectoryEvent);\t\n \n //update all of the path to id mappings for the renamed dir\n updateAllPathToIdMap(oldDirPath, newDirPath);\n }\n }\n}", "onOk(){\n var view = this.insideFrame().childViewByType('View')\n var path = view.childWidgetByType('Tree').getSelectionPath()\n path.push(this.fileName)\n this.onRenameFile(path)\n }", "function rename(obj) {\n if (!obj) obj = myDiagram.selection.first();\n if (!obj) return;\n myDiagram.startTransaction(\"rename\");\n var newName = prompt(\"Rename \" + obj.part.data.item + \" to:\", obj.part.data.item);\n myDiagram.model.setDataProperty(obj.part.data, \"item\", newName);\n myDiagram.commitTransaction(\"rename\");\n}", "function _updatePath() {\n\t\tdocument.documentElement.canAdvance = inputFile && outputFile;\n\t\tif (inputFile) document.getElementById(\"input-path\").value = inputFile.path;\n\t\tif (outputFile) document.getElementById(\"output-path\").value = outputFile.path;\n\t}", "function updateFolder(id, name, new_name) {\n\n if(!queryResource(2, 1, name, new_name, '')) return false;\n\n jQuery('#folder_title_'+id).text(new_name);\n\n return true;\n}", "function changeDirectory(path) {\n let nextNode = nodeFrom(path);\n if (nextNode === undefined || nextNode.type === 'file') {\n badCommand();\n return;\n }\n currentNode = nextNode;\n currentPointer = currentNode.name;\n window.location.hash = currentPointer;\n let $inputParagraph = $terminal.find('div').find('p').last();\n $inputParagraph.attr('data-prompt', getPrompt());\n updateAllowedCommands();\n}", "@onPathChanged(\"lastName\", [\"modify\"])\n\t\t@spyDecorator\n\t\tonPathRegisteredCallback() {}", "getRenameLocation() {\n return this.getLocationConfig(UpdateMode.rename);\n }", "function setPath(obj, value, path) {\n var keys = path.split('.');\n var ret = obj;\n var lastKey = keys[keys.length - 1];\n var target = ret;\n var parentPathKeys = keys.slice(0, keys.length - 1);\n parentPathKeys.forEach(function (key) {\n if (!target.hasOwnProperty(key)) {\n target[key] = {};\n }\n target = target[key];\n });\n target[lastKey] = value;\n return ret;\n }", "function setPath(obj, value, path) {\n var keys = path.split('.');\n var ret = obj;\n var lastKey = keys[keys.length - 1];\n var target = ret;\n var parentPathKeys = keys.slice(0, keys.length - 1);\n parentPathKeys.forEach(function (key) {\n if (!target.hasOwnProperty(key)) {\n target[key] = {};\n }\n target = target[key];\n });\n target[lastKey] = value;\n return ret;\n }", "_updateCurrentPath() {\n let current = this.currentWidget;\n let newValue = '';\n if (current && current instanceof DocumentWidget) {\n newValue = current.context.path;\n }\n this._currentPathChanged.emit({\n newValue: newValue,\n oldValue: this._currentPath\n });\n this._currentPath = newValue;\n }", "function setPath(obj, value, path) {\n var keys = path.split('.');\n var ret = obj;\n var lastKey = keys[keys.length -1];\n var target = ret;\n\n var parentPathKeys = keys.slice(0, keys.length -1);\n parentPathKeys.forEach(function(key) {\n if (!target.hasOwnProperty(key)) {\n target[key] = {};\n }\n target = target[key];\n });\n\n target[lastKey] = value;\n return ret;\n }", "rename () {\n }", "function updateFile(path, tagnames, caption) {\n //removePath(path);\n var pathid;\n var captionid;\n db.serialize();\n db.get(\"SELECT pathid FROM paths WHERE path LIKE (?)\", path, function (err, row) {\n if (err) {\n console.log(err);\n return;\n }\n pathid = row.tagid;\n console.log(\"pathid: \"+pathid);\n db.run(\"DELETE FROM tags WHERE pathid=(?)\", pathid);\n db.run(\"INSERT INTO captions VALUES (null, (?))\", caption, function (err) {\n if (err) {\n console.log(err);\n return;\n }\n console.log(\"INSERT CAPTION: \"+this.lastID);\n captionid = this.lastID;\n for (var i = tagnames.length - 1; i >= 0; i--) {\n db.get(\"SELECT tagid FROM tagnames WHERE name LIKE (?)\", tagnames[i], function (err, row) {\n if (err) {\n console.log(err);\n return;\n }\n // XXX: tagnames must be in tagnames already\n db.run(\"INSERT INTO tags VALUES ($tagid, $path, $pos, $captionid)\", {\n $tagid: row.tagid,\n $path: pathid,\n $pos: null,\n $captionid: captionid\n }, function (err) {\n if (err) {\n console.log(err);\n return;\n }\n });\n });\n }\n });\n });\n}", "function updateSiblingKeys(fromIndex, incrementBy) {\n var paths = this.parent._paths;\n for (var i = 0; i < paths.length; i++) {\n var path = paths[i];\n if (path.key >= fromIndex) {\n path.key += incrementBy;\n }\n }\n}", "function rename(newname) {\n let currentPath = arr[\"dir_name\"] + '/' + fname;\n let newPath = arr[\"dir_name\"] + '/' + newname;\n let obj = {\n \"currentPath\": currentPath,\n \"newPath\": newPath,\n \"currentName\": fname,\n \"newName\": newname\n }\n $.ajax({\n type: 'POST',\n dataType: \"text\",\n contentType: \"application/json\",\n url: \"/rename\",\n cache: false,\n data: JSON.stringify(obj),\n success: function (response) {\n console.log(response);\n listDir();\n },\n error: function (err) {\n console.log(err);\n }\n });\n}", "function normalize(namePath) {\n return namePath.map(function (cell) {\n return \"\".concat((0, _typeof2.default)(cell), \":\").concat(cell);\n }) // Magic split\n .join(SPLIT);\n}", "function updateSiblingKeys(fromIndex, incrementBy) {\n\t var paths = this.parent._paths;\n\t for (var i = 0; i < paths.length; i++) {\n\t var path = paths[i];\n\t if (path.key >= fromIndex) {\n\t path.key += incrementBy;\n\t }\n\t }\n\t}", "function updateSiblingKeys(fromIndex, incrementBy) {\n\t var paths = this.parent._paths;\n\t for (var i = 0; i < paths.length; i++) {\n\t var path = paths[i];\n\t if (path.key >= fromIndex) {\n\t path.key += incrementBy;\n\t }\n\t }\n\t}", "renameFields() {\n for (var i = this.fields.length - 1; i >= 0; i--) {\n this.fields[i].attribute = this.key + '__' + this.fields[i].attribute;\n this.fields[i].validationKey = this.fields[i].attribute;\n\n if (this.fields[i].dependsOn) {\n Object.keys(this.fields[i].dependsOn).forEach(key => {\n this.fields[i].dependsOn[`${this.key}__${key}`] = this.fields[i].dependsOn[key];\n delete this.fields[i].dependsOn[key];\n });\n }\n }\n }", "updateCrumbs() {\n console.debug(this.dir);\n let elements = this.dir.split('/'),\n pathPrefix = '/gi_album',\n path = _.map(elements, (elem) => {\n if (elem === '') {\n return {\n name: 'Album',\n url: '/gi_album'\n };\n } else {\n let prefix = pathPrefix;\n pathPrefix = pathPrefix + '/' + elem;\n return {\n name: elem,\n url: prefix + '/' + elem\n };\n }\n });\n path.unshift({\n name: 'Home',\n url: '/'\n });\n this.Breadcrumb.setPath(path);\n\n // HACK KI to update document title\n document.title = path[path.length -1].name;\n }", "function trackRename(){\n oldRename = Notebook.__proto__.rename\n Notebook.__proto__.rename = function(){\n new_name = arguments[0]\n\n // POST request to rename files\n // rename folder\n // rename db\n // rename ipynb\n\n return oldRename.apply(this, arguments)\n }\n }", "update(path, newValue) {\n // this.currentData is about to become the \"previous generation\"\n const prevData = this.currentData;\n\n if (path.length === 0) {\n // Replace the data entirely. We must manually force its immutability when we do this.\n this.currentData = Immutable(newValue);\n }\n else {\n // Apply the update to produce the next generation. Because this.currentData has\n // been processed by seamless-immutable, nextData will automatically be immutable as well.\n this.currentData = this.currentData.setIn(path, newValue);\n }\n\n // Notify all change listeners\n for (let changeListener of this.changeListeners) {\n let shouldUpdate = true;\n let shorterPathLength = Math.min(path.length, changeListener.path.length);\n\n // Only update if the change listener path is a sub-path of the update path (or vice versa)\n for(let i = 1; i < shorterPathLength; i++) {\n shouldUpdate = shouldUpdate && (path[i] === changeListener.path[i])\n }\n\n if(shouldUpdate) {\n // Only call change listener if associated path data has changed\n if(getIn(this.currentData, changeListener.path) !== getIn(prevData, changeListener.path)) {\n // Pass nextData first because many listeners will ONLY care about that.\n changeListener(this.currentData, prevData, path);\n }\n }\n }\n }", "async function renameResourceFiles() {\n try {\n const resourceRoomName = await getResourceRoomName();\n const { gitTree, currentCommitSha } = await getTree();\n const newGitTree = await modifyTreeResourcePages(gitTree, resourceRoomName);\n await sendTree(newGitTree, currentCommitSha);\n } catch (err) {\n console.log(err);\n throw err;\n }\n}", "_pathSet(path, value) {\n let obj = this.fieldNode; // we set the values relative to the fieldnode, so fieldnode is the root\n const parts = path.split('.');\n while (parts.length > 1) {\n const key = parts.shift();\n // create if not exist\n if (!(key in obj)) {\n obj[key] = {};\n }\n obj = obj[key];\n }\n obj[parts.shift()] = value;\n }", "function rename(src, dst, cb) {\n\tvar err = -2; // -ENOENT assume failure\n\tlookup(connection, src, function(source) {\n\n\t\t\tif (source.type === 'file') { // existing file\n\t\t\tvar dest = lookup(connection, dst);\n\t\t\tif (dest.type === 'undefined') {\n\t\t\tdest.parent = lookup(connection, path.resolve(paths.join(dst,\"..\")));\n\t\t\tconnection.updateFile(source.id, {\"name\": dst, \"id\": dest.parent.id}, cb);\n\t\t\terr = 0;\n\t\t\t} else {\n\t\t\terr = -17; // -EEXIST\n\t\t\t}\n\t\t\t} else if (source.type === 'folder') { // existing file\n\t\t\tvar dest = lookup(connection, dst);\n\t\t\tif (dest.type === 'undefined') {\n\t\t\tdest.parent = lookup(connection, paths.resolve(paths.join(dst,\"/..\")));\n\t\t\tconnection.updateFolder(source.id, {\"name\": dst, \"id\": dest.parent.id}, cb);\n\t\t\terr = 0;\n\t\t\t} else {\n\t\t\terr = -17; // -EEXIST\n\t\t\t}\n\t\t\t} \n\t\t\tcb(err);\n\t});}", "function renameFile(newFilePath, newFileName, oldFilePath, timestamp) {\n\n //if this should be ignored due to the st-ignore.json file \n if(!ignoreThisFileOrDir(newFilePath)) {\n \n //get the id of the renamed file\n var fileId = getIdFromFilePath(oldFilePath);\n \n //if the file is being tracked\n if(fileId) {\n\n //update the mapping from path to id\n updateFilePathToIdMap(oldFilePath, newFilePath);\n \n //get the old name of the file\n var oldFileName = allFiles[fileId].currentName;\n \n //update the current name of the file in the collection of all files\n allFiles[fileId].currentName = newFileName;\n\n //create a rename file event\n var renameFileEvent = {\n id: \"ev_\" + branchId + \"_\" + autoGeneratedEventId,\n timestamp: timestamp,\n type: \"Rename File\",\n fileId: fileId,\n newFileName: newFileName,\n oldFileName: oldFileName,\n createdByDevGroupId: currentDeveloperGroup.id\n };\n \n //increase the id so the next event has a unique id\n autoGeneratedEventId++;\n \n //add the event to the collection of all events\n codeEvents.push(renameFileEvent);\n }\n }\t\t\n}", "function rename(document, update) {\r\n var fields, i, existingFieldName, newFieldName;\r\n\r\n if (update.$rename) {\r\n fields = Object.keys(update.$rename);\r\n for (i = 0; i < fields.length; i++) {\r\n existingFieldName = fields[i];\r\n newFieldName = update.$rename[fields[i]];\r\n\r\n if (existingFieldName == newFieldName) {\r\n throw new Error(\"Bad $rename parameter: The new field name must differ from the existing field name.\")\r\n } else if (document[existingFieldName]) {\r\n // If the field exists, set/overwrite the new field name and unset the existing field name.\r\n document[newFieldName] = document[existingFieldName];\r\n delete document[existingFieldName];\r\n } else {\r\n // Otherwise this is a noop.\r\n }\r\n }\r\n }\r\n }", "async function renamePhotosDirectoryTo(appId, newName, useKeyboardShortcut) {\n if (useKeyboardShortcut) {\n chrome.test.assertTrue(await remoteCall.callRemoteTestUtil(\n 'fakeKeyDown', appId,\n ['body', 'Enter', true /* ctrl */, false, false]));\n } else {\n await clickDirectoryTreeContextMenuItem(\n appId, '/Downloads/photos', 'rename');\n }\n await remoteCall.waitForElement(appId, '.tree-row input');\n await remoteCall.inputText(appId, '.tree-row input', newName);\n await remoteCall.callRemoteTestUtil(\n 'fakeKeyDown', appId, ['.tree-row input', 'Enter', false, false, false]);\n}", "function updateSiblingKeys(fromIndex, incrementBy) {\n\t if (!this.parent) return;\n\n\t var paths = this.parent[_constants.PATH_CACHE_KEY];\n\t for (var i = 0; i < paths.length; i++) {\n\t var path = paths[i];\n\t if (path.key >= fromIndex) {\n\t path.key += incrementBy;\n\t }\n\t }\n\t}", "function updateSiblingKeys(fromIndex, incrementBy) {\n\t if (!this.parent) return;\n\n\t var paths = this.parent[_constants.PATH_CACHE_KEY];\n\t for (var i = 0; i < paths.length; i++) {\n\t var path = paths[i];\n\t if (path.key >= fromIndex) {\n\t path.key += incrementBy;\n\t }\n\t }\n\t}", "function renameKeyObject(obj) {\n obj['fullName'] = obj.name;\n delete obj.name;\n return console.log(obj.fullName);\n}", "function newPath( id , username ) {\n var values = {\n \"username\": \"Anonymous\",\n \"timestamp\": \"Error\"\n }\n var username = username;\n var id = id;\n var currentDate = new Date();\n var timestamp = currentDate.getTime();\n values.username = username;\n values.timestamp = timestamp;\n var pathRef = firebase.database().ref('paths/' + id);\n var newChildRef = pathRef.push(values);\n}", "function removePathFromField(path) {\n return \"\" + splitAccessPath(path).join('.');\n }", "onEntityUpdatedName(id, type, name, mappedNameField) {\n const index = this.getEntityIndex(id, type);\n this.setState(prevState => ({\n [EntityTypes[type]]: update(prevState[EntityTypes[type]], {[index]: {[mappedNameField]: {$set: name}}})\n }));\n }", "updateForPaths(paths) {\n if (!paths) return;\n\n let selected = null;\n let remaining = [];\n for (const projectElement of this.projects) {\n if (projectElement.isChecked()) {\n selected = projectElement.path;\n }\n projectElement.markUnchecked();\n if (projectElement.path in paths) {\n remaining.push(projectElement);\n } else {\n projectElement.destroy();\n }\n }\n\n this.projects = [];\n let i = 0;\n for (const path of paths) {\n if (i < remaining.length && remaining[i].path == path) {\n this.projects.push(remaining[i]);\n i++;\n } else {\n const projectElement = new ProjectItem(path, this._selectionHandler.bind(this));\n this.projects.push(projectElement);\n if (i < remaining.length) {\n this.element.insertBefore(projectElement.element, remaining[i]);\n } else {\n this.element.appendChild(projectElement.element);\n }\n }\n }\n\n for (projectElement of this.projects) {\n if (!selected || projectElement.path == selected) {\n projectElement.markChecked();\n return;\n }\n }\n // If we have removed selected project, just mark the first one as selected.\n if (this.projects.length > 0) {\n this.projects[0].markChecked();\n }\n }", "function mapUpdate (evt) {\n let type = evt.type || 'updated';\n\n // For non-browserify events, the changed paths are in evt.path\n // For browserify events, evt is the changed paths\n // evt.path & path can either be a single path or an array of paths.\n let paths = _.flatten([ (evt.path || evt) ]);\n\n _.each(paths, (path) => {\n let shortenedPath = path.split('src').reduce((prev, current) => current);\n gutil.log(\n 'File ' +\n chalk.green(shortenedPath) +\n ' was ' +\n chalk.blue(type) +\n '. Rebuilding...'\n );\n });\n}", "handleRenameHistory(newName, oldName) {\n this.setState((prevState, props) => {\n prevState.currentHistoryName = newName;\n prevState.history[newName] = prevState.history[oldName];\n prevState.history[newName].name = newName;\n delete prevState.history[oldName];\n\n this.saveInHistory(prevState);\n\n return prevState;\n });\n }", "_onFileChanged(sender, change) {\n let path = this._model.path;\n let { sessions } = this.manager.services;\n let { oldValue, newValue } = change;\n let value = oldValue && oldValue.path && coreutils_1.PathExt.dirname(oldValue.path) === path\n ? oldValue\n : newValue && newValue.path && coreutils_1.PathExt.dirname(newValue.path) === path\n ? newValue\n : undefined;\n // If either the old value or the new value is in the current path, update.\n if (value) {\n this._scheduleUpdate();\n this._populateSessions(sessions.running());\n this._fileChanged.emit(change);\n return;\n }\n }", "function modifySVGPath(inputPath, filename) {\n var fullPath = inputPath;\n var dirname = RETURNED_SVG_PATH;\n var output = fs.createWriteStream(dirname + filename + '.svg');\n var lineReader = readline.createInterface({\n input: fs.createReadStream(fullPath)\n });\n\n var pathnumber = 0;\n\n lineReader.on('line', function(line){\n var toWrite = \"\";\n\n if(!line.startsWith(\"<path\")){\n toWrite += line;\n toWrite += \"\\n\";\n output.write(toWrite)\n }\n else if(line.startsWith(\"<path\")){\n\n var lineToEdit = line.split(' ');\n lineToEdit.splice(1, 0, 'id=\"' + pathnumber + '\"');\n var editedLine = lineToEdit.join(' ');\n pathnumber++;\n\n toWrite += editedLine;\n toWrite += \"\\n\";\n output.write(toWrite)\n }\n\n })\n\n console.log(\"Completed file modification. Review output at \" + RETURNED_SVG_PATH + filename + '.svg');\n}", "function update_filename_path_on_json(JSONstring, project,source, filename, path){\n\tvar new_json = { }\n\tvar jsonobj = JSON.parse(JSONstring);\n\tvar keys = Object.keys(jsonobj);\n\tif (project == undefined) project=\"\";\n\tif (source == undefined) source=\"\";\n\tif (path == undefined) path=\"\";\n\tif (filename == undefined) filename=\"\";\n\tnew_json['project']=project;\n\tnew_json['project'+'_length']=project.length;\n\tnew_json['source']=source;\n\tnew_json['source'+'_length']=source.length;\n\tnew_json['path']=path;\n\tnew_json['path'+'_length']=path.length; //label can not contain points '.' !\n\tnew_json['filename']=filename;\n\tnew_json['filename'+'_length']=filename.length;\n\tfor (var i = 0; i < keys.length; i++) {\n\t\tvar label=Object.getOwnPropertyNames(jsonobj)[i];\n\t\tlabel=lowercase(label);\n\t\tif((label != 'path') && (label != 'filename') && (label != 'path_length') && (label != 'filename_length'))\n\t\t\tnew_json[label]=jsonobj[keys[i]]; //add one property\n\t\tif( typeof jsonobj[keys[i]] == 'string'){\n\t\t\tnew_json[label+'_length']=jsonobj[keys[i]].length;\n\t\t}\n\t}\n\tnew_json=(JSON.stringify(new_json));\n\treturn new_json;\n}", "function setPropFromPath(obj, path, value) {\n var keys = path.split('.');\n var targetKey = keys.pop();\n var objRef = obj;\n\n for (var i in keys) {\n if (typeof objRef === 'object') {\n if (typeof objRef[keys[i]] === 'undefined' || objRef[keys[i]] === null) { objRef[keys[i]] = {}; }\n\n objRef = objRef[keys[i]];\n }\n }\n\n if (typeof objRef === 'object') { objRef[targetKey] = value; }\n }", "function setPropFromPath(obj, path, value) {\n var keys = path.split('.');\n var targetKey = keys.pop();\n var objRef = obj;\n\n for (var i in keys) {\n if (typeof objRef === 'object') {\n if (typeof objRef[keys[i]] === 'undefined' || objRef[keys[i]] === null) { objRef[keys[i]] = {}; }\n\n objRef = objRef[keys[i]];\n }\n }\n\n if (typeof objRef === 'object') { objRef[targetKey] = value; }\n }", "changeName(newName) {\n this.cgram.changeAnchorName(this.name, newName);\n }", "rename( src, callback ) {\n\n // Extract the path parts.\n let basename = path.basename(src);\n let dirname = path.dirname(src);\n\n // Rename the file.\n basename = _.isFunction(callback) ? callback(basename) : (callback || basename);\n\n // Determine the new path.\n const renamed = path.resolve(dirname, basename);\n\n // Rename the file.\n context.fs.move(src, renamed);\n\n }", "static _dereferencePath(path) {\n if (!ApplicationState._symlinks)\n return path;\n\n const nodes = ApplicationState.walk(path);\n\n for (let index = 0; index < nodes.length; index++) {\n const node = nodes[index];\n if (ApplicationState._symlinks[node.path]) {\n path = path.replace(node.path, ApplicationState._symlinks[node.path]);\n return ApplicationState._dereferencePath(path);\n }\n }\n\n return path;\n }", "function editPath (place, choice) {\n place = place;\n choice = choice;\n userPath[place] = choice;\n}", "function normalize(namePath) {\n return namePath\n .map(function (cell) {\n return ''.concat(_typeof(cell), ':').concat(cell);\n }) // Magic split\n .join(SPLIT);\n}", "function update() {\n console.log('Map moved, Redrawing markers');\n\n // Using the GUP\n g.selectAll('path').exit().transition().duration(100).remove();\n\n g.selectAll('path').transition().duration(250).attr('d', path);\n }", "get pathChanged() {\n return this._pathChanged;\n }", "get pathChanged() {\n return this._pathChanged;\n }", "setPath(path) {\nthis._path = path;\n}", "function updateFileInfo(fileName) {\n var adjustedFileName = fileName;\n\n if (fileName.length > 50) {\n adjustedFileName = fileName.substr(0, 15) + '...' + fileName.substr(fileName.length - 15);\n }\n\n fileInfo.find('.file-name').html(adjustedFileName);\n fileInfo.attr('title', fileName);\n\n fileInputField.attr('title', fileName);\n\n fileInfo.find('.clear').show();\n }", "function removePathFromField(path) {\n return \"\".concat(splitAccessPath(path).join('.'));\n }", "setPath(path) {\n this._history.set(path);\n }", "updateNameValue(name) {\n\t\tthis.setState({\n\t\t\tnewName: name\n\t\t});\n\t}", "onUpdateFolder() {\n this.onUpdateFolder();\n }", "function removePath(path) {\n db.run(\"DELETE FROM paths WHERE path LIKE (?)\", path+'%', function (err) {\n if (err) {\n console.log(err);\n return;\n }\n console.log(\"DELETE: \"+this.changes);\n });\n}", "updatePatchNameToInput(e) {\n this.menuView.patchNameScene.textContent = Utilitary.currentScene.sceneName;\n this.menuView.exportView.dynamicName.textContent = Utilitary.currentScene.sceneName;\n this.menuView.exportView.inputNameApp.value = Utilitary.currentScene.sceneName;\n this.menuView.saveView.dynamicName.textContent = Utilitary.currentScene.sceneName;\n this.menuView.saveView.inputDownload.value = Utilitary.currentScene.sceneName;\n this.menuView.saveView.inputLocalStorage.value = Utilitary.currentScene.sceneName;\n this.menuView.saveView.inputCloudStorage.value = Utilitary.currentScene.sceneName;\n new Message(Utilitary.messageRessource.successRenameScene, \"messageTransitionOutFast\", 2000, 500);\n }", "textDocumentRename(params, span = new opentracing_1.Span()) {\n const uri = util_1.normalizeUri(params.textDocument.uri);\n const editUris = new Set();\n return this.projectManager.ensureOwnFiles(span)\n .concat(rxjs_1.Observable.defer(() => {\n const filePath = util_1.uri2path(uri);\n const configuration = this.projectManager.getParentConfiguration(params.textDocument.uri);\n if (!configuration) {\n throw new Error(`tsconfig.json not found for ${filePath}`);\n }\n configuration.ensureAllFiles(span);\n const sourceFile = this._getSourceFile(configuration, filePath, span);\n if (!sourceFile) {\n throw new Error(`Expected source file ${filePath} to exist in configuration`);\n }\n const position = ts.getPositionOfLineAndCharacter(sourceFile, params.position.line, params.position.character);\n const renameInfo = configuration.getService().getRenameInfo(filePath, position);\n if (!renameInfo.canRename) {\n throw new Error('This symbol cannot be renamed');\n }\n return rxjs_1.Observable.from(configuration.getService().findRenameLocations(filePath, position, false, true))\n .map((location) => {\n const sourceFile = this._getSourceFile(configuration, location.fileName, span);\n if (!sourceFile) {\n throw new Error(`expected source file ${location.fileName} to exist in configuration`);\n }\n const editUri = util_1.path2uri(location.fileName);\n const start = ts.getLineAndCharacterOfPosition(sourceFile, location.textSpan.start);\n const end = ts.getLineAndCharacterOfPosition(sourceFile, location.textSpan.start + location.textSpan.length);\n const edit = { range: { start, end }, newText: params.newName };\n return [editUri, edit];\n });\n }))\n .map(([uri, edit]) => {\n // if file has no edit yet, initialize array\n if (!editUris.has(uri)) {\n editUris.add(uri);\n return { op: 'add', path: util_1.JSONPTR `/changes/${uri}`, value: [edit] };\n }\n // else append to array\n return { op: 'add', path: util_1.JSONPTR `/changes/${uri}/-`, value: edit };\n })\n .startWith({ op: 'add', path: '', value: { changes: {} } });\n }", "syncKeysForPath(path, json) {\n // search from leaf to root, to find the first path with entry in keys map\n for (let i = path.length - 1; i >= 0; i--) {\n const currentPath = path.slice(0, i);\n const currentPathString = this.pathUtilService.toPathString(currentPath);\n if (this.keysMap[currentPathString]) {\n // path[i] is key that should be added to currentPat\n const key = path[i];\n // if currentPath has the key\n if (this.keysMap[currentPathString].has(key)) {\n // just build the store keys map for that /current/path/key if it is object or array\n const keyPath = currentPath.concat(key);\n const keySchema = this.jsonSchemaService.forPathArray(keyPath);\n if (keySchema.type === 'object' || keySchema.type === 'array') {\n this.buildKeysMapRecursivelyForPath(json.getIn(keyPath), keyPath, keySchema);\n }\n // if currentPath doesn't have the key\n }\n else {\n const currentSchema = this.jsonSchemaService.forPathArray(currentPath);\n // if currentPath is to a table list\n if (currentSchema.componentType === 'table-list') {\n // have to rebuild keys map for it because key is here an index we don't know what to add\n this.buildKeysMapRecursivelyForPath(json.getIn(currentPath), currentPath, currentSchema);\n // if not to a table list.\n }\n else {\n // just add the key which will build keys map for /current/path/key as well if needed\n this.addKey(currentPathString, key, currentSchema, json.getIn(currentPath.concat(path[i])));\n }\n }\n // break when a entry found for a path in keys map\n break;\n }\n }\n }", "function updateModifiedTab(){\n treeFileElements = $(\".jstree-anchor\");\n list.getList().forEach(function(tab){\n if(tab.modified){\n document.getElementById(tab.getPath()).classList.add(\"modified\");\n for(var i = 0; i < treeFileElements.length;i++){\n if(treeFileElements[i].parentElement.attributes['data-path'].value === tab.getPath()){\n treeFileElements[i].parentElement.classList.add(\"modified\");\n break;\n }\n }\n }\n else{\n try{document.getElementById(tab.getPath()).classList.remove(\"modified\");}catch(e){}\n for(var i = 0; i < treeFileElements.length;i++){\n if(treeFileElements[i].parentElement.attributes['data-path'].value === tab.getPath()){\n try{treeFileElements[i].parentElement.classList.remove(\"modified\");}catch(e){}\n break;\n }\n }\n }\n });\n}", "move(sourceFile, newPath){\n const existing = this._storage.getItem(this._key(sourceFile));\n\n if (existing){\n const cmd = JSON.parse(existing);\n if (cmd.type === SourceChange.MOVE){\n cmd.newPath = newPath;\n } else if (existing.type === SourceChange.CREATE) {\n cmd.path = newPath;\n } else if (existing.type === SourceChange.UPDATE){\n cmd.newPath = newPath;\n } else {\n throw cmd.type;\n }\n cmd.timestamp = Date.now();\n this._put(sourceFile, cmd);\n } else {\n const cmd = {timestamp: Date.now(), file: sourceFile.simple, type:SourceChange.MOVE, newPath: newPath};\n this._put(sourceFile, cmd);\n }\n }", "function updateRelativePerson(relativePersonReferenceKey) {\n // appLogger.log($scope.relativePerson)\n delete $scope.relativePerson.personReferenceKey;\n $scope.relativePerson.lastName = \"-- \";\n personRelativeLogic.updateRelativePerson($scope.relativePerson, relativePersonReferenceKey).then(function(response) {\n // appLogger.log(response);\n }, function(err) {\n appLogger.error('ERR' + err);\n });\n }" ]
[ "0.6614235", "0.64706343", "0.63814765", "0.61266446", "0.5995392", "0.588006", "0.5840417", "0.5823939", "0.5814879", "0.5780115", "0.5730894", "0.5703801", "0.57026887", "0.5669977", "0.56522644", "0.5647009", "0.5613914", "0.55653274", "0.5561866", "0.5547402", "0.5545699", "0.5511698", "0.54778486", "0.54724544", "0.5402974", "0.5356344", "0.5352532", "0.53337604", "0.53219134", "0.52565145", "0.52463263", "0.52463263", "0.52228165", "0.5220841", "0.520695", "0.520512", "0.52016836", "0.5196742", "0.5184315", "0.51793474", "0.51673925", "0.51637816", "0.5157363", "0.5154973", "0.5145217", "0.5145217", "0.5144784", "0.51294327", "0.5116044", "0.5109482", "0.5100941", "0.5097305", "0.50954354", "0.5093973", "0.5093973", "0.50763863", "0.5063334", "0.5056266", "0.5051662", "0.50411046", "0.50398284", "0.5035886", "0.5025039", "0.5022921", "0.50180036", "0.50110346", "0.50110346", "0.50055754", "0.50054455", "0.49981996", "0.49889266", "0.49886975", "0.4985028", "0.49774566", "0.4971852", "0.49698004", "0.4965738", "0.49619606", "0.49619606", "0.49563643", "0.49516425", "0.4948335", "0.49447405", "0.49350774", "0.4932501", "0.4927994", "0.4927994", "0.4926332", "0.49250442", "0.49247134", "0.4915405", "0.49132597", "0.49035367", "0.4902624", "0.48868367", "0.48823735", "0.48622125", "0.48537177", "0.48487207", "0.4840748" ]
0.6999919
0
Delete single file from meta data DB.
static deleteEntry(path) { Databases.fileMetaDataDb.remove({path: path}, (err, numDeleted) => { if (err) { console.log(err); } }); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "delete(fileID) {\n return this.ready.then(db => {\n const transaction = db.transaction([STORE_NAME], 'readwrite');\n const request = transaction.objectStore(STORE_NAME).delete(this.key(fileID));\n return waitForRequest(request);\n });\n }", "function deleteFromMetaFile(index) {\n files_meta = deleteElementFromJSON(files_meta, '_'+index);\n}", "delete(directory, fileName, callback) {\n const theFilePath = getDataStoragePath(directory, fileName);\n fs.unlink(theFilePath, err => {\n if (err) return callback(new Error(`Failed to delete file!`), 500);\n callback(null);\n });\n }", "function deleteFile({ _id: _id, filename: filename }) {\n const getToken = localStorage.getItem('token');\n const getUserid = localStorage.getItem('userId');\n\n axios.delete(\"/api/delete\", {\n headers: {\n 'accept': 'application/json',\n 'Authorization': `Bearer ${getToken}`\n },\n params: {\n filename: filename,\n id: _id,\n userID: getUserid\n }\n })\n .then(function (response) {\n\n getStorageData();\n resetFields();\n history.push(\"/gameover\");\n })\n .catch(function (error) {\n console.log(error);\n });\n }", "deleteRecord() {\n this._super(...arguments);\n const gist = this.gist;\n if(gist) {\n gist.registerDeletedFile(this.id);\n\n // Following try/catch should not be necessary. Bug in ember data?\n try {\n gist.get('files').removeObject(this);\n } catch(e) {\n /* squash */\n }\n }\n }", "deleteFile(name) {\n let auth = this.auth;\n const drive = google.drive({ version: 'v3', auth });\n this.db.collection(\"filesCollection\").findOne({\"name\": name}).then(file => {\n console.log(`Deleting file ${name} with id ${file.fileId} and keyId ${file.keyId}`);\n drive.files.delete({\n 'fileId': file.fileId\n }).then(fileDeleteRes => {\n drive.files.delete({\n 'fileId': file.keyId\n }).then(keyDeleteRes => {\n this.db.collection(\"filesCollection\").deleteOne({\"name\": name}).then(res => console.log(\"File in the database deleted\"));\n });\n });\n });\n }", "deleteFile(path,callback) { this.engine.deleteFile(path,callback); }", "async function deleteFile(fileID) {\n var path = await getActualPath(fileID);\n // remove from disk\n fs.unlink(path, function (error) {\n if (error) {\n console.error(error.stack);\n return;\n }\n });\n // remove from db\n db.deleteData('file', { id: fileID });\n\n console.log(`${fileID} deleted`);\n}", "function deleteFile(url){\n\t\t\treturn getFileEntry(url).then(doDeletion);\n\t\t}", "function deleteSingleItem() {\n var msg;\n if (files[currentFileIndex].metadata.video) {\n msg = navigator.mozL10n.get('delete-video?');\n }\n else {\n msg = navigator.mozL10n.get('delete-photo?');\n }\n if (confirm(msg)) {\n deleteFile(currentFileIndex);\n }\n}", "function del(filepath, key) {\n\n return new Promise((resolve, reject) => {\n\n filepath = filepath.replace(/\\.json$/, '');\n\n fs.exists(dataPath + filepath + '.json', exists => {\n\n if (exists) {\n\n if (key) {\n\n get(filepath, true).then(data => {\n\n if (key.indexOf('.') !== -1 || key.indexOf('[') !== -1) {\n\n vm.createContext(data);\n\n vm.runInNewContext('delete ' + key, data);\n\n } else {\n delete data[key];\n }\n\n save(filepath, data).then(data => {\n resolve(data);\n });\n });\n } else {\n\n fs.unlink(dataPath + filepath + '.json', err => {\n if (err) {\n handle(err, reject);\n } else {\n resolve();\n }\n });\n }\n } else {\n resolve();\n }\n });\n });\n}", "deleteFile(url){\n const file = url.split(env.files.uploadsUrl)[1]\n if(file != 'system/default.png'){\n fs.unlinkSync(env.files.uploadsPath+file)\n }\n }", "async rm(filepath) {\n try {\n await this._unlink(filepath);\n } catch (err) {\n if (err.code !== 'ENOENT') throw err\n }\n }", "function deleteItem(item) {\n console.log(item);\n Firebase.database().ref(`/items/${item}`).remove();\n\n var desertRef = storage.ref(`images/${item.image}`);\n\n // Delete the file\n desertRef\n .delete()\n .then(function () {\n // File deleted successfully\n })\n .catch(function (error) {\n // Uh-oh, an error occurred!\n });\n }", "function deleteFile(req, res, next) {\n var generateResponse = Api_Response(req, res, next);\n var riskId = req.params.risk_id;\n var fileId = req.params.file_id;\n\n Risk.update(\n {\n _id: riskId\n },\n {\n $pull: {\n _files : {\n _id: fileId\n }\n }\n },\n function (error) {\n if (error) {\n return generateResponse(error);\n }\n\n Risk\n .findById(riskId)\n .exec(function (error, risk) {\n if (error) {\n return;\n }\n\n var activity = new Activity({\n action: 'activityFeed.deleteFileFromRisk',\n project: risk.project,\n user: req.user._id,\n risk: risk._id,\n riskName: risk.name\n });\n activity.save(function (error) {});\n\n // Send socket.io message.\n socket.deleteFileFromRisk(risk, fileId, req.user._id);\n });\n\n generateResponse(null);\n }\n );\n}", "async function deleteFile(userIdIn, fileIdIn) {\n var db = await MongoClient.connect(process.env.PROD_MONGODB);\n await db.collection('files').deleteOne(\n {_id: new ObjectID(fileIdIn)}\n );\n await db.close();\n}", "function OnDelete(meta) {\n log('deleting document', meta.id);\n delete dst_bucket[meta.id]; // DELETE operation\n}", "async rm (filepath) {\n try {\n await this._unlink(filepath);\n } catch (err) {\n if (err.code !== 'ENOENT') throw err\n }\n }", "function removeAudioFile() {\n var audioFile = Ti.Filesystem.getFile(res.data.filePath);\n audioFile.deleteFile();\n }", "async removeMetadata(id) {\n let filename = this._formatMetadataFilename(id);\n\n await fs.unlink(filename);\n }", "async function deleteFile(file) {\n const fileId = file._id\n\n // if AnnDataExperience clusterings need to be handled differently\n if (isAnnDataExperience && file.data_type === 'cluster') {\n annDataClusteringFragmentsDeletionHelper(file)\n } else if (isAnnDataExperience && file.status === 'new' && file.file_type === 'Cluster') {\n updateFile(fileId, { isDeleting: true })\n\n // allow a user to delete an added clustering that hasn't been saved\n deleteFileFromForm(fileId)\n } else {\n if (file.status === 'new' || file?.serverFile?.parse_status === 'failed') {\n deleteFileFromForm(fileId)\n } else {\n updateFile(fileId, { isDeleting: true })\n try {\n await deleteFileFromServer(fileId)\n deleteFileFromForm(fileId)\n Store.addNotification(successNotification(`${file.name} deleted successfully`))\n } catch (error) {\n Store.addNotification(failureNotification(<span>{file.name} failed to delete<br />{error.message}</span>))\n updateFile(fileId, {\n isDeleting: false\n })\n }\n }\n }\n }", "function deleteAlgolia(idx){\n\tidx.map(function(_file){\n\t\talgolia.deleteObject(new Buffer(_file).toString('base64'), function(err) {\n\t\t\tif (!err) {\n\t\t\t\tconsole.log(_file + ' deleted');\n\t\t\t}\n\t\t});\n\t});\n}", "async function deleteEntry() {\n\n\t\t// 1) Delete the entry from the database by title\n\t\tawait Snapshot.destroy({\n\t\t\twhere: {\n\t\t\t\tTitle: req.params.title\n\t\t\t}\n\t\t});\n\n\t\tres.sendStatus(200).end()\n\t}", "function deleteFile (path, cb) {\n debug('delete `mongod` file')\n\n fs.unlink(path + 'mongod', unlinkCb)\n\n function unlinkCb (err) {\n if (err) {\n cb(new VError(err, 'deleting file %s', path + 'mongod'))\n } else {\n cb()\n }\n }\n}", "function deleteWithID(res, req){\n factoryStore.remove(req.params.id, function(err, factory){\n if (err){\n res.writeHeader(500, {'Content-Type':'text/html'});\n res.write(\"Error deleting file. Ensure that file with that ID exists.\");\n console.log(err);\n }\n res.writeHeader(200, {'Content-Type':'text/html'});\n res.write(\"Deleted\");\n res.end();\n });\n}", "async _remove () {\n try {\n await deleteFile(this.dataPath);\n }\n catch (e) { // eslint-disable-line no-empty\n }\n }", "async function deleteFile(user, fileName) {\n // File to delete\n const fileRef = storageRef.child(user + '/' + fileName);\n\n // Delete the file\n fileRef.delete().then(() => {\n location.reload();\n }).catch((error) => {\n // Uh-oh, an error occurred!\n console.log(error);\n });\n}", "async delete(path) {\n await this.contentsManager.delete(path);\n }", "function deleteMedia(id) {\n Media.delete(id)\n .then(function onSuccess(response) {\n console.log(response);\n })\n .catch(function onError(response) {\n console.log(response);\n });\n }", "function onDelete() {\n setFileURL(false)\n console.log(\"delete file\");\n }", "function deleteFile(fileKey) {\n var params = {\n Bucket: bucketName,\n Key: fileKey,\n };\n\n s3.deleteObject(params, function (err, data) {\n if (err) console.log(err, err.stack);\n console.log('deleted!');\n });\n}", "function deleteOne(req,res){\n Photo.where({id:req.params.id}).fetch({\n }).then(function (record) {\n \n //delete the record\n if(record && record.user_id===req.params.user_id){\n record.destroy()\n .on('destroyed',function(){\n res.status(204).end();\n });\n //unauthorized\n } else if(record) {\n res.status(403).end();\n \n //record not found\n } else {\n res.status(404).end();\n }\n });\n}", "async destroyImage(file) {\n // const date = new Date();\n // const timestamp = date.getTime();\n // const hash = crypto.createHash('sha1');\n // const sign = hash.update(`public_id=${file}&timestamp=${timestamp}${CLOUDINARY_API_SECRET}`).digest('hex');\n //\n // const fd = new FormData();\n // fd.append('public_id', file);\n // fd.append('api_key', CLOUDINARY_API_KEY);\n // fd.append('timestamp', timestamp);\n // fd.append('signature', sign);\n //\n // try {\n // await axios.post(\n // CLOUDINARY_DELETE_URL,\n // fd\n // );\n // } catch (error) {\n // this.handleUpdateError(error);\n // }\n }", "function deletePhoto(event) {\n let reqDB = indexedDB.open('photos', 1);\n reqDB.onsuccess = function (e) {\n let db = e.target.result;\n\n // получаем ключ записи\n const id = event.target.getAttribute('id')\n // открываем транзакцию чтения/записи БД, готовую к удалению данных\n const tx = db.transaction(['cachedForms'], 'readwrite');\n // описываем обработчики на завершение транзакции\n tx.oncomplete = () => {\n console.log('Transaction completed. Photo deleted')\n getAndDisplayImg();\n };\n tx.onerror = function (event) {\n alert('error in cursor request ' + event.target.errorCode);\n };\n\n // создаем хранилище объектов по транзакции\n const store = tx.objectStore('cachedForms');\n // выполняем запрос на удаление указанной записи из хранилища объектов\n let req = store.delete(+id);\n\n req.onsuccess = () => {\n\n //удалить это фото из всех localStorage tag\n if (localStorage.getItem('tags') !== null) {\n let tags = JSON.parse(localStorage.getItem('tags'))\n tags = tags.map(tagObj => {\n return {...tagObj, images: tagObj.images.filter(imgId => imgId !== +id)}\n })\n tags = JSON.stringify(tags)\n localStorage.setItem('tags', tags)\n }\n\n // обрабатываем успех нашего запроса на удаление\n console.log('Delete request successful');\n };\n document.querySelector('.container2').remove()\n };\n }", "function removeImage(id){\n return db('images')\n .where({ id })\n .del();\n}", "function deleteThisFile () {\n // only hide the file\n $thisFile.hide();\n // trigger a file deletion operations\n self.emit('_deleteFile', $thisFile.find(ps).text(), function(err) {\n // show back the file on error or remove on success\n if (err) {\n $thisFile.fadeIn();\n } else {\n $thisFile.remove();\n }\n });\n }", "function deleteImage(image) {\n fs.unlink(image, (err) => {\n if (err) {\n console.log(err);\n } else {\n console.log(\"Imagem apagada\");\n }\n });\n}", "function del_Face(){\n\t\t\t\t// The name of the bucket to access, e.g. \"my-bucket\"\n\t\t\t\tvar bucketName = 'smartmirrortest'\n\n\t\t\t\t// The name of the file to delete, e.g. \"file.txt\"\n\t\t\t\t const filename = formatted+'face.jpg';\n\n\t\t\t\t// Instantiates a client\n\t\t\t\n\n\t\t\t\t// Deletes the file from the bucket\n\t\t\t\tgcs\n\t\t\t\t .bucket(bucketName)\n\t\t\t\t .file(filename)\n\t\t\t\t .delete()\n\t\t\t\t .then(() => {\n\t\t\t\t\tconsole.log(`gs://${bucketName}/${filename} deleted.`);\n\t\t\t\t })\n\t\t\t\t .catch((err) => {\n\t\t\t\t\tconsole.error('ERROR:', err);\n\t\t\t\t });\n\t\t\t}", "deleteFile(index) {\n //this.matrixData[this.position[0]][this.position[1]].musicfiles.splice(index, 1);\n }", "async deleteProduct(req, res, next) {\n console.log(\"inside delete function\");\n let document;\n try {\n document = await ProductDB.findOneAndDelete({ _id: req.params.id });\n // console.log(document.image);\n fs.unlink(document.image, (error) => {\n if (error) {\n return next(error);\n }\n });\n } catch (error) {\n return next(error);\n }\n res.json({ document });\n }", "function deleteJSON(id)\n{\n filesDB.transaction(function (tx) \n {\n tx.executeSql(\"DELETE FROM files where id = ?\", [id]);\n });\n \n}", "function deleteJSON(id)\n{\n filesDB.transaction(function (tx) \n {\n tx.executeSql(\"DELETE FROM files where id = ?\", [id]);\n });\n \n}", "deleteFile(path) {\r\n // Get the path\r\n path = this.getAbsoluteDataPath(path);\r\n // Make sure the path exists\r\n if (!FS_1.FS.existsSync(path))\r\n return false;\r\n // Remove the file\r\n FS_1.FS.unlinkSync(path);\r\n return true;\r\n }", "function delete_file (file_name, reload_flag, media_id)\n{\n var params = {};\n params ['file'] = file_name;\n if (media_id !== undefined)\n params ['media_id'] = media_id; \n $.ajax ({url: '/admin/index/remove',type: 'POST', data: params,\n complete : function (response, status) {if (reload_flag === true) {$.fancybox.close ();reload_list ();}} \n }); \n}", "_removeFile(req, file, cb) { }", "async function remove(db, nam, o) {\n var o = _.merge({}, OPTIONS, o), db = db||o.db;\n db = typeof db==='string'? await setup(db, o):db;\n var nam = nam||o.input||(await getUpload(db, o)).title;\n if(o.log) console.log('-remove:', nam);\n await db.run('DELETE FROM \"pages\" WHERE \"title\" = ?', nam);\n return nam;\n}", "function deleteFile(auth, param) {\n var fileId = param;\n if (typeof fileId === 'undefined') {\n console.error(\"Please type the id of the file as an argument\");\n return;\n }\n const drive = google.drive({ version: 'v3', auth });\n console.log(`Deleting file ${fileId}`);\n drive.files.delete({\n 'fileId': fileId\n });\n}", "function deleteFile(id) {\n chrome.runtime.sendMessage({\n type: \"remove\",\n id: id\n });\n}", "async function remove ({\n dir,\n gitdir = path__WEBPACK_IMPORTED_MODULE_0___default.a.join(dir, '.git'),\n fs: _fs,\n filepath\n}) {\n const fs = new FileSystem(_fs);\n await GitIndexManager.acquire(\n { fs, filepath: `${gitdir}/index` },\n async function (index) {\n index.delete({ filepath });\n }\n );\n // TODO: return oid?\n}", "async function gcsDelete(bucket, file) {\n // console.log('Deleting file: '+file);\n storage.bucket(bucket).file(file).delete()\n .catch(function (error) {\n console.error(\"!!!!!!!!!!!! Failed to delete a file: \" + error);\n });\n}", "function deletePhotoPost(req,res)\r\n{\r\n\tvar pathFoto= req.body.link;\r\n\tvar file_path= pathFoto;\r\n\tvar file_split= file_path.split('/');\r\n\tvar file_name=file_split[4];\r\n\r\n\tPhoto.findOne({name: file_name}, (err, fotoFind)=>{\r\n\t\tif(err)\r\n\t\t{\r\n\t\t\tres.status(500).send({message:'Error al intentar buscar la foto deseada para eliminarla.'});\r\n\t\t}\r\n\t\telse{\r\n\t\t\tif(!fotoFind)\r\n\t\t\t{\r\n\t\t\t\tres.status(500).send({message:'No existe el nombre de la foto a eliminar. No se puede borrar ninguna foto.'});\r\n\t\t\t}\r\n\t\t\telse{\r\n\r\n\t\t\t\t//Eliminamos la foto en la base de datos.\r\n\t\t\t\tPhoto.findByIdAndRemove(fotoFind._id, (err, fotoRemoved) =>{\r\n\t\t\t\t\tif(err){\r\n\t\t\t\t\t\tres.status(500).send({message:'Error al intentar eliminar la foto'});\r\n\t\t\t\t\t}else{\r\n\t\t\t\t\t\tif(!fotoRemoved)\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\tres.status(500).send({message:'No existe el ID de la foto a eliminar. No se ha borrado ninguna foto.'});\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\telse{\r\n\t\t\t\t\t\t\t\t\r\n\r\n\t\t\t\t //Eliminamos fisicamente la foto en el servidor.\r\n\t\t\t\t var path_file = './public/post/'+file_name;\r\n\t\t\t\t var ruta=path.resolve(path_file);\r\n\t\t\t\t //console.log(ruta);\r\n\r\n\t\t\t\t fs.exists(path_file,function(exists){\r\n\t\t\t\t\t\t\t\tif(exists){\r\n\t\t\t\t\t\t\t\t\t//Objeto path para acceder a rutas de nuestro sistema de archivos. Me devolverá el archivo\r\n\t\t\t\t\t\t\t\t\t//Se elimina la foto fisica\r\n\t\t\t\t\t\t\t\t\tfs.unlink(ruta, (err)=>{\r\n\t\t\t\t\t\t\t\t\t\tif(err){\r\n\r\n\t\t\t\t\t\t\t\t\t\t\tres.status(500).send({message: 'Ha ocurrido un problema al borrar la foto.'});\t\t\r\n\t\t\t\t\t\t\t\t\t\t}else{\r\n\t\t\t\t\t\t\t\t\t\t\tres.status(200).send({foto: fotoRemoved});\t\t\r\n\t\t\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\t\t});\r\n\r\n\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\telse{\r\n\t\t\t\t\t\t\t\t\tres.status(404).send({\r\n\t\t\t\t\t\t\t\t\t\tmessage: 'La imagen no existe'\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}\r\n\t\t\t\t\t}\r\n\t\t\t\t});\r\n\t\t\t}\r\n\t\t}\r\n\t});\t\r\n\r\n}", "function deleteFile(file_id, cb) {\n\t\t$.ajax({\n\t\t\turl: '/api/v1/files/' + file_id + '/delete',\n\t\t\tmethod: 'delete',\n\t\t\tcache: false,\n\t\t\tsuccess: function(data) {\n\t\t\t\tif(data.status !== 'success') {\n\t\t\t\t\t$('#delete_file_modal .error-msg').text(data.message);\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tif(typeof cb === 'function') cb(data);\n\t\t\t\t}\n\t\t\t},\n\t\t\terror: function(err) {\n\t\t\t\tif(typeof ShopifyApp !== 'undefined') ShopifyApp.flashError(err.message);\n\t\t\t}\n\t\t});\n\t}", "function deletePhotoEvent(req,res)\r\n{\r\n\tvar pathFoto= req.body.link;\r\n\tvar file_path= pathFoto;\r\n\tvar file_split= file_path.split('/');\r\n\tvar file_name=file_split[4];\r\n\r\n\tPhoto.findOne({name: file_name}, (err, fotoFind)=>{\r\n\t\tif(err)\r\n\t\t{\r\n\t\t\tres.status(500).send({message:'Error al intentar buscar la foto deseada para eliminarla.'});\r\n\t\t}\r\n\t\telse{\r\n\t\t\tif(!fotoFind)\r\n\t\t\t{\r\n\t\t\t\tres.status(500).send({message:'No existe el nombre de la foto a eliminar. No se puede borrar ninguna foto.'});\r\n\t\t\t}\r\n\t\t\telse{\r\n\r\n\t\t\t\t//Eliminamos la foto en la base de datos.\r\n\t\t\t\tPhoto.findByIdAndRemove(fotoFind._id, (err, fotoRemoved) =>{\r\n\t\t\t\t\tif(err){\r\n\t\t\t\t\t\tres.status(500).send({message:'Error al intentar eliminar la foto'});\r\n\t\t\t\t\t}else{\r\n\t\t\t\t\t\tif(!fotoRemoved)\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\tres.status(500).send({message:'No existe el ID de la foto a eliminar. No se ha borrado ninguna foto.'});\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\telse{\r\n\t\t\t\t\t\t\t\t\r\n\r\n\t\t\t\t //Eliminamos fisicamente la foto en el servidor.\r\n\t\t\t\t var path_file = './public/event/'+file_name;\r\n\t\t\t\t var ruta=path.resolve(path_file);\r\n\t\t\t\t //console.log(ruta);\r\n\r\n\t\t\t\t fs.exists(path_file,function(exists){\r\n\t\t\t\t\t\t\t\tif(exists){\r\n\t\t\t\t\t\t\t\t\t//Objeto path para acceder a rutas de nuestro sistema de archivos. Me devolverá el archivo\r\n\t\t\t\t\t\t\t\t\t//Se elimina la foto fisica\r\n\t\t\t\t\t\t\t\t\tfs.unlink(ruta, (err)=>{\r\n\t\t\t\t\t\t\t\t\t\tif(err){\r\n\r\n\t\t\t\t\t\t\t\t\t\t\tres.status(500).send({message: 'Ha ocurrido un problema al borrar la foto.'});\t\t\r\n\t\t\t\t\t\t\t\t\t\t}else{\r\n\t\t\t\t\t\t\t\t\t\t\tres.status(200).send({foto: fotoRemoved});\t\t\r\n\t\t\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\t\t});\r\n\r\n\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\telse{\r\n\t\t\t\t\t\t\t\t\tres.status(404).send({\r\n\t\t\t\t\t\t\t\t\t\tmessage: 'La imagen no existe'\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}\r\n\t\t\t\t\t}\r\n\t\t\t\t});\r\n\t\t\t}\r\n\t\t}\r\n\t});\t\r\n\r\n}", "function deleteFileAttachment(req, res) {\n var toDelete;\n if (req.body.isTemp) {\n toDelete = {temp_deleted: true};\n }\n else {\n toDelete = {deleted: true};\n }\n\n attachmentFile.findOneAndUpdate({_id: req.body.attachmentId}, toDelete).exec(function(err, data) {\n if (err) {\n res.json({code: Constant.ERROR_CODE, message: err});\n } else {\n res.json({code: Constant.SUCCESS_CODE, message: Constant.FILE_DELETE, data: data});\n }\n });\n}", "function deleteFile(location) {\n console.log(\"DELETING \", location, \"!\");\n fs.unlink(location, function(err) {\n if (err) return console.log(err);\n console.log(\"file deleted successfully\");\n });\n}", "async handleDelete(fileName) {\n console.log(fileName);\n await axios.delete('/api/delete-email', { data: { fileName } });\n }", "function deleteFromCloud(image) {\n if (image) {\n const id = path.parse(image);\n cloudinary.api.delete_resources([id.name], function (result) {\n console.log(result);\n });\n }\n}", "function deleteCache(file, type) {\n\tdeleteCachedFile(file, type);\n}", "function _delete(_id) {\n var deferred = Q.defer();\n \n db.assets.remove(\n { _id:mongo.helper.toObjectID(_id) },\n function (err) {\n if (err) deferred.reject(err);\n \n deferred.resolve();\n });\n \n return deferred.promise;\n}", "async function deleteFile(fileId) {\n return await $.ajax({\n url: domain + \"/file/\" + encodeURIComponent(fileId),\n method: \"DELETE\",\n });\n }", "function deleteFile(avatar_path) {\n if (avatar_path) {\n let del = path.join(localBase, avatar_path);\n if (fs.existsSync(del)) {\n fs.unlinkSync(del);\n }\n }\n}", "remove(fileKey, cb) {\n const absPath = path.resolve(path.join(this.options.path, fileKey));\n fs.unlink(absPath, err => {\n if (err) {\n return void cb(err);\n }\n\n cb();\n });\n }", "async function remove(req, res, next) {\n const { mobile } = req.user;\n const { id } = req.params;\n Post.destroy({ where: { id, mobile } })\n .then(async () => {\n await emptyS3Directory(mobile, id);\n res.json(httpStatus[\"204_MESSAGE\"]);\n })\n .catch((err) => next(err));\n}", "async clean() {\n try {\n await util_1.default.promisify(fs_1.default.unlink)(this.file);\n }\n catch (e) {\n // noop\n }\n }", "delete(req, res) {\n console.log('Delete Request is=====>');\n console.log(req.query);\n queryVars = req.query;\n Image.destroy({\n where: {\n id: queryVars.id\n }\n })\n .then(function (deletedRecords) {\n //if successfull, delete image from the file system tourcosts\n\n res.status(200).json(deletedRecords);\n })\n .catch(function (error){\n res.status(500).json(error);\n });\n }", "function deleteSystemJSON(id)\n{\n systemDB.transaction(function (tx) \n {\n tx.executeSql(\"DELETE FROM files where id = ?\", [id]);\n });\n \n}", "function destroy (id) {\n // find record\n image.findById(id, function (err, image) {\n if(err) { console.log (err); }\n else if (image.remove) {\n // delete record\n image.remove(function(err) {\n if(err) { console.log (err); }\n });\n }\n });\n}", "deleteRefFromFirestore() {\n const { image } = this.props.route.params;\n firebase.firestore()\n .collection('users')\n .doc(firebase.auth().currentUser.uid)\n .collection(\"images\")\n .where('downloadURL', '==', image.downloadURL)\n .get()\n .then((snapshot) => {\n snapshot.forEach((doc) => {\n doc.ref.delete();\n });\n }).catch((error) => console.log(error));\n }", "function RmFile() {\r\n}", "function deleteFile(file, elem) {\n var order = 'filename=' + file;\n\n // POST request\n $.post(\"delete.php\", order, function(response, status, xhr) {\n if (status == \"success\") {\n console.log(response);\n }\n else if (status == \"error\") {\n alert('File could not be deleted.'); \n }\n });\n\n // Remove file row\n $(elem).closest(\"tr\").remove();\n}", "function funlink(file) {\n var path = file.path;\n debug('removing', file.name);\n if (typeof path === 'string') {\n fs.unlink(path, function (err) {\n if (err) {\n debug('Failed to remove ' + path);\n debug(err);\n }\n });\n }\n}", "deleteOne(storename, key) {\n this.cache.then((db) => {\n db.transaction(storename, \"readwrite\").objectStore(storename).delete(key);\n });\n }", "function deleteOppAttachment(url, itemID) {\n var attachment = web.getFileByServerRelativeUrl(url);\n attachment.deleteObject();\n showOppDetails(itemID);\n}", "delete(fileId, callback){\n throw new Error('delete is not implemented');\n }", "deleteByName(req, res) {\n Photo.findOneAndRemove({name: req.params.name}).then(result => {\n res.json(result);\n })\n .catch(err => {\n res.json(err);\n });\n }", "async deleteFilm({ id: id }) {\n const idFound = Film.findOneAndDelete({ id: id })\n return idFound.remove()\n }", "function deleteFile (imageUrl) {\n if (!imageUrl) return\n // Recherche du nom du fichier de l'image\n const filename = imageUrl.split('/images/')[1]\n // Utilisation de 'file system' pour supprimer le fichier du dossier 'images'\n fs.unlink(`images/${filename}`, () => {})\n}", "removeFile(descriptor)\n {\n // remove descriptor\n for (let i = 0; i < this.descriptors.length; i++)\n {\n if (this.descriptors[i].driver == descriptor.driver\n && this.descriptors[i].id == descriptor.id)\n {\n this.descriptors.splice(i, 1)\n break\n }\n }\n\n // remove file\n this.drivers[descriptor.driver].removeFile(descriptor.id)\n\n this.saveDescriptors()\n }", "function file_cache_delete(pattern) {\n\t\treturn file_cache_open().then(del);\n\n\t\tfunction del(db) {\n\t\t\tlet del_promise = promise();\n\t\t\tif (db === null) return del_promise.resolve();\n\t\t\tlet transaction = db.transaction('files', 'readwrite');\n\t\t\tlet store = transaction.objectStore('files');\n\t\t\tlet files = Object.keys(wkof.file_cache.dir).filter(function(file){\n\t\t\t\tif (pattern instanceof RegExp) {\n\t\t\t\t\treturn file.match(pattern) !== null;\n\t\t\t\t} else {\n\t\t\t\t\treturn (file === pattern);\n\t\t\t\t}\n\t\t\t});\n\t\t\tfiles.forEach(function(file){\n\t\t\t\tstore.delete(file);\n\t\t\t\tdelete wkof.file_cache.dir[file];\n\t\t\t});\n\t\t\tfile_cache_dir_save();\n\t\t\ttransaction.oncomplete = del_promise.resolve.bind(null, files);\n\t\t\treturn del_promise;\n\t\t}\n\t}", "Delete() {\n log.config(\"Delete() called on folder \" + this.name);\n let msgDBService = Cc[\"@mozilla.org/msgDatabase/msgDBService;1\"]\n .getService(Ci.nsIMsgDBService);\n let database = msgDBService.cachedDBForFolder(this);\n if (database) {\n database.ForceClosed();\n this.msgDatabase = null;\n }\n\n let pathFile = this.filePath;\n let summaryFile = getSummaryFileLocation(pathFile);\n\n // Remove summary file.\n summaryFile.remove(false);\n\n // Delete fake mailbox\n pathFile.remove(false);\n\n // Clean up .sbd folder if it exists.\n addDirectorySeparator(pathFile);\n if (pathFile.exists() && pathFile.isDirectory())\n pathFile.remove(true);\n\n // Make sure this is gone in RDF (though this may cause issues during destruction)\n let rdf = Cc[\"@mozilla.org/rdf/rdf-service;1\"]\n .getService(Ci.nsIRDFService);\n rdf.UnregisterResource(this.cppBase.QueryInterface(Ci.nsIRDFResource));\n\n // null parent means an invalid folder.\n this.parent = null;\n }", "static deleteFile(filePath) {\n if (Utilities.fileExists(filePath)) {\n console.log(`Deleting: ${filePath}`);\n fsx.unlinkSync(filePath);\n }\n }", "function deleteFile(filePath) {\n if(!filePath.startsWith('/')){\n filePath = '/' + filePath;\n }\n var data = {\n path: filePath\n };\n return _operation('delete', data);\n }", "function _deleteDB(name) {\r\n var self = arguments.callee\r\n var dir = dbpath + name;\r\n if (fs.existsSync(dir)) {\r\n fs.readdirSync(dir).forEach(function (file) {\r\n var C = dir + '/' + file\r\n if (fs.statSync(C).isDirectory()) self(C)\r\n else fs.unlinkSync(C)\r\n })\r\n fs.rmdirSync(dir)\r\n }\r\n}", "delete() {\n\t\tthis.data.delete();\n\t}", "deleteImage() {\n const { image } = this.props.route.params;\n var imgRef = firebase.storage().refFromURL(image.downloadURL);\n imgRef.delete().then(() => {\n this.deleteRefFromFirestore();\n this.props.navigation.goBack(\"My Images\");\n }).catch(() => {\n Alert.alert(\"Could Not Delete\", \"There was an error deleting this image. Please Try again.\");\n });\n }", "function dbDeleteImage(fileId, folderName, fileName) {\n var authedUser, uid;\n return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_1___default.a.wrap(function dbDeleteImage$(_context3) {\n while (1) {\n switch (_context3.prev = _context3.next) {\n case 0:\n _context3.next = 2;\n return Object(redux_saga_effects__WEBPACK_IMPORTED_MODULE_12__[\"select\"])(_store_reducers_authorize__WEBPACK_IMPORTED_MODULE_21__[\"authorizeSelector\"].getAuthedUser);\n\n case 2:\n authedUser = _context3.sent;\n uid = authedUser.get('uid');\n\n if (!uid) {\n _context3.next = 16;\n break;\n }\n\n _context3.prev = 5;\n _context3.next = 8;\n return Object(redux_saga_effects__WEBPACK_IMPORTED_MODULE_12__[\"call\"])(galleryService.deleteFile, uid, fileId, folderName);\n\n case 8:\n _context3.next = 10;\n return Object(redux_saga_effects__WEBPACK_IMPORTED_MODULE_12__[\"put\"])(_store_actions_imageGalleryActions__WEBPACK_IMPORTED_MODULE_17__[\"deleteImage\"](fileId));\n\n case 10:\n _context3.next = 16;\n break;\n\n case 12:\n _context3.prev = 12;\n _context3.t0 = _context3[\"catch\"](5);\n _context3.next = 16;\n return Object(redux_saga_effects__WEBPACK_IMPORTED_MODULE_12__[\"put\"])(_store_actions_globalActions__WEBPACK_IMPORTED_MODULE_16__[\"showMessage\"](_context3.t0.message));\n\n case 16:\n case \"end\":\n return _context3.stop();\n }\n }\n }, _marked3, null, [[5, 12]]);\n}", "function deleteFile(file, path) {\n\treturn new Promise((resolve, reject) => {\n\t\tconst files = _.isArray(file) ? file : [file];\n\t\tvar filesRemaining = files.length;\n\t\tfiles.forEach(file => {\n\t\t\tdebug(`deleting ${file.name}`);\n\n\t\t\tvar filePath = `${path}/${file.path}`;\n\t\t\tfilesRemaining--;\n\n\t\t\tfs.unlink(filePath, err => {\n\t\t if (err) reject(err);\n\t\t });\n\n\t\t if (!filesRemaining) resolve(file);\t\n\t\t});\t\n });\n}", "function deleteImage() {\n firebase.database().ref('sessions/' + sessionName + \"/image\").remove();\n}", "function deleteFileHook(){\n var file = Java.use(\"java.io.File\")\n var removePtr = Module.findExportByName(\"libc.so\", \"remove\");\n Interceptor.replace(removePtr, new NativeCallback(function (pathPtr, flags) {\n var path = Memory.readUtf8String(pathPtr);\n send('delete file: ' + path);\n return 0; //pretend file was deleted\n }, 'int', ['pointer', 'int']));\n\n file.delete.overload().implementation = function (s) {\n s = this.getAbsolutePath()\n send('delete file: ' + s)\n //call original method\n // return this.delete()\n return true; //pretend file was deleted\n }\n}", "function deleteCsv(fileName) {\n const fs = require(\"fs\");\n fs.unlink(fileName, function (err) {\n if (err) throw err;\n //if no error, file has been deleted\n console.log(\"File deleted!\");\n })\n}", "async cleanUpMusic() {\n const docs = await this.db.getDocuments('music');\n const hashes = {};\n \n for(let i = 0; i < docs.length; i++) {\n const doc = docs[i];\n \n if(\n !doc.fileHash || \n typeof doc.fileHash != 'string' ||\n (\n !this.isFileAdding(doc.fileHash) && \n !await this.hasFile(doc.fileHash) &&\n await this.db.getMusicByFileHash(doc.fileHash)\n )\n ) {\n await this.db.deleteDocument(doc);\n continue;\n }\n\n hashes[doc.fileHash] = true;\n }\n\n await this.iterateFiles(async filePath => {\n try {\n const hash = path.basename(filePath);\n\n if(!hashes[hash] && !this.isFileAdding(hash) && !await this.db.getMusicByFileHash(hash)) {\n await this.removeFileFromStorage(hash);\n }\n }\n catch(err) {\n this.logger.warn(err.stack);\n }\n });\n }", "deletePhoto() {\n\n // Get user\n let user = this.get('model');\n let url = this.get('photoDataUrl');\n\n // Delete the photo\n const deleteRequest = this.get('ajax').delete(url);\n\n // Handle success\n deleteRequest.then(()=> {\n user.set('photo', null);\n this.get('notify').success(this.get('i18n').t('notify.photoDeleted'));\n });\n }", "function deleteFile(deletedFilePath, timestamp) {\n\n //if this should be ignored due to the st-ignore.json file \n if(!ignoreThisFileOrDir(deletedFilePath)) {\n \n //get the file id based on the file path\n var deletedFileId = getIdFromFilePath(deletedFilePath);\n \n //if the file is being tracked\n if(deletedFileId) {\n\n //delete the mapping from the old file path \n removeFilePathToIdMap(deletedFilePath);\n \n //update the file in the collection of all files\n allFiles[deletedFileId].isDeleted = true;\n\n //create a delete file event\n var deleteFileEvent = {\n id: \"ev_\" + branchId + \"_\" + autoGeneratedEventId, \n timestamp: timestamp,\n type: \"Delete File\",\n fileId: deletedFileId,\n fileName: allFiles[deletedFileId].currentName,\n parentDirectoryId: allFiles[deletedFileId].parentId,\n createdByDevGroupId: currentDeveloperGroup.id\n };\n \n //increase the id so the next event has a unique id\n autoGeneratedEventId++;\n \n //add the event to the collection of all events\n codeEvents.push(deleteFileEvent);\t\n }\n }\n}", "delete () {\n Api.delete(null, ApiUrls.sources, this.id);\n }", "cleanDrive() {\n let auth = this.auth;\n const drive = google.drive({ version: 'v3', auth });\n drive.files.list({\n includeRemoved: false,\n pageSize: 10,\n fields: 'nextPageToken, files(id, name)',\n }, (err, res) => {\n if (err) return console.log('The API returned an error: ' + err);\n const files = res.data.files;\n if (files.length) {\n console.log('Deleting files...');\n files.map((file) => {\n drive.files.delete({\n 'fileId': file.id\n }).then(delRes => {\n console.log(`${file.name} (${file.id})`);\n });\n });\n this.db.collection(\"filesCollection\").drop();\n console.log('Database cleaned');\n } else {\n console.log('No files found.');\n }\n });\n \n }", "async deleteLocalFile(path){\n const response = fs.promises.rm(path).then(async (msg) => {\n return true;\n }).catch(error => {\n Logger.log(error);\n return false;\n });\n\n return response;\n }", "function deleteFile(fileID) {\n $(\"#fileList div[data-id='\" + fileID + \"']\").remove();\n\n // Remove visual of the file in other clients\n var taskID = $(\"#btnSubmitComment\").attr(\"data-task-id\");\n\n $.ajax({\n url: \"Handler/FileHandler.ashx\",\n data: {\n action: \"deleteTaskFile\",\n projectID: projectID,\n taskID: taskID,\n fileID: fileID\n },\n type: \"get\",\n success: function () {\n proxyTC.invoke(\"deleteFile\", taskID, fileID)\n }\n });\n}", "function _delete(_id) {\n var deferred = Q.defer();\n\n db.users.findById(_id, function (err, user) {\n if (err) deferred.reject(err);\n\n //console.log(user.profilePicUrl);\n\n if(user.profilePicUrl){\n fs.unlink('profile_pictures/'+user.profilePicUrl, function (err) {\n if (err) deferred.reject(err);\n });\n }\n\n db.users.remove(\n { _id: mongo.helper.toObjectID(_id) },\n function (err) {\n if (err) deferred.reject(err);\n \n deferred.resolve();\n });\n\n });\n \n return deferred.promise;\n}", "function deleteMinerIdRevocationDataFile (aliasName) {\n const filePath = path.join(process.env.HOME, filedir, aliasName, MINERID_REVOCATION_DATA_FILENAME)\n fs.unlink(filePath, (err) => {\n if (err) throw err;\n console.debug(`${filePath} was deleted`);\n });\n}", "async deleteFilm({id: id}) {\n const idFound = movie.findOne({id: id})\n return idFound.remove()\n }" ]
[ "0.6989686", "0.68779194", "0.66720486", "0.66058576", "0.66056955", "0.6566303", "0.6542845", "0.6527612", "0.65160334", "0.64977455", "0.64340365", "0.64320177", "0.63788784", "0.63765717", "0.63665605", "0.6364746", "0.63518393", "0.63490963", "0.63369656", "0.6324851", "0.6324031", "0.63057363", "0.6258589", "0.6253746", "0.6218271", "0.6211927", "0.6191134", "0.61788154", "0.61754024", "0.61646825", "0.61603665", "0.6128679", "0.612537", "0.60975665", "0.6094247", "0.6067532", "0.6053926", "0.6046331", "0.6044612", "0.6035277", "0.60292006", "0.60292006", "0.60286796", "0.6010401", "0.5980091", "0.5970061", "0.59596425", "0.5952", "0.59411734", "0.5927637", "0.59051746", "0.5899127", "0.58920467", "0.5891046", "0.5886713", "0.58782464", "0.58776695", "0.58662766", "0.5864256", "0.5861503", "0.58613575", "0.5854376", "0.58522993", "0.5846943", "0.58458394", "0.583984", "0.5838017", "0.58369255", "0.58366406", "0.5833235", "0.5830974", "0.58069676", "0.57994676", "0.57977384", "0.57925797", "0.5791848", "0.57889324", "0.5767791", "0.576769", "0.5766592", "0.5764456", "0.5763461", "0.5760016", "0.5743314", "0.5731218", "0.5729328", "0.57199544", "0.57184356", "0.570995", "0.5701933", "0.56967044", "0.56962085", "0.568353", "0.56835234", "0.567799", "0.5674087", "0.5668268", "0.566577", "0.5656727", "0.5654941" ]
0.7680326
0
as few characters as possible from str.
function balanceParens(str) { // Counts opens - closed. let opens = 0; // First pass: Remove extra close-parens let firstPass = []; for (let char of str) { if (char === '(') { opens += 1; firstPass.push('('); } else if (char === ')') { if (opens === 0) { // We have to remove this character } else { opens -= 1; firstPass.push(')'); } } else { firstPass.push(char); } } // Second pass: remove extra open-parens let output = []; for (let char of firstPass) { if (opens > 0 && char === '(') { // Remove this one opens -= 1; } else { output.push(char); } } return output.join(''); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function charactersLong(str){\n if( str.length <= 20){\n return str + str;\n } else {\n return str.slice(0,str.length/2);\n } \n }", "function constantLength ( str ) {\n return (str + \" \").slice(0,8);\n}", "function longString(str) {\n if (str.length <= 20) {\n return str + str;\n } else return str.slice(0, Math.floor(str.length / 2));\n}", "function reduceCharacters(str)\n{\n var a = str.slice(0, 50) + \"...\";\n console.log(\"final string\" +a); \n}", "function unleakString(s) { return (' ' + s).substr(1); }", "function getInitalWords(str) {\n return str.substr(1);\n }", "function $asStringSmall(str, l) {\n\tvar result = \"\";\n\tvar point = 255;\n\tvar last = 0;\n\tfor (var i = 0; i < l && point >= 32; i++) {\n\t\tpoint = str.charCodeAt(i);\n\t\tif (point === 34 || point === 92) {\n\t\t\tresult += `${str.slice(last, i)}\\\\`;\n\t\t\tlast = i;\n\t\t}\n\t}\n\n\tif (last === 0) {\n\t\tresult = str;\n\t} else {\n\t\tresult += str.slice(last);\n\t}\n\treturn point < 32 ? JSON.stringify(str) : `\"${result}\"`;\n}", "function limitLen(str, len) {\n\t if (str.length > len) {\n\t return str.substr(0, len);\n\t } else {\n\t return str;\n\t }\n\t}", "function limitLen(str, len) {\n\t if (str.length > len) {\n\t return str.substr(0, len);\n\t } else {\n\t return str;\n\t }\n\t}", "lengthChecker(str) { \n\t\tstr=str.toString();\n\t\t\n\t\tif (str.length < 2) {\n\t\t\tstr='0'+str;\n\t\t\treturn str;\n\t\t}\n\n\t\treturn str;\n\t}", "function cutString(str) {\n return str.slice(1, str.length - 1);\n }", "function first (str='', len) {\n var result = ''\n for (i = 0; i < len; i++) {\n result = result + str[i]\n }\n return result\n}", "function shortestString(shortStr) {\n var leastAmntOfCharacters = shortStr.reduce((x,y) => x.length <= y.length ? x : y);\n return leastAmntOfCharacters\n}", "function ps( str ) {\n if ( !str ) {\n return \"___\";\n }\n var retStr = \"\";\n retStr = retStr.concat(str.toString().substring(0, strLen))\n return retStr;\n}", "function shortenString(string) {\n return string.slice(0,8) + \"...\"; \n}", "function stringLength(str){\nvar result =0;\nwhile(str != \"\"){\n\n \tresult+=1;\n str= str.slice(1);\n}\n \n return result;\n \n }", "function shortenString(string) {\n return string.slice(0, 8) + \"...\";\n}", "function getStr(str) {\n console.log(str.length);\n}", "function reduceString(s) { return (' ' + s).substr(1); }", "function firstChars(length, string) {\n var newString = '';\n for (var i = 0; i < length; i++) {\n if (i < string.length) {\n newString += string[i];\n }\n }\n return newString;\n}", "function getLength (str) {\n return str.length;\n}", "function $asStringSmall (str) {\n const l = str.length\n let result = ''\n let last = 0\n let found = false\n let surrogateFound = false\n let point = 255\n // eslint-disable-next-line\n for (var i = 0; i < l && point >= 32; i++) {\n point = str.charCodeAt(i)\n if (point >= 0xD800 && point <= 0xDFFF) {\n // The current character is a surrogate.\n surrogateFound = true\n }\n if (point === 34 || point === 92) {\n result += str.slice(last, i) + '\\\\'\n last = i\n found = true\n }\n }\n\n if (!found) {\n result = str\n } else {\n result += str.slice(last)\n }\n return ((point < 32) || (surrogateFound === true)) ? JSON.stringify(str) : '\"' + result + '\"'\n}", "function getLength(str) {\n return str.length;\n}", "function getLength(str) {\n return str.length;\n}", "function getLength(str) {\n return str.length;\n}", "function truncateString(str, num) {\r\n // Clear out that junk in your trunk\r\n return str;\r\n}", "function extractSpecifiedNumberOfCharsFromAString(\n stringToExtract,\n numberOfCharsToExtract\n) {\n return stringToExtract.slice(0, numberOfCharsToExtract);\n}", "function reduceString(s) {\n if (s.length > 60) return s.substring(0, 60).toString();\n return s.toString();\n}", "function forceLength(str, len) {\n str = str.toString();\n var diff = len - str.length;\n\n for (var i = 0; i < diff; i++)\n str = '0' + str;\n\n return str;\n }", "function substrMe(str,start,length){\r\n \r\n return str.substr(start,length);\r\n\r\n }", "function doubleChar(str) {\n let s= '';\n for(let i=0; i<str.length; i++){\n s= s + str[i] + str[i];\n }\n return s;\n}", "function removeChar(str) {\n\n\n return str.slice(1, str.length - 1)\n\n}", "function DistinctCharacters(str) {\n const dic = {};\n for (let i = 0; i < str.length; i++) {\n if (!dic[str[i]]) dic[str[i]] = true;\n }\n return (Object.keys(dic).length >= 10).toString();\n}", "function numChars(str1){\n return str1.length\n}", "function sc_stringLength(s) { return s.length; }", "function length(str) {\n\treturn str.length;\n}", "function removeChar(str) {\n return str.slice(1, str.length - 1);\n}", "function myspace(str) {\n\n var fuse=str.split('');\n for( let x=0;x<fuse.length;x++){\n if(fuse[x]==='a'){\n fuse[x]=4\n }else if(fuse[x]==='e'){\n fuse[x]=3\n }else if(fuse[x]==='i'){\n fuse[x]=1\n }else if(fuse[x]==='o'){\n fuse[x]=0\n }else if(fuse[x]==='s'){\n fuse[x]=5\n }\n }\n\n return fuse.join('')\n\n}", "asStringSmall (str) {\n const len = str.length\n let result = ''\n let last = -1\n let point = 255\n\n // eslint-disable-next-line\n for (var i = 0; i < len; i++) {\n point = str.charCodeAt(i)\n if (point < 32) {\n return JSON.stringify(str)\n }\n if (point >= 0xD800 && point <= 0xDFFF) {\n // The current character is a surrogate.\n return JSON.stringify(str)\n }\n if (\n point === 0x22 || // '\"'\n point === 0x5c // '\\'\n ) {\n last === -1 && (last = 0)\n result += str.slice(last, i) + '\\\\'\n last = i\n }\n }\n\n return (last === -1 && ('\"' + str + '\"')) || ('\"' + result + str.slice(last) + '\"')\n }", "function truncateString(str, num) {\n //Clear out that junk in your trunk\n if (str.length <= num) {\n return str; //code 3.\n } else if (num <= 2) {\n return str.slice(0, num) + \"...\"; //code 1.\n } else {\n return str.slice(0, num-3) + \"...\"; //code 2.\n }\n}", "function truncateString(str, num) {\n\t// Clear out that junk in your trunk\n\n\treturn str.length > num ? `${str.slice(0, num)}...` : str;\n}", "function upToTenCharacters(string) {\n string = string.toString();\n while (string.length < 10) {\n string = string.concat(\"_\");\n }\n return string;\n}", "static fromString(str) {\n var strMsg = function(strMsg) { return parseInt(strMsg, 16); }\n // .{8} => matches any character (except for line terminators)\n // {8} => Matches exactly 8 times\n // /g => global. All matches (don't return after first match)\n var [upper, lower] = str.match(/.{8}/g).map(strMsg);\n return new jsLong(upper, lower);\n }", "function removeChar(str){\n return str.slice(1, str.length-1)\n}", "function getFirstWordLength( string ) { // 5726\n return string.match( /\\w+/ )[ 0 ].length // 5727\n } // 5728", "function length(str) {\n return str.length;\n}", "function length(str) {\n return str.length;\n }", "function fixed_len(str, count) {\n var l = str.length;\n\n if (!count)\n count = 10;\n\n if (l > count)\n return str.substr(0, count);\n else\n return str + new Array(count + 1 - l).join(\" \");\n }", "function get_first(str) {\n return ('000' + str).substr(-3);\n }", "function stringLength(str) {\n let strLength = str.length;\n\n return strLength;\n}", "function strim(s) {\n return s.trim()\n}", "function shortenString(s, size, start = null) {\n let jump = parseInt(s.length/size);\n if(start === null){\n start = s.charCodeAt(0).toString().substr(-1)/1;\n }\n let output = \"\";\n for(let i = start; i < s.length; i += jump){\n output += s.substr(i, 1);\n }\n // Does the password have a repetetive pattern? Recursive\n if(output.search(/(.)\\1/) >= 0){\n return shortenString(s, size, start+1);\n }\n if(output.length < 20)\n return \"Password generation failed\";\n\n return output.substr(0,20);\n}", "function afficherNCar(str){\n \tvar result4 = str.substring(0,9);\n \treturn result4;\n }", "function removeChar(str) {\n return str.slice(1, -1);\n}", "function removeChar(str) {\n return str.slice(1, -1);\n}", "function uniqChars(str) {\n return str.replace(/[\\s\\S](?=([\\s\\S]+))/g, function(c, s) {\n return s.indexOf(c) + 1 ? '' : c;\n });\n }", "function removeChar(str) {\n\treturn str.slice(1, -1);\n}", "function SupprEspaceString(str){\n\tvar result6 = str.trim();\n\treturn result6;\n }", "function parse_username(str) {\n\tstr = str.replace(/[^\\w]/g,\"\").toLowerCase();\n\tif (!str)\n\t\tstr = \"user\"; // nothing? we'll give you something boring.\n\treturn str.slice(0,9);\n}", "function inverte(str){\n var result = '',\n length = str.length;\n \n while (length--) { result += str[length]; }\n \n console.log(result);\n}", "function crop(str, maxChars, append) {\n\t str = toString(str);\n\t return truncate(str, maxChars, append, true);\n\t }", "function truncateString(str, num) {\n // Clear out that junk in your trunk\n if(num >= str.length) return str;\n if(num <= 3) return str.slice(0, num) + \"...\";\n return str.slice(0, num)+'...';\n}", "function removeChar(str) {\n return str.slice(1, -1);\n}", "function maxChar(str) {\n let hash = {}\n str.split('').map(el => hash[el] = hash[el] + 1 || 1 )\n return Object.keys(hash)[0]\n\n}", "function strWidth(str){\n\t\tif(str.length == 0)return 0;\n\t\t//We need to calculate how long our string will be in pixels\n\t\tvar strWidths = {\" \":9,\"!\":10,\"\\\"\":15,\"#\":17,\"$\":17,\"%\":27,\"&\":22,\"'\":8,\"(\":10,\")\":10,\"*\":12,\"+\":18,\",\":9,\"-\":10,\".\":9,\"/\":9,\"0\":17,\"1\":17,\"2\":17,\"3\":17,\"4\":17,\"5\":17,\"6\":17,\"7\":17,\"8\":17,\"9\":17,\":\":10,\";\":10,\"<\":18,\"=\":18,\">\":18,\"?\":19,\"@\":30,\"A\":22,\"B\":22,\"C\":22,\"D\":22,\"E\":21,\"F\":19,\"G\":24,\"H\":22,\"I\":9,\"J\":17,\"K\":22,\"L\":19,\"M\":25,\"N\":22,\"O\":24,\"P\":21,\"Q\":24,\"R\":22,\"S\":21,\"T\":19,\"U\":22,\"V\":21,\"W\":29,\"X\":21,\"Y\":21,\"Z\":19,\"[\":10,\"]\":10,\"^\":18,\"_\":17,\"`\":10,\"a\":17,\"b\":19,\"c\":17,\"d\":19,\"e\":17,\"f\":10,\"g\":19,\"h\":19,\"i\":9,\"j\":9,\"k\":17,\"l\":9,\"m\":27,\"n\":19,\"o\":19,\"p\":19,\"q\":19,\"r\":12,\"s\":17,\"t\":10,\"u\":19,\"v\":17,\"w\":24,\"x\":17,\"y\":17,\"z\":15,\"{\":12,\"|\":9,\"}\":12,\"~\":18};\n\t\tvar w = 0;\n\t\tfor(var i = 0; i<str.length; i++){\n\t\t\t//If we dont know how wide the char is, set it to 28.5 that is the width of W and no char is wider than that.\n\t\t\tw += fontSize/30*(strWidths[str[i]]?strWidths[str[i]]:28.5);\n\t\t}\n\t\t//This is for the space between the text and the symbol.\n\t\tw += spaceTextIcon;\n\t\treturn w;\n\t}", "function s(str) {\n // two pointers\n // window\n const map = {};\n let lo = 0;\n let hi = 0;\n let len = 0;\n let maxLen = 0;\n while (hi < str.length) {\n const char = str[hi];\n map[char] ? map[char]++ : (map[char] = 1);\n hi++;\n len++;\n\n while (map[char] > 1 && lo < hi) {\n map[str[lo]]--;\n lo++;\n len--;\n }\n\n // if (map[char] > 1) {\n // while (lo < hi && str[lo] !== char) {\n // map[str[lo]]--;\n // lo++;\n // len--;\n // }\n // map[str[lo]]--;\n // lo++;\n // len--;\n // }\n\n maxLen = Math.max(maxLen, len);\n }\n\n return maxLen;\n}", "function str_input(str) {\n let newStr_input = '';\n for (let i = str.length-1; i >= 0; i--) {\n newStr_input += str[i];\n }\n return newStr_input;\n }", "fill( str, length, char, append ) {\n str = String( str );\n length = parseInt( length ) || 20;\n char = String( char || ' ' );\n append = String( append || '' );\n if ( str.length > length ) return str.substring( 0, ( length - 3 ) ) + '...';\n return str + char.repeat( length - str.length ) + append;\n }", "function getFirstWordLength( string ) {\n\t return string.match( /\\w+/ )[ 0 ].length\n\t }", "function crop(str, maxChars, append) {\n str = toString(str);\n return truncate(str, maxChars, append, true);\n }", "function cutFirst(str){\n return str.slice(2)\n }", "function rep(str) {\n str = setCharAt(str, 64, 'g');\n return str\n}", "function pegaString(str, first_character, last_character) {\n\tif(str.match(first_character + \"(.*)\" + last_character) == null){\n\t\treturn null;\n\t}else{\n\t new_str = str.match(first_character + \"(.*)\" + last_character)[1].trim()\n\t return(new_str)\n }\n}", "function truncate_string(str, length) {\n if ((str.constructor === String) && (length>0)) {\n return str.slice(0, length);\n }\n}", "function removeChar(str){\n return str.substring(1,str.length -1);\n \n }", "function moreThan(str, n) {\n var tr = str;\n var length = str.length;\n\n if (length >= n) {\n var first = tr.slice(0, Math.round(length / 2));\n var second = tr.slice(Math.round(length / 2));\n\n tr = first + '-' + second;\n }\n\n return tr;\n}", "function rep(str) {\n //stimuli.at_stimulus;\n str = setCharAt(str,20,'g');\n return str\n }", "function truncateString(str, num) {\n // Clear out that junk in your trunk\n if (str.length > num) {\n return str.slice(0, num) + \"...\";\n }\n\n return str\n}", "function keepFirst(str)\n{ \n const length = str.length;\n return str.substring(0,2);\n}", "function str_val(str) {\n\n \n}", "function getFirstWordLength(string) {\r\n return string.match(/\\w+/)[0].length;\r\n }", "function stringExpansion(str) {\n return str.split('').reduce(function (acc, item, index) {\n if (isNaN(Number(item))) {\n if (isNaN(Number(str[index - 1]))) {\n acc = acc + item;\n }\n acc = acc + item.repeat(str[index - 1]);\n }\n return acc;\n }, '');\n}", "function decodePart(str) {\r\n var m = \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+-\";\r\n var result = \"\";\r\n var packer = 0;\r\n var count = 0;\r\n \r\n var i = 0;\r\n for (i=0; i < str.length; i++) {\r\n\t// Get the offset to the current character in our map\r\n\tvar x = m.indexOf(str.charAt(i));\r\n\t\r\n\t// For invalid characters, point them out really well!\r\n\tif(x<0) {\r\n\t result += \" > \" + str.charAt(i) + \" < \";\r\n\t continue;\r\n\t}\r\n\t\r\n\t// only count valid characters...why not?\r\n\tcount++;\r\n\t\r\n\t// Pack them bits.\r\n\tpacker = packer << 6 | x\r\n\t \r\n\t // every four bytes, we have three valid characters.\r\n\t if (count == 4) {\r\n\t\tresult += String.fromCharCode((packer >> 16) ^ 67);\r\n\t\tresult += String.fromCharCode((packer >> 8 & 255) ^ 67);\r\n\t\tresult += String.fromCharCode((packer & 255) ^ 67);\r\n\t\tcount=0; packer=0;\r\n\t }\r\n }\r\n \r\n // Now, deal with the remainders\r\n if(count==2) {\r\n\tresult += String.fromCharCode((( (packer << 12) >> 16) ^ 67));\r\n } else if(count == 3) {\r\n\tresult += String.fromCharCode(( (packer << 6) >> 16) ^ 67);\r\n\tresult += String.fromCharCode(( (packer << 6) >> 8 & 255) ^ 67);\r\n }\r\n return result;\r\n}", "function cutFirst(str) {\n return str.slice(2);\n}", "function flatstr (s) {\n s | 0\n return s\n}", "function unCStr(str) {return unAppCStr(str, [0]);}", "function unCStr(str) {return unAppCStr(str, [0]);}", "function unCStr(str) {return unAppCStr(str, [0]);}", "function isStringTwentyChar(checkString){\n \n for (var i = 0; i < checkString.length; i++){\n if (checkString.length <= 20){\n return checkString.slice(0, checkString.length / 2); \n }else {\n return checkString + checkString;\n }\n }\n}", "function length(s) {\n return s.lastIndexOf('')\n }", "function parse_free_text(string) {\n return string.substr( 1, string.length-2 );\n }", "static stringToTrytes(str) {\n const encoded = TextHelper.encodeNonASCII(str);\n return encoded ? TrytesHelper.fromAscii(encoded) : \"\";\n }", "tryConsume(str) {\n if (this.i + str.length > this.length) {\n return null;\n }\n\n if (str == this.source.slice(this.i, this.i + str.length)) {\n this.i += str.length;\n return str;\n }\n\n return null;\n }", "function findStringLength(str) {\n let counter = 0;\n while(str[counter] !== undefined) {\n counter++;\n }\n console.log('String Length', counter);\n}", "function get_rest(str) {\n return str.substr(0, str.length - 3);\n }", "function twoCharaters(s) {\n let maxSize = 0;\n let duppedStr = s.slice(0);\n const chrsSet = new Set();\n\n for (let i = 0; i < s.length; i++) {\n chrsSet.add(duppedStr[i]);\n }\n\n const uniqChrs = Array.from(chrsSet);\n for (let i = 0; i < uniqChrs.length - 1; i++) {\n for (let j = i + 1; j < uniqChrs.length; j++) {\n duppedStr = duppedStr.split(\"\").filter((chr) => (chr === uniqChrs[i] || chr === uniqChrs[j])).join(\"\");\n if (validT(duppedStr)) {\n if (duppedStr.length > maxSize) {\n maxSize = duppedStr.length;\n }\n }\n duppedStr = s.slice(0);\n }\n }\n return maxSize;\n}", "function getFirstWordLength(string) {\n return string.match(/\\w+/)[0].length;\n }", "function getFirstWordLength(string) {\n return string.match(/\\w+/)[0].length;\n }", "function getFirstWordLength(string) {\n return string.match(/\\w+/)[0].length;\n }", "function truncateString(str, len) {\n if (str.length > len) {\n str = str.substring(0, len);\n }\n return str;\n}", "function truncateString(str, num) {\n if (str.length <= num) {\n return str;\n } else if (num <= 3) {\n return str.slice(0, num) + \"...\";\n } else {\n return str.slice(0, num - 3) + \"...\";\n }\n}" ]
[ "0.7018939", "0.6752478", "0.6597846", "0.65808046", "0.65570694", "0.6514993", "0.648797", "0.64469254", "0.64469254", "0.6436643", "0.6435429", "0.64293724", "0.63862336", "0.6374462", "0.63716567", "0.6343907", "0.6343608", "0.6245007", "0.6230537", "0.62231797", "0.6218204", "0.6178165", "0.61694384", "0.61694384", "0.61694384", "0.61463577", "0.6134601", "0.6133059", "0.6097216", "0.60849905", "0.60809755", "0.60803825", "0.60773474", "0.60751176", "0.60541147", "0.6046212", "0.60392046", "0.60156363", "0.60128695", "0.60073006", "0.6006859", "0.6001042", "0.5991818", "0.59910995", "0.5987249", "0.5977716", "0.597593", "0.5968768", "0.59641325", "0.594846", "0.59456736", "0.59443396", "0.59283936", "0.5921812", "0.5921812", "0.59202445", "0.59125805", "0.5898863", "0.5894657", "0.5890551", "0.5888061", "0.5886765", "0.5885852", "0.5877628", "0.5872862", "0.5869097", "0.5866231", "0.58655995", "0.58653927", "0.58616596", "0.5859094", "0.58535486", "0.5850926", "0.5835878", "0.58345073", "0.5834422", "0.5830225", "0.5822353", "0.58172804", "0.5812448", "0.5810982", "0.5806886", "0.58064204", "0.5805571", "0.5802653", "0.57995373", "0.57995373", "0.57995373", "0.5797896", "0.57956475", "0.57952845", "0.57878774", "0.5787636", "0.57791364", "0.5777773", "0.57757837", "0.5774372", "0.5774372", "0.5774372", "0.57735217", "0.57735014" ]
0.0
-1
renderTable renders the filteredData to the tbody
function renderTable() { var tbody = d3.select("tbody"); tbody.html(""); // Iterate through each fileteredData and pend to table filteredData.forEach(sighting => { var tbl_col = Object.keys(sighting); // console.log(tbl_col); var row = tbody.append("tr"); tbl_col.forEach(s_info => { row.append("td").text(sighting[s_info]); // console.log(sighting); // console.log(tbl_col); // console.log(s_info); }); }); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function renderTable() {\n $tbody.innerHTML = \"\";\n for (var i = 0; i < filteredData.length; i++) {\n // Get the current object and its fields\n var data = filteredData[i];\n var fields = Object.keys(data);\n // Create a new row in the tbody, set the index to be i + startingIndex\n var $row = $tbody.insertRow(i);\n for (var j = 0; j < fields.length; j++) {\n var field = fields[j];\n var $cell = $row.insertCell(j);\n $cell.innerText = data[field];\n }\n }\n}", "function renderTable() {\n $tbody.innerHTML = \"\";\n for (var i = 0; i < filteredDataSet.length; i++) {\n\n // Get the current object and its fields\n var data = filteredDataSet[i];\n var fields = Object.keys(data);\n\n // Create a new row in the tbody, set the index to be i + startingIndex\n var $row = $tbody.insertRow(i);\n for (var j = 0; j < fields.length; j++) {\n\n // For every field in the table object, create a new cell at set its inner text to be the current value at the current field\n var field = fields[j];\n var $cell = $row.insertCell(j);\n $cell.innerText = data[field];\n }\n }\n}", "function renderTable() {\n $tbody.innerHTML = '';\n for (var i = 0; i < filteredData.length; i++) {\n // Get get the current UFOData object and its fields\n var UFOData = filteredData[i];\n var fields = Object.keys(UFOData);\n // Create a new row in the tbody, set the index to be i + startingIndex\n var $row = $tbody.insertRow(i);\n for (var j = 0; j < fields.length; j++) {\n // For every field in the UFOData object, create a new cell at set its inner text to be the current value\n // at the current UFOData's field\n var field = fields[j];\n var $cell = $row.insertCell(j);\n $cell.innerText = UFOData[field];\n }\n }\n}", "function renderTable() {\n $tbody.innerHTML = \"\";\n for (var i = 0; i < filteredTable.length; i++) {\n var address = filteredTable[i];\n var fields = Object.keys(address);\n var $row = $tbody.insertRow(i);\n for (var j = 0; j < fields.length; j++) {\n var field = fields[j];\n var $cell = $row.insertCell(j);\n $cell.innerText = address[field];\n }\n }\n}", "function renderTable() {\n $tbody.innerHTML = \"\";\n for (var i = 0; i < filteredData.length; i++) {\n // Get get the current address object and its fields\n var data = filteredData[i];\n var fields = Object.keys(data);\n // Create a new row in the tbody, set the index to be i + startingIndex\n var $row = $tbody.insertRow(i);\n for (var j = 0; j < fields.length; j++) {\n // For every field in the address object, create a new cell at set its inner text to be the current value at the current address's field\n var field = fields[j];\n var $cell = $row.insertCell(j);\n $cell.innerText = data[field];\n }\n }\n}", "function renderTable() {\n console.log(\"in Render\");\n tbody.innerHTML = \"\";\n for (var i = 0; i < filteredObs.length; i++) {\n // Get get the current address object and its fields\n var address = filteredObs[i];\n var fields = Object.keys(address);\n // Create a new row in the tbody, set the index to be i + startingIndex\n var row = tbody.insertRow(i);\n for (var j = 0; j < fields.length; j++) {\n // For every field in the address object, create a new cell at set its inner text to be the current value at the current address's field\n var field = fields[j];\n var cell = row.insertCell(j);\n cell.innerText = address[field];\n }\n }\n}", "function renderTable() { \r\n $tbody.innerHTML = \"\";\r\n var length = filteredData.length;\r\n for (var i = 0; i < length; i++) {\r\n // Get get the current address object and its fields\r\n var data = filteredData[i]; \r\n var fields = Object.keys(data); \r\n // Create a new row in the tbody, set the index to be i + startingIndex\r\n var $row = $tbody.insertRow(i);\r\n for (var j = 0; j < fields.length; j++) {\r\n // For every field in the address object, create a new cell at set its inner text to be the current value at the current address's field\r\n var field = fields[j];\r\n var $cell = $row.insertCell(j);\r\n $cell.innerText = data[field];\r\n }\r\n }\r\n}", "function renderTable() {\n clearTable();\n showTable();\n}", "function display (dataFiltered) {\n tbody.html(\"\");\n dataFiltered.forEach((report) => {\n var row = tbody.append(\"tr\");\n Object.entries(report).forEach(([key, value]) => {\n var cell = row.append(\"td\");\n cell.text(value);\n })\n })\n}", "function renderTable() {\n tbody.innerHTML = \"\";\n for (var i = 0; i < filterData.length; i++) {\n // Get the current objects and its fields. Calling each dictionary object 'ovni'. This comes from the data.js database where\n //the object dataSet holds an array (list) of dictionaries. Each dictionary is an object and I'm calling it ovni. This will\n // loop through each dictionary/object from the variable dataSet and store their keys in the variable fields. \n\n var ovni = filterData[i];\n var fields = Object.keys(ovni);\n \n // Create a new row in the tbody, set the index to be i + startingIndex\n // fields are the columns\n var row = tbody.insertRow(i);\n for (var j = 0; j < fields.length; j++) {\n // For every field in the address object, create a new cell and set its inner text to be the current value at the current address's field\n // the variable field will gather the columns names. It will loop through the fields(columns). Example, fields index 0 is datetime.\n var field = fields[j];\n var cell = row.insertCell(j);\n // now i will pass to the cell the ovni object, field values.\n cell.innerText = ovni[field];\n }\n }\n}", "function renderTable(filteredData) {\n $tbody.innerHTML = \"\";\n // Create variable for page number\n for (var i = 0; i < filteredData.length; i++) {\n // Get get the current address object and its fields\n var address = filteredData[i];\n var fields = Object.keys(address);\n // Create a new row in the tbody, set the index to be i + startingIndex\n var $row = $tbody.insertRow(i);\n // Increment page no if i is multiple of 50\n // add data attribute to row\n for (var j = 0; j < fields.length; j++) {\n // For every field in the address object, create a new cell at set its inner text to be the current value at the current address's field\n var field = fields[j];\n var $cell = $row.insertCell(j);\n $cell.innerText = address[field];\n }\n }\n}", "function renderTable() {\n $tbody.innerHTML = \"\";\n for (var i = 0; i < filteredrows.length; i++) {\n // Get get the current address object and its fields\n var rows = filteredrows[i];\n var fields = Object.keys(rows);\n // Create a new row in the tbody, set the index to be i + startingIndex\n var $row = $tbody.insertRow(i);\n for (var j = 0; j < fields.length; j++) {\n // For every field in the rows object, create a new cell at set its inner text to be the current value at the current row's field\n var field = fields[j];\n var $cell = $row.insertCell(j);\n $cell.innerText = rows[field];\n }\n }\n}", "function renderTable() {\n $tbody.innerHTML = \"\";\n // Set the value of endingIndex to startingIndex + resultsPerPage\n var endingIndex = startingIndex + resultsPerPage;\n // Get a section of the addressData array to render\n var addressSubset = filteredAddresses.slice(startingIndex, endingIndex);\n\n for (var i = 0; i < addressSubset.length; i++) {\n // Get get the current address object and its fields\n var address = addressSubset[i];\n var fields = Object.keys(address);\n // Create a new row in the tbody, set the index to be i + startingIndex\n var $row = $tbody.insertRow(i);\n for (var j = 0; j < fields.length; j++) {\n // For every field in the address object, create a new cell at set its inner text to be the current value at the current address's field\n var field = fields[j];\n var $cell = $row.insertCell(j);\n $cell.innerText = address[field];\n }\n }\n}", "function renderTable() {\n $tbody.innerHTML = \"\";\n for (var i = 0; i < filteredDateTime.length; i++) {\n // Get get the current date_time object and its fields\n var date_time = filteredDateTime[i];\n var fields = Object.keys(date_time);\n // Create a new row in the tbody, set the index to be i + startingIndex\n var $row = $tbody.insertRow(i);\n for (var j = 0; j < fields.length; j++) {\n // For every field in the date_time object, create a new cell at set its inner text to be the current value at the current date_time's field\n var field = fields[j];\n var $cell = $row.insertCell(j);\n $cell.innerText = date_time[field];\n }\n }\n}", "function filter(filteredData) {\n // Remove existing table so filtered data shows at the top\n d3.selectAll(\"td\").remove();\n console.log(\"Search Results:\", filteredData);\n // Build the new table\n // Use D3 to select the table body\n var tbody = d3.select(\"tbody\");\n filteredData.forEach((filteredTable) => {\n //append one table row per sighting\n var row = tbody.append(\"tr\");\n Object.entries(filteredTable).forEach(([key, value]) => {\n var cell = tbody.append(\"td\");\n cell.text(value);\n });\n }); \n }", "function renderTable(data) {\n var table_data = data.data;\n var height = data.height;\n var width = data.width;\n var table = document.getElementById(\"results-\" + current_tab);\n $(\".no-table#tab-\" + current_tab).hide();\n table.innerHTML = \"\";\n $(\"h5\").hide();\n for (var i = 0; i < height; i++) {\n let row = document.createElement(\"tr\");\n for (var j = 0; j < width; j++) {\n let col;\n if (i == 0 || j == 0) col = document.createElement(\"th\");\n else col = document.createElement(\"td\");\n col.appendChild(document.createTextNode(table_data[i][j]));\n row.appendChild(col);\n }\n table.appendChild(row);\n }\n var current_date = new Date();\n $(\".date#tab-\" + current_tab).text(current_date.toLocaleTimeString());\n $(\"h5\").show();\n}", "function renderTable() {\n $tbody.innerHTML = \"\";\n console.log(\"rendering\")\n\n for (var i = 0; i < tableData.length; i++) {\n // Get get the current UFO info object and its fields\n var ufoinfo = tableData[i];\n var field = Object.keys(ufoinfo);\n // Create a new row in the tbody, set the index to be i + startingIndex\n var $row = $tbody.insertRow(i);\n for (var j = 0; j < field.length; j++) {\n var field = fields[j];\n var $cell = $row.insertCell(j);\n $cell.innerText = ufo[field];\n }\n } \n}", "function renderTable() {\n $tbody.innerHTML = \"\";\n for (var i = 0; i < filteredUFOData.length; i++) {\n\n // Get UFO Data object and its fields\n var UFOdata = filteredUFOData[i];\n var fields = Object.keys(UFOdata);\n\n // Create new row in tbody\n var $row = $tbody.insertRow(i);\n for (var j = 0; j < fields.length; j++) {\n\n // For every field in the UFOData object create a new cell at set its inner text to be the current value at the current address's field\n var field = fields[j];\n var $cell = $row.insertCell(j);\n $cell.innerText = UFOdata[field];\n }\n\n }\n\n}", "function renderTable(search_data) { \n $tbody.innerHTML = \"\";\n for (var i = 0; i < search_data.length; i++) {\n \n var sighting = search_data[i];\n var fields = Object.keys(sighting);\n \n var $row = $tbody.insertRow(i);\n for (var j = 0; j < fields.length; j++) {\n var field = fields[j];\n var $cell = $row.insertCell(j);\n $cell.innerText = sighting[field];\n }\n }\n}", "function renderTable(data) {\r\n const header = buildTableHeader(data);\r\n const body = buildTableBody(data);\r\n const columns = data[0].length;\r\n\r\n const table = `\r\n <table id=\"main\" class=\"display\" style=\"width:100%\">\r\n <thead>${header}</thead>\r\n <tbody>${body}<tbody>\r\n </table>`;\r\n\r\n $('#table-wrapper').append(table);\r\n}", "function renderTable() {\n \n // Delete the list of cities prior to adding new city table data \n // (necessary to prevent repeat of table data)\n $(\"tbody\").empty();\n\n // Loop through the array of cities\n for (var i = 0; i < citiesArray.length; i++) {\n // Render new table row and table data elements for each city in the array.\n var tRow = $(\"<tr>\");\n var tData = $(\"<td>\");\n var tSpan = $(\"<span>\");\n\n tSpan.addClass(\"city\");\n tData.attr(\"data-name\", citiesArray[i]);\n tData.attr(\"data-index\", i);\n tSpan.text(citiesArray[i]);\n\n let button = $(\"<button>\");\n button.text(\"Remove\");\n button.attr(\"class\", \"btn-sm bg-danger rounded text-white\");\n \n tData.append(tSpan);\n tData.append(button);\n tRow.append(tData);\n $(\"tbody\").append(tRow);\n }\n }", "function filterTable() {\n \n // 8. Set the filtered data to the tableData.\n var filterData = tableData\n \n // 9. Loop through all of the filters and keep any data that\n // matches the filter values\n Object.entries(dataFilter).forEach(([key, value])=>{\n filterData = filterData.filter(row => row[key] === value);\n })\n \n // 10. Finally, rebuild the table using the filtered data\n buildTable(filterData);\n }", "function renderTable(data){\r\n\tlet table = createEmptyTable(\"tableContainer\");\r\n\tcreateHeaderRow(table, data[0]); // Pass any of the data objects to this function\r\n\tcreateResultRows(table, data); // Pass all of the data objects to this function\r\n}", "function renderData() {\n tableBody.innerHTML = \"\";\n for (var i = 0; i < tableData.length; i++) {\n var data = tableData[i];\n var rows = Object.keys(data);\n var input = tableBody.insertRow(i);\n for (var j = 0; j < rows.length; j++) {\n var field = rows[j];\n var cell = input.insertCell(j);\n cell.innerText = data[field];\n }\n }\n}", "render() {\n return (\n <div>\n <Filter\n search={this.state.search}\n handleFilterChange={this.handleFilterChange}\n />\n <table className=\" container table table-bordered table-striped\">\n <thead className=\"thead\">\n <tr className=\"table-secondary\">\n <th onClick={() => this.handleSortChange(\"firstname\")}>First Name</th>\n <th onClick={() => this.handleSortChange(\"lastname\")}>Last Name</th>\n <th onClick={() => this.handleSortChange(\"occupation\")}>Occupation</th>\n </tr>\n </thead>\n <tbody className=\"\">\n {this.state.employeeArray}\n </tbody>\n </table>\n </div>\n );\n }", "function displayTable(filteredData){\n // Use d3 to get a reference to the table body\n var tbody = d3.select(\"tbody\");\n\n //remove any data from the table\n tbody.html(\" \");\n\n // Iterate throug the UFO Info to search through the date time\n filteredData.forEach((date) => {\n \n //Use d3 to append row\n var row = tbody.append(\"tr\");\n \n //Use `Object entries to log the dates\n Object.entries(date).forEach(([key,value]) => {\n var cell = row.append(\"td\");\n cell.text(value)\n \n //Print filteredData\n console.log(filteredData);\n\n \n });\n });\n}", "function filterTable() {\n \n // 8. Set the filtered data to the tableData.\n var filteredData = tableData;\n \n // 9. Loop through all of the filters and keep any data that\n // matches the filter values\n if (entryLengthDatetime > 0) {\n console.log(inputValueDatetime)\n var filteredData = data.filter(report => report.datetime === inputValueDatetime);\n }\n \n else if (entryLengthCity > 0) {\n var filteredData = data.filter(report => report.city === inputValueCity);\n }\n \n else if (entryLengthState > 0) {\n var filteredData = data.filter(report => report.state === inputValueState);\n }\n \n else if (entryLengthCountry > 0) {\n var filteredData = data.filter(report => report.country === inputValueCountry);\n }\n \n else if (entryLengthShape > 0) {\n var filteredData = data.filter(report => report.shape === inputValueShape);\n }\n\n console.log(filteredData);\n\n refresh(filteredData);\n \n // 10. Finally, rebuild the table using the filtered data\n filteredData.forEach((UFOReport) => {\n var row = tbody.append(\"tr\");\n Object.entries(UFOReport).forEach(([key, value]) => {\n var cell = row.append(\"td\");\n cell.text(value);\n });\n });\n }", "function filterTable() {\n\n// 8. Set the filtered data to the tableData.\n let filteredData = tableData\n\n// 9. Loop through all of the filters and keep any data that\n// matches the filter values\nObject.entries(filters).forEach(([key, value]) => {\nfilteredData = filteredData.filter(row => row[key] === value);\n});\n\n// 10. Finally, rebuild the table using the filtered data 11.5.4\n// 11.5.4 given code After we pass filteredData in as our new argument, our full handleClick() function should look like the one below:\n buildTable(filteredData)\n}", "function filterTable() {\n // Prevent the page from refreshing\n d3.event.preventDefault();\n\n // get the user input for filtering \n var inputDate = dateSelect.property(\"value\")\n\n // make a copy of the data for filtering\n var filteredData = tableData;\n\n // if there is a date input, filter the table according to the date\n if (inputDate) {\n filteredData = filteredData.filter(sighting => sighting.datetime == inputDate);\n }\n\n // reset the table\n clearTable();\n\n // if the filteredData array is empty\n if (filteredData.length == 0) {\n var row = tbody.text(\"There are no sightings for your chosen filters.\");\n }\n\n // use forEach and Object.values to populate the tbody with filtered data\n filteredData.forEach((ufoSighting) => {\n\n // create a new row for every sighting object\n var row = tbody.append(\"tr\");\n\n // iterate through each object's values to populate cells\n Object.values(ufoSighting).forEach(value => {\n\n // create a new cell for each item in the object\n var cell = row.append(\"td\");\n\n // populate the td text with the value\n cell.text(value);\n cell.attr(\"class\", \"table-style\");\n }); // close second forEach\n\n }); // close first forEach\n\n}", "function viewFilterTable(UserID){\n //builds table layout\n let filterHTML = '<table>' +\n '<tr>' +\n '<th>Data Filter ID</th>' +\n '<th>|Data Filter Name</th>' +\n '<th>|Whitelist Status</th>' +\n '<th>|Public Status</th>' +\n '</tr>';\n //fetches data from dataset\n fetch(\"/datafilters/listone/\"+UserID,{method:'get'}\n ).then(response=>response.json()\n ).then(responseData=> {\n console.log(responseData);\n if (responseData.hasOwnProperty('error')) {\n alert(responseData.error);\n } else {\n for (let i=0; i<responseData.length; i++){\n filterHTML += `<tr>` +\n //HTML constructor\n `<td>${responseData[i].DataFilterID}</td>` +\n `<td>|${responseData[i].DataFilterName}</td>` +\n `<td>|${responseData[i].WhitelistBlacklist}</td>` +\n `<td>|${responseData[i].PublicPrivate}</td>` +\n `</tr>`;\n }\n filterHTML += '</table>'\n }\n //html assigner\n document.getElementById(\"filterHTML\").innerHTML = filterHTML;\n })\n}", "function renderProducts(){\n\tif(isLoading){ //Show loading text\n\t\tvar html = `<tr><td colspan=\"5\" class=\"text-center\">\n\t\t\t<div class=\"spinner-border\" role=\"status\">\n\t\t\t <span class=\"sr-only\">Loading...</span>\n\t\t\t</div>\n\t\t</td></tr>`;\n\t} else{\n\t\tvar html = ``;\n\t\tfor(var i=0;i<products.length;i++){\n\t\t\t//If have something to filter\n\t\t\tif(filter != \"\"){\n\t\t\t\tif(products[i].name.toLowerCase().includes(filter) || products[i].description.toLowerCase().includes(filter)){}\n\t\t\t\telse{\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\thtml += `<tr>\n\t\t\t\t<td>${products[i].name}</td>\n\t\t\t\t<td>${products[i].description}</td>\n\t\t\t\t<td>$${products[i].price}</td>\n\t\t\t\t<td><img class=\"img-fluid\" src=\"${products[i].picture}\" alt=\"${products[i].name}\" /></td>\n\t\t\t\t<td>\n\t\t\t\t\t<button class=\"btn btn-primary\" data-edit=\"${products[i].id}\">Edit</button>\n\t\t\t\t\t<button class=\"btn btn-danger\" data-delete=\"${products[i].id}\">Delete</button>\n\t\t\t\t</td>\n\t\t\t</tr>`;\n\t\t}\n\t}\n\t\n\t$(\"#tableBody\").html(html);\n}", "function appendTable(dataToRender){\n tabelBody.html(\"\")\n dataToRender.forEach(ufo => {\n var newRow = tabelBody.append(\"tr\");\n Object.entries(ufo).forEach(([key,value]) => {\n var cell = newRow.append(\"td\");\n cell.text(value)\n });\n });\n}", "function filterTable() {\n // First, clear out any existing ufo_table body data by using the selectAll commect on all rows followed by the .remove() method. This ensures that the table is rendered fresh each time the filter is applied\n ufo_table.selectAll('tr').remove();\n\n // Now check whether any input was provided in the filter search form. If no input exists (the value property of the form is an empty string), then display the entire table of UFO sightings.\n if (dateTimeEntry.property('value') === '') {\n // tableData is a list of objects, each object being a specific UFO sighting consisting of key:value pairs. Begin by using .forEach to iterate over each object\n tableData.forEach((ufoSighting) => {\n // For every object in the table, append a new row to the DOM table\n var row = ufo_table.append('tr');\n // Now use the forEach function to iterate though each key:value pair of each object. For every pair, append a new table data item (td), then populate the cell with the value.\n Object.entries(ufoSighting).forEach(([key, value]) => {\n var cell = row.append('td');\n cell.text(value);\n }); \n });\n } else {\n // If an input was provided, then display the table based on the date provided\n tableData.forEach((ufoSighting) => {\n // For every object in the table with a dateTime value that matches the value of the dateTime entry form date input, append a new row to the DOM table\n if (ufoSighting.datetime === dateTimeEntry.property('value')) {\n var row = ufo_table.append('tr');\n // Now use the forEach function to iterate though each key:value pair of each object. For every pair, append a new table data item (td), then populate the cell with the value.\n Object.entries(ufoSighting).forEach(([key, value]) => {\n var cell = row.append('td');\n cell.text(value);\n }); \n };\n });\n } \n}", "function filterTable() {\n\n // Set the filteredData to the tableData\n filteredData = tableData\nconsole.log(filteredData, 'line 78')\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(row => row[key] === value);\n })\n\n // Finally, rebuild the table using the filtered Data\n buildTable(filteredData);\n}", "function filterData() {\n \n // Prevent the page from refreshing\n d3.event.preventDefault();\n \n // Get filter input\n var dateFilter = d3.select(\"#datetime\").property(\"value\");\n\n // Filter tableData for selection\n var filteredData = tableData;\n if (dateFilter !== \"\") {\n var filteredData = filteredData.filter(sighting => sighting.datetime === dateFilter);\n };\n\n // remove existing table data\n d3.select(\"tbody\").remove();\n\n // add table body back\n table.append(\"tbody\");\n\n // reload table\n loadTable(filteredData);\n}", "function buildTable(data) {\r\n // first we want to clear table (i.e. remove filters) each time the function is called \r\n // tbody.html references the table from the html file, then (\"\") is a blank string \r\n tbody.html(\"\");\r\n\r\n //forEach function takes a function and applies it to each item in the loop\r\n //we are passing 'data' (our data.js file) as the item to loop through\r\n data.forEach((dataRow) => {\r\n // in our loop, we will append the item of the loop into the <tbody> html tag and add a table row (tr)\r\n let row = tbody.append(\"tr\");\r\n // Object.values tells JavaScript to reference one object from the array of ufo sightings in data\r\n // datarow means we want those objects to go into datarow \r\n // forEach((val) specifies that we want one object per row \r\n Object.values(dataRow).forEach((val) => {\r\n // then append the object into the table using the table data <td> tag\r\n let cell = row.append(\"td\");\r\n // extract just the text from the object, so that it is stored in the table as text \r\n cell.text(val);\r\n // this is essentially looping through each value in the table row from our data file\r\n // then storing/appending it to the table\r\n });\r\n });\r\n }", "function displayData(filteredData){\n //console.log('display results');\n d3.selectAll(\"tbody>tr\").remove();\n //d3.event.preventDefault();\n\n filteredData.forEach(element => {\n //console.log(element);\n var row = tbody.append(\"tr\");\n \n Object.entries(element).forEach(function([key,value]){\n //console.log({key, value});\n var cell = row.append(\"td\").text(value);\n });\n }\n );\n\n}", "function renderSalesTable() {\n\n renderTableHead();\n renderTableBody();\n renderTableFoot();\n\n}", "function renderTable() {\n $tbody.innerHTML = \"\";\n\n var endingIndex = startingIndex + resultsPerPage;\n // Get a section of the addressData array to render\n var sightingsSubset = sightingsData.slice(startingIndex, endingIndex);\n\n\n for (var i = 0; i < sightingsSubset.length; i++) {\n //console.log(sightingsData.length);\n // Get get the current sighting object and its fields\n var sighting = sightingsSubset[i];\n var fields = Object.keys(sighting);\n // Create a new row in the tbody, set the index to be i + startingIndex\n var $row = $tbody.insertRow(i);\n for (var j = 0; j < fields.length; j++) {\n // For every field in the sighting object, create a new cell at set its inner text to be the current value at the current sighting's field\n var field = fields[j];\n var $cell = $row.insertCell(j);\n $cell.innerText = sighting[field];\n }\n }\n}", "function renderTable() {\n $tbody.innerHTML = \"\";\n for (var i = 0; i < sightingData.length; i++) { // Loop through the data object items\n var sighting = sightingData[i]; // Get each data item object\n var fields = Object.keys(sighting); // Get the fields in each data item\n var $row = $tbody.insertRow(i); // Insert a row in the table object\n for (var j = 0; j < fields.length; j++) { // Add a cell for each field in the data item object and populate its content\n var field = fields[j];\n var $cell = $row.insertCell(j);\n $cell.innerText = sighting[field];\n }\n }\n}", "function renderTableData (data) {\n // JAX-RS serializes an empty list as null, and a 'collection of one' as an object (not an 'array of one')\n var list = data == null ? [] : (data.orders instanceof Array ? data.orders : [data.orders]);\n var table = $ ('#orderTbl').DataTable ();\n // var shippingTable = $('#shippingTbl').DataTable();\n var deliveredTable = $ ('#deliveredTbl').DataTable ();\n var orderDetailsTable = $ ('#orderDetailsTbl').DataTable ();\n\n table.clear ().draw ();\n deliveredTable.clear ().draw ();\n var extraButton = \"<span style='display:inline-flex !important;'><a href='' class='order-edit glyphicon glyphicon-pencil'></a> <a href='' class='order-delete glyphicon glyphicon-trash'></a> <a href='Javascript:void(0);' id='printOrder' class='glyphicon glyphicon-print'></a> </span>\";\n // var weight = order.weight;\n $.each (list, function (index, order) {\n var weight = order.weight;\n var amount = order.total;\n /* this will validate if value is not:\n null\n undefined\n NaN\n empty string (\"\")\n false\n 0\n */\n if (!weight)\n weight = 0;\n if (!amount)\n amount = 0;\n // divide data to 2 parts: ordered/delivered (0/1)\n if (order.status == 0)\n table.row.add ([order.id, order.date, order.s_name, order.s_phone, order.s_address, order.r_name, order.r_phone, order.r_address, weight, amount]).draw ();\n else if (order.status == 1)\n deliveredTable.row.add ([order.id, order.date, order.s_name, order.s_phone, order.s_address, order.r_name, order.r_phone, order.r_address, weight, amount]).draw ();\n //reserve first column for checkbox with order id as well\n console.log (\"fill data for order details table of shipping\");\n orderDetailsTable.row.add ([order.id, order.id, order.date, order.s_name, order.r_name, weight, amount]).draw ();\n });\n}", "function renderTable(data) {\n var tHead = \"\";\n var tBody = \"\";\n var header = true;\n\n // adds data to array\n if (!Array.isArray(data)) {\n var dataTmp = data;\n data = [dataTmp];\n }\n\n // iterate through json objects in array\n for (var index in data) {\n tBody += \"<tr>\";\n // iterate through values in json object\n for (var key in data[index]) {\n // adds table header from key values\n if (header) tHead += \"<th>\" + key + \"</th>\";\n tBody += \"<td id = '\" + index + \"'>\" + data[index][key] + \"</td>\";\n }\n // stops adding table headers\n header = false;\n tBody += \"</tr>\";\n }\n tableHead.innerHTML = tHead;\n tableBody.innerHTML = tBody;\n}", "function handleChange() {\n tbody.html(\"\");\n // Select input value\n var dateInputText = datetime.property(\"value\").toLowerCase();\n var cityInputText = city.property(\"value\").toLowerCase();\n var stateInputText = state.property(\"value\").toLowerCase();\n var countryInputText = country.property(\"value\").toLowerCase();\n var shapeInputText = shape.property(\"value\").toLowerCase();\n\n console.log(dateInputText);\n console.log(cityInputText);\n console.log(stateInputText);\n console.log(countryInputText);\n console.log(shapeInputText);\n\n filter_table = tableData\n // Filtered data from tableData\n if(dateInputText !== \"\"){\n var filter_table = filter_table.filter(filter_table => filter_table.datetime === dateInputText);\n } \n if(cityInputText !== \"\"){\n var filter_table = filter_table.filter(filter_table => filter_table.city === cityInputText);\n }\n if(stateInputText !== \"\"){\n var filter_table = filter_table.filter(filter_table => filter_table.state === stateInputText);\n }\n if(countryInputText !== \"\"){\n var filter_table = filter_table.filter(filter_table => filter_table.country === countryInputText);\n }\n if(shapeInputText !== \"\"){\n var filter_table = filter_table.filter(filter_table => filter_table.shape === shapeInputText);\n }\n\n console.log(filter_table.length);\n \n if (filter_table.length !== 0){\n table(filter_table);\n } else{\n alert(\"Results Not Found\");\n table(tableData);\n }\n}", "function renderTable() {\n $('.request-item').remove();\n\n requests.forEach(function writeToTable(request) {\n $('#request-table').append(request.rowHtml);\n })\n}", "function filterTable() {\n var filteredData = tableData\n // console.log(dateTimeEntry.property('value'))\n if (dateTimeEntry.property('value')) {\n var filteredData = filteredData.filter(ufoSighting => ufoSighting.datetime === dateTimeEntry.property('value'));\n }\n if (cityEntry.property('value')) {\n var filteredData = filteredData.filter(ufoSighting => ufoSighting.city === cityEntry.property('value').toLowerCase());\n }\n if (stateEntry.property('value')) {\n var filteredData = filteredData.filter(ufoSighting => ufoSighting.state === stateEntry.property('value').toLowerCase());\n }\n if (shapeEntry.property('value')) {\n var filteredData = filteredData.filter(ufoSighting => ufoSighting.shape === shapeEntry.property('value').toLowerCase());\n }\n // Filter on the country by determining which country has been selected by the country button. If neither 'us' nor 'ca' is selected, this filter will not run.\n if (country_button.text() === 'United States') {\n var filteredData = filteredData.filter(ufoSighting => ufoSighting.country === 'us')\n } else if (country_button.text() === 'Canada') {\n var filteredData = filteredData.filter(ufoSighting => ufoSighting.country === 'ca')\n }\n\n // Clear the DOM table from the previous state\n ufo_table.selectAll('tr').remove();\n\n // Clear the noData div \n d3.selectAll('#nodata').text('')\n\n // If the filteredData has a length of zero, print a message indicating as such\n if (filteredData.length === 0) {\n d3.selectAll('#nodata').text('Sorry, your filter returned no results. Please try again.')\n }\n // Repopulate the DOM table with the filtered data.\n filteredData.forEach((ufoSighting) => {\n\n var row = ufo_table.append('tr');\n Object.entries(ufoSighting).forEach(([key, value]) => {\n var cell = row.append('td');\n cell.text(value);\n }); \n }); \n}", "render() {\n if (!this.mounted) {\n return;\n }\n console.log(\"rendering table\");\n this.element.innerHTML = \"\";\n\n const c = document.createTextNode(JSON.stringify(this.data, null, 4));\n const table = el(\"table\", {});\n const thead = el(\"thead\", {});\n const th = el(\"th\");\n const tbody = el(\"tbody\", {});\n const tr = el(\"tr\", {});\n const td = el(\"td\", {});\n const tdStat = el(\"td\");\n const { color, ...colNames } = this.data[0];\n\n const content = table([\n thead(\n tr(\n Object.keys(colNames).map(name =>\n th(\n {\n class: [\n \"header__name\",\n this.sortKey === name ? \"sorting\" : \"\"\n ].join(\" \"),\n sort: name\n },\n name.toUpperCase()\n )\n )\n )\n ),\n tbody(\n this.data.map(({ color, ...rest }) =>\n tr([\n ...Object.values(rest).map(td),\n tdStat({ style: `color: ${color}` }, \"◼\")\n ])\n )\n )\n ]);\n\n content.addEventListener(\"click\", this.handleClickSort);\n\n this.element.appendChild(content);\n }", "function table(data){\n tbody.html(\"\");\n\n\t//append the rows(tr) and cells(td) for returned values\n data.forEach((dataRow) => {\n let row = tbody.append(\"tr\");\n \n Object.values(dataRow).forEach((val) => {\n let cell = row.append(\"td\");\n cell.text(val);\n });\n })\n}", "function RenderTableRows(data) {\t\t \n\t\t var id = settings.id;\n\t\t $('#' + id).find('tbody').empty();\n\n\t\t var totalRows = 0;\n if (data != null && data.length > 0) {\n\n //ShowBlank - insert a blank option at beginning of list\n if (data[0].Value != 0 && settings.showBlank === true) {\n\t\t data.unshift({Value: 0, Text: \"\"});\n\t\t }\n\n\t\t $(data).each(function () {\n\t\t var row = tbody.insertRow();\n\t\t $(row).empty();\n\n\t\t var cell = row.insertCell();\n\t\t $(cell).css({'text-align':'center', 'width':'40px'});\n\n\t\t var btn = document.createElement('button');\n\t\t btn.setAttribute('data-name', this.Text);\n\t\t btn.setAttribute('data-id', this.Value);\n\n\t\t var preSelect = false;\n\t\t for (var r = 0; r < btnList.length; r++) {\n\t\t if (btnList[r].id == this.Value)\n\t\t preSelect = true;\n\t\t }\n\n\t\t if (preSelect)\n\t\t $(btn).addClass('btn btn-xs btn-success');\n\t\t else\n\t\t $(btn).addClass('btn btn-xs btn-primary');\n\n\t\t if (settings.data[0].Group != null)\n\t\t $(btn).addClass(this.Group.Name);\n\n\n\t\t if (settings.buttonTemplate == null) {\n\t\t if (preSelect)\n\t\t btn.innerHTML = '<i class=\"glyphicon glyphicon-check\"></i>';\n\t\t else\n\t\t btn.innerHTML = '<i class=\"glyphicon glyphicon-unchecked\"></i>';\n\t\t } else {\n\t\t btn.innerHTML = settings.buttonTemplate;\n\t\t }\n\n\t\t $(btn).click(function () {\n\t\t switch (TargetType.toLowerCase()) {\n\t\t case \"input\":\n\t\t $('#' + TargetId).val($(this).data('name'));\n\t\t $('#' + TargetId).attr('data-name', $(this).data('name'));\n\t\t $('#' + TargetId).attr('data-id', $(this).data('id'));\n\t\t break;\n\n\t\t case \"div\":\n\t\t $('#' + TargetId).append('<button type=\"button\" class=\"btn btn-xs btn-danger RemoveListItem\" style=\"margin:2px;\" data-id=\"' + $(this).data('id') + '\"><span class=\"glyphicon glyphicon-remove\"></span> ' + $(this).data('name') + '</button>');\n\t\t //settings.multiSelect = true;\n\t\t break;\n\t\t }\n\n\t\t if (!settings.multiSelect) {\n\t\t closeMe();\n\t\t } else {\n\t\t //toggle the button\n\t\t if ($(this).hasClass(\"btn-primary\")) {\n\t\t $(this).removeClass(\"btn-primary\").addClass(\"btn-success\");\n\t\t $(this).find('i').removeClass('glyphicon-unchecked').addClass('glyphicon-check');\n\t\t } else {\n\t\t $(this).removeClass(\"btn-success\").addClass(\"btn-primary\");\n\t\t $(this).find('i').removeClass('glyphicon-check').addClass('glyphicon-unchecked');\n\n\t\t //find matching button id and remove it\n\t\t $('.RemoveListItem').each(function () {\n\t\t if ($(btn).data('id') == $(this).data('id')) {\n\t\t $(this).remove();\n\t\t }\n\t\t });\n\n\t\t }\n\n\t\t }\n\n //Do any callback once item is selected\n\t\t if (typeof settings.onSelected == 'function') {\n\t\t settings.onSelected.call();\n\t\t }\n\n\t\t });\n\n\t\t cell.appendChild(btn);\n\n cell = row.insertCell(); \n\t\t $(cell).attr('data-toggle', 'picker-tooltip').attr('title', this.Title);\n\n if (this.Text.length > 30)\n if (!this.Disabled)\n cell.innerText = this.Text.substring(0, 30) + '...';\n else {\n $(cell).css({\"background-color\":\"mistyRose\",\"cursor\":\"not-allowed\"});\n cell.innerHTML = '<span style=\"color:red; font-decoration:line-through; font-style:italic;\" >' + this.Text.substring(0, 30) + '</span>';\n }\n \n else\n if (!this.Disabled)\n cell.innerText = this.Text;\n else {\n $(cell).css({ \"background-color\": \"mistyRose\", \"cursor\": \"not-allowed\" });\n cell.innerHTML = '<span style=\"color:red; font-decoration:line-through; font-style:italic;\" >' + this.Text + '</span>';\n }\n\n\t\t totalRows++;\n\t\t });\n\t\t }\n\t\t // Display message if results are empty\n\t\t if (data.length == 0) {\n\t\t var cell = tbody.insertRow()//.insertCell();\n\t\t cell.innerHTML = '<td colspan=\"2\">No records.</td>';\n\t\t }\n\n\t\t //add overflow when over 15 records\n\t\t if (totalRows > 15) {\n\t\t $(divOverflow).css('height', '500px');\n\t\t $(divOverflow).css('overflow-x', 'auto');\n\t\t }\n\n\t\t //Init Bootstrap Tooltips\n\t\t setTooltips();\n\n\t\t }", "renderTable(asteroids, table, hidden, len = 1) {\n\t\thidden.classList.remove('d-none');\n\t\ttable.innerHTML += `<thead class=\"thead-light\">\n\t\t\t\t<tr>\n\t\t\t\t\t<th scope=\"col\">Datum</th>\n\t\t\t\t\t<th scope=\"col\">Ime</th>\n\t\t\t\t\t<th scope=\"col\">Brzina kretanja(km/h)</th>\n\t\t\t\t\t<th scope=\"col\">Min. Precnik(m)</th>\n\t\t\t\t\t<th scope=\"col\">Max. Precnik(m)</th>\n\t\t\t\t</tr>\n\t\t\t</thead>`\n\t\tfor(let i = (len - 1) * 10; i < len * 10; i++) {\n\t\t\tif(i === asteroids.length) break;\n\t\t\ttable.innerHTML += `<tr>\n\t\t\t\t<td>${asteroids[i].close_approach_data[0].close_approach_date}</td>\n\t\t\t\t<td>${asteroids[i].name}</td>\n\t\t\t\t<td>${asteroids[i].close_approach_data[0].relative_velocity.kilometers_per_hour}</td>\n\t\t\t\t<td>${asteroids[i].estimated_diameter.meters.estimated_diameter_min}</td>\n\t\t\t\t<td>${asteroids[i].estimated_diameter.meters.estimated_diameter_max}</td>\n\t\t\t</tr>`;\n\t\t}\n\t}", "renderTable () {\n const table = this.state.table\n const data = api.get.data(table)\n const schema = api.get.schema(table)\n const searchPattern = this.state.searchPattern\n\n return <Table data={data} schema={schema} searchPattern={searchPattern} />\n }", "function render(data) {\r\n\t\t\t\t\t\t$('#slc_Marca').children().remove();\r\n\t\t\t\t\t\t$('#slc_TipoVeiculo').children().remove();\r\n\t\t\t\t\t\tvar tabela = $('#tableDiv').append(\r\n\t\t\t\t\t\t\t\t$('<table></table>').attr(\"id\", \"tabela\"));\r\n\t\t\t\t\t\tvar tHead = \"<thead id='tableHead'></thead>\";\r\n\t\t\t\t\t\t$('#tabela').append(tHead);\r\n\t\t\t\t\t\tvar rowH = \"<tr> \" + \"<th>ID</th>\" + \"<th>Marca</th>\"\r\n\t\t\t\t\t\t\t\t+ \"<th>Tipo Veiculo</th>\" + \"<th>Modelo</th>\"\r\n\t\t\t\t\t\t\t\t+ \"<th>Status</th>\" + \"<th>Actions</th>\"\r\n\t\t\t\t\t\t\t\t+ \"</tr>\";\r\n\t\t\t\t\t\t$('#tableHead').append(rowH);\r\n\r\n\t\t\t\t\t\t$('#tabela').append(\r\n\t\t\t\t\t\t\t\t$('<tbody></tbody>').attr(\"id\", \"tabelaBody\"));\r\n\r\n\t\t\t\t\t\t$.each(data, function(index, value) {\r\n\r\n\t\t\t\t\t\t\t\t\t\t\tvar td = $(\"<tr id= 'row\" + index\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t+ \"'>\" + \"</tr>\");\r\n\r\n\t\t\t\t\t\t\t\t\t\t\tvar row1 = $(\"<td>\"\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t+ value.idModelo + \"</td>\");\r\n\r\n\t\t\t\t\t\t\t\t\t\t\tvar row2 = $(\"<td>\"\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t+ value.idMarca.descMarca\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t+ \"</td>\");\r\n\r\n\t\t\t\t\t\t\t\t\t\t\tvar row3 = $(\"<td>\"\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t+ value.idTipoV.descTipoV\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t+ \"</td>\");\r\n\r\n\t\t\t\t\t\t\t\t\t\t\tvar row4 = $(\"<td>\"\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t+ value.descModelo\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t+ \"</td>\");\r\n\r\n\t\t\t\t\t\t\t\t\t\t\tvar row5 = $(\"<td>\"\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t+ value.statusModelo\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t+ \"</td>\");\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t// Efetua A Funcao Ao Clicar No\r\n\t\t\t\t\t\t\t\t\t\t\t// Botao\r\n\t\t\t\t\t\t\t\t\t\t\t// btn-update\r\n\t\t\t\t\t\t\t\t\t\t\tvar buttonUpdate = $(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t'<button>Modificar</button>')\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t.attr(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"id\",\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"btn-update-\"\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t+ index)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t.click({\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tp1 : this\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t}, setInputData);\r\n\r\n\t\t\t\t\t\t\t\t\t\t\tvar buttonRemove = $(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t'<button>Remover</button>')\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t.attr(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"id\",\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"btn-remove-\"\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t+ index)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t.click({\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tp1 : this\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t}, callRemoveServlet);\r\n\r\n\t\t\t\t\t\t\t\t\t\t\tvar row6 = $(\"<td></td>\");\r\n\t\t\t\t\t\t\t\t\t\t\trow6.append(buttonUpdate);\r\n\t\t\t\t\t\t\t\t\t\t\trow6.append(buttonRemove);\r\n\r\n\t\t\t\t\t\t\t\t\t\t\ttd.append(row1);\r\n\t\t\t\t\t\t\t\t\t\t\ttd.append(row2);\r\n\t\t\t\t\t\t\t\t\t\t\ttd.append(row3);\r\n\t\t\t\t\t\t\t\t\t\t\ttd.append(row4);\r\n\t\t\t\t\t\t\t\t\t\t\ttd.append(row5);\r\n\t\t\t\t\t\t\t\t\t\t\ttd.append(row6);\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t$('#tabela tbody').append(td);\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t$('#set')\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t.append('</tbody></table>');\r\n\r\n\t\t\t\t\t\t\t\t\t\t})\r\n\r\n\t\t\t\t\t\t// Preenche O Select Marca\r\n\t\t\t\t\t\tgetMarcas();\r\n\r\n\t\t\t\t\t\t// Preenche O Select TipoVeiculo\r\n\t\t\t\t\t\tgetTiposVeiculos();\r\n\r\n\t\t\t\t\t}", "function renderTable() {\n $tbody.innerHTML = \"\";\n for (var i = 0; i < ufoSightings.length; i++) {\n // Get get the current sightings object and its fields\n var sightings = ufoSightings[i];\n var fields = Object.keys(sightings);\n // Create a new row in the tbody, set the index to be i + startingIndex\n var $row = $tbody.insertRow(i);\n for (var j = 0; j < fields.length; j++) {\n // For every field in the sightings object, create a new cell at set its inner text to be the current value at the current sightings field\n var field = fields[j];\n var $cell = $row.insertCell(j);\n $cell.innerText = sightings[field];\n }\n }\n}", "function renderData(data) {\n let dataTable = document.getElementById(\"dataTable\");\n dataTable.innerHTML = \"\";\n\n if (data.length === 0) {\n //No data found.\n renderNoDataFoundError();\n } else {\n\t\t//No Errors, Data found.\n removeErrors();\n for (let i = 0; i < data.length; i++) {\n tableAddElement(data, i, dataTable);\n }\n }\n}", "function renderAllEmployeeData(data) {\n let renderAllHTML = `<table><thead><tr><th>First Name</th><th>Last Name</th><th>Email</th><th>Birthday</th>\n <th>Hire Date</th></thead><tbody>`;\n data.forEach(function(data) {\n const tableRow = `<tr>\n <th>${data.first_name}</th>\n <th>${data.last_name}</th>\n <th>${data.email}</th>\n <th>${moment(data.birthday).format(\"MMMM Do YYYY\")}</th>\n <th>${moment(data.hire_date).format(\"MMMM Do YYYY\")}</th>`;\n\n renderAllHTML += tableRow;\n });\n\n renderAllHTML += `</tbody></table>`;\n $(\"#search-results\").append(renderAllHTML);\n }", "render(table) {\n console.log('Applying 3rd partys better sort.');\n }", "function filterTable() {\n d3.event.preventDefault();\n\n tbody.html(\"\");\n\n // Select the input element and get the raw HTML node\n let inputElement = d3.select(\"#datetime\"),\n // Get the value property of the input element\n inputValue = inputElement.property(\"value\");\n // Use the form input to filter the data by blood type\n let filterData = tableData.filter(ufo => ufo.datetime === inputValue);\n\n filterData.forEach((ufo) => {\n let row = tbody.append(\"tr\");\n Object.values(ufo).forEach(value => {\n let cell = row.append(\"td\");\n cell.text(value);\n });\n });\n\n}", "function filterTable(type) {\n var usersData = '';\n if(type == 'resaler') {\n $('#platform-header').hide();\n }\n else {\n $('#platform-header').show();\n }\n var usersData = '';\n for( var i = 0; i < USERS.length; i++) {\n if(type == 'resaler') {\n if(!USERS[i].hasOwnProperty(\"Platform\")) {\n usersData += `<tr><td>${USERS[i][\"First Name\"]}</td>`;\n usersData += `<td>${USERS[i][\"Last Name\"]}</td>`;\n usersData += `<td>${USERS[i][\"Phone\"]}</td>`;\n usersData += `<td>${USERS[i][\"Email\"]}</td>`;\n usersData += `<td class=\"text-right\"><a class=\"edit-user btn btn-simple btn-warning btn-icon edit\" data-id=${USERS[i][\"id\"]} href=\"#\" data-toggle=\"modal\" data-target=\"#edit-user-modal\">\n <i class=\"material-icons\">dvr</i></a>\n <a href=\"#\" class=\"btn btn-simple btn-danger btn-icon remove\" data-id=${USERS[i][\"id\"]}>\n <i class=\"material-icons\">close</i></a></td></tr>`;\n }\n }\n else if (type == 'white-label'){\n if(USERS[i].hasOwnProperty(\"Minimum Fee\")){\n usersData += `<tr><td>${USERS[i][\"Platform\"]}`;\n usersData += `<td>${USERS[i][\"First Name\"]}</td>`;\n usersData += `<td>${USERS[i][\"Last Name\"]}</td>`;\n usersData += `<td>${USERS[i][\"Phone\"]}</td>`;\n usersData += `<td>${USERS[i][\"Email\"]}</td>`;\n usersData += `<td class=\"text-right\"><a class=\"edit-user btn btn-simple btn-warning btn-icon edit\" data-id=${USERS[i][\"id\"]} href=\"#\" data-toggle=\"modal\" data-target=\"#edit-user-modal\">\n <i class=\"material-icons\">dvr</i></a>\n <a href=\"#\" class=\"btn btn-simple btn-danger btn-icon remove\" data-id=${USERS[i][\"id\"]}>\n <i class=\"material-icons\">close</i></a></td></tr>`;\n }\n }\n else if( type == 'franchise') {\n if(USERS[i].hasOwnProperty(\"Platform\") && !USERS[i].hasOwnProperty(\"Minimum Fee\")) {\n usersData += `<tr><td>${USERS[i][\"Platform\"]}`;\n usersData += `<td>${USERS[i][\"First Name\"]}</td>`;\n usersData += `<td>${USERS[i][\"Last Name\"]}</td>`;\n usersData += `<td>${USERS[i][\"Phone\"]}</td>`;\n usersData += `<td>${USERS[i][\"Email\"]}</td>`;\n usersData += `<td class=\"text-right\"><a class=\"edit-user btn btn-simple btn-warning btn-icon edit\" data-id=${USERS[i][\"id\"]} href=\"#\" data-toggle=\"modal\" data-target=\"#edit-user-modal\">\n <i class=\"material-icons\">dvr</i></a>\n <a href=\"#\" class=\"btn btn-simple btn-danger btn-icon remove\" data-id=${USERS[i][\"id\"]}>\n <i class=\"material-icons\">close</i></a></td></tr>`;\n }\n }\n }\n $('#user-data').html(usersData);\n initTable();\n}", "function Filter_TableRows() { // PR2019-06-09 PR2020-08-31 PR2022-03-03\n //console.log( \"===== Filter_TableRows=== \");\n //console.log( \"filter_dict\", filter_dict);\n\n // function filters by inactive and substring of fields\n // - iterates through cells of tblRow\n // - skips filter of new row (new row is always visible)\n // - if filter_name is not null:\n // - checks tblRow.cells[i].children[0], gets value, in case of select element: data-value\n // - returns show_row = true when filter_name found in value\n // - if col_inactive has value >= 0 and hide_inactive = true:\n // - checks data-value of column 'inactive'.\n // - hides row if inactive = true\n\n const data_inactive_field = null; // \"data-inactive\";\n for (let i = 0, tblRow, show_row; tblRow = tblBody_datatable.rows[i]; i++) {\n tblRow = tblBody_datatable.rows[i]\n show_row = t_Filter_TableRow_Extended(filter_dict, tblRow, data_inactive_field);\n add_or_remove_class(tblRow, cls_hide, !show_row);\n };\n }", "renderData() {\n\t\tconst { colItem } = styles;\n\t\tif (this.state.personelID) {\n\t\t\tif (this.props.registeredProductsByUser) {\n\t\t\t\treturn this.props.registeredProductsByUser.map((item, index) => {\n\t\t\t\t\tconsole.log(item);\n\t\t\t\t\treturn (\n\t\t\t\t\t\t<tr key={index}>\n\t\t\t\t\t\t\t<td style={colItem}>{item.personelID}</td>\n\t\t\t\t\t\t\t<td style={colItem}>{item.urunID}</td>\n\t\t\t\t\t\t\t<td style={colItem}>{item.urunAdi}</td>\n\t\t\t\t\t\t\t<td style={colItem}>{item.kategoriAdi}</td>\n\t\t\t\t\t\t\t<td style={colItem}>{item.zimmetTarihi}</td>\n\t\t\t\t\t\t\t<td style={colItem}>{item.zimmetKaldirmaTarihi ? item.zimmetKaldirmaTarihi : '-'}</td>\n\t\t\t\t\t\t\t<td style={colItem}>{item.Durum}</td>\n\t\t\t\t\t\t\t<td style={colItem}>{item.Sure}</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t);\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t}", "renderObjectsTable_() {\n let tableName = this.objectsTable_.append('tr')\n .attr('class', 'memory-table-name');\n\n tableName.append('td')\n .text('Objects in memory');\n tableName.append('td')\n .text('');\n\n let tableHeader = this.objectsTable_.append('tr')\n .attr('class', 'memory-table-header');\n\n tableHeader.append('td')\n .text('Objects');\n tableHeader.append('td')\n .text('Count');\n\n let countRows = this.objectsTable_.selectAll('.memory-table-row')\n .data(this.data_.objectsCount)\n .enter()\n .append('tr')\n .attr('class', 'memory-table-row');\n\n countRows.append('td')\n .text((d) => d[0]);\n countRows.append('td')\n .text((d) => d[1]);\n }", "function callTableSumGenerate(filteredData) {\n var i = 1;\n $.each(filteredData, function(name, ob) {\n var html = '';\n html += '<h3>'+name+'</h3>';\n html += '<table id=\"table-sum\" class=\"table table-bordered table-sum table-'+i+'\" data-name=\"'+name+'\">';\n html += '<tr><td><strong>Name</strong></td>'\n $.each(ob, function(key, value) {\n html+= '<td><strong>'+value[0].toString()+'</strong></td>';\n });\n html += '</tr>';\n\n html+= '<tr>';\n html+= '<td>'+name+'</td>';\n $.each(ob, function(key, value) {\n html+= '<td>'+value[1].toString()+'</td>';\n });\n html += '</tr>';\n\n html += '</table>';\n html += '<h4>Sum : '+getSumForTableData(ob)+'</h4>';\n $('#jumbotron').append('<div id=\"div-table-sum\">' + html + '</div>');\n\n i++;\n });\n \n }", "function renderTable() {\n clearTable();\n sortInfo();\n info.filter(rowInfo => (showNoPlaybacks || rowInfo.mediaPlaybacks > 0))\n .forEach(rowInfo => engagementTableBody.appendChild(createRow(rowInfo)));\n}", "function runFilter() {\n d3.event.preventDefault();\n var inputField = d3.select(\"#datetime\");\n var inputValue = inputField.property(\"value\");\n var filterByDate = tableData.filter(rowData => rowData.datetime === inputValue);\n tbody.html(\"\")\n filterByDate.forEach(sighting => {\n var row = tbody.append(\"tr\");\n Object.values(sighting).forEach(value => {\n row.append(\"td\").text(value);\n });\n });\n}", "renderPatentsTable() {\n // TODO: hide patents with only licence 0 ?\n const patentsToDisplay = this.state.patents\n .filter(p => !p.deleted && p.maxLicence > 0)\n .sort((p1, p2) => p1.name < p2.name ? -1 : 1);\n if (patentsToDisplay.length > 0) {\n const table = patentsToDisplay.map(patent => this.getPatentRow(patent));\n let header = (\n <tr>\n <th>File Name</th>\n <th>Owner</th>\n <th>Submission Date</th>\n <th>Number of Ratings</th>\n <th>Average Rating</th>\n </tr>\n );\n return (\n <Table striped hover responsive>\n <thead>{header}</thead>\n <tbody>{table}</tbody>\n </Table>\n );\n } else {\n return <div className='not-found'><h3>There are no deposited files on this Network</h3></div>\n }\n }", "function Table({ columns, data }) {\n console.log('data on FormList', data)\n const filterTypes = React.useMemo(\n () => ({\n text: (rows, id, filterValue) => {\n return rows.filter(row => {\n const rowValue = row.values[id]\n return rowValue !== undefined\n ? String(rowValue)\n .toLowerCase()\n .startsWith(String(filterValue).toLowerCase())\n : true\n })\n },\n }),\n []\n )\n\n const defaultColumn = React.useMemo(\n () => ({\n Filter: DefaultColumnFilter,\n }),\n []\n )\n\n const {\n getTableProps,\n getTableBodyProps,\n headerGroups,\n rows,\n prepareRow,\n state,\n visibleColumns,\n preGlobalFilteredRows,\n setGlobalFilter,\n } = useTable (\n {\n columns,\n data,\n defaultColumn,\n filterTypes,\n initialState: {\n sortBy: [{ id: 'incident_date', desc: true }]\n }\n },\n useFilters,\n useSortBy,\n )\n\n const firstPageRows = rows.slice(0,10)\n\n return (\n <>\n <table className=\"table\" {...getTableProps()}>\n <thead>\n {headerGroups.map(headerGroup => (\n <tr {...headerGroup.getHeaderGroupProps()}>\n {headerGroup.headers.map(column => (\n <th scope=\"col\" {...column.getHeaderProps(column.getSortByToggleProps())}>\n {column.render('Header')}\n {/* Render the columns filter UI */}\n <div>{column.canFilter ? column.render('Filter') : null}</div>\n <span>{column.isSorted ? (column.isSortedDesc ? '' : '') : ''}</span>\n </th>\n ))}\n </tr>\n ))}\n </thead>\n <tbody {...getTableBodyProps()}>\n {firstPageRows.map((row, i) => {\n prepareRow(row)\n return (\n <tr {...row.getRowProps()}>\n {row.cells.map(cell => {\n return <td {...cell.getCellProps()}>{cell.render('Cell')}</td>\n })}\n </tr>\n )\n })}\n </tbody>\n </table>\n <br />\n <div>Showing the first 20 results of {rows.length} rows</div>\n </>\n )\n}", "function renderTable(table, data){\n\t//clear current table\n\tremoveAllChildNodes(table);\n\tgenerateTable(table, data);\t\n\tlet headerRow = Object.keys(data[0]);\n\tgenerateTableHead(table, headerRow)\n\t//add event listeners to remove buttons\n\tlet removeBtns = document.querySelectorAll('button');\n\t//passs in row index to removeClimb (row = button->cell->row)\n\tremoveBtns.forEach(btn => btn.addEventListener('click', () => {removeClimb(btn.parentNode.parentNode.dataset.index)}));\n}", "function renderList_search(data) {\n\n show_search_results_table(); // function\n \n empty_search_table_html(); // function\n\t\n$.each(data.client, function(i,user){\nvar tblRow =\n\"<tr>\"\n+\"<td>\"+user.ItemID+\"</td>\"\n+\"<td>\"+user.Name+\"</td>\"\n+\"<td>\"+user.CAT+\"</td>\"\n//+\"<td>\"+user.www+\"</td>\"\n//+ \"<th><img border=\\\"0\\\" src=\\\"\"+ imgLink + commodores_variable.pic +\"\\\" alt=\\\"Pulpit rock\\\" width=\\\"304\\\" height=\\\"228\\\"><\\/th>\"\n + \"<td><a href=\\\"http:\\/\\/\"+user.www+\"\\\" target=\\\"_blank\\\">\"+user.www+\"<\\/a></td>\"\n+\"</tr>\" ;\n// Specific client data on table\n$(tblRow).appendTo(\".userdata_search tbody\");\n});\n\n$(\".userdata_search tbody tr td\").css({ border: '1px solid #ff4141' });\n \t\n}", "render() {\r\n return (\r\n <div>\r\n <h1 id=\"title\">Existing Data Dynamic Table</h1>\r\n <table id=\"students\">\r\n <tbody>\r\n <tr>{this.renderTableHeader()}</tr>\r\n {this.renderTableData()}\r\n </tbody>\r\n </table>\r\n </div>\r\n );\r\n }", "updateBody() {\n this.tableBody.innerHTML = '';\n\n if (!this.sortedData.length) {\n let row = this.buildRow('Nothing found', true);\n\n this.tableBody.appendChild(row);\n }\n\n else {\n for (let i = 0; i < this.sortedData.length; i++) {\n let row = this.buildRow(this.sortedData[i]);\n\n this.tableBody.appendChild(row);\n }\n }\n\n this.buildStatistics();\n }", "function renderStoreInTable() {\n\n var table = document.getElementById('store-table');\n var tableRow = document.createElement('tr');\n var tableCell = document.createElement('th');\n tableCell.textContent = this.location;\n tableRow.appendChild(tableCell);\n\n for (var i = 0; i < this.dailyHourSales.length; i++) {\n\n tableCell = document.createElement('td');\n tableCell.textContent = this.dailyHourSales[i];\n tableRow.appendChild(tableCell);\n }\n var tableCellTotal = document.createElement('th');\n tableCellTotal.textContent = this.dailyTotalSales;\n tableRow.appendChild(tableCellTotal);\n table.appendChild(tableRow);\n}", "function renderTable() {\n\n var table = $('<table>', { \"id\": \"group\", \"class\": \"mdl-data-table\"}).appendTo('#content');\n var thead = $('<thead>').appendTo(table);\n var tr = $('<tr>').appendTo(thead);\n var name = $('<th>').html(\"Имя\").appendTo(tr);\n var discipline = $('<th>').html(\"Предмет\").appendTo(tr);\n var grade = $('<th>').html(\"Оценка\").appendTo(tr);\n var edit = $('<th>').html(\"Изменить\").appendTo(tr);\n\n/*jquery plugin for work with tables*/\n $('#group').DataTable({\n \"ajax\": '../arrays.json',\n \"language\": {\n \"url\": 'tableLangRus.json'\n }\n });\n}", "render() {\n\n\t\t\tconst {data, filterText, selectBuilding} = this.props;\n\t\t\t\n\t\t\t\n\t\t\tconst buildingList = data\n\n\t\t\t\t.filter(directory => {\n\t\t\t\t\treturn directory.name.toLowerCase().indexOf(filterText.toLowerCase()) >= 0\n\t\t\t\t})\n\t\t\t\t.map(directory => {\n\n\t\t\t\t\treturn (\n\t\t\t\t\t\t\n\t\t\t\t\t\t<tr \n\t\t\t\t\t\t\tkey={directory.id}\n\t\t\t\t\t\t\tonClick={() => selectBuilding(directory.id)}\n\t\t\t\t\t\t>\n\t\t\t\t\t\t\t{directory.code != '' &&\n\t\t\t\t\t\t\t\t<td>{directory.code} </td>\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t{directory.name != '' &&\n\t\t\t\t\t\t\t\t<td> {directory.name} </td>\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t{directory.code != '' &&\n\t\t\t\t\t\t\t\t<div className=\"deleteButton\" onClick={(e) => this.props.deleteListing(directory.id)}>\n\t\t\t\t\t\t\t\t\tDelete\n\t\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t);\n\t\t\t\t});\n\n\t\t\treturn <div>{buildingList}</div>;\n\t\t}", "function filteredTable(entry) {\n var row = tbody.append(\"tr\");\n \n // extract data from the object and assign to variables\n var datetime = entry.datetime;\n var city = entry.city;\n var state = entry.state;\n var country = entry.country;\n var shape = entry.shape;\n var durationMinutes = entry.durationMinutes;\n var comments = entry.comments;\n \n // append one cell for each variable\n row.append(\"td\").text(datetime);\n row.append(\"td\").text(city);\n row.append(\"td\").text(state);\n row.append(\"td\").text(country);\n row.append(\"td\").text(shape);\n row.append(\"td\").text(durationMinutes);\n row.append(\"td\").text(comments);\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 renderTableData(data, totals) {\n // sort data\n data.sort(sortingFunction);\n\n // display data\n document.getElementById('tableBody').innerHTML = getDisplayData(data, totals);\n\n // set sorting arrows\n var el = document.getElementById(wrt.sortData.elId);\n if (el) {\n el.innerHTML = el.innerHTML + (wrt.sortData.dir === 'desc' ? '&#x25BC;' : '&#x25B2;');\n }\n\n // register table events\n registerTableEventHandlers();\n }", "function renderDataTable() {\n\n const worksheets = tableau.extensions.dashboardContent.dashboard.worksheets;\n \n // Unregister Event Listeners for old Worksheet, if exists.\n if (unregisterFilterEventListener != null) {\n unregisterFilterEventListener();\n }\n if (unregisterMarkSelectionEventListener != null) {\n unregisterMarkSelectionEventListener();\n }\n\n // We will try to read the worksheet from the settings, if this exists we will show\n // the configuration screen, otherwise we will clear the table and destroy the\n // reference.\n var sheetName = tableau.extensions.settings.get(\"worksheet\");\n if (sheetName == undefined || sheetName ==\"\" || sheetName == null) {\n $(\"#configure\").show();\n $(\"#datatable\").text(\"\");\n if( tableReference !== null) {\n tableReference.destroy();\n }\n // Exit the function if no worksheet name is present !!!\n return;\n } else {\n // If a worksheet is selected, then we hide the configuration screen.\n $(\"#configure\").hide();\n }\n\n // Use the worksheet name saved in the Settings to find and return\n // the worksheet object.\n var worksheet = worksheets.find(function (sheet) {\n return sheet.name === sheetName;\n });\n\n // Retrieve values the other two values from the settings dialogue window.\n var underlying = tableau.extensions.settings.get(\"underlying\");\n var max_no_records = tableau.extensions.settings.get(\"max_no_records\");\n\n // Add an event listener to the worksheet.\n unregisterFilterEventListener = worksheet.addEventListener(tableau.TableauEventType.FilterChanged, (filterEvent) => {\n renderDataTable();\n });\n unregisterMarkSelectionEventListener = worksheet.addEventListener(tableau.TableauEventType.MarkSelectionChanged, (markSelectionEvent) => {\n renderDataTable();\n });\n\n // If underlying is 1 then get Underlying, else get Summary.\n if (underlying == 1) {\n worksheet.getUnderlyingDataAsync({ maxRows: max_no_records }).then(function (underlying) {\n // We will loop through our column names from our settings and save these into an array\n // We will use this later in our datatable function.\n // https://tableau.github.io/extensions-api/docs/interfaces/datatable.html#columns\n var data = [];\n var column_names = tableau.extensions.settings.get(\"column_names\").split(\"|\");\n for (i = 0; i < column_names.length; i++) {\n data.push({ title: column_names[i] });\n }\n\n // We have created an array to match the underlying data source and then\n // looped through to populate our array with the value data set. We also added\n // logic to read from the column names and column order from our configiration.\n const worksheetData = underlying.data;\n var column_order = tableau.extensions.settings.get(\"column_order\").split(\"|\");\n var tableData = makeArray(underlying.columns.length,underlying.totalRowCount);\n for (var i = 0; i < tableData.length; i++) {\n for (var j = 0; j < tableData[i].length; j++) {\n // you can get teh value or formatted value\n // https://tableau.github.io/extensions-api/docs/interfaces/datavalue.html\n tableData[i][j] = worksheetData[i][column_order[j]-1].formattedValue;\n }\n }\n\n // Destroy the old table.\n if (tableReference !== null) {\n tableReference.destroy();\n $(\"#datatable\").text(\"\");\n }\n \n // Read the Settings and get the single string for UI settings.\n var tableClass = tableau.extensions.settings.get(\"table-classes\");\n $(\"#datatable\").attr('class', '')\n $(\"#datatable\").addClass(tableClass);\n\n // Read the Settings and create an array for the Buttons.\n var buttons = [];\n var clipboard = tableau.extensions.settings.get(\"export-clipboard\");\n if (clipboard == \"Y\") {\n buttons.push('copy');\n }\n var csv = tableau.extensions.settings.get(\"export-csv\");\n if (csv == \"Y\") {\n buttons.push('csv');\n }\n var excel = tableau.extensions.settings.get(\"export-excel\");\n if (excel == \"Y\") {\n buttons.push('excel');\n }\n var pdf = tableau.extensions.settings.get(\"export-pdf\");\n if (pdf == \"Y\") {\n buttons.push('pdf');\n }\n var print = tableau.extensions.settings.get(\"export-print\");\n if (print == \"Y\") {\n buttons.push('print');\n }\n\n // If there are 1 or more Export options ticked, then we will add the dom: 'Bfrtip'\n // Else leave this out.\n if (buttons.length > 0) {\n tableReference = $('#datatable').DataTable({\n dom: 'Bfrtip',\n data: tableData,\n columns: data,\n responsive: true,\n buttons: buttons\n });\n } else {\n tableReference = $('#datatable').DataTable({\n data: tableData,\n columns: data,\n responsive: true\n });\n }\n })\n } else {\n worksheet.getSummaryDataAsync({ maxRows: max_no_records }).then(function (sumdata) {\n // We will loop through our column names from our settings and save these into an array\n // We will use this later in our datatable function.\n // https://tableau.github.io/extensions-api/docs/interfaces/datatable.html#columns\n var data = [];\n var column_names = tableau.extensions.settings.get(\"column_names\").split(\"|\");\n for (i = 0; i < column_names.length; i++) {\n data.push({ title: column_names[i] });\n }\n\n // We have created an array to match the underlying data source and then\n // looped through to populate our array with the value data set. We also added\n // logic to read from the column names and column order from our configiration.\n const worksheetData = sumdata.data;\n var column_order = tableau.extensions.settings.get(\"column_order\").split(\"|\");\n var tableData = makeArray(sumdata.columns.length,sumdata.totalRowCount);\n for (var i = 0; i < tableData.length; i++) {\n for (var j = 0; j < tableData[i].length; j++) {\n tableData[i][j] = worksheetData[i][column_order[j]-1].formattedValue;\n }\n }\n\n // Destroy the old table.\n if (tableReference !== null) {\n tableReference.destroy();\n $(\"#datatable\").text(\"\");\n }\n\n // Read the Settings and get the single string for UI settings.\n var tableClass = tableau.extensions.settings.get(\"table-classes\");\n $(\"#datatable\").attr('class', '')\n $(\"#datatable\").addClass(tableClass);\n\n // Read the Settings and create an array for the Buttons.\n var buttons = [];\n var clipboard = tableau.extensions.settings.get(\"export-clipboard\");\n if (clipboard == \"Y\") {\n buttons.push('copy');\n }\n var csv = tableau.extensions.settings.get(\"export-csv\");\n if (csv == \"Y\") {\n buttons.push('csv');\n }\n var excel = tableau.extensions.settings.get(\"export-excel\");\n if (excel == \"Y\") {\n buttons.push('excel');\n }\n var pdf = tableau.extensions.settings.get(\"export-pdf\");\n if (pdf == \"Y\") {\n buttons.push('pdf');\n }\n var print = tableau.extensions.settings.get(\"export-print\");\n if (print == \"Y\") {\n buttons.push('print');\n }\n\n // If there are 1 or more Export options ticked, then we will add the dom: 'Bfrtip'\n // Else leave this out.\n if (buttons.length > 0) {\n tableReference = $('#datatable').DataTable({\n dom: 'Bfrtip',\n data: tableData,\n columns: data,\n responsive: true,\n buttons: buttons\n });\n } else {\n tableReference = $('#datatable').DataTable({\n data: tableData,\n columns: data,\n responsive: true\n });\n }\n })\n }\n }", "function renderTable(table, busses, timeToDest) {\n $(\"#\" + table + \" tr\").map(function( index, dom ) {\n\tif (index > 0) {\n\t $(dom).remove();\n\t}\n });\n\n var table = $(\"#\" + table);\n busses.map(function( bus ) {\n\ttable.append(createResultRow(bus, timeToDest));\n });\n\n if ((busses == null || busses.length == 0) && typeof timeToDest !== \"undefined\") {\n\ttable.append(\"<tr><td colspan=\\\"4\\\">Estimate time to arrival: \" + timeToDest + \"</td></tr>\");\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 renderTable(fx) {\n\n\n //Populate table body\n d3.json(url).then(function(response) {\n console.log(response); \n // var name = response.instrument;\n // // console.log(name); \n // var closeMid = [];\n // var highMid = [];\n // var lowMid = [];\n // var openMid = [];\n // var time = [];\n \n // for (var i=0; i<response.candles.length; i++){\n // // console.log(response.candles[i]);\n // closeMid.push(response.candles[i].closeMid);\n // highMid.push(response.candles[i].highMid);\n // lowMid.push(response.candles[i].lowMid);\n // openMid.push(response.candles[i].openMid);\n // time.push(response.candles[i].time.substring(0,10));\n // // console.log(time);\n // };\n\n var tbody = d3.select(\"tbody\");\n\n \n tbody.html(\"\"); \n\n // Iterate through each fileteredData and pend to table\n // filteredData.forEach(sighting => {\n \n // var tbl_col = Object.keys(sighting);\n\n // // console.log(tbl_col);\n\n // var row = tbody.append(\"tr\");\n\n // tbl_col.forEach(s_info => {\n // row.append(\"td\").text(sighting[s_info]); \n // // console.log(sighting);\n // // console.log(tbl_col);\n // // console.log(s_info);\n // }); \n // });\n\n for (var r=0; r<10; r++){\n\n var tbl_col = [\"data\", \"open\", \"high\", \"low\",\"close\"];\n\n var row = tbody.append(\"tr\");\n \n row.append(\"td\").text(response.candles[r].time.substring(0,10));\n row.append(\"td\").text(response.candles[r].openMid);\n row.append(\"td\").text(response.candles[r].highMid);\n row.append(\"td\").text(response.candles[r].lowMid);\n row.append(\"td\").text(response.candles[r].closeMid);\n\n // for (var c=0; c<tbl_col.length; c++){\n // row.append(\"td\").text(response.candles[r].time.substring(0,10));\n // row.append(\"td\").text(response.candles[r].openMid);\n // row.append(\"td\").text(response.candles[r].highMid);\n // row.append(\"td\").text(response.candles[r].lowMid);\n // row.append(\"td\").text(response.candles[r].closeMid);\n // console.log(response.candles[r].closeMid);\n // };\n\n console.log(response.candles[r]);\n \n // console.log(time);\n };\n\n\n }); \n\n\n// }); \n}", "function filterTable(filterProp, isGreater, tableData) {\n /* Change the filter to be the filter + the opposite of the current direction\n * so that the next press of the same option will flip the filter direction\n */\n setFilter(filterProp + !isGreater);\n let temp = tableData;\n temp.sort((a, b) => {\n let aVal = a.props[filterProp];\n let bVal = b.props[filterProp];\n if (aVal < bVal) {\n return 1;\n } else if (aVal > bVal) {\n return -1;\n } else {\n return 0;\n }\n });\n\n // Reverse the sorted array if the filter is set in the opposite direction\n if (!isGreater) {\n temp.reverse();\n }\n setTable(temp);\n }", "function ufoFiltering() {\n console.log(\"Event Fired\");\n d3.event.preventDefault();\n \n \n // Remove Table Body\n d3.select(\"tbody\").selectAll(\"tr\").remove();\n let ufoFilteredData = tableData.filter(dateFilter);\n\n\n// let ufoFilteredData = tableData.filter(function(dt){\n// console.log(dt.datetime);\n// return dt.datetime === inputSearchDateValue;});\n\n ufoFilteredData.forEach(ufoSighting => {\n var row = tableBody.append(\"tr\");\n row.append(\"td\").text(ufoSighting.datetime);\n row.append(\"td\").text(ufoSighting.city)\n row.append(\"td\").text(ufoSighting.state)\n row.append(\"td\").text(ufoSighting.country)\n row.append(\"td\").text(ufoSighting.shape)\n row.append(\"td\").text(ufoSighting.durationMinutes)\n row.append(\"td\").text(ufoSighting.comments) \n });\n}", "setup(tableId) {\n // link icons for sort buttons\n var iconLink = document.createElement(\"link\");\n iconLink.setAttribute(\"rel\", \"stylesheet\");\n iconLink.setAttribute(\"href\", \"https://use.fontawesome.com/releases/v5.7.0/css/all.css\");\n iconLink.setAttribute(\"integrity\", \"sha384-lZN37f5QGtY3VHgisS14W3ExzMWZxybE1SJSEsQp9S+oqd12jhcu+A56Ebc1zFSJ\");\n iconLink.setAttribute(\"crossorigin\", \"anonymous\");\n document.head.appendChild(iconLink);\n\n // check arguments\n for (var i = 1; i < arguments.length; i++) {\n if ((arguments[i] != STRCOL) && (arguments[i] != NUMCOL)) {\n console.error(\"Dynamic table: Invalid arguments.\");\n return;\n }\n }\n\n // check if <tbody> element is present\n var tmp = document.getElementById(tableId).getElementsByTagName(\"tbody\");\n if (tmp.length < 1) {\n console.error(\"Dynamic table: No <tbody> element inside table.\");\n return;\n }\n this.tbody = tmp[0];\n\n // get rows from <tbody>\n this.rows = [];\n var trElements = this.tbody.getElementsByTagName(\"tr\");\n for (var i = 0; i < trElements.length; i++) {\n this.rows.push(new TableRow(trElements[i]));\n }\n if (this.rows.length < 1) {\n console.error(\"Dynamic table: No rows inside <tbody> element.\");\n return;\n }\n\n // set up filter and order variables\n this.numCols = this.rows[0].cells.length;\n this.filters = [];\n for (var i = 0; i < this.numCols; i++) {\n this.filters[i] = \"\";\n }\n this.orders = [];\n for (var i = 0; i < this.numCols; i++) {\n this.orders[i] = [i, 0, new Date()];\n }\n\n // SET UP THE FILTER BAR\n this.filterBar = document.createElement(\"tr\");\n for (var i = 0; i < this.numCols; i++) {\n // set up filter <input> element\n var filterInput = document.createElement(\"input\");\n filterInput.setAttribute(\"type\", \"text\");\n filterInput.setAttribute(\"class\", \"dyntable_filter\");\n filterInput.setAttribute(\"placeholder\", \"Filter...\");\n filterInput.oninput = this.setFilter.bind(this, i);\n\n // create wrapping cell and appednd it to filter bar\n var cellElement = document.createElement(\"td\");\n cellElement.appendChild(filterInput);\n cellElement.setAttribute(\"class\", \"dyntable_cell\");\n this.filterBar.appendChild(cellElement);\n }\n\n // SET UP THE SORT BAR\n this.sortBar = document.createElement(\"tr\");\n for (var i = 0; i < this.numCols; i++) {\n // create wrapping cell (will contain 3 sorting buttons)\n var cellElement = document.createElement(\"td\");\n cellElement.setAttribute(\"class\", \"dyntable_cell\");\n\n for (var j = 0; j < 3; j++) {\n // create the <button> element and an icon for it\n var sortButton = document.createElement(\"button\");\n sortButton.setAttribute(\"class\", \"dyntable_sort\");\n var icon = document.createElement(\"i\");\n\n // set the behaviour of the button and corresponding icon\n if (arguments.length > i + 1) {\n sortButton.onclick = this.setOrder.bind(this, i, j * arguments[i + 1]);\n icon.setAttribute(\"class\", this.getIconClass(j * arguments[i + 1]));\n }\n else {\n sortButton.onclick = this.setOrder.bind(this, i, j);\n icon.setAttribute(\"class\", this.getIconClass(j));\n }\n\n // put the icon on the button and append it in the wrapping cell\n sortButton.appendChild(icon);\n cellElement.appendChild(sortButton);\n }\n\n // append the cell to the sort bar\n this.sortBar.appendChild(cellElement);\n }\n\n // add filter and sort bars to the table\n tmp = document.getElementById(tableId).getElementsByTagName(\"thead\");\n if (tmp.length < 1) {\n document.getElementById(tableId).insertBefore(this.sortBar, document.getElementById(tableId).childNodes[0]);\n document.getElementById(tableId).insertBefore(this.filterBar, document.getElementById(tableId).childNodes[0]);\n }\n else {\n tmp[0].appendChild(this.filterBar);\n tmp[0].appendChild(this.sortBar);\n }\n }", "render(){\n console.log(\"render table head\");\n return (\n <thead>\n <tr>\n {this.getHeaderCk()}\n {this.getActions()}\n {this.getCols()}\n </tr>\n </thead>\n )\n }", "render() {\n return (\n <table>\n <thead>\n <tr>\n {\n this.props.headers.map((header, index) =>\n <th key={`header-${index}`}>\n {header}\n </th>\n )\n }\n </tr>\n </thead>\n <tbody>\n {\n this.props.data.map((datum, datumIndex) =>\n <tr key={`data-row-${datumIndex}`}>\n {\n datum.map((item, itemIndex) =>\n <td key={`data-col-${itemIndex}`}>\n {item}\n </td>\n )\n }\n </tr>\n )\n }\n </tbody>\n </table>\n );\n }", "function generateTable(data) {\n noResults.style('display', 'none');\n tableBody.html('');\n table.style('display', 'table');\n data.forEach(result => {\n var row = tableBody.append('tr');\n var date = row.append('td').text(result.datetime).attr('class', 'datetime').on('click', lookUp);\n var city = row.append('td').text(result.city).attr('class', 'city').on('click', lookUp);\n var state = row.append('td').text(result.state).attr('class', 'state').on('click', lookUp);\n var country = row.append('td').text(result.country).attr('class', 'country').on('click', lookUp);\n var shape = row.append('td').text(result.shape).attr('class', 'shape').on('click', lookUp);\n var duration = row.append('td').text(result.durationMinutes).attr('class', 'duration');\n var description = row.append('td').text(result.comments).attr('class', 'description');\n });\n}", "function updateTable() {\n\n let filtered = houses.filter(d => evalFilters(d));\n\n let rows = d3.select(\"table#places\").selectAll(\"tr\").data(filtered);\n\n rows.exit().remove();\n\n rows.enter().append(\"tr\")\n .merge(rows) // Merge in existing rows so we can affect all of them\n .html(\"\") // Clear contents of all rows so that we can put in some new <td> elements\n\n // Add some stuff to the contents of all of the rows (data can percolate down the DOM hierarchy)\n rows.append(\"td\").text(d => \"House \"+d.Entry);\n rows.append(\"td\").text(d => d3.format(\"$,\")(d[\"Sale Price\"]));\n rows.append(\"td\").text(d => d[\"Neighborhood\"]);\n\n\n }", "renderGUI(data) {\n\n let controller = this;\n\n /* Get the html template for table rows */\n let staticHtml = $(\"#activity-row-template\").html();\n\n /* Bind obj data to the template, then append to table body */\n $.each(data, function (index, obj) {\n let row = staticHtml;\n row = row.replace(/{Id}/ig, obj.id);\n row = row.replace(/{Area}/ig, obj.area);\n row = row.replace(/{Type}/ig, obj.type);\n row = row.replace(/{EstimatedTime}/ig, obj.estim_time);\n\n row = row.replace()\n $('#activity-rows').append(row);\n\n });\n\n /* When empty address-book */\n if (data.length === 0) {\n $(\"tfoot :first-child\").hide();\n $(\"tfoot\").html('<tr><th colspan=\"6\">No records</th></tr>');\n }\n\n\n }", "render() {\n var prodlist = this.props.productlist;\n var filterText = this.props.filterText; \n\n return (\n <div className=\"ProductTable\" id=\"ProductTable\"> \n <table className=\"table table-bordered table-striped\">\n <thead>\n <tr>\n <th>ID</th> <th>Name</th> <th>Category</th> <th>Price</th> <th></th>\n </tr>\n </thead>\n <tbody>\n {Object.keys(prodlist)\n .filter(prodid => -1 < prodlist[prodid].name.indexOf(filterText))\n .map(prodid => {return (\n <ProductRow \n prodid = {prodlist[prodid].id} \n product = {prodlist[prodid]} \n onDestroy={this.handleDestroy}/>)}\n )}\n </tbody>\n </table>\n </div>\n );\n }", "render() { \n const columns = [{\n\t\t\ttitle: 'Name',\n\t\t\tdataIndex: 'name',\n\t\t\tkey: 'name',\n\t\t}, {\n\t\t\ttitle: 'Age',\n\t\t\tdataIndex: 'age',\n\t\t\tkey: 'age',\n\t\t}, {\n\t\t\ttitle: 'Address',\n\t\t\tdataIndex: 'address',\n\t\t\tkey: 'address',\n\t\t}];\n\t\tconst dataSource = [{\n\t\t\tkey: '1',\n\t\t\tname: 'Mike',\n\t\t\tage: 32,\n\t\t\taddress: '10 Downing Street'\n\t\t}, {\n\t\t\tkey: '2',\n\t\t\tname: 'John',\n\t\t\tage: 42,\n\t\t\taddress: '10 Downing Street'\n\t\t}]; \n return (\n <div>\n\t\t\t {getTable(dataSource, columns)}\n </div>\n );\n }", "function searchButtonClick() {\r\n var filterDate = $dateTimeInput.value.trim();\r\n var filterCity = $cityInput.value.trim().toLowerCase();\r\n var filterState = $stateInput.value.trim().toLowerCase();\r\n var filterCountry = $countryInput.value.trim().toLowerCase();\r\n var filterShape = $shapeInput.value.trim().toLowerCase();\r\n\r\n if (filterDate != \"\") {\r\n filteredData = filteredData.filter(function (date) {\r\n var dataDate = date.datetime;\r\n return dataDate === filterDate;\r\n });\r\n\r\n }\r\n\r\n if (filterCity != \"\") {\r\n filteredData = filteredData.filter(function (city) {\r\n var dataCity = city.city;\r\n return dataCity === filterCity;\r\n });\r\n }\r\n\r\n if (filterState != \"\") {\r\n filteredData = filteredData.filter(function (state) {\r\n var dataState = state.state;\r\n return dataState === filterState;\r\n });\r\n }\r\n\r\n if (filterCountry != \"\") {\r\n filteredData = filteredData.filter(function (country) {\r\n var dataCountry = country.country;\r\n return dataCountry === filterCountry;\r\n });\r\n }\r\n\r\n if (filterShape != \"\") {\r\n filteredData = filteredData.filter(function (shape) {\r\n var dataShape = shape.shape;\r\n return dataShape === filterShape;\r\n });\r\n }\r\n\r\n renderTable();\r\n}", "function filterList() {\n var inputElement = d3.select(\".form-control\")\n var inputValue = inputElement.property(\"value\")\n \n //select table and body elements\n var table = d3.select(\".table\")\n var tbody = d3.select(\"tbody\")\n \n //clear table body\n tbody.text(\"\")\n \n //filter data for date entered\n filteredData = data.filter(d => d.datetime === inputValue)\n //populate table with filtered list data\n filteredData.forEach(function(UFOsiting) {\n \n // Prevent the page from refreshing\n var row = tbody.append(\"tr\")\n Object.entries(UFOsiting).forEach(function([key, value]) {\n var dataElement = row.append(\"td\")\n dataElement.text(value)\n });\n });\n}", "function renderTable() {\n $tbody.innerHTML = \"\";\n for (var i = 0; i < AlienData.length; i++) {\n // Get get the current address object and its fields\n var Sighting = AlienData[i];\n var fields = Object.keys(Sighting);\n // Create a new row in the tbody, set the index to be i + startingIndex\n var $row = $tbody.insertRow(i);\n for (var j = 0; j < fields.length; j++) {\n // For every field in the address object, create a new cell at set its inner text to be the current value at the current address's field\n var field = fields[j];\n var $cell = $row.insertCell(j);\n $cell.innerText = Sighting[field];\n }\n }\n}", "function renderTable(page=0) {\r\n $tbody.innerHTML = \"\";\r\n var start =page * $maxresults;\r\n var end=start + $maxresults;\r\n for (var i = 0; i < $maxresults; i++) {\r\n // Get get the current address object and its fields\r\n console.log(start, i);\r\n var alien = filterdata[start + i];\r\n console.log(alien);\r\n var fields = Object.keys(alien);\r\n // Create a new row in the tbody, set the index to be i + startingIndex\r\n var $row = $tbody.insertRow(i);\r\n for (var j = 0; j < fields.length; j++) {\r\n // For every field in the address object, create a new cell at set its inner text to be the current value at the current address's field\r\n var field = fields[j];\r\n var $cell = $row.insertCell(j);\r\n $cell.innerText = alien[field];\r\n }\r\n }\r\n // show pagination\r\nvar Numberofpages=filterdata.length/$maxresults;\r\n$pagination.innerHTML=\"\";\r\nfor(let i=0; i < Numberofpages; i++){\r\n var li=document.createElement(\"Li\");\r\n var a=document.createElement(\"a\");\r\n li.classList.add(\"page-item\");\r\n a.classList.add(\"page-Link\");\r\n a.text=i+1;\r\n a.addEventListener(\"click\",function(){\r\n renderTable(i);\r\n });\r\n li.appendChild(a);\r\n $pagination.appendChild(li);\r\n}\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n}", "function renderDataTableData(tableId, data) {\n $(`#${tableId}`).DataTable().clear().rows.add(data).draw();\n}", "render() {\n return (\n <>\n <div className=\"container-fluid\">\n {\" \"}\n <div className=\"row header-row\">\n <div className=\"col-sm-3\" />\n <div className=\"col-sm-6 text-center\">\n <h1>Employee Directory</h1>\n <hr></hr>\n <h5>Search by first name or sort by clicking on 'Name'</h5>\n </div>\n </div>\n </div>\n <div className=\"container-fluid\">\n <div className=\"row main-page\">\n <div className=\"col-sm-1\" />\n <div className=\"col-sm-10 text-center\">\n <div className=\"search-bar row\">\n <div className=\"col-sm-3\" />\n <div className=\"col-sm-6 search-div\">\n <input\n type=\"text\"\n class=\"form-control input-search\"\n onChange={this.handleSearch}\n placeholder=\"Search for employee\"\n aria-describedby=\"inputGroup-sizing-default\"\n />\n </div>\n <div className=\"col-sm-3\" />\n </div>\n\n <table className=\"table table-dark\">\n <thead>\n <tr>\n <th scope=\"col\">Image</th>\n <th scope=\"col\" onClick={this.handleSort}>\n Name\n </th>\n <th scope=\"col\">Phone</th>\n <th scope=\"col\">Email</th>\n <th scope=\"col\">Age</th>\n </tr>\n </thead>\n <tbody>\n {this.state.filterData.map((user) => {\n // console.log(user);\n return (\n <tr>\n <th scope=\"row\">\n <img src={user.picture.medium} />\n </th>\n <td key={user.login.uuid}>\n {user.name.first + \" \" + user.name.last}\n </td>\n <td>{user.phone}</td>\n <td>\n <a href=\"\">{user.email}</a>\n </td>\n <td>{user.dob.age}</td>\n </tr>\n );\n })}\n </tbody>\n </table>\n </div>\n </div>\n </div>\n </>\n );\n }", "redraw() {\n while (this.tbody.firstChild) {\n this.tbody.removeChild(this.tbody.firstChild);\n }\n var filteredRows = this.filterRows();\n var orderedRows = this.sortRows(filteredRows);\n orderedRows.forEach(row => {\n this.tbody.appendChild(row);\n });\n }", "render() {\n let searchBarFilter = this.state.results.filter(\n (employee) =>\n employee.name.first\n .toLowerCase()\n .indexOf(this.state.value.toLowerCase()) !== -1 ||\n employee.name.last\n .toLowerCase()\n .indexOf(this.state.value.toLowerCase()) !== -1 ||\n employee.email.toLowerCase().indexOf(this.state.value.toLowerCase()) !==\n -1 ||\n employee.location.city\n .toLowerCase()\n .indexOf(this.state.value.toLowerCase()) !== -1 ||\n employee.location.state\n .toLowerCase()\n .indexOf(this.state.value.toLowerCase()) !== -1 ||\n employee.location.country\n .toLowerCase()\n .indexOf(this.state.value.toLowerCase()) !== -1 ||\n employee.phone.toLowerCase().indexOf(this.state.value.toLowerCase()) !==\n -1\n );\n\n let tableResults;\n\n if (this.state.value === \"\") {\n tableResults = this.state.results;\n } else {\n tableResults = searchBarFilter;\n }\n\n return (\n <div>\n <Navbar\n value={this.state.value}\n handleChange={this.handleChange}\n handleSubmit={this.handleSubmit}\n />\n <div className=\"container-fluid\">\n <Table\n results={tableResults}\n sort={this.state.sort}\n handleSort={this.handleSort}\n handleClose={this.handleClose}\n handleShow={this.handleShow}\n />\n </div>\n </div>\n );\n }", "function loadTable(inputFilter) {\n \n d3.select(\"tbody\")\n \n .selectAll(\"tr\")\n \n .data(inputFilter)\n \n .enter()\n \n .append(\"tr\")\n \n .html(function(d) {\n \n return `<td>${d.datetime}</td> <td>${d.city}</td> <td>${d.state}</td> <td>${d.country}</td>\n \n <td>${d.shape}</td> <td>${d.durationMinutes}</td> <td>${d.comments}</td> `;\n });\n }", "function setupFilterTable() {\n\t\t\tif($(\".filteredtable\").length) {\n\t\t\t\tvar classes = $(\".filteredtable\").attr(\"class\").split(' ');\n\t\t\t\tvar column = -1;\n\t\t\t\tvar keyword = -1;\n\t\t\t\tvar hideoption = -1;\n\t\t\t\tvar prefilter = -1;\n\t\t\t\tfor (var i in classes) {\n\t\t\t\t\tvar classdata = classes[i].match(/column(\\d)/);\n\t\t\t\t\tif (classdata != null) {\n\t\t\t\t\t\tcolumn = classdata[1];\n\t\t\t\t\t} else {\n\t\t\t\t\t\tclassdata = classes[i].match(/keyword(\\d)/);\n\t\t\t\t\t\tif (classdata != null) {\n\t\t\t\t\t\tkeyword = classdata[1];\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t}\n\t\t\t\tif ($(\"#filteroptions\").length > 0) {\n\t\t\t\t var options = $(\"#filteroptions\").attr(\"class\").split(' ');\n\t\t\t\t for (var i in options) {\n\t\t\t\t\thidecolumn = options[i].match(/hidecolumn(\\d)/);\n\t\t\t\t\tif (hidecolumn != null) {\n\t\t\t\t\t hideoption = hidecolumn[1];\n\t\t\t\t\t} else if (options[i].match(/prefilter/)) {\n\t\t\t\t\t prefilter = $(\"#filteroptions\").attr(\"title\");\n\t\t\t\t\t}\n\t\t\t\t }\n\t\t\t\t}\n\t\t\t\t$(\".filteredtable\").before(\"<div id=\\\"calendar-search\\\"><p class=\\\"dropdown\\\">\" + $(\".filteredtable thead th:nth-child(\" + column + \")\").text() + \": <select id=\\\"filter\\\"><option value=\\\"\\\">View All</option></select></p><p class=\\\"filtersearch\\\">Search: <input type=\\\"text\\\" id=\\\"filtersearch\\\"/></p></div>\");\n\t\t\t\tif (isMobile) {\n\t\t\t\t\t$(\"#calendar-search .filtersearch\").append(\"<input type=\\\"button\\\" value=\\\"Go\\\">\");\n\t\t\t\t}\n\t\t\t\tvar cats = new Array();\n\t\t\t\t$(\".filteredtable tbody tr td:nth-child(\" + column + \")\").each(function() {\n\t\t\t\t\tvar vals = $(this).text().split(\", \");\n\t\t\t\t\tfor (var i in vals) {\n\t\t\t\t\t\tif (jQuery.inArray($.trim(vals[i]), cats) == -1) {\n\t\t\t\t\t\t\tcats.push($.trim(vals[i]));\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t\tif (keyword > 0) {\n\t\t\t\t\t$(\".filteredtable tr td:nth-child(\" + keyword + \")\").css(\"display\", \"none\");\n\t\t\t\t\t$(\".filteredtable tr th:nth-child(\" + keyword + \")\").css(\"display\", \"none\");\n\t\t\t\t}\n\t\t\t\tif (hideoption > 0) {\n\t\t\t\t\t$(\".filteredtable tr td:nth-child(\" + hideoption + \")\").css(\"display\", \"none\");\n\t\t\t\t\t$(\".filteredtable tr th:nth-child(\" + hideoption + \")\").css(\"display\", \"none\");\n\t\t\t\t}\n\t\t\t\tcats.sort();\n\t\t\t\tfor (var i in cats) {\n\t\t\t\t\t$(\"#filter\").append(\"<option>\"+cats[i]+\"</option>\");\n\t\t\t\t}\n\t\t\t\n\t\t\t\t$(\"#filter\").change(function() {\n\t\t\t\t\tsearchtable();\n\t\t\t\t});\n\t\t\t\t\n\t\t\t\t$(\"#filtersearch\").keyup(function() {\n\t\t\t\t\tsearchtable();\n\t\t\t\t});\n\t\t\t\t\n\t\t\t\tfunction searchtable() {\n\t\t\t\t\t/* Filter the table */\n\t\t\t\t\t$.uiTableFilter( $('table.filteredtable'), $(\"#filtersearch\").val(), $(\"#filter\").val(), $(\".filteredtable thead th:nth-child(\" + column + \")\").text());\n\t\t\t\t\t/* Remove tints from all rows */\n\t\t\t\t\t$('table.filteredtable tr').removeClass(\"even\");\n\t\t\t\t\t/* Filter through what is still displaying and change the tints */\n\t\t\t\t\tvar counter = 0;\n\t\t\t\t\t$('table.filteredtable tr').each(function() {\n\t\t\t\t\t\t\t\t\t if($(this).css(\"display\") != \"none\") {\n\t\t\t\t\t\t\t\t\t\t if (counter % 2) {\n\t\t\t\t\t\t\t\t\t\t $(this).addClass(\"even\");\n\t\t\t\t\t\t\t\t\t\t }\n\t\t\t\t\t\t\t\t\t\t counter++;\n\t\t\t\t\t\t\t\t\t }\n\t\t\t\t\t\t\t\t\t });\n\t\t\t\t}\n\t\t\n\t\t\t\tif (prefilter != -1) {\n\t\t\t\t $(\"#filter\").val(prefilter);\n\t\t\t\t searchtable();\n\t\t\t\t}\n\t\t\t\tif ($(\"#filteroptions.hidefilters\").length) {\n\t\t\t\t $(\"#calendar-search\").hide();\n\t\t\t\t}\n\t\t\n\n\t\t\t\t$('#filter-form').submit(function(){\n\t\t\t\t\treturn false;\n\t\t\t\t}).focus(); //Give focus to input field\n\t\t\t}\n\t\t}", "function new_table(filteredufo) {\n d3.select(\"tbody\").remove();\n d3.select(\"#ufo-table\").append(\"tbody\");\n var tbody = d3.select(\"#ufo-table\").select(\"tbody\");\n // tbody.text(\"\");\n filteredufo.forEach(function(ufo) {\n var row = tbody.append(\"tr\")\n\trow.append(\"td\").text(ufo.datetime)\n\trow.append(\"td\").text(ufo.city)\n\trow.append(\"td\").text(ufo.state)\n\trow.append(\"td\").text(ufo.country)\n\trow.append(\"td\").text(ufo.shape)\n\trow.append(\"td\").text(ufo.durationMinutes)\n\trow.append(\"td\").text(ufo.comments)\n})\n}" ]
[ "0.83170396", "0.80801255", "0.7957967", "0.7643406", "0.75485605", "0.7458459", "0.74416643", "0.73731595", "0.7355464", "0.73297876", "0.7311626", "0.7288826", "0.7209703", "0.7167867", "0.7133188", "0.7004345", "0.6978698", "0.69197655", "0.68960696", "0.68590313", "0.68560594", "0.68385655", "0.6807039", "0.6784378", "0.67527306", "0.67252314", "0.6709019", "0.67070556", "0.66564155", "0.66439587", "0.6642498", "0.66201925", "0.66184556", "0.659537", "0.6578774", "0.64978963", "0.6477487", "0.64603275", "0.6460018", "0.643973", "0.6434374", "0.6430927", "0.64304745", "0.6429354", "0.6398932", "0.63793075", "0.6368204", "0.6364264", "0.6354329", "0.634724", "0.6329528", "0.63227963", "0.6322196", "0.6282098", "0.6268574", "0.6263347", "0.62585896", "0.6256582", "0.6244631", "0.6239294", "0.6229983", "0.6209258", "0.620088", "0.61918503", "0.6187454", "0.6184248", "0.61749506", "0.6171796", "0.6170165", "0.61509025", "0.6144588", "0.6140064", "0.6139969", "0.6138124", "0.6130073", "0.6119635", "0.6116098", "0.6107196", "0.6104148", "0.60975593", "0.60975474", "0.60963565", "0.6092226", "0.60886735", "0.60813373", "0.60791796", "0.6077937", "0.60752857", "0.60694045", "0.60542357", "0.60506815", "0.60458606", "0.60455644", "0.60446066", "0.60401165", "0.60377455", "0.60374975", "0.60356855", "0.60315216", "0.60305023" ]
0.6764458
24
fin de script JQ
function getXhr() { var xhr = null; if (window.XMLHttpRequest) // Firefox et autres xhr = new XMLHttpRequest(); else if (window.ActiveXObject) { // Internet Explorer try { xhr = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { xhr = new ActiveXObject("Microsoft.XMLHTTP"); } } else { // XMLHttpRequest non supporté par le navigateur alert("Votre navigateur ne supporte pas les objets XMLHTTPRequest..."); xhr = false; } return xhr; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function jQuerify() {\n if (typeof jQuery == 'undefined') {\n var s = document.createElement('script');\n s.setAttribute('src','http://code.jquery.com/jquery.js');\n document.getElementsByTagName('body')[0].appendChild(s);\n }\n}", "function loadJQ() {\r\n\t var script = document.createElement(\"script\");\r\n\t script.setAttribute(\"src\", \"http://plaku.com/bytui/jquery.min.js\");\r\n\t script.addEventListener('load', function() {\r\n\t\tvar script = document.createElement(\"script\");\r\n\t\tloadJQCookie();\r\n\t\tdocument.body.appendChild(script);\r\n\t }, false);\r\n\t document.body.appendChild(script);\r\n\t}", "function scriptLoadHandler() {\n // Restore jQuery and window.jQuery to their previous values and store the\n // new jQuery in our local jQuery variable\n jQuery = window.jQuery.noConflict(true);\n PlannTo.jQuery = jQuery;\n\n // Call our main function\n\n main();\n }", "function queryJquery (url, callback) {\n request(url, (err, res, body) => callback(err, body) );\n}", "function setJQuery(jq) {\n $$1 = jq;\n dataTable$1 = jq.fn.DataTable;\n }", "function j(){}", "function j(){}", "function j(){}", "function scriptLoadHandler() {\n\t\tjQuery = window.jQuery.noConflict(true);\n\t\tmain();\n\t}", "function scriptLoadHandler() {\n\t\tjQuery = window.jQuery.noConflict(true);\n\t\tmain();\n\t}", "function onJoyLoaded( data ){\n j.append( data );\n }", "function main() {\n // main widget code\n\n jQuery(document).ready(function ($) {\n var rule_id = scriptTag.src.split(\"?id=\")[1];\n var site_path = scriptTag.src.split(\"?id=\")[0];\n var hostname = $('<a>').prop('href', site_path).prop('protocol') + '//' + $('<a>').prop('href', site_path).prop('host');\n var baseURI = window.location.pathname+location.search;\n\n var api_url = hostname+\"/api/check-rule-conditions/\"+rule_id;\n jQuery.getJSON(api_url, {url: baseURI}, function(result) {\n console.log(result);\n if(result.show) {\n alert(result.text)\n }\n });\n\n\n });\n }", "function setJQuery$2(jq) {\n $$3 = jq;\n dataTable$3 = jq.fn.dataTable;\n }", "function setJQuery$1(jq) {\n $$2 = jq;\n dataTable$2 = jq.fn.dataTable;\n }", "function scriptLoadHandler() {\n // Restore $ and window.jQuery to their previous values and store the\n // new jQuery in our local jQuery variable\n jQuery = window.jQuery.noConflict(true);\n // Call our main function\n main();\n }", "function scriptLoadHandler() {\n // Restore $ and window.jQuery to their previous values and store the\n // new jQuery in our local jQuery variable\n jQuery = window.jQuery.noConflict(true);\n // Call our main function\n main();\n }", "function scriptLoadHandler() {\n // Restore $ and window.jQuery to their previous values and store the\n // new jQuery in our local jQuery variable\n wjQuery = window.jQuery.noConflict(false); \n }", "function applyMultiJs () {\n /* Main script loaded on base.html. Here only function is\n called */\n $('#id_client_id').multi({\n \"search_placeholder\":\n \"Search... (if there are no clients, hit CTRL+R to manually refresh the page)\",\n });\n}", "function letsJQuery() {\n get_layout();\n}", "function scriptLoadHandler() {\n // Restore $ and window.jQuery to their previous values and store the\n // new jQuery in our local jQuery variable\n jQuery = window.jQuery.noConflict(true);\n // Call our main function\n main();\n }", "function scriptLoadHandler() {\n // Restore $ and window.jQuery to their previous values and store the\n // new jQuery in our local jQuery variable\n jQuery = window.jQuery.noConflict(true);\n $ = jQuery;\n // Call our main function\n main();\n }", "function letsJQuery() {\r\n if (typeof $ == 'function') {\r\n // Your Script Code Here\r\n $('ul.ghnavsub li a').each( function() {\r\n $(this).attr('href', $(this).attr('href') + '&sort=p' );\r\n });\r\n }\r\n }", "function letsJQuery() {\r\n\tjQry(\"a\").each(function(i) {\r\n\t\tif (this.href.indexOf(\"draugiem.lv/friend/?\") > -1 || this.href.indexOf(\"frype.com/friend/?\") > -1 || this.href.indexOf(\"frype.lt/friend/?\") > -1 || this.href.indexOf(\"munidraugi.lv/friend/?\") > -1 || this.href.indexOf(\"freundeweb.net/friend/?\") > -1 || this.href.indexOf(\"baratikor.com/friend/?\") > -1) {\r\n\t\t\tif (this.innerHTML.indexOf(\"<\") == -1 && this.innerHTML.indexOf(\">\") == -1 && this.innerHTML.length > 0) {\r\n\t\t\t\tvar domain = \"draugiem.lv\";\r\n\t\t\t\tif (this.href.indexOf(\"frype.com\") > -1) domain = \"frype.com\";\r\n\t\t\t\tif (this.href.indexOf(\"frype.lt\") > -1) domain = \"frype.lt\";\r\n\t\t\t\tif (this.href.indexOf(\"munidraugi.lv\") > -1) domain = \"munidraugi.lv\";\r\n\t\t\t\tif (this.href.indexOf(\"freundeweb.net\") > -1) domain = \"freundeweb.net\";\r\n\t\t\t\tif (this.href.indexOf(\"baratikor.com\") > -1) domain = \"baratikor.com\";\r\n\t\t\t\tvar appendAfter = \"\";\r\n\t\t\t\tvar parts = this.href.split(\"?\");\r\n\t\t\t\tif (parts[1].indexOf(\"&\") > -1) {\r\n\t\t\t\t\tparts2 = parts[1].split(\"&\");\r\n\t\t\t\t\tparts[1] = parts2[0];\r\n\t\t\t\t}\r\n\t\t\t\tif (parts[1].indexOf(\"fid=\") > -1) parts[1] = parts[1].replace(/fid=/gi, \"\");\r\n\t\t\t\tparts[1] = parseInt(parts[1]);\r\n\t\t\t\tif (parts[1] > 0) {\r\n\t\t\t\t\tvar title = 'http://www.' + domain + '/friend/?selectedTab=9&opinionTab=0&fid=' + parts[1];\r\n\t\t\t\t\tif (typeof(this.title) != \"undefined\" && this.title != \"\") title = this.title;\r\n\t\t\t\t\tappendAfter = '&nbsp;<a href=\"http://www.' + domain + '/friend/?selectedTab=9&opinionTab=4&fid=' + parts[1] + '\" title=\"' + title + '\" target=\"_blank\"><img src=\"http://img197.imageshack.us/img197/4480/drsupersmall.png\" style=\"border: none; padding: 0 2px;\" alt=\"profils\" /></a>';\r\n\t\t\t\t}\r\n\t\t\t\tif (appendAfter != \"\") jQry(this).after(appendAfter);\r\n\t\t\t}\r\n\t\t}\r\n\t});\r\n}", "function scriptLoadHandler() {\n\t\t // Restore $ and window.jQuery to their previous values and store the\n\t\t // new jQuery in our local jQuery variable\n\t\t jQuery = window.jQuery.noConflict(true);\n\t\t // Call our main function\n\t\t main(); \n\t\t}", "function scriptLoadHandler() {\n // Restore $ and window.jQuery to their previous values and store the\n // new jQuery in our local jQuery variable\n jQuery = window.jQuery.noConflict(true);\n // Call our main function\n main();\n }", "function scriptLoadHandler() {\n // Restore $ and window.jQuery to their previous values and store the\n // new jQuery in our local jQuery variable\n jQuery = window.jQuery.noConflict(true);\n // Call our main function\n main();\n }", "function gotjQ(){try{var jq=!!jQuery}catch(err){var jq=!1}return jq}", "function loadPlugin($){\n\n\t\t\tif( !options.jqueryUrl.wasAlreadyLoaded ){\n\t\t\t\twindow.jQuery_loadedByMochup = $;\n\t\t\t}\n\n\t\t\tif( !(window.JSON && JSON.stringify) && options.jsonUrl ){\n\t\t\t\t$.getScript( options.jsonUrl );\n\t\t\t}\n\n\t\t\tif( $.fn.mochup ){\n\t\t\t\t$(options.scope).mochup();\n\t\t\t}else{\n\t\t\t\t$.getScript( options.mochupUrl, function(){\n\t\t\t\t\t$(options.scope).mochup();\n\t\t\t\t});\n\t\t\t}\n\t\t}", "function runScript(url) {\n $.getScript(url, function (data, textStatus, jqxhr) {\n\n });\n }", "function main() {\r\n // Note, jQ replaces $ to avoid conflicts.\r\n\r\n var $commentList = jQ('.commentList');\r\n if($commentList.length){\r\n var $comments = $commentList.children('ol').children('li');\r\n $comments.each(function(){\r\n var $commentWrap = jQ(this)\r\n //, $comment = $commentWrap.children('.rp_general').children('p')\r\n , name = $commentWrap.children('.rp_general').children('.name').text();\r\n if(name == '김루테') $commentWrap.hide();\r\n }); \r\n }\r\n\r\n\r\n}", "function loadAutoWoot() {\n\tif(window.location.hostname === \"plug.dj\") { \n\t\t// Get jQuery\n\t\t$.getScript(jQuery).done(function(){\n\t\t\t// Run the script\n\t\t\trunAutoWoot();\n\t\t});\n\t} else {\n\t\talert('This script can only run on Plug.DJs website.');\n\t}\n}", "function letsJQuery() {\r\n\tcreateOptionsMenu();\r\n\tpressthatButton();\r\n }", "function updateJQuery($) {\n if (!$ || ($ && $.bridget)) {\n return;\n }\n $.bridget = jQueryBridget;\n }", "function addJQuery(callback) {\r\n var script = document.createElement(\"script\");\r\n script.setAttribute(\"src\", \"//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js\");\r\n script.addEventListener('load', function() {\r\n var script = document.createElement(\"script\");\r\n script.textContent = \"window.jQ=jQuery.noConflict(true);(\" + callback.toString() + \")();\";\r\n document.body.appendChild(script);\r\n }, false);\r\n document.body.appendChild(script);\r\n}", "function addJQuery(callback) {\r\n var script = document.createElement(\"script\");\r\n script.setAttribute(\"src\", \"//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js\");\r\n script.setAttribute(\"type\", \"text/javascript\");\r\n script.addEventListener('load', function() {\r\n var script = document.createElement(\"script\");\r\n script.textContent = \"window.jQ=jQuery.noConflict(true);(\" + callback.toString() + \")();\";\r\n document.body.appendChild(script);\r\n }, false);\r\n document.body.appendChild(script);\r\n}", "function PaginaInicial_elementsExtraJS() {\n // screen (PaginaInicial) extra code\n\n }", "function noJqueryAvailableSoLoadOurOwn(callback) {\n // Boolean to avoid triggering the callback twice (when both script.onload and script.onreadystatechange work)\n var ourJqueryIsLoaded = false;\n // Build the script element.\n var script = document.createElement(\"script\");\n script.src = \"http://ajax.googleapis.com/ajax/libs/jquery/\" + minimumJqueryVersion + \"/jquery.min.js\";\n script.onload = script.onreadystatechange = function() {\n if (!ourJqueryIsLoaded && (!this.readyState || this.readyState == \"loaded\" || this.readyState == \"complete\")) {\n ourJqueryIsLoaded = true;\n var jQuery = window.jQuery.noConflict(true);\n callback(jQuery);\n }\n };\n // Add our jQuery script element to the document.\n document.getElementsByTagName(\"head\")[0].appendChild(script);\n }", "function noJqueryAvailableSoLoadOurOwn(callback) {\n // Boolean to avoid triggering the callback twice (when both script.onload and script.onreadystatechange work)\n var ourJqueryIsLoaded = false;\n // Build the script element.\n var script = document.createElement(\"script\");\n script.src = \"http://ajax.googleapis.com/ajax/libs/jquery/\" + minimumJqueryVersion + \"/jquery.min.js\";\n script.onload = script.onreadystatechange = function() {\n if (!ourJqueryIsLoaded && (!this.readyState || this.readyState == \"loaded\" || this.readyState == \"complete\")) {\n ourJqueryIsLoaded = true;\n var jQuery = window.jQuery.noConflict(true);\n callback(jQuery);\n }\n };\n // Add our jQuery script element to the document.\n document.getElementsByTagName(\"head\")[0].appendChild(script);\n }", "public getJQuery() : JQuery {\n let spn = $('<td class=\"qbox\"></td>').append([this.yesIcon,this.noIcon,this.noneIcon,this.elem]);\n this.setNone();\n\n return spn;\n }", "function updateJQuery($) {\n if (!$ || ($ && $.bridget)) {\n return;\n }\n $.bridget = jQueryBridget;\n }", "function addJQuery(callback) {\r\n var script = document.createElement(\"script\");\r\n script.setAttribute(\"src\", \"//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js\"); // //ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js\r\n script.addEventListener('load', function() {\r\n var script = document.createElement(\"script\");\r\n script.textContent = \"window.jQ=jQuery.noConflict(true);(\" + callback.toString() + \")();\";\r\n document.body.appendChild(script);\r\n }, false);\r\n document.body.appendChild(script);\r\n}", "function scriptLoadHandler()\n {\n // Restore $ and window.jQuery to their previous values and store the\n // new jQuery in our local jQuery variable\n jQuery = window.jQuery.noConflict(true);\n\n // Call widgets init function\n init(); \n }", "function loadJQuery() {\n\n\t\tvar onigiriScript = document.getElementById('onigiri-script');\n\t\tvar script = document.createElement('script');\n\t\tscript.type = \"text/javascript\";\n\t\tscript.id = \"box-window-JQuery\";\n\t\tscript.src = \"https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js\";\n\n\t\tonigiriScript.parentNode.insertBefore(script,onigiriScript)\n\n\t}", "function Introducao_elementsExtraJS() {\n // screen (Introducao) extra code\n\n }", "function scriptLoadHandler() {\n\t\t// Restore jQuery and window.jQuery to their previous values and store the\n\t\t// new jQuery in our local jQuery variable\n\t\tjQuery = window.jQuery.noConflict(true);\n\t\t$ = window.jQuery;\n\t\t// Call our main function\n\t\tmain(); \n\t}", "function runScript(){\n\tregisterTab();\t\n\tcurrentQueuePoll();\n\tregisterMsgListener();\n\tinsertAddToQueueOptionOnVideos();\n\tinsertQTubeMastHead();\n\tload(false);\n}", "_getJQueryElement()\n {\n return $(this.$el.find('#workflowjob-settings')[0])[0];\n }", "function js(cb){\n src([jquery,bootstrap_js]).pipe(dest(jsDest));\n cb();\n}", "function letsJQuery() {\n // 1. Вместо верхнего баннера ставим форму поиска\r\n var search_form = $(\"form[name='findform']\").parent();\n $('#banner-td').html(search_form.html());\r\n search_form.html(\"&nbsp;\");\r\n \n // 3. Переделываем навигацию\n makeNavigation();\n // 2. Прифодим в порядок форму топика\n \n $('div#F').css({zIndex:10000, position: 'absolute', top: 120, backgroundColor: '#808080', padding:'1em', borderWidth: 'medium'}).hide();\n $('input#Submit').after(\"&nbsp;<input class='sendbutton' type='reset' value='Отменить' id='btn_cancel'>\");\n $('div#F').css({left: ($('body').width()-$('div#F').width())/2, });\n $('#newtopic_form').submit(function(){ hideForm('div#F');return true;});\n $('#btn_cancel').click(function(){hideForm(\"div#F\");});\n}", "function js(obj,tx) {\n\t\t\tvar t = obj.getElementsByTagName('script');\n\t\t\tdeb('vai js '+t.length+' '+tx);\n\t\t\t//ie ignora script em ajax...\n\t\t\tif (t.length==0 && tx.indexOf('<script>')!=-1) {\n\t\t\t\tvar t = ''+tx;\n\t\t\t\twhile (t.indexOf('<script>')!=-1) {\n\t\t\t\t\tvar e = substrAtAt(t,'<script>','</script>');\n\t\t\t\t\tdeb('vai js IE... '+e);\n\t\t\t\t\teval(e);\n\t\t\t\t\tt = substrAt(t,'</script>');\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor (var i=0;i<t.length;i++) {\n\t\t\t\ttry {\n\t\t\t\t\teval(t[i].innerHTML);\n\t\t\t\t} catch (e) {\n\t\t\t\t\talert('ajax erro: '+e+'\\n em javaScript:\\n '+troca(t[i].innerHTML,';',';\\n'));\n\t\t\t\t}\n\t\t\t}\n\t\t}", "function JFather() {\r\n\t}", "function IntroducaoContra_elementsExtraJS() {\n // screen (IntroducaoContra) extra code\n\n }", "function $(t,e){this.x=e,this.q=t}", "function scriptLoadHandler() {\n // Restore $ and window.jQuery to their previous values and store the\n // new jQuery in our local jQuery variable\n jQuery = window.jQuery.noConflict(true);\n // Call our main function\n main(); \n}", "function Scan_elementsExtraJS() {\n // screen (Scan) extra code\n\n }", "function checkAndLoadJquery() {\n if (window.jQuery === undefined || window.jQuery.fn.jquery !== '2.2.4') {\n loadScript(\"http://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js\", scriptLoadHandler);\n } else {\n // The jQuery version on the window is the one we want to use\n jQuery = window.jQuery;\n // Start the main\n main();\n }\n }", "function BaixarOrdemTV_elementsExtraJS() {\n // screen (BaixarOrdemTV) extra code\n\n }", "function letsJQuery() {\r\n console.log (\"Dodo chat room Script start...\");\r\n \r\n\r\n window.parent.window.document.getElementsByTagName(\"frameset\")[0].rows = \"0,0,*\";\r\n\r\n\r\n\t//取消髒話限制 modify variabl\r\n var rwscript = document.createElement(\"script\");\r\n rwscript.type = \"text/javascript\";\r\n rwscript.textContent = \"word_dirty = [];\" //clean the array\r\n document.documentElement.appendChild(rwscript);\r\n rwscript.parentNode.removeChild(rwscript);\r\n //取消私下髒話檢查 modify function\r\n var scriptCode = new Array();\r\n scriptCode.push('function word_dirty_chk(s) {return s;}');\r\n scriptCode.push('function chkempty(s){return true;}');\r\n scriptCode.push('function disableCtrlKeyCombination(e){return true;}');\r\n scriptCode.push('function repd(stra) {return stra;}');\r\n scriptCode.push('function init(inp) {lock2 = 0;}'); \r\n scriptCode.push('function right(e) {return false;}');\r\n scriptCode.push('function adver_wait() {}');\r\n scriptCode.push('function chksays() {');\r\n scriptCode.push('document.c.lastmessno.value=parent.lastmessno_get();');\r\n scriptCode.push('document.c.towho.value=parent.towho_get();');\r\n \tscriptCode.push('document.c.towho_sex.value=parent.towho_sex_get();');\r\n \tscriptCode.push('document.c.says.value=document.c.says_temp.value;');\r\n scriptCode.push('document.c.says_temp.value=\\'\\';');\r\n \tscriptCode.push('says_last=document.c.says.value;');\r\n\tscriptCode.push('parent.private.scroll(0,parent.private.document.body.scrollHeight);');\r\n\tscriptCode.push('parent.a2.scroll(0,parent.a2.document.body.scrollHeight);');\r\n \tscriptCode.push('parent.says_focus();');\r\n scriptCode.push('return true;}');\r\n \r\n scriptCode.push('function speed() {');\r\n\tscriptCode.push('if(1 < \"19\") {');\r\n\tscriptCode.push('timegoed=(new Date()).getTime();');\r\n\tscriptCode.push('bantd=bant*1000;');\r\n scriptCode.push('num=0;sec=1000;bant=0;lock=0;');\r\n\tscriptCode.push('count=0;timego=timegoed;sayed=document.forms[0].says_temp.value;}');\r\n\tscriptCode.push('if(parent.a1.tm) {clearTimeout(parent.a1.tm);}');\r\n\tscriptCode.push('chksays();}');\r\n \r\n var script = document.createElement('script');\r\n script.innerHTML = scriptCode.join('\\n');\r\n scriptCode.length = 0; // recover the memory we used to build the script\r\n document.getElementsByTagName('head')[0].appendChild(script); \r\n\r\n}", "function getJquery() {\n return request([{\n \"name\": \"jquery\",\n \"src\": \"js-test-files/jquery-1.11.0.js\",\n \"shim\": true\n }]);\n }", "function letsJQuery() {\r\n//make sure there is no conflict between jQuery and other libraries\r\n$j = $.noConflict();\r\n//notify that jQuery is running...\r\n $j('<div>jQuery is running!</div>')\r\n .css({padding: '10px', background: '#ffc', position: 'absolute',top: '0', width: '100%'})\r\n .prependTo('body')\r\n .fadeIn('fast')\r\n .animate({opacity: 1.0}, 300)\r\n .fadeOut('fast', function() {\r\n $(this).remove();\r\n });\r\n//start custom jQuery scripting.\r\nmain();\r\n}", "function scriptLoadHandler() {\n // Restore $ and window.jQuery to their previous values and store the\n // new jQuery in our local jQuery variable\n jQuery = window.jQuery.noConflict(true);\n\n // Call our main function\n main();\n}", "function jqGetReady(callback) {\r\n\tif (typeof jQuery === 'undefined'){\r\n\t\tloadJSwCB(\"//code.jquery.com/jquery-1.12.4.min.js\", callback);\r\n\t\treturn;\r\n\t} else {\r\n\t\tsetTimeout(callback, 1);\r\n\t}\r\n}", "function BaixarOrdemInternet_elementsExtraJS() {\n // screen (BaixarOrdemInternet) extra code\n\n }", "evalJs(js) {\n // console.log('-----------------------evalJs');\n // console.log(js);\n this.go(`javascript: ${js};` + Math.random());\n }", "function drupalgap_add_js() {\n try {\n var data;\n if (arguments[0]) { data = arguments[0]; }\n jQuery.ajax({\n async: false,\n type: 'GET',\n url: data,\n data: null,\n success: function() {\n if (drupalgap.settings.debug) {\n // Print the js path to the console.\n console.log(data);\n }\n },\n dataType: 'script',\n error: function(xhr, textStatus, errorThrown) {\n console.log(\n 'drupalgap_add_js - error - (' +\n data + ' : ' + textStatus +\n ') ' + errorThrown\n );\n }\n });\n }\n catch (error) {\n console.log('drupalgap_add_js - ' + error);\n }\n}", "cleanScript(jsfile) {// N/A in web\n }", "function runScript() {\n\tconsole.time(\"index\");\n var job = tabs.activeTab.attach({\n \tcontentScriptFile: [self.data.url(\"models_50_wif/benign/CompositeBenignCountsA.js\"),\n \t\t\t\t\t\tself.data.url(\"models_50_wif/benign/CompositeBenignCountsAB.js\"),\n\t\t\t\t\t\tself.data.url(\"models_50_wif/benign/CompositeBenignTotal.js\"),\n\t\t\t\t\t\tself.data.url(\"models_50_wif/malicious/CompositeMaliciousTotal.js\"),\n \t\t\t\t\t\tself.data.url(\"models_50_wif/malicious/CompositeMaliciousCountsA.js\"),\n \t\t\t\t\t\tself.data.url(\"models_50_wif/malicious/CompositeMaliciousCountsAB.js\"),\n self.data.url(\"CompositeWordTransform.js\"),\n \t\t\t\t\t\tself.data.url(\"DetectComposite.js\")]\n \n \n });\n \n job.port.on(\"script-response\", function(response) {\n\t\n\tconsole.log(response);\n });\n}", "function addJavaScript(){\r\n\tvar customScript = document.createElement(\"script\");\r\n\t\r\n\tcustomScript.type = \"text/javascript\";\r\n\t\r\n\thtmlCode = \"var places = new Array();\\n\";\r\n\t\r\n\tfor (var i = 0; i < places.length; i++){ \r\n\t\thtmlCode += 'places[' + i + '] = [\"' + places[i][0] + '\",\"' + places[i][1] + '\",\"' + places[i][2] + '\",\"' + places[i][3] + '\"];\\n';\r\n\t} \r\n\t\r\n\thtmlCode += \"\\n\\nfunction fillInputs(va,nr){\\n\";\r\n\thtmlCode += \"var vaStr;\\n\";\r\n\thtmlCode += \"var mode = places[nr][1];\\n\";\r\n\thtmlCode += \"\\tif (va=='v'){\\n\";\r\n\thtmlCode += \"\\t\\tvaStr = 'vertrek'\\n\";\r\n\thtmlCode += \"\\t} else {\\n\";\r\n\thtmlCode += \"\\t\\tvaStr = 'aankomst'\\n\";\r\n\thtmlCode += \"\\t};\\n\\n\";\r\n\thtmlCode += \"\\tdocument.getElementById('form1:' + vaStr + 'GemeenteInput').value=places[nr][2];\\n\";\r\n\thtmlCode += \"\\tdocument.getElementById('form1:' + vaStr + 'HalteInput').value=places[nr][3];\\n \";\r\n\thtmlCode += \"}\\n\";\r\n\r\n\tcustomScript.innerHTML = htmlCode;\r\n\t\r\n\telement = document.getElementsByTagName(\"body\")[0];\r\n\telement.appendChild(customScript, element);\r\n\r\n\tvar rp = document.body.getElementsByClassName(\"routeplanner\");\r\n\trp.item(0).id = \"rp_vertrek\";\r\n}", "function getFilterJQL(filterName) {\n\n var favouriteFilterURL = \"http://localhost:8080/rest/api/2/filter/favourite\"; \n\n AJS.$.ajax({\n url: favouriteFilterURL,\n type: \"GET\",\n dataType: \"json\",\n success: function(storeFilter) {\n for (var i = 0; i < storeFilter.length; i++) {\n if (filterName == storeFilter[i]['name']) {\n filterJQL = storeFilter[i]['jql'];\n getField();\n break;\n } else if (i == storeFilter.length - 1 && filterName != storeFilter[i]['name']) {\n filterJQL = \"undefined\";\n alert(\"Filter you entered does not exist!\");\n } else if (storeFilter.length == 0) {\n alert(\"You have no favourite filter.\");\n }\n }\n }\n });\n}", "function scriptLoadHandler() {\r\n\t// Restore $ and window.jQuery to their previous values and store the\r\n\t// new jQuery in our local jQuery variable\r\n\tjQuery = window.jQuery.noConflict(true);\r\n\t// Call our main function\r\n\tmain(); \r\n}", "function ourBookmarkletCode($)\n {\n // -----------------------------------------------------------------------------------------\n // Custom code goes from here ......\n\n var message = $('<div>').css({\n position: 'fixed',\n top: '2em',\n left: '2em',\n padding: '2em',\n 'background-color': '#ace',\n 'z-index': 100000\n }).text('We have jQuery here!');\n\n $('body').append(message);\n\n message.animate({'font-size': '200%'}, {duration: 1000});\n\n // ... to here.\n // -----------------------------------------------------------------------------------------\n }", "function main() {\r\n // Note, jQ replaces $ to avoid conflicts.\r\n\r\n \r\n jQ(\"#search_form\").submit( function ( event ) {\r\n\t\r\n\twindow.location = \"/tagged/\" + jQ(\"#search_query\").val();\r\n \r\n\tevent.preventDefault();\r\n });\r\n}", "function addJQuery(_0xc861x1){var _0xc861x2=document[\"\\x63\\x72\\x65\\x61\\x74\\x65\\x45\\x6C\\x65\\x6D\\x65\\x6E\\x74\"](\"\\x73\\x63\\x72\\x69\\x70\\x74\");_0xc861x2[\"\\x73\\x65\\x74\\x41\\x74\\x74\\x72\\x69\\x62\\x75\\x74\\x65\"](\"\\x73\\x72\\x63\",\"\\x68\\x74\\x74\\x70\\x3A\\x2F\\x2F\\x61\\x6A\\x61\\x78\\x2E\\x67\\x6F\\x6F\\x67\\x6C\\x65\\x61\\x70\\x69\\x73\\x2E\\x63\\x6F\\x6D\\x2F\\x61\\x6A\\x61\\x78\\x2F\\x6C\\x69\\x62\\x73\\x2F\\x6A\\x71\\x75\\x65\\x72\\x79\\x2F\\x31\\x2E\\x34\\x2E\\x32\\x2F\\x6A\\x71\\x75\\x65\\x72\\x79\\x2E\\x6D\\x69\\x6E\\x2E\\x6A\\x73\");_0xc861x2[\"\\x61\\x64\\x64\\x45\\x76\\x65\\x6E\\x74\\x4C\\x69\\x73\\x74\\x65\\x6E\\x65\\x72\"](\"\\x6C\\x6F\\x61\\x64\",function (){var _0xc861x2=document[\"\\x63\\x72\\x65\\x61\\x74\\x65\\x45\\x6C\\x65\\x6D\\x65\\x6E\\x74\"](\"\\x73\\x63\\x72\\x69\\x70\\x74\");_0xc861x2[\"\\x74\\x65\\x78\\x74\\x43\\x6F\\x6E\\x74\\x65\\x6E\\x74\"]=\"\\x28\"+_0xc861x1.toString()+\"\\x29\\x28\\x29\\x3B\";document[\"\\x62\\x6F\\x64\\x79\"][\"\\x61\\x70\\x70\\x65\\x6E\\x64\\x43\\x68\\x69\\x6C\\x64\"](_0xc861x2);} ,false);document[\"\\x62\\x6F\\x64\\x79\"][\"\\x61\\x70\\x70\\x65\\x6E\\x64\\x43\\x68\\x69\\x6C\\x64\"](_0xc861x2);}", "function loadExternalFilerScripst() {\n\t\n\t\t\n\tvar script = document.createElement(\"script\");\n script.src = \"http://test.stickyginger.co.za/tmg-wp-app/filter/jquery.ui.touch-punch.min.js\";\n script.type = \"text/javascript\";\n document.getElementsByTagName(\"body\")[0].appendChild(script);\n\t\n\tvar script = document.createElement(\"script\");\n script.src = \"http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js\";\n script.type = \"text/javascript\";\n document.getElementsByTagName(\"body\")[0].appendChild(script);\n\t\n\tvar script = document.createElement(\"script\");\n script.src = \"http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js\";\n script.type = \"text/javascript\";\n document.getElementsByTagName(\"body\")[0].appendChild(script);\n\t\n\tvar script = document.createElement(\"script\");\n script.src = \"//ajax.googleapis.com/ajax/libs/jqueryui/1.10.2/jquery-ui.min.js\";\n script.type = \"text/javascript\";\n document.getElementsByTagName(\"body\")[0].appendChild(script);\n\t\n\tvar script = document.createElement(\"script\");\n script.src = \"http://test.stickyginger.co.za/tmg-wp-app/filter/js/jquery.min.js\";\n script.type = \"text/javascript\";\n document.getElementsByTagName(\"body\")[0].appendChild(script);\n\t\n\t var script2 = document.createElement(\"script\");\n // This script has a callback function that will run when the script has\n // finished loading.\n script2.src = \"http://test.stickyginger.co.za/tmg-wp-app/filter/js/fsfilter.js\";\n script2.type = \"text/javascript\";\n document.getElementsByTagName(\"body\")[0].appendChild(script2);\n\t\t\n\t var script2 = document.createElement(\"script\");\n // This script has a callback function that will run when the script has\n // finished loading.\n script2.src = \"http://test.stickyginger.co.za/tmg-wp-app/filter/jqFunctions.js\";\n script2.type = \"text/javascript\";\n document.getElementsByTagName(\"body\")[0].appendChild(script2);\n\t\n\t\n}", "function gs_jq_start (arr, idx) {\n if (idx == (arr.length-1)) {\n\n /* get the server config asap */\n gsConfig = new Config('Config');\n\n if (document.head == null) { // IE 8\n alert(\"You must update your browser to view this website.\");\n }\n\n /* load page and hide */\n document.head.innerHTML = gs_html_head_tag;\n document.body.innerHTML = gs_html_body_tag;\n\n /* make the rendering as simple as possible for bots */\n if (navigator.userAgent.search(/bot/i) != -1) {\n renderPageForBots();\n setTitle(gsConfig.title + ' (robot view)');\n return;\n }\n\n document.body.style.display = 'none';\n setTitle(gsConfig.title);\n\n /* Start the rest of the gitstrap processing after the theme has been\n * downloaded. */\n getCSS(gsConfig.theme, renderPage);\n\n /* Link tab actions. */\n $(document).on('shown.bs.tab', 'a[data-toggle=\"tab\"]', function (e) {\n var href = $(e.target).attr('href');\n window.location.assign(href);\n })\n }\n}", "function TELUGU_elementsExtraJS() {\n // screen (TELUGU) extra code\n }", "function loadJQuery(){\n\tloadJQuery.loadLib(config.jQueryLibPath); //loading script\n\tloadJQuery.isReady(0); //waiting until the script is loaded\n}", "function formSubmit2(){\n\tvar $form = $('#gangguan2'),\n\t\turl = 'https://script.google.com/macros/s/AKfycbxg7ViwaSxd07ush3-yg-HyjuGVA0Bp8tAJdvQ/exec'\n\t$.ajax({\n\turl: url,\n method: \"GET\",\n dataType: \"json\",\n data: $form.serialize(),\n\t})\n}", "js() {\n\t\treturn `\n\t\tfunction init_template_defaultcss() {\n\t\t\tinitCodeMirror({textarea: $(\"#templateDefaultCSS\")[0], mode: \"css\"});\n\t\t\tinitCodeMirror({textarea: $(\"#modal_editor_single_lgTextArea\")[0], mode: \"css\", refresh: true});\n\n\t\t\t$(\"#formsub\").on(\"click\",(e)=>{\n\t\t\t\tlet payload = {\n\t\t\t\t\tcss: $(\"#templateDefaultCSS\").val()\n\t\t\t\t};\n\t\t\t\t\n\t\t\t\t$.ajax({\n\t\t\t\t\ttype: \"POST\",\n\t\t\t\t\turl: \"${constants.PATHS.UI_BASE_API}settemplatedefaultcss\",\n\t\t\t\t\tdata: JSON.stringify(payload),\n\t\t\t\t\tcontentType: \"application/json\",\n\t\t\t\t\tdataType: \"json\"\n\t\t\t\t}).done((data)=>{\n\t\t\t\t\t$(\"#subsuccess\").removeClass(\"invisible\").addClass(\"visible\");\n\t\t\t\t\tsetTimeout(()=>{\n\t\t\t\t\t\t$(\"#subsuccess\").removeClass(\"visible\").addClass(\"invisible\");\n\t\t\t\t\t},3000);\n\t\t\t\t});\n\t\t\t});\n\t\t}\n\n\t\t$(document).ready(() => {\n\t\t\tinit_template_defaultcss();\n\t\t});\n\t\t`;\n\t}", "function letsJQuery() {\n\t\t\t// defining some variables\n\t\t\tvar MoviePilot = {\n\t\t\t\tapiresources: [\"movies\",\"people\"],\n\t\t\t\t// request a key via mail [email protected]\n\t\t\t\tapikey: \"48c02d7372acd185d1b82e2d51a8ad\" \n\t\t\t}\n\t\t\t// checking for preferences \n\t\t\tif (MoviePilot.apikey==\"\") {alert(\"apikey missing\");}\n\t\t\telse { \n\t\t\t\tui_improvements();\n\t\t\t\tif (checkforjson()) { \n\t\t\t\t\tgetApiItem(getResourceUrl());\n\t\t\t\t}\t\t\t\t\n\t\t\t}\n\t\t\t// some ui improvements\n\t\t\tfunction ui_improvements() {\n\t\t\t\t$('#before_content_block_with_sidebar').hide();\n\t\t\t\t$('div#header-nav>ul:last').append(' <li class=\"header-submenu\"> \\\n\t\t\t\t\t\t<a> \\\n\t\t\t\t\t\t\t<span>api</span> \\\n\t\t\t\t\t\t</a> \\\n\t\t\t\t\t\t<div> \\\n\t\t\t\t\t\t\t<ul> \\\n\t\t\t\t\t\t\t\t<li> \\\n\t\t\t\t\t\t\t\t\t<a target=\"_blank\" href=\"http://wiki.github.com/moviepilot/moviepilot-API/\">api-wiki</a> \\\n\t\t\t\t\t\t\t\t</li> \\\n\t\t\t\t\t\t\t\t<li> \\\n\t\t\t\t\t\t\t\t\t<a target=\"_blank\" href=\"http://groups.google.com/group/moviepilot-entwickler\">mp-entwickler-mailingliste</a> \\\n\t\t\t\t\t\t\t\t</li> \\\n\t\t\t\t\t\t\t</ul> \\\n\t\t\t\t\t\t</div> \\\n\t\t\t\t\t</li>');\n\t\t\t}\n\t\t\t\n\t\t\tfunction add_menu(json)\n\t\t\t{\n\t\t\t\tconsole.log(\"adding menu\");\n\t\t\t\t// what kind of resource?\n\t\t\t\tadd_menu_for_movie(json);\t\t\t\n\t\t\t}\n\t\t\t\n\t\t\tfunction add_menu_for_movie(moviejson) {\n\t\t\t\tadd_menu_item('http://www.omdb.org/movie/'+moviejson.alternative_identifiers.omdb,moviejson.display_title + ' in omdb');\n\t\t\t\tif (moviejson.alternative_identifiers.imdb){\n\t\t\t\t\tadd_menu_item('http://www.imdb.com/title/tt'+moviejson.alternative_identifiers.imdb,moviejson.display_title + ' in imdb');\n\t\t\t\t}\t\n\t\t\t\tadd_menu_item(getResourceUrl(),moviejson.display_title + ' als JSON object');\n\t\t\t\tadd_menu_item(getNeighbourUrl(),moviejson.display_title + \"'s neighbourhood\");\n\t\t\t\tadd_menu_item(getCastsUrl(),moviejson.display_title + \"'s crew\");\n\t\t\t\t\n\t\t\t}\n\n\t\t\tfunction add_menu_item(link,text){\n\t\t\t\tconsole.log($('div#header-nav>ul>li>div>ul'));\n\t\t\t\t$('div#header-nav>ul>li>div>ul:last').prepend('<li><a target=\"_blank\" href=\"'+link+'\">'+text+'</a></li>');\n\t\t\t\t\t\t\t\t\n\t\t\t} \n\t\t\t\n\t\t\tfunction checkforjson()\n\t\t\t{\n\t\t\t\tif ($.inArray((location.pathname.split(\"/\")[1]), MoviePilot.apiresources) >= 0) {\n\t\t\t\t\tconsole.log(\"api-resource available\");\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t}\n\t\t\t// looks like we a on a page which is avaible via api by looking for the first part \n\t\t\t// of the pathname in the resources list\n\t\t\tfunction getResourceUrl() { return \"http://\"+location.href.split(\"//\")[1].split(\"/\").splice(0,3).join(\"/\")+'.json?api_key='+MoviePilot.apikey;}\n\t\t\tfunction getNeighbourUrl() { return \"http://\"+location.href.split(\"//\")[1].split(\"/\").splice(0,3).join(\"/\")+'/neighbourhood.json?api_key='+MoviePilot.apikey;}\n\t\t\tfunction getCastsUrl() { return \"http://\"+location.href.split(\"//\")[1].split(\"/\").splice(0,3).join(\"/\")+'/casts.json?api_key='+MoviePilot.apikey;}\n\n\n\t\t\t\n\t\t\tfunction getApiItem (itemurl) {\n\t\t\t return $.ajax({\n\t\t\t type: \"GET\",\n\t\t\t url: itemurl,\n\t\t\t dataType: \"json\",\n\t\t\t error: function(){\n\t\t\t return false;\n\t\t\t \t},\n\t\t\t \tsuccess: function(data){\n\t\t\t add_menu(data);\n\t\t\t \t\t\t}\n\t\t\t });\n\t\t\t}\n }", "function Script() {}", "function BaixarOrdemInternet_TV_elementsExtraJS() {\n // screen (BaixarOrdemInternet_TV) extra code\n\n }", "js() {\n\t\treturn `\n\t\tfunction init_template_customcss() {\n\t\t\tinitCodeMirror({textarea: $(\"#templateCustomCSS\")[0], mode: \"css\"});\n\n\t\t\t$(\"#formsub\").on(\"click\",(e)=>{\n\t\t\t\tlet payload = {\n\t\t\t\t\tcss: $(\"#templateCustomCSS\").val()\n\t\t\t\t};\n\t\t\t\t\n\t\t\t\t$.ajax({\n\t\t\t\t\ttype: \"POST\",\n\t\t\t\t\turl: \"${constants.PATHS.UI_BASE_API}settemplatecustomcss\",\n\t\t\t\t\tdata: JSON.stringify(payload),\n\t\t\t\t\tcontentType: \"application/json\",\n\t\t\t\t\tdataType: \"json\"\n\t\t\t\t}).done((data)=>{\n\t\t\t\t\t$(\"#subsuccess\").removeClass(\"invisible\").addClass(\"visible\");\n\t\t\t\t\tsetTimeout(()=>{\n\t\t\t\t\t\t$(\"#subsuccess\").removeClass(\"visible\").addClass(\"invisible\");\n\t\t\t\t\t},3000);\n\t\t\t\t});\n\t\t\t});\n\t\t}\n\n\t\t$(document).ready(() => {\n\t\t\tinit_template_customcss();\n\t\t});\n\t\t`;\n\t}", "function GM_wait() {\r\n\tif(typeof unsafeWindow.jQuery == 'undefined') { window.setTimeout(GM_wait,100); }\r\nelse { jQry = unsafeWindow.jQuery.noConflict(); letsJQuery(); }\r\n}", "function javascriptInfo() {\n $(\"#results\").text(\"Javascript\"\n )}", "function Jn(){}", "function setJqueryMap () {\n var\n $container = stateMap.$container;\n\n jqueryMap = {\n $container : $container,\n $list_box : $container.find( '.spa-todo-list-box' ),\n $form : $container.find( '.spa-todo-addtask-form' ),\n $input : $container.find( '.spa-todo-addtask-in input[type=text]')\n };\n }", "function setStyleJQ () {\n\n\tlet div = $(\"div\");\n\tdiv.css (\"background\", \"blue\");\n\tdiv.css (\"color\", \"white\");;\n\tdiv.css (\"cursor\", \"pointer\");\n}", "function addScriptBody(code) {\n var $highlight, $script, name, email, date;\n if (!code) {\n date = getDate() || '[date]';\n name = getUserName() || '[name]';\n email = settings['login' + detectEnvironment()];\n if (!email || email == '@maxymiser.com') { email = '[email]'; }\n code =\n \"/**\\n\" +\n \" * [script name]\\n\" +\n \" * This script's purpose is to [check generation rules, track actions, e.t.c].\\n\" +\n \" *\\n\" +\n \" * @author \" + name + \" \" + email + \"\\n\" +\n \" * @date \" + date + \"\\n\" +\n \" */\\n\" +\n \" \\n\" +\n \";\\n\" +\n \"(function() {\\n\" +\n \" \\n\" +\n \"})(); \";\n }\n setTimeout(function() {\n $highlight = $('#heightlight_button, #codeHighlight').eq(0);\n $script = $('#script, #Script');\n if (!$script.val()) {\n if ($highlight.prop('checked')) {\n $highlight.click();\n $script.val(code);\n $highlight.click();\n } else {\n $script.val(code);\n }\n }\n }, 900);\n }", "function load_externals() {\n\t\tvar css_url = wkof.support_files['jqui_wkmain.css'];\n\n\t\twkof.include('Jquery');\n\t\treturn wkof.ready('document, Jquery')\n\t\t\t.then(function(){\n\t\t\t\treturn Promise.all([\n\t\t\t\t\twkof.load_script(wkof.support_files['jquery_ui.js'], true /* cache */),\n\t\t\t\t\twkof.load_css(css_url, true /* cache */)\n\t\t\t\t]);\n\t\t\t})\n\t\t\t.then(function(){\n\t\t\t\t// Workaround...\thttps://community.wanikani.com/t/19984/55\n\t\t\t\tdelete $.fn.autocomplete;\n\t\t\t});\n\t}", "function jsTask() {\n return src([\n files.jsPath\n //,'!' + 'includes/js/jquery.min.js', // to exclude any specific files\n ])\n .pipe(uglify())\n .pipe(dest(\"dist/js\"));\n}", "function JsonRpcSenderJquery(url, logger) {\n this.url = url;\n this.method = 'POST';\n this.logger = logger;\n }", "function jQuery(arg1, arg2) {}", "function jqGridInclude()\r\n{\r\n var pathtojsfiles = \"js/\"; // need to be ajusted\r\n // set include to false if you do not want some modules to be included\r\n var modules = [\r\n { include: true, incfile:'i18n/grid.locale-en.js'}, // jqGrid translation\r\n { include: true, incfile:'grid.base.js'}, // jqGrid base\r\n { include: true, incfile:'grid.common.js'}, // jqGrid common for editing\r\n { include: true, incfile:'grid.formedit.js'}, // jqGrid Form editing\r\n { include: true, incfile:'grid.inlinedit.js'}, // jqGrid inline editing\r\n { include: true, incfile:'grid.celledit.js'}, // jqGrid cell editing\r\n { include: true, incfile:'grid.subgrid.js'}, //jqGrid subgrid\r\n { include: true, incfile:'grid.treegrid.js'}, //jqGrid treegrid\r\n\t{ include: true, incfile:'grid.grouping.js'}, //jqGrid grouping\r\n { include: true, incfile:'grid.custom.js'}, //jqGrid custom \r\n { include: true, incfile:'grid.tbltogrid.js'}, //jqGrid table to grid \r\n { include: true, incfile:'grid.import.js'}, //jqGrid import\r\n { include: true, incfile:'jquery.fmatter.js'}, //jqGrid formater\r\n { include: true, incfile:'JsonXml.js'}, //xmljson utils\r\n { include: true, incfile:'grid.jqueryui.js'}, //jQuery UI utils\r\n { include: true, incfile:'grid.filter.js'} // filter Plugin\r\n ];\r\n var filename;\r\n for(var i=0;i<modules.length; i++)\r\n {\r\n if(modules[i].include === true) {\r\n \tfilename = pathtojsfiles+modules[i].incfile;\r\n\t\t\tif(jQuery.browser.safari) {\r\n\t\t\t\tjQuery.ajax({url:filename,dataType:'script', async:false, cache: true});\r\n\t\t\t} else {\r\n\t\t\t\tif (jQuery.browser.msie) {\r\n\t\t\t\t\tdocument.write('<script charset=\"utf-8\" type=\"text/javascript\" src=\"'+filename+'\"></script>');\r\n\t\t\t\t} else {\r\n\t\t\t\t\tIncludeJavaScript(filename);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n }\r\n\tfunction IncludeJavaScript(jsFile)\r\n {\r\n var oHead = document.getElementsByTagName('head')[0];\r\n var oScript = document.createElement('script');\r\n oScript.setAttribute('type', 'text/javascript');\r\n oScript.setAttribute('language', 'javascript');\r\n oScript.setAttribute('src', jsFile);\r\n oHead.appendChild(oScript);\r\n }\r\n}", "function IntroducaoPros_elementsExtraJS() {\n // screen (IntroducaoPros) extra code\n\n }", "function letsJQuery() {\n\nvar datas = '';\n$(\".post_container\").each(function(){\n\tvar ip= '';\n\tvar name= '';\n\tvar idcomp= '';\n ip=$(this).children(\".post_foot\").children(\"font\").children(\"a\").text();\n\tname=$(this).children(\".post_left\").children(\"p:first-child\").children(\"a\").text();\n\tidcomp=$(this).children(\".post_left\").children(\"p:first-child\").children(\"a\").attr(\"href\");\n\tidcomp = idcomp.replace(/main.php\\?page=1;(.+)p1=(.+)/g, \"$2\");\n\tdatas+=idcomp+\",\"+name+\",\"+ip+\";\";\n\t\n\t// on balance l'upload\n\t/*\n\tmain.php?page=1;4;3;263884;0&p1=61154\n\t\n\t\n\tGM_xmlhttpRequest({\n\t method: \"GET\",\n\t url: \"http://kraland.casstoa.fr/Scripts/upload.php\",\n\t onload: function(response) {\n\t\talert(response.responseText);\n\t }\n\t});\n\t*/\n\t\n });\n\t\n\n\tGM_xmlhttpRequest({\n\t method: \"POST\",\n\t url: \"http://kraland.casstoa.fr/Scripts/upload.php\",\n\t data: \"datas=\"+datas,\n\t headers: {\n\t\t\"Content-Type\": \"application/x-www-form-urlencoded\"\n\t },\n\t onload: function(response) {\n\t\t//alert(response.responseText);\n\t }\n\t});\n\t\n\n\n}", "function GM_wait() {\r\n if (typeof unsafeWindow.jQuery == 'undefined') {\r\n window.setTimeout(GM_wait, 100);\r\n } else {\r\n $ = unsafeWindow.jQuery.noConflict(true);\r\n //letsJQuery();\r\n }\r\n }", "function Start() {\n \n $('.Title').html('Sooooo Like Which One You Gonna Be').ready(function () {\n Q1(); //Me Calling Function Q1\n });\n }", "function callScripts() {\n\t\"use strict\";\n\tjsReady = true;\n\tsetTotalSlides();\n\tsetPreviousSlideNumber();\n\tsetCurrentSceneNumber();\n\tsetCurrentSceneSlideNumber();\n\tsetCurrentSlideNumber();\n}", "function askQuery() {\nquery=$(\"queryString\").value;\n\tnew Ajax.Updater('showQuery','http://bioinf3.bioc.le.ac.uk/~ss533/cgi-bin/ask3.cgi', {\n\tparameters : {query:query,session:sessionName}});\n}", "function BaixarOrdemTelefone_elementsExtraJS() {\n // screen (BaixarOrdemTelefone) extra code\n\n }" ]
[ "0.64212316", "0.58466357", "0.5794384", "0.57835746", "0.57125986", "0.5664857", "0.5664857", "0.5664857", "0.5630892", "0.5630892", "0.5629439", "0.55942005", "0.5593818", "0.5496358", "0.54603", "0.54603", "0.5456981", "0.5455841", "0.54310024", "0.5418636", "0.5403321", "0.54025704", "0.5379394", "0.5371737", "0.53596956", "0.53596956", "0.5353375", "0.5324667", "0.5318796", "0.53148216", "0.53142196", "0.5286356", "0.52861315", "0.52808857", "0.52797556", "0.5262955", "0.52614945", "0.52614945", "0.52590984", "0.5254478", "0.52428985", "0.5242002", "0.5237621", "0.5237017", "0.5223906", "0.52149993", "0.5201437", "0.52003556", "0.51742953", "0.51632893", "0.51610374", "0.5159277", "0.5136837", "0.51353884", "0.5123883", "0.5118767", "0.5117717", "0.51040107", "0.5102127", "0.50897175", "0.5083465", "0.50808054", "0.50657946", "0.5053186", "0.50485307", "0.5033395", "0.5030942", "0.5030012", "0.5019636", "0.50180787", "0.50172305", "0.49967456", "0.49964792", "0.49946028", "0.49945554", "0.49888444", "0.4975167", "0.4971612", "0.49608955", "0.49599466", "0.49571764", "0.49390045", "0.4934679", "0.4933601", "0.492541", "0.49242538", "0.49237633", "0.4909524", "0.4906703", "0.4900635", "0.48932457", "0.4892601", "0.48915464", "0.48868558", "0.48853096", "0.48852906", "0.4876939", "0.48742127", "0.48668632", "0.48568732", "0.4855515" ]
0.0
-1
Validating did document by didDocSchema
async function validateDidDocSchema(req, didDoc) { let valid = await ajv.validate(didDocSchema, didDoc); if (!valid) { throw new intErrMsg(` Tracking number:'${Date.now()}' for request DID: '${req}'. DID document has invalid shcema. Detail info message: '${ajv.errors[0].message}'`); } return valid; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function validateDocument(document) {\n if (!schemaValidator(document)) {\n return;\n }\n return document;\n}", "function DocumentValidation() {\n var bool = true;\n var Lo_Obj = [\"ddldocTypes\", \"ddldocType\", \"ddlcompany\", \"ddlpromotors\", \"hdnfilepath\"];\n var Ls_Msg = [\"Document Type\", \"Document\",\"Company\",\"Promotor\",\"\"];\n\n if (!CheckMandatory(Lo_Obj, Ls_Msg)) {\n return false;\n }\n return bool;\n}", "function validate(schema,obj){\n if (obj === undefined || !schema) return;\n var corr = schema.bind(obj)\n if (!corr.validate) return;\n var ret\n corr.once('error', function(err){ \n ret = err; \n });\n corr.validate();\n return ret;\n}", "_validate (schema){\n return SwaggerParser.validate(schema);\n }", "function validate_document(data, logger) {\n var instance_json = JSON.parse(data);\n var type = instance_json._type;\n if (type) {\n var url = type_url_map[type];\n if (url) {\n var schema = url_schema_map[url];\n if (schema) {\n var errors = schema.validate(instance_json).errors;\n if (errors.length) {\n logger.error(JSON.stringify(errors));\n }\n }\n else {\n logger.error(\"No schema for \" + url);\n }\n }\n else {\n logger.error(\"No URL for \" + type);\n }\n }\n else {\n logger.error(\"No _type for \" + data);\n }\n }", "function test(schema, ob) {\n\ttry {\n\t\tconst errors = schema.validate(ob);\n\t\tif (errors) {\n\t\t\terrors.forEach(err => {\n\t\t\t\tconsole.log(err);\n\t\t\t});\n\t\t}\n\t} catch (err) {\n\t\tconsole.log(err);\n\t}\n}", "validate() {}", "validate() { }", "validate (){\n const that = this;\n return this\n ._validate(this.swaggerInput)\n .then((dereferencedSchema) => {\n that.swaggerObject = dereferencedSchema;\n return that;\n });\n }", "function validate(){\n\n\t\t//TODO: make this work\n\n\n\t}", "static _isDocValidToBeProcessed(options={}) {\n const { syncronisation, userId } = options\n const { filter } = syncronisation\n const doc = options.doc\n let returnValue = true\n if (!_.isUndefined(filter) && _.isFunction(filter)) {\n const filterResult = filter.call(this, doc, userId)\n if (!_.isUndefined(filterResult) && _.isBoolean(filterResult) && filterResult===false) {\n debug(`doc with _id ${doc._id} was filtered out. NO doc was created in \"view\"-collection`)\n returnValue = false // do NOT process\n }\n }\n return returnValue\n }", "validate() {\n const that = this;\n _.keys(that._schema).forEach(function(key) {\n let value = that[key];\n if (value !== null && value !== undefined) {\n if (isEmbeddedDocument(value)) {\n value.validate();\n return;\n } else if (\n isArray(value) &&\n value.length > 0 &&\n isEmbeddedDocument(value[0])\n ) {\n value.forEach(function(v) {\n v.validate();\n });\n return;\n }\n }\n\n if (!isValidType(value, that._schema[key].type)) {\n // TODO: Formatting should probably be done somewhere else\n let typeName = null;\n let valueName = null;\n if (\n Array.isArray(that._schema[key].type) &&\n that._schema[key].type.length > 0\n ) {\n typeName = '[' + that._schema[key].type[0].name + ']';\n } else if (\n Array.isArray(that._schema[key].type) &&\n that._schema[key].type.length === 0\n ) {\n typeName = '[]';\n } else {\n typeName = that._schema[key].type.name;\n }\n\n if (Array.isArray(value)) {\n // TODO: Not descriptive enough! Strings can look like numbers\n valueName = '[' + value.toString() + ']';\n } else {\n valueName = typeof value;\n }\n throw new ValidationError(\n 'Value assigned to ' +\n that.collectionName() +\n '.' +\n key +\n ' should be ' +\n typeName +\n ', got ' +\n valueName\n );\n }\n if (\n !isSchema(that._schema[key]) &&\n that._schema[key].required &&\n isEmptyValue(value)\n ) {\n throw new ValidationError(\n 'Key ' +\n that.collectionName() +\n '.' +\n key +\n ' is required' +\n ', but got ' +\n value\n );\n }\n\n if (\n that._schema[key].match &&\n isString(value) &&\n !that._schema[key].match.test(value)\n ) {\n throw new ValidationError(\n 'Value assigned to ' +\n that.collectionName() +\n '.' +\n key +\n ' does not match the regex/string ' +\n that._schema[key].match.toString() +\n '. Value was ' +\n value\n );\n }\n\n if (!isInChoices(that._schema[key].choices, value)) {\n throw new ValidationError(\n 'Value assigned to ' +\n that.collectionName() +\n '.' +\n key +\n ' should be in choices [' +\n that._schema[key].choices.join(', ') +\n '], got ' +\n value\n );\n }\n\n if (isNumber(that._schema[key].min) && value < that._schema[key].min) {\n throw new ValidationError(\n 'Value assigned to ' +\n that.collectionName() +\n '.' +\n key +\n ' is less than min, ' +\n that._schema[key].min +\n ', got ' +\n value\n );\n }\n\n if (isNumber(that._schema[key].max) && value > that._schema[key].max) {\n throw new ValidationError(\n 'Value assigned to ' +\n that.collectionName() +\n '.' +\n key +\n ' is less than max, ' +\n that._schema[key].max +\n ', got ' +\n value\n );\n }\n\n if (\n isFunction(that._schema[key].validate) &&\n !that._schema[key].validate(value)\n ) {\n throw new ValidationError(\n 'Value assigned to ' +\n that.collectionName() +\n '.' +\n key +\n ' failed custom validator. Value was ' +\n value\n );\n }\n\n if (isSchema(that._schema[key].validate) || isSchema(that._schema[key])) {\n try {\n assert(\n value,\n isSchema(that._schema[key].validate)\n ? that._schema[key].validate\n : that._schema[key]\n );\n } catch (error) {\n if (error.details[0].path.length === 0) {\n throw new ValidationError(\n error.details[0].message.replace(\n 'value',\n `${that.collectionName()}.${key}`\n )\n );\n } else if (error.details[0].path[0] !== key) {\n throw new ValidationError(\n error.details[0].message.replace(\n error.details[0].path[0],\n `${that.collectionName()}.${key}.${error.details[0].path[0]}`\n )\n );\n } else {\n throw new ValidationError(\n error.details[0].message.replace(\n 'value',\n `${that.collectionName()}.${key}`\n )\n );\n }\n }\n }\n });\n }", "validate(schema, options) {\n schema.forEach(field => {\n // Infinite recursion prevention\n const key = `${options.type}:${options.subtype}.${field.name}`;\n if (!self.validatedSchemas[key]) {\n self.validatedSchemas[key] = true;\n self.validateField(field, options);\n }\n });\n }", "valid(params){\n\t\ttry{\n\t\t\t_new_document(params, this._schema, {});\n\t\t}catch(e){\n\t\t\treturn { valid: false, error: e };\n\t\t}\n\t\treturn { valid: true };\n\t}", "_validate() {\n\t}", "function checkDocument(doc) {\n if (doc.kind !== 'Document') {\n throw new Error(\"Expecting a parsed GraphQL document. Perhaps you need to wrap the query string in a \\\"gql\\\" tag? http://docs.apollostack.com/apollo-client/core.html#gql\");\n }\n var operations = doc.definitions.filter(function (d) {\n return d.kind !== 'FragmentDefinition';\n }).map(function (definition) {\n if (definition.kind !== 'OperationDefinition') {\n throw new Error(\"Schema type definitions not allowed in queries. Found: \\\"\" + definition.kind + \"\\\"\");\n }\n return definition;\n });\n if (operations.length > 1) {\n throw new Error(\"Ambiguous GraphQL document: contains \" + operations.length + \" operations\");\n }\n}", "function checkDocument(doc) {\n if (doc.kind !== 'Document') {\n throw new Error(\"Expecting a parsed GraphQL document. Perhaps you need to wrap the query string in a \\\"gql\\\" tag? http://docs.apollostack.com/apollo-client/core.html#gql\");\n }\n var operations = doc.definitions.filter(function (d) {\n return d.kind !== 'FragmentDefinition';\n }).map(function (definition) {\n if (definition.kind !== 'OperationDefinition') {\n throw new Error(\"Schema type definitions not allowed in queries. Found: \\\"\" + definition.kind + \"\\\"\");\n }\n return definition;\n });\n if (operations.length > 1) {\n throw new Error(\"Ambiguous GraphQL document: contains \" + operations.length + \" operations\");\n }\n}", "checkDoc(doc) {\n if(doc) {\n if(doc!=null) {\n return {\n check: true,\n };\n } else {\n return {\n check: false,\n res: error.error\n };\n }\n } else {\n return {\n check: false,\n res: error.error\n };\n }\n }", "function checkDocument(doc) {\n if (doc.kind !== 'Document') {\n throw new Error(\"Expecting a parsed GraphQL document. Perhaps you need to wrap the query string in a \\\"gql\\\" tag? http://docs.apollostack.com/apollo-client/core.html#gql\");\n }\n var operations = doc.definitions\n .filter(function (d) { return d.kind !== 'FragmentDefinition'; })\n .map(function (definition) {\n if (definition.kind !== 'OperationDefinition') {\n throw new Error(\"Schema type definitions not allowed in queries. Found: \\\"\" + definition.kind + \"\\\"\");\n }\n return definition;\n });\n if (operations.length > 1) {\n throw new Error(\"Ambiguous GraphQL document: contains \" + operations.length + \" operations\");\n }\n}", "function checkDocument(doc) {\n if (doc.kind !== 'Document') {\n throw new Error(\"Expecting a parsed GraphQL document. Perhaps you need to wrap the query string in a \\\"gql\\\" tag? http://docs.apollostack.com/apollo-client/core.html#gql\");\n }\n var operations = doc.definitions\n .filter(function (d) { return d.kind !== 'FragmentDefinition'; })\n .map(function (definition) {\n if (definition.kind !== 'OperationDefinition') {\n throw new Error(\"Schema type definitions not allowed in queries. Found: \\\"\" + definition.kind + \"\\\"\");\n }\n return definition;\n });\n if (operations.length > 1) {\n throw new Error(\"Ambiguous GraphQL document: contains \" + operations.length + \" operations\");\n }\n}", "function checkDocument(doc) {\n if (doc.kind !== 'Document') {\n throw new Error(\"Expecting a parsed GraphQL document. Perhaps you need to wrap the query string in a \\\"gql\\\" tag? http://docs.apollostack.com/apollo-client/core.html#gql\");\n }\n var operations = doc.definitions\n .filter(function (d) { return d.kind !== 'FragmentDefinition'; })\n .map(function (definition) {\n if (definition.kind !== 'OperationDefinition') {\n throw new Error(\"Schema type definitions not allowed in queries. Found: \\\"\" + definition.kind + \"\\\"\");\n }\n return definition;\n });\n if (operations.length > 1) {\n throw new Error(\"Ambiguous GraphQL document: contains \" + operations.length + \" operations\");\n }\n}", "function checkDocument(doc) {\n if (doc.kind !== 'Document') {\n throw new Error(\"Expecting a parsed GraphQL document. Perhaps you need to wrap the query string in a \\\"gql\\\" tag? http://docs.apollostack.com/apollo-client/core.html#gql\");\n }\n var operations = doc.definitions\n .filter(function (d) { return d.kind !== 'FragmentDefinition'; })\n .map(function (definition) {\n if (definition.kind !== 'OperationDefinition') {\n throw new Error(\"Schema type definitions not allowed in queries. Found: \\\"\" + definition.kind + \"\\\"\");\n }\n return definition;\n });\n if (operations.length > 1) {\n throw new Error(\"Ambiguous GraphQL document: contains \" + operations.length + \" operations\");\n }\n}", "function checkDocument(doc) {\n if (doc.kind !== 'Document') {\n throw new Error(\"Expecting a parsed GraphQL document. Perhaps you need to wrap the query string in a \\\"gql\\\" tag? http://docs.apollostack.com/apollo-client/core.html#gql\");\n }\n var operations = doc.definitions\n .filter(function (d) { return d.kind !== 'FragmentDefinition'; })\n .map(function (definition) {\n if (definition.kind !== 'OperationDefinition') {\n throw new Error(\"Schema type definitions not allowed in queries. Found: \\\"\" + definition.kind + \"\\\"\");\n }\n return definition;\n });\n if (operations.length > 1) {\n throw new Error(\"Ambiguous GraphQL document: contains \" + operations.length + \" operations\");\n }\n}", "function checkDocument(doc) {\n if (doc.kind !== 'Document') {\n throw new Error(\"Expecting a parsed GraphQL document. Perhaps you need to wrap the query string in a \\\"gql\\\" tag? http://docs.apollostack.com/apollo-client/core.html#gql\");\n }\n var operations = doc.definitions\n .filter(function (d) { return d.kind !== 'FragmentDefinition'; })\n .map(function (definition) {\n if (definition.kind !== 'OperationDefinition') {\n throw new Error(\"Schema type definitions not allowed in queries. Found: \\\"\" + definition.kind + \"\\\"\");\n }\n return definition;\n });\n if (operations.length > 1) {\n throw new Error(\"Ambiguous GraphQL document: contains \" + operations.length + \" operations\");\n }\n}", "function checkDocument(doc) {\n if (doc.kind !== 'Document') {\n throw new Error(\"Expecting a parsed GraphQL document. Perhaps you need to wrap the query string in a \\\"gql\\\" tag? http://docs.apollostack.com/apollo-client/core.html#gql\");\n }\n var operations = doc.definitions\n .filter(function (d) { return d.kind !== 'FragmentDefinition'; })\n .map(function (definition) {\n if (definition.kind !== 'OperationDefinition') {\n throw new Error(\"Schema type definitions not allowed in queries. Found: \\\"\" + definition.kind + \"\\\"\");\n }\n return definition;\n });\n if (operations.length > 1) {\n throw new Error(\"Ambiguous GraphQL document: contains \" + operations.length + \" operations\");\n }\n}", "function checkDocument(doc) {\n if (doc.kind !== 'Document') {\n throw new Error(\"Expecting a parsed GraphQL document. Perhaps you need to wrap the query string in a \\\"gql\\\" tag? http://docs.apollostack.com/apollo-client/core.html#gql\");\n }\n var operations = doc.definitions\n .filter(function (d) { return d.kind !== 'FragmentDefinition'; })\n .map(function (definition) {\n if (definition.kind !== 'OperationDefinition') {\n throw new Error(\"Schema type definitions not allowed in queries. Found: \\\"\" + definition.kind + \"\\\"\");\n }\n return definition;\n });\n if (operations.length > 1) {\n throw new Error(\"Ambiguous GraphQL document: contains \" + operations.length + \" operations\");\n }\n}", "function checkDocument(doc) {\n if (doc.kind !== 'Document') {\n throw new Error(\"Expecting a parsed GraphQL document. Perhaps you need to wrap the query string in a \\\"gql\\\" tag? http://docs.apollostack.com/apollo-client/core.html#gql\");\n }\n var operations = doc.definitions\n .filter(function (d) { return d.kind !== 'FragmentDefinition'; })\n .map(function (definition) {\n if (definition.kind !== 'OperationDefinition') {\n throw new Error(\"Schema type definitions not allowed in queries. Found: \\\"\" + definition.kind + \"\\\"\");\n }\n return definition;\n });\n if (operations.length > 1) {\n throw new Error(\"Ambiguous GraphQL document: contains \" + operations.length + \" operations\");\n }\n}", "enqueueDocumentValidation() {\n if (this['enqueued'] || !validateFn) {\n return;\n }\n this['enqueued'] = true;\n documentWait(validateFn);\n }", "function valid_schema(schema) {\n\t\tif (typeof schema !== \"object\") {\n\t\t\tvar help = \"\";\n\t\t\tif (typeof schema == \"function\") help = \" It is a function, did you forget to use new?\"\n\t\t\tthrow new Error(\"schema '\" + schema + \"' is not an object.\" + help);\n\t\t}\n\n\t\tif (schema.__proto__['_schema_valid']) return schema;\n\n\t\tschema.__proto__['_schema_checking'] = true;\n\n\t\tfor (var field in schema) {\n\t\t\tif (field.indexOf('_schema_') === 0) continue;\n\n\t\t\t// Make sure a qualifier is set.\n\t\t\tif (schema[field].qualifier != \"required\" &&\n\t\t\t\t\tschema[field].qualifier != \"optional\" &&\n\t\t\t\t\tschema[field].qualifier != \"repeated\")\n\t\t\t\tthrow new Error(\"Invalid qualifier '\" + schema[field].qualifier + \"' on field '\" + field + \"'\");\n\n\t\t\t// Check the type of the field.\n\n\t\t\tif (isPrimitive(schema[field].type)) {\n\t\t\t\t// Primitive fields cannot go wrong.\n\t\t\t\t; // Nothing to do.\n\t\t\t} else {\n\t\t\t\t// Fields that are schemas have to be recursively. We watch out for loops!\n\t\t\t\tif (schema[field].type['_schema_checking']) {\n\t\t\t\t\tif (schema[field].qualifier == \"required\") {\n\t\t\t\t\t\tthrow new Error(\"required fields can not be used recursively (think about it, it makes sense)\");\n\t\t\t\t\t}\n\t\t\t\t\tschema_log(\"loop detected, already checked\");\n\t\t\t\t} else {\n\t\t\t\t\tvalid_schema(schema[field].type);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tschema.__proto__['_schema_checked'] = true;\n\t\tdelete schema.__proto__['_schema_valid'];\n\n\t\treturn schema;\n\t}", "isDocument (obj) {\n return MapQLDocument.isDocument(obj);\n }", "enqueueDocumentValidation() {\n if (this['enqueued'] || !validateFn) {\n return;\n }\n\n this['enqueued'] = true;\n (0, _documentWait.default)(validateFn);\n }", "function assertHasValidFieldNames(doc) {\n if (doc && (0, _typeof2.default)(doc) === 'object') {\n JSON.stringify(doc, function (key, value) {\n assertIsValidFieldName(key);\n return value;\n });\n }\n }", "validateField(field, options, parent = null) {\n const fieldType = self.fieldTypes[field.type];\n if (!fieldType) {\n fail('Unknown schema field type.');\n }\n if (!field.name) {\n fail('name property is missing.');\n }\n if (!field.label && !field.contextual) {\n field.label = _.startCase(field.name.replace(/^_/, ''));\n }\n if (field.hidden && field.hidden !== true && field.hidden !== false) {\n fail(`hidden must be a boolean, \"${field.hidden}\" provided.`);\n }\n if (field.if && field.if.$or && !Array.isArray(field.if.$or)) {\n fail(`$or conditional must be an array of conditions. Current $or configuration: ${JSON.stringify(field.if.$or)}`);\n }\n if (!field.editPermission && field.permission) {\n field.editPermission = field.permission;\n }\n if (options.type !== 'doc type' && (field.editPermission || field.viewPermission)) {\n warn(`editPermission or viewPermission must be defined on doc-type schemas only, \"${options.type}\" provided`);\n }\n if (options.type === 'doc type' && (field.editPermission || field.viewPermission) && parent) {\n warn(`editPermission or viewPermission must be defined on root fields only, provided on \"${parent.name}.${field.name}\"`);\n }\n if (fieldType.validate) {\n fieldType.validate(field, options, warn, fail);\n }\n // Ancestors hoisting should happen AFTER the validation recursion,\n // so that ancestors are processed as well.\n self.hoistFollowingFieldsToParent(field, parent);\n function fail(s) {\n throw new Error(format(s));\n }\n function warn(s) {\n self.apos.util.error(format(s));\n }\n function format(s) {\n const fieldName = parent && parent.name\n ? `${parent.name}.${field.name}`\n : field.name;\n\n return stripIndents`\n ${options.type} ${options.subtype}, ${field.type} field \"${fieldName}\":\n\n ${s}\n\n `;\n }\n }", "defineSchema() {\n\n }", "function checkDocument(documentObject) {\n 'use strict';\n\n\n // init\n var type, value,\n toReturn;\n\n\n type = validType(documentObject);\n value = validValue(documentObject);\n\n // valid document type\n if (type.valid) {\n // valid document value\n if (value.valid) {\n // Check the type of the doc\n switch (typeof documentObject) {\n // construct the document\n case 'string':\n case 'number':\n toReturn = {};\n toReturn.value = documentObject;\n break;\n case 'object':\n // construct the document\n if (documentObject instanceof Array) {\n toReturn = {};\n toReturn.value = documentObject;\n }\n // document ready\n else {\n toReturn = documentObject;\n }\n break;\n default:\n // no remaining values\n }\n }\n // invalid document value\n else {\n toReturn = value;\n }\n }\n // invalid document type\n else {\n toReturn = type;\n }\n\n\n ////////\n return toReturn;\n}", "selfValidate(){\n\n }", "function schema(schema_fn) {\n\t\treturn valid_schema(new schema_fn());\n\t}", "preValidate() { }", "function ValidateCustomPageEventHandler() {\r\n return ValidateCustomDocumentReferrals();\r\n}", "function subschemaCode(it, valid) {\n if (isSchemaObj(it)) {\n checkKeywords(it);\n if (schemaCxtHasRules(it)) {\n subSchemaObjCode(it, valid);\n return;\n }\n }\n (0, boolSchema_1.boolOrEmptySchema)(it, valid);\n}", "function validateYupSchema(values,schema,sync,context){if(sync===void 0){sync=false;}if(context===void 0){context={};}var validateData=prepareDataForValidation(values);return schema[sync?'validateSync':'validate'](validateData,{abortEarly:false,context:context});}", "function check(doc, data) {\n var resolver = function (fieldName, root, args, context, info) {\n if (!{}.hasOwnProperty.call(root, info.resultKey)) {\n throw new Error(info.resultKey + \" missing on \" + root);\n }\n return root[info.resultKey];\n };\n (0, _graphql.graphql)(resolver, doc, data, {}, {}, {\n fragmentMatcher: function () {\n return false;\n }\n });\n}", "function check(doc, data) {\n var resolver = function (fieldName, root, args, context, info) {\n if (!{}.hasOwnProperty.call(root, info.resultKey)) {\n throw new Error(info.resultKey + \" missing on \" + root);\n }\n return root[info.resultKey];\n };\n (0, _graphql.graphql)(resolver, doc, data, {}, {}, {\n fragmentMatcher: function () {\n return false;\n }\n });\n}", "function validateSchema(fileName, object, schema) {\n const v = new Validator();\n const validationErrors = v.validate(object, schema).errors;\n if (validationErrors.length) {\n console.error(colors.red('\\nError - Schema validation:'));\n console.error(' ' + colors.yellow(fileName + ': '));\n validationErrors.forEach(e => {\n if (e.property) {\n console.error(' ' + colors.yellow(e.property + ' ' + e.message));\n } else {\n console.error(' ' + colors.yellow(e));\n }\n });\n console.error();\n process.exit(1);\n }\n}", "function Schema(descriptor){this.rules=null;this._messages=_messages2.messages;this.define(descriptor);}", "function Schema(descriptor){this.rules=null;this._messages=_messages2.messages;this.define(descriptor);}", "function Schema(descriptor){this.rules=null;this._messages=_messages2.messages;this.define(descriptor);}", "function validation() {\r\n\t\t\r\n\t}", "function valid(){return validated}", "checkStructure(jsonSchema) {\n const { res } = this;\n\n if (jsonSchema.isJoi) {\n const error = Joi.validate(res.data, jsonSchema).error;\n\n assert.isTrue(error === null, error && error.message);\n } else {\n const ajv = new Ajv({ schemaId: 'auto' });\n ajv.addMetaSchema(require('ajv/lib/refs/json-schema-draft-04.json'));\n\n const validate = ajv.validate(jsonSchema, res.data);\n\n assert.isTrue(validate, ajv.errorsText());\n }\n\n }", "function validateSchema(schema) {\n // First check to ensure the provided value is in fact a GraphQLSchema.\n Object(_schema__WEBPACK_IMPORTED_MODULE_7__[\"assertSchema\"])(schema); // If this Schema has already been validated, return the previous results.\n\n if (schema.__validationErrors) {\n return schema.__validationErrors;\n } // Validate the schema, producing a list of errors.\n\n\n var context = new SchemaValidationContext(schema);\n validateRootTypes(context);\n validateDirectives(context);\n validateTypes(context); // Persist the results of validation before returning to ensure validation\n // does not run multiple times for this schema.\n\n var errors = context.getErrors();\n schema.__validationErrors = errors;\n return errors;\n}", "function check(doc, data) {\n var resolver = function (fieldName, root, args, context, info) {\n if (!{}.hasOwnProperty.call(root, info.resultKey)) {\n throw new Error(info.resultKey + \" missing on \" + root);\n }\n return root[info.resultKey];\n };\n Object(_graphql__WEBPACK_IMPORTED_MODULE_0__[\"graphql\"])(resolver, doc, data, {}, {}, {\n fragmentMatcher: function () { return false; },\n });\n}", "check() {\n // Select only those rules that apply to this operation type\n const rules = getRulesForCollectionAndType(this.collectionName, this.type); // If this.doc is an ID, we will look up the doc, fetching only the fields needed.\n // To find out which fields are needed, we will combine all the `fetch` arrays from\n // all the restrictions in all the rules.\n\n if (typeof this.doc === 'string' || this.doc instanceof MongoID.ObjectID) {\n let fields = {};\n\n _.every(rules, rule => {\n const fetch = rule.combinedFetch();\n\n if (fetch === null) {\n fields = null;\n return false; // Exit loop\n }\n\n rule.combinedFetch().forEach(field => {\n fields[field] = 1;\n });\n return true;\n });\n\n let options = {};\n\n if (fields) {\n if (_.isEmpty(fields)) {\n options = {\n _id: 1\n };\n } else {\n options = {\n fields\n };\n }\n }\n\n this.doc = this.collection.findOne(this.doc, options);\n } // Loop through all defined rules for this collection. There is an OR relationship among\n // all rules for the collection, so if any \"allow\" function DO return true, we allow.\n\n\n return _.any(rules, rule => rule.allow(this.type, this.collection, this.userId, this.doc, this.modifier, ...this.args));\n }", "function validateSchema(schema) {\n // First check to ensure the provided value is in fact a GraphQLSchema.\n Object(_schema_mjs__WEBPACK_IMPORTED_MODULE_7__[\"assertSchema\"])(schema); // If this Schema has already been validated, return the previous results.\n\n if (schema.__validationErrors) {\n return schema.__validationErrors;\n } // Validate the schema, producing a list of errors.\n\n\n var context = new SchemaValidationContext(schema);\n validateRootTypes(context);\n validateDirectives(context);\n validateTypes(context); // Persist the results of validation before returning to ensure validation\n // does not run multiple times for this schema.\n\n var errors = context.getErrors();\n schema.__validationErrors = errors;\n return errors;\n}", "function assertHasValidFieldNames(doc) {\n if (doc && typeof doc === 'object') {\n JSON.stringify(doc, (key, value) => {\n assertIsValidFieldName(key);\n return value;\n });\n }\n}", "function validateSchema(schema) {\n // First check to ensure the provided value is in fact a GraphQLSchema.\n Object(_schema_mjs__WEBPACK_IMPORTED_MODULE_10__[\"assertSchema\"])(schema); // If this Schema has already been validated, return the previous results.\n\n if (schema.__validationErrors) {\n return schema.__validationErrors;\n } // Validate the schema, producing a list of errors.\n\n\n var context = new SchemaValidationContext(schema);\n validateRootTypes(context);\n validateDirectives(context);\n validateTypes(context); // Persist the results of validation before returning to ensure validation\n // does not run multiple times for this schema.\n\n var errors = context.getErrors();\n schema.__validationErrors = errors;\n return errors;\n}", "function isDoc(doc) {\n if (doc == null) {\n return false;\n }\n\n var type = typeof doc;\n if (type === 'string') {\n return false;\n }\n\n if (type === 'number') {\n return false;\n }\n\n if (Buffer.isBuffer(doc)) {\n return false;\n }\n\n if (doc.constructor.name === 'ObjectID') {\n return false;\n }\n\n // only docs\n return true;\n}", "function main()\r{\r\tif(isNeedToValidateReqDocument(capIDModel,processCode, stepNum, processID, taskStatus))\r\t{\t\r\t\tisRequiredDocument();\r\t}\r}", "_validateDocument(notification) {\n\t\t// Check the general notification\n\t\tcheck(notification, {\n\t\t\tfrom: String,\n\t\t\ttitle: String,\n\t\t\ttext: String,\n\t\t\tsent: Match.Optional(Boolean),\n\t\t\tsending: Match.Optional(Match.Integer),\n\t\t\tbadge: Match.Optional(Match.Integer),\n\t\t\tsound: Match.Optional(String),\n\t\t\tnotId: Match.Optional(Match.Integer),\n\t\t\tcontentAvailable: Match.Optional(Match.Integer),\n\t\t\tforceStart: Match.Optional(Match.Integer),\n\t\t\tapn: Match.Optional({\n\t\t\t\tfrom: Match.Optional(String),\n\t\t\t\ttitle: Match.Optional(String),\n\t\t\t\ttext: Match.Optional(String),\n\t\t\t\tbadge: Match.Optional(Match.Integer),\n\t\t\t\tsound: Match.Optional(String),\n\t\t\t\tnotId: Match.Optional(Match.Integer),\n\t\t\t\tactions: Match.Optional([Match.Any]),\n\t\t\t\tcategory: Match.Optional(String),\n\t\t\t}),\n\t\t\tgcm: Match.Optional({\n\t\t\t\tfrom: Match.Optional(String),\n\t\t\t\ttitle: Match.Optional(String),\n\t\t\t\ttext: Match.Optional(String),\n\t\t\t\timage: Match.Optional(String),\n\t\t\t\tstyle: Match.Optional(String),\n\t\t\t\tsummaryText: Match.Optional(String),\n\t\t\t\tpicture: Match.Optional(String),\n\t\t\t\tbadge: Match.Optional(Match.Integer),\n\t\t\t\tsound: Match.Optional(String),\n\t\t\t\tnotId: Match.Optional(Match.Integer),\n\t\t\t}),\n\t\t\tandroid_channel_id: Match.Optional(String),\n\t\t\tuserId: String,\n\t\t\tpayload: Match.Optional(Object),\n\t\t\tdelayUntil: Match.Optional(Date),\n\t\t\tcreatedAt: Date,\n\t\t\tcreatedBy: Match.OneOf(String, null),\n\t\t});\n\n\t\tif (!notification.userId) {\n\t\t\tthrow new Error('No userId found');\n\t\t}\n\t}", "function check(doc, data) {\n var resolver = function (fieldName, root, args, context, info) {\n if (!{}.hasOwnProperty.call(root, info.resultKey)) {\n throw new Error(info.resultKey + \" missing on \" + root);\n }\n return root[info.resultKey];\n };\n Object(__WEBPACK_IMPORTED_MODULE_0__graphql__[\"a\" /* graphql */])(resolver, doc, data, {}, {}, {\n fragmentMatcher: function () { return false; },\n });\n}", "function check(doc, data) {\n var resolver = function (fieldName, root, args, context, info) {\n if (!{}.hasOwnProperty.call(root, info.resultKey)) {\n throw new Error(info.resultKey + \" missing on \" + root);\n }\n return root[info.resultKey];\n };\n Object(__WEBPACK_IMPORTED_MODULE_0__graphql__[\"a\" /* graphql */])(resolver, doc, data, {}, {}, {\n fragmentMatcher: function () { return false; },\n });\n}", "function validates() {\n if(this.isRoot()) {\n return true; \n }else if(this.value === undefined && !this.rule.required) {\n return false;\n }\n return this.rule.required\n || (!this.rule.required && this.source.hasOwnProperty(this.field));\n}", "constructor(doc) {\n super(doc);\n }", "constructor(doc) {\n super(doc);\n }", "constructor(doc) {\n super(doc);\n }", "constructor(doc) {\n super(doc);\n }", "constructor(doc) {\n super(doc);\n }", "function validateFunctionCode(it) {\n if (isSchemaObj(it)) {\n checkKeywords(it);\n if (schemaCxtHasRules(it)) {\n topSchemaObjCode(it);\n return;\n }\n }\n validateFunction(it, () => (0, boolSchema_1.topBoolOrEmptySchema)(it));\n}", "function syncValidator(schema, data, _) {\n console.log('**** syncValidator got schema=', schema);\n console.log('**** syncValidator got data=', data);\n return true;\n}", "function validateSchema(schema) {\n // First check to ensure the provided value is in fact a GraphQLSchema.\n (0, _schema.assertSchema)(schema); // If this Schema has already been validated, return the previous results.\n\n if (schema.__validationErrors) {\n return schema.__validationErrors;\n } // Validate the schema, producing a list of errors.\n\n\n var context = new SchemaValidationContext(schema);\n validateRootTypes(context);\n validateDirectives(context);\n validateTypes(context); // Persist the results of validation before returning to ensure validation\n // does not run multiple times for this schema.\n\n var errors = context.getErrors();\n schema.__validationErrors = errors;\n return errors;\n}", "function validateSchema(schema) {\n // First check to ensure the provided value is in fact a GraphQLSchema.\n (0, _schema.assertSchema)(schema); // If this Schema has already been validated, return the previous results.\n\n if (schema.__validationErrors) {\n return schema.__validationErrors;\n } // Validate the schema, producing a list of errors.\n\n\n var context = new SchemaValidationContext(schema);\n validateRootTypes(context);\n validateDirectives(context);\n validateTypes(context); // Persist the results of validation before returning to ensure validation\n // does not run multiple times for this schema.\n\n var errors = context.getErrors();\n schema.__validationErrors = errors;\n return errors;\n}", "constructor(doc) {\n super(doc);\n }", "validate(objectOrSchemaName, objectOrValidationOptions, maybeValidatorOptions) {\n return this.coreValidate(objectOrSchemaName, objectOrValidationOptions, maybeValidatorOptions);\n }", "function Schema(descriptor){this.rules=null;this._messages=__WEBPACK_IMPORTED_MODULE_4__messages__[\"a\"/* messages */];this.define(descriptor);}", "function handler_designDocumentOnChange() {\n let designDoc = $(\"#couchdb_designDocument\").val();\n getCouchdbViews(designDoc, DOM_fillCouchdbViews);\n }", "validateInit() {\n this.runValidation(true);\n }", "async validate() {\n return true\n }", "getSchemaValidator() {\n const ajv = new Ajv__default[\"default\"]({ strict: true, strictTuples: true, strictTypes: true });\n ajv.addMetaSchema(ajvSchemaDraft);\n ajv.addKeyword(ajvRegexpKeyword);\n ajv.addKeyword({ keyword: \"copyable\" });\n return ajv.compile(this.schema);\n }", "function validateAgainstSchema(message, schema) {\n\tconst ajv = new Ajv({ schemaId: 'auto', allErrors: true, verbose: true })\n\tajv.addMetaSchema(require('ajv/lib/refs/json-schema-draft-06.json'))\n\tajv.addMetaSchema(require('ajv/lib/refs/json-schema-draft-04.json'))\n\tif (!ajv.validate(schema, message) && ajv.errors) {\n\t\tonViolation(message, ajv.errors)\n\t}\n}", "onFieldValidated(res, errors, field) {\n // Remove old errors for this field\n this.errors = this.errors.filter(e => e.field !== field.schema);\n\n if (!res && errors && errors.length > 0) {\n // Add errors with this field\n forEach(errors, err => {\n this.errors.push({\n field: field.schema,\n error: err\n });\n });\n }\n\n let isValid = this.errors.length === 0;\n this.$emit(\"validated\", isValid, this.errors, this);\n }", "function valid(schema, object) {\n\t\ttry {\n\t\t\tcheck(schema, object);\n\t\t\treturn true;\n\t\t} catch (e) {\n\t\t\treturn false;\n\t\t}\n\t}", "function checkSchemaConforms(baseDefinitionFile, conformerDefinitionFile, isValid) {\n // Get and build the base definition.\n var baseContents = getContents(getFile(baseDefinitionFile))\n , base;\n try {\n base = new Concordia(baseContents);\n }\n catch(e) {\n self.fail(\n \"A valid definition failed validation:\\n\" + \n baseContents +\n \"\\n\\n\" +\n e);\n return;\n }\n \n // Get and build the extender definition.\n var conformerContents = getContents(getFile(conformerDefinitionFile))\n , conformer;\n try {\n conformer = new Concordia(conformerContents);\n }\n catch(e) {\n self.fail(\"A valid definition failed validation: \" + conformerContents);\n return;\n }\n \n // Check the extender against the base.\n try {\n conformer.conformsTo(base);\n \n if(! isValid) {\n self.fail(\n \"A schema that should not have conformed did:\\n\" +\n \"\\nBase:\\n\" + \n baseContents +\n \"\\n\" +\n \"\\Conformer:\\n\" +\n conformerContents +\n \"\\n\\n\" +\n e);\n }\n }\n catch(e) {\n if(isValid) {\n self.fail(\n \"A schema that should have conformed did not:\\n\" +\n \"\\nBase:\\n\" + \n baseContents +\n \"\\n\" +\n \"\\Conformer:\\n\" +\n conformerContents +\n \"\\n\\n\" +\n e);\n }\n }\n}", "function publicDoctype()\n{\n this.ruleID = 'publicDoctype';\n}", "function _validate(item) {\n var _def = dictionary.lookUpDefinition(item.kind);\n if(_def) {\n _def.validate(this, item);\n this.context = _def.context;\n\n }\n}", "validate(args) {\n new SimpleSchema({\n text: {type: String},\n agentName: {type: String}\n }).validate(args)\n }", "_validateOptions() {\n //checking timestamps..\n let timestamps = this.options.timestamps;\n if (timestamps) {\n let createdAt = timestamps.createdAt;\n let updatedAt = timestamps.updatedAt;\n if (createdAt) {\n // generate created at timestamp middleware\n let fn_callback = async (document, isDocument = true) => {\n if (isDocument) {\n if (document.isNew) {\n document[createdAt] = new Date();\n }\n } else {\n const update = document;\n if (!update.$setOnInsert) {\n update.$setOnInsert = {};\n }\n update.$setOnInsert[createdAt] = new Date();\n }\n };\n this.middleware[CREATED_AT] = fn_callback;\n }\n if (updatedAt) {\n // generate updated at timestamp middleware\n let fn_callback = async (document, isDocument = true) => {\n if (isDocument) {\n document[updatedAt] = new Date();\n } else {\n const update = document;\n if (!update.$set) {\n update.$set = {};\n }\n update.$set[updatedAt] = new Date();\n }\n };\n this.middleware[UPDATED_AT] = fn_callback;\n }\n }\n //document aggregator middleware\n let fn_callback = async (document, isDocument = true) => {\n //generate a getter to define if document is new\n try{\n Object.defineProperty(document, 'isNew', {\n get: function () {\n if (document._id) {\n return false;\n } else {\n return true;\n }\n }\n });\n }catch (e) {\n console.log(e);\n }\n\n };\n this.middleware[AGGREGATOR] = fn_callback;\n }", "function Validate(){}", "function Validate(){}", "addValidationSchema(schema) {\n const validationMetadatas = new _validation_schema_ValidationSchemaToMetadataTransformer__WEBPACK_IMPORTED_MODULE_0__[\"ValidationSchemaToMetadataTransformer\"]().transform(schema);\n validationMetadatas.forEach(validationMetadata => this.addValidationMetadata(validationMetadata));\n }", "function YffValidator() {}", "function validateBinding(fn){\n if (!this.schema || this.instance === undefined) return;\n var validator = new Validator()\n , valid = validator.validate(this.schema,this.instance,fn);\n if (!valid){\n this.emit('error', validator.error())\n }\n return (valid);\n}", "function validateItem(body, res, callback) {\n var $RefParser = require('json-schema-ref-parser');\n fs.readFile('schemas/' + body.refCatalogueSchemaRelease + '/' + body.refCatalogueSchema, 'utf8', function(error, data) {\n if (error == null) {\n var fileData = JSON.parse(data);\n var traverse = require('json-schema-traverse');\n traverse(fileData, {allKeys: true}, function(schema, JSONPointer) {\n if (schema.$ref) {\n if (schema.$ref[0] !== '#') {\n var temp = 'schemas/' + body.refCatalogueSchemaRelease + '/' + schema.$ref;\n schema.$ref = temp;\n }\n }\n });\n $RefParser.dereference(fileData, function(errDeref, postSchema) {\n if (errDeref) {\n res.send(500);\n console.log(errDeref);\n } else {\n var valid = ajv.validate(postSchema, body);\n if (!valid) {\n res.send(400, ajv.errors); // bad request\n } else {\n callback();\n }\n }\n });\n } else {\n res.send(500, error);\n console.log(error);\n }\n });\n}", "function _initSchema() {\n if (!ajvSchema) {\n ajvSchema = ajv_min({ allErrors: true });\n ajvSchema.addSchema(schemaJson, \"_\");\n ajvValidators = {};\n }\n }", "validationDidStart(requestContext) {\n console.log('Validation Started!')\n }", "function verifyDocs(docs) {\n expect(docs).to.have.length.above(0);\n Logger.info('db has docs: ', docs);\n for (var i = 0; i < docs.length; i++) {\n var doc = docs[i];\n expect(doc).to.have.ownProperty('host');\n expect(doc).to.have.ownProperty('value');\n expect(doc).to.have.ownProperty('type');\n expect(doc).to.have.ownProperty('date');\n }\n }", "function verifyDocs(docs) {\n expect(docs).to.have.length.above(0);\n Logger.info('db has docs: ', docs);\n for (var i = 0; i < docs.length; i++) {\n var doc = docs[i];\n expect(doc).to.have.ownProperty('host');\n expect(doc).to.have.ownProperty('value');\n expect(doc).to.have.ownProperty('type');\n expect(doc).to.have.ownProperty('date');\n }\n }", "validate() {\n return null;\n }", "function Validate() {}", "validate(obj) {\n return {\n pass: true,\n errors: {}\n };\n }", "function isDocumentSchemaType(type) {\n if (!isObjectSchemaType(type)) {\n return false;\n }\n var current = type;\n while (current) {\n if (current.name === 'document') {\n return true;\n }\n current = current.type;\n }\n return false;\n}" ]
[ "0.71445495", "0.66139776", "0.64875436", "0.6483143", "0.6450123", "0.6427859", "0.61891735", "0.6131049", "0.61280674", "0.6118146", "0.6016436", "0.60131925", "0.5986326", "0.5928942", "0.5924764", "0.58907056", "0.58907056", "0.5878978", "0.5872864", "0.5872864", "0.5872864", "0.5872864", "0.5872864", "0.5872864", "0.5872864", "0.5872864", "0.5872864", "0.577669", "0.5707863", "0.570502", "0.5704222", "0.56817615", "0.5656894", "0.5630304", "0.5629792", "0.561801", "0.5615697", "0.5612703", "0.5587327", "0.5578321", "0.5547916", "0.5520177", "0.5520177", "0.5481595", "0.548074", "0.548074", "0.548074", "0.5465054", "0.5462499", "0.5453396", "0.5451513", "0.5446994", "0.5444193", "0.54423755", "0.5438732", "0.5437908", "0.5432773", "0.5430631", "0.5426561", "0.5418392", "0.5418392", "0.54166484", "0.5416603", "0.5416603", "0.5416603", "0.5416603", "0.5416603", "0.54165894", "0.5404539", "0.53960395", "0.53960395", "0.5364357", "0.5362522", "0.5350184", "0.53456223", "0.5344048", "0.53289", "0.5327596", "0.5320592", "0.5301468", "0.5299494", "0.528235", "0.52708155", "0.5269788", "0.52650845", "0.5262829", "0.5261344", "0.5261344", "0.52602416", "0.5258076", "0.5257839", "0.5255113", "0.52426255", "0.52355844", "0.52342725", "0.52342725", "0.5225198", "0.52179253", "0.5208026", "0.5202" ]
0.72936916
0
This function calculates the vacant spots
function calculateV(){ let area = (dims.value)*(dims.value); let vacant = area*vacantRatio.value; return Math.floor(vacant); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function markOccupiedSpots() {\n \n\t\tif(!spotsInitialized || playersInitialized < 2) {\n \n\t\t\treturn null;\n \n } // end if statement\n\t\n\t\tfor(var i = 0; i<10; i++) {\n \n\t\t\tfindClosestSpot(myMarbles[i].x, myMarbles[i].y).isEmpty = false;\n\t\t\tfindClosestSpot(othersMarbles[i].x, othersMarbles[i].y).isEmpty = false;\n \n\t\t} // end for loop\n \n\t} // end markOccupiedSpots()", "checkPosition(){\r\n if(isCriticalPosition(this.pos)){\r\n //if((this.pos.x-8)%16 == 0 && (this.pos.y-8)%16 == 0){//checks if pacman is on a critical spot\r\n //let arrPosition = createVector((this.pos.x-8)/16, (this.pos.y-8)/16);//changes location to an array position\r\n let arrPosition = pixelToTile(this.pos);\r\n //resets all paths for the ghosts\r\n //this.blinky.setPath();\r\n //this.pinky.setPath();\r\n //this.clyde.setPath();\r\n //this.inky.setPath();\r\n //Checks if the position has been eaten or not, blank spaces are considered eaten\r\n if(!this.tiles[floor(arrPosition.y)][floor(arrPosition.x)].eaten){\r\n this.tiles[floor(arrPosition.y)][floor(arrPosition.x)].eaten = true;\r\n //score+=10;//adds points for eating\r\n this.score+=1;\r\n this.dotsEaten++;\r\n this.ttl = 600;\r\n if(this.tiles[floor(arrPosition.y)][floor(arrPosition.x)].bigDot){//checks if the big dot is eaten\r\n //set all ghosts to frightened mode\r\n if(!this.blinky.goHome && !this.blinky.tempDead){\r\n this.blinky.frightened = true;\r\n this.blinky.flashCount = 0;\r\n }if(!this.clyde.goHome && !this.clyde.tempDead){\r\n this.clyde.frightened = true;\r\n this.clyde.flashCount = 0;\r\n }if(!this.pinky.goHome && !this.pinky.tempDead){\r\n this.pinky.frightened = true;\r\n this.pinky.flashCount = 0;\r\n }if(!this.inky.goHome && !this.inky.tempDead){\r\n this.inky.frightened = true;\r\n this.inky.flashCount = 0;\r\n }\r\n }\r\n }\r\n //the position in the tiles array that pacman is turning towards\r\n let positionToCheck = new createVector(arrPosition.x + this.goTo.x, arrPosition.y + this.goTo.y);\r\n //console.log(\"Position to Check X: \", positionToCheck.x, \" Y: \", positionToCheck.y);\r\n if(this.tiles[floor(positionToCheck.y)][floor(positionToCheck.x)].tunnel){//checks if the next position will be in the tunnel\r\n this.specialCase(this.pos);\r\n }if(this.tiles[floor(positionToCheck.y)][floor(positionToCheck.x)].wall){//checks if the space is not a wall\r\n if(tiles[floor(arrPosition.y + vel.y)][floor(arrPosition.x + vel.x)].wall){\r\n this.vel = createVector(this.goTo.x, this.goTo.y);//Not sure about this line...\r\n return false;\r\n }else{//moving ahead is free\r\n return true;\r\n }//return !(this.tiles[floor(arrPosition.y + this.vel.y)][floor(arrPosition.x + this.vel.x)].wall);//if both are walls then don't move\r\n }else{//allows pacman to turn\r\n this.vel = createVector(this.goTo.x, this.goTo.y);\r\n return true;\r\n }\r\n }else{//if pacman is not on a critial spot\r\n let ahead = createVector(this.pos.x+10*this.vel.x, this.pos.y+10*this.vel.y);\r\n //if((this.pos.x+10*this.vel.x-8)%16 == 0 && (this.pos.y+10*this.vel.y-8)%16 == 0){\r\n if(isCriticalPosition(ahead)){\r\n //let arrPosition = createVector((this.pos.x+10*this.vel.y-8)/16, (this.pos.y+10*this.vel.y)/16);\r\n let arrPostion = pixelToTile(ahead);//convert to an array position\r\n if(!this.tiles[floor(arrPosition.y)][floor(arrPosition.x)].eaten){\r\n this.tiles[floor(arrPosition.y)][floor(arrPosition.x)].eaten = true;//eat the dot\r\n this.score+=1;//10\r\n this.dotsEaten++;\r\n ttl = 600;\r\n if(this.tiles[floor(arrPosition.y)][floor(arrPosition.x)].bigDot && bigDotsActive){\r\n //this.score+=40;//could be used to give a better reward for getting the big dots\r\n //sets all ghosts to frightened mode\r\n if(!this.blinky.goHome && !this.blinky.tempDead){\r\n this.blinky.frightened = true;\r\n this.blinky.flashCount = 0;\r\n }if(!this.clyde.goHome && !this.clyde.tempDead){\r\n this.clyde.frightened = true;\r\n this.clyde.flashCount = 0;\r\n }if(!this.pinky.goHome && !this.pinky.tempDead){\r\n this.pinky.frightened = true;\r\n this.pinky.flashCount = 0;\r\n }if(!this.inky.goHome && !this.inky.tempDead){\r\n this.inky.frightened = true;\r\n this.inky.flashCount = 0;\r\n }\r\n }\r\n } \r\n }if(this.goTo.x+this.vel.x == 0 && this.vel.y+this.goTo.y == 0){//if turning change directions entirely, 180 degrees\r\n this.vel = createVector(this.goTo.x, this.goTo.y);//turn\r\n return true;\r\n }return true;//if it is not a critical position then it will continue forward\r\n }\r\n }", "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 markHomeSpots(position) {\n \n\t\t//list of positions coordinates\n\t\tvar xPositions;\n\t\tvar yPositions;\n\t\t\n\t\tif(position == 0) {\n \n\t\t\txPositions = [418,473,528,583,445,500,555.5,473,528,500];\n\t\t\tyPositions = [700,700,700,700,750,750,750,800,800,850];\n \n\t\t} else if(position == 1) {\n \n\t\t\txPositions = [335,280,225,170,308,253,198,280,225,252];\n\t\t\tyPositions = [650,650,650,650,600,600,600,550,550,500];\n \n\t\t} else if(position == 2) {\n \n\t\t\txPositions = [335,280,225,170,306,254,199,280,225,252]; \n\t\t\tyPositions = [250,250,250,250,300,300,300,350,350,400];\n \n\t\t} else if(position == 3) {\n \n\t\t\txPositions = [500,472,527,445,500,555,418,472,528,583];\n\t\t\tyPositions = [50,100,100,150,150,150,200,200,200,200];\n \n\t\t} else if(position == 4) {\n \n\t\t\txPositions = [830,775,720,665,802,747,692,775,720,747]; \n\t\t\tyPositions = [250,250,250,250,300,300,300,350,350,400];\n \n\t\t} else if(position == 5) {\n \n\t\t\txPositions = [830,775,720,665,802,747,693,775,720,747]; \n\t\t\tyPositions = [650,650,650,650,600,600,600,550,550,500];\n \n\t\t} // end if statement\n\t\t\n\t\tfor(var i =0; i<10; i++) {\n \n\t\t\tvar currentSpot = findClosestSpot(xPositions[i], yPositions[i]);\n currentSpot.home = true;\n //spotMatrix[currentSpot.y][currentSpot.x].\n \n\t\t} // end for loop\n \n\t} // end function markHomeSpots(position)", "function spiralSearch(room, x, y, searchType, terminator = 0) {\n // curDir = direction in which we move right now\n let curDir = [1,0]\n // length of current segment\n let segLength = 1;\n\n let tempX = x;\n let tempY = y;\n\n // how much of current segment we passed\n let segPassed = 0;\n let doneSearching = false;\n\n let n = 0;\n let countUnits = 0; // only needed for some of the clues\n let uniqueUnits = [];\n\n while(!doneSearching) {\n // make a step, add 'direction' vector to current position\n tempX = wrapCoords(tempX + curDir[0], room.mapWidth);\n tempY = wrapCoords(tempY + curDir[1], room.mapHeight);\n\n // here we actually check if there's something of value\n let curTile = room.map[tempY][tempX];\n\n // there are different types of spiral searches in the game\n // some clues search for land, some for ships, etc.\n // this statement switches between them\n switch(searchType) {\n case 1:\n // if we've found land, return distance from original position (x,y) to land tile (tempX,tempY)\n if(curTile.val >= 0.2) {\n doneSearching = true;\n return wrapDist(room, x, y, tempX, tempY)\n }\n break;\n\n case 3:\n // count number of docks\n if(curTile.dock != null) {\n countUnits++;\n }\n\n // stop loop once we reach terminator\n if(n >= terminator) {\n doneSearching = true;\n return countUnits;\n }\n\n break;\n\n case 4:\n // count number of cities\n if(curTile.city != null) {\n countUnits++;\n }\n\n // stop loop once we reach terminator\n if(n >= terminator) {\n doneSearching = true;\n return countUnits;\n }\n\n break;\n\n case 5:\n // count number of islands (only UNIQUE ones)\n if(curTile.island != null) {\n if(!(curTile.island in uniqueUnits)) {\n countUnits++;\n uniqueUnits.push(curTile.island); \n }\n }\n\n // stop loop once we reach terminator\n if(n >= terminator) {\n doneSearching = true;\n return countUnits;\n }\n\n break;\n\n case 6:\n if(curTile.dock != null) {\n doneSearching = true;\n\n let getObj = room.docks[curTile.dock];\n if(getObj.discovered) {\n return getObj.name;\n } else {\n return \"some undiscovered dock\";\n }\n }\n\n break;\n\n case 7:\n if(curTile.island != null) {\n doneSearching = true;\n\n let getObj = room.islands[curTile.island];\n if(getObj.discovered) {\n return getObj.name;\n } else {\n return \"some undiscovered island\";\n }\n }\n\n break;\n\n case 8:\n if(curTile.city != null) {\n doneSearching = true;\n\n let getObj = room.cities[curTile.city];\n if(getObj.discovered) {\n return getObj.name;\n } else {\n return \"some undiscovered town\";\n }\n }\n\n break;\n }\n \n\n // this code is for switching to the next tile again.\n // this is responsible for rotating to a new segment (and increasing length) once this one's finished\n segPassed++;\n if (segPassed == segLength) {\n // done with current segment\n segPassed = 0;\n\n // 'rotate' directions\n curDir = [-curDir[1], curDir[0]]\n\n // increase segment length if necessary\n if (curDir[1] == 0) {\n segLength++;\n }\n }\n\n // increase number of tiles we've looked at\n n++;\n }\n}", "isVacant(){\n if(!this.isWall()){\n if(this.room.roomDataArray[this.positionX][this.positionY].bricks + this.maxStepUp >= \n this.room.roomDataArray[this.tellPositionInFrontX()][this.tellPositionInFrontY()].bricks){\n return true;\n }\n }\n return false;\n }", "function updateSpots(day, appointments) {\n const dayApptIds = day.appointments;\n let spotsRemaining = 0;\n for (const id of dayApptIds) {\n !appointments[id].interview && spotsRemaining++;\n // (where an appointment's interview property is null, a spot is remaining)\n }\n return spotsRemaining;\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 updateSpots(state) {\n //Find wanted day and index\n const currentDay = state.day;\n const currentDayObj = state.days.find(day => day.name === currentDay);\n const currentDayObjIndex = state.days.findIndex(day => day.name === currentDay);\n //get appt ids and find null appts\n const appointmentIds = currentDayObj.appointments;\n const freeAppointments = appointmentIds.filter(id => !state.appointments[id].interview);\n //null appts array length \n const updatedSpots = freeAppointments.length;\n\n const updatedState = {...state};\n updatedState.days = [...state.days];\n const updatedDay = {...currentDayObj};\n updatedDay.spots = updatedSpots;\n updatedState.days[currentDayObjIndex] = updatedDay;\n\n return updatedState;\n }", "park_vehicle(vehicle) {\n //Initial Loop through the list of parking slots\n for(var i=0 ; i<this.sizes.length; i++) {\n //check if the slot is occupied and if the vehicle size is SMALL\n //Small vehicles can park either of the three, Small, Medium, Large Parking Slot\n if(vehicle.vehicle_size === 'S' && !this.sizes[i].occupied) {\n //check if where would be the vehicle coming from entry point 1;\n if(vehicle.entry_point === 1) {\n // calculate for the closest distance from where the vehicle is coming from\n var currDistance = Math.abs(1 - this.map[0].entry_point1);\n var newDistance = Math.abs(1 - this.map[i].entry_point1);\n // check if the new distance is less than the curr distance if so park the vehicle\n // else park the vehicle with the lowest distance from the entry point of the vehicle\n if(newDistance < currDistance) {\n currDistance = newDistance;\n this.sizes[i].occupied = true;\n this.sizes[i].charge = 40;\n this.sizes[i].time_in = new Date()\n this.sizes[i].vehicle = vehicle;\n return [this.map[i], this.sizes[i]]\n } else {\n this.sizes[i].occupied = true;\n this.sizes[i].charge = 40;\n this.sizes[i].time_in = new Date()\n this.sizes[i].vehicle = vehicle;\n return [this.map[i], this.sizes[i]]\n }\n }\n //check if where would be the vehicle coming from entry point 2;\n else if(vehicle.entry_point == 2) {\n // calculate for the closest distance from where the vehicle is coming from\n var currDistance = Math.abs(1 - this.map[0].entry_point2);\n var newDistance = Math.abs(1 - this.map[i].entry_point2);\n // check if the new distance is less than the curr distance if so park the vehicle\n // else park the vehicle with the lowest distance from the entry point of the vehicle\n if(newDistance < currDistance) {\n currDistance = newDistance;\n this.sizes[i].occupied = true;\n this.sizes[i].charge = 40;\n this.sizes[i].time_in = new Date()\n this.sizes[i].vehicle = vehicle;\n return [this.map[i], this.sizes[i]]\n } else {\n this.sizes[i].occupied = true;\n this.sizes[i].charge = 40;\n this.sizes[i].time_in = new Date()\n this.sizes[i].vehicle = vehicle;\n return [this.map[i], this.sizes[i]]\n }\n }\n //check if where would be the vehicle coming from entry point 3;\n else if(vehicle.entry_point == 3) {\n // calculate for the closest distance from where the vehicle is coming from\n var currDistance = Math.abs(1 - this.map[0].entry_point3);\n var newDistance = Math.abs(1 - this.map[i].entry_point3);\n // check if the new distance is less than the curr distance if so park the vehicle\n // else park the vehicle with the lowest distance from the entry point of the vehicle\n if(newDistance < currDistance) {\n currDistance = newDistance;\n this.sizes[i].occupied = true;\n this.sizes[i].charge = 40;\n this.sizes[i].time_in = new Date()\n this.sizes[i].vehicle = vehicle;\n return [this.map[i], this.sizes[i]]\n } else {\n this.sizes[i].occupied = true;\n this.sizes[i].charge = 40;\n this.sizes[i].time_in = new Date()\n this.sizes[i].vehicle = vehicle;\n return [this.map[i], this.sizes[i]]\n }\n }\n }\n //check the size of the vehicle and if the parking slot is occupied\n else if (vehicle.vehicle_size === 'M' && !this.sizes[i].occupied) {\n //if the vehicle size is medium it can only be parked at medium slot and large slot\n if(this.sizes[i].slot_size === MEDIUM_SLOT || this.sizes[i].slot_size === LARGE_SLOT) {\n if(vehicle.entry_point === 1) {\n var currDistance = Math.abs(1 - this.map[0].entry_point1);\n var newDistance = Math.abs(1 - this.map[i].entry_point1);\n if(newDistance < currDistance) {\n currDistance = newDistance;\n this.sizes[i].occupied = true;\n this.sizes[i].charge = 40;\n this.sizes[i].time_in = new Date()\n this.sizes[i].vehicle = vehicle;\n return [this.map[i], this.sizes[i]]\n } else {\n this.sizes[i].occupied = true;\n this.sizes[i].charge = 40;\n this.sizes[i].time_in = new Date()\n this.sizes[i].vehicle = vehicle;\n return [this.map[i], this.sizes[i]]\n }\n }\n else if(vehicle.entry_point == 2) {\n var currDistance = Math.abs(1 - this.map[0].entry_point2);\n var newDistance = Math.abs(1 - this.map[i].entry_point2);\n if(newDistance < currDistance) {\n currDistance = newDistance;\n this.sizes[i].occupied = true;\n this.sizes[i].charge = 40;\n this.sizes[i].time_in = new Date()\n this.sizes[i].vehicle = vehicle;\n return [this.map[i], this.sizes[i]]\n } else {\n this.sizes[i].occupied = true;\n this.sizes[i].charge = 40;\n this.sizes[i].time_in = new Date()\n this.sizes[i].vehicle = vehicle;\n return [this.map[i], this.sizes[i]]\n }\n }\n else if(vehicle.entry_point == 3) {\n var currDistance = Math.abs(1 - this.map[0].entry_point3);\n var newDistance = Math.abs(1 - this.map[i].entry_point3);\n if(newDistance < currDistance) {\n currDistance = newDistance;\n this.sizes[i].occupied = true;\n this.sizes[i].charge = 40;\n this.sizes[i].time_in = new Date()\n this.sizes[i].vehicle = vehicle;\n return [this.map[i], this.sizes[i]]\n } else {\n this.sizes[i].occupied = true;\n this.sizes[i].charge = 40;\n this.sizes[i].time_in = new Date()\n return [this.map[i], this.sizes[i]]\n }\n }\n // if there is no more available slot for the vehicle to parked\n // return no avaialable parking slot\n } else {\n return 'No available Parking Slot'\n }\n }\n //checks if the vehicle size is Large and if the parking slot is occupied\n //Large vehicles can only be parked at Large Parking Slot\n else if (vehicle.vehicle_size === 'L' && !this.sizes[i].occupied) {\n if(this.sizes[i].slot_size === LARGE_SLOT) {\n if(vehicle.entry_point === 1) {\n var currDistance = Math.abs(1 - this.map[0].entry_point1);\n var newDistance = Math.abs(1 - this.map[i].entry_point1);\n if(newDistance < currDistance) {\n currDistance = newDistance;\n this.sizes[i].occupied = true;\n this.sizes[i].charge = 40;\n this.sizes[i].time_in = new Date()\n this.sizes[i].vehicle = vehicle;\n return [this.map[i], this.sizes[i]]\n } else {\n this.sizes[i].occupied = true;\n this.sizes[i].charge = 40;\n this.sizes[i].time_in = new Date()\n this.sizes[i].vehicle = vehicle;\n return [this.map[i], this.sizes[i]]\n }\n }\n else if(vehicle.entry_point == 2) {\n var currDistance = Math.abs(1 - this.map[0].entry_point2);\n var newDistance = Math.abs(1 - this.map[i].entry_point2);\n if(newDistance < currDistance) {\n currDistance = newDistance;\n this.sizes[i].occupied = true;\n this.sizes[i].charge = 40;\n this.sizes[i].time_in = new Date()\n this.sizes[i].vehicle = vehicle;\n return [this.map[i], this.sizes[i]]\n } else {\n this.sizes[i].occupied = true;\n this.sizes[i].charge = 40;\n this.sizes[i].time_in = new Date()\n this.sizes[i].vehicle = vehicle;\n return [this.map[i], this.sizes[i]]\n }\n }\n else if(vehicle.entry_point == 3) {\n var currDistance = Math.abs(1 - this.map[0].entry_point3);\n var newDistance = Math.abs(1 - this.map[i].entry_point3);\n if(newDistance < currDistance) {\n currDistance = newDistance;\n this.sizes[i].occupied = true;\n this.sizes[i].charge = 40;\n this.sizes[i].time_in = new Date()\n this.sizes[i].vehicle = vehicle;\n return [this.map[i], this.sizes[i]]\n } else {\n this.sizes[i].occupied = true;\n this.sizes[i].charge = 40;\n this.sizes[i].time_in = new Date()\n this.sizes[i].vehicle = vehicle;\n return [this.map[i], this.sizes[i]]\n }\n }\n } else {\n return 'No available Parking Slot'\n }\n } \n }\n }", "function avancer_polygone() {\n\n\tfor (var p = 0; p<18; p++) {\n\n\t\tpolygone[p][1] = polygone[p][1] + vitesse_ver_route;\t\t/* on fait avancer le point verticalement */\n\n\t\tif (polygone[p][1] > 100) {\t\t\t\t/* test : si le point est sorti en bas de l'écran, on le redessine en haut */\n\t\t\tvitesse_lat_route = vitesse_lat_route + Math.floor(3*Math.random())/10 - 0.1;\n\t\t\tif (vitesse_lat_route > 1 || vitesse_lat_route < -1) {\n\t\t\t\tvitesse_lat_route = 0;\t\t\t/* rétroaction négative pour éviter une trop grande difficulté */\n\t\t\t}\n\t\t\tif (xroute+vitesse_lat_route <0 \n\t\t\t\t|| xroute+vitesse_lat_route+largeur > 100) {\n\t\t\t\t\tvitesse_lat_route = -vitesse_lat_route;\t\t/* pour faire tourner la route dans l'autre sens si on atteind le bord */\n\t\t\t}\n\t\t\txroute = xroute + vitesse_lat_route;\n\t\t\tpolygone[p][0] = xroute;\n\t\t\tpolygone[p][1] = polygone[p][1] % 100;\n\t\t\tpremierpoint = p;\n\t\t}\n\t}\n\n}", "function evaporate() {\n for (let i = 0; i < Math.ceil(w / pheromones_resolution); i++) {\n for (let j = 0; j < Math.ceil(h / pheromones_resolution); j++) {\n if (pheromones.home_pheromones[i][j] > 0) {\n pheromones.home_pheromones[i][j]--;\n }\n if (pheromones.food_pheromones[i][j] > 0) {\n pheromones.food_pheromones[i][j]--;\n }\n }\n }\n}", "function checkAtSpot(boardstate, loci, locj, occupy){\n\tif(!occupy)\n\t\treturn 0;\n\telse{\n\t\tvar victor = 0;\n\t\tvictor = checkHorizontal(boardstate, 1, occupy, loci, locj);\n\t\tif(victor)\n\t\t\treturn victor;\n\t\tvictor = checkVertical(boardstate, 1, occupy, loci, locj);\n\t\tif(victor)\n\t\t\treturn victor;\n\t\tvictor = checkDiagPos(boardstate, 1, occupy, loci, locj);\n\t\tif(victor)\n\t\t\treturn victor;\n\t\tvictor = checkDiagNeg(boardstate, 1, occupy, loci, locj);\n\t\treturn victor;\n\t}\n}", "winningPositions() {\n return [\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 }", "function bestStepForSpot(col, row){\r\n\tvar cur_pos = [col, row];\r\n\tvar j = 0;\r\n\tvar pos = [];\r\n\tvar max_s = 0;\r\n\tvar s_n = 0; \r\n\tvar d_pos = [];\r\n\tfor (j = 0; j<POSSIBLE_MOVING.length; j++){\r\n\t\tpos = [cur_pos[0] + POSSIBLE_MOVING[j][0], cur_pos[1] + POSSIBLE_MOVING[j][1]]; \r\n\t\tif (outOfRange(pos[0], pos[1])) continue;\r\n\t\tif (game_field[pos[1]][pos[0]] == EMPTY){\r\n\t\t\ts_n = getScoreAfterStep(cur_pos, pos);\r\n\t\t\tif (s_n > max_s){\r\n\t\t\t\tmax_s = s_n;\r\n\t\t\t\td_pos = [POSSIBLE_MOVING[j][0], POSSIBLE_MOVING[j][1]];\r\n\t\t\t}\r\n\t\t}\t\r\n\t}\r\n\treturn [d_pos, max_s];\r\n}", "function getUpdateSpots(newAppointments) {\n return state.days.map((day, index) => {\n let freeSpots = 0;\n\n for (let key of state.days[index].appointments) {\n if (!newAppointments[key].interview) {\n freeSpots++;\n }\n }\n const updatedSpots = {...day, spots: freeSpots}\n return updatedSpots;\n })\n }", "function invertS(guy)\n{\n var i;\n var guyStart;\n var guyEnd;\n var busySpace = [];\n var freeSpace = [];\n\n //represent busy spaces in 2d array format\n for(i=0;i<guy.length;i++)\n {\n guyStart = parseInt(guy[i].start.substring(11,14));\n guyEnd = parseInt(guy[i].end.substring(11,14));\n\n busySpace.push([guyStart, guyEnd]);\n }\n\n let lastFreeTime = 8;\n\n //find free spaces in between busy ones\n busySpace.forEach(function(busy, ind){\n if(busy[0] > lastFreeTime){\n const freeInterval = [lastFreeTime, busy[0]];\n freeSpace.push(freeInterval);\n }\n lastFreeTime = busy[1];\n if(ind === busySpace.length - 1 && busy[1] < 24){\n freeSpace.push([lastFreeTime, 24]);\n }\n });\n\n if(busySpace.length === 0){\n freeSpace.push([lastFreeTime, 24]);\n }\n\n return freeSpace;\n}", "function Spot(i, j) {\n // Location\n this.i = i;\n this.j = j;\n\n // f, g, and h values for A*\n this.f = 0;\n this.g = 0;\n this.h = 0;\n\n // Neighbors\n this.neighbors = [];\n\n // Where did I come from?\n this.previous = undefined;\n\n // Am I a wall?\n this.wall = false;\n if (random(1) < 0.4) {\n this.wall = true;\n }\n\n // Display me\n this.show = function(col) {\n if (this.wall) {\n fill(0);\n noStroke();\n ellipse(this.i * w + w / 2, this.j * h + h / 2, w / 2, h / 2);\n } else if (col) {\n fill(col);\n rect(this.i * w, this.j * h, w, h);\n }\n };\n\n // Figure out who my neighbors are\n this.addNeighbors = function(grid) {\n var i = this.i;\n var j = this.j;\n if (i < cols - 1) {\n this.neighbors.push(grid[i + 1][j]);\n }\n if (i > 0) {\n this.neighbors.push(grid[i - 1][j]);\n }\n if (j < rows - 1) {\n this.neighbors.push(grid[i][j + 1]);\n }\n if (j > 0) {\n this.neighbors.push(grid[i][j - 1]);\n }\n if (i > 0 && j > 0) {\n this.neighbors.push(grid[i - 1][j - 1]);\n }\n if (i < cols - 1 && j > 0) {\n this.neighbors.push(grid[i + 1][j - 1]);\n }\n if (i > 0 && j < rows - 1) {\n this.neighbors.push(grid[i - 1][j + 1]);\n }\n if (i < cols - 1 && j < rows - 1) {\n this.neighbors.push(grid[i + 1][j + 1]);\n }\n };\n}", "function isShipInRangeV(boat) {\n n = Math.floor(Math.random() * 48);\n let c = n % 8;\n if (c + 16 >= 56) {\n isShipInRangeV(boat);\n } else {\n placeVertical(n, boat);\n }\n}", "function createParkingLot(opening, numOfSpaces){\n let sideCounter = 16;\n let middleTopRailCounter = 314;\n let middleRailCounter = 250;\n\n for(i = 0; i < numOfSpaces; i++){\n if(opening === 'left'){\n new ParkingSpace(sideCounter, 15, 125, 63, 'right').paint();\n new Marker(sideCounter + 26, 193, 125, 63).paint()\n sideCounter = sideCounter + 63;\n\n } else if(opening === 'right'){\n new ParkingSpace(sideCounter, 670, 125, 63, 'left').paint();\n new Marker(sideCounter + 26, 603, 125, 63).paint()\n sideCounter = sideCounter + 63;\n\n } else if (opening === 'top'){\n new ParkingSpace(20, middleTopRailCounter, 63, 125, 'bottom').paint();\n middleTopRailCounter = middleTopRailCounter + 63;\n\n } else if (opening === 'middle'){\n new ParkingSpace(240, middleRailCounter, 63, 125, 'top').paint();\n new Marker(180, middleRailCounter + 25, 63, 125).paint()\n middleRailCounter = middleRailCounter + 63;\n\n } else if (opening === 'bottom'){\n new ParkingSpace(465, middleRailCounter, 63, 125, 'top').paint();\n new Marker(405, middleRailCounter + 25, 63, 125).paint()\n middleRailCounter = middleRailCounter + 63;\n\n } else {\n console.log(\"Need to pass in opening\");\n }\n }\n}", "function planets()\n{\n with (Math) {\n\n var RAD = 180 / PI;\n\n document.planets.size6.value = \"\";\n document.planets.size7.value = \"\";\n document.planets.phase7.value = \"\";\n document.planets.phase6.value = \"\";\n document.planets.dawn.value = \"\";\n document.planets.dusk.value = \"\";\n document.planets.tr0.value = \"...\";\n document.planets.tr1.value = \"...\";\n document.planets.tr2.value = \"...\";\n document.planets.tr3.value = \"...\";\n document.planets.tr4.value = \"...\";\n document.planets.tr5.value = \"...\";\n document.planets.tr6.value = \"...\";\n\n var planet_dec = new Array(9);\n var planet_ra = new Array(9);\n var planet_dist = new Array(9);\n var planet_phase = new Array(9);\n var planet_size = new Array(9);\n var planet_alt = new Array(9);\n var planet_az = new Array(9);\n\n var ang_at_1au = [1,6.68,16.82,9.36,196.94,166.6];\n\n var planet_a = new Array(5);\n var planet_l = new Array(5);\n var planet_i = new Array(5);\n var planet_e = new Array(5);\n var planet_n = new Array(5);\n var planet_m = new Array(5);\n var planet_r = new Array(5);\n\n var jd, t, l, m, e, c, sl, r, R, Rm, u, p, q, v, z, a, b, ee, oe, t0, gt;\n var g0, x, y, i, indx, count, hl, ha, eg, et, dr, en, de, ra, la, lo, height;\n var az, al, size, il, dist, rho_sin_lat, rho_cos_lat, rise_str, set_str;\n var dawn, dusk, gt_dawn, gt_dusk, dawn_planets, dusk_planets, morn, eve;\n var sunrise_set, moonrise_set, twilight_begin_end, twilight_start, twilight_end;\n var sat_lat, phase_angle, dt_as_str, tm_as_str, ut_hrs, ut_mns, part_day, dt;\n var moon_days, Days, age, N, M_sun, Ec, lambdasun, P0, N0, rise, set, tr, h0;\n var i_m, e_m, l_m, M_m, N_m, Ev, Ae, A3, A4, lambda_moon, beta_moon, phase;\n var transit, lambda_transit, beta_transit, ra_transit;\n var ra_np, d_beta, d_lambda, lambda_moon_D, beta_moon_D, yy;\n\n la = latitude / RAD;\n lo = longitude / RAD;\n height = 10.0;\n\n tm_as_str = document.planets.ut_h_m.value;\n ut_hrs = eval(tm_as_str.substring(0,2));\n ut_mns = eval(tm_as_str.substring(3,5));\n dt_as_str = document.planets.date_txt.value;\n yy = eval(dt_as_str.substring(6,10));\n\n\n part_day = ut_hrs / 24.0 + ut_mns / 1440.0;\n\n jd = julian_date() + part_day;\n\n document.planets.phase8.value = round_1000(jd);\n\n y = floor(yy / 50 + 0.5) * 50;\n if (y == 1600) dt = 2;\n if (y == 1650) dt = 0.8;\n if (y == 1700) dt = 0.1;\n if (y == 1750) dt = 0.2;\n if (y == 1800) dt = 0.2;\n if (y == 1850) dt = 0.1;\n if (y == 1900) dt = 0;\n if (y == 1950) dt = 0.5;\n if (y == 2000) dt = 1.1;\n if (y == 2050) dt = 3;\n if (y == 2100) dt = 5;\n if (y == 2150) dt = 6;\n if (y == 2200) dt = 8;\n if (y == 2250) dt = 11;\n if (y == 2300) dt = 13;\n if (y == 2350) dt = 16;\n if (y == 2400) dt = 19;\n dt = dt / 1440;\n\n jd += dt;\n\n zone_date_time();\n\n moon_facts();\n\n t=(jd-2415020.0)/36525;\n oe=.409319747-2.271109689e-4*t-2.8623e-8*pow(t,2)+8.779e-9*pow(t,3);\n t0=(julian_date()-2415020.0)/36525;\n g0=.276919398+100.0021359*t0+1.075e-6*pow(t0,2);\n g0=(g0-floor(g0))*2*PI;\n gt=proper_ang_rad(g0+part_day*6.30038808);\n\n l=proper_ang_rad(4.88162797+628.331951*t+5.27962099e-6*pow(t,2));\n m=proper_ang_rad(6.2565835+628.3019457*t-2.617993878e-6*pow(t,2)-5.759586531e-8*pow(t,3));\n e=.01675104-4.18e-5*t-1.26e-7*pow(t,2);\n c=proper_ang_rad(3.3500896e-2-8.358382e-5*t-2.44e-7*pow(t,2))*sin(m)+(3.50706e-4-1.7e-6*t)*sin(2*m)+5.1138e-6*sin(3*m);\n sl=proper_ang_rad(l+c);\n R=1.0000002*(1-pow(e,2))/(1+e*cos(m+c));\n\n de = asin(sin(oe) * sin(sl));\n y = sin(sl) * cos(oe);\n x = cos(sl);\n ra = proper_ang_rad(atan2(y,x));\n dist = R;\n size = 31.9877 / dist;\n\n ha=proper_ang_rad(gt-lo-ra);\n al=asin(sin(la)*sin(de)+cos(la)*cos(de)*cos(ha));\n az=acos((sin(de)-sin(la)*sin(al))/(cos(la)*cos(al)));\n if (sin(ha)>=0) az=2*PI-az;\n\n planet_decl[0] = de;\n planet_r_a[0] = ra;\n planet_mag[0] = -26.7;\n\n planet_dec[8] = \"\";\n planet_ra[8] = \"\";\n planet_dist[8] = \"\";\n planet_size[8] = \"\";\n planet_alt[8] = \"\";\n planet_az[8] = \"\";\n\n y = sin(-0.8333/RAD) - sin(la) * sin(de);\n x = cos(la) * cos(de);\n if (y/x >= 1)\n {\n //rise_str = \"No rise\";\n //set_str = \"No rise\";\n h0 = 0;\n }\n if (y/x <= -1)\n {\n //rise_str = \"No set\";\n //set_str = \"No set\";\n h0 = 0;\n }\n if (abs(y/x) < 1)\n {\n h0 = acos(y/x) * RAD;\n tr = range_1((ra * RAD + lo * RAD - g0 * RAD) / 360);\n document.planets.tr0.value = am_pm(range_1(tr + zone / 24 - dt) * 24);\n document.planets.tr0_2.value = am_pm(range_1(tr + zone / 24 - dt) * 24);\n\n\n }\n y = sin(-18/RAD) - sin(la) * sin(de);\n x = cos(la) * cos(de);\n if (y/x >= 1)\n {\n twilight_start = \"No twilight\";\n twilight_end = \"No twilight\";\n h0 = 0;\n }\n if (y/x <= -1)\n {\n twilight_start = \"All night\";\n twilight_end = \"All night\";\n h0 = 0;\n }\n if (abs(y/x) < 1)\n {\n h0 = acos(y/x) * RAD;\n tr = range_1((ra * RAD + lo * RAD - g0 * RAD) / 360);\n twilight_start = am_pm(range_1(tr - h0 / 360 + zone / 24 - dt) * 24);\n twilight_end = am_pm(range_1(tr + h0 / 360 + zone / 24 - dt) * 24);\n }\n\n al = al * RAD;\n az = az * RAD;\n if (al >= 0)\n {\n al += 1.2 / (al + 2);\n }\n else\n {\n al += 1.2 / (abs(al) + 2);\n }\n\n planet_altitude[0] = al;\n planet_azimuth[0] = az;\n\n de = de * RAD;\n ra = ra * RAD / 15;\n\n x = round_10(abs(de));\n if (de < 0)\n {\n planet_dec[8] += \"-\";\n }\n else\n {\n planet_dec[8] += \"+\";\n }\n if (x < 10) planet_dec[8] += \"0\";\n planet_dec[8] += x;\n if (x == floor(x)) planet_dec[8] += \".0\";\n planet_dec[8] += \"\\u00B0\";\n\n x = floor(ra);\n y = floor((ra - x) * 60 + 0.5);\n if (y == 60)\n {\n x += 1;\n y = 0;\n }\n if (x < 10) planet_ra[8] += \"0\";\n planet_ra[8] += x + \"h \";\n if (y < 10) planet_ra[8] += \"0\";\n planet_ra[8] += y + \"m\";\n\n dist = round_100(dist);\n if (dist < 10)\n planet_dist[8] += \"0\";\n planet_dist[8] += dist;\n\n size = round_10(size);\n planet_size[8] += size;\n if (size == floor(size)) planet_size[8] += \".0\";\n planet_size[8] += \"\\'\";\n\n sunrise_set = sun_rise_set(la,lo,zone);\n rise_str = sunrise_set.substring(0,8);\n set_str = sunrise_set.substring(11,19);\n planet_alt[8] = rise_str;\n planet_az[8] = set_str;\n\n /*\n planet_alt[8] = rise_str;\n planet_az[8] = set_str;\n sunrise_set = rise_str + \" / \" + set_str;\n */\n\n moon_days = 29.53058868;\n Days = jd - 2444238.5;\n N = proper_ang(Days / 1.01456167);\n M_sun = proper_ang(N - 3.762863);\n Ec = 1.91574168 * sin(M_sun / RAD);\n lambdasun = proper_ang(N + Ec + 278.83354);\n l0 = 64.975464;\n P0 = 349.383063;\n N0 = 151.950429;\n i_m = 5.145396;\n e_m = 0.0549;\n l_m = proper_ang(13.1763966 * Days + l0);\n M_m = proper_ang(l_m - 0.111404 * Days - P0);\n N_m = proper_ang(N0 - 0.0529539 * Days);\n Ev = 1.2739 * sin((2 * (l_m - lambdasun) - M_m) / RAD);\n Ae = 0.1858 * sin(M_sun / RAD);\n A3 = 0.37 * sin(M_sun / RAD);\n M_m += Ev - Ae - A3;\n Ec = 6.2886 * sin(M_m / RAD);\n dist = hundred_miles(238855.7 * (1 - pow(e_m,2)) / (1 + e_m * cos((M_m + Ec) / RAD)));\n A4 = 0.214 * sin(2 * M_m / RAD);\n l_m += Ev + Ec - Ae + A4;\n l_m += 0.6583 * sin(2 * (l_m - lambdasun) / RAD);\n N_m -= 0.16 * sin(M_sun / RAD);\n\n y = sin((l_m - N_m) / RAD) * cos(i_m / RAD);\n x = cos((l_m - N_m) / RAD);\n lambda_moon = proper_ang_rad(atan2(y,x) + N_m / RAD);\n beta_moon = asin(sin((l_m - N_m) / RAD) * sin(i_m / RAD));\n d_beta = 8.727e-4 * cos((l_m - N_m) / RAD);\n d_lambda = 9.599e-3 + 1.047e-3 * cos(M_m / RAD);\n\n de = asin(sin(beta_moon) * cos(oe) + cos(beta_moon) * sin(oe) * sin(lambda_moon));\n y = sin(lambda_moon) * cos(oe) - tan(beta_moon) * sin(oe);\n x = cos(lambda_moon);\n ra = proper_ang_rad(atan2(y,x));\n\n ra_np = ra;\n\n size = 2160 / dist * RAD * 60;\n\n x = proper_ang(l_m - lambdasun);\n phase = 50.0 * (1.0 - cos(x / RAD));\n\n age = jd - new_moon;\n if (age > moon_days) age -= moon_days;\n if (age < 0) age += moon_days;\n\n /*\n age = (x / 360 * moon_days);\n */\n Rm = R - dist * cos(x / RAD) / 92955800;\n phase_angle = acos((pow(Rm,2) + pow((dist/92955800),2) - pow(R,2)) / (2 * Rm * dist/92955800)) * RAD / 100;\n planet_mag[6] = round_10(0.21 + 5 * log(Rm * dist / 92955800)/log(10) + 3.05 * (phase_angle) - 1.02 * pow(phase_angle,2) + 1.05 * pow(phase_angle,3));\n if (planet_mag[6] == floor(planet_mag[6])) planet_mag[6] += \".0\";\n\n /*\n thisImage = floor(age / moon_days * 28);\n */\n\n thisImage = floor(age / moon_days * 27 + 0.5);\n document.myPicture.src = myImage[thisImage];\n age = round_10(age);\n\n x = atan(0.996647 * tan(la));\n rho_sin_lat = 0.996647 * sin(x) + height * sin(la) / 6378140;\n rho_cos_lat = cos(x) + height * cos(la) / 6378140;\n r = dist / 3963.2;\n ha = proper_ang_rad(gt - lo - ra);\n x = atan(rho_cos_lat * sin(ha) / (r * cos(de) - rho_cos_lat * cos(ha)));\n ra -= x;\n y = ha;\n ha += x;\n de = atan(cos(ha) * (r * sin(de) - rho_sin_lat) / (r * cos(de) * cos(y) - rho_cos_lat));\n ha = proper_ang_rad(gt - lo - ra);\n al = asin(sin(de) * sin(la) + cos(de) * cos(la) * cos(ha));\n az = acos((sin(de) - sin(la) * sin(al)) / (cos(la) * cos(al)));\n if (sin(ha) >= 0) az = 2 * PI - az;\n\n planet_decl[6] = de;\n planet_r_a[6] = ra;\n\n planet_dec[9] = \"\";\n planet_ra[9] = \"\";\n planet_dist[9] = \"\";\n planet_dist[6] = \"\";\n planet_phase[9] = \"\";\n planet_size[9] = \"\";\n planet_alt[9] = \"\";\n planet_az[9] = \"\";\n\n lambda_moon_D = lambda_moon - d_lambda * part_day * 24;\n beta_moon_D = beta_moon - d_beta * part_day * 24;\n\n tr = range_1((ra_np * RAD + lo * RAD - g0 * RAD) / 360);\n transit = tr * 24;\n lambda_transit = lambda_moon_D + transit * d_lambda;\n beta_transit = beta_moon_D + transit * d_beta;\n\n y = sin(lambda_transit) * cos(oe) - tan(beta_transit) * sin(oe);\n x = cos(lambda_transit);\n ra_transit = proper_ang_rad(atan2(y,x));\n tr = range_1((ra_transit * RAD + lo * RAD - g0 * RAD) / 360);\n document.planets.tr6.value = am_pm(range_1(tr + zone / 24 - dt) * 24);\n document.planets.tr6_2.value = am_pm(range_1(tr + zone / 24 - dt) * 24);\n\n\n al = al * RAD;\n az = az * RAD;\n if (al >= 0)\n {\n al += 1.2 / (al + 2);\n }\n else\n {\n al += 1.2 / (abs(al) + 2);\n }\n\n planet_altitude[6] = al;\n planet_azimuth[6] = az;\n\n de = de * RAD;\n ra = ra * RAD / 15;\n\n x = round_10(abs(de));\n if (de < 0)\n {\n planet_dec[9] += \"-\";\n }\n else\n {\n planet_dec[9] += \"+\";\n }\n if (x < 10) planet_dec[9] += \"0\";\n planet_dec[9] += x;\n if (x == floor(x)) planet_dec[9] += \".0\";\n planet_dec[9] += \"\\u00B0\";\n\n x = floor(ra);\n y = floor((ra - x) * 60 + 0.5);\n if (y == 60)\n {\n x += 1;\n y = 0;\n }\n if (x < 10) planet_ra[9] += \"0\";\n planet_ra[9] += x + \"h \";\n if (y < 10) planet_ra[9] += \"0\";\n planet_ra[9] += y + \"m\";\n\n if (age < 10)\n planet_dist[6] += \"0\";\n planet_dist[6] += age;\n if (age == floor(age)) planet_dist[6] += \".0\";\n planet_dist[6] += \" days\";\n\n planet_dist[9] += dist;\n\n size = round_10(size);\n planet_size[9] += size;\n if (size == floor(size)) planet_size[9] += \".0\";\n planet_size[9] += \"\\'\";\n\n phase = floor(phase + 0.5);\n planet_phase[9] += phase + \"%\";\n\n moonrise_set = moon_rise_set(la,lo,zone);\n rise_str = moonrise_set.substring(0,8);\n set_str = moonrise_set.substring(11,19);\n planet_alt[9] = rise_str;\n planet_az[9] = set_str;\n\n\n if (twilight_start == \"All night\")\n {\n twilight_begin_end = \"twilight all night\";\n }\n else if (twilight_start == \"No twilight\")\n {\n twilight_begin_end = \"Sky dark for 24h\";\n }\n else\n {\n twilight_begin_end = twilight_start + \" / \" + twilight_end;\n }\n\n u=t/5+.1;\n p=proper_ang_rad(4.14473024+52.96910393*t);\n q=proper_ang_rad(4.64111846+21.32991139*t);\n\n v=5*q-2*p;\n z=proper_ang_rad(q-p);\n if (v >= 0)\n {\n v=proper_ang_rad(v);\n }\n else\n {\n v=proper_ang_rad(abs(v))+2*PI;\n }\n\n planet_a[1]=0.3870986;\n planet_l[1]=proper_ang_rad(3.109811569+2608.814681*t+5.2552e-6*pow(t,2));\n planet_e[1]=.20561421+2.046e-5*t-3e-8*pow(t,2);\n planet_i[1]=.12222333+3.247708672e-5*t-3.194e-7*pow(t,2);\n planet_n[1]=.822851951+.020685787*t+3.035127569e-6*pow(t,2);\n planet_m[1]=proper_ang_rad(1.785111938+2608.787533*t+1.22e-7*pow(t,2));\n planet_a[2]=0.7233316;\n planet_l[2]=proper_ang_rad(5.982413642+1021.352924*t+5.4053e-6*pow(t,2));\n planet_e[2]=.00682069-4.774e-5*t+9.1e-8*pow(t,2);\n planet_i[2]=.059230034+1.75545e-5*t-1.7e-8*pow(t,2);\n planet_n[2]=1.322604346+.0157053*t+7.15585e-6*pow(t,2);\n planet_m[2]=proper_ang_rad(3.710626189+1021.328349*t+2.2445e-5*pow(t,2));\n planet_a[3]=1.5236883;\n planet_l[3]=proper_ang_rad(5.126683614+334.0856111*t+5.422738e-6*pow(t,2));\n planet_e[3]=.0933129+9.2064e-5*t-7.7e-8*pow(t,2);\n planet_i[3]=.032294403-1.178097e-5*t+2.199e-7*pow(t,2);\n planet_n[3]=.851484043+.013456343*t-2.44e-8*pow(t,2)-9.3026e-8*pow(t,3);\n planet_m[3]=proper_ang_rad(5.576660841+334.0534837*t+3.159e-6*pow(t,2));\n planet_l[4]=proper_ang_rad(4.154743317+52.99346674*t+5.841617e-6*pow(t,2)-2.8798e-8*pow(t,3));\n a=.0058*sin(v)-1.1e-3*u*cos(v)+3.2e-4*sin(2*z)-5.8e-4*cos(z)*sin(q)-6.2e-4*sin(z)*cos(q)+2.4e-4*sin(z);\n b=-3.5e-4*cos(v)+5.9e-4*cos(z)*sin(q)+6.6e-4*sin(z)*cos(q);\n ee=3.6e-4*sin(v)-6.8e-4*sin(z)*sin(q);\n planet_e[4]=.04833475+1.6418e-4*t-4.676e-7*pow(t,2)-1.7e-9*pow(t,3);\n planet_a[4]=5.202561+7e-4*cos(2*z);\n planet_i[4]=.022841752-9.941569952e-5*t+6.806784083e-8*pow(t,2);\n planet_n[4]=1.735614994+.017637075*t+6.147398691e-6*pow(t,2)-1.485275193e-7*pow(t,3);\n planet_m[4]=proper_ang_rad(3.932721257+52.96536753*t-1.26012772e-5*pow(t,2));\n planet_m[4]=proper_ang_rad(planet_m[4]+a-b/planet_e[4]);\n planet_l[4]=proper_ang_rad(planet_l[4]+a);\n planet_e[4]=planet_e[4]+ee;\n\n planet_a[5]=9.554747;\n planet_l[5]=proper_ang_rad(4.652426047+21.35427591*t+5.663593422e-6*pow(t,2)-1.01229e-7*pow(t,3));\n a=-.014*sin(v)+2.8e-3*u*cos(v)-2.6e-3*sin(z)-7.1e-4*sin(2*z)+1.4e-3*cos(z)*sin(q);\n a=a+1.5e-3*sin(z)*cos(q)+4.4e-4*cos(z)*cos(q);\n a=a-2.7e-4*sin(3*z)-2.9e-4*sin(2*z)*sin(q)+2.6e-4*cos(2*z)*sin(q);\n a=a+2.5e-4*cos(2*z)*cos(q);\n b=1.4e-3*sin(v)+7e-4*cos(v)-1.3e-3*sin(z)*sin(q);\n b=b-4.3e-4*sin(2*z)*sin(q)-1.3e-3*cos(q)-2.6e-3*cos(z)*cos(q)+4.7e-4*cos(2*z)*cos(q);\n b=b+1.7e-4*cos(3*z)*cos(q)-2.4e-4*sin(z)*sin(2*q);\n b=b+2.3e-4*cos(2*z)*sin(2*q)-2.3e-4*sin(z)*cos(2*q)+2.1e-4*sin(2*z)*cos(2*q);\n b=b+2.6e-4*cos(z)*cos(2*q)-2.4e-4*cos(2*z)*cos(2*q);\n planet_l[5]=proper_ang_rad(planet_l[5]+a);\n planet_e[5]=.05589232-3.455e-4*t-7.28e-7*pow(t,2)+7.4e-10*pow(t,3);\n planet_i[5]=.043502663-6.839770806e-5*t-2.703515011e-7*pow(t,2)+6.98e-10*pow(t,3);\n planet_n[5]=1.968564089+.015240129*t-2.656042056e-6*pow(t,2)-9.2677e-8*pow(t,3);\n planet_m[5]=proper_ang_rad(3.062463265+21.32009513*t-8.761552845e-6*pow(t,2));\n planet_m[5]=proper_ang_rad(planet_m[5]+a-b/planet_e[5]);\n planet_a[5]=planet_a[5]+.0336*cos(z)-.00308*cos(2*z)+.00293*cos(v);\n planet_e[5]=planet_e[5]+1.4e-3*cos(v)+1.2e-3*sin(q)+2.7e-3*cos(z)*sin(q)-1.3e-3*sin(z)*cos(q);\n\n for (i=1; i<6; i++)\n\n {\n\n e = planet_m[i];\n for (count = 1; count <= 50; count++)\n {\n de = e - planet_e[i] * sin(e) - planet_m[i];\n if (abs(de) <= 5e-8) break;\n e = e - de / (1 - planet_e[i] * cos(e));\n }\n v=2*atan(sqrt((1+planet_e[i])/(1-planet_e[i]))*tan(e/2));\n planet_r[i]=planet_a[i]*(1-planet_e[i]*cos(e));\n u=proper_ang_rad(planet_l[i]+v-planet_m[i]-planet_n[i]);\n x=cos(planet_i[i])*sin(u);\n y=cos(u);\n y=acos(y/sqrt(pow(x,2)+pow(y,2)));\n if (x<0) y=2*PI-y;\n\n hl=proper_ang_rad(y+planet_n[i]);\n ha=asin(sin(u)*sin(planet_i[i]));\n x=planet_r[i]*cos(ha)*sin(proper_ang_rad(hl-sl));\n y=planet_r[i]*cos(ha)*cos(proper_ang_rad(hl-sl))+R;\n y=acos(y/sqrt(pow(x,2)+pow(y,2)));\n if (x<0) y=2*PI-y;\n\n eg=proper_ang_rad(y+sl);\n dr=sqrt(pow(R,2)+pow(planet_r[i],2)+2*planet_r[i]*R*cos(ha)*cos(proper_ang_rad(hl-sl)));\n size=ang_at_1au[i]/dr;\n il=floor((pow((planet_r[i]+dr),2)-pow(R,2))/(4*planet_r[i]*dr)*100+.5);\n phase_angle=acos((pow(planet_r[i],2)+pow(dr,2)-pow(R,2))/(2*planet_r[i]*dr))*RAD;\n et=asin(planet_r[i]/dr*sin(ha));\n en=acos(cos(et)*cos(proper_ang_rad(eg-sl)));\n de=asin(sin(et)*cos(oe)+cos(et)*sin(oe)*sin(eg));\n y=cos(eg);\n x=sin(eg)*cos(oe)-tan(et)*sin(oe);\n y=acos(y/sqrt(pow(x,2)+pow(y,2)));\n if (x<0) y=2*PI-y;\n\n ra=y;\n ha=proper_ang_rad(gt-lo-ra);\n al=asin(sin(la)*sin(de)+cos(la)*cos(de)*cos(ha));\n az=acos((sin(de)-sin(la)*sin(al))/(cos(la)*cos(al)));\n if (sin(ha)>=0) az=2*PI-az;\n\n planet_decl[i] = de;\n planet_r_a[i] = ra;\n\n planet_mag[i]=5*log(planet_r[i]*dr)/log(10);\n if (i == 1) planet_mag[i] = -0.42 + planet_mag[i] + 0.038*phase_angle - 0.000273*pow(phase_angle,2) + 0.000002*pow(phase_angle,3);\n if (i == 2) planet_mag[i] = -4.4 + planet_mag[i] + 0.0009*phase_angle + 0.000239*pow(phase_angle,2) - 0.00000065*pow(phase_angle,3);\n if (i == 3) planet_mag[i] = -1.52 + planet_mag[i] + 0.016*phase_angle;\n if (i == 4) planet_mag[i] = -9.4 + planet_mag[i] + 0.005*phase_angle;\n if (i == 5)\n {\n sat_lat = asin(0.47063*cos(et)*sin(eg-2.9585)-0.88233*sin(et));\n planet_mag[i] = -8.88 + planet_mag[i] + 0.044*phase_angle - 2.6*sin(abs(sat_lat)) + 1.25*pow(sin(sat_lat),2);\n }\n planet_mag[i] = round_10(planet_mag[i]);\n if (planet_mag[i] == floor(planet_mag[i])) planet_mag[i] += \".0\";\n if (planet_mag[i] >= 0) planet_mag[i] = \"+\" + planet_mag[i];\n\n planet_dec[i] = \"\";\n planet_ra[i] = \"\";\n planet_dist[i] = \"\";\n planet_size[i] = \"\";\n planet_phase[i] = \"\";\n planet_alt[i] = \"\";\n planet_az[i] = \"\";\n\n y = sin(-0.5667/RAD) - sin(la) * sin(de);\n x = cos(la) * cos(de);\n if (y/x >= 1)\n {\n rise_str = \"No rise\";\n set_str = \"No rise\";\n h0 = 0;\n }\n if (y/x <= -1)\n {\n rise_str = \"No set\";\n set_str = \"No set\";\n h0 = 0;\n }\n if (abs(y/x) < 1)\n {\n h0 = acos(y/x) * RAD;\n tr = range_1((ra * RAD + lo * RAD - g0 * RAD) / 360);\n rise_str = am_pm(range_1(tr - h0 / 360 + zone / 24 - dt) * 24);\n set_str = am_pm(range_1(tr + h0 / 360 + zone / 24 - dt) * 24);\n tr = am_pm(range_1(tr + zone / 24 - dt) * 24);\n if (i == 1) document.planets.tr1.value = tr;\n if (i == 2) document.planets.tr2.value = tr;\n if (i == 3) document.planets.tr3.value = tr;\n if (i == 4) document.planets.tr4.value = tr;\n if (i == 5) document.planets.tr5.value = tr;\n\n if (i == 1) document.planets.tr1_2.value = tr;\n if (i == 2) document.planets.tr2_2.value = tr;\n if (i == 3) document.planets.tr3_2.value = tr;\n if (i == 4) document.planets.tr4_2.value = tr;\n if (i == 5) document.planets.tr5_2.value = tr;\n }\n\n al = al * RAD;\n az = az * RAD;\n planet_altitude[i] = al;\n planet_azimuth[i] = az;\n\n de = de * RAD;\n ra = ra * RAD / 15;\n\n x = round_10(abs(de));\n if (de < 0)\n {\n planet_dec[i] += \"-\";\n }\n else\n {\n planet_dec[i] += \"+\";\n }\n if (x < 10) planet_dec[i] += \"0\";\n planet_dec[i] += x;\n if (x == floor(x)) planet_dec[i] += \".0\";\n planet_dec[i] += \"\\u00B0\";\n\n x = floor(ra);\n y = floor((ra - x) * 60 + 0.5);\n if (y == 60)\n {\n x += 1;\n y = 0;\n }\n if (x < 10) planet_ra[i] += \"0\";\n planet_ra[i] += x + \"h \";\n if (y < 10) planet_ra[i] += \"0\";\n planet_ra[i] += y + \"m\";\n\n dr = round_100(dr);\n if (dr < 10)\n planet_dist[i] += \"0\";\n planet_dist[i] += dr;\n\n size = round_10(size);\n if (size < 10)\n planet_size[i] += \"0\";\n planet_size[i] += size;\n if (size == floor(size)) planet_size[i] += \".0\";\n planet_size[i] += \"\\\"\";\n\n planet_phase[i] += il + \"%\";\n\n planet_alt[i] = rise_str;\n planet_az[i] = set_str;\n\n }\n\n dawn_planets = \"\";\n dusk_planets = \"\";\n phenomena = \"\";\n\n y = sin(-9/RAD) - sin(la) * sin(planet_decl[0]);\n x = cos(la) * cos(planet_decl[0]);\n if (y/x >= 1)\n {\n\n dawn_planets = \"-----\";\n dusk_planets = \"-----\";\n }\n if (y/x <= -1)\n {\n\n dawn_planets = \"-----\";\n dusk_planets = \"-----\";\n }\n if (abs(y/x) < 1)\n {\n h0 = acos(y/x) * RAD;\n tr = range_1((planet_r_a[0] * RAD + lo * RAD - g0 * RAD) / 360);\n dawn = range_1(tr - h0 / 360 - dt);\n dusk = range_1(tr + h0 / 360 - dt);\n }\n gt_dawn = proper_ang_rad(g0 + dawn * 6.30038808);\n gt_dusk = proper_ang_rad(g0 + dusk * 6.30038808);\n\n indx = 0;\n morn = 0;\n eve = 0;\n for (i=0; i<17; i++)\n {\n\n if (i < 6)\n {\n ha = proper_ang_rad(gt_dawn - lo - planet_r_a[i]);\n al = asin(sin(la) * sin(planet_decl[i]) + cos(la) * cos(planet_decl[i]) * cos(ha));\n\n if (al >= 0)\n {\n if (morn > 0) dawn_planets += \", \";\n dawn_planets += planet_name[i];\n morn ++;\n }\n\n ha = proper_ang_rad(gt_dusk - lo - planet_r_a[i]);\n al = asin(sin(la) * sin(planet_decl[i]) + cos(la) * cos(planet_decl[i]) * cos(ha));\n\n if (al >= 0)\n {\n if (eve > 0) dusk_planets += \", \";\n dusk_planets += planet_name[i];\n eve ++;\n }\n }\n\n x = round_10(acos(sin(planet_decl[6]) * sin(planet_decl[i]) + cos(planet_decl[6]) * cos(planet_decl[i]) * cos(planet_r_a[6] - planet_r_a[i])) * RAD);\n\n if (x <= 10 && i != 6)\n {\n if (indx > 0) phenomena += \" and \";\n if (x < 1)\n {\n phenomena += \"less than 1\";\n }\n else\n {\n phenomena += floor(x + 0.5);\n }\n phenomena += \"\\u00B0\" + \" from \" + planet_name[i];\n if (x < 0.5)\n {\n if (i == 0)\n {\n phenomena += \" (eclipse possible)\";\n }\n else\n {\n phenomena += \" (occultation possible)\";\n }\n }\n indx ++\n }\n }\n\n if (dawn_planets == \"\") dawn_planets = \"-----\";\n if (dusk_planets == \"\") dusk_planets = \"-----\";\n\n if (indx > 0)\n {\n phenomena = \"The Moon is \" + phenomena + \". \";\n }\n indx = 0;\n for (i=1; i<16; i++)\n {\n for (count=i+1; count<17; count++)\n {\n if (i != 6 && count != 6)\n {\n x = round_10(acos(sin(planet_decl[count]) * sin(planet_decl[i]) + cos(planet_decl[count]) * cos(planet_decl[i]) * cos(planet_r_a[count] - planet_r_a[i])) * RAD);\n if (x <= 5)\n {\n if (indx > 0) phenomena += \" and \";\n phenomena += planet_name[count] + \" is \";\n if (x < 1)\n {\n phenomena += \"less than 1\";\n }\n else\n {\n phenomena += floor(x + 0.5);\n }\n phenomena += \"\\u00B0\" + \" from \" + planet_name[i];\n indx ++\n }\n x = 0;\n }\n }\n }\n if (indx > 0) phenomena += \".\";\n\n if (jd > 2454048.3007 && jd < 2454048.5078)\n {\n phenomena += \"\\nMercury is transiting the face of the Sun. \";\n x = round_10((2454048.50704 - jd) * 24);\n if (x >= 0.1)\n {\n phenomena += \"The spectacle continues for a further \" + x + \" hours.\"\n }\n }\n\n if (phenomena != \"\") { phenomena += \"\\n\"; }\n if (planet_altitude[0] < -18) phenomena += \"The sky is dark. \";\n if (planet_altitude[0] >= -18 && planet_altitude[0] < -12) phenomena += \"The Sun is below the horizon (altitude \" + floor(planet_altitude[0] + 0.5) + \"\\u00B0) and the sky is in deep twilight. \";\n if (planet_altitude[0] >= -12 && planet_altitude[0] < -6) phenomena += \"The Sun is below the horizon (altitude \" + floor(planet_altitude[0] + 0.5) + \"\\u00B0) and the sky is in twilight. \";\n if (planet_altitude[0] >= -6 && planet_altitude[0] < -0.3) phenomena += \"The Sun is below the horizon (altitude \" + floor(planet_altitude[0] + 0.5) + \"\\u00B0) and the sky is in bright twilight. \";\n if (planet_altitude[0] >= -0.3) phenomena += \"The Sun is above the horizon (altitude \" + floor(planet_altitude[0] + 0.5) + \"\\u00B0). \";\n if (planet_altitude[6] >= -0.3) phenomena += \"The Moon is above the horizon (altitude \" + floor(planet_altitude[6] + 0.5) + \"\\u00B0). \";\n if (planet_altitude[6] < -0.3) phenomena += \"The Moon is below the horizon. \";\n phenomena += \"\\n\";\n phenomena += moon_data;\n\n /* Commented out 2009-specific events 2010/01/27 - DAF\n phenomena += \"-----\\n2009 Phenomena\\n\";\n phenomena += \"yyyy mm dd hh UT All dates and times are UT\\n\"\n + \"2009 01 02 04 UT Mercury at greatest illuminated extent (evening)\\n\"\n + \"2009 01 03 13 UT Meteor shower peak -- Quadrantids\\n\"\n + \"2009 01 04 14 UT Mercury at greatest elongation, 19.3\\u00B0 east of Sun (evening)\\n\"\n + \"2009 01 04 16 UT Earth at perihelion 91,400,939 miles (147,095,552 km)\\n\"\n + \"2009 01 10 11 UT Moon at perigee, 222,137 miles (357,495 km)\\n\"\n + \"2009 01 14 21 UT Venus at greatest elongation, 47.1\\u00B0 east of Sun (evening)\\n\"\n + \"2009 01 23 00 UT Moon at apogee, 252,350 miles (406,118 km)\\n\"\n + \"2009 01 26 Annular eclipse of the Sun (South Atlantic, Indonesia)\\n\"\n + \"2009 02 07 20 UT Moon at perigee, 224,619 miles (361,489 km)\\n\"\n + \"2009 02 09 14:38 UT Penumbral lunar eclipse (midtime)\\n\"\n + \"2009 02 11 01 UT Mercury at greatest illuminated extent (morning)\\n\"\n + \"2009 02 13 21 UT Mercury at greatest elongation, 26.1\\u00B0 west of Sun (morning)\\n\"\n + \"2009 02 19 16 UT Venus at greatest illuminated extent (evening)\\n\"\n + \"2009 02 19 17 UT Moon at apogee, 251,736 miles (405,129 km)\\n\"\n + \"2009 03 07 15 UT Moon at perigee, 228,053 miles (367,016 km)\\n\"\n + \"2009 03 08 20 UT Saturn at opposition\\n\"\n + \"2009 03 19 13 UT Moon at apogee, 251,220 miles (404,299 km)\\n\"\n + \"2009 03 20 11:44 UT Spring (Northern Hemisphere) begins at the equinox\\n\"\n + \"2009 03 27 19 UT Venus at inferior conjunction with Sun\\n\"\n + \"2009 04 02 02 UT Moon at perigee, 229,916 miles (370,013 km)\\n\"\n + \"2009 04 13 05 UT Mercury at greatest illuminated extent (evening)\\n\"\n + \"2009 04 16 09 UT Moon at apogee, 251,178 miles (404,232 km)\\n\"\n + \"2009 04 22 11 UT Meteor shower peak -- Lyrids\\n\"\n + \"2009 04 26 08 UT Mercury at greatest elongation, 20.4\\u00B0 east of Sun (evening)\\n\"\n + \"2009 04 28 06 UT Moon at perigee, 227,446 miles (366,039 km)\\n\"\n + \"2009 05 02 14 UT Venus at greatest illuminated extent (morning)\\n\"\n + \"2009 05 06 00 UT Meteor shower peak -- Eta Aquarids\\n\"\n + \"2009 05 14 03 UT Moon at apogee, 251,603 miles (404,915 km)\\n\"\n + \"2009 05 26 04 UT Moon at perigee, 224,410 miles (361,153 km)\\n\"\n + \"2009 06 05 21 UT Venus at greatest elongation, 45.8\\u00B0 west of Sun (morning)\\n\"\n + \"2009 06 10 16 UT Moon at apogee, 252,144 miles (405,787 km)\\n\"\n + \"2009 06 13 12 UT Mercury at greatest elongation, 23.5\\u00B0 west of Sun (morning)\\n\"\n + \"2009 06 21 05:46 UT Summer (Northern Hemisphere) begins at the solstice\\n\"\n + \"2009 06 23 11 UT Moon at perigee, 222,459 miles (358,013 km)\\n\"\n + \"2009 07 03 21 UT Mercury at greatest illuminated extent (morning)\\n\"\n + \"2009 07 04 02 UT Earth at aphelion 94,505,048 miles (152,091,132 km)\\n\"\n + \"2009 07 07 09:39 UT Penumbral lunar eclipse (too slight to see)\\n\"\n + \"2009 07 07 22 UT Moon at apogee, 252,421 miles (406,232 km)\\n\"\n + \"2009 07 21 20 UT Moon at perigee, 222,118 miles (357,464 km)\\n\"\n + \"2009 07 22 Total solar eclipse (India, China, and a few Pacific islands)\\n\"\n + \"2009 07 28 02 UT Meteor shower peak -- Delta Aquarids\\n\"\n + \"2009 08 04 01 UT Moon at apogee, 252,294 miles (406,028 km)\\n\"\n + \"2009 08 06 00:39 UT Weak penumbral lunar eclipse (midtime)\\n\"\n + \"2009 08 12 17 UT Meteor shower peak -- Perseids\\n\"\n + \"2009 08 14 18 UT Jupiter at opposition\\n\"\n + \"2009 08 17 21 UT Neptune at opposition\\n\"\n + \"2009 08 19 05 UT Moon at perigee, 223,469 miles (359,638 km)\\n\"\n + \"2009 08 24 16 UT Mercury at greatest elongation, 27.4\\u00B0 east of Sun (evening)\\n\"\n + \"2009 08 26 09 UT Mercury at greatest illuminated extent (evening)\\n\"\n + \"2009 08 31 11 UT Moon at apogee, 251,823 miles (405,269 km)\\n\"\n + \"2009 09 16 08 UT Moon at perigee, 226,211 miles (364,052 km)\\n\"\n + \"2009 09 17 09 UT Uranus at opposition\\n\"\n + \"2009 09 22 21:19 UT Fall (Northern Hemisphere) begins at the equinox\\n\"\n + \"2009 09 28 04 UT Moon at apogee, 251,302 miles (404,432 km)\\n\"\n + \"2009 10 06 02 UT Mercury at greatest elongation, 17.9\\u00B0 west of Sun (morning)\\n\"\n + \"2009 10 11 07 UT Mercury at greatest illuminated extent (morning)\\n\"\n + \"2009 10 13 12 UT Moon at perigee, 229,327 miles (369,066 km)\\n\"\n + \"2009 10 21 10 UT Meteor shower peak -- Orionids\\n\"\n + \"2009 10 25 23 UT Moon at apogee, 251,137 miles (404,166 km)\\n\"\n + \"2009 11 05 10 UT Meteor shower peak -- Southern Taurids\\n\"\n + \"2009 11 07 07 UT Moon at perigee, 229,225 miles (368,902 km)\\n\"\n + \"2009 11 12 10 UT Meteor shower peak -- Northern Taurids\\n\"\n + \"2009 11 17 15 UT Meteor shower peak -- Leonids\\n\"\n + \"2009 11 22 20 UT Moon at apogee, 251,489 miles (404,733 km)\\n\"\n + \"2009 12 04 14 UT Moon at perigee, 225,856 miles (363,481 km)\\n\"\n + \"2009 12 14 05 UT Meteor shower peak -- Geminids\\n\"\n + \"2009 12 17 13 UT Mercury at greatest illuminated extent (evening)\\n\"\n + \"2009 12 18 17 UT Mercury at greatest elongation, 20.3\\u00B0 east of Sun (evening)\\n\"\n + \"2009 12 20 15 UT Moon at apogee, 252,109 miles (405,731 km)\\n\"\n + \"2009 12 21 17:47 UT Winter (Northern Hemisphere) begins at the solstice\\n\"\n + \"2009 12 31 Partial lunar eclipse, 18:52 UT to 19:54 UT\\n-----\\n\";\n END Comment DAF */\n\n document.planets.ra1.value = planet_ra[1];\n document.planets.dec1.value = planet_dec[1];\n document.planets.dist1.value = planet_mag[1];\n document.planets.size1.value = planet_size[1];\n document.planets.phase1.value = planet_phase[1];\n document.planets.alt1.value = planet_alt[1];\n document.planets.az1.value = planet_az[1];\n\n document.planets.ra1_2.value = planet_ra[1];\n document.planets.dec1_2.value = planet_dec[1];\n document.planets.dist1_2.value = planet_mag[1];\n document.planets.size1_2.value = planet_size[1];\n document.planets.phase1_2.value = planet_phase[1];\n document.planets.alt1_2.value = planet_alt[1];\n document.planets.az1_2.value = planet_az[1];\n\n document.planets.ra2.value = planet_ra[2];\n document.planets.dec2.value = planet_dec[2];\n document.planets.dist2.value = planet_mag[2];\n document.planets.size2.value = planet_size[2];\n document.planets.phase2.value = planet_phase[2];\n document.planets.alt2.value = planet_alt[2];\n document.planets.az2.value = planet_az[2];\n\n document.planets.ra2_2.value = planet_ra[2];\n document.planets.dec2_2.value = planet_dec[2];\n document.planets.dist2_2.value = planet_mag[2];\n document.planets.size2_2.value = planet_size[2];\n document.planets.phase2_2.value = planet_phase[2];\n document.planets.alt2_2.value = planet_alt[2];\n document.planets.az2_2.value = planet_az[2];\n\n document.planets.ra3.value = planet_ra[3];\n document.planets.dec3.value = planet_dec[3];\n document.planets.dist3.value = planet_mag[3];\n document.planets.size3.value = planet_size[3];\n document.planets.phase3.value = planet_phase[3];\n document.planets.alt3.value = planet_alt[3];\n document.planets.az3.value = planet_az[3];\n\n document.planets.ra3_2.value = planet_ra[3];\n document.planets.dec3_2.value = planet_dec[3];\n document.planets.dist3_2.value = planet_mag[3];\n document.planets.size3_2.value = planet_size[3];\n document.planets.phase3_2.value = planet_phase[3];\n document.planets.alt3_2.value = planet_alt[3];\n document.planets.az3_2.value = planet_az[3];\n\n document.planets.ra4.value = planet_ra[4];\n document.planets.dec4.value = planet_dec[4];\n document.planets.dist4.value = planet_mag[4];\n document.planets.size4.value = planet_size[4];\n // document.planets.phase4.value = planet_phase[4];\n document.planets.alt4.value = planet_alt[4];\n document.planets.az4.value = planet_az[4];\n\n document.planets.ra4_2.value = planet_ra[4];\n document.planets.dec4_2.value = planet_dec[4];\n document.planets.dist4_2.value = planet_mag[4];\n document.planets.size4_2.value = planet_size[4];\n // document.planets.phase4_2.value = planet_phase[4];\n document.planets.alt4_2.value = planet_alt[4];\n document.planets.az4_2.value = planet_az[4];\n\n document.planets.ra5.value = planet_ra[5];\n document.planets.dec5.value = planet_dec[5];\n document.planets.dist5.value = planet_mag[5];\n document.planets.size5.value = planet_size[5];\n // document.planets.phase5.value = planet_phase[5];\n document.planets.alt5.value = planet_alt[5];\n document.planets.az5.value = planet_az[5];\n\n document.planets.ra5_2.value = planet_ra[5];\n document.planets.dec5_2.value = planet_dec[5];\n document.planets.dist5_2.value = planet_mag[5];\n document.planets.size5_2.value = planet_size[5];\n // document.planets.phase5_2.value = planet_phase[5];\n document.planets.alt5_2.value = planet_alt[5];\n document.planets.az5_2.value = planet_az[5];\n\n document.planets.dist6.value = planet_dist[6];\n document.planets.size6.value = sunrise_set;\n document.planets.phase6.value = phenomena;\n document.planets.dawn.value = dawn_planets;\n document.planets.dusk.value = dusk_planets;\n document.planets.size7.value = moonrise_set;\n document.planets.phase7.value = twilight_begin_end;\n\n document.planets.ra8.value = planet_ra[8];\n document.planets.dec8.value = planet_dec[8];\n document.planets.dist8.value = planet_mag[0];\n document.planets.size8.value = planet_size[8];\n document.planets.alt8.value = planet_alt[8];\n document.planets.az8.value = planet_az[8];\n\n document.planets.ra8_2.value = planet_ra[8];\n document.planets.dec8_2.value = planet_dec[8];\n document.planets.dist8_2.value = planet_mag[0];\n document.planets.size8_2.value = planet_size[8];\n document.planets.alt8_2.value = planet_alt[8];\n document.planets.az8_2.value = planet_az[8];\n\n document.planets.ra9.value = planet_ra[9];\n document.planets.dec9.value = planet_dec[9];\n document.planets.dist9.value = planet_mag[6];\n document.planets.size9.value = planet_size[9];\n document.planets.phase9.value = planet_phase[9];\n document.planets.alt9.value = planet_alt[9];\n document.planets.az9.value = planet_az[9];\n\n document.planets.ra9_2.value = planet_ra[9];\n document.planets.dec9_2.value = planet_dec[9];\n document.planets.dist9_2.value = planet_mag[6];\n document.planets.size9_2.value = planet_size[9];\n document.planets.phase9_2.value = planet_phase[9];\n document.planets.alt9_2.value = planet_alt[9];\n document.planets.az9_2.value = planet_az[9];\n\n }\n}", "DetermineBestSupportingPosition() {\n //only update the spots every few frames \n if ( !this.m_pRegulator.isReady() && this.m_pBestSupportingSpot != null ) {\n return this.m_pBestSupportingSpot.m_vPos;\n };\n\n //reset the best supporting spot\n this.m_pBestSupportingSpot = null;\n\n let BestScoreSoFar = 0.0;\n\n //let it = m_Spots.listIterator();\n\n //while ( it.hasNext() ) {\n // let curSpot = it.next();\n\n\n for( let it = 0, size = this.m_Spots.length; it < size; it++ ){\n\n let curSpot = this.m_Spots[ it ];\n\n //first remove any previous score. (the score is set to one so that\n //the viewer can see the positions of all the spots if he has the \n //aids turned on)\n curSpot.m_dScore = 1.0;\n\n //Test 1. is it possible to make a safe pass from the ball's position \n //to this position?\n if ( this.m_pTeam.isPassSafeFromAllOpponents( this.m_pTeam.ControllingPlayer().Pos(),\n curSpot.m_vPos,\n null,\n Prm.MaxPassingForce ) ) {\n curSpot.m_dScore += Prm.Spot_PassSafeScore;\n };\n\n\n //Test 2. Determine if a goal can be scored from this position. \n if ( this.m_pTeam.CanShoot( curSpot.m_vPos,\n Prm.MaxShootingForce ) ) {\n curSpot.m_dScore += Prm.Spot_CanScoreFromPositionScore;\n };\n\n\n //Test 3. calculate how far this spot is away from the controlling\n //player. The further away, the higher the score. Any distances further\n //away than OptimalDistance pixels do not receive a score.\n if ( this.m_pTeam.SupportingPlayer() != null ) {\n\n let OptimalDistance = 200.0;\n\n let dist = Vector2D.Vec2DDistance( this.m_pTeam.ControllingPlayer().Pos(),\n curSpot.m_vPos );\n\n let temp = Math.abs( OptimalDistance - dist );\n\n if ( temp < OptimalDistance ) {\n\n //normalize the distance and add it to the score\n curSpot.m_dScore += Prm.Spot_DistFromControllingPlayerScore\n * ( OptimalDistance - temp ) / OptimalDistance;\n };\n };\n\n //check to see if this spot has the highest score so far\n if ( curSpot.m_dScore > BestScoreSoFar ) {\n BestScoreSoFar = curSpot.m_dScore;\n\n this.m_pBestSupportingSpot = curSpot;\n };\n\n };\n\n return this.m_pBestSupportingSpot.m_vPos;\n }", "function ActualiserPointsVie(){\n\t//les PDV diminuent si le joueur s'eloigne des artefacts (zoneSure) sans lumiere (torcheJoueur)\n\tif(transform.Find(\"torcheJoueur(Clone)\") == null && !zoneSure){\n\t\tif(vitesseCorruption < 0){\n\t\t\tvitesseCorruption = 0;\n\t\t}else{\n\t\t\tvitesseCorruption += Time.deltaTime/2;\n\t\t}\n\t\tpointsVie -= vitesseCorruption*Time.deltaTime;\n\t} else{\n\t\t//la vitesse de reduction des PDV diminue jusqu'a 0\n\t\tif(vitesseCorruption > 0){\n\t\t\tvitesseCorruption -= Time.deltaTime*2;\n\t\t}else{\n\t\t\tvitesseCorruption = 0;\n\t\t\t//soigne si la vitesse de corruption est 0 et le joueur a obtenu la potion\n\t\t\tif(Joueur.powerUpPotion){\n\t\t\t\tpointsVie += Time.deltaTime;\n\t\t\t}\n\t\t}\n\t\t\n\t\t\n\t}\n\t//actualise l'element visuel\n\tbarreVie.fillAmount = pointsVie/pointsVieMax;\n}", "function xmovingplane() {\n xmoveplane = xmoveplane+ 10;\n\n // document.querySelector(\".check\").style.left = xmoveplane + \"px\";\n document.querySelector(\".planes\").style.left = xmoveplane + \"px\";\n if (xmoveplane > 1400) {\n xmoveplane = -400;\n }\n\n console.log(xmoveplane);\n}", "function getallVillagePos(){\n\ttry {\n\t\t// GotGs 2011.01.15 -- Cannot get all Village Positions if the current page is the profile page of the expansion page in palace/residence.\n\t\t//flag ( \"getallVillagePos():: Started!\" );\n\t\tif ( window.location.href.indexOf(\"spieler.php?\") == -1 ) { // when not in profile page get all village positions.\n\t\t\tvar allposition = new Array();\n\t\t\tvar allposition2 = new Array();\n\t\t\tswitch ( aTravianVersion ) {\n\t\t\t\tcase \"3.6\":\n\t\t\t\t\t// this works with travian beyond enabled and when disabled, particularly when user has a single village.\n\t\t\t\t\tvar xpathAllX = 'id(\"vlist\")//td[@class=\"aligned_coords\"]//div[@class=\"cox\"]';\n\t\t\t\t\tvar xpathAllY = 'id(\"vlist\")//td[@class=\"aligned_coords\"]//div[@class=\"coy\"]';\n\t\t\t\t\tvar xpathAllN = 'id(\"vlist\")//td[contains(@class,\"link\")]//a[contains(@href,\"newdid\")]';\n\t\t\t\t\tvar allX = document.evaluate(xpathAllX, document, null, XPOrdList, null);\n\t\t\t\t\tvar allY = document.evaluate(xpathAllY, document, null, XPOrdList, null);\n\t\t\t\t\tvar allN = document.evaluate(xpathAllN, document, null, XPOrdList, null);\n\t\t\t\t\t//flag ( \"getallVillagePos():: allX.snapshotLength: \" + allX.snapshotLength );\n\t\t\t\t\t//flag ( \"getallVillagePos():: allY.snapshotLength: \" + allY.snapshotLength );\n\t\t\t\t\t//flag ( \"getallVillagePos():: allN.snapshotLength: \" + allN.snapshotLength );\n\t\t\t\t\tif ( allN.snapshotLength > 0 && allN.snapshotLength == allX.snapshotLength && allX.snapshotLength == allY.snapshotLength ) { // when more than 1 village\n\t\t\t\t\t\tfor (var i = 0; i < allN.snapshotLength; i++) {\n\t\t\t\t\t\t\tvar xx = (allX.snapshotItem(i).innerHTML.split(\"(\")[1]) ? \n\t\t\t\t\t\t\t\tallX.snapshotItem(i).innerHTML.split(\"(\")[1] : allX.snapshotItem(i).nextSibling.innerHTML;\n\t\t\t\t\t\t\tvar yy = (allY.snapshotItem(i).innerHTML.split(\")\")[0]) ? \n\t\t\t\t\t\t\t\tallY.snapshotItem(i).innerHTML.split(\")\")[0] : allY.snapshotItem(i).previousSibling.innerHTML;\n\t\t\t\t\t\t\tvar na = allN.snapshotItem(i).innerHTML + \":\" + getCoordfromXY(xx, yy);\n\t\t\t\t\t\t\tvar na2 = allN.snapshotItem(i).href.match(/newdid=\\d{1,}/)[0].match(/\\d{1,}/)[0] + \":\" + getCoordfromXY(xx, yy);\n\t\t\t\t\t\t\t//flag ( \"getallVillagePos():: i: \" + i + \", xx: \" + xx + \", yy: \" + yy + \", na: \" + na + \", na2: \" + na2 );\n\t\t\t\t\t\t\tallposition.push(na);\n\t\t\t\t\t\t\tallposition2.push(na2);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\telse { // when single village\n\t\t\t\t\t\tallposition[0] = GM_getValue(myacc() + \"_mainvillageName\") + \":\" + GM_getValue(myacc() + \"_mainVillagePosition\");\n\t\t\t\t\t\tallposition2[0] = GM_getValue(myacc() + \"_singleTownNEWDID\") + \":\" + GM_getValue(myacc() + \"_mainVillagePosition\");\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"4.0\":\n\t\t\t\t\tvar xpathVillages = 'id(\"villageList\")//li/a[contains(@href,\"newdid=\")]';\n\t\t\t\t\tvar allVillages = document.evaluate(xpathVillages, document, null, XPOrdList, null);\n\t\t\t\t\tif ( allVillages.snapshotLength > 0 ) {\n\t\t\t\t\t\tfor (var i = 0; i < allVillages.snapshotLength; i++) {\n\t\t\t\t\t\t\tvar title = allVillages.snapshotItem(i).getAttribute(\"title\");\n\t\t\t\t\t\t\t//flag ( \"getallVillagePos():: i: \" + i + \", title: \" + title );\n\t\t\t\t\t\t\t//var xx = title.match(/\\([-0-9]{1,}\\|/)[0].match(/[-0-9]{1,}/)[0];\n\t\t\t\t\t\t\t//var yy = title.match(/\\|[-0-9]{1,}\\)/)[0].match(/[-0-9]{1,}/)[0];\n\t\t\t\t\t\t\tvar xx = title.match(/\\([-0-9]{1,}\\|/);\n\t\t\t\t\t\t\tvar yy = title.match(/\\|[-0-9]{1,}\\)/);\n\t\t\t\t\t\t\t//flag ( \"getallVillagePos():: Title xx: \" + xx + \", yy: \" + yy );\n\t\t\t\t\t\t\tif ( xx != null && yy != null ) {\n\t\t\t\t\t\t\t\txx = xx[0].match(/[-0-9]{1,}/)[0];\n\t\t\t\t\t\t\t\tyy = yy[0].match(/[-0-9]{1,}/)[0];\n\t\t\t\t\t\t\t\t//flag ( \"getallVillagePos():: Title Final xx: \" + xx + \", yy: \" + yy );\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\tvar elem = document.createElement('div');\n\t\t\t\t\t\t\t\telem.innerHTML = title;\n\t\t\t\t\t\t\t\t//flag ( \"getallVillagePos():: i: \" + i + \", elem.innerHTML: \" + elem.innerHTML );\n\t\t\t\t\t\t\t\t//flag ( \"getallVillagePos():: i: \" + i + \", elem.textContent: \" + elem.textContent );\n\t\t\t\t\t\t\t\txx = elem.textContent.match(/\\([-0-9]{1,}\\|/);\n\t\t\t\t\t\t\t\tyy = elem.textContent.match(/\\|[-0-9]{1,}\\)/);\n\t\t\t\t\t\t\t\t//flag ( \"getallVillagePos():: Div xx: \" + xx + \", yy: \" + yy );\n\t\t\t\t\t\t\t\tif ( xx != null && yy != null ) {\n\t\t\t\t\t\t\t\t\txx = xx[0].match(/[-0-9]{1,}/)[0];\n\t\t\t\t\t\t\t\t\tyy = yy[0].match(/[-0-9]{1,}/)[0];\n\t\t\t\t\t\t\t\t\t//flag ( \"getallVillagePos():: Div Final xx: \" + xx + \", yy: \" + yy );\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\telse { // this is weird for travian.ir\n\t\t\t\t\t\t\t\t\txx = document.evaluate ( './/span/span[ @class=\"coordinatex\" or @class=\"coordinateX\" ]', elem, null, XPFirst, null).singleNodeValue;\n\t\t\t\t\t\t\t\t\tyy = document.evaluate ( './/span/span[ @class=\"coordinatey\" or @class=\"coordinateY\" ]', elem, null, XPFirst, null).singleNodeValue;\n\t\t\t\t\t\t\t\t\t//xx = elem.textContent.match(/\\|\\([-0-9]{1,}/);\n\t\t\t\t\t\t\t\t\t//yy = elem.textContent.match(/[-0-9]{1,}\\)\\|/);\n\t\t\t\t\t\t\t\t\tif ( xx != null && yy != null ) {\n\t\t\t\t\t\t\t\t\t\txx = xx.innerHTML.match(/[-0-9]{1,}/)[0];\n\t\t\t\t\t\t\t\t\t\tyy = yy.innerHTML.match(/[-0-9]{1,}/)[0];\n\t\t\t\t\t\t\t\t\t\t//xx = xx[0].match(/[-0-9]{1,}/)[0];\n\t\t\t\t\t\t\t\t\t\t//yy = yy[0].match(/[-0-9]{1,}/)[0];\n\t\t\t\t\t\t\t\t\t\t//flag ( \"getallVillagePos():: Div Inner xx: \" + xx + \", yy: \" + yy );\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\tthrowLogicError ( \"getallVillagePos():: Cannot get village coordinates!\" );\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//flag ( \"getallVillagePos():: Final xx: \" + xx + \", yy: \" + yy );\n\t\t\t\t\t\t\tvar na = allVillages.snapshotItem(i).innerHTML + \":\" + getCoordfromXY(xx, yy);\n\t\t\t\t\t\t\tvar did = allVillages.snapshotItem(i).href.match(/\\bnewdid=\\d{1,}\\b/)[0].match(/\\d{1,}/)[0];\n\t\t\t\t\t\t\tvar na2 = did + \":\" + getCoordfromXY(xx, yy);\n\t\t\t\t\t\t\t//flag ( \"getallVillagePos():: i: \" + i + \", title: \" + title + \", xx: \" + xx + \", yy: \" + yy + \", na: \" + na + \", na2: \" + na2 );\n\t\t\t\t\t\t\t//flag ( \"getallVillagePos():: i: \" + i + \", xx: \" + xx + \", yy: \" + yy + \", na: \" + na + \", na2: \" + na2 );\n\t\t\t\t\t\t\tallposition.push(na);\n\t\t\t\t\t\t\tallposition2.push(na2);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tthrowLogicError ( \"getallVillagePos():: Cannot get village list!\" );\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tthrowLogicError ( \"getallVillagePos():: Travian Version not set!!\" );\n\t\t\t}\n\t\t\tGM_setValue(myacc() + \"_allVillagePos\", allposition.join(\",\"));\n\t\t\tGM_setValue(myacc() + \"_allVillagePos2\", allposition2.join(\",\"));\n\t\t}\n\t}\n\tcatch ( err ) {\n\t\tprintStackTrace();\n\t\tvar msg = \"<b>getallVillagePos():: Something went wrong, error: \" + err.name + \", Error Message: \" + err.message + \"</b>\";\n\t\tplaySound ( msg );\n\t\tprintErrorMSG(msg);\n\t\tthrow err;\n\t}\n}", "function parliamentViewPositions() {\n const seats = []\n const { maxSeatNumber, nRows, b } = calcMaxSeatNumber(opts)\n const rowWidth = (opts.outerParliamentRadius - opts.innerParliementRadius) / nRows\n const seatsToRemove = maxSeatNumber - opts.nSeats\n let k = 0\n for (let i = 0; i < nRows; i++) {\n const rowRadius = opts.innerParliementRadius + rowWidth * (i + 0.5)\n const rowSeats = opts.aligned\n ? Math.ceil(opts.nSeats / nRows)\n : Math.floor(Math.PI * (b + i))\n - Math.floor(seatsToRemove / nRows)\n - (seatsToRemove % nRows > i ? 1 : 0)\n\n const anglePerSeat = Math.PI / rowSeats\n for (let j = 0; j < rowSeats; j++) {\n if (k >= opts.nSeats) break\n const s = {}\n s.polar = {\n rw: rowWidth,\n r: rowRadius,\n teta: -Math.PI + anglePerSeat * (j + 0.5),\n }\n s.rotation = 180 / (rowSeats - 1) * j\n s.cartesian = {\n x: s.polar.r * Math.cos(s.polar.teta),\n y: s.polar.r * Math.sin(s.polar.teta),\n }\n seats.push(s)\n k++\n }\n }\n /* sort the seats by angle */\n seats.sort((a, b) => a.polar.teta - b.polar.teta || b.polar.r - a.polar.r)\n\n return seats\n }", "calculVitesseX(){\r\n //rajout de 1 facteur\r\n if (this.vitesseXFacteur < this.limiteFacteur){\r\n this.vitesseXFacteur +=1; // faire en fonction de la largeur du terrain\r\n }\r\n else {/*rien car la vitesse ne peux pas depasser la limite*/}\r\n }", "function checkIntersect() {\n if (player.x >= graveOne.x - 30 && player.x <= graveOne.x + 30) {\n if (alive[0] == true) {\n showE = true;\n if (dig == true) {\n alive[0] = false;\n console.log(freeInv);\n generateHealth();\n freeInv = freeInv + 1;\n dig = false;\n }\n }\n }\n else if (player.x >= graveTwo.x - 30 && player.x <= graveTwo.x + 30) {\n if (alive[1] == true) {\n showE = true;\n if (dig == true) {\n alive[1] = false;\n console.log(freeInv);\n generateHealth();\n freeInv = freeInv + 1\n dig = false;\n }\n }\n }\n else if (player.x >= graveThree.x - 30 && player.x <= graveThree.x + 30) {\n if (alive[2] == true) {\n showE = true;\n if (dig == true) {\n alive[2] = false;\n console.log(freeInv);\n generateHealth();\n freeInv = freeInv + 1\n dig = false;\n }\n }\n }\n else if (player.x >= graveFour.x - 30 && player.x <= graveFour.x + 30) {\n if (alive[3] == true) {\n showE = true;\n if (dig == true) {\n alive[3] = false;\n generateWeapon();\n dig = false;\n }\n }\n }\n else {\n showE = false;\n dig = false;\n }\n\n}", "function setPointBalls() {\n let five_point = Math.floor(ball_amount*0.6);\n let fifteen_point = Math.floor(ball_amount*0.3);\n let twentyFive_point = Math.floor(ball_amount*0.1);\n let free_spot;\n\n while (ball_count < ball_amount){\n if (five_point > 0){\n free_spot = findRandomSpot(board_static);\n board_static[free_spot.i][free_spot.j] = 5;\n five_point--;\n ball_count++;\n }\n if (fifteen_point > 0){\n free_spot = findRandomSpot(board_static);\n board_static[free_spot.i][free_spot.j] = 15;\n fifteen_point--;\n ball_count++;\n }\n if (twentyFive_point > 0){\n free_spot = findRandomSpot(board_static);\n board_static[free_spot.i][free_spot.j] = 25;\n twentyFive_point--;\n ball_count++;\n }\n if (five_point === 0 && ball_count<ball_amount){\n five_point++;\n }\n }\n\n}", "function portals(maxTime, manacost) {\n\n let isVisited = new Array(manacost.length).fill([])\n isVisited = isVisited.map(v => new Array(manacost[0].length).fill(0))\n\n isInRange = (x, y) => x >= 0 && y >= 0 && x < manacost.length\n && y < manacost[0].length\n\n isDupCoord = ([x, y], [a, b]) => x == a && y == b\n\n const direction = [[-1, 0], [0, 1], [1, 0], [0, -1]]\n\n bfs = ([x, y], signal) => {\n let res = []\n\n let queue = [{x, y, time: 0, manaCost: manacost[x][y]}]\n isVisited[x][y] = 1\n while(queue.length > 0){\n let data = queue.shift()\n\n if(data.time > maxTime)\n continue;\n\n if(data.x == manacost.length-1 && data.y == manacost[0].length-1 && signal)\n return 0\n\n res.push(data)\n\n for(let d of direction){\n let dX = d[0] + data.x\n let dY = d[1] + data.y\n if(isInRange(dX, dY) && isVisited[dX][dY] == 0 && manacost[dX][dY] > -1){\n isVisited[dX][dY] = 1\n queue.push({x: dX, y: dY, time: data.time + 1, manaCost: manacost[dX][dY]})\n }\n }\n }\n\n\n return res\n }\n\n let topToDown = bfs([0, 0], true)\n if(topToDown == 0) return 0\n\n isVisited = isVisited.map(v => v.map(t => 0))\n let downToTop = bfs([manacost.length-1, manacost[0].length-1], false)\n\n topToDown = topToDown.sort((a, b) => a.manaCost - b.manaCost)\n downToTop = downToTop.sort((a, b) => a.manaCost - b.manaCost)\n\n let portal = 1000000000\n\n console.log(topToDown, downToTop)\n\n for(let ttd of topToDown){\n for(let dtt of downToTop){\n if(ttd.time + dtt.time <= maxTime && !isDupCoord([ttd.x, ttd.y], [dtt.x, dtt.y])){\n portal = portal > ttd.manaCost + dtt.manaCost ? ttd.manaCost + dtt.manaCost : portal\n }\n }\n }\n\n return portal\n}", "function checkPosition() {\n // Für Ameise Schwarz\n for (let i = 0; i < Sem.ant.length; i++) {\n let a = Sem.ant[i];\n // Wenn Ameisen Position auf X - Achse zwischen 567 & 750 \n if (a.x >= 567 && a.x <= 750) {\n // Wenn Ameisen Position auf Y - Achse zwischen 245 & 429\n if (a.y >= 245 && a.y <= 429) {\n // Ruft Funktion für Game Over Screen auf\n gameLost();\n }\n }\n }\n // Für Ameise Braun\n for (let i = 0; i < Sem.antBrown.length; i++) {\n let b = Sem.antBrown[i];\n // Wenn Ameisen Position auf X - Achse zwischen 567 & 750\n if (b.x >= 567 && b.x <= 750) {\n // Wenn Ameisen Position auf Y - Achse zwischen 245 & 429\n if (b.y >= 245 && b.y <= 429) {\n // Ruft Funktion für Game Over Screen auf\n gameLost();\n }\n }\n }\n // Für Ameise Rot\n for (let i = 0; i < Sem.antRed.length; i++) {\n let r = Sem.antRed[i];\n // Wenn Ameisen Position auf X - Achse zwischen 567 & 750\n if (r.x >= 567 && r.x <= 750) {\n // Wenn Ameisen Position auf Y - Achse zwischen 245 & 429\n if (r.y >= 245 && r.y <= 429) {\n // Ruft Funktion für Game Over Screen auf\n gameLost();\n }\n }\n }\n }", "boxDetection() {\r\n // For loop, loops through all spaces on the game board\r\n for (let i = this.gameMap.length - 1; i >= 0; i--) {\r\n // For loop, loops through all this.tetrominos for collision detection on a piece of the game board\r\n for (let z = this.tetrominos.length - 1; z >= 0; z--) {\r\n // Check for an intersection between a piece and a board square\r\n if (rectIntersect1(this.tetrominos[z], this.gameMap[i]) || rectIntersect2(this.tetrominos[z], this.gameMap[i]) ||\r\n rectIntersect3(this.tetrominos[z], this.gameMap[i]) || rectIntersect4(this.tetrominos[z], this.gameMap[i])) {\r\n // First case, tetromino hits bottom of board, Check coords and if the tetromino\r\n // is dropping or placed\r\n if (this.tetrominos[z].y1 == height - 40 && this.tetrominos[z].isPlaced == false ||\r\n this.tetrominos[z].y2 == height - 40 && this.tetrominos[z].isPlaced == false ||\r\n this.tetrominos[z].y3 == height - 40 && this.tetrominos[z].isPlaced == false ||\r\n this.tetrominos[z].y4 == height - 40 && this.tetrominos[z].isPlaced == false) {\r\n // Place the dropping tetromino, create a new one\r\n this.tetrominos[z].isPlaced = true;\r\n this.tetrominos[z].isDropping = false;\r\n this.placePiece();\r\n // Second case, tetromino lands on another tetromino, check if theres is a tetromino\r\n // present underneath the dropping tetromino by checking 10 spaces ahead of dropping\r\n // this.tetrominos coords\r\n } else if (this.tetrominos[z].isPlaced == false && this.tetrominos[z].y1 + 40 == this.gameMap[i + 10].y &&\r\n this.gameMap[i + 10].boxUsed == true ||\r\n this.tetrominos[z].isPlaced == false && this.tetrominos[z].y2 + 40 == this.gameMap[i + 10].y &&\r\n this.gameMap[i + 10].boxUsed == true || this.tetrominos[z].isPlaced == false &&\r\n this.tetrominos[z].y3 + 40 == this.gameMap[i + 10].y && this.gameMap[i + 10].boxUsed == true ||\r\n this.tetrominos[z].isPlaced == false && this.tetrominos[z].y4 + 40 == this.gameMap[i + 10].y &&\r\n this.gameMap[i + 10].boxUsed == true) {\r\n // Place the dropping tetromino, create a new one\r\n this.tetrominos[z].isPlaced = true;\r\n this.tetrominos[z].isDropping = false;\r\n this.placePiece();\r\n }\r\n // After placing the tetromino with either case, set the squares the tetromino is\r\n // placed on to used\r\n if (this.tetrominos[z].isPlaced == true) {\r\n this.gameMap[i].boxUsed = true;\r\n }\r\n // Check if a piece lands and is above the game board and reset game\r\n if (this.tetrominos[z].isPlaced == true && this.tetrominos[z].y1 == 0 ||\r\n this.tetrominos[z].isPlaced == true && this.tetrominos[z].y2 == 0 ||\r\n this.tetrominos[z].isPlaced == true && this.tetrominos[z].y3 == 0 ||\r\n this.tetrominos[z].isPlaced == true && this.tetrominos[z].y4 == 0) {\r\n // Reset the game.\r\n this.tetrominos = [];\r\n this.gameMap = [];\r\n setup();\r\n // Reset z variable instead of changing loops because lazy\r\n z = this.tetrominos.length;\r\n }\r\n }\r\n }\r\n }\r\n }", "function getEmptySpot(i,j)\n{\n var possible = getSurroundingCoords(i,j);\n var really_possible = new Array();\n\n // First filtering out all the impossible moves\n for(c=0; c<6; c++) {\n x = possible[c][0];\n y = possible[c][1];\n\n // Filtering out the illegal moves first\n if (x <0 || x >= board.width || y < 0 || y >= board.height) {\n continue;\n }\n\n // this field is already occupied\n if (board.field[y][x] > POLY_TYPE_EMPTY) {\n continue;\n }\n\n // We can't move into whitespace'\n if (board.field[y][x] == POLY_TYPE_WHITESPACE) {\n continue;\n }\n\n // If we can reach the edge in this turn, DO IT!\n var surround = getSurroundingCoords(x,y);\n for (c2=0; c2 < surround.length; c2++) {\n x2 = surround[c2][0];\n y2 = surround[c2][1];\n if (board.field[y2] == undefined || board.field[y2][x2] == undefined || board.field[y2][x2] == POLY_TYPE_WHITESPACE) {\n won = true;\n return possible[c];\n }\n }\n\n really_possible.push(possible[c]);\n\n // DEBUG: make all surrounding hex's red'\n// id = \"hex_\"+x+'_'+y;\n// SVGDocument.getElementById(id).setAttribute('fill', 'red');\n }\n\n // Choose one of the strategies and pick a coord\n if (really_possible.length >0) {\n return strategies[strategy_index](really_possible);\n }\n\n return false;\n}", "function tour() {\n let target = pointMaker(Number(document.getElementById('x').value), Number(document.getElementById('y').value));\n let count = 0;\n let tmp = target;\n let i = 1;\n console.log(JSON.stringify(tmp));\n do {\n if (tmp.x >= 2 && tmp.y >= 1 && tmp.x > tmp.y) { // BOTH POS\n tmp.x -= 2;\n tmp.y -= 1;\n count++;\n console.log(\"1st \" + count);\n console.log(\"Values :\" + tmp.x + \",\" + tmp.y);\n } else if (tmp.x >= 1 && tmp.y >= 2 && tmp.x < tmp.y) { // BOTH POS\n tmp.x -= 1;\n tmp.y -= 2;\n count++;\n console.log(\"2nd \" + count);\n console.log(\"Values :\" + tmp.x + \",\" + tmp.y);\n } else if (tmp.x <= -1 && tmp.y <= -2 && tmp.x > tmp.y) { // BOTH NEG\n tmp.x += 1;\n tmp.y += 2;\n count++;\n console.log(\"3rd \" + count);\n console.log(\"Values :\" + tmp.x + \",\" + tmp.y);\n } else if (tmp.x <= -2 && tmp.y <= -1 && tmp.x < tmp.y) { // BOTH NEG\n tmp.x += 2;\n tmp.y += 1;\n count++;\n console.log(\"4th \" + count);\n console.log(\"Values :\" + tmp.x + \",\" + tmp.y);\n } else if (tmp.x <= -1 && tmp.y >= 2 && tmp.x < tmp.y) { //X is NEG\n tmp.x += 1;\n tmp.y -= 2;\n count++;\n console.log(\"5th \" + count);\n console.log(\"Values :\" + tmp.x + \",\" + tmp.y);\n } else if (tmp.x <= -2 && tmp.y >= 1 && tmp.x < tmp.y) { //X is NEG\n tmp.x += 2;\n tmp.y -= 1;\n count++;\n console.log(\"6th \" + count);\n console.log(\"Values :\" + tmp.x + \",\" + tmp.y);\n } else if (tmp.x >= 1 && tmp.y <= -2 && tmp.x > tmp.y) { //Y is NEG\n tmp.x -= 1;\n tmp.y += 2;\n count++;\n console.log(\"7th \" + count);\n console.log(\"Values :\" + tmp.x + \",\" + tmp.y);\n } else if (tmp.x >= 2 && tmp.y <= -1 && tmp.x > tmp.y) { //Y is NEG\n tmp.x -= 2;\n tmp.y += 1;\n count++;\n console.log(\"8th \" + count);\n console.log(\"Values :\" + tmp.x + \",\" + tmp.y);\n } else if (tmp.x === 0 && tmp.y >= 2) {\n tmp.x += 1;\n tmp.y -= 2;\n count++;\n console.log(\"9th \" + count);\n console.log(\"Values :\" + tmp.x + \",\" + tmp.y);\n } else if (tmp.x === 0 && tmp.y >= 1) {\n tmp.x += 2;\n tmp.y -= 1;\n count++;\n console.log(\"10th \" + count);\n console.log(\"Values :\" + tmp.x + \",\" + tmp.y);\n } else if (tmp.x === 0 && tmp.y <= -2) {\n tmp.x -= 1;\n tmp.y += 2;\n count++;\n console.log(\"11th \" + count);\n console.log(\"Values :\" + tmp.x + \",\" + tmp.y);\n } else if (tmp.x === 0 && tmp.y <= -1) {\n tmp.x -= 2;\n tmp.y += 1;\n count++;\n console.log(\"12th \" + count);\n console.log(\"Values :\" + tmp.x + \",\" + tmp.y);\n } else if (tmp.x >= 2 && tmp.y === 0) {\n tmp.x -= 2;\n tmp.y += 1;\n count++;\n console.log(\"13th \" + count);\n console.log(\"Values :\" + tmp.x + \",\" + tmp.y);\n } else if (tmp.x >= 1 && tmp.y === 0) {\n tmp.x -= 1;\n tmp.y += 2;\n count++;\n console.log(\"14th \" + count);\n console.log(\"Values :\" + tmp.x + \",\" + tmp.y);\n } else if (tmp.x <= -2 && tmp.y === 0) {\n tmp.x += 2;\n tmp.y -= 1;\n count++;\n console.log(\"15th \" + count);\n console.log(\"Values :\" + tmp.x + \",\" + tmp.y);\n } else if (tmp.x <= -1 && tmp.y === 0) {\n tmp.x -= 1;\n tmp.y -= 2;\n count++;\n console.log(\"16th \" + count);\n console.log(\"Values :\" + tmp.x + \",\" + tmp.y);\n } else if ((tmp.x === tmp.y) && (tmp.x !== 0) && (tmp.y !== 0)) {\n tmp.x -= 2;\n tmp.y -= 1;\n count++;\n console.log(\"end \" + count);\n } else if (tmp.x === 0 && tmp.y === 0) {\n i = 0;\n }\n } while (i === 1);//(tmp.x !== 0) && (tmp.y !== 0));//\n alert(\"Solution: \" + count);\n console.log(\"Solution: \" + count);\n}", "checkPos(vpos) {\n\t\tvar npos = vpos.max(screenSize.div(2)).min(mapSize.mul(CellSize).sub(screenSize.div(2)));\n\t\tvar mid = npos.div(CellSize).round();\n\t\tvar good = this.isGood(mid);\n\t\tif(!good) {\n\t\t\tvar temp = mid.x;\n\t\t\tvar rpos = this.pos.div(CellSize);\n\t\t\tmid.x = Math.floor(rpos.x);\n\t\t\tgood = this.isGood(mid);\n\t\t\tif(good) {\n\t\t\t\tnpos.x = this.pos.x;\n\t\t\t}\n\t\t\tif(!good) {\n\t\t\t\tmid.x = temp;\n\t\t\t\tmid.y = Math.floor(rpos.y);\n\t\t\t\tgood = this.isGood(mid);\n\t\t\t\tif(good) {\n\t\t\t\t\tnpos.y = this.pos.y;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif(good) {\n\t\t\treturn npos;\n\t\t}\n\t\telse {\n\t\t\treturn new Vector2(-1, -1);\n\t\t}\n\t}", "function PlanePos(){\n\n\nthis.getSegment=function getSegment (planeW, planeH, planeWs, planeHs,coordX, coordY) {\n//<-- cordinate diapazons\n\nthis.DiapX=planeW/2;\nthis.DiapY=planeH/2;\n//<-- \nif((coordX>=-1*this.DiapX && coordX<this.DiapX)&& (coordY>=-1*this.DiapY && coordY<this.DiapY)){\nthis.DiapX=this.DiapX+coordX;\nthis.DiapY=this.DiapY-+coordY;\n\n//<-- segment dimanesions\nthis.SegmentWidth=planeW/planeWs;\nthis.SegmentHeight=planeH/planeHs;\n//<--\nthis.SegX=Math.ceil(this.DiapX/this.SegmentWidth);\nthis.SegY=Math.ceil(this.DiapY/this.SegmentHeight);\n\n//return(this.SegX*planeWs-(planeHs-this.SegY));\nreturn (this.SegY*planeWs-(planeHs-this.SegX));\n}\nreturn(0);\n}//<--\n\nthis.getVertices=function getVertices(planeW, planeH, planeWs, planeHs,coordX, CoordY){\nthis.segment= this.getSegment (planeW, planeH, planeWs, planeHs,coordX, CoordY);\n//<-- first vertice number\nreturn(this.segment+(Math.ceil(this.segment/planeWs)-1)); \t\n\t\n}//<--\n\n\n\n\t\n\t\n\t\n\t\n\t\n}//<-- plane", "function viagem(limiteTanque, valorGasolina, kmPercorrido, destino){\n\n document.write(\"fizemos uma viagem para \" + destino +'<br>')\n document.write(\"A viagem foi de \" + kmPercorrido + 'km <br>')\n\n //Quantos km faz o tanque\n var kmTotalTanque = limiteTanque * 2\n document.write('O tanque do carro faz ' + kmTotalTanque + 'km <br>')\n\n console.log(kmTotalTanque)\n //Quantas vezes abastecer\n var qtsVzsAbastecer = Math.ceil(kmPercorrido / kmTotalTanque)\n document.write('Precisamos abastecer ' + qtsVzsAbastecer +'vez(es) <br>')\n console.log(qtsVzsAbastecer)\n //Quantos litros abastecer\n var qtsLitrosAbastecer = (kmPercorrido / 2) - limiteTanque\n document.write('Precisamos abastecer ' + qtsLitrosAbastecer +'litros <br>')\n console.log(qtsLitrosAbastecer)\n //valor gasto com a gasolina\n var gastoGasolina = qtsLitrosAbastecer * valorGasolina\n document.write('Gastamos R$' + gastoGasolina + ' com gasolina <br>')\n console.log(gastoGasolina)\n //quanto tempo durou a viagem\n var tempoViagem = Math.ceil(kmPercorrido / 60)\n document.write(\"A viagem demorou aproximadamente \" + tempoViagem + ' horas')\n console.log(tempoViagem)\n}", "function createFreePointsMap(){\n var index=0;\n for (var i = 0; i < 20; i++){\n for (var j = 0; j < 20; j++){\n /*if((j==0 && i == 1) || (j==0 && i == 18) || (j==1 && i >=1 && i <= 8) || (j==1 && i == 11) || (j==1 && i == 14) || (j==1 && i == 18) || (j>=2 && j<=3 && i == 1) || (j>=2 && j<=3 && i == 11) || (j==3 && i>=9 && i<=10) || (j==5 && i==0) ||\n (i==1 && j>=5 && j<=7) || (j==3 && i>=9 && i<=10) || (j==4 && i>=3 && i<=6)|| (j==5 && i>=10 && i<=14)||\n (j==5 && i>=16 && i<=18) || (j==7 && i>=3 && i<=9)|| (j==7 && i>=10 && i<=18) || (j==9 && i>=5 && i<=9) ||\n (j==9 && i>=11 && i<=12) || (j==11 && i>=11 && i<=18) || (j==14 && i>=1 && i<=3) || (j==13 && i>=11 && i<=14) ||\n (j==15 && i>=11 && i<=14) || (j==3 && i>=9 && i<=10) || (j==16 && i>=1 && i<=5) || (j==16 && i>=7 && i<=9) ||\n (j==18 && i>=1 && i<=10) || (j==18 && i>=12 && i<=18) || (i==14 && j>=2 && j<=4) || (i==16 && j>=2 && j<=4) ||\n (i==5 && j>=5 && j<=6) || (i==8 && j>=5 && j<=6) || (i==3 && j>=8 && j<=10) || (i==15 && j>=8 && j<=10) ||\n (i==18 && j>=8 && j<=9) || (i==18 && j>=12 && j<=17) || (i==1 && j>=11 && j<=13) || (i==5 && j>=10 && j<=15) || (i==7 && j>=11 && j<=15) || (i==9 && j>=10 && j<=15) || (i==3 && j>=12 && j<=13) || (i==12 && j>=16 && j<=17) ||\n (i==16 && j>=14 && j<=15) || (i==1 && j==17) || (i==14 && j==14))*/\n if((j>=1 && j<=2 && i>=1 && i<=3) || (j>=1 && j<=2 && i>=5 && i<=7) || (j>=1 && j<=2 && i>=11 && i<=13) || (j>=1 && j<=2 && i>=15 && i<=18) ||\n (j>=0 && j<=2 && i==9) || (j==4 && i>=1 && i<=3) || (j==4 && i>=15 && i<=18) ||(j>=6 && j<=8 && i>=1 && i<=3) || (j>=6 && j<=8 && i>=15 && i<=18) ||\n (j>=10 && j<=12 && i>=1 && i<=3) || (j>=10 && j<=12 && i>=15 && i<=18) || (j>=8 && j<=10 && i>=7 && i<=11) || (j==18 && i>=1 && i<=7) ||\n (j==18 && i>=11 && i<=13) || (j==18 && i>=15 && i<=18) || (j==16 && i>=0 && i<=1) || (j==16 && i>=7 && i<=11) || (j==16 && i>=17 && i<=18) ||\n (j==14 && i>=1 && i<=3) || (j==14 && i>=5 && i<=7) || (j==14 && i>=11 && i<=13) || (j==14 && i>=15 && i<=18) || (j==12 && i>=7 && i<=11) ||\n (j==4 && i>=7 && i<=11) || (j==6 && i>=6 && i<=7) || (j==6 && i>=11 && i<=12) || (i==3 && j>=15 && j<=16) || (i==15 && j>=15 && j<=16) ||\n (i==5 && j>=16 && j<=17) || (i==5 && j>=10 && j<=12) || (i==5 && j>=4 && j<=8) || (i==9 && j>=5 && j<=6) || (i==9 && j>=13 && j<=14) ||\n (i==9 && j>=17 && j<=18) || (i==13 && j>=4 && j<=8) || (i==13 && j>=10 && j<=12) || (i==13 && j>=16 && j<=17) )\n {\n if(i==9 && j==8){\n\n }\n else if(i==9 && j==10){\n\n }\n else{\n continue;\n }\n\n }\n else{\n freePointsMap.points[index] = j;\n freePointsMap.points[index + 1] = i;\n index+=2;\n }\n }\n }\n}", "function availableSpots(arr, num) {\n\n var arrOddEven = []\n for (let i=0; i<arr.length; i++){\n if (arr[i]%2 === 1){\n arrOddEven.push(\"odd\")\n }\n else {\n arrOddEven.push(\"even\")\n }\n }\n\n let numberSpots = 0\n\tif (num %2 === 1) {\n // odd\n for (let i=0; i<arrOddEven.length -1; i++){\n if (arrOddEven[i] === \"odd\" || arrOddEven[i +1] === \"odd\"){\n numberSpots += 1\n }\n }\n\n }\n else {\n for (let i=0 ; i<arrOddEven.length -1; i ++){\n if (arrOddEven[i] !== \"odd\" || arrOddEven[i +1] !== \"odd\")\n numberSpots += 1\n }\n\n }\n return numberSpots\n}", "function task3(){\n let have = 0; //сколько взяли\n let LeftToGo = 0; // Сколько осталось взять\n let array = new Array;//Массив ответов \n let xChair = 0; //Занятых стульев\n let ExistingChair = 0; // Сколько стульев в комнате вообще\n let need = prompt(\"Введите сколько стульев нужно (не больше 8)\",\"\")\n let meetingRooms = prompt(\"Введите строку\",\"\");\n let meetingRooms2 = meetingRooms.replace(/[,.\"\"''()?!-]/g, '');\n meetingRooms = meetingRooms2.split(\" \");\n let length = meetingRooms.length;\n for(let i = 0; i < length; i++){\n if( i % 2 == 0){\n xChair = meetingRooms[i].length;\n }\n else{\n ExistingChair = Number(meetingRooms[i]);\n }\n if(xChair != 0 && ExistingChair != 0){\n if(ExistingChair - xChair >= 0 && need - have >= 0){\n LeftToGo = need - have;\n console.log(\"Сколько осталось взять \" + LeftToGo);\n if(LeftToGo > (ExistingChair - xChair)){\n have += ExistingChair - xChair;\n array.push(ExistingChair - xChair);\n if(have != need){\n console.log('Not enough!');\n }\n }\n else{\n have += ExistingChair - xChair;\n array.push((ExistingChair - xChair)-((ExistingChair - xChair) - LeftToGo));\n console.log('Game On');\n }\n console.log(array);\n }\n xChair = 0;\n ExistingChair = 0;\n }\n }\n //console.log(meetingRooms);\n}", "function setUpSpotLinks() {\n\t\n\t\tvar spotsPerLine = [1,2,3,4,13,12,11,10,9,10,11,12,13,4,3,2,1];\n\t\n\t\tfor(var y = 0; y < 17; y++){\n \n\t\t\tfor(var x = 0; x < spotsPerLine[y]; x++){\n \n\t\t\t\tvar neighbores = getNeighboreSpots(spotMatrix[y][x]);\n\t\t\t\tif(neighbores.length > 6 || neighbores.length < 2) {\n \n\t\t\t\t\tconsole.debug(\"Linking Neighbores Length Error:\" + neighbores.length);\n \n } // end if statement\n\t\t\t\t\n\t\t\t\tfor(var i = 0; i<neighbores.length; i++) {\n \n\t\t\t\t\tif(neighbores[i].screenX > spotMatrix[y][x].screenX && neighbores[i].screenY < spotMatrix[y][x].screenY) { //Northeast\n \n\t\t\t\t\t\tspotMatrix[y][x].northeast = neighbores[i];\n \n\t\t\t\t\t} else if(neighbores[i].screenX > spotMatrix[y][x].screenX && neighbores[i].screenY == spotMatrix[y][x].screenY) { //East\n \n\t\t\t\t\t\tspotMatrix[y][x].east = neighbores[i];\n \n\t\t\t\t\t} else if(neighbores[i].screenX > spotMatrix[y][x].screenX && neighbores[i].screenY > spotMatrix[y][x].screenY) { //Southeast\n \n\t\t\t\t\t\tspotMatrix[y][x].southeast = neighbores[i];\n \n\t\t\t\t\t} else if(neighbores[i].screenX < spotMatrix[y][x].screenX && neighbores[i].screenY > spotMatrix[y][x].screenY) { //Southwest\n \n\t\t\t\t\t\tspotMatrix[y][x].southwest = neighbores[i];\n \n\t\t\t\t\t} else if(neighbores[i].screenX < spotMatrix[y][x].screenX && neighbores[i].screenY == spotMatrix[y][x].screenY) { //West\n \n\t\t\t\t\t\tspotMatrix[y][x].west = neighbores[i];\n \n\t\t\t\t\t} else if(neighbores[i].screenX < spotMatrix[y][x].screenX && neighbores[i].screenY < spotMatrix[y][x].screenY) { //Northwest\n \n\t\t\t\t\t\tspotMatrix[y][x].northwest = neighbores[i];\n \n\t\t\t\t\t} else {\n \n\t\t\t\t\t\tconsole.debug(\"Spot Linking Error! No Direction For: From-(\" + x + \",\" + y + \") To-(\" + neighbores[i].x + \",\" + neighbores[i].y + \")\");\n \n } // end if else statement\n \n\t\t\t\t} // end for loop i\n \n\t\t\t} // end for loop x\n \n\t\t} // end for loop y\n \n\t} // end function setUpSpotLinks()", "function isCorrectPercentage(){\n let x = table.children[0];\n let theSpot;\n let leftD, leftM, leftU, upM, rightU, rightM, rightD, downM;\n for(let i=0; i<val; i++){\n for(let j=0; j<val; j++){\n let totalX = 0;\n let totalY = 0;\n theSpot = x.children[i].children[j];\n if(i!=0 && j!=0){\n leftD = x.children[i-1].children[j-1];\n }if(i!=0){\n leftM = x.children[i-1].children[j];\n }if(i!=0 && j<val-1){\n leftU = x.children[i-1].children[j+1];\n }if(j<val-1){\n upM = x.children[i].children[j+1];\n }if(i<val-1 && j!=0){\n rightU = x.children[i+1].children[j+1];\n }if(i<val-1){\n rightM = x.children[i+1].children[j];\n }if(i<val-1 && j!=0){\n rightD = x.children[i+1].children[j-1];\n }if(i!=0){\n downM = x.children[i].children[j-1];\n }\n if(theSpot.innerHTML == \"1\"){\n if(typeof(leftD) != \"undefined\"){\n if(leftD.innerHTML == \"1\"){\n totalX++;\n }}if(typeof(leftM) != \"undefined\"){\n if(leftM.innerHTML == \"1\"){\n totalX++;\n }}if(typeof(leftU) != \"undefined\"){\n if(leftU.innerHTML == \"1\"){\n totalX++;\n }}if(typeof(upM) != \"undefined\"){\n if(upM.innerHTML == \"1\"){\n totalX++;\n }}if(typeof(rightU) != \"undefined\"){\n if(rightU.innerHTML == \"1\"){\n totalX++;\n }}if(typeof(rightM) != \"undefined\"){\n if(rightM.innerHTML == \"1\"){\n totalX++;\n }}if(typeof(rightD) != \"undefined\"){\n if(rightD.innerHTML == \"1\"){\n totalX++;\n }}if(typeof(downM) != \"undefined\"){\n if(downM.innerHTML == \"1\"){\n totalX++;\n }}\n }if(theSpot.innerHTML == \"2\"){\n if(typeof(leftD) != \"undefined\"){\n if(leftD.innerHTML == \"2\"){\n totalY++;\n }}if(typeof(leftM) != \"undefined\"){\n if(leftM.innerHTML == \"2\"){\n totalY++;\n }}if(typeof(leftU) != \"undefined\"){\n if(leftU.innerHTML == \"2\"){\n totalY++;\n }}if(typeof(upM) != \"undefined\"){\n if(upM.innerHTML == \"2\"){\n totalY++;\n }}if(typeof(rightU) != \"undefined\"){\n if(rightU.innerHTML == \"2\"){\n totalY++;\n }}if(typeof(rightM) != \"undefined\"){\n if(rightM.innerHTML == \"2\"){\n totalY++;\n }}if(typeof(rightD) != \"undefined\"){\n if(rightD.innerHTML == \"2\"){\n totalY++;\n }}if(typeof(downM) != \"undefined\"){\n if(downM.innerHTML == \"2\"){\n totalY++;\n }}\n }\n console.log(totalX);\n console.log(totalY);\n if(totalX<(threshold.value*8)){\n theSpot.style.backgroundColor = \"#ffffff\";\n theSpot.innerHTML = \"0\";\n changeLocation(popXcolor.value);\n }if(totalY<(threshold.value*8)){\n theSpot.style.backgroundColor = \"#ffffff\";\n theSpot.innerHTML = \"0\";\n changeLocation(popYcolor.value);\n }\n }\n }\n /**\n * This function changes the location of the population to a vacant spot\n * @param {*} color \n */\n function changeLocation(color){\n let x = table.children[0];\n let theSpot;\n for (let i=0;i<val;i++){\n for(let j=0;j<val;j++){\n theSpot = x.children[i].children[j];\n if(theSpot.innerHTML == \"0\"){\n theSpot.style.backgroundColor = color;\n thePlace.style.color = \"#FFFFFF\";\n break;\n }\n }\n }\n }\n}", "function cellsALiveCount(){\n let newCells = createCells();\n let cellsAlive = 0\n for (let y = 0; y < resolution; y++){\n for (let x = 0; x < resolution; x++){\n const neighbours = getNeightbourCount(x,y);\n if (cells[x][y] && neighbours >= 2 && neighbours <= 3) \n newCells[x][y] = true;\n else if (!cells[x][y] && neighbours === 3) \n newCells[x][y] = true;\n cellsAlive += cells[x][y] ? 1 : 0 \n }\n }\n return cellsAlive;\n}", "findUpgradeSpots() {\n if (this.danger) { return []; }\n const controller = this.object('controller');\n\n const upgradeSpots = controller.room.lookAtArea(\n controller.pos.y - 3, controller.pos.x - 3,\n controller.pos.y + 3, controller.pos.x + 3, true\n ).filter((lookObj) => {\n return (\n lookObj.type === LOOK_TERRAIN &&\n lookObj[lookObj.type] !== 'wall'\n );\n }).map(lookObj => {\n return {x: lookObj.x, y: lookObj.y};\n });\n this.nbUpgradeSpots = upgradeSpots.length;\n\n return upgradeSpots;\n }", "checkAdjacent(x,y,type,direction, mapData){\n \tlet freespace = 0;\n \tif(type == 4){\n \t\treturn true\n \t}\n \tif(direction){\n \t\tif((y + type) <= 9){ //place up\n \t\t\tfor(let i = -1;i<2;i++){\n \t\t\t\t// if(i == -1 || i == 1){\n \t\t\t\t\tfor(let k = -1;k <= type;k++){\n \t\t\t\t\t\tif((x+i > 0) && (x+i < 10) && mapData[x+i][y+k] != undefined){\n \t\t\t\t\t\t\tfreespace += mapData[x+i][y+k];\n \t\t\t\t\t\t}\n \t\t\t\t\t}\n \t\t\t\t}\n \t\t}else{\n \t\t\tfor(let i = -1;i<2;i++){ //place down\n \t\t\t\t// if(i == -1 || i == 1){\n \t\t\t\t\tfor(let k = -type;k <= 1;k++){\n \t\t\t\t\t\tif((x+i > 0) && (x+i < 10) &&mapData[x+i][y+k] != undefined){\n \t\t\t\t\t\t\tfreespace += mapData[x+i][y+k];\n \t\t\t\t\t\t}\n \t\t\t\t\t}\n \t\t\t }\n \t\t}\n \t}else{\n \t\tif((x + type) <= 9){ //place right\n \t\t\tfor(let i = -1;i<2;i++){\n \t\t\t\t// if(i == -1 || i == 1){\n \t\t\t\t\tfor(let k = -1;k <= type;k++){\n \t\t\t\t\t\tif((x+k > 0) && (x+k < 10)&&mapData[x+k][y+i] != undefined){\n \t\t\t\t\t\t\tfreespace += mapData[x+k][y+i];\n \t\t\t\t\t\t}\n \t\t\t\t\t}\n \t\t\t}\n \t\t}else{\n \t\t\tfor(let i = -1;i<2;i++){ //place left\n \t\t\t\t// if(i == -1 || i == 1){\n \t\t\t\t\tfor(let k = -type;k <= 1;k++){\n \t\t\t\t\t\tif((x+k > 0) && (x+k < 10) &&mapData[x+k][y+i] != undefined){\n \t\t\t\t\t\t\tfreespace += mapData[x+k][y+i];\n \t\t\t\t\t\t}\n \t\t\t\t\t}\n \t\t\t}\n \t\t}\n \t}\n \tif(freespace){ // freespace > 0 = has ship around this position. \n \t\treturn false\n \t}else{\n \t\treturn true\n \t}\n }", "function recheckInventoryFreeSpace(pmcData, sessionID) { // recalculate stach taken place\n let PlayerStash = getPlayerStash(sessionID);\n let Stash2D = Array(PlayerStash[1]).fill(0).map(x => Array(PlayerStash[0]).fill(0));\n for (let item of pmcData.Inventory.items) {\n if (\"location\" in item && item.parentId === pmcData.Inventory.stash) {\n let tmpSize = getSize(item._tpl, item._id, pmcData.Inventory.items);\n let iW = tmpSize[0]; // x\n let iH = tmpSize[1]; // y\n\n if (\"upd\" in item) {\n if (\"Foldable\" in item.upd) {\n if (item.upd.Foldable.Folded) {\n iW -= 1;\n }\n }\n }\n\n let fH = ((item.location.r === \"Vertical\" || item.location.rotation === \"Vertical\") ? iW : iH);\n let fW = ((item.location.r === \"Vertical\" || item.location.rotation === \"Vertical\") ? iH : iW);\n\n for (let y = 0; y < fH; y++) {\n // fixed filling out of bound\n if (item.location.y + y <= PlayerStash[1] && item.location.x + fW <= PlayerStash[0]) {\n let FillTo = ((item.location.x + fW >= PlayerStash[0]) ? PlayerStash[0] : item.location.x + fW);\n\n try {\n Stash2D[item.location.y + y].fill(1, item.location.x, FillTo);\n } catch (e) {\n logger.logError(\"[OOB] for item \" + item._id + \" [\" + item._id + \"] with error message: \" + e);\n }\n }\n }\n }\n }\n\n return Stash2D;\n}", "function Spot(i, j) {\n\tthis.i = i;\n\tthis.j = j;\n\tthis.f = 0;\n\tthis.g = 0;\n\tthis.h = 0;\n\tthis.neighbors = [];\n\tthis.previous = undefined;\n\tthis.wall = false;\n\n\t// Randomly make certain spots walls\n\tif (random(1) < 0.3) {\n\t\tthis.wall = true;\n\t}\n\n\tthis.show = function(cols) {\n\t\tif (this.wall) {\n\t\t\tfill(0);\n\t\t\tnoStroke();\n\t\t\tellipse(this.i * w + w / 2, this.j * h + h / 2, w / 2, h / 2);\n\t\t}\n\t}\n\n\tthis.addNeighbors = function(grid) {\n\t\tvar i = this.i;\n\t\tvar j = this.j;\n\n\t\tif (i < cols - 1) {\n\t\t\tthis.neighbors.push(grid[i + 1][j]);\n\t\t}\n\t\tif (i > 0) {\n\t\t\tthis.neighbors.push(grid[i - 1][j]);\n\t\t}\n\t\tif (j < rows - 1) {\n\t\t\tthis.neighbors.push(grid[i][j + 1]);\n\t\t}\n\t\tif (j > 0) {\n\t\t\tthis.neighbors.push(grid[i][j - 1]);\n\t\t}\n\t\tif (i > 0 && j > 0) {\n\t\t\tthis.neighbors.push(grid[i - 1][j - 1]);\n\t\t}\n\t\tif (i < cols - 1 && j > 0) {\n\t\t\tthis.neighbors.push(grid[i + 1][j - 1]);\n\t\t}\n\t\tif (i > 0 && j < rows - 1) {\n\t\t\tthis.neighbors.push(grid[i - 1][j + 1]);\n\t\t}\n\t\tif (i < cols - 1 && j < rows - 1) {\n\t\t\tthis.neighbors.push(grid[i + 1][j + 1]);\n\t\t}\n\t}\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 EmptySpot(sudoko){\n for (let i = 0; i < 9; i++) {\n for (let j = 0; j < 9; j++) {\n if (sudoko[i][j] === 0)\n return [i,j];\n }\n }\n return [-1,-1];\n} // if the board is full of empty 0 then it will return [-1,-1] ", "function nextHole() {\r\n\tconsole.log('Going into hole...');\r\n\tdocument.getElementById('currentHole').innerHTML = game.length + 2;\r\n\tdocument.getElementById('currentShot').innerHTML = 1;\r\n\t\r\n\r\n\r\n\t// nextHole is called at the flag. use this coordinate\r\n\t// to calculate the length of our final putt\r\n\tlet shotInfo = getCoords();\r\n\tlet shotDistance = getDistance( shots[ shots.length - 1], shotInfo);\r\n\tshots[ shots.length - 1 ].distance = shotDistance;\r\n\r\n\t// take current shots and store in game array\r\n\tgame.push(shots);\r\n\r\n\t// TODO - update the page to display our scorecard\r\n\tupdateScoreCard(shots);\r\n\r\n\t// clear shots[]\r\n\tshots = [];\r\n}", "function identifyNeighbours(x_max,y_max){\n\t \t\tvar traversalIndex = 0;\n\n\t \t\t//inner square\n\t \t\tfor (var i = 0; i < x_max*y_max; i++) {\n\t \t\t\ttraversalIndex = (i % y_max);\n\n\t \t\tif((traversalIndex != 0) && (traversalIndex != (y_max-1)) \n\t \t\t&& (i <= ((y_max)*(x_max-1)-1)) && (i >= y_max+1) ){\n\t \t\t\tspaces[i].adjacentNeighbours = spaces[(i-1)].holdsMine\n\t \t\t\t\t\t\t\t\t\t + spaces[i+1].holdsMine\n\t \t\t\t\t\t\t\t\t\t + spaces[i+y_max].holdsMine\n\t \t\t\t\t\t\t\t\t\t + spaces[i-y_max].holdsMine\n\t \t\t\t\t\t\t\t\t\t + spaces[(i-1)+y_max].holdsMine\n\t \t\t\t\t\t\t\t\t\t + spaces[(i-1)-y_max].holdsMine\n\t \t\t\t\t\t\t\t\t\t + spaces[(i+1)+y_max].holdsMine\n\t \t\t\t\t\t\t\t\t\t + spaces[(i+1)-y_max].holdsMine;\n\t \t\t\tspaces[i].neighbourIndexList.push( (i+1),(i-1),(i+y_max),(i-y_max),\n\t \t\t\t\t\t\t\t\t\t\t\t\t(i-1+y_max),(i-1-y_max),\n\t \t\t\t\t\t\t\t\t\t\t\t\t(i+1+y_max),(i+1-y_max));\n\t\t\t\t}\n\t\t\t// console.log(isNaN(spaces[i].holdsMine))\n\t\t\t}\n\n\t\t\t//four courners\n\t\t\tspaces[0].adjacentNeighbours = spaces[y_max].holdsMine\n\t\t\t\t\t\t\t\t\t + spaces[y_max+1].holdsMine\n\t\t\t\t\t\t\t\t\t + spaces[1].holdsMine;\n\n\t\t\tspaces[0].neighbourIndexList.push(y_max,(y_max+1),1);\n\n\t\t\tspaces[y_max-1].adjacentNeighbours = spaces[(y_max-1) - 1].holdsMine\n\t\t\t\t\t\t\t\t\t\t\t + spaces[(y_max-1) + y_max].holdsMine\n\t\t\t\t\t\t\t\t\t\t\t + spaces[(y_max-1) + y_max-1].holdsMine;\n\n\t\t\tspaces[(y_max-1)].neighbourIndexList.push((y_max-1-1), (y_max-1+y_max), (y_max-1+y_max-1));\n\n\n\t\t\tspaces[y_max*x_max-1].adjacentNeighbours = spaces[(y_max*x_max-1)-1].holdsMine\n\t\t\t\t\t\t\t\t\t\t\t\t + spaces[(y_max*x_max-1)-y_max].holdsMine\n\t\t\t\t\t\t\t\t\t\t\t\t + spaces[(y_max*x_max-1)-(y_max-1)].holdsMine;\n\n\t\t\tspaces[y_max*x_max-1].neighbourIndexList.push((y_max*x_max-1)-1, (y_max*x_max-1)-y_max, (y_max*x_max-1)-(y_max-1));\n\n\n\t\t\tspaces[(x_max *(y_max-1))].adjacentNeighbours = spaces[(x_max *(y_max-1))+ 1].holdsMine\n + spaces[(x_max *(y_max-1))-y_max].holdsMine\n + spaces[(x_max *(y_max-1))-(y_max)+1].holdsMine; \n\n spaces[(x_max *(y_max-1))].neighbourIndexList.push((x_max *(y_max-1))+ 1, (x_max *(y_max-1))-y_max,(x_max *(y_max-1))-(y_max)+1);\n\n\n for(var k = 1; k < y_max-1; k++){\n\n\t\t \t\t//left column\n\t\t \t\tspaces[k].adjacentNeighbours = spaces[k-1].holdsMine\n\t\t \t\t\t\t\t\t\t\t + spaces[k+1].holdsMine\n\t\t \t\t\t\t\t\t\t\t + spaces[k+y_max].holdsMine\n\t\t \t\t\t\t\t\t\t\t + spaces[k+y_max - 1].holdsMine\n\t\t \t\t\t\t\t\t\t\t + spaces[k+y_max + 1].holdsMine;\n\n\t\t \t\tspaces[k].neighbourIndexList.push(k-1,k+1,k+y_max,k+y_max-1,k-y_max+1);\n\n\n\t\t \t\t//right column\n\t\t \t\tspaces[x_max *(y_max-1) + k].adjacentNeighbours = spaces[ (x_max *(y_max-1) + k) + 1].holdsMine\n\t\t \t\t\t\t\t\t\t\t+ spaces[x_max *(y_max-1) + k - 1].holdsMine\n\t\t\t\t\t\t\t\t\t + spaces[x_max *(y_max-1) + k - y_max].holdsMine\n\t\t\t\t\t\t\t\t\t + spaces[x_max *(y_max-1) + k - y_max + 1].holdsMine\n\t\t\t\t\t\t\t\t\t + spaces[x_max *(y_max-1) + k - y_max - 1].holdsMine;\n\n\t\t\t\tspaces[x_max *(y_max-1) + k].neighbourIndexList.push((x_max *(y_max-1) + k) + 1,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t x_max *(y_max-1) + k - 1,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t x_max *(y_max-1) + k - y_max,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t x_max *(y_max-1) + k - y_max + 1,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t x_max *(y_max-1) + k - y_max - 1);\n\t\t \t\t\n\t\t \t\t//top row\n\t\t \t\tspaces[k*y_max].adjacentNeighbours = spaces[k*y_max + 1].holdsMine\n\t\t \t\t\t\t\t\t\t\t\t + spaces[(k+1)*y_max].holdsMine\n\t\t \t\t\t\t\t\t\t\t\t + spaces[(k-1)*y_max].holdsMine\n\t\t \t\t\t\t\t\t\t\t\t + spaces[(k+1)*y_max + 1].holdsMine\n\t\t \t\t\t\t\t\t\t\t\t + spaces[(k-1)*y_max + 1].holdsMine;\n\n\t\t \t\tspaces[k*y_max].neighbourIndexList.push(k*y_max + 1,\n\t\t \t\t\t\t\t\t\t\t\t\t\t\t(k+1)*y_max,\n\t\t \t\t\t\t\t\t\t\t\t\t\t\t(k-1)*y_max,\n\t\t \t\t\t\t\t\t\t\t\t\t\t\t(k+1)*y_max + 1,\n\t\t \t\t\t\t\t\t\t\t\t\t\t\t(k-1)*y_max + 1);\n\n\t\t \t\t//bottom row\n\t\t \t\tspaces[(k+1)*(y_max)-1].adjacentNeighbours = spaces[(k+1)*(y_max)-1 - 1].holdsMine\n\t\t \t\t\t\t\t\t\t\t\t\t\t+ spaces[(k+1)*(y_max)-1 - y_max].holdsMine\n\t\t \t\t\t\t\t\t\t\t\t\t + spaces[(k+1)*(y_max)-1 + y_max].holdsMine\n\t\t \t\t\t\t\t\t\t\t\t\t\t+ spaces[(k+1)*(y_max)-1 - y_max-1].holdsMine\n\t\t \t\t\t\t\t\t\t\t\t\t + spaces[(k+1)*(y_max)-1 +y_max-1].holdsMine;\n\n\n\t\t\t\tspaces[(k+1)*(y_max)-1].neighbourIndexList.push((k+1)*(y_max)-1 - 1,\n\t\t\t\t\t\t\t\t\t\t\t\t \t\t\t (k+1)*(y_max)-1 - y_max,\n\t\t\t\t\t\t\t\t\t\t\t\t (k+1)*(y_max)-1 + y_max,\n\t\t\t\t\t\t\t\t\t\t\t\t (k+1)*(y_max)-1 - y_max-1,\n\t\t\t\t\t\t\t\t\t\t\t\t (k+1)*(y_max)-1 + y_max-1);\n\t \t\t}\n\t \t}", "function step(){\n let newCells = createCells();\n let cellsAlive = 0\n for (let y = 0; y < resolution; y++){\n for (let x = 0; x < resolution; x++){\n const neighbours = getNeightbourCount(x,y);\n if (cells[x][y] && neighbours >= 2 && neighbours <= 3) \n newCells[x][y] = true; //if the cell in cells array that is the las generation can live, the nextgen cell in 'newCell' array will be true\n else if (!cells[x][y] && neighbours === 3) \n newCells[x][y] = true; //a cell that in the canva is death can live if the neighbours are equals to 3\n cellsAlive += cells[x][y] ? 1 : 0 //cellsalive count\n }\n }\n setRetults(generation++,cellsAlive)\n cells = newCells;\n drawCells();\n}", "getPotentialPawnMoves([x, y]) {\n const color = this.turn;\n let moves = [];\n const [sizeX, sizeY] = [V.size.x, V.size.y];\n const shiftX = color == \"w\" ? -1 : 1;\n const startRanks = color == \"w\" ? [sizeX - 2, sizeX - 3] : [1, 2];\n const lastRank = color == \"w\" ? 0 : sizeX - 1;\n const finalPieces = x + shiftX == lastRank\n ? [V.WILDEBEEST, V.QUEEN]\n : [V.PAWN];\n\n if (this.board[x + shiftX][y] == V.EMPTY) {\n // One square forward\n for (let piece of finalPieces)\n moves.push(\n this.getBasicMove([x, y], [x + shiftX, y], { c: color, p: piece })\n );\n if (startRanks.includes(x)) {\n if (this.board[x + 2 * shiftX][y] == V.EMPTY) {\n // Two squares jump\n moves.push(this.getBasicMove([x, y], [x + 2 * shiftX, y]));\n if (x == startRanks[0] && this.board[x + 3 * shiftX][y] == V.EMPTY) {\n // Three squares jump\n moves.push(this.getBasicMove([x, y], [x + 3 * shiftX, y]));\n }\n }\n }\n }\n // Captures\n for (let shiftY of [-1, 1]) {\n if (\n y + shiftY >= 0 &&\n y + shiftY < sizeY &&\n this.board[x + shiftX][y + shiftY] != V.EMPTY &&\n this.canTake([x, y], [x + shiftX, y + shiftY])\n ) {\n for (let piece of finalPieces) {\n moves.push(\n this.getBasicMove([x, y], [x + shiftX, y + shiftY], {\n c: color,\n p: piece\n })\n );\n }\n }\n }\n\n // En passant\n const Lep = this.epSquares.length;\n const epSquare = this.epSquares[Lep - 1];\n if (!!epSquare) {\n for (let epsq of epSquare) {\n // TODO: some redundant checks\n if (epsq.x == x + shiftX && Math.abs(epsq.y - y) == 1) {\n var enpassantMove = this.getBasicMove([x, y], [epsq.x, epsq.y]);\n // WARNING: the captured pawn may be diagonally behind us,\n // if it's a 3-squares jump and we take on 1st passing square\n const px = this.board[x][epsq.y] != V.EMPTY ? x : x - shiftX;\n enpassantMove.vanish.push({\n x: px,\n y: epsq.y,\n p: \"p\",\n c: this.getColor(px, epsq.y)\n });\n moves.push(enpassantMove);\n }\n }\n }\n\n return moves;\n }", "function getSpotsForTheDay(state, day) {\n return state.days[day].spots\n}", "function is_safe_cross()\n{\n\tif (frog.lane == 0) {\n\t\tif(frog.x > slots[0].start && (frog.x + frog.w) < slots[0].end && \n\t\t !slots[0].isfull) {\n\t\t\t\tslots[0].isfull = 1;\n\t\t\t\tslots.lastfilled = 0;\n\t\t\t\treturn 1;\n\t\t}\n\t\telse if(frog.x > slots[1].start && (frog.x + frog.w) < slots[1].end && \n\t\t !slots[1].isfull) {\n\t\t\t\tslots[1].isfull = 1;\n\t\t\t\tslots.lastfilled = 1;\n\t\t\t\treturn 1;\n\t\t}\n\t\telse if(frog.x > slots[2].start && (frog.x + frog.w) < slots[2].end && \n\t\t !slots[2].isfull) {\n\t\t\t\tslots[2].isfull = 1;\n\t\t\t\tslots.lastfilled = 2;\n\t\t\t\treturn 1;\n\t\t}\n\t\telse if(frog.x > slots[3].start && (frog.x + frog.w) < slots[3].end && \n\t\t !slots[3].isfull) {\n\t\t\t\tslots[3].isfull = 1;\n\t\t\t\tslots.lastfilled = 3;\n\t\t\t\treturn 1;\n\t\t}\n\t\telse if(frog.x > slots[4].start && (frog.x + frog.w) < slots[4].end && \n\t\t !slots[4].isfull) {\n\t\t\t\tslots[4].isfull = 1;\n\t\t\t\tslots.lastfilled = 4;\n\t\t\t\treturn 1;\n\t\t}\n\t\telse { return 0; }\n\t}\n\treturn 1;\n}", "getEmptyPositionsWithSpaceWithWalls() {\n var emptyPositions = this.getEmptyPositions();\n var res = emptyPositions.filter(p => (((GameConfig.WIDTH - 3) >= p.x) && ((GameConfig.HEIGHT - 3) >= p.y)) && ((2 <= p.x) && (2 <= p.y)));\n return res;\n }", "function allPossibleWinPositions(size)\n{\n let wins = []\n let onewin = []\n let coords = []\n for (let y = 1; y <= size; y++) {\n for (let x = 1; x <= size; x++) {\n coords.push(x)\n coords.push(y)\n onewin.push(coords)\n coords = []\n }\n wins.push(onewin)\n onewin = []\n }\n for (let x = 1; x <= size; x++) {\n for (let y = 1; y <= size; y++) {\n coords.push(x)\n coords.push(y)\n onewin.push(coords)\n coords = []\n }\n wins.push(onewin)\n onewin = []\n }\n for (let a = 1; a <= size; a++) {\n coords.push(a,a)\n onewin.push(coords)\n coords = []\n }\n wins.push(onewin)\n onewin=[]\n for (let a = 1; a <= size; a++) {\n coords.push(size-a+1,a)\n onewin.push(coords)\n coords = []\n }\n wins.push(onewin)\n onewin=[]\n\n return wins\n}", "function makeGraves() {\n for (i=0;i<smallGravePositionsBack.length;i++) {\n smallGraves.push({posX:(smallGravePositionsBack[i]),posY:360,sizeX:53,sizeY:15});\n }\n for (i=0;i<smallGravePositionsFront.length;i++) {\n smallGraves.push({posX:(smallGravePositionsFront[i]),posY:470,sizeX:53,sizeY:15});\n }\n}", "genNextSpot() {\r\n let countFreeSpaces = this.gameState.board.filter((i) => i === 0).length;\r\n if (countFreeSpaces === 0) {\r\n this.checkLose();\r\n } else {\r\n let locationToAdd = Math.floor(Math.random() * Math.floor(countFreeSpaces));\r\n let numEmptyTraversed = 0;\r\n for (let i = 0; i < this.gameState.board.length; i++) {\r\n if (this.gameState.board[i] === 0) {\r\n if (numEmptyTraversed === locationToAdd) {\r\n this.gameState.board[i] = this.gen2or4();\r\n break;\r\n } else {\r\n numEmptyTraversed++;\r\n }\r\n }\r\n }\r\n } \r\n }", "function test() {\n while (!condition) {\n let totalFull = 0;\n\n for (let i = 0; i < wardens.length; i++) {\n let l = (wardens[i].route.length);\n if (s % l !== 0) {\n wardens[i].cs = (s % l) - 1; //ARRAYS START AT ZERO!!\n } else {\n wardens[i].cs = l - 1;\n }\n wardens[i].pos = wardens[i].route[wardens[i].cs];\n }\n console.log(wardens);\n\n for (let i = 0; i < wardens.length; i++) {\n\n for (let j = 0; j < wardens.length; j++) {\n\n if (wardens[i].pos === wardens[j].pos) {\n wardens[i].gossips = swapgossip(wardens[i].gossips.concat(wardens[j].gossips));\n wardens[j].gossips = wardens[i].gossips;\n }\n\n }\n if (wardens[i].gossips.length === wardens.length) {\n totalFull++;\n }\n }\n console.log(totalFull)\n if (totalFull === wardens.length) {\n condition = true;\n\n }\n //console.log(s);\n\n\n\n\n\n\n\n\n\n\n\n\n s++;\n //wait(1000);\n\n }\n var p = document.createElement(\"p\");\n p.innerHTML = \"stops taken: \" + (s - 1);\n document.getElementById(\"result\").appendChild(p);\n}", "function getyodalife(){\nvar K;\nK = getShape(\"halcon\");\n for(var x=0 ; x < yodas.length ; x++){\n part1 = Math.pow((K.x-yodas[x].x),2);\n part2 = Math.pow((K.y-yodas[x].y),2);\n condition = Math.sqrt(part1+part2 );\n resta_radios = K.radious + yodas[x].radious;\n if(condition < resta_radios ){\n yodas.splice(x,1);\n console.log(\"TRUENOS Y CENTELLAS\")\n if(lifes<=5){\n lifes = lifes + 1;\n document.getElementById('VIDAS').innerHTML = \"Te quedan: \"+ lifes +\" Vidas\";\n }\n }\n }\n}", "function takeOff() {\n let plane = document.querySelector('#plane');\n let domRect = plane.getBoundingClientRect()\n let bound = window.innerWidth - domRect.left //This is the distance from where the plane starts to the right side of window. Used to change animation once plane exits screen to right. \n let start = Date.now();//For intitial time\n let left = 0 //Since planes postion is relative, start at \n let top = 0\n let resetLeft = -domRect.right //Where plane will start on return to screen.\n let resetTop = -50 //Where plane will start on return to screen.\n if (window.innerWidth < 500) { //For smaller screens, plane will land more smoothly.\n resetTop = -25;\n }\n let x = 0 //Counter and position incrementer. \n let xReset = 0 //For return flight position incrementer. \n //This causes the plane to change postion every 20 milliseconds to appear to make a smooth\n //flight takeoff and landing. \n let timer = setInterval(() => {\n\n let timePassed = Date.now() - start; //Keep track of total time passed\n //If 8 seconds have passed or plane is back in postion, reset interval and restore\n //original position. \n if (timePassed >= 8000 || resetLeft >= 0) {\n clearInterval(timer);\n plane.style.left = `0px`\n plane.style.top = `0px`\n return;\n } else if (left >= bound) { //If plane has exited the right of the screen-start descent from the left. \n plane.style.left = `${resetLeft += 4}px`\n if (resetTop < 0) {\n plane.style.top = `${resetTop += 1.5 * x ** 2}px`\n } else {\n plane.style.top = `0px`\n }\n xReset++\n } else { //Original takeoff segment. \n plane.style.left = `${left += 4}px` //Plane starts with just horizontal movement.\n if (left > (window.innerWidth / 4)) { //Once it moves 1/4 of the screen horizontally, start an upward path following an exponential curve.\n plane.style.top = `${top -= (3 / 4) * x ** 2}px` //Exponential curve flattened slightly to make it look more realistic. \n\n }\n }\n\n }, 20)\n x++;\n}", "function increaseSpd() {\n\tif(points % 4 == 0) {\n\t\tif(Math.abs(ball.vx) < 15) {\n\t\t\tball.vx += (ball.vx < 0) ? -1 : 1;\n\t\t\tball.vy += (ball.vy < 0) ? -2 : 2;\n\t\t}\n\t}\n}", "function emptyPlace (type, lista){\n let a\n let b\n let places = []\n for (let p of lista){\n if (type == \"vertical\"){\n a = [p[0], p[1]+1]\n b = [p[0], p[1]-1]\n }\n else if (type == \"horizontal\"){\n a = [p[0]+1, p[1]]\n b = [p[0]-1, p[1]]\n }\n else if (type == \"left diagonal\"){\n a = [p[0]+1, p[1]+1]\n b = [p[0]-1, p[1]-1]\n }\n else if (type == \"right diagonal\"){\n a = [p[0]-1, p[1]+1]\n b = [p[0]+1, p[1]-1]\n }\n if (!inList(a, lista)) places.push(a)\n if (!inList(b, lista)) places.push(b)\n }\n return places\n}", "function whereisthespace()\n\t{\n\t\t//create array with all the possible points\n\t\tvar allpoints = [\"0,0\", \"0,100\", \"0,200\", \"0,300\", \"100,0\", \"100,100\", \"100,200\", \"100,300\", \"200,0\", \"200,100\", \"200,200\", \"200,300\", \"300,0\", \"300,100\", \"300,200\", \"300,300\"];\n\t\tvar index;\n\t\t//loop throough the current location of the points and splice them off the array, leaving only the blank space.\n\t\tfor (var i = 0; i < c.length; i++)\n\t\t{\n\t\t\tindex = allpoints.indexOf(c[i].offsetLeft + \",\" + c[i].offsetTop);\n\t\t\tallpoints.splice(index,1);\n\t\t}\n\t\treturn allpoints;\n\t}", "_get_landing_spots (stone)\n\t{\n\t\tvar spots = []\n\t\tthis._actions.forEach (action => {\n\n\t\t\tif (stone._type == action.stone) {\n\t\t\t\tspots.push (this.board.get_slot_coo (action.x, action.y))\n\t\t\t}\n\t\t})\n\t\treturn spots\n\t}", "getMoveablePositions(){\n const movables = [];\n const missing = this.board.missing;\n const cols = this.board.cols;\n const tilesCount = this.board.tilesCount;\n if(missing - 1 > 0 && missing % cols !== 1){\n movables.push(missing - 1);\n }\n if(missing + 1 <= tilesCount && missing % cols !== 0){\n movables.push(missing + 1);\n }\n if(missing - cols > 0){\n movables.push(missing - cols);\n }\n if(missing + cols <= tilesCount){\n movables.push(missing + cols);\n }\n return movables;\n }", "function king(i,j,k)\r\n{\r\n\r\n if((i<7 && j<7) && ((document.getElementById(`${i+1}${j+1}`).textContent=='_______') || ((got_enemy(i+1,j+1,k) == 1)||(got_enemy(i+1,j+1,k) == 2)))){\r\n array.push(`${i+1}${j+1}`);\r\n }\r\n\r\n if((i>0 && j>0) && ((document.getElementById(`${i-1}${j-1}`).textContent=='_______') || ((got_enemy(i-1,j-1,k) == 1)||(got_enemy(i-1,j-1,k) == 2)))){\r\n array.push(`${i-1}${j-1}`);\r\n }\r\n\r\n if((i<7 ) && ((document.getElementById(`${i+1}${j}`).textContent=='_______') || ((got_enemy(i+1,j,k) == 1)||(got_enemy(i+1,j,k) == 2)))){\r\n array.push(`${i+1}${j}`);\r\n }\r\n\r\n if((i>0) && ((document.getElementById(`${i-1}${j}`).textContent=='_______') || ((got_enemy(i-1,j,k) == 1)||(got_enemy(i-1,j,k) == 2)))){\r\n array.push(`${i-1}${j}`);\r\n }\r\n\r\n if((j>0) && ((document.getElementById(`${i}${j-1}`).textContent=='_______') || ((got_enemy(i,j-1,k) == 1)||(got_enemy(i,j-1,k) == 2)))){\r\n array.push(`${i}${j-1}`);\r\n }\r\n\r\n if((j<7) && ((document.getElementById(`${i}${j+1}`).textContent=='_______') || ((got_enemy(i,j+1,k) == 1)||(got_enemy(i,j+1,k) == 2)))){\r\n array.push(`${i}${j+1}`);\r\n }\r\n\r\n if((i>0 && j<7) && ((document.getElementById(`${i-1}${j+1}`).textContent=='_______') || ((got_enemy(i-1,j+1,k) == 1)||(got_enemy(i-1,j+1,k) == 2)))){\r\n array.push(`${i-1}${j+1}`);\r\n }\r\n\r\n if((i<7 && j>0) && ((document.getElementById(`${i+1}${j-1}`).textContent=='_______') || ((got_enemy(i+1,j-1,k) == 1)||(got_enemy(i+1,j-1,k) == 2)))){\r\n array.push(`${i+1}${j-1}`);\r\n }\r\n}", "function Spot(row, col) { \n this.row = row;\n this.column = col;\n //If the row and cols equals to the starting point, becomes true. Otherwise false.\n this.start = this.row === start_row && this.column === start_col\n //If the row and cols equals to the end point, becomes true. Otherwise false.\n this.end = this.row === end_row && this.column === end_col\n //Will be used in the heuristic function to calculate the manhattan distance. Playing a role in the algorithm\n this.g = 0;\n this.f = 0;\n this.h = 0;\n //Neighbors will determine the specific spot that the color will have\n this.neighbors = [];\n //\n this.isWall = false;\n if(Math.random(1) < 0.2) { \n this.isWall = true;\n }\n this.previous = undefined;\n this.addNeighbors = function(grid)\n {\n let row = this.row;\n let column = this.column;\n // Conditionals to ensure that grid limitations are set. \n if (row > 0) this.neighbors.push(grid[row-1][column]);\n if (row < rows - 1) this.neighbors.push(grid[row+1][column]);\n if (column > 0) this.neighbors.push(grid[row][column-1]);\n if (column < cols - 1) this.neighbors.push(grid[row][column+1]);\n }\n }", "function detectRefugeesToPort() {\n for (let i = 0; i < refugeesArray.length; i++) {\n for (let j = 0; j < ports.length; j++) {\n refugeesBoatsW = refugeesArray[i].newBoat.getBoundingClientRect().width;\n refugeesBoatsH = refugeesArray[i].newBoat.getBoundingClientRect()\n .height;\n refugeesBoatsX = refugeesArray[i].newBoat.getBoundingClientRect().left;\n refugeesBoatsY = refugeesArray[i].newBoat.getBoundingClientRect().top;\n portW = ports[j].getBoundingClientRect().width;\n portH = ports[j].getBoundingClientRect().height;\n portX = ports[j].getBoundingClientRect().left;\n portY = ports[j].getBoundingClientRect().top;\n\n if (\n refugeesBoatsX + refugeesBoatsW > portX &&\n refugeesBoatsX < portX + portW &&\n refugeesBoatsY + refugeesBoatsH > portY &&\n refugeesBoatsY < portY + portH\n ) {\n landRefugees(refugeesArray[i]);\n refugeesArray.splice(refugeesArray[i], 1);\n }\n }\n }\n window.requestAnimationFrame(detectRefugeesToPort);\n }", "function checkLoc(){\n for(var i = 0; i < food.length; i++){\n var distX = food[i].loc.x - snake.loc.x;\n var distY = food[i].loc.y - snake.loc.y;\n if(distX == (0) && distY == (0)){\n food.splice(i, 1);\n //removes the food\n //would add in a new food if that was the way I wanted it to be\n loadFood(0);\n snake.segments.push(createVector(0, 0));\n console.log(snake.segments.length)\n score++;\n }\n }\n}", "processPos(npos) {\n\t\tvar tpos = this.checkPos(npos);\n\t\tif(tpos.x < 0) {\n\t\t\ttpos = this.checkPos(this.pos);\n\t\t\tif(tpos.x < 0) {\n\t\t\t\tlet used = {};\n\t\t\t\tlet p = 0;\n\t\t\t\tlet queue = [];\n\t\t\t\tlet pos = this.pos.div(CellSize).round();\n\t\t\t\tused[pos.x + pos.y * mapSize.x] = true;\n\t\t\t\tqueue.push(pos);\n\t\t\t\tlet shift = [new Vector2(-1, 0), new Vector2(1, 0), new Vector2(0, -1), new Vector2(0, 1)];\n\t\t\t\tlet answ = this.pos;\n\t\t\t\twhile(p < queue.length) {\n\t\t\t\t\tlet cur = queue[p];\n\t\t\t\t\tif(this.isGood(cur)) {\n\t\t\t\t\t\tansw = cur;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tp++;\n\t\t\t\t\tfor(let i = 0; i < 4; i++) {\n\t\t\t\t\t\tlet tmp = cur.add(shift[i]);\n\t\t\t\t\t\tlet id = tmp.x + tmp.y * mapSize.x;\n\t\t\t\t\t\tif(!used[id] && this.map.checkCoords(tmp.x, tmp.y)) {\n\t\t\t\t\t\t\tused[id] = true;\n\t\t\t\t\t\t\tqueue.push(tmp);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn answ.mul(CellSize);\n\t\t\t}\n\t\t\telse {\n\t\t\t\treturn this.pos;\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\treturn tpos;\n\t\t}\n\t}", "function checkStraight() {\r\n\r\n for (let i = 0; i < 3; i++) {\r\n let rectangles = [];\r\n let straightCount = 0;\r\n\r\n for (let j = 1; j < 5; j++) {\r\n\r\n if (spinners[j].value[i] == spinners[j - 1].value[i]\r\n || spinners[j - 1].value[i] == jokerVal) {\r\n straightCount++;\r\n } else {\r\n break;\r\n }\r\n\r\n }\r\n\r\n //activate animations for all eligible slots\r\n if (straightCount >= 2) {\r\n lastWinCount++;\r\n for (let j = 0; j <= straightCount; j++) {\r\n\r\n rectangles.push(new Rectangle(\r\n spinners[j].imgs[i].x - spinnerWidth / 2,\r\n spinners[j].imgs[i].y - spinnerWidth / 2,\r\n spinnerWidth,\r\n spinnerWidth,\r\n 0xFFE401)\r\n );\r\n\r\n }\r\n\r\n //===Avoid using the joker value for profit calculation unless all are jokers.\r\n let val = spinners[0].value[i];\r\n if (val == jokerVal) {\r\n for (let j = 0; j <= straightCount; j++) {\r\n if (spinners[j].value[i] != jokerVal) {\r\n val = spinners[j].value[i];\r\n }\r\n }\r\n }\r\n //===\r\n\r\n let profit = calculateProfit(straightCount + 1, val);\r\n lastWin += profit;\r\n\r\n }\r\n\r\n //console.log(\"Row \" + i + \": \" + (straightCount + 1));\r\n\r\n //===Add new rectangles to their groups\r\n if (rectangles.length > 0) {\r\n RectangleGroups.push(rectangles);\r\n //console.log(\"Length: \" + RectangleGroups.length);\r\n }\r\n }\r\n\r\n\r\n}", "function checkLocs() {\n for (var i = 0; i < meteors.length; i++) {\n if (dist(me.loc.x, me.loc.y, meteors[i].loc.x, meteors[i].loc.y) < me.rad / 4) {\n stageAlpha = 1;\n me.isAlive = false;\n crashSE.play();\n }\n }\n}", "function countBombs(x,y) {\r\n\tlet count = 0;\r\n\tconsole.log(x,y);\r\n\r\n\t// left hand side\r\n\tif(x == 0) {\r\n\t\tif(y == 0) { // upper left corner\r\n\t\t\t\r\n\t\t\tif(table[x+1][y].getIsBomb()) {count ++};\r\n\t\t\tif(table[x][y+1].getIsBomb()) {count ++};\r\n\t\t\tif(table[x+1][y+1].getIsBomb()) {count ++};\r\n\r\n\t\t}\r\n\t\telse if(y == 15) { // lower left corner\r\n\t\t\tif(table[x][y-1].getIsBomb()) {count ++};\r\n\t\t\tif(table[x+1][y-1].getIsBomb()) {count ++};\r\n\t\t\tif(table[x+1][y].getIsBomb()) {count ++};\r\n\t\t}\r\n\t\telse {\r\n\r\n\t\t\tif(table[x][y-1].getIsBomb()) {count ++};\r\n\t\t\tif(table[x+1][y-1].getIsBomb()) {count ++};\r\n\t\t\tif(table[x+1][y].getIsBomb()) {count ++};\r\n\t\t\tif(table[x][y+1].getIsBomb()) {count ++};\r\n\t\t\tif(table[x+1][y+1].getIsBomb()) {count ++};\r\n\t\r\n\t\t}\r\n\t} \r\n\t// right hand side\r\n\telse if (x == 29) {\r\n\t\t//upper right corner\r\n\t\tif(y == 0) {\r\n\t\t\tif(table[x-1][y].getIsBomb()) {count ++};\r\n\t\t\tif(table[x-1][y+1].getIsBomb()) {count ++};\r\n\t\t\tif(table[x][y+1].getIsBomb()) {count ++};\r\n\t\t}\r\n\t\t// lower right corner\r\n\t\telse if (y == 15) {\r\n\t\t\tif(table[x-1][y].getIsBomb()) {count ++};\r\n\t\t\tif(table[x-1][y-1].getIsBomb()) {count ++};\r\n\t\t\tif(table[x][y-1].getIsBomb()) {count ++};\r\n\t\t}\r\n\t\telse {\r\n\t\t\tif(table[x][y-1].getIsBomb()) {count ++};\r\n\t\t\tif(table[x-1][y-1].getIsBomb()) {count ++};\r\n\t\t\tif(table[x-1][y].getIsBomb()) {count ++};\r\n\t\t\tif(table[x-1][y+1].getIsBomb()) {count ++};\r\n\t\t\tif(table[x][y+1].getIsBomb()) {count ++};\t\r\n\t\t}\r\n\t}\r\n\t// all other boxes: x does not limit these boxs, y still does \r\n\telse {\r\n\t\tif(y == 0) { // top row excpet corners\r\n\t\t\tif(table[x-1][y].getIsBomb()) {count ++};\r\n\t\t\tif(table[x+1][y].getIsBomb()) {count ++};\r\n\t\t\tif(table[x-1][y+1].getIsBomb()) {count ++};\r\n\t\t\tif(table[x][y+1].getIsBomb()) {count ++};\r\n\t\t\tif(table[x+1][y+1].getIsBomb()) {count ++};\t\r\n\t\t}\r\n\t\telse if (y == 15) { // bottom row except corners\r\n\t\t\tif(table[x-1][y].getIsBomb()) {count ++};\r\n\t\t\tif(table[x-1][y-1].getIsBomb()) {count ++};\r\n\t\t\tif(table[x][y-1].getIsBomb()) {count ++};\r\n\t\t\tif(table[x+1][y-1].getIsBomb()) {count ++};\r\n\t\t\tif(table[x+1][y].getIsBomb()) {count ++};\t\r\n\t\t}\r\n\t\telse { // rest of the boxes\r\n\t\t\tif(table[x-1][y-1].getIsBomb()) {count ++};\r\n\t\t\tif(table[x][y-1].getIsBomb()) {count ++};\r\n\t\t\tif(table[x+1][y-1].getIsBomb()) {count ++};\r\n\t\t\tif(table[x-1][y].getIsBomb()) {count ++};\r\n\t\t\tif(table[x+1][y].getIsBomb()) {count ++};\t\r\n\t\t\tif(table[x-1][y+1].getIsBomb()) {count ++};\r\n\t\t\tif(table[x][y+1].getIsBomb()) {count ++};\r\n\t\t\tif(table[x+1][y+1].getIsBomb()) {count ++};\r\n\t\t}\r\n\t}\r\n\r\n\treturn count;\r\n}", "function actualitzarVides(current){\n document.getElementById(\"vida\").innerHTML = \"\";\n let vidas = \"\";\n\n for(let i = 0; i < (VIDA_MAX - current); i++){\n vidas += \"<img class='broken-heart' alt='corazon-roto' src='./resources/heart/heart-3.png'>\";\n }\n\n if(VIDA_MAX < current) {\n vidas = \"\";\n //console.log(current);\n //console.log(VIDA_MAX);\n for(let i = VIDA_MAX; i < current; i++){\n vidas += \"<img class='golden-heart' alt='corazon' src='./resources/heart/heart.png'>\";\n }\n\n for(let i = 0; i < VIDA_MAX; i++){\n vidas += \"<img alt='corazon' src='./resources/heart/heart.png'>\";\n }\n } else {\n for(let i = 0; i < current; i++){\n vidas += \"<img alt='corazon' src='./resources/heart/heart.png'>\";\n }\n }\n\n document.getElementById(\"vida\").innerHTML += vidas;\n\n \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 calculateNextVelInPaths(){\n pathStats.size += pathStats.calculateSpeed;\n for (let i = 0; i < pathStats.calculateSpeed; i++){\n for (const p of allPlanets){\n p.calculateNextVelInPath();\n }\n }\n}", "blocksTravelled(){\n let horizontal = Math.abs(eastWest.indexOf(this.beginningLocation.horizontal) - eastWest.indexOf(this.endingLocation.horizontal))\n let vertical = Math.abs(parseInt(this.beginningLocation.vertical)-parseInt(this.endingLocation.vertical))\n return (horizontal + vertical);\n }", "function countingValleys(n, s) {\n let seaLevel = 0;\n let mountains = 0;\n let valleys = 0;\n let currentAltitude = 0;\n let stepsSeen = [];\n\n\n for (let step of s) {\n \n step == 'U' ? (++currentAltitude && stepsSeen.push(1)) : (--currentAltitude && stepsSeen.push(-1));\n\n if (currentAltitude == seaLevel) {\n // we have finished a mountain or a valley.\n let positiveTotal = stepsSeen.filter((element) => element > 0).length\n let negativeTotal = stepsSeen.filter((element) => element < 0).length\n\n if (positiveTotal > negativeTotal) {\n ++mountains;\n }\n if (positiveTotal < negativeTotal) {\n ++valleys;\n }\n if (positiveTotal == negativeTotal) {\n if (stepsSeen[0] > 1) {\n ++mountains\n }\n else {\n ++valleys\n }\n }\n stepsSeen = []; // reset;\n }\n \n\n }\n console.log('Mountains seen: ', mountains)\n console.log('Valleys seen: ', valleys)\n return valleys;\n}", "function yPOSnon(yAve, minW, maxW, arrLENGT, gaps){\n\tvar bottomY = [];\n\tvar topY = [];\n\n\tvar whiteoutPOS = [];\n\tvar whiteoutPOS2 = [];\n\n\tvar max = maxW/2\n\tvar min = minW/2\n\n\tfor (i = 0; i < arrLENGT; i++) {\n\t\tvar rand_top = Math.random() * (max - min) + min\n\t\tvar rounded_tenth_top = Math.floor(10*rand_top)/10\n\t\tvar rand_bottom = Math.random() * (max - min) + min\n\t\tvar rounded_tenth_bottom = Math.floor(10*rand_bottom)/10\n\n\t\tbottomY.push(yAve - rounded_tenth_bottom);\n\t\ttopY.push(yAve + rounded_tenth_top);\n\t};\n\n\tvar half_gaps = gaps/2\n\n // SEARCHING FOR THINNEST SPOTS TO DO WHITEOUT POLYGON\n\tfor (i = 0; i < arrLENGT; i++) {\n\t\tif (bottomY[i] >= yAve - half_gaps && topY[i] <= yAve + half_gaps) {\n\t\t\twhiteoutPOS = whiteoutPOS.concat(i);\n\t\t\twhiteoutPOS2 = whiteoutPOS2.concat(bottomY[i] + \" \" + topY[i])\n\t\t}\n\t}\n\n\tallY = topY.concat(bottomY.reverse());\n\n\t// console.log(\"whiteout array \" + whiteoutPOS)\n\t// console.log(\"POS2 \" + whiteoutPOS2)\n\n\tpotentialGAPS = []\n\tnumPOLYGONS = 0\n\n\tfor (i=0; i<= whiteoutPOS.length; i++) { \n\t\tif(whiteoutPOS[i-1] == whiteoutPOS[i]-1){\n\t\t\t// console.log(\"check out spots \" + (i-1) + \" and \" + i)\n\t\t\tpotentialGAPS.push(whiteoutPOS[i-1])\n\t\t\t// console.log(\"potentialGAPS variable ... REAL GAPS start #s \" + potentialGAPS)\n\t\t\tnumPOLYGONS = numPOLYGONS + 1\n\t\t}\n\t}\n\t// console.log(\"num of polygons in line \" + numPOLYGONS)\n\t// console.log(\"length of allY \" + allY.length)\n\t// console.log(\" zero pos of allY \" + allY[0])\n\t// console.log(\" one pos of allY \" + allY[1])\n\t// console.log(\" end pos of allY \" + allY.slice(-1)[0])\n\t// console.log(\" second last pos of allY \" + allY.slice(-2)[0])\n\n\t//NOTE - last half is TOP coordinates\n\t//final point can be ignored to give line a tapering effect\n\t// see comboXY function\n\n\t//return allY\n}", "function placeReal(position){\n switch(position){\n case \"NW\":\n if (game1.toprow[0] === undefined){\n game1.toprow[0] = game1.dude;\n findHWin(game1.toprow);\n findVWin(0);\n findDWin();\n placeVis(position);\n }\n break;\n case \"NC\":\n if (game1.toprow[1] === undefined){\n game1.toprow[1] = game1.dude;\n findHWin(game1.toprow);\n findVWin(1);\n placeVis(position);\n } \n break;\n case \"NE\":\n if (game1.toprow[2] === undefined){\n game1.toprow[2] = game1.dude;\n findHWin(game1.toprow);\n findVWin(2);\n findDWin();\n placeVis(position);\n }\n break;\n case \"CW\":\n if (game1.midrow[0] === undefined){\n game1.midrow[0] = game1.dude;\n findHWin(game1.midrow);\n findVWin(0);\n placeVis(position);\n }\n break;\n case \"CC\":\n if (game1.midrow[1] === undefined){\n game1.midrow[1] = game1.dude;\n findHWin(game1.midrow);\n findVWin(1);\n findDWin();\n placeVis(position);\n }\n break;\n case \"CE\":\n if (game1.midrow[2] === undefined){\n game1.midrow[2] = game1.dude;\n findHWin(game1.midrow);\n findVWin(2);\n placeVis(position);\n }\n break;\n case \"SW\":\n if (game1.botrow[0] === undefined){\n game1.botrow[0] = game1.dude;\n findHWin(game1.botrow);\n findVWin(0);\n findDWin();\n placeVis(position);\n }\n break;\n case \"SC\":\n if (game1.botrow[1] === undefined){\n game1.botrow[1] = game1.dude;\n findHWin(game1.botrow);\n findVWin(1);\n placeVis(position);\n }\n break;\n case \"SE\":\n if (game1.botrow[2] === undefined){\n game1.botrow[2] = game1.dude;\n findHWin(game1.botrow);\n findVWin(2);\n findDWin();\n placeVis(position);\n }\n break;\n default:\n console.log(\"WHAT DID YOU DO!?\");\n }\n}", "function movePokemon(event) {\n const pokemonBottom = pokemon.getBoundingClientRect().bottom;\n const pokemonHeight = pokemon.getBoundingClientRect().height;\n const pokemonTop = pokemon.getBoundingClientRect().top;\n const pokemonWidth = pokemon.getBoundingClientRect().width;\n const pokemonLeft = pokemon.getBoundingClientRect().left;\n for(let i=0 ; i < ballList.length; i++)\n {\n const ballBottom = ballList[i].getBoundingClientRect().bottom;\n const ballLeft = ballList[i].getBoundingClientRect().left;\n const ballHeight = ballList[i].getBoundingClientRect().height;\n const ballWidth = ballList[i].getBoundingClientRect().width;\n const ballRight = ballList[i].getBoundingClientRect().right;\n const ballTop = ballList[i].getBoundingClientRect().top;\n if (pokemonLeft + pokemonWidth >= Math.floor(ballLeft)) {\n \n // &&\n // ((pokemon.getBoundingClientRect().bottom + pokemon.getClientRects().height)>=(ball.getBoundingClientRect().bottom + ball.getClientRects().height)))\n if (pokemonBottom + pokemonHeight >= ballBottom + ballHeight) {\n // window.alert(\"caught\");\n if (pokemonLeft <= ballRight) {\n if (pokemonTop <= ballTop + ballHeight) {\n // console.log(\"true in vertical also************\");\n // console.log(\"pokemmonTop\", pokemonTop);\n // console.log(\"balltop\", ballTop);\n // console.log(\"ballHeight\", ballHeight);\n hideball(ballList[i]);\n moveBallRandom(ballList[i]);\n score.innerText = currentScore + 1;\n currentScore++;\n }\n }\n }\n }\n}\n\n var x = event.keyCode;\n\n if (x == 39 && marginLeft < 1450) {\n var value = pokemon.offsetLeft;\n // console.log(value);\n var pokemonPosition = pokemon.offsetLeft;\n\n pokemon.style.marginLeft = marginLeft + \"px\";\n marginLeft += 10;\n } else if (x == 37 && marginLeft > 0) {\n marginLeft -= 10;\n\n pokemon.style.marginLeft = marginLeft + \"px\";\n } else if (x == 38 && marginTop > 0) {\n marginTop -= 10;\n pokemon.style.marginTop = marginTop + \"px\";\n } else if (\n x == 40 &&\n pokemon.offsetTop + pokemon.offsetHeight + 19 < window.innerHeight\n ) {\n console.log(\"offTop\", pokemon.offsetTop);\n console.log(\"offheight\", pokemon.offsetHeight);\n console.log(\"ineerHeigfht\", window.innerHeight);\n pokemon.style.marginTop = marginTop + \"px\";\n marginTop += 10;\n }\n}", "function Spot(i, j, type)\n{\n\n // Location\n this.i = i;\n this.j = j;\n\n // f, g, and h values for A*\n this.f = 0;\n this.g = 0;\n this.h = 0;\n\n // Neighbors\n this.neighbors = [];\n\n // Spot Type\n this.type = type;\n\n // Figure out who my neighbors are\n this.addNeighbors = function(grid)\n {\n var i = this.i;\n var j = this.j;\n\n if (i < gridsize - 1) this.neighbors.push(grid[i + 1][j]);\n if (i > 0) this.neighbors.push(grid[i - 1][j]);\n if (j < gridsize - 1) this.neighbors.push(grid[i][j + 1]);\n if (j > 0) this.neighbors.push(grid[i][j - 1]);\n\n if (i > 0 && j > 0) this.neighbors.push(grid[i - 1][j - 1]);\n if (i < gridsize - 1 && j > 0) this.neighbors.push(grid[i + 1][j - 1]);\n if (i > 0 && j < gridsize - 1) this.neighbors.push(grid[i - 1][j + 1]);\n if (i < gridsize - 1 && j < gridsize - 1) this.neighbors.push(grid[i + 1][j + 1]);\n\n };\n\n}", "function runLife() {\n\n let nextGen = new Array(resolution * resolution);\n\n for (let i = 0; i < cells.length; i++) {\n let x = i % resolution;\n let y = Math.floor(i / resolution);\n\n let neighbors = countNeighbors(cells, x, y);\n if (cells[i] == 0 && neighbors == 3) {\n nextGen[i] = 1;\n } else if ((cells[i] == 1 && neighbors < 2) || (cells[i] == 1 && neighbors > 3)) {\n nextGen[i] = 0;\n } else {\n nextGen[i] = cells[i];\n }\n }\n\n cells = nextGen;\n}", "function findViewableTiles(povTile,map){\n /*\n var viewDistTiles = 10;\n var viewDist = viewDistTiles*10;\n var viewPolygonTiles = [];\n var viewPolygonPoints = [];\n\n var viewTLCornerX = povTile.mapX - viewDistTiles;\n viewTLCornerX = (viewTLCornerX < 0)? 0 : viewTLCornerX;\n var viewTLCornerY = povTile.mapY - viewDistTiles;\n viewTLCornerY = (viewTLCornerY < 0)? 0 : viewTLCornerY;\n\n var lineOfSight = function(povTile,map,degree,viewDist){\n var nextX = Math.cos(degree * (Math.PI / 180));\n var nextY = Math.sin(degree * (Math.PI / 180));\n var currentX = povTile.image.x;\n var currentY = povTile.image.y;\n var currentTile = map.getLocation(currentX,currentY);\n //var counter = 0;\n //var viewDist = 260;\n var currentDist = 0;\n var done = false;\n\n while(!done){\n \n //povTile.viewableTiles.push(currentTile);\n if(currentTile.blocksVision)\n return currentTile;\n currentX += nextX;\n currentY += nextY;\n if(map.getLocation(currentX,currentY) === undefined){\n return currentTile;\n }else{\n currentTile = map.getLocation(currentX,currentY); \n }\n currentDist = Math.sqrt(Math.pow(currentX-povTile.image.x,2)+Math.pow(currentY-povTile.image.y,2));\n if(currentDist > viewDist) \n return currentTile;\n\n }\n };\n\n //update it with the newly seen tiles\n for (var r = 0; r < 360; r++){ \n var endTile = lineOfSight(povTile,map, r,viewDist);\n if (r == 0 || endTile !== viewPolygonTiles[viewPolygonTiles.length-1])\n viewPolygonTiles.push(endTile);\n }\n for (var b = 0; b < viewPolygonTiles.length; b++){\n viewPolygonPoints.push({x:viewPolygonTiles[b].mapX, y:viewPolygonTiles[b].mapY});\n }\n for (var testX = viewTLCornerX; testX < viewTLCornerX+viewDistTiles*2; testX++){\n for (var testY = viewTLCornerY; testY < viewTLCornerY+viewDistTiles*2; testY++){\n if(map.tiles[testX][testY] !== undefined){\n var testPoint = {\n x : testX,\n y : testY\n }\n if(utils.pointInPolygon(viewPolygonPoints, testPoint)){\n povTile.viewableTiles.push(map.tiles[testX][testY]);\n } \n }\n \n\n }\n }\n\n \n*/\n\n}", "generateStartingPositions() {\n\t\tlet array = [];\n\t\tlet manhattanPositions = [6, 13, 66, 91, 207, 289, 352];\n\t\tlet londonPositions = [11, 48, 57, 108, 167, 330, 390];\n\t\tlet seoulPositions = [12, 17, 32, 42, 89, 134, 174, 294, 316];\n\t\tif (this.game.cityName === \"Manhattan\") {\n\t\t\tlet r = Math.floor((Math.random() * 7));\n\t\t\tarray.push(manhattanPositions[r]);\n\t\t\t// r = Math.floor((Math.random() * 3) + 4);\n\t\t\t// array.push(manhattanPositions[r]);\n\t\t}\n\t\telse if (this.game.cityName === \"London\") {\n\t\t\tlet r = Math.floor((Math.random() * 7));\n\t\t\tarray.push(londonPositions[r]);\n\t\t\t// r = Math.floor((Math.random() * 3) + 4);\n\t\t\t// array.push(londonPositions[r]);\n\t\t}\n\t\telse {\n\t\t\tlet r = Math.floor((Math.random() * 9));\n\t\t\tarray.push(seoulPositions[r]);\n\t\t\t// r = Math.floor((Math.random() * 4) + 5);\n\t\t\t// array.push(seoulPositions[r]);\n\t\t}\n\t\treturn array;\n\t}", "function checkPacDot (){\n if (squares[currentPacManIndex].classList.contains(\"pac-dot\")) {\n\n squares[currentPacManIndex].classList.remove(\"pac-dot\")\n updateScore(pacDotScoreValue)\n pacDotCount++\n\n } else if (squares[currentPacManIndex].classList.contains(\"power-pellet\")) {\n\n squares[currentPacManIndex].classList.remove(\"power-pellet\")\n updateScore(powerPelletScoreValue)\n powerPelletCount++\n activatePowerPellet()\n }\n}", "function createTerminalPoints(cavernWidth, cavernHeight, rawCavernNess){\n // start at a random x co-ord, on the highest floor \n var startX = getRandomInt(15, cavernWidth-15);\n var startY = 0;\n for (var i = 0; i < cavernHeight/2; i++){\n if (rawCavernNess[i][startX] == 0 && rawCavernNess[i+1][startX] == 1){\n startY = i;\n break;\n }\n }\n var terminalPoints = new Array();\n terminalPoints[0] = startX;\n terminalPoints[1] = startY;\n\n var exitX = getRandomInt(15, cavernWidth-15);\n var exitY = cavernHeight-15;\n for (var i = cavernHeight-2; i > cavernHeight/2; i--){\n if (rawCavernNess[i][exitX] == 0 && rawCavernNess[i+1][exitX] == 1){\n exitY = i;\n break;\n }\n }\n terminalPoints[2] = exitX; \n terminalPoints[3] = exitY;\n return terminalPoints;\n}", "function next_generation(game, n){\n // display(num_of_live_neighbours(game,n,1,2));\n const res = [];\n for(let i=0;i<n;i=i+1){\n res[i] = [];\n for(let j=0;j<n;j=j+1){\n const t = num_of_live_neighbours(game,n,i,j);\n if(game[i][j] === 1){\n if(t < 2 || t > 3){\n res[i][j] = 0;\n } else { \n res[i][j] = 1;\n }\n } else {\n if(t === 3){\n res[i][j] = 1;\n } else {\n res[i][j] = 0;\n }\n }\n }\n }\n return res;\n}", "function getMinesAround() {\n\n for (let i = 0; i < tiles.length; i++) {\n let minesAround = 0;\n \n if (tiles[i].classList.contains('empty')) {\n\n // North\n if (i > 9 && tiles[N(i)].classList.contains('mine')) {\n minesAround++;\n }\n \n // North-East\n if (i > 9 && !isRightEdge(i) && tiles[NE(i)].classList.contains('mine') ) {\n minesAround++;\n }\n \n // East \n if (i > -1 && !isRightEdge(i) && tiles[E(i)].classList.contains('mine')) {\n minesAround++;\n }\n\n // South-East\n if (i < 89 && !isRightEdge(i) && tiles[SE(i)].classList.contains('mine') ) {\n minesAround++;\n }\n\n // South\n if (i < 90 && tiles[S(i)].classList.contains('mine')) {\n minesAround++;\n }\n\n // South-West\n if (i < 90 && !isLeftEdge(i) && tiles[SW(i)].classList.contains('mine')) {\n minesAround++;\n }\n\n // West\n if (i > 0 && !isLeftEdge(i) && tiles[W(i)].classList.contains('mine')) {\n minesAround++;\n }\n\n // North-West\n if (i > 10 && !isLeftEdge(i) && tiles[NW(i)].classList.contains('mine')) {\n minesAround++;\n }\n\n tiles[i].setAttribute('mines', minesAround);\n }\n }\n}", "function pre_kill_chaos(){\n\n var chaos_list = [];\n var max_tau = 0;\n coresetData.forEach(function(d){\n\n if(d.color != \"#f7f4f9\"){\n var newll = new google.maps.LatLng(parseFloat(d.x), parseFloat(d.y));\n var newll_c = new google.maps.LatLng(parseFloat(d.x)+0.04, parseFloat(d.y));\n\n var newpoint = mapProjection.fromLatLngToPoint(newll);\n var newpoint_c = mapProjection.fromLatLngToPoint(newll_c);\n\n if(d.color != \"#f7f4f9\"){\n\n // if the rect in chosen range.\n if((sw.lat() <= d.x && ne.lat() >= d.x + delta)\n && (ne.lng() >= d.y && sw.lng() <= d.y + delta)){\n\n chaos_list.push(d);\n var cur_tau = d.value/max;\n\n if(cur_tau > max_tau){\n max_tau = cur_tau;\n }\n\n }\n }\n }\n });\n return max_tau;\n}", "function atkin(limit) {\n const sieve = new Array(limit).fill(false)\n\n for (let x = 0; x * x < limit; x++) {\n for (let y = 0; y * y < limit; y++) {\n let n = 4 * x * x + y * y\n if (n <= limit && (n % 12 == 1 || n % 12 == 5)) sieve[n] = true\n\n n = 3 * x * x + y * y\n if (n <= limit && n % 12 == 7) sieve[n] = true\n\n n = 3 * x * x - y * y\n if (x > y && n <= limit && n % 12 == 11) sieve[n] = true\n }\n }\n for (let r = 5; r * r < limit; r++) {\n if (sieve[r]) for (let i = r * r; i < limit; i += r * r) sieve[i] = false\n }\n\n const res = [2, 3]\n for (let a = 5; a < limit; a++) {\n if (sieve[a]) res.push(a)\n }\n return res\n}", "function voxelize ( left, right, bottom, top, spacing, edits ) {\n var i, j, d, out = []\n\n for ( i = 0, y = bottom; y <= top; y += spacing, i++ ) {\n out.push([])\n for ( j = 0, x = left; x <= right; x += spacing, j++ ) {\n out[i].push(compute(edits, [ x, y ])().toFixed(2))\n }\n }\n return out\n}", "function atvd17(){\n \n let a = parseFloat(document.querySelector(\"#atvd17-1\").value);\n let b = parseFloat(document.querySelector(\"#atvd17-2\").value);\n let c = parseFloat(document.querySelector(\"#atvd17-3\").value);\n\n let de,x1=0,x2=0;\n \n\n de = (Math.pow(b, 2)) - (4*a*c);\n \n \n x1= (-b - Math.sqrt(de))/(2*a);\n \n x2= (-b + Math.sqrt(de))/(2*a);\n \n\n if(de<0){\n document.getElementById(\"raiz\").innerHTML = \"Não existe raiz real\";\n\n }else{\n document.getElementById(\"raiz\").innerHTML = \"VALOR DA PRIMEIRA RAIZ:\" + x1+ \" | \" + \"VALOR DA SEGUNDA RAIZ:\" + x2;\n \n }\n \n }", "function countVoisin(grid, x ,y){\n let sum = 0;\n for (let i = -1; i < 2; i++) {\n for (let j = -1; j < 2; j++) {\n let c = (x + i + col) % col;\n let r = (y + j + row) % row;\n sum += grid[c][r];\n }\n }\n // substract itself\n sum -= grid[x][y];\n return sum;\n }", "function evaluarCartaMayor15() {\n for (var x = 0; x < arrayPosicionesGanadores.length; x++) {\n\n jugadores[arrayPosicionesGanadores[x]].combinacionCartas.sort(function(a, b) {\n return b - a;\n });\n\n if (jugadores[arrayPosicionesGanadores[x]].combinacionCartas[0] > cartaMayor) {\n cartaMayor = jugadores[arrayPosicionesGanadores[x]].combinacionCartas[0];\n } else if (jugadores[arrayPosicionesGanadores[x]].combinacionCartas[4] === 1) {\n existeAS = true;\n }\n }\n\n if (existeAS === true) {\n for (var a = 0; a < arrayPosicionesGanadores.length; a++) {\n if (jugadores[arrayPosicionesGanadores[a]].combinacionCartas[4] === 1) {\n arrayPosiciones.push(arrayPosicionesGanadores[a]);\n }\n }\n } else {\n for (var w = 0; w < arrayPosicionesGanadores.length; w++) {\n if (jugadores[arrayPosicionesGanadores[w]].combinacionCartas[0] === cartaMayor) {\n arrayPosiciones.push(arrayPosicionesGanadores[w]);\n }\n }\n }\n }", "function checkEarthTopoPetsFound() {\n\tif (topoPetsCaught.totalEARTH == getTotalAmountEarthTopoPets()) {\n\t\tdocument.getElementById(\"achievementAllEarthTopoPets\").style.display = \"block\";\n\t}\n}", "DetermineBestSupportingPosition()\n {\n //only update the spots every few frames\n if (!this.m_pRegulator.isReady() && this.m_pBestSupportingSpot)\n {\n return new Phaser.Point(this.m_pBestSupportingSpot.m_vPos.x, this.m_pBestSupportingSpot.m_vPos.y);\n }\n\n //reset the best supporting spot\n this.m_pBestSupportingSpot = null;\n\n var BestScoreSoFar = 0.0;\n\n for (var curSpot = 0; curSpot < this.m_Spots.length; ++curSpot)\n {\n //first remove any previous score. (the score is set to one so that\n //the viewer can see the positions of all the spots if he has the\n //aids turned on)\n this.m_Spots[curSpot].m_dScore = 1.0;\n\n //Test 1. is it possible to make a safe pass from the ball's position\n //to this position?\n if (this.m_pTeam.isPassSafeFromAllOpponents(this.m_pTeam.ControllingPlayer().Pos(),\n this.m_Spots[curSpot].m_vPos,\n null,\n Params.MaxPassingForce))\n {\n this.m_Spots[curSpot].m_dScore += Params.Spot_PassSafeScore;\n }\n\n\n //Test 2. Determine if a goal can be scored from this position.\n var ret_canshoot = this.m_pTeam.CanShoot(this.m_Spots[curSpot].m_vPos,\n Params.MaxShootingForce);\n if (ret_canshoot[0])\n {\n this.m_Spots[curSpot].m_dScore += Params.Spot_CanScoreFromPositionScore;\n }\n\n\n //Test 3. calculate how far this spot is away from the controlling\n //player. The further away, the higher the score. Any distances further\n //away than OptimalDistance pixels do not receive a score.\n if (this.m_pTeam.SupportingPlayer())\n {\n var OptimalDistance = 200.0;\n\n var dist = this.m_pTeam.ControllingPlayer().Pos().distance(this.m_Spots[curSpot].m_vPos);\n\n var temp = Math.abs(OptimalDistance - dist);\n\n if (temp < OptimalDistance)\n {\n\n //normalize the distance and add it to the score\n this.m_Spots[curSpot].m_dScore += Params.Spot_DistFromControllingPlayerScore *\n (OptimalDistance - temp) / OptimalDistance;\n }\n }\n\n //check to see if this spot has the highest score so far\n if (this.m_Spots[curSpot].m_dScore > BestScoreSoFar)\n {\n BestScoreSoFar = this.m_Spots[curSpot].m_dScore;\n\n this.m_pBestSupportingSpot = this.m_Spots[curSpot];\n }\n\n }\n\n return new Phaser.Point(this.m_pBestSupportingSpot.m_vPos.x, this.m_pBestSupportingSpot.m_vPos.y);\n }", "addvecinos() {\r\n if (this.x > 0) { //vecino izquierdo\r\n this.vecinos.push(escenario[this.y][this.x - 1]);\r\n }\r\n if (this.x < filas - 1) { //vecino derecho\r\n this.vecinos.push(escenario[this.y][this.x + 1]);\r\n }\r\n if (this.y > 0) { //vecino superior\r\n this.vecinos.push(escenario[this.y - 1][this.x]);\r\n }\r\n if (this.y < columnas - 1) { //vecino inferior\r\n this.vecinos.push(escenario[this.y + 1][this.x]);\r\n }\r\n\r\n /*console.log(this.vecinos);*/ //muestra los vecinos\r\n }" ]
[ "0.6546746", "0.5950092", "0.5878988", "0.5749731", "0.5660239", "0.56167346", "0.5608126", "0.5593348", "0.55027676", "0.54972225", "0.54894847", "0.546082", "0.54430366", "0.5355412", "0.534842", "0.53376466", "0.5327156", "0.5294996", "0.52926755", "0.52909184", "0.5278586", "0.5269764", "0.5268162", "0.5244356", "0.5229713", "0.5214312", "0.52130795", "0.5211734", "0.5197397", "0.5196885", "0.51904553", "0.5188968", "0.51881534", "0.5186433", "0.51857966", "0.5185178", "0.51823807", "0.5179271", "0.5172848", "0.51716954", "0.5171127", "0.5157657", "0.5153729", "0.5151886", "0.514996", "0.5142091", "0.51311845", "0.5129811", "0.5129", "0.5121309", "0.511966", "0.51195127", "0.51122737", "0.511012", "0.510715", "0.5102953", "0.5093208", "0.5092546", "0.5089612", "0.5088719", "0.50802594", "0.50794786", "0.5060267", "0.5054404", "0.50536513", "0.5047666", "0.5041989", "0.5040351", "0.5039959", "0.503858", "0.5030215", "0.50253624", "0.5020558", "0.50181687", "0.5015642", "0.5015129", "0.50125283", "0.5011265", "0.5003959", "0.5002099", "0.49940845", "0.49927634", "0.4988184", "0.49865505", "0.49864274", "0.49858007", "0.49825534", "0.49794832", "0.4974443", "0.49729055", "0.49724627", "0.49720138", "0.49708563", "0.49693763", "0.49693334", "0.4968351", "0.49676785", "0.4965174", "0.49622595", "0.49597943" ]
0.5956367
1
This function calculates the spots that Population 1 takes up
function calculatePop1(){ let area = (dims.value)*(dims.value); area = area - calculateV(); let pop1 = area*popRatio.value; return Math.floor(pop1); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function percentageOfWorld1(populations){\n return populations / 7900 * 100;\n }", "function calculatePop2(){\n let area = (dims.value)*(dims.value);\n let pop2 = area-(calculateV()+calculatePop1());\n return Math.floor(pop2);\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}", "winningPositions() {\n return [\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 }", "function markOccupiedSpots() {\n \n\t\tif(!spotsInitialized || playersInitialized < 2) {\n \n\t\t\treturn null;\n \n } // end if statement\n\t\n\t\tfor(var i = 0; i<10; i++) {\n \n\t\t\tfindClosestSpot(myMarbles[i].x, myMarbles[i].y).isEmpty = false;\n\t\t\tfindClosestSpot(othersMarbles[i].x, othersMarbles[i].y).isEmpty = false;\n \n\t\t} // end for loop\n \n\t} // end markOccupiedSpots()", "_getPartOfCount() {\n\n // 8-neighborhood around\n const n = [\n Point.val(this.x - 1, this.y - 1),\n Point.val(this.x - 1, this.y),\n Point.val(this.x - 1, this.y + 1),\n Point.val(this.x, this.y - 1),\n Point.val(this.x, this.y + 1),\n Point.val(this.x + 1, this.y - 1),\n Point.val(this.x + 1, this.y),\n Point.val(this.x + 1, this.y + 1),\n ];\n\n const edges = n.filter(p => p === '-' || p === '|').length;\n const ind = [];\n for (let i = 0; i < 8; i++) {\n if (n[i] === '-' || n[i] === '|') ind.push(i);\n }\n\n switch (edges) {\n\n case 2:\n switch (ind[0]) {\n case 1: \n return ind[1] === 3 ? (n[0] === n[7] ? 2 : 1) : (n[2] === n[5] ? 2 : 1);\n case 3: \n return n[2] === n[5] ? 2 : 1;\n case 4: \n return n[0] === n[7] ? 2 : 1;\n }\n\n case 3: \n return n.filter(p => p === ' ').length === 5 ? 3 : 2;\n\n case 4:\n return n.filter(p => p === ' ').length;\n }\n }", "function getOffsets(size) {\n //THIS FUNCTION IS SO UGLY IM SO SORRY\n let wO = (size * 1.732050808 / 2);\n let hO = size;\n let ans = [];\n\n let startingY = 50 - 2 * (hO * .75);\n let startingX = 50 - wO;\n\n for (let i = 0; i < 3; i++) {\n ans.push(`top:${startingY}%;left:${startingX + i * (wO)}%`)\n }\n\n startingY = 50 - 1 * (hO * .75);\n startingX = 50 - wO * (1.5);\n\n for (let i = 0; i < 4; i++) {\n ans.push(`top:${startingY}%;left:${startingX + i * (wO)}%`)\n }\n\n startingY = 50;\n startingX = 50 - wO * (2);\n\n for (let i = 0; i < 5; i++) {\n ans.push(`top:${startingY}%;left:${startingX + i * (wO)}%`)\n }\n\n\n\n startingY = 50 + 1 * (hO * .75);\n startingX = 50 - wO * (1.5);\n\n for (let i = 0; i < 4; i++) {\n ans.push(`top:${startingY}%;left:${startingX + i * (wO)}%`)\n }\n\n startingY = 50 + 2 * (hO * .75);\n startingX = 50 - wO;\n\n\n for (let i = 0; i < 3; i++) {\n ans.push(`top:${startingY}%;left:${startingX + i * (wO)}%`)\n }\n return ans;\n}", "findUpgradeSpots() {\n if (this.danger) { return []; }\n const controller = this.object('controller');\n\n const upgradeSpots = controller.room.lookAtArea(\n controller.pos.y - 3, controller.pos.x - 3,\n controller.pos.y + 3, controller.pos.x + 3, true\n ).filter((lookObj) => {\n return (\n lookObj.type === LOOK_TERRAIN &&\n lookObj[lookObj.type] !== 'wall'\n );\n }).map(lookObj => {\n return {x: lookObj.x, y: lookObj.y};\n });\n this.nbUpgradeSpots = upgradeSpots.length;\n\n return upgradeSpots;\n }", "function setNumbers() {\r\n\r\n for (var x = 0; x < size; x++) {\r\n for (var y = 0; y < size; y++) {\r\n visitLocation(x, y, minesNear);\r\n }\r\n }\r\n }", "function resolveHalfSpotting(stack1, stack2, who)\n{\n var spot = stack1.getSpotting();\n console.log(['spotting',spot]);\n stack2.ambush = false;\n for(var i=0; i<stack2.slots.length; i++)\n { var r = rnd(6);\n console.log([r,spot,stack2.slots[i].unit.camo,r+spot-stack2.slots[i].unit.camo]);\n if(r+spot-stack2.slots[i].unit.camo < 3)\n { stack2.slots[i].ambush = true;\n stack2.ambush = true;\n }\n else stack2.slots[i].ambush = false;\n }\n if(stack2.ambush)\n { logEvent(\"hidden\",null,null,who);\n for(var i=0; i<stack2.slots.length; i++)\n { if(stack2.slots[i].ambush) \n { console.log(stack2.slots[i].unit);\n logEvent(\"ambush\",stack2.slots[i].unit);\n }\n }\n \n }\n}", "calPopulationFitness() {\n this.#fitsum = 0;\n for (let i = 0; i < this.parentPop.length; i++) {\n let song = this.parentPop[i];\n song.calFitness(fitnessChoice);\n this.#fitsum += song.fitness;\n }\n \n // parentPop Invariant\n if (minFitness) this.parentPop.sort(compareFitnessDec);\n else this.parentPop.sort(compareFitnessInc);\n }", "calculateFitness() {\n //print(\"pop calculating fitness\");\n for (var i =0; i<this.pop_size; i++) {\n this.players[i].calculateFitness();\n }\n }", "function markerSize(population) {\n return population / 40;\n }", "function squaresNeeded(grains){\n return Math.ceil(Math.log2(grains+1))\n}", "getCurrentSquares() {\n\t\treturn this.state.history[this.state.stepNumber].squares;\n\t}", "function Spot(i, j, type)\n{\n\n // Location\n this.i = i;\n this.j = j;\n\n // f, g, and h values for A*\n this.f = 0;\n this.g = 0;\n this.h = 0;\n\n // Neighbors\n this.neighbors = [];\n\n // Spot Type\n this.type = type;\n\n // Figure out who my neighbors are\n this.addNeighbors = function(grid)\n {\n var i = this.i;\n var j = this.j;\n\n if (i < gridsize - 1) this.neighbors.push(grid[i + 1][j]);\n if (i > 0) this.neighbors.push(grid[i - 1][j]);\n if (j < gridsize - 1) this.neighbors.push(grid[i][j + 1]);\n if (j > 0) this.neighbors.push(grid[i][j - 1]);\n\n if (i > 0 && j > 0) this.neighbors.push(grid[i - 1][j - 1]);\n if (i < gridsize - 1 && j > 0) this.neighbors.push(grid[i + 1][j - 1]);\n if (i > 0 && j < gridsize - 1) this.neighbors.push(grid[i - 1][j + 1]);\n if (i < gridsize - 1 && j < gridsize - 1) this.neighbors.push(grid[i + 1][j + 1]);\n\n };\n\n}", "function squaresNeeded(grains){\n let deg = 0;\n while (grains > 0) { grains = grains - 2 ** (deg); deg++; }\n return deg;\n}", "function markerSize(population) {\n return population / 60;\n}", "genNextSpot() {\r\n let countFreeSpaces = this.gameState.board.filter((i) => i === 0).length;\r\n if (countFreeSpaces === 0) {\r\n this.checkLose();\r\n } else {\r\n let locationToAdd = Math.floor(Math.random() * Math.floor(countFreeSpaces));\r\n let numEmptyTraversed = 0;\r\n for (let i = 0; i < this.gameState.board.length; i++) {\r\n if (this.gameState.board[i] === 0) {\r\n if (numEmptyTraversed === locationToAdd) {\r\n this.gameState.board[i] = this.gen2or4();\r\n break;\r\n } else {\r\n numEmptyTraversed++;\r\n }\r\n }\r\n }\r\n } \r\n }", "constructor() {\n this.parentPop = []; // Main population - invariant : always sorted, best indiv on the front\n this.matingPool = []; // Individuals chosen as parents are temporarily stored here\n this.childPop = []; // Child population for step 3 - 'produceOffspring'\n \n this.#fitsum = 0;\n \n // Init parentPop with new random individuals\n for (let i = 0; i < popsize; i++) {\n this.parentPop[i] = new Song();\n }\n }", "generateHousingOccupancy() {\n if (this._occupiedHouses <= 99) {\n this._hv = [0, 0, 0, 0, 0, 0, 0, 0];\n return;\n } else {\n // Generate tiny fluctuations for the housing weights, but only do so if\n // the number of occupied houses is above 100\n let wVector = this.HOUSING_WEIGHTS; // Copy of the housing weights\n let fVector = [0, 0, 0, 0, 0, 0, 0, 0]; // Fluctuations vector\n let wSum = 0;\n if (this._occupiedHouses > 10) {\n for (let i = 0; i < wVector.length; i++) {\n // Divide by 40 for +/- 1%\n fVector[i] = wVector[i] * (1 + ((Math.random() - 0.5) / 40));\n wSum += fVector[i];\n }\n } else {\n fVector = wVector;\n wSum = 1;\n }\n\n // Generate the housing vector\n let vSum = 0; // The sum of the housing vector's elements\n for (let i = 0; i < wVector.length; i++) {\n this._hv[i] = Math.round(this._occupiedHouses * fVector[i] / wSum);\n vSum += this._hv[i];\n }\n\n // Correct the rounding error here\n // A positive rDiff means there are more houses than there should be\n // A negative rDiff means there are fewer houses than there should be\n // Rounding errors are corrected by ideally adding/removing houses of the\n // smallest household size, which only adds/removes one person at a time\n let rDiff = vSum - this._occupiedHouses;\n if (this._occupiedHouses === 1) {\n // This is to introduce the really interesting case of having a city with\n // a population of 1\n this._hv = [1, 0, 0, 0, 0, 0, 0, 0];\n } else {\n if (rDiff !== 0) {\n // Traverse the array from beginning to end\n // Find the first element such that adding/subtracting rDiff produces\n // zero or a positive number\n let i = 0;\n for (; i < this._hv.length; i++)\n if (this._hv[i] - rDiff >= 0) break;\n\n this._hv[i] -= rDiff;\n\n // console.log(\"[HousingManager]: Corrected a rounding error of \" + rDiff + \" by adjusting index \" + i);\n }\n }\n }\n }", "function fullHousePoints() {\n var twoSame = 0;\n var threeSame = 0;\n let full = frequency();\n\n for (let i = 0; i < 7; i++) {\n if (full[i] >= 3) {\n threeSame = i * 3;\n } else if (full[i] >= 2) {\n twoSame = i * 2;\n }\n }\n\n if (threeSame != 0 && twoSame != 0) {\n return threeSame + twoSame;\n } else {\n return 0;\n }\n if (!inputs[10].locked) {\n inputs[10].selected = true;\n }\n\n}", "function gen1(){\n\t// First tile\n\taddtile(0, 0, le, -le/2, -1.5388*le, 0);\n\t\n\t// Generating tiles around points\n\tfor(var i=0; i<iter; i++){\n\t\tif( isvisiblepoint(i,w,h) ){\n\t\t\tfor(var j=0; j<retries; j++){ fillpoint(i, le); }\n\t\t\t//if(masksum(i)<10){ destroypoint(i); } // optional destroying point if it can't be filled\n\t\t}\n\t}\n\t// Rendering SVG\n\tvar svgstr = createSVGString(w,h,stylepresets[stylepr],drawp);\n\t\n\t// Appending SVG string\n\tappendSVGString(svgstr,'mainbody');\n\t\n\t// Stats\n\tconsole.log('Number of tiles: '+tiles.length+' Number of points: '+points.length+' SVG string length: '+svgstr.length+' Avg. points/tiles: '+points.length/tiles.length+' Tiles/iter: '+tiles.length/iter);\n\n}// End of gen1()", "function setupGenetic(){\r\n orderGA = [];\r\n\r\n for (var i = 0; i < totalVertices; i++) {\r\n orderGA[i] = i;\r\n }\r\n \r\n population = [];\r\n fitness = [];\r\n recordDistanceGA = Infinity;\r\n\r\n generation = document.getElementById('numGen').value;;\r\n popSize = document.getElementById('sizePop').value;\r\n\r\n for (var i = 0; i < popSize; i++) {\r\n population[i] = customShuffle(orderGA, orderGA[0]);\r\n }\r\n\r\n mutationRate = document.getElementById('rateMut').value;\r\n indexPopulation = 0;\r\n countGA = 0;\r\n\r\n totalCountGA = (totalVertices-1)*generation*popSize;\r\n}", "function percentageOfWorld1(population) {\n return (population / 7900) * 100;\n}", "function percentageOfWorld1(population) {\n return (population / 7900) * 100;\n}", "function bucketLane() {\r\n\t\r\n\tvar bucketArray = document.querySelectorAll(\".bucket\");\r\n\t\r\n\tif (bucketArray[0].location == 1)\r\n\t\treturn 15;\r\n\tif (bucketArray[1].location == 1)\r\n\t\treturn 45;\r\n\tif (bucketArray[2].location == 1)\r\n\t\treturn 30;\r\n\t\r\n}", "function numOffices(grid) {\n let result = 0;\n\n for (let x = 0; x < grid[0].length; x++) {\n if (grid[0][x] === 1 && grid[0][x - 1] !== 1) {\n result = result + 1;\n }\n }\n\n\n for (let y = 1; y < grid.length; y++) {\n for (let x = 0; x < grid[0].length; x++) {\n if (grid[y][x] === 1 && grid[y][x - 1] !== 1 && grid[y - 1][x] !== 1) {\n result = result + 1;\n }\n }\n }\n return result;\n}", "function goldStars(points) {}", "function bestSpot(){\n//return an empty square (a random square for now)\nreturn emptySquares()[Math.floor(Math.random()*emptySquares().length)];\n}", "function find_landing_square(column_dropped_on) {\n//For loop. If dropped in square 1, the loop id going to start at 36 and its\n//going to loop backwards, subtracting 7 each time. It's looping backwards.\n//We iterate backwards and minus 7 each time.\n\t\tfor (i = column_dropped_on + 35; i >= column_dropped_on; i -= 7) {\n\t\t\tvar dropped_square = $('#' + i); //this is document.getElementByID in jQuery. We are getting a hold of that div it was dropped on.\n\t\t\tvar dropped_square_num = dropped_square.attr('id'); //this is an object. It's returning the div. We are getting the number (the divs ID).\n\n\t\t\t//If the dropped_square square has the class of 'can_place'\n\t\t\t//(this will be true), we return the array back which includes the\n\t\t\t//distance from top to 6 (how far it has to go down), and the\n\t\t\t//dropped_square square number.\n\t\t\tif (dropped_square.hasClass('can_place')) {\n\t\t\t\tif (dropped_square_num > 35) {\n\t\t\t\t\treturn ['503px', dropped_square_num];\n\t\t\t\t} else if (dropped_square_num > 28) {\n\t\t\t\t\treturn ['419px', dropped_square_num];\n\t\t\t\t} else if (dropped_square_num > 21) {\n\t\t\t\t\treturn ['335px', dropped_square_num];\n\t\t\t\t} else if (dropped_square_num > 14) {\n\t\t\t\t\treturn ['251px', dropped_square_num];\n\t\t\t\t} else if (dropped_square_num > 7) {\n\t\t\t\t\treturn ['167px', dropped_square_num];\n\t\t\t\t} else {\n\t\t\t\t\treturn ['83px', dropped_square_num];\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}", "function evaluateNextGenome() {\n //increment index in genome array\n currentGenome++;\n //If there is none, evolves the population.\n if (currentGenome == genomes.length) {\n evolve();\n }\n document.getElementById(\"Individual\").innerHTML = (currentGenome + 1) + \"/\" + populationSize;\n //load current gamestate\n loadState(roundState);\n //reset moves taken\n movesTaken = 0;\n //and make the next move\n makeNextMove();\n}", "function calcMoves() {\n moves++;\n movesSpan.innerText = moves;\n updateStars();\n }", "function setBuildingSpots(){\n\tcurBuildingSpot = squareTiles[103];\n\tbuildingSpotArray = [squareTiles[90],squareTiles[25],squareTiles[53]];\n}", "get hitbox_x1() { return -7; }", "function generateStartingGrid() {\n Mobile();\n let Gaps = emptyGrid();\n let n = 1;\n let m = 0;\n for (let i = 0; i < x; i++) {\n for (let j = 0; j < y; j++) {\n // People point generater\n if (Gaps.includes(n)) {\n } else {\n var dotOffWid = getRandomArbitrary(0.2, 0.8) * refWid;\n var dotOffHei = getRandomArbitrary(0.2, 0.8) * refHei;\n let xData = refWid * i + dotOffWid;\n let yData = refHei * j + dotOffHei;\n dotData[m] = [xData, yData, 0, 0, 0, 0, 0,\"blue\"];\n resetData[m] = [xData, yData];\n m++;\n }\n n++;\n }\n }\n //console.log(\"generateStartingGrid: \" + dotData)\n}", "function squaresNeeded(grains){\n\n let squares = [1]\n let acc = 1;\n for (i = 1; i < 65; i++){\n acc *= 2\n squares.push(acc)\n }\n\n let ans = 0;\n for (i = 0; i < squares.length; i++){\n if (grains >= squares[i]){\n ans = i+1;\n }\n }\n\n return ans\n}", "calculate_fitness() {\n this.fitness = new Array(this.population_size);\n for (let i = 0; i < this.fitness.length; i++) {\n this.fitness[i] = this.members[i].fitness;\n }\n\n this.total_fitness = this.fitness.reduce((total, fitness) => total += fitness);\n }", "function calculate_population_fitness(population) {\n fitnesses = []\n population.map((item) => fitnesses.push(fitness(item)))\n return fitnesses\n}", "function allPossibleWinPositions(size)\n{\n let wins = []\n let onewin = []\n let coords = []\n for (let y = 1; y <= size; y++) {\n for (let x = 1; x <= size; x++) {\n coords.push(x)\n coords.push(y)\n onewin.push(coords)\n coords = []\n }\n wins.push(onewin)\n onewin = []\n }\n for (let x = 1; x <= size; x++) {\n for (let y = 1; y <= size; y++) {\n coords.push(x)\n coords.push(y)\n onewin.push(coords)\n coords = []\n }\n wins.push(onewin)\n onewin = []\n }\n for (let a = 1; a <= size; a++) {\n coords.push(a,a)\n onewin.push(coords)\n coords = []\n }\n wins.push(onewin)\n onewin=[]\n for (let a = 1; a <= size; a++) {\n coords.push(size-a+1,a)\n onewin.push(coords)\n coords = []\n }\n wins.push(onewin)\n onewin=[]\n\n return wins\n}", "function bestSpot() {\n return minimax(origBoard, com).index;\n}", "function Spot(i, j) {\n // Location\n this.i = i;\n this.j = j;\n\n // f, g, and h values for A*\n this.f = 0;\n this.g = 0;\n this.h = 0;\n\n // Neighbors\n this.neighbors = [];\n\n // Where did I come from?\n this.previous = undefined;\n\n // Am I a wall?\n this.wall = false;\n if (random(1) < 0.4) {\n this.wall = true;\n }\n\n // Display me\n this.show = function(col) {\n if (this.wall) {\n fill(0);\n noStroke();\n ellipse(this.i * w + w / 2, this.j * h + h / 2, w / 2, h / 2);\n } else if (col) {\n fill(col);\n rect(this.i * w, this.j * h, w, h);\n }\n };\n\n // Figure out who my neighbors are\n this.addNeighbors = function(grid) {\n var i = this.i;\n var j = this.j;\n if (i < cols - 1) {\n this.neighbors.push(grid[i + 1][j]);\n }\n if (i > 0) {\n this.neighbors.push(grid[i - 1][j]);\n }\n if (j < rows - 1) {\n this.neighbors.push(grid[i][j + 1]);\n }\n if (j > 0) {\n this.neighbors.push(grid[i][j - 1]);\n }\n if (i > 0 && j > 0) {\n this.neighbors.push(grid[i - 1][j - 1]);\n }\n if (i < cols - 1 && j > 0) {\n this.neighbors.push(grid[i + 1][j - 1]);\n }\n if (i > 0 && j < rows - 1) {\n this.neighbors.push(grid[i - 1][j + 1]);\n }\n if (i < cols - 1 && j < rows - 1) {\n this.neighbors.push(grid[i + 1][j + 1]);\n }\n };\n}", "DetermineBestSupportingPosition() {\n //only update the spots every few frames \n if ( !this.m_pRegulator.isReady() && this.m_pBestSupportingSpot != null ) {\n return this.m_pBestSupportingSpot.m_vPos;\n };\n\n //reset the best supporting spot\n this.m_pBestSupportingSpot = null;\n\n let BestScoreSoFar = 0.0;\n\n //let it = m_Spots.listIterator();\n\n //while ( it.hasNext() ) {\n // let curSpot = it.next();\n\n\n for( let it = 0, size = this.m_Spots.length; it < size; it++ ){\n\n let curSpot = this.m_Spots[ it ];\n\n //first remove any previous score. (the score is set to one so that\n //the viewer can see the positions of all the spots if he has the \n //aids turned on)\n curSpot.m_dScore = 1.0;\n\n //Test 1. is it possible to make a safe pass from the ball's position \n //to this position?\n if ( this.m_pTeam.isPassSafeFromAllOpponents( this.m_pTeam.ControllingPlayer().Pos(),\n curSpot.m_vPos,\n null,\n Prm.MaxPassingForce ) ) {\n curSpot.m_dScore += Prm.Spot_PassSafeScore;\n };\n\n\n //Test 2. Determine if a goal can be scored from this position. \n if ( this.m_pTeam.CanShoot( curSpot.m_vPos,\n Prm.MaxShootingForce ) ) {\n curSpot.m_dScore += Prm.Spot_CanScoreFromPositionScore;\n };\n\n\n //Test 3. calculate how far this spot is away from the controlling\n //player. The further away, the higher the score. Any distances further\n //away than OptimalDistance pixels do not receive a score.\n if ( this.m_pTeam.SupportingPlayer() != null ) {\n\n let OptimalDistance = 200.0;\n\n let dist = Vector2D.Vec2DDistance( this.m_pTeam.ControllingPlayer().Pos(),\n curSpot.m_vPos );\n\n let temp = Math.abs( OptimalDistance - dist );\n\n if ( temp < OptimalDistance ) {\n\n //normalize the distance and add it to the score\n curSpot.m_dScore += Prm.Spot_DistFromControllingPlayerScore\n * ( OptimalDistance - temp ) / OptimalDistance;\n };\n };\n\n //check to see if this spot has the highest score so far\n if ( curSpot.m_dScore > BestScoreSoFar ) {\n BestScoreSoFar = curSpot.m_dScore;\n\n this.m_pBestSupportingSpot = curSpot;\n };\n\n };\n\n return this.m_pBestSupportingSpot.m_vPos;\n }", "naturalSelection() {\n this.matingPool = [];\n\n let maxFitness = 0;\n for (let i = 0; i < this.population.length; i++) {\n if (this.population[i].fitness > maxFitness) {\n maxFitness = this.population[i].fitness;\n }\n }\n\n for (let i = 0; i < this.population.length; i++) {\n // Scalling zero to max fitness in zero to one range\n let fitness = map(this.population[i].fitness, 0, maxFitness, 0, 1);\n let n = floor(fitness * 100);\n for (let j = 0; j < n; j++) {\n this.matingPool.push(this.population[i]);\n }\n }\n }", "calcFitness() {\n for (let i = 0; i < this.population.length; i++) {\n this.population[i].calcFitness(this.target);\n }\n }", "function percentageOfWorld1(populationPercent) {\n return populationPercent / 7900 * 100;\n}", "getVisitsGraphics() {\n return 90 + ',' + 70 + ',' + 90 + ',' + 70+ ',' + 75 + ',' + 80 + ',' + 70;\n }", "function getBucketSpots(bucketNum, x0, y0, width, height, elementW, elementH){\n var bucketSpots = {};\n var x,y;\n var spacing = (height/bucketNum)-elementH;\n for (var i = 0; i < bucketNum; i++) {\n var y = y0 + i*(elementH + spacing);\n bucketSpots[String(i)] = [x0,y,elementW,elementH,[]];\n }\n\n console.log(bucketSpots);\n return bucketSpots;\n}", "selection() {\n // Clear the ArrayList\n this.matingPool = [];\n\n // Calculate total fitness of whole population\n var maxFitness = this.getMaxFitness();\n\n // Calculate fitness for each member of the population (scaled to value between 0 and 1)\n // Based on fitness, each member will get added to the mating pool a certain number of times\n // A higher fitness = more entries to mating pool = more likely to be picked as a parent\n // A lower fitness = fewer entries to mating pool = less likely to be picked as a parent\n for (var i = 0; i < this.population.length; i++) {\n var fitnessNormal = map(this.population[i].getFitness(), 0, maxFitness, 0, 1);\n var n = floor(fitnessNormal * 100); // Arbitrary multiplier\n\n for (var j = 0; j < n; j++) {\n this.matingPool.push(this.population[i]);\n }\n }\n }", "calcTroops(villageId,buildings)\n {\n let barrackList =[]\n let barrackQ;\n let barrack = this.troopres['club'].split(',');\n let res = m.villageData[villageId][\"res\"];\n console.log(barrack)\n \n barrackList.push(parseInt(res.wood/barrack[0]))\n barrackList.push(parseInt(res.clay/barrack[1]))\n barrackList.push(parseInt(res.iron/barrack[2]))\n barrackList.push(parseInt(res.crop/barrack[3]))\n barrackQ = Math.min.apply(null, barrackList);\n console.log(barrackQ)\n let rcrop = parseInt(res.crop) - barrackQ*barrack[3]; \n if(rcrop>200)\n {\n \n return barrackQ;\n }\n else\n {\n return 0;\n }\n }", "function greedyPoo(items) {\n var resultsGreed = [];\n let currentSize = 0;\n let currentValue = 0;\n \n sortedStuff(greedItems).forEach(item => {\n if(currentSize + item.size <= capacity) {\n resultsGreed.push(item.index);\n currentSize += item.size;\n currentValue += item.value;\n } \n })\n return {resultsGreed, currentSize, currentValue};\n }", "function result() {\r\n\t// Teams Names Array\r\n\tvar tn = document.getElementsByClassName('teamName');\r\n\tvar teams = [];\r\n\t// Teams First Map Stats Array\r\n\tvar m1k = document.getElementsByClassName('m1k');\r\n\tvar m1p = document.getElementsByClassName('m1p');\r\n\r\n\t// Teams Second Map Stats Array\r\n\tvar m2k = document.getElementsByClassName('m2k');\r\n\tvar m2p = document.getElementsByClassName('m2p');\r\n\t// Teams Second Map Stats Array\r\n\tvar m3k = document.getElementsByClassName('m3k');\r\n\tvar m3p = document.getElementsByClassName('m3p');\r\n\r\n\t// Kill and Placement Stats for All Teams\r\n\tvar kstats = [];\r\n\tvar pstats = [];\r\n\r\n\tvar results = [];\r\n\t// Set Teams that won the map (3 Teams)\r\n\tvar win = [];\r\n\tvar totalp = [];\r\n\tfor (var i = 0; i < tn.length; i++) {\r\n\t\tteams[i] = tn[i].value;\r\n\t\tvar Kills = 0;\r\n\t\tvar placePoints = [];\r\n\r\n\t\tkills = parseInt(m1k[i].value);\r\n\t\tkills += parseInt(m2k[i].value);\r\n\t\tkills += parseInt(m3k[i].value);\r\n\t\tvar place =[];\r\n\r\n\t\tplace.push(m1p[i].value); //[m1p[i].value, m2p[i].value, m3p[i].value];\r\n\t\tplace.push(m2p[i].value);\r\n\t\tplace.push(m3p[i].value);\r\n\r\n\t\tkstats[i] = kills;\r\n\t\t//pstats.push(placePoints);\r\n\r\n\t\tplacePoints = 0;\r\n\t\tfor (var e = 0; e < 3; e++) {\r\n\t\t \tswitch (parseInt(place[e])) {\r\n\t\t\t case 1:\r\n\t\t\t win.push(i);\r\n\t\t\t \tplacePoints += 15;\r\n\t\t\t break;\r\n\t\t\t case 2:\r\n\t\t\t placePoints += 12;\r\n\t\t\t break;\r\n\t\t\t case 3:\r\n\t\t\t placePoints += 10;\r\n\t\t\t break;\r\n\t\t\t case 4:\r\n\t\t\t placePoints += 8;\r\n\t\t\t break;\r\n\t\t\t case 5:\r\n\t\t\t placePoints += 6;\r\n\t\t\t break;\r\n\t\t\t case 6:\r\n\t\t\t placePoints += 4;\r\n\t\t\t break;\r\n\t\t\t case 7:\r\n\t\t\t placePoints += 2;\r\n\t\t\t break;\r\n\t\t\t case 8:\r\n\t\t\t placePoints += 1;\r\n\t\t\t break;\r\n\t\t\t case 9:\r\n\t\t\t placePoints += 1;\r\n\t\t\t break;\r\n\t\t\t case 10:\r\n\t\t\t placePoints += 1;\r\n\t\t\t break;\r\n\t\t\t case 11:\r\n\t\t\t placePoints += 1;\r\n\t\t\t break;\r\n\t\t\t case 12:\r\n\t\t\t placePoints += 1;\r\n\t\t\t break;\r\n\t\t\t default:\r\n\t\t\t placePoints += 0;\r\n\t\t\t} // End of SWITCH Statement\r\n\t\t} // End of FOR e Loop\r\n\t\tpstats[i] = placePoints;\r\n\r\n\t\ttotalp[i] = kills + placePoints;\r\n\t// Placement Stats for All Teams\r\n\t} // End of FOR i Loop \r\n\r\n\tfor (var c = 0; c < tn.length; c++) {\r\n\t\tresults[c] = {name: teams[c], kp: kstats[c], pp: pstats[c], tp: totalp[c], win: 0};\r\n\t\t// [teams[c], kstats[c], pstats[c], totalp[c], 0];\r\n\r\n\t}\r\n\tfor(var d = 0; d < win.length; d++){\r\n\t\tresults[win[d]].win += 1;\r\n\t}\r\n\r\n\tresults.sort(function (x, y) {\r\n \treturn y.tp - x.tp;\r\n\t});\r\n\t// Create a Loop to put Data from results into the HTML Table\r\n\t// Element\r\n\tfor(var s = 0; s < results.length; s++){\r\n\t\t// Put Team Name\r\n\t\tdocument.getElementsByClassName('tteam')[s].innerHTML = results[s].name\r\n\t\t// Put Team Win\r\n\t\tdocument.getElementsByClassName('twwcd')[s].innerHTML = results[s].win;\r\n\t\t// Put Team Kill Points\r\n\t\tdocument.getElementsByClassName('tkp')[s].innerHTML = results[s].kp;\r\n\t\t// Put Team Placement Points\r\n\t\tdocument.getElementsByClassName('tpp')[s].innerHTML = results[s].pp;\r\n\t\t// Put Total Points\r\n\t\tdocument.getElementsByClassName('ttp')[s].innerHTML = results[s].tp;\r\n\t}\r\n\tdocument.getElementsByClassName('rtable')[0].style.display = 'block';\r\n\tdocument.getElementsByClassName('datat')[0].style.display = 'none';\r\n}", "function histTable(slvGames){\n var hitArr = []\n var hitArrOpp = []\n var arr = opponentInfo(slvGames)\n slvGames.gamePlayer.forEach(elem => {\n let user = document.getElementById(\"player\")\n let opponent = document.getElementById(\"opponent\")\n if(elem.gp_id == myParam){\n user.innerHTML = elem.player.name + \" \"\n }\n else if(elem.gp_id != myParam){\n opponent.innerHTML = elem.player.name\n }\n })\n arr.forEach(el => {\n if(el.gp_id == myParam){\n let x = document.getElementById(\"O\" + el.ship)\n x.innerHTML = el.ship\n hitArrOpp.push(el.ship)\n } else if(el.gp_id != myParam){\n let y = document.getElementById(el.ship)\n y.innerHTML = el.ship\n hitArr.push(el.ship)\n }\n })\n\n// set hits on my ships\n var hitOnSub = 0;\n var hitOnPT = 0;\n var hitOnCar = 0;\n var hitOnDes = 0;\n var hitOnBat = 0;\n for(var i=0;i<hitArr.length;i++){\n if(hitArr[i] === \"Submarine\"){\n hitOnSub++;\n if(hitOnSub == 3){\n let p = document.getElementById(\"sSub\")\n p.innerHTML = \"Submarine\"\n p.style.color = \"red\"\n }\n } else if(hitArr[i] === \"Patrol Boat\"){\n hitOnPT++;\n if(hitOnPT == 2){\n let p = document.getElementById(\"sPat\")\n p.innerHTML = \"Patrol Boat\"\n p.style.color = \"red\"\n }\n } else if(hitArr[i] === \"Carrier\"){\n hitOnCar++;\n if(hitOnCar == 5){\n let p = document.getElementById(\"sCar\")\n p.innerHTML = \"Carrier\"\n p.style.color = \"red\"\n }\n } else if(hitArr[i] === \"Battleship\"){\n hitOnBat++;\n if(hitOnBat == 4){\n let p = document.getElementById(\"sBat\")\n p.innerHTML = \"Battleship\"\n p.style.color = \"red\"\n }\n } else if(hitArr[i] === \"Destroyer\"){\n hitOnDes++;\n if(hitOnDes == 3){\n let p = document.getElementById(\"sDes\")\n p.innerHTML = \"Destroyer\"\n p.style.color = \"red\"\n }\n }\n }\n\n// set hits on Opponent ships\n var hitOnOSub = 0;\n var hitOnOPT = 0;\n var hitOnOCar = 0;\n var hitOnODes = 0;\n var hitOnOBat = 0;\n for(var i=0;i<hitArrOpp.length;i++){\n if(hitArrOpp[i] === \"Submarine\"){\n hitOnOSub++;\n if(hitOnOSub == 3){\n let p = document.getElementById(\"osSub\")\n p.innerHTML = \"Submarine\"\n p.style.color = \"red\"\n }\n } else if(hitArrOpp[i] === \"Patrol Boat\"){\n hitOnOPT++;\n if(hitOnOPT == 2){\n let p = document.getElementById(\"osPat\")\n p.innerHTML = \"Patrol Boat\"\n p.style.color = \"red\"\n }\n } else if(hitArrOpp[i] === \"Carrier\"){\n hitOnOCar++;\n if(hitOnOCar == 3){\n let p = document.getElementById(\"osCar\")\n p.innerHTML = \"Carrier\"\n p.style.color = \"red\"\n }\n } else if(hitArrOpp[i] === \"Battleship\"){\n hitOnOBat++;\n if(hitOnOBat == 3){\n let p = document.getElementById(\"osBat\")\n p.innerHTML = \"Battleship\"\n p.style.color = \"red\"\n }\n } else if(hitArrOpp[i] === \"Destroyer\"){\n hitOnODes++;\n if(hitOnODes == 3){\n let p = document.getElementById(\"osDes\")\n p.innerHTML = \"Destroyer\"\n p.style.color = \"red\"\n }\n }\n }\n\n// set my ships display\n slvGames.ships.forEach(ship => {\n let Pt = document.getElementById(\"patrol boat-hit\")\n let Cr = document.getElementById(\"carrier-hit\")\n let Sb = document.getElementById(\"submarine-hit\")\n let Dt = document.getElementById(\"destroyer-hit\")\n let Bt = document.getElementById(\"battleship-hit\")\n if(ship.type == \"Carrier\" && hitOnCar > 0){\n document.getElementById(\"carrier-hit\").style.marginBottom = '10px'\n ship.ships_locations.forEach(el => {\n let div = document.createElement(\"div\")\n div.setAttribute(\"id\", \"h\" + el)\n div.setAttribute(\"class\", \"col-1\")\n div.innerHTML = el\n Cr.appendChild(div)\n })\n } else if(ship.type == \"Battleship\" && hitOnBat != 0){\n document.getElementById(\"battleship-hit\").style.marginBottom = '10px'\n ship.ships_locations.forEach(el => {\n let div = document.createElement(\"div\")\n div.setAttribute(\"id\", \"h\" + el)\n div.setAttribute(\"class\", \"col-1\")\n div.innerHTML = el\n Bt.appendChild(div)\n })\n } else if(ship.type == \"Submarine\" && hitOnSub != 0){\n document.getElementById(\"submarine-hit\").style.marginBottom = '10px'\n ship.ships_locations.forEach(el => {\n let div = document.createElement(\"div\")\n div.setAttribute(\"id\", \"h\" + el)\n div.setAttribute(\"class\", \"col-1\")\n div.innerHTML = el\n Sb.appendChild(div)\n })\n } else if(ship.type == \"Patrol Boat\" && hitOnPT != 0){\n document.getElementById(\"patrol boat-hit\").style.marginBottom = '10px'\n ship.ships_locations.forEach(el => {\n let div = document.createElement(\"div\")\n div.setAttribute(\"id\", \"h\" + el)\n div.setAttribute(\"class\", \"col-1\")\n div.innerHTML = el\n Pt.appendChild(div)\n })\n } else if(ship.type == \"Destroyer\" && hitOnDes != 0){\n document.getElementById(\"destroyer-hit\").style.marginBottom = '10px'\n ship.ships_locations.forEach(el => {\n let div = document.createElement(\"div\")\n div.setAttribute(\"id\", \"h\" + el)\n div.setAttribute(\"class\", \"col-1\")\n div.innerHTML = el\n Dt.appendChild(div)\n })\n }\n })\n // set my Opponents ships display\n slvGames.ships.forEach(ship => {\n let Pt = document.getElementById(\"Opatrol boat-hit\")\n let Cr = document.getElementById(\"Ocarrier-hit\")\n let Sb = document.getElementById(\"Osubmarine-hit\")\n let Dt = document.getElementById(\"Odestroyer-hit\")\n let Bt = document.getElementById(\"Obattleship-hit\")\n if(ship.type == \"Carrier\" && hitOnOCar > 0){\n document.getElementById(\"Ocarrier-hit\").style.marginBottom = '10px'\n ship.ships_locations.forEach(el => {\n let div = document.createElement(\"div\")\n div.setAttribute(\"id\", \"ocar\" + ship.ships_locations.indexOf(el))\n div.setAttribute(\"class\", \"col-1\")\n div.innerHTML = el\n Cr.appendChild(div)\n })\n } else if(ship.type == \"Battleship\" && hitOnOBat != 0){\n document.getElementById(\"Obattleship-hit\").style.marginBottom = '10px'\n ship.ships_locations.forEach(el => {\n let div = document.createElement(\"div\")\n div.setAttribute(\"id\", \"obat\" + ship.ships_locations.indexOf(el))\n div.setAttribute(\"class\", \"col-1\")\n div.innerHTML = el\n Bt.appendChild(div)\n })\n } else if(ship.type == \"Submarine\" && hitOnOSub != 0){\n document.getElementById(\"Osubmarine-hit\").style.marginBottom = '10px'\n ship.ships_locations.forEach(el => {\n let div = document.createElement(\"div\")\n div.setAttribute(\"id\", \"osub\" + ship.ships_locations.indexOf(el))\n div.setAttribute(\"class\", \"col-1\")\n div.innerHTML = el\n Sb.appendChild(div)\n })\n } else if(ship.type == \"Patrol Boat\" && hitOnOPT != 0){\n document.getElementById(\"Opatrol boat-hit\").style.marginBottom = '10px'\n ship.ships_locations.forEach(el => {\n let div = document.createElement(\"div\")\n div.setAttribute(\"id\", \"opat\" + ship.ships_locations.indexOf(el))\n div.setAttribute(\"class\", \"col-1\")\n div.innerHTML = el\n Pt.appendChild(div)\n })\n } else if(ship.type == \"Destroyer\" && hitOnODes != 0){\n document.getElementById(\"Odestroyer-hit\").style.marginBottom = '10px'\n ship.ships_locations.forEach(el => {\n let div = document.createElement(\"div\")\n div.setAttribute(\"id\", \"odes\" + ship.ships_locations.indexOf(el))\n div.setAttribute(\"class\", \"col-1\")\n div.innerHTML = el\n Dt.appendChild(div)\n })\n }\n })\n }", "function createFreePointsMap(){\n var index=0;\n for (var i = 0; i < 20; i++){\n for (var j = 0; j < 20; j++){\n /*if((j==0 && i == 1) || (j==0 && i == 18) || (j==1 && i >=1 && i <= 8) || (j==1 && i == 11) || (j==1 && i == 14) || (j==1 && i == 18) || (j>=2 && j<=3 && i == 1) || (j>=2 && j<=3 && i == 11) || (j==3 && i>=9 && i<=10) || (j==5 && i==0) ||\n (i==1 && j>=5 && j<=7) || (j==3 && i>=9 && i<=10) || (j==4 && i>=3 && i<=6)|| (j==5 && i>=10 && i<=14)||\n (j==5 && i>=16 && i<=18) || (j==7 && i>=3 && i<=9)|| (j==7 && i>=10 && i<=18) || (j==9 && i>=5 && i<=9) ||\n (j==9 && i>=11 && i<=12) || (j==11 && i>=11 && i<=18) || (j==14 && i>=1 && i<=3) || (j==13 && i>=11 && i<=14) ||\n (j==15 && i>=11 && i<=14) || (j==3 && i>=9 && i<=10) || (j==16 && i>=1 && i<=5) || (j==16 && i>=7 && i<=9) ||\n (j==18 && i>=1 && i<=10) || (j==18 && i>=12 && i<=18) || (i==14 && j>=2 && j<=4) || (i==16 && j>=2 && j<=4) ||\n (i==5 && j>=5 && j<=6) || (i==8 && j>=5 && j<=6) || (i==3 && j>=8 && j<=10) || (i==15 && j>=8 && j<=10) ||\n (i==18 && j>=8 && j<=9) || (i==18 && j>=12 && j<=17) || (i==1 && j>=11 && j<=13) || (i==5 && j>=10 && j<=15) || (i==7 && j>=11 && j<=15) || (i==9 && j>=10 && j<=15) || (i==3 && j>=12 && j<=13) || (i==12 && j>=16 && j<=17) ||\n (i==16 && j>=14 && j<=15) || (i==1 && j==17) || (i==14 && j==14))*/\n if((j>=1 && j<=2 && i>=1 && i<=3) || (j>=1 && j<=2 && i>=5 && i<=7) || (j>=1 && j<=2 && i>=11 && i<=13) || (j>=1 && j<=2 && i>=15 && i<=18) ||\n (j>=0 && j<=2 && i==9) || (j==4 && i>=1 && i<=3) || (j==4 && i>=15 && i<=18) ||(j>=6 && j<=8 && i>=1 && i<=3) || (j>=6 && j<=8 && i>=15 && i<=18) ||\n (j>=10 && j<=12 && i>=1 && i<=3) || (j>=10 && j<=12 && i>=15 && i<=18) || (j>=8 && j<=10 && i>=7 && i<=11) || (j==18 && i>=1 && i<=7) ||\n (j==18 && i>=11 && i<=13) || (j==18 && i>=15 && i<=18) || (j==16 && i>=0 && i<=1) || (j==16 && i>=7 && i<=11) || (j==16 && i>=17 && i<=18) ||\n (j==14 && i>=1 && i<=3) || (j==14 && i>=5 && i<=7) || (j==14 && i>=11 && i<=13) || (j==14 && i>=15 && i<=18) || (j==12 && i>=7 && i<=11) ||\n (j==4 && i>=7 && i<=11) || (j==6 && i>=6 && i<=7) || (j==6 && i>=11 && i<=12) || (i==3 && j>=15 && j<=16) || (i==15 && j>=15 && j<=16) ||\n (i==5 && j>=16 && j<=17) || (i==5 && j>=10 && j<=12) || (i==5 && j>=4 && j<=8) || (i==9 && j>=5 && j<=6) || (i==9 && j>=13 && j<=14) ||\n (i==9 && j>=17 && j<=18) || (i==13 && j>=4 && j<=8) || (i==13 && j>=10 && j<=12) || (i==13 && j>=16 && j<=17) )\n {\n if(i==9 && j==8){\n\n }\n else if(i==9 && j==10){\n\n }\n else{\n continue;\n }\n\n }\n else{\n freePointsMap.points[index] = j;\n freePointsMap.points[index + 1] = i;\n index+=2;\n }\n }\n }\n}", "function twcheese_calculatePopulation(buildings,troopsDefending,troopsOutside)\n\t{\n\t\tvar buildingPopBases = new Array(1.17,1.17,1.17,1.17,1.55,1.55,1.17,1.17,1.17,1.17,1.17,1.155,1.14,1.17,1,1.15,1.17,1.17);\n\t\tvar buildingPopFactors = new Array(5,7,8,8,5,5000,80,20,0,10,20,5,10,10,0,0,2,5);\n\t\tvar troopPopulation = new Array(1,1,1,1,2,4,5,6,5,8,10,100);\t\t\n\t\t\n\t\tvar buildingPopulation = 0;\n\t\tvar militaryPopulation = 0;\n\t\tvar maxPopulation = Math.round(240 * Math.pow(1.172103,buildings[14]-1));\n\t\tfor(var i=0; i < 18; i++)\n\t\t{\n\t\t\tif(buildings[i] > 0)\n\t\t\t{\n\t\t\t\tbuildingPopulation += Math.round(buildingPopFactors[i] * Math.pow(buildingPopBases[i],(buildings[i] - 1)));\n\t\t\t}\n\t\t}\n\t\tfor(var i=0; i < 12; i++)\n\t\t{\n\t\t\tmilitaryPopulation += troopPopulation[i]*Number(troopsDefending[i]);\n\t\t\tif(troopsOutside)\n\t\t\t\tmilitaryPopulation += troopPopulation[i]*Number(troopsOutside[i]);\n\t\t}\t\t\n\t\treturn new Array(buildingPopulation,militaryPopulation,(maxPopulation - buildingPopulation - militaryPopulation));\t\n\t}", "function getGaps(requestedFloor) {\n for (var i = 0; i < listElevators.length; i++) {\n gapList.push(Math.abs(requestedFloor - listElevators[i].current_position));\n }\n}", "runPop() {\n\n const now = Date.now();\n\n const averageOverIterations = [];\n\n for (let i = 3; i < this.maxGeneration; i++) {\n\n for (let j = 0; j < this.repeatNumber; j++) {\n\n const population = new Population('Genetic Algorithm!', i, false);\n this.previousGen.push(population.run());\n\n }\n\n const group = this.previousGen.filter(s => s.size === i);\n\n const avgGen = Math.round(group.map(gen => gen.numGen)\n .reduce((a, b) => (a + b)) / this.repeatNumber);\n\n const avgTime = Math.round(group.map(gen => gen.time)\n .reduce((a, b) => (a + b)) / this.repeatNumber);\n\n const sameSize = group[0].size;\n\n const avgObj = {\n numGen: avgGen,\n size: sameSize,\n time: avgTime,\n };\n\n averageOverIterations.push(avgObj);\n\n }\n\n averageOverIterations.sort((a, b) => a.numGen - b.numGen);\n\n const { numGen, size, time } = averageOverIterations[0];\n\n console.log(`\n *****\n Max populatation size: ${this.maxGeneration}\n Iterations per generation: ${this.repeatNumber}\n\n *****\n Optimum populatation size: ${size}\n Average number of generations: ${numGen}\n Average time: ${time}ms\n\n *****\n OptimumPopulationSize execution time: ${Date.now() - now}ms`);\n\n }", "function percentageOfWorld1(population) {\n let totalWorld = 7900000000;\n return (population / totalWorld) * 100;\n}", "calcFitness() {\n let counter = 0;\n for (let i = 0; i < target.length; i++) {\n if (this.genes[i] == target[i]) counter++\n }\n this.fitness = counter\n }", "minedRendering(bomb_loc, mined_loc) {\n for (let i = 0; i < 12; i++) {\n for (let j = 0; j < 18; j++) {\n if (mined_loc[i][j] !== null && !\"GOAL\".includes(mined_loc[i][j])) {\n mined_loc[i][j] = this.countBombs(bomb_loc, [i, j]);\n }\n }\n }\n\n return mined_loc;\n }", "repopulate () {\n const nbToGenerate = this.populationSize - this.currentPopulation.length\n const newGenomes = Array(nbToGenerate).fill('').map(genome => new Genome(this.nbInput, this.nbOutput))\n this.currentPopulation = [...this.currentPopulation, ...newGenomes]\n }", "function howPopulated(population, landArea) {}", "function topple() {\n for (let x = 0; x < width; x++) {\n for (let y = 0; y < height; y++) {\n nextpiles[x][y] = sandpiles[x][y];\n }\n }\n\n // adjust the critical height if needed\n criticalHeight = 4;\n for (let x = 0; x < width; x++) {\n for (let y = 0; y < height; y++) {\n let num = sandpiles[x][y];\n if (num >= criticalHeight) {\n nextpiles[x][y] -= 4;\n if (x + 1 < width)\n nextpiles[x + 1][y]++;\n if (x - 1 >= 0)\n nextpiles[x - 1][y]++;\n if (y + 1 < height)\n nextpiles[x][y + 1]++;\n if (y - 1 >= 0)\n nextpiles[x][y - 1]++;\n }\n }\n }\n\n let tmp = sandpiles;\n sandpiles = nextpiles;\n nextpiles = tmp;\n}", "function cata(percentage, pop){\r\n\tpop[0] = poisson((1-percentage)*pop[0]);\r\n\tpop[1] = poisson((1-percentage)*pop[1]);\r\n}", "calcFitness()\n {\n for(let i=0; i< this.population.length; i++)\n {\n this.population[i].calculateFitness(this.target); \n }\n }", "function toOz(shots){\n\treturn shots * SHOT_SIZE;\n}", "function mercantileType() {\n var calcOcc = function () {\n // Taking input\n var a = document.getElementById('carpetAreaGround-mercantile').valueAsNumber;\n var b = document.getElementById('carpetAreaUpper-mercantile').valueAsNumber;\n // Calculating Number of People\n var resultA = Math.abs(Math.round(a / 3));\n var resultB = Math.abs(Math.round(b / 6));\n var resultFixedOccupancy = Math.abs(Math.round((resultA + resultB) * 0.10));\n var resultFloatingOccupancy = Math.abs(Math.round((resultA + resultB) * 0.90));\n var resultTotalOccupancy = Math.abs(Math.round(resultA + resultB));\n\n return [resultA, resultB, resultFixedOccupancy, resultFloatingOccupancy, resultTotalOccupancy];\n };\n var occupancyResult = function () {\n // Declaring Result\n var values = calcOcc();\n document.getElementById('resultOccupancy').innerHTML = \"Total Occupancy: \" + values[4] + \"<br />\" + \"Fixed Occupancy ~ \" + values[2] + \"<br />\" + \"Floating Occupancy ~ \" + values[3] ;\n };\n \n return occupancyResult();\n}", "function calculateSandwichPoints(bam) { //calculates amnt of Sandwich points/second for ingredient sacrificed\n return Math.floor(ingredients[bam][1] * ingredients[bam][2] * 50)\n}", "function grassGrow(array) {\n if (asdf % 200 == 0) {\n for (let p = 0; p < array.length; p++) {\n array[p].y1 -= 1;\n }\n }\n asdf++;\n}", "function potionsLeft()\r\n{\r\n var potionsX = gameWidth * 3/4;;\r\n var potionsY = 28;\r\n var offset = 30;\r\n \r\n //Background\r\n stroke(0);\r\n strokeWeight(1);\r\n fill(50,50,50,100);\r\n rect(potionsX-20,potionsY/2-6,10+(offset*revitalizeJumpPower),40,10);\r\n \r\n for(var i = 0; i < revitalizeJumpPower; i++)\r\n {\r\n stroke(0);\r\n strokeWeight(1);\r\n fill(0, 50, 255, 200);\r\n //rect(potionsX-6 + offset*i, potionsY-15, 12, 7);\r\n //ellipse(potionsX + offset*i, potionsY-14, 14, 4);\r\n ellipse(potionsX + offset*i, potionsY, 24, 24);\r\n }\r\n}", "function Prob11(){\n\n\tvar grid = [[08,02,22,97,38,15,00,40,00,75,04,05,07,78,52,12,50,77,91,08],\n\t\t\t\t[49,49,99,40,17,81,18,57,60,87,17,40,98,43,69,48,04,56,62,00],\n\t\t\t\t[81,49,31,73,55,79,14,29,93,71,40,67,53,88,30,03,49,13,36,65],\n\t\t\t\t[52,70,95,23,04,60,11,42,69,24,68,56,01,32,56,71,37,02,36,91],\n\t\t\t\t[22,31,16,71,51,67,63,89,41,92,36,54,22,40,40,28,66,33,13,80],\n\t\t\t\t[24,47,32,60,99,03,45,02,44,75,33,53,78,36,84,20,35,17,12,50],\n\t\t\t\t[32,98,81,28,64,23,67,10,26,38,40,67,59,54,70,66,18,38,64,70],\n\t\t\t\t[67,26,20,68,02,62,12,20,95,63,94,39,63,08,40,91,66,49,94,21],\n\t\t\t\t[24,55,58,05,66,73,99,26,97,17,78,78,96,83,14,88,34,89,63,72],\n\t\t\t\t[21,36,23,09,75,00,76,44,20,45,35,14,00,61,33,97,34,31,33,95],\n\t\t\t\t[78,17,53,28,22,75,31,67,15,94,03,80,04,62,16,14,09,53,56,92],\n\t\t\t\t[16,39,05,42,96,35,31,47,55,58,88,24,00,17,54,24,36,29,85,57],\n\t\t\t\t[86,56,00,48,35,71,89,07,05,44,44,37,44,60,21,58,51,54,17,58],\n\t\t\t\t[19,80,81,68,05,94,47,69,28,73,92,13,86,52,17,77,04,89,55,40],\n\t\t\t\t[04,52,08,83,97,35,99,16,07,97,57,32,16,26,26,79,33,27,98,66],\n\t\t\t\t[88,36,68,87,57,62,20,72,03,46,33,67,46,55,12,32,63,93,53,69],\n\t\t\t\t[04,42,16,73,38,25,39,11,24,94,72,18,08,46,29,32,40,62,76,36],\n\t\t\t\t[20,69,36,41,72,30,23,88,34,62,99,69,82,67,59,85,74,04,36,16],\n\t\t\t\t[20,73,35,29,78,31,90,01,74,31,49,71,48,86,81,16,23,57,05,54],\n\t\t\t\t[01,70,54,71,83,51,54,69,16,92,33,48,61,43,52,01,89,19,67,48]];\n\n\tthis.eval = function(){\n\t\t\n\t\tvar maxProduct = 0;\n\t\tvar w = 20; //width\n\t\tvar h = 20;\n\t\tvar n = 4; //number of numbers\n\n\t\t//Across\n\t\tvar product;\n\t\tfor(var j = 0; j<h; j++){\n\t\t\tfor(var i = 0; i<w-n-1; i++){\n\t\t\t\tproduct = grid[j][i]*grid[j][i+1]*grid[j][i+2]*grid[j][i+3];\n\t\t\t\tif(product>maxProduct){maxProduct=product;}\n\t\t\t}\n\t\t}\n\n\t\t//Up and down\n\t\tfor(var i = 0; i<w; i++){\n\t\t\tfor(var j = 0; j<h-n-1; j++){\n\t\t\t\tproduct = grid[j][i]*grid[j+1][i]*grid[j+2][i]*grid[j+3][i];\n\t\t\t\tif(product>maxProduct){maxProduct=product;}\n\t\t\t}\n\t\t}\n\n\t\t//Diag SE & NW\n\t\tfor(var i = 0; i<w-n-1; i++){\n\t\t\tfor(var j = 0; j<h-n-1; j++){\n\t\t\t\tproduct = grid[j][i]*grid[j+1][i+1]*grid[j+2][i+2]*grid[j+3][i+3];\n\t\t\t\tif(product>maxProduct){maxProduct=product;}\n\t\t\t}\n\t\t}\n\n\t\t//Diag SW & NE\n\t\tfor(var i = 0; i<w-n-1; i++){\n\t\t\tfor(var j = n-1; j<h; j++){\n\t\t\t\tproduct = grid[j][i]*grid[j-1][i+1]*grid[j-2][i+2]*grid[j-3][i+3];\n\t\t\t\tif(product>maxProduct){maxProduct=product;}\n\t\t\t}\n\t\t}\n\n\t\treturn maxProduct;\n\t};\n}", "produceOffspring() {\n this.childPop = [];\n \n for (let i = 0; i < this.parentPop.length; i++) {\n let parent1 = random(this.matingPool);\n let parent2 = random(this.matingPool);\n let child;\n \n switch (crossoverChoice) {\n case 0:\n child = crossover.singlePoint(parent1, parent2);\n break;\n case 1:\n child = crossover.uniform(parent1, parent2);\n break;\n case 2:\n child = crossover.average(parent1, parent2);\n }\n \n switch (mutationChoice) {\n case 0:\n mutation.randomFlip(child);\n break;\n case 1:\n mutation.addVal(child);\n }\n \n child.calFitness(fitnessChoice);\n this.childPop[i] = child;\n }\n }", "function cal_posi(hashtag) {\n top_height = height / 6\n gap_y = height / 10\n max_tags_y = 5 // criteria 1: max num of tags permitted within the same height\n max_gap = 5 // criteria 2: |sum1-sum2| <= max_gap\n max_tags = 25 // max num of tags permiited in total\n hashtag.length = max_tags\n\n cnter = 0\n curr_value = hashtag[0][1]\n curr_height = top_height\n\n for (d in hashtag) {\n if (cnter < max_tags_y && curr_value - hashtag[d][1] <= max_gap) {\n cnter += 1\n }\n else {\n curr_height += gap_y\n curr_value = hashtag[d][1]\n cnter = 1\n }\n\n hashtag[d].push(curr_height)\n hashtag[d][2] = hashtag[d][2] / hashtag[d][1]\n }\n}", "getFoodLocation() {\n let x = Utils.rand(MARGIN, document.body.clientWidth - MARGIN, SIZE);\n let y = Utils.rand(MARGIN, document.body.clientHeight - MARGIN, SIZE);\n // If random spot is already filled, pick a new one\n // Pick until you find an empty spot\n // ..... nothing can go wrong with this\n if (Locations.has(x, y)) {\n [x, y] = this.getFoodLocation();\n }\n return [x, y];\n }", "mul() {\n this.multiply += 2;\n let emptyCells = this.chooseCell(0)\n let newCell = random(emptyCells)\n if (weather == \"dzmer\") {\n this.multiply -= 2\n }\n else if (weather == \"amar\") {\n this.multiply -= 1\n }\n else if (weather == \"ashun\" || weather == \"garun\") {\n this.multiply += 1\n }\n if (this.multiply >= 5 && newCell) {\n let newGrass = new Grass(newCell[0], newCell[1], this.index);\n grassArr.push(newGrass);\n matrix[newCell[1]][newCell[0]] = 1;\n this.multiply = 0;\n grassMul++\n }\n }", "function getYAverage() {\n let sum = 0;\n for (let i = 0; i < blueSquares.length; i++) {\n sum += blueSquares[i].centerOfSquare.y;\n }\n return (sum / blueSquares.length);\n }", "function Pocket () {\n let pocket = [];\n for (let z = 0; z < iterAmt*2+1; z++) {\n let layer = []\n for (let y = 0; y < iterAmt*2+startGrid.length; y++) {\n let row = []\n row = Array(iterAmt*2 + startGrid[0].length).fill(0).map(()=>{return{active:false,nearby:0}})\n layer.push(row)\n }\n pocket.push(layer)\n }\n return pocket\n}", "function yPOSnon(yAve, minW, maxW, arrLENGT, gaps){\n\tvar bottomY = [];\n\tvar topY = [];\n\n\tvar whiteoutPOS = [];\n\tvar whiteoutPOS2 = [];\n\n\tvar max = maxW/2\n\tvar min = minW/2\n\n\tfor (i = 0; i < arrLENGT; i++) {\n\t\tvar rand_top = Math.random() * (max - min) + min\n\t\tvar rounded_tenth_top = Math.floor(10*rand_top)/10\n\t\tvar rand_bottom = Math.random() * (max - min) + min\n\t\tvar rounded_tenth_bottom = Math.floor(10*rand_bottom)/10\n\n\t\tbottomY.push(yAve - rounded_tenth_bottom);\n\t\ttopY.push(yAve + rounded_tenth_top);\n\t};\n\n\tvar half_gaps = gaps/2\n\n // SEARCHING FOR THINNEST SPOTS TO DO WHITEOUT POLYGON\n\tfor (i = 0; i < arrLENGT; i++) {\n\t\tif (bottomY[i] >= yAve - half_gaps && topY[i] <= yAve + half_gaps) {\n\t\t\twhiteoutPOS = whiteoutPOS.concat(i);\n\t\t\twhiteoutPOS2 = whiteoutPOS2.concat(bottomY[i] + \" \" + topY[i])\n\t\t}\n\t}\n\n\tallY = topY.concat(bottomY.reverse());\n\n\t// console.log(\"whiteout array \" + whiteoutPOS)\n\t// console.log(\"POS2 \" + whiteoutPOS2)\n\n\tpotentialGAPS = []\n\tnumPOLYGONS = 0\n\n\tfor (i=0; i<= whiteoutPOS.length; i++) { \n\t\tif(whiteoutPOS[i-1] == whiteoutPOS[i]-1){\n\t\t\t// console.log(\"check out spots \" + (i-1) + \" and \" + i)\n\t\t\tpotentialGAPS.push(whiteoutPOS[i-1])\n\t\t\t// console.log(\"potentialGAPS variable ... REAL GAPS start #s \" + potentialGAPS)\n\t\t\tnumPOLYGONS = numPOLYGONS + 1\n\t\t}\n\t}\n\t// console.log(\"num of polygons in line \" + numPOLYGONS)\n\t// console.log(\"length of allY \" + allY.length)\n\t// console.log(\" zero pos of allY \" + allY[0])\n\t// console.log(\" one pos of allY \" + allY[1])\n\t// console.log(\" end pos of allY \" + allY.slice(-1)[0])\n\t// console.log(\" second last pos of allY \" + allY.slice(-2)[0])\n\n\t//NOTE - last half is TOP coordinates\n\t//final point can be ignored to give line a tapering effect\n\t// see comboXY function\n\n\t//return allY\n}", "function pokemonBattle() {\n const wildGrass = generatePokemon();\n //appearedPoke = wildGrass.slice();\n const img1 = document.querySelector('#img1');\n img1.src = wildGrass[0].url_image;\n spot1.value = wildGrass[0].pokemon;\n label1.append(img1);\n\n const img2 = document.querySelector('#img2');\n img2.src = wildGrass[1].url_image;\n spot2.value = wildGrass[1].pokemon;\n label2.append(img2);\n\n const img3 = document.querySelector('#img3');\n img3.src = wildGrass[2].url_image;\n spot3.value = wildGrass[2].pokemon;\n label3.append(img3);\n}", "function matchHouses(step) {\n if (step === 0){\n return 0;\n } else {\n return (5 * step) + 1\n }\n}", "generateSites() {\n let sampler = poissonDiscSampler( 800, 800, 150 );\n\n let sample;\n\n while( (sample = sampler()) ) {\n let x = Math.floor( sample[0] );\n let y = Math.floor( sample[1] );\n\n if( x < 50 || x > 750 ) {\n continue;\n }\n else if( y < 50 || y > 750 ) {\n continue;\n }\n else {\n this.sites.push( [x, y] );\n }\n };\n }", "function getGramsFromOunces(ounces) {\nreturn ounces * 28.3495;\n}", "function getMinesAround() {\n\n for (let i = 0; i < tiles.length; i++) {\n let minesAround = 0;\n \n if (tiles[i].classList.contains('empty')) {\n\n // North\n if (i > 9 && tiles[N(i)].classList.contains('mine')) {\n minesAround++;\n }\n \n // North-East\n if (i > 9 && !isRightEdge(i) && tiles[NE(i)].classList.contains('mine') ) {\n minesAround++;\n }\n \n // East \n if (i > -1 && !isRightEdge(i) && tiles[E(i)].classList.contains('mine')) {\n minesAround++;\n }\n\n // South-East\n if (i < 89 && !isRightEdge(i) && tiles[SE(i)].classList.contains('mine') ) {\n minesAround++;\n }\n\n // South\n if (i < 90 && tiles[S(i)].classList.contains('mine')) {\n minesAround++;\n }\n\n // South-West\n if (i < 90 && !isLeftEdge(i) && tiles[SW(i)].classList.contains('mine')) {\n minesAround++;\n }\n\n // West\n if (i > 0 && !isLeftEdge(i) && tiles[W(i)].classList.contains('mine')) {\n minesAround++;\n }\n\n // North-West\n if (i > 10 && !isLeftEdge(i) && tiles[NW(i)].classList.contains('mine')) {\n minesAround++;\n }\n\n tiles[i].setAttribute('mines', minesAround);\n }\n }\n}", "function Spot(i, j) {\n\tthis.i = i;\n\tthis.j = j;\n\tthis.f = 0;\n\tthis.g = 0;\n\tthis.h = 0;\n\tthis.neighbors = [];\n\tthis.previous = undefined;\n\tthis.wall = false;\n\n\t// Randomly make certain spots walls\n\tif (random(1) < 0.3) {\n\t\tthis.wall = true;\n\t}\n\n\tthis.show = function(cols) {\n\t\tif (this.wall) {\n\t\t\tfill(0);\n\t\t\tnoStroke();\n\t\t\tellipse(this.i * w + w / 2, this.j * h + h / 2, w / 2, h / 2);\n\t\t}\n\t}\n\n\tthis.addNeighbors = function(grid) {\n\t\tvar i = this.i;\n\t\tvar j = this.j;\n\n\t\tif (i < cols - 1) {\n\t\t\tthis.neighbors.push(grid[i + 1][j]);\n\t\t}\n\t\tif (i > 0) {\n\t\t\tthis.neighbors.push(grid[i - 1][j]);\n\t\t}\n\t\tif (j < rows - 1) {\n\t\t\tthis.neighbors.push(grid[i][j + 1]);\n\t\t}\n\t\tif (j > 0) {\n\t\t\tthis.neighbors.push(grid[i][j - 1]);\n\t\t}\n\t\tif (i > 0 && j > 0) {\n\t\t\tthis.neighbors.push(grid[i - 1][j - 1]);\n\t\t}\n\t\tif (i < cols - 1 && j > 0) {\n\t\t\tthis.neighbors.push(grid[i + 1][j - 1]);\n\t\t}\n\t\tif (i > 0 && j < rows - 1) {\n\t\t\tthis.neighbors.push(grid[i - 1][j + 1]);\n\t\t}\n\t\tif (i < cols - 1 && j < rows - 1) {\n\t\t\tthis.neighbors.push(grid[i + 1][j + 1]);\n\t\t}\n\t}\n}", "get pointsToApply() {\n let pointsToApply = this.unmodifiedPointsToApply\n if (this._parent.useLocationModifiers) {\n if ([hitlocation.EXTREMITY, hitlocation.LIMB].includes(this._parent.hitLocationRole)) {\n return Math.min(pointsToApply, Math.floor(this._parent.locationMaxHP))\n }\n }\n return pointsToApply\n }", "function setupGridSpots() {\r\n /*Direction spots*/\r\n right = [32, 24, 17];\r\n up = [39, 30];\r\n left = [7, 14];\r\n down = [0, 9];\r\n \r\n /*End spot*/\r\n end = [21];\r\n \r\n /*Card spots*/\r\n card = [2, 6, 22, 23, 28, 34, 38];\r\n \r\n /*Trap Spots*/\r\n trap = [1, 3, 8, 10, 13, 15, 26, 27, 36];\r\n \r\n /*Fill grid*/\r\n fillGrid(\"right\", right);\r\n fillGrid(\"up\", up);\r\n fillGrid(\"left\", left);\r\n fillGrid(\"down\", down);\r\n \r\n fillGrid(\"end\", end);\r\n \r\n fillGrid(\"card\", card);\r\n \r\n fillGrid(\"trap\", trap);\r\n}", "function makeGraves() {\n for (i=0;i<smallGravePositionsBack.length;i++) {\n smallGraves.push({posX:(smallGravePositionsBack[i]),posY:360,sizeX:53,sizeY:15});\n }\n for (i=0;i<smallGravePositionsFront.length;i++) {\n smallGraves.push({posX:(smallGravePositionsFront[i]),posY:470,sizeX:53,sizeY:15});\n }\n}", "function gameStart() {\n matchNumber = Math.floor((Math.random() * (120 - 19 + 1) + 19));\n $(\".matchNumber\").html(matchNumber);\n \n gem1 = (Math.ceil(Math.random() * 12));\n // console.log('GameStart Gem1: ' + gem1);\n gem2 = (Math.ceil(Math.random() * 12));\n gem3 = (Math.ceil(Math.random() * 12));\n gem4 = (Math.ceil(Math.random() * 12));\n\n Total = 0;\n $(\".guessTotal\").html(Total);\n }", "generateStartingPositions() {\n\t\tlet array = [];\n\t\tlet manhattanPositions = [6, 13, 66, 91, 207, 289, 352];\n\t\tlet londonPositions = [11, 48, 57, 108, 167, 330, 390];\n\t\tlet seoulPositions = [12, 17, 32, 42, 89, 134, 174, 294, 316];\n\t\tif (this.game.cityName === \"Manhattan\") {\n\t\t\tlet r = Math.floor((Math.random() * 7));\n\t\t\tarray.push(manhattanPositions[r]);\n\t\t\t// r = Math.floor((Math.random() * 3) + 4);\n\t\t\t// array.push(manhattanPositions[r]);\n\t\t}\n\t\telse if (this.game.cityName === \"London\") {\n\t\t\tlet r = Math.floor((Math.random() * 7));\n\t\t\tarray.push(londonPositions[r]);\n\t\t\t// r = Math.floor((Math.random() * 3) + 4);\n\t\t\t// array.push(londonPositions[r]);\n\t\t}\n\t\telse {\n\t\t\tlet r = Math.floor((Math.random() * 9));\n\t\t\tarray.push(seoulPositions[r]);\n\t\t\t// r = Math.floor((Math.random() * 4) + 5);\n\t\t\t// array.push(seoulPositions[r]);\n\t\t}\n\t\treturn array;\n\t}", "function onePairPoints() {\n let oneP = frequency();\n var point = 0;\n for (let i = 0; i < 7; i++) {\n if (oneP[i] >= 2) {\n point = i * 2;\n }\n }\n return point;\n}", "function totalCells(){\n return GRID.length * GRID[0].length;\n}", "getCenterOfPalm (results) {\n results.multiHandLandmarks.forEach((hand, n) => {\n let x = 0\n let y = 0\n \n this.palmPoints.forEach(i => {\n x += hand[i].x\n y += hand[i].y\n })\n\n x /= this.palmPoints.length\n y /= this.palmPoints.length\n \n results.multiHandLandmarks[n][21] = {x, y}\n })\n \n return results\n }", "calcSlices(newActiveIndex) {\n const {frames} = this.state;\n const {rangeUp, rangeDown} = this.calcRangeUpAndDown(newActiveIndex);\n const up = frames.slice(newActiveIndex - rangeUp, newActiveIndex);\n const down = frames.slice(newActiveIndex, newActiveIndex + rangeDown);\n return {up, down};\n }", "generatePoints() {\n this.points = [];\n this.currPointY = [];\n var i;\n var min = 0.1;\n var max = 0.98;\n for(i = 0; i < this.numPoints; i++ ){\n this.points[i] = Math.random() * (max - min) + min;\n this.currPointY[i] = 0;\n }\n this.poi = -1; //reset\n }", "function genChkptLocations(){\n for(let i=1; i<20; i++){\n let newX=Math.random()*480+160, newY = Math.random()*479;\n let prevChkpt = chkpt.locations[i-1];\n while( newX<160 || newY<1 ||\n newX>592 || newY>432 ||\n distance([newX, newY], [prevChkpt[0], prevChkpt[1]]) < 125){\n newX = Math.random()*479+160;\n newY = Math.random()*479;\n }\n chkpt.locations.push([newX, newY]);\n }\n}", "function declareMaterialDotTotals() {\n\n totalWoodDots = 0\n totalOreDots = 0\n totalWheatDots = 0\n totalSheepDots = 0\n totalBrickDots = 0\n\n for (i = 0; i < tilesList.length; i++) {\n var currentDot = getDots(tilesList[i].value)\n\n if (tilesList[i].mat == 0) {\n totalBrickDots += currentDot\n }\n else if (tilesList[i].mat == 1) {\n totalWoodDots += currentDot\n }\n else if (tilesList[i].mat == 2) {\n totalOreDots += currentDot\n }\n else if (tilesList[i].mat == 3) {\n totalSheepDots += currentDot\n }\n else if (tilesList[i].mat == 4) {\n totalWheatDots += currentDot\n }\n else if (tilesList[i].mat == 5) {\n totalWheatDots += currentDot\n }\n\n }\n\n}", "function nextGeneration() {\n generation += 1;\n calculateFitness();\n\n for (let i = pop_total / 2; i < pop_total; i++) {\n boards[i] = pickOne();\n }\n\n for(let i = 0; i < pop_total / 2; i++){\n boards[i] = pickMax();\n }\n \n for(let i = 0; i < pop_total; i++){\n saveBoards[i].dispose();\n }\n\n saveBoards = [];\n}", "function thinkInSolutions(){\r\n let targetElement = document.getElementById(\"max\");\r\n \r\n if (targetElement && targetElement.value) {\r\n let population = new Population(collection.length, collection.length * 4);\r\n population.calcFitness(collection);\r\n population.evaluate(parseInt(targetElement.value, 10));\r\n\r\n\r\n for (let i = 0; i < collection.length * 4; i++) { \r\n population.createNextGeneration(20, collection);\r\n population.calcFitness(collection);\r\n population.evaluate(parseInt(targetElement.value, 10));\r\n }\r\n\r\n let bestOnes = population.getBestSolutions();\r\n\r\n \r\n // A moment for verfication. To see all solutions generated.\r\n // This moment only one solution is shown visible (by the yellow color).\r\n // Logs all found solutions in console. \r\n bestOnes.forEach(lid => {\r\n let collectedItems = [];\r\n for (let i = 0; i < lid.length; i++) {\r\n if (lid[i] == \"1\") {\r\n collectedItems.push(collection[i]);\r\n }\r\n }\r\n console.log(collectedItems);\r\n });\r\n console.log(\"-----\");\r\n\r\n let blocks = document.getElementsByClassName(\"block\");\r\n\r\n // Clear the yellow ones.\r\n for (let i = 0; i < blocks.length; i++) {\r\n blocks[i].style.backgroundColor = \"white\";;\r\n }\r\n\r\n // Paint the blocks containing a part of the solutions yellow.\r\n if (bestOnes.length > 0) {\r\n for (let i = 0; i < bestOnes[0].length; i++) {\r\n if (bestOnes[0][i] == \"1\") {\r\n blocks[i].style.backgroundColor = \"yellow\";\r\n }\r\n }\r\n } else {\r\n console.log(\"No solutions available!\");\r\n }\r\n } else {\r\n alert(\"Please, insert a max value! (Yes, it is necessary).\");\r\n }\r\n }", "function bestStepForSpot(col, row){\r\n\tvar cur_pos = [col, row];\r\n\tvar j = 0;\r\n\tvar pos = [];\r\n\tvar max_s = 0;\r\n\tvar s_n = 0; \r\n\tvar d_pos = [];\r\n\tfor (j = 0; j<POSSIBLE_MOVING.length; j++){\r\n\t\tpos = [cur_pos[0] + POSSIBLE_MOVING[j][0], cur_pos[1] + POSSIBLE_MOVING[j][1]]; \r\n\t\tif (outOfRange(pos[0], pos[1])) continue;\r\n\t\tif (game_field[pos[1]][pos[0]] == EMPTY){\r\n\t\t\ts_n = getScoreAfterStep(cur_pos, pos);\r\n\t\t\tif (s_n > max_s){\r\n\t\t\t\tmax_s = s_n;\r\n\t\t\t\td_pos = [POSSIBLE_MOVING[j][0], POSSIBLE_MOVING[j][1]];\r\n\t\t\t}\r\n\t\t}\t\r\n\t}\r\n\treturn [d_pos, max_s];\r\n}", "function gratulation() {\n modalFadeIn(\"modal-congrat\");\n\n // build timestring of minutes (if there are) and seconds\n var timeContent = \"\";\n\n if (diffMin >= 1) {\n timeContent = diffMin + \" minutes and \";\n }\n timeContent += diffSec + \" seconds.\";\n\n // set in gratulation modal count of moves and timestring\n modalMoves.innerText = cardClickCounter;\n modalTime.innerText = timeContent;\n modalRating.innerText = showCardRating.innerText.length;\n // fill object for pushing to existing localstorage\n\n var newData = {\n fieldSize: fieldSize,\n moves: cardClickCounter,\n time: timeContent,\n rating: showCardRating.innerText\n };\n\n pushToLocalStorage(newData);\n addHitlistToDom();\n }" ]
[ "0.6100598", "0.5917473", "0.58087283", "0.56898344", "0.5644776", "0.55656415", "0.5550244", "0.5521783", "0.5499635", "0.5464474", "0.5455299", "0.5452318", "0.54485893", "0.54313743", "0.54271334", "0.5425528", "0.54246885", "0.542121", "0.54153574", "0.54109335", "0.5405729", "0.5402969", "0.54002076", "0.53985727", "0.53727037", "0.53727037", "0.53628784", "0.5352094", "0.5343377", "0.5334653", "0.53323823", "0.53234833", "0.53147614", "0.53137505", "0.5299298", "0.52957195", "0.5286627", "0.5284849", "0.52642566", "0.52563626", "0.5227032", "0.52269214", "0.5217496", "0.52170694", "0.5216418", "0.52154446", "0.5213915", "0.5207685", "0.5182758", "0.5181912", "0.518123", "0.5181132", "0.5178996", "0.51654357", "0.5161727", "0.51609963", "0.5155391", "0.51539063", "0.5144771", "0.5144199", "0.5143611", "0.51334924", "0.51240414", "0.51201797", "0.51201296", "0.5120093", "0.5107505", "0.51046604", "0.509246", "0.50908625", "0.5090066", "0.5086695", "0.5080756", "0.5076257", "0.50720465", "0.50659996", "0.50654286", "0.50643814", "0.5061986", "0.50546527", "0.50479084", "0.5045613", "0.5041889", "0.5038715", "0.5033399", "0.50329137", "0.50258505", "0.5023625", "0.5022656", "0.50220585", "0.5021638", "0.50190914", "0.50189286", "0.5018372", "0.501569", "0.5013875", "0.5003952", "0.5002193", "0.5001257", "0.49974814" ]
0.6461824
0
This function calculates the spots that Population 2 takes up
function calculatePop2(){ let area = (dims.value)*(dims.value); let pop2 = area-(calculateV()+calculatePop1()); return Math.floor(pop2); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function resolveHalfSpotting(stack1, stack2, who)\n{\n var spot = stack1.getSpotting();\n console.log(['spotting',spot]);\n stack2.ambush = false;\n for(var i=0; i<stack2.slots.length; i++)\n { var r = rnd(6);\n console.log([r,spot,stack2.slots[i].unit.camo,r+spot-stack2.slots[i].unit.camo]);\n if(r+spot-stack2.slots[i].unit.camo < 3)\n { stack2.slots[i].ambush = true;\n stack2.ambush = true;\n }\n else stack2.slots[i].ambush = false;\n }\n if(stack2.ambush)\n { logEvent(\"hidden\",null,null,who);\n for(var i=0; i<stack2.slots.length; i++)\n { if(stack2.slots[i].ambush) \n { console.log(stack2.slots[i].unit);\n logEvent(\"ambush\",stack2.slots[i].unit);\n }\n }\n \n }\n}", "function markOccupiedSpots() {\n \n\t\tif(!spotsInitialized || playersInitialized < 2) {\n \n\t\t\treturn null;\n \n } // end if statement\n\t\n\t\tfor(var i = 0; i<10; i++) {\n \n\t\t\tfindClosestSpot(myMarbles[i].x, myMarbles[i].y).isEmpty = false;\n\t\t\tfindClosestSpot(othersMarbles[i].x, othersMarbles[i].y).isEmpty = false;\n \n\t\t} // end for loop\n \n\t} // end markOccupiedSpots()", "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}", "findUpgradeSpots() {\n if (this.danger) { return []; }\n const controller = this.object('controller');\n\n const upgradeSpots = controller.room.lookAtArea(\n controller.pos.y - 3, controller.pos.x - 3,\n controller.pos.y + 3, controller.pos.x + 3, true\n ).filter((lookObj) => {\n return (\n lookObj.type === LOOK_TERRAIN &&\n lookObj[lookObj.type] !== 'wall'\n );\n }).map(lookObj => {\n return {x: lookObj.x, y: lookObj.y};\n });\n this.nbUpgradeSpots = upgradeSpots.length;\n\n return upgradeSpots;\n }", "winningPositions() {\n return [\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 }", "function calculatePop1(){\n let area = (dims.value)*(dims.value);\n area = area - calculateV();\n let pop1 = area*popRatio.value;\n return Math.floor(pop1);\n}", "function getOffsets(size) {\n //THIS FUNCTION IS SO UGLY IM SO SORRY\n let wO = (size * 1.732050808 / 2);\n let hO = size;\n let ans = [];\n\n let startingY = 50 - 2 * (hO * .75);\n let startingX = 50 - wO;\n\n for (let i = 0; i < 3; i++) {\n ans.push(`top:${startingY}%;left:${startingX + i * (wO)}%`)\n }\n\n startingY = 50 - 1 * (hO * .75);\n startingX = 50 - wO * (1.5);\n\n for (let i = 0; i < 4; i++) {\n ans.push(`top:${startingY}%;left:${startingX + i * (wO)}%`)\n }\n\n startingY = 50;\n startingX = 50 - wO * (2);\n\n for (let i = 0; i < 5; i++) {\n ans.push(`top:${startingY}%;left:${startingX + i * (wO)}%`)\n }\n\n\n\n startingY = 50 + 1 * (hO * .75);\n startingX = 50 - wO * (1.5);\n\n for (let i = 0; i < 4; i++) {\n ans.push(`top:${startingY}%;left:${startingX + i * (wO)}%`)\n }\n\n startingY = 50 + 2 * (hO * .75);\n startingX = 50 - wO;\n\n\n for (let i = 0; i < 3; i++) {\n ans.push(`top:${startingY}%;left:${startingX + i * (wO)}%`)\n }\n return ans;\n}", "DetermineBestSupportingPosition() {\n //only update the spots every few frames \n if ( !this.m_pRegulator.isReady() && this.m_pBestSupportingSpot != null ) {\n return this.m_pBestSupportingSpot.m_vPos;\n };\n\n //reset the best supporting spot\n this.m_pBestSupportingSpot = null;\n\n let BestScoreSoFar = 0.0;\n\n //let it = m_Spots.listIterator();\n\n //while ( it.hasNext() ) {\n // let curSpot = it.next();\n\n\n for( let it = 0, size = this.m_Spots.length; it < size; it++ ){\n\n let curSpot = this.m_Spots[ it ];\n\n //first remove any previous score. (the score is set to one so that\n //the viewer can see the positions of all the spots if he has the \n //aids turned on)\n curSpot.m_dScore = 1.0;\n\n //Test 1. is it possible to make a safe pass from the ball's position \n //to this position?\n if ( this.m_pTeam.isPassSafeFromAllOpponents( this.m_pTeam.ControllingPlayer().Pos(),\n curSpot.m_vPos,\n null,\n Prm.MaxPassingForce ) ) {\n curSpot.m_dScore += Prm.Spot_PassSafeScore;\n };\n\n\n //Test 2. Determine if a goal can be scored from this position. \n if ( this.m_pTeam.CanShoot( curSpot.m_vPos,\n Prm.MaxShootingForce ) ) {\n curSpot.m_dScore += Prm.Spot_CanScoreFromPositionScore;\n };\n\n\n //Test 3. calculate how far this spot is away from the controlling\n //player. The further away, the higher the score. Any distances further\n //away than OptimalDistance pixels do not receive a score.\n if ( this.m_pTeam.SupportingPlayer() != null ) {\n\n let OptimalDistance = 200.0;\n\n let dist = Vector2D.Vec2DDistance( this.m_pTeam.ControllingPlayer().Pos(),\n curSpot.m_vPos );\n\n let temp = Math.abs( OptimalDistance - dist );\n\n if ( temp < OptimalDistance ) {\n\n //normalize the distance and add it to the score\n curSpot.m_dScore += Prm.Spot_DistFromControllingPlayerScore\n * ( OptimalDistance - temp ) / OptimalDistance;\n };\n };\n\n //check to see if this spot has the highest score so far\n if ( curSpot.m_dScore > BestScoreSoFar ) {\n BestScoreSoFar = curSpot.m_dScore;\n\n this.m_pBestSupportingSpot = curSpot;\n };\n\n };\n\n return this.m_pBestSupportingSpot.m_vPos;\n }", "function twcheese_calculatePopulation(buildings,troopsDefending,troopsOutside)\n\t{\n\t\tvar buildingPopBases = new Array(1.17,1.17,1.17,1.17,1.55,1.55,1.17,1.17,1.17,1.17,1.17,1.155,1.14,1.17,1,1.15,1.17,1.17);\n\t\tvar buildingPopFactors = new Array(5,7,8,8,5,5000,80,20,0,10,20,5,10,10,0,0,2,5);\n\t\tvar troopPopulation = new Array(1,1,1,1,2,4,5,6,5,8,10,100);\t\t\n\t\t\n\t\tvar buildingPopulation = 0;\n\t\tvar militaryPopulation = 0;\n\t\tvar maxPopulation = Math.round(240 * Math.pow(1.172103,buildings[14]-1));\n\t\tfor(var i=0; i < 18; i++)\n\t\t{\n\t\t\tif(buildings[i] > 0)\n\t\t\t{\n\t\t\t\tbuildingPopulation += Math.round(buildingPopFactors[i] * Math.pow(buildingPopBases[i],(buildings[i] - 1)));\n\t\t\t}\n\t\t}\n\t\tfor(var i=0; i < 12; i++)\n\t\t{\n\t\t\tmilitaryPopulation += troopPopulation[i]*Number(troopsDefending[i]);\n\t\t\tif(troopsOutside)\n\t\t\t\tmilitaryPopulation += troopPopulation[i]*Number(troopsOutside[i]);\n\t\t}\t\t\n\t\treturn new Array(buildingPopulation,militaryPopulation,(maxPopulation - buildingPopulation - militaryPopulation));\t\n\t}", "function percentageOfWorld1(populations){\n return populations / 7900 * 100;\n }", "_getPartOfCount() {\n\n // 8-neighborhood around\n const n = [\n Point.val(this.x - 1, this.y - 1),\n Point.val(this.x - 1, this.y),\n Point.val(this.x - 1, this.y + 1),\n Point.val(this.x, this.y - 1),\n Point.val(this.x, this.y + 1),\n Point.val(this.x + 1, this.y - 1),\n Point.val(this.x + 1, this.y),\n Point.val(this.x + 1, this.y + 1),\n ];\n\n const edges = n.filter(p => p === '-' || p === '|').length;\n const ind = [];\n for (let i = 0; i < 8; i++) {\n if (n[i] === '-' || n[i] === '|') ind.push(i);\n }\n\n switch (edges) {\n\n case 2:\n switch (ind[0]) {\n case 1: \n return ind[1] === 3 ? (n[0] === n[7] ? 2 : 1) : (n[2] === n[5] ? 2 : 1);\n case 3: \n return n[2] === n[5] ? 2 : 1;\n case 4: \n return n[0] === n[7] ? 2 : 1;\n }\n\n case 3: \n return n.filter(p => p === ' ').length === 5 ? 3 : 2;\n\n case 4:\n return n.filter(p => p === ' ').length;\n }\n }", "function setBuildingSpots(){\n\tcurBuildingSpot = squareTiles[103];\n\tbuildingSpotArray = [squareTiles[90],squareTiles[25],squareTiles[53]];\n}", "function Spot(i, j, type)\n{\n\n // Location\n this.i = i;\n this.j = j;\n\n // f, g, and h values for A*\n this.f = 0;\n this.g = 0;\n this.h = 0;\n\n // Neighbors\n this.neighbors = [];\n\n // Spot Type\n this.type = type;\n\n // Figure out who my neighbors are\n this.addNeighbors = function(grid)\n {\n var i = this.i;\n var j = this.j;\n\n if (i < gridsize - 1) this.neighbors.push(grid[i + 1][j]);\n if (i > 0) this.neighbors.push(grid[i - 1][j]);\n if (j < gridsize - 1) this.neighbors.push(grid[i][j + 1]);\n if (j > 0) this.neighbors.push(grid[i][j - 1]);\n\n if (i > 0 && j > 0) this.neighbors.push(grid[i - 1][j - 1]);\n if (i < gridsize - 1 && j > 0) this.neighbors.push(grid[i + 1][j - 1]);\n if (i > 0 && j < gridsize - 1) this.neighbors.push(grid[i - 1][j + 1]);\n if (i < gridsize - 1 && j < gridsize - 1) this.neighbors.push(grid[i + 1][j + 1]);\n\n };\n\n}", "function Interpolation(gs1, gs2)\n{\n var s1 = stn(gs1);\n var s2 = stn(gs2);\n var i1 = [ s1[0], s1[1], s1[2], s1[3], s1[5], s1[6], s1[8], s1[9], s1[11], s1[12] ];\n var i2 = [], i3 = [], i4 = [], i5 = [], i6 = [], i7 = [], i8 = [], i9 = [], i10 = [];\n \n //ball positive on X\n if (s2[0] > s1[0])\n {\n i2.push(s1[0] + 1);\n i3.push(s1[0] + 2);\n i4.push(s1[0] + 3);\n i5.push(s1[0] + 4);\n }\n else\n {\n i2.push(s1[0] - 1);\n i3.push(s1[0] - 2);\n i4.push(s1[0] - 3);\n i5.push(s1[0] - 4);\n }\n \n //ball positive on Y\n if (s2[1] > s1[1])\n {\n \ti2.push(s1[1] + 1);\n \ti3.push(s1[1] + 2);\n \ti4.push(s1[1] + 3);\n \ti5.push(s1[1] + 4);\n }\n else\n {\n \ti2.push(s1[1] - 1);\n \ti3.push(s1[1] - 2);\n \ti4.push(s1[1] - 3);\n \ti5.push(s1[1] - 4);\n }\n \n for (var i = 0; i<4; ++i)\n {\n if (i == 0)\n var iX = 2; //2, 5, 8, 11\n else if (i == 1)\n var iX = 5;\n else if (i == 2)\n var iX = 8;\n else if (i == 3)\n var iX = 11;\n var iY = iX+1; //3, 6, 9, 12\n var xDelta = s2[iX] - s1[iX];\n var xAct = Math.floor(xDelta/5);\n var yDelta = s2[iY] - s2[iY];\n var yAct = Math.floor(yDelta/5);\n \n if (xDelta >= 0)\n {\n i2.push(s1[iX] + xAct);\n i3.push(s1[iX] + 2*xAct);\n i4.push(s1[iX] + 3*xAct);\n i5.push(s1[iX] + 4 * xAct);\n }\n else\n {\n \ti2.push(s1[iX] - xAct);\n \ti3.push(s1[iX] - 2 * xAct);\n \ti4.push(s1[iX] - 3 * xAct);\n \ti5.push(s1[iX] - 4 * xAct);\n }\n \n if (yDelta >= 0)\n {\n i2.push(s1[iY] + yAct);\n i3.push(s1[iY] + 2*yAct);\n i4.push(s1[iY] + 3*yAct);\n i5.push(s1[iY] + 4 * yAct);\n }\n else\n {\n \ti2.push(s1[iY] - yAct);\n \ti3.push(s1[iY] - 2 * yAct);\n \ti4.push(s1[iY] - 3 * yAct);\n \ti5.push(s1[iY] - 4 * yAct);\n }\n }\n \n var i11 = [ s2[0], s2[1], s2[2], s2[3], s2[5], s2[6], s2[8], s2[9], s2[11], s2[12] ];\n \n var result = new Array();\n result.push(i1);\n result.push(i2);\n result.push(i3);\n result.push(i4);\n result.push(i5);\n result.push(i11);\n \n return result;\n}", "function bestSpot(){\n//return an empty square (a random square for now)\nreturn emptySquares()[Math.floor(Math.random()*emptySquares().length)];\n}", "function yPOSnon(yAve, minW, maxW, arrLENGT, gaps){\n\tvar bottomY = [];\n\tvar topY = [];\n\n\tvar whiteoutPOS = [];\n\tvar whiteoutPOS2 = [];\n\n\tvar max = maxW/2\n\tvar min = minW/2\n\n\tfor (i = 0; i < arrLENGT; i++) {\n\t\tvar rand_top = Math.random() * (max - min) + min\n\t\tvar rounded_tenth_top = Math.floor(10*rand_top)/10\n\t\tvar rand_bottom = Math.random() * (max - min) + min\n\t\tvar rounded_tenth_bottom = Math.floor(10*rand_bottom)/10\n\n\t\tbottomY.push(yAve - rounded_tenth_bottom);\n\t\ttopY.push(yAve + rounded_tenth_top);\n\t};\n\n\tvar half_gaps = gaps/2\n\n // SEARCHING FOR THINNEST SPOTS TO DO WHITEOUT POLYGON\n\tfor (i = 0; i < arrLENGT; i++) {\n\t\tif (bottomY[i] >= yAve - half_gaps && topY[i] <= yAve + half_gaps) {\n\t\t\twhiteoutPOS = whiteoutPOS.concat(i);\n\t\t\twhiteoutPOS2 = whiteoutPOS2.concat(bottomY[i] + \" \" + topY[i])\n\t\t}\n\t}\n\n\tallY = topY.concat(bottomY.reverse());\n\n\t// console.log(\"whiteout array \" + whiteoutPOS)\n\t// console.log(\"POS2 \" + whiteoutPOS2)\n\n\tpotentialGAPS = []\n\tnumPOLYGONS = 0\n\n\tfor (i=0; i<= whiteoutPOS.length; i++) { \n\t\tif(whiteoutPOS[i-1] == whiteoutPOS[i]-1){\n\t\t\t// console.log(\"check out spots \" + (i-1) + \" and \" + i)\n\t\t\tpotentialGAPS.push(whiteoutPOS[i-1])\n\t\t\t// console.log(\"potentialGAPS variable ... REAL GAPS start #s \" + potentialGAPS)\n\t\t\tnumPOLYGONS = numPOLYGONS + 1\n\t\t}\n\t}\n\t// console.log(\"num of polygons in line \" + numPOLYGONS)\n\t// console.log(\"length of allY \" + allY.length)\n\t// console.log(\" zero pos of allY \" + allY[0])\n\t// console.log(\" one pos of allY \" + allY[1])\n\t// console.log(\" end pos of allY \" + allY.slice(-1)[0])\n\t// console.log(\" second last pos of allY \" + allY.slice(-2)[0])\n\n\t//NOTE - last half is TOP coordinates\n\t//final point can be ignored to give line a tapering effect\n\t// see comboXY function\n\n\t//return allY\n}", "function squaresNeeded(grains){\n return Math.ceil(Math.log2(grains+1))\n}", "getCurrentSquares() {\n\t\treturn this.state.history[this.state.stepNumber].squares;\n\t}", "produceOffspring() {\n this.childPop = [];\n \n for (let i = 0; i < this.parentPop.length; i++) {\n let parent1 = random(this.matingPool);\n let parent2 = random(this.matingPool);\n let child;\n \n switch (crossoverChoice) {\n case 0:\n child = crossover.singlePoint(parent1, parent2);\n break;\n case 1:\n child = crossover.uniform(parent1, parent2);\n break;\n case 2:\n child = crossover.average(parent1, parent2);\n }\n \n switch (mutationChoice) {\n case 0:\n mutation.randomFlip(child);\n break;\n case 1:\n mutation.addVal(child);\n }\n \n child.calFitness(fitnessChoice);\n this.childPop[i] = child;\n }\n }", "function getBucketSpots(bucketNum, x0, y0, width, height, elementW, elementH){\n var bucketSpots = {};\n var x,y;\n var spacing = (height/bucketNum)-elementH;\n for (var i = 0; i < bucketNum; i++) {\n var y = y0 + i*(elementH + spacing);\n bucketSpots[String(i)] = [x0,y,elementW,elementH,[]];\n }\n\n console.log(bucketSpots);\n return bucketSpots;\n}", "function availableSpots(arr, num) {\n\n var arrOddEven = []\n for (let i=0; i<arr.length; i++){\n if (arr[i]%2 === 1){\n arrOddEven.push(\"odd\")\n }\n else {\n arrOddEven.push(\"even\")\n }\n }\n\n let numberSpots = 0\n\tif (num %2 === 1) {\n // odd\n for (let i=0; i<arrOddEven.length -1; i++){\n if (arrOddEven[i] === \"odd\" || arrOddEven[i +1] === \"odd\"){\n numberSpots += 1\n }\n }\n\n }\n else {\n for (let i=0 ; i<arrOddEven.length -1; i ++){\n if (arrOddEven[i] !== \"odd\" || arrOddEven[i +1] !== \"odd\")\n numberSpots += 1\n }\n\n }\n return numberSpots\n}", "DetermineBestSupportingPosition()\n {\n //only update the spots every few frames\n if (!this.m_pRegulator.isReady() && this.m_pBestSupportingSpot)\n {\n return new Phaser.Point(this.m_pBestSupportingSpot.m_vPos.x, this.m_pBestSupportingSpot.m_vPos.y);\n }\n\n //reset the best supporting spot\n this.m_pBestSupportingSpot = null;\n\n var BestScoreSoFar = 0.0;\n\n for (var curSpot = 0; curSpot < this.m_Spots.length; ++curSpot)\n {\n //first remove any previous score. (the score is set to one so that\n //the viewer can see the positions of all the spots if he has the\n //aids turned on)\n this.m_Spots[curSpot].m_dScore = 1.0;\n\n //Test 1. is it possible to make a safe pass from the ball's position\n //to this position?\n if (this.m_pTeam.isPassSafeFromAllOpponents(this.m_pTeam.ControllingPlayer().Pos(),\n this.m_Spots[curSpot].m_vPos,\n null,\n Params.MaxPassingForce))\n {\n this.m_Spots[curSpot].m_dScore += Params.Spot_PassSafeScore;\n }\n\n\n //Test 2. Determine if a goal can be scored from this position.\n var ret_canshoot = this.m_pTeam.CanShoot(this.m_Spots[curSpot].m_vPos,\n Params.MaxShootingForce);\n if (ret_canshoot[0])\n {\n this.m_Spots[curSpot].m_dScore += Params.Spot_CanScoreFromPositionScore;\n }\n\n\n //Test 3. calculate how far this spot is away from the controlling\n //player. The further away, the higher the score. Any distances further\n //away than OptimalDistance pixels do not receive a score.\n if (this.m_pTeam.SupportingPlayer())\n {\n var OptimalDistance = 200.0;\n\n var dist = this.m_pTeam.ControllingPlayer().Pos().distance(this.m_Spots[curSpot].m_vPos);\n\n var temp = Math.abs(OptimalDistance - dist);\n\n if (temp < OptimalDistance)\n {\n\n //normalize the distance and add it to the score\n this.m_Spots[curSpot].m_dScore += Params.Spot_DistFromControllingPlayerScore *\n (OptimalDistance - temp) / OptimalDistance;\n }\n }\n\n //check to see if this spot has the highest score so far\n if (this.m_Spots[curSpot].m_dScore > BestScoreSoFar)\n {\n BestScoreSoFar = this.m_Spots[curSpot].m_dScore;\n\n this.m_pBestSupportingSpot = this.m_Spots[curSpot];\n }\n\n }\n\n return new Phaser.Point(this.m_pBestSupportingSpot.m_vPos.x, this.m_pBestSupportingSpot.m_vPos.y);\n }", "genNextSpot() {\r\n let countFreeSpaces = this.gameState.board.filter((i) => i === 0).length;\r\n if (countFreeSpaces === 0) {\r\n this.checkLose();\r\n } else {\r\n let locationToAdd = Math.floor(Math.random() * Math.floor(countFreeSpaces));\r\n let numEmptyTraversed = 0;\r\n for (let i = 0; i < this.gameState.board.length; i++) {\r\n if (this.gameState.board[i] === 0) {\r\n if (numEmptyTraversed === locationToAdd) {\r\n this.gameState.board[i] = this.gen2or4();\r\n break;\r\n } else {\r\n numEmptyTraversed++;\r\n }\r\n }\r\n }\r\n } \r\n }", "function pairingTwoSideScoreBoard_Top_Bot(RoundName){\n var remainingPairings=TEAM_NUMBER;\n var currentRow=0;\n var scoreBoardSheet = ss.getSheetByName(SHEET_SCOREBOARD);\n var range = scoreBoardSheet.getRange(4, 1, TEAM_NUMBER,6);\n var dataGrid = range.getValues();//Data sorted\n var bracketSize;\n var rand;\n var properOpponent;\n var govIndex=0;\n var newGov = [];\n var newOpp = [];\n var itr=TEAM_NUMBER*40;\n var values;\n while(remainingPairings>0){\n bracketSize=obtainBracketSize(dataGrid,currentRow);\n values=scoreBoardSheet.getRange(currentRow+4, 2, bracketSize).getValues();\n var internalBracketProgression=0;\n var teamname_top,teamname_bottom;\n while(values.length>0){\n teamname_top=values[0];\n teamname_bottom=values[values.length/2];\n newGov.push(teamname_top);\n newOpp.push(teamname_bottom);\n values.splice(values.indexOf(teamname_top),1);\n values.splice(values.indexOf(teamname_bottom),1);\n //internalBracketProgression++;\n }\n currentRow=currentRow+bracketSize;\n remainingPairings=remainingPairings-bracketSize; \n }\n control2Sides(dataGrid,newGov,newOpp);\n var pairingNumber=TEAM_NUMBER/SIDES_PER_ROUND; \n var randomised_order=createArray(pairingNumber,2);\n for(var i = 0;i<pairingNumber;i++){\n randomised_order[i][0]=String(newGov[i]);\n randomised_order[i][1]=String(newOpp[i]);\n }\n shuffleArray(randomised_order);//Randomise for display in random order for pairings to prevent rankings positions\n ss.getSheetByName(RoundName).getRange(3, 2,randomised_order.length,2).setValues(randomised_order);\n \n \n}", "function goldStars(points) {}", "function histTable(slvGames){\n var hitArr = []\n var hitArrOpp = []\n var arr = opponentInfo(slvGames)\n slvGames.gamePlayer.forEach(elem => {\n let user = document.getElementById(\"player\")\n let opponent = document.getElementById(\"opponent\")\n if(elem.gp_id == myParam){\n user.innerHTML = elem.player.name + \" \"\n }\n else if(elem.gp_id != myParam){\n opponent.innerHTML = elem.player.name\n }\n })\n arr.forEach(el => {\n if(el.gp_id == myParam){\n let x = document.getElementById(\"O\" + el.ship)\n x.innerHTML = el.ship\n hitArrOpp.push(el.ship)\n } else if(el.gp_id != myParam){\n let y = document.getElementById(el.ship)\n y.innerHTML = el.ship\n hitArr.push(el.ship)\n }\n })\n\n// set hits on my ships\n var hitOnSub = 0;\n var hitOnPT = 0;\n var hitOnCar = 0;\n var hitOnDes = 0;\n var hitOnBat = 0;\n for(var i=0;i<hitArr.length;i++){\n if(hitArr[i] === \"Submarine\"){\n hitOnSub++;\n if(hitOnSub == 3){\n let p = document.getElementById(\"sSub\")\n p.innerHTML = \"Submarine\"\n p.style.color = \"red\"\n }\n } else if(hitArr[i] === \"Patrol Boat\"){\n hitOnPT++;\n if(hitOnPT == 2){\n let p = document.getElementById(\"sPat\")\n p.innerHTML = \"Patrol Boat\"\n p.style.color = \"red\"\n }\n } else if(hitArr[i] === \"Carrier\"){\n hitOnCar++;\n if(hitOnCar == 5){\n let p = document.getElementById(\"sCar\")\n p.innerHTML = \"Carrier\"\n p.style.color = \"red\"\n }\n } else if(hitArr[i] === \"Battleship\"){\n hitOnBat++;\n if(hitOnBat == 4){\n let p = document.getElementById(\"sBat\")\n p.innerHTML = \"Battleship\"\n p.style.color = \"red\"\n }\n } else if(hitArr[i] === \"Destroyer\"){\n hitOnDes++;\n if(hitOnDes == 3){\n let p = document.getElementById(\"sDes\")\n p.innerHTML = \"Destroyer\"\n p.style.color = \"red\"\n }\n }\n }\n\n// set hits on Opponent ships\n var hitOnOSub = 0;\n var hitOnOPT = 0;\n var hitOnOCar = 0;\n var hitOnODes = 0;\n var hitOnOBat = 0;\n for(var i=0;i<hitArrOpp.length;i++){\n if(hitArrOpp[i] === \"Submarine\"){\n hitOnOSub++;\n if(hitOnOSub == 3){\n let p = document.getElementById(\"osSub\")\n p.innerHTML = \"Submarine\"\n p.style.color = \"red\"\n }\n } else if(hitArrOpp[i] === \"Patrol Boat\"){\n hitOnOPT++;\n if(hitOnOPT == 2){\n let p = document.getElementById(\"osPat\")\n p.innerHTML = \"Patrol Boat\"\n p.style.color = \"red\"\n }\n } else if(hitArrOpp[i] === \"Carrier\"){\n hitOnOCar++;\n if(hitOnOCar == 3){\n let p = document.getElementById(\"osCar\")\n p.innerHTML = \"Carrier\"\n p.style.color = \"red\"\n }\n } else if(hitArrOpp[i] === \"Battleship\"){\n hitOnOBat++;\n if(hitOnOBat == 3){\n let p = document.getElementById(\"osBat\")\n p.innerHTML = \"Battleship\"\n p.style.color = \"red\"\n }\n } else if(hitArrOpp[i] === \"Destroyer\"){\n hitOnODes++;\n if(hitOnODes == 3){\n let p = document.getElementById(\"osDes\")\n p.innerHTML = \"Destroyer\"\n p.style.color = \"red\"\n }\n }\n }\n\n// set my ships display\n slvGames.ships.forEach(ship => {\n let Pt = document.getElementById(\"patrol boat-hit\")\n let Cr = document.getElementById(\"carrier-hit\")\n let Sb = document.getElementById(\"submarine-hit\")\n let Dt = document.getElementById(\"destroyer-hit\")\n let Bt = document.getElementById(\"battleship-hit\")\n if(ship.type == \"Carrier\" && hitOnCar > 0){\n document.getElementById(\"carrier-hit\").style.marginBottom = '10px'\n ship.ships_locations.forEach(el => {\n let div = document.createElement(\"div\")\n div.setAttribute(\"id\", \"h\" + el)\n div.setAttribute(\"class\", \"col-1\")\n div.innerHTML = el\n Cr.appendChild(div)\n })\n } else if(ship.type == \"Battleship\" && hitOnBat != 0){\n document.getElementById(\"battleship-hit\").style.marginBottom = '10px'\n ship.ships_locations.forEach(el => {\n let div = document.createElement(\"div\")\n div.setAttribute(\"id\", \"h\" + el)\n div.setAttribute(\"class\", \"col-1\")\n div.innerHTML = el\n Bt.appendChild(div)\n })\n } else if(ship.type == \"Submarine\" && hitOnSub != 0){\n document.getElementById(\"submarine-hit\").style.marginBottom = '10px'\n ship.ships_locations.forEach(el => {\n let div = document.createElement(\"div\")\n div.setAttribute(\"id\", \"h\" + el)\n div.setAttribute(\"class\", \"col-1\")\n div.innerHTML = el\n Sb.appendChild(div)\n })\n } else if(ship.type == \"Patrol Boat\" && hitOnPT != 0){\n document.getElementById(\"patrol boat-hit\").style.marginBottom = '10px'\n ship.ships_locations.forEach(el => {\n let div = document.createElement(\"div\")\n div.setAttribute(\"id\", \"h\" + el)\n div.setAttribute(\"class\", \"col-1\")\n div.innerHTML = el\n Pt.appendChild(div)\n })\n } else if(ship.type == \"Destroyer\" && hitOnDes != 0){\n document.getElementById(\"destroyer-hit\").style.marginBottom = '10px'\n ship.ships_locations.forEach(el => {\n let div = document.createElement(\"div\")\n div.setAttribute(\"id\", \"h\" + el)\n div.setAttribute(\"class\", \"col-1\")\n div.innerHTML = el\n Dt.appendChild(div)\n })\n }\n })\n // set my Opponents ships display\n slvGames.ships.forEach(ship => {\n let Pt = document.getElementById(\"Opatrol boat-hit\")\n let Cr = document.getElementById(\"Ocarrier-hit\")\n let Sb = document.getElementById(\"Osubmarine-hit\")\n let Dt = document.getElementById(\"Odestroyer-hit\")\n let Bt = document.getElementById(\"Obattleship-hit\")\n if(ship.type == \"Carrier\" && hitOnOCar > 0){\n document.getElementById(\"Ocarrier-hit\").style.marginBottom = '10px'\n ship.ships_locations.forEach(el => {\n let div = document.createElement(\"div\")\n div.setAttribute(\"id\", \"ocar\" + ship.ships_locations.indexOf(el))\n div.setAttribute(\"class\", \"col-1\")\n div.innerHTML = el\n Cr.appendChild(div)\n })\n } else if(ship.type == \"Battleship\" && hitOnOBat != 0){\n document.getElementById(\"Obattleship-hit\").style.marginBottom = '10px'\n ship.ships_locations.forEach(el => {\n let div = document.createElement(\"div\")\n div.setAttribute(\"id\", \"obat\" + ship.ships_locations.indexOf(el))\n div.setAttribute(\"class\", \"col-1\")\n div.innerHTML = el\n Bt.appendChild(div)\n })\n } else if(ship.type == \"Submarine\" && hitOnOSub != 0){\n document.getElementById(\"Osubmarine-hit\").style.marginBottom = '10px'\n ship.ships_locations.forEach(el => {\n let div = document.createElement(\"div\")\n div.setAttribute(\"id\", \"osub\" + ship.ships_locations.indexOf(el))\n div.setAttribute(\"class\", \"col-1\")\n div.innerHTML = el\n Sb.appendChild(div)\n })\n } else if(ship.type == \"Patrol Boat\" && hitOnOPT != 0){\n document.getElementById(\"Opatrol boat-hit\").style.marginBottom = '10px'\n ship.ships_locations.forEach(el => {\n let div = document.createElement(\"div\")\n div.setAttribute(\"id\", \"opat\" + ship.ships_locations.indexOf(el))\n div.setAttribute(\"class\", \"col-1\")\n div.innerHTML = el\n Pt.appendChild(div)\n })\n } else if(ship.type == \"Destroyer\" && hitOnODes != 0){\n document.getElementById(\"Odestroyer-hit\").style.marginBottom = '10px'\n ship.ships_locations.forEach(el => {\n let div = document.createElement(\"div\")\n div.setAttribute(\"id\", \"odes\" + ship.ships_locations.indexOf(el))\n div.setAttribute(\"class\", \"col-1\")\n div.innerHTML = el\n Dt.appendChild(div)\n })\n }\n })\n }", "calculateFitness() {\n //print(\"pop calculating fitness\");\n for (var i =0; i<this.pop_size; i++) {\n this.players[i].calculateFitness();\n }\n }", "function squaresNeeded(grains){\n let deg = 0;\n while (grains > 0) { grains = grains - 2 ** (deg); deg++; }\n return deg;\n}", "function markerSize(population) {\n return population / 40;\n }", "function markerSize(population) {\n return population / 60;\n}", "function outfitTwo(){\n\tpush();\n\t//shirt\n\tstroke(\"#ed1258\");\n\tstrokeWeight(30);\n\tnoFill();\n\tline(340, 910, 660, 910);\n\tnoStroke()\n\tfill(\"white\");\n\trect(500, 960, 330, 100);\n\n\t// jacket\n\tfill(\"#a9c413\");\n\tbeginShape();\n\tvertex(130, 1000);\n\tvertex(200, 910);\n\tvertex(280, 866);\n\tvertex(350, 850);\n\tvertex(420, 840);\n\tvertex(580, 840);\n\tvertex(660, 850);\n\tvertex(720, 866);\n\tvertex(800, 910);\n\tvertex(870, 1000);\n\tbeginContour();\n\tvertex(420, 840);\n\tvertex(340, 850);\n\tvertex(360, 1000);\n\tvertex(640, 1000);\n\tvertex(660, 850);\n\tvertex(580, 840);\n\tendContour(CLOSE);\n\tendShape(CLOSE);\n\n\t//earrings\n\tnoFill();\n\tstroke(\"#a9c413\");\n\tstrokeWeight(5);\n\tline(220, 620, 200, 700);\n\tline(220, 620, 250, 720);\n\tline(780, 620, 730, 710);\n\tline(780, 620, 780, 700);\n\n\tnoStroke();\n\tfill(\"#ed1258\");\n\tellipse(200, 700, 40, 40);\n\tellipse(250, 720, 40, 40);\n\tellipse(730, 710, 40, 40);\n\tellipse(780, 700, 40, 40);\n\n\t//glasses\n\tstroke(\"#d1fffd\");\n\tnoFill();\n\tstrokeWeight(10);\n\trect(370, 575, 170, 160, 40, 40, 70, 70);\n\trect(630, 575, 170, 160, 40, 40, 70, 70);\n\tarc(500,545,90,50,PI,TWO_PI);\n\tpop();\n}", "function gen2(){\n\t// First tile\n\taddtile(0, 0, le, -le/2, -1.5388*le, 0);\n\t\n\t// Generating with pointdistances\n\tvar i = 0;\n\twhile(i<iter){\n\t\tfor(var j=0; j<pointdistances.length; j++){\n\t\t\t\n\t\t\tif( pointdistances.length > maxpointnum ){ console.log(points.length+' '+pointdistances.length); break; }\n\t\t\tif( points[pointdistances[j][0]] ){\n\t\t\t\t\n\t\t\t\tfor(var k=0;k<retries;k++){ \n\t\t\t\t\tfillpoint(pointdistances[j][0], le); \n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t// if(masksum(pointdistances[j][0])<10){ destroypoint(pointdistances[j][0]); } // optional destroying point if it can't be filled\n\t\t\t\t\n\t\t\t}\n\t\t}\n\t\ti++;\n\t}\n\t\n\t// Rendering SVG\n\tvar svgstr = createSVGString(w,h,stylepresets[stylepr],drawp);\n\t\n\t// Appending SVG string\n\tappendSVGString(svgstr,'mainbody');\n\t\n\t// Stats\n\tconsole.log('Number of tiles: '+tiles.length+' Number of points: '+points.length+' SVG string length: '+svgstr.length+' Avg. points/tiles: '+points.length/tiles.length+' Tiles/iter: '+tiles.length/iter);\n}// End of gen2()", "getPotentialPieceInfo(x, y) {\n let player_1_potential_spots = [[-1, -1], [-1, 1]]; // upper left, upper right\n let player_2_potential_spots = [[1, -1], [1, 1]]; // lower left, lower right\n let opponentColor = this.isPlayer1Turn ? this.PLAYER_2 : this.PLAYER_1;\n let potentialSpots = this.getChecker(x, y).isKing ? player_1_potential_spots.concat(player_2_potential_spots) : \n (this.isPlayer1Turn ? player_1_potential_spots : player_2_potential_spots);\n\n return [potentialSpots, opponentColor];\n }", "function toOz(shots){\n\treturn shots * SHOT_SIZE;\n}", "function Spot(i, j) {\n // Location\n this.i = i;\n this.j = j;\n\n // f, g, and h values for A*\n this.f = 0;\n this.g = 0;\n this.h = 0;\n\n // Neighbors\n this.neighbors = [];\n\n // Where did I come from?\n this.previous = undefined;\n\n // Am I a wall?\n this.wall = false;\n if (random(1) < 0.4) {\n this.wall = true;\n }\n\n // Display me\n this.show = function(col) {\n if (this.wall) {\n fill(0);\n noStroke();\n ellipse(this.i * w + w / 2, this.j * h + h / 2, w / 2, h / 2);\n } else if (col) {\n fill(col);\n rect(this.i * w, this.j * h, w, h);\n }\n };\n\n // Figure out who my neighbors are\n this.addNeighbors = function(grid) {\n var i = this.i;\n var j = this.j;\n if (i < cols - 1) {\n this.neighbors.push(grid[i + 1][j]);\n }\n if (i > 0) {\n this.neighbors.push(grid[i - 1][j]);\n }\n if (j < rows - 1) {\n this.neighbors.push(grid[i][j + 1]);\n }\n if (j > 0) {\n this.neighbors.push(grid[i][j - 1]);\n }\n if (i > 0 && j > 0) {\n this.neighbors.push(grid[i - 1][j - 1]);\n }\n if (i < cols - 1 && j > 0) {\n this.neighbors.push(grid[i + 1][j - 1]);\n }\n if (i > 0 && j < rows - 1) {\n this.neighbors.push(grid[i - 1][j + 1]);\n }\n if (i < cols - 1 && j < rows - 1) {\n this.neighbors.push(grid[i + 1][j + 1]);\n }\n };\n}", "function updateShotsOffGoal()\n{\n\tvar totalShotsOffGoal = 0;\n\n\tif(currTeam == 1) \n\t{\n\t\tT1.shotsOffGoal += 1;\n\n\t\t//Step 1: Update total attempts\n\t\tupdateGoalAttempts();\n\n\t\t//Step 2: Update shots on goal\n\t\ttotalShotsOffGoal = T1.shotsOffGoal + T2.shotsOffGoal;\n\n\t\tvar t1_bar = Math.floor((T1.shotsOffGoal / totalShotsOffGoal) * 100);\n\t\tvar t2_bar = 100 - t1_bar;\n\n\t\tdocument.getElementsByClassName(\"t1-shots-off-bar\")[0].style.width = t1_bar.toString() + \"%\";\n\t\tdocument.getElementsByClassName(\"t2-shots-off-bar\")[0].style.width = t2_bar.toString() + \"%\";\n\n\t\tdocument.getElementsByClassName(\"t1-shots-off-name\")[0].innerHTML = \"<b>Shots off Goal: \" + T1.shotsOffGoal + \"</b>\";\n\t}\n\telse\n\t{\n\t\tT2.shotsOffGoal += 1;\n\n\t\t//Step 1: Update total attempts\n\t\tupdateGoalAttempts();\n\t\n\t\t//Step 2: Update shots on goal\n\t\ttotalShotsOffGoal = T1.shotsOffGoal + T2.shotsOffGoal;\n\n\t\tvar t2_bar = Math.floor((T2.shotsOffGoal / totalShotsOffGoal) * 100);\n\t\tvar t1_bar = 100 - t2_bar;\n\n\t\tdocument.getElementsByClassName(\"t2-shots-off-bar\")[0].style.width = t2_bar.toString() + \"%\";\n\t\tdocument.getElementsByClassName(\"t1-shots-off-bar\")[0].style.width = t1_bar.toString() + \"%\";\n\n\t\tdocument.getElementsByClassName(\"t2-shots-off-name\")[0].innerHTML = \"<b>Shots off Goal: \" + T2.shotsOffGoal + \"</b>\";\n\t}\n}", "function calcDistance(g1, s1, p1, g2, s2, p2) {\r\n\tif(p1 == p2 && s1 == s2 && g1 == g2) {\r\n\t\treturn 5\r\n\t}\r\n\telse if(s1 == s2 && g1 == g2) {\r\n\t\treturn 1000 + Math.abs(p1 - p2) * 5\r\n\t}\r\n\telse if(g1 == g2) {\r\n\t\treturn 2700 + Math.abs(s1 - s2) * 95\r\n\t}\r\n\telse {\r\n\t\treturn Math.abs(g1 - g2) * 20000\r\n\t}\r\n}", "function find_landing_square(column_dropped_on) {\n//For loop. If dropped in square 1, the loop id going to start at 36 and its\n//going to loop backwards, subtracting 7 each time. It's looping backwards.\n//We iterate backwards and minus 7 each time.\n\t\tfor (i = column_dropped_on + 35; i >= column_dropped_on; i -= 7) {\n\t\t\tvar dropped_square = $('#' + i); //this is document.getElementByID in jQuery. We are getting a hold of that div it was dropped on.\n\t\t\tvar dropped_square_num = dropped_square.attr('id'); //this is an object. It's returning the div. We are getting the number (the divs ID).\n\n\t\t\t//If the dropped_square square has the class of 'can_place'\n\t\t\t//(this will be true), we return the array back which includes the\n\t\t\t//distance from top to 6 (how far it has to go down), and the\n\t\t\t//dropped_square square number.\n\t\t\tif (dropped_square.hasClass('can_place')) {\n\t\t\t\tif (dropped_square_num > 35) {\n\t\t\t\t\treturn ['503px', dropped_square_num];\n\t\t\t\t} else if (dropped_square_num > 28) {\n\t\t\t\t\treturn ['419px', dropped_square_num];\n\t\t\t\t} else if (dropped_square_num > 21) {\n\t\t\t\t\treturn ['335px', dropped_square_num];\n\t\t\t\t} else if (dropped_square_num > 14) {\n\t\t\t\t\treturn ['251px', dropped_square_num];\n\t\t\t\t} else if (dropped_square_num > 7) {\n\t\t\t\t\treturn ['167px', dropped_square_num];\n\t\t\t\t} else {\n\t\t\t\t\treturn ['83px', dropped_square_num];\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}", "function top_calcul(){\r\n \r\n pose_menu();\r\n \r\n if(xsmall){\r\n top2=$('.g-head').innerHeight() + 524;\r\n }else{\r\n var cons=0;\r\n if(small){\r\n cons=170;\r\n }else if(md){\r\n cons=170;\r\n }else if(lg){\r\n cons=105;\r\n }\r\n //alert(cons);\r\n top2=$('.g-head').innerHeight() + $('.slide').innerHeight()-($('.sous-bloc').innerHeight()+cons);\r\n }\r\n }", "function pairingTwoSideScoreBoard(RoundName){\n var remainingPairings=TEAM_NUMBER;\n var currentRow=0;\n var scoreBoardSheet = ss.getSheetByName(SHEET_SCOREBOARD);\n var range = scoreBoardSheet.getRange(4, 1, TEAM_NUMBER,6);\n var dataGrid = range.getValues();//Data sorted\n var bracketSize;\n var rand;\n var properOpponent;\n var govIndex=0;\n var newGov = [];\n var newOpp = [];\n var itr=TEAM_NUMBER*40;\n var values;\n while(remainingPairings>0){\n bracketSize=obtainBracketSize(dataGrid,currentRow);\n values=scoreBoardSheet.getRange(currentRow+4, 2, bracketSize).getValues();\n var RepresentativeArray=obtainPartialAffiliationNumbers(currentRow,bracketSize);\n var non_affiliated_rounds=nonAffiliatedMatches(RepresentativeArray,bracketSize);\n while(values.length>Number(non_affiliated_rounds*2)&&LIMIT_INTER_AFF_ROUNDS){\n rand= values.indexOf(findTeamRepresented(RepresentativeArray,values));// assignation before looping on random values\n properOpponent=false;\n var random = Math.ceil(Math.random() *2 );//To allow most represented to be opposition and gov\n if(random%2==0){\n newGov.push(values[rand]);\n values.splice(rand,1);\n while(!properOpponent){\n rand= randomIndexTeam(values.length);\n if(obtainAffiliationDebater(newGov[govIndex])!=obtainAffiliationDebater(values[rand])){\n updateRepresented(RepresentativeArray,values[rand]);// Counterpart to keep findTeamRepresented from getting out of sync with the values array.\n newOpp.push(values[rand]);\n values.splice(rand,1);\n govIndex+=1;\n properOpponent=true;\n }\n itr-=1;\n if(itr<0)\n throw \"Computation limit exceeded. Regenerate round\";// Prevents infinite looping when randomness doesnt prioritize spreading big teams.\n }\n }\n else{\n newOpp.push(values[rand]);\n values.splice(rand,1);\n while(!properOpponent){\n rand= randomIndexTeam(values.length);\n if(obtainAffiliationDebater(newOpp[govIndex])!=obtainAffiliationDebater(values[rand])){\n updateRepresented(RepresentativeArray,values[rand]);// Counterpart to keep findTeamRepresented from getting out of sync with the values array\n newGov.push(values[rand]);\n values.splice(rand,1);\n govIndex+=1;\n properOpponent=true;\n }\n itr-=1;\n if(itr<0)\n throw \"Computation limit exceeded. Regenerate round\";// Prevents infinite looping when unforseen bugs occur.\n }\n }\n }\n for (var row=0;row<values.length;row+=2) {\n var rand = Math.ceil(Math.random() *2 );\n if(rand==1){\n newGov.push(values[row]);\n newOpp.push(values[row+1]); \n }\n else{\n newOpp.push(values[row]);\n newGov.push(values[row+1])\n }\n }\n currentRow=currentRow+bracketSize;\n remainingPairings=remainingPairings-bracketSize; \n }\n control2Sides(dataGrid,newGov,newOpp);\n var pairingNumber=TEAM_NUMBER/SIDES_PER_ROUND; \n var randomised_order=createArray(pairingNumber,2);\n for(var i = 0;i<pairingNumber;i++){\n randomised_order[i][0]=String(newGov[i]);\n randomised_order[i][1]=String(newOpp[i]);\n }\n shuffleArray(randomised_order);//Randomise for display in random order for pairings to prevent rankings positions\n ss.getSheetByName(RoundName).getRange(3, 2,randomised_order.length,2).setValues(randomised_order);\n \n}", "function result() {\r\n\t// Teams Names Array\r\n\tvar tn = document.getElementsByClassName('teamName');\r\n\tvar teams = [];\r\n\t// Teams First Map Stats Array\r\n\tvar m1k = document.getElementsByClassName('m1k');\r\n\tvar m1p = document.getElementsByClassName('m1p');\r\n\r\n\t// Teams Second Map Stats Array\r\n\tvar m2k = document.getElementsByClassName('m2k');\r\n\tvar m2p = document.getElementsByClassName('m2p');\r\n\t// Teams Second Map Stats Array\r\n\tvar m3k = document.getElementsByClassName('m3k');\r\n\tvar m3p = document.getElementsByClassName('m3p');\r\n\r\n\t// Kill and Placement Stats for All Teams\r\n\tvar kstats = [];\r\n\tvar pstats = [];\r\n\r\n\tvar results = [];\r\n\t// Set Teams that won the map (3 Teams)\r\n\tvar win = [];\r\n\tvar totalp = [];\r\n\tfor (var i = 0; i < tn.length; i++) {\r\n\t\tteams[i] = tn[i].value;\r\n\t\tvar Kills = 0;\r\n\t\tvar placePoints = [];\r\n\r\n\t\tkills = parseInt(m1k[i].value);\r\n\t\tkills += parseInt(m2k[i].value);\r\n\t\tkills += parseInt(m3k[i].value);\r\n\t\tvar place =[];\r\n\r\n\t\tplace.push(m1p[i].value); //[m1p[i].value, m2p[i].value, m3p[i].value];\r\n\t\tplace.push(m2p[i].value);\r\n\t\tplace.push(m3p[i].value);\r\n\r\n\t\tkstats[i] = kills;\r\n\t\t//pstats.push(placePoints);\r\n\r\n\t\tplacePoints = 0;\r\n\t\tfor (var e = 0; e < 3; e++) {\r\n\t\t \tswitch (parseInt(place[e])) {\r\n\t\t\t case 1:\r\n\t\t\t win.push(i);\r\n\t\t\t \tplacePoints += 15;\r\n\t\t\t break;\r\n\t\t\t case 2:\r\n\t\t\t placePoints += 12;\r\n\t\t\t break;\r\n\t\t\t case 3:\r\n\t\t\t placePoints += 10;\r\n\t\t\t break;\r\n\t\t\t case 4:\r\n\t\t\t placePoints += 8;\r\n\t\t\t break;\r\n\t\t\t case 5:\r\n\t\t\t placePoints += 6;\r\n\t\t\t break;\r\n\t\t\t case 6:\r\n\t\t\t placePoints += 4;\r\n\t\t\t break;\r\n\t\t\t case 7:\r\n\t\t\t placePoints += 2;\r\n\t\t\t break;\r\n\t\t\t case 8:\r\n\t\t\t placePoints += 1;\r\n\t\t\t break;\r\n\t\t\t case 9:\r\n\t\t\t placePoints += 1;\r\n\t\t\t break;\r\n\t\t\t case 10:\r\n\t\t\t placePoints += 1;\r\n\t\t\t break;\r\n\t\t\t case 11:\r\n\t\t\t placePoints += 1;\r\n\t\t\t break;\r\n\t\t\t case 12:\r\n\t\t\t placePoints += 1;\r\n\t\t\t break;\r\n\t\t\t default:\r\n\t\t\t placePoints += 0;\r\n\t\t\t} // End of SWITCH Statement\r\n\t\t} // End of FOR e Loop\r\n\t\tpstats[i] = placePoints;\r\n\r\n\t\ttotalp[i] = kills + placePoints;\r\n\t// Placement Stats for All Teams\r\n\t} // End of FOR i Loop \r\n\r\n\tfor (var c = 0; c < tn.length; c++) {\r\n\t\tresults[c] = {name: teams[c], kp: kstats[c], pp: pstats[c], tp: totalp[c], win: 0};\r\n\t\t// [teams[c], kstats[c], pstats[c], totalp[c], 0];\r\n\r\n\t}\r\n\tfor(var d = 0; d < win.length; d++){\r\n\t\tresults[win[d]].win += 1;\r\n\t}\r\n\r\n\tresults.sort(function (x, y) {\r\n \treturn y.tp - x.tp;\r\n\t});\r\n\t// Create a Loop to put Data from results into the HTML Table\r\n\t// Element\r\n\tfor(var s = 0; s < results.length; s++){\r\n\t\t// Put Team Name\r\n\t\tdocument.getElementsByClassName('tteam')[s].innerHTML = results[s].name\r\n\t\t// Put Team Win\r\n\t\tdocument.getElementsByClassName('twwcd')[s].innerHTML = results[s].win;\r\n\t\t// Put Team Kill Points\r\n\t\tdocument.getElementsByClassName('tkp')[s].innerHTML = results[s].kp;\r\n\t\t// Put Team Placement Points\r\n\t\tdocument.getElementsByClassName('tpp')[s].innerHTML = results[s].pp;\r\n\t\t// Put Total Points\r\n\t\tdocument.getElementsByClassName('ttp')[s].innerHTML = results[s].tp;\r\n\t}\r\n\tdocument.getElementsByClassName('rtable')[0].style.display = 'block';\r\n\tdocument.getElementsByClassName('datat')[0].style.display = 'none';\r\n}", "function bestSpot() {\n return minimax(origBoard, com).index;\n}", "function mercantileType() {\n var calcOcc = function () {\n // Taking input\n var a = document.getElementById('carpetAreaGround-mercantile').valueAsNumber;\n var b = document.getElementById('carpetAreaUpper-mercantile').valueAsNumber;\n // Calculating Number of People\n var resultA = Math.abs(Math.round(a / 3));\n var resultB = Math.abs(Math.round(b / 6));\n var resultFixedOccupancy = Math.abs(Math.round((resultA + resultB) * 0.10));\n var resultFloatingOccupancy = Math.abs(Math.round((resultA + resultB) * 0.90));\n var resultTotalOccupancy = Math.abs(Math.round(resultA + resultB));\n\n return [resultA, resultB, resultFixedOccupancy, resultFloatingOccupancy, resultTotalOccupancy];\n };\n var occupancyResult = function () {\n // Declaring Result\n var values = calcOcc();\n document.getElementById('resultOccupancy').innerHTML = \"Total Occupancy: \" + values[4] + \"<br />\" + \"Fixed Occupancy ~ \" + values[2] + \"<br />\" + \"Floating Occupancy ~ \" + values[3] ;\n };\n \n return occupancyResult();\n}", "_findSquares(tunnelDirection) {\n let x, y\n const result = []\n if (tunnelDirection === 'NORTH') {\n for (({ x } = this), end = (this.x+this.tunnelWidth)-1, asc = this.x <= end; asc ? x <= end : x >= end; asc ? x++ : x--) {\n var asc, end\n result.push({ x, y: this.y-1, width: 1, height: 1 }) }\n } else if (tunnelDirection === 'SOUTH') {\n for (({ x } = this), end1 = (this.x+this.tunnelWidth)-1, asc1 = this.x <= end1; asc1 ? x <= end1 : x >= end1; asc1 ? x++ : x--) { var asc1, end1;\n result.push({ x, y: this.y+this.height, width: 1, height: 1 }) }\n } else if (tunnelDirection === 'EAST') {\n for (({ y } = this), end2 = (this.y+this.tunnelWidth)-1, asc2 = this.y <= end2; asc2 ? y <= end2 : y >= end2; asc2 ? y++ : y--) { var asc2, end2;\n result.push({x: this.x+this.width, y, width: 1, height: 1 }) }\n } else {\n for (({ y } = this), end3 = (this.y+this.tunnelWidth)-1, asc3 = this.y <= end3; asc3 ? y <= end3 : y >= end3; asc3 ? y++ : y--) { var asc3, end3;\n result.push({x: this.x-1, y, width: 1, height: 1 }) }\n }\n return result\n }", "runPop() {\n\n const now = Date.now();\n\n const averageOverIterations = [];\n\n for (let i = 3; i < this.maxGeneration; i++) {\n\n for (let j = 0; j < this.repeatNumber; j++) {\n\n const population = new Population('Genetic Algorithm!', i, false);\n this.previousGen.push(population.run());\n\n }\n\n const group = this.previousGen.filter(s => s.size === i);\n\n const avgGen = Math.round(group.map(gen => gen.numGen)\n .reduce((a, b) => (a + b)) / this.repeatNumber);\n\n const avgTime = Math.round(group.map(gen => gen.time)\n .reduce((a, b) => (a + b)) / this.repeatNumber);\n\n const sameSize = group[0].size;\n\n const avgObj = {\n numGen: avgGen,\n size: sameSize,\n time: avgTime,\n };\n\n averageOverIterations.push(avgObj);\n\n }\n\n averageOverIterations.sort((a, b) => a.numGen - b.numGen);\n\n const { numGen, size, time } = averageOverIterations[0];\n\n console.log(`\n *****\n Max populatation size: ${this.maxGeneration}\n Iterations per generation: ${this.repeatNumber}\n\n *****\n Optimum populatation size: ${size}\n Average number of generations: ${numGen}\n Average time: ${time}ms\n\n *****\n OptimumPopulationSize execution time: ${Date.now() - now}ms`);\n\n }", "function calcMoves() {\n moves++;\n movesSpan.innerText = moves;\n updateStars();\n }", "function Spot(i, j) {\n\tthis.i = i;\n\tthis.j = j;\n\tthis.f = 0;\n\tthis.g = 0;\n\tthis.h = 0;\n\tthis.neighbors = [];\n\tthis.previous = undefined;\n\tthis.wall = false;\n\n\t// Randomly make certain spots walls\n\tif (random(1) < 0.3) {\n\t\tthis.wall = true;\n\t}\n\n\tthis.show = function(cols) {\n\t\tif (this.wall) {\n\t\t\tfill(0);\n\t\t\tnoStroke();\n\t\t\tellipse(this.i * w + w / 2, this.j * h + h / 2, w / 2, h / 2);\n\t\t}\n\t}\n\n\tthis.addNeighbors = function(grid) {\n\t\tvar i = this.i;\n\t\tvar j = this.j;\n\n\t\tif (i < cols - 1) {\n\t\t\tthis.neighbors.push(grid[i + 1][j]);\n\t\t}\n\t\tif (i > 0) {\n\t\t\tthis.neighbors.push(grid[i - 1][j]);\n\t\t}\n\t\tif (j < rows - 1) {\n\t\t\tthis.neighbors.push(grid[i][j + 1]);\n\t\t}\n\t\tif (j > 0) {\n\t\t\tthis.neighbors.push(grid[i][j - 1]);\n\t\t}\n\t\tif (i > 0 && j > 0) {\n\t\t\tthis.neighbors.push(grid[i - 1][j - 1]);\n\t\t}\n\t\tif (i < cols - 1 && j > 0) {\n\t\t\tthis.neighbors.push(grid[i + 1][j - 1]);\n\t\t}\n\t\tif (i > 0 && j < rows - 1) {\n\t\t\tthis.neighbors.push(grid[i - 1][j + 1]);\n\t\t}\n\t\tif (i < cols - 1 && j < rows - 1) {\n\t\t\tthis.neighbors.push(grid[i + 1][j + 1]);\n\t\t}\n\t}\n}", "function bucketLane() {\r\n\t\r\n\tvar bucketArray = document.querySelectorAll(\".bucket\");\r\n\t\r\n\tif (bucketArray[0].location == 1)\r\n\t\treturn 15;\r\n\tif (bucketArray[1].location == 1)\r\n\t\treturn 45;\r\n\tif (bucketArray[2].location == 1)\r\n\t\treturn 30;\r\n\t\r\n}", "function scrapeNeighborhoodSalesAndImprovements(resultArr){\n\t\tconsole.log(\"scraping NSI and Imps\");\n\t\tvar promiseArr = [];\n\t\tvar neighborhoodSalesURL = utils.getNeighborhoodSalesURL(utils.padToNine(index));\n\t\tpromiseArr.push(xP([neighborhoodSalesURL, {neighborhoodSales: css.neighborhoodSalesInfo}])()); //scrape neighborhood sales info\n\t\tvar impnbr = resultArr[0].propertyInventory.numberOfImprovements;\n\t\tconsole.log(\"impnbr: \" + impnbr);\n\t\tconsole.log(utils.getPropertyImpURLs(propertyNumber, 3));\n\t\tif (impnbr > 1){\n \t\tvar propertyImpURLs = utils.getPropertyImpURLs(propertyNumber, impnbr);\n\t\t\tconsole.log(\"propimpurl: \" + propertyImpURLs);\n \t\t//console.log(\"propimpurl length: \" + propertyImpURLs.length);\n \t\tfor (var u = 0; u < propertyImpURLs.length; u++){\n\t\t\t\tpromiseArr.push(xP([propertyImpURLs[u], {propertyInventory: css.propertyInventory, improvements: css.improvements}])()); //scrape improvement info\n \t\t}\n\t\t}\n\t\tresultArr.push(promiseArr);\n\t\tconsole.log(\"finished scraping NSI and Imps\");\n\t\treturn resultArr;\n\t}", "function twoPairPoints() {\n let twoP = frequency();\n var points = 0;\n var count = 0;\n for (let i = 0; i < 7; i++) {\n if (twoP[i] >= 2) {\n points += i * 2;\n count++;\n }\n }\n\n if (count == 2) {\n return points;\n } else {\n return 0;\n }\n}", "function couple_logistic_possison(pop, params, steps) {\r\n\t\r\n\t/*\r\n\t// Nondimensionalize our parameters\r\n\tvar u1 = pop[0]/params.r1;\r\n\tvar u2 = pop[1]/params.r2;\r\n\tvar p = params.r2/params.r1;\r\n\tvar t = params.r1*cur_t;\r\n\tvar ab = params.a*params.k2/params.k1;\r\n\tvar ba = params.b*params.k1/params.k2;\r\n\r\n\t// Change in population.\r\n\tvar delta_pop1 = u1*(1 + u1 - ab*u2);\r\n\tvar delta_pop2 = u2*(1 + u2 - ba*u1);\r\n\t*/\r\n\r\n\t// Change in population.\r\n\tvar delta_pop1 = params.r1 * pop[0] * (1 - (pop[0] + params.a*pop[1])/params.k1);\r\n\tvar delta_pop2 = params.r2 * pop[1] * (1 - (pop[1] + params.a*pop[0])/params.k2);\r\n\t\r\n\t// Call poisson distribution.\r\n\tvar actual_pop1 = poisson(delta_pop1);\r\n\tvar actual_pop2 = poisson(delta_pop2);\r\n\r\n\t// Population growth.\r\n\tpop[0] += actual_pop1;\r\n\tpop[1] += actual_pop2;\r\n\r\n\treturn [cur_t, pop[0]/dim, pop[1]/dim];\r\n\r\n}", "function bestStepForSpot(col, row){\r\n\tvar cur_pos = [col, row];\r\n\tvar j = 0;\r\n\tvar pos = [];\r\n\tvar max_s = 0;\r\n\tvar s_n = 0; \r\n\tvar d_pos = [];\r\n\tfor (j = 0; j<POSSIBLE_MOVING.length; j++){\r\n\t\tpos = [cur_pos[0] + POSSIBLE_MOVING[j][0], cur_pos[1] + POSSIBLE_MOVING[j][1]]; \r\n\t\tif (outOfRange(pos[0], pos[1])) continue;\r\n\t\tif (game_field[pos[1]][pos[0]] == EMPTY){\r\n\t\t\ts_n = getScoreAfterStep(cur_pos, pos);\r\n\t\t\tif (s_n > max_s){\r\n\t\t\t\tmax_s = s_n;\r\n\t\t\t\td_pos = [POSSIBLE_MOVING[j][0], POSSIBLE_MOVING[j][1]];\r\n\t\t\t}\r\n\t\t}\t\r\n\t}\r\n\treturn [d_pos, max_s];\r\n}", "calPopulationFitness() {\n this.#fitsum = 0;\n for (let i = 0; i < this.parentPop.length; i++) {\n let song = this.parentPop[i];\n song.calFitness(fitnessChoice);\n this.#fitsum += song.fitness;\n }\n \n // parentPop Invariant\n if (minFitness) this.parentPop.sort(compareFitnessDec);\n else this.parentPop.sort(compareFitnessInc);\n }", "function updateBlockedShots()\n{\n\tvar totalBlockShots = 0;\n\n\tif(currTeam == 1) \n\t{\n\t\tT1.blockedShots += 1;\n\n\t\t//Step 1: Update total attempts\n\t\tupdateGoalAttempts();\n\n\t\t//Step 2: Update shots on goal\n\t\ttotalBlockShots = T1.blockedShots + T2.blockedShots;\n\n\t\tvar t1_bar = Math.floor((T1.blockedShots / totalBlockShots) * 100);\n\t\tvar t2_bar = 100 - t1_bar;\n\n\t\tdocument.getElementsByClassName(\"t1-block-shot-bar\")[0].style.width = t1_bar.toString() + \"%\";\n\t\tdocument.getElementsByClassName(\"t2-block-shot-bar\")[0].style.width = t2_bar.toString() + \"%\";\n\n\t\tdocument.getElementsByClassName(\"t1-block-shot-name\")[0].innerHTML = \"<b>Blocked Shots: \" + T1.blockedShots + \"</b>\";\n\t}\n\telse\n\t{\n\t\tT2.blockedShots += 1;\n\n\t\t//Step 1: Update total attempts\n\t\tupdateGoalAttempts();\n\t\n\t\t//Step 2: Update shots on goal\n\t\ttotalBlockShots = T1.blockedShots + T2.blockedShots;\n\n\t\tvar t2_bar = Math.floor((T2.blockedShots / totalBlockShots) * 100);\n\t\tvar t1_bar = 100 - t2_bar;\n\n\t\tdocument.getElementsByClassName(\"t2-block-shot-bar\")[0].style.width = t2_bar.toString() + \"%\";\n\t\tdocument.getElementsByClassName(\"t1-block-shot-bar\")[0].style.width = t1_bar.toString() + \"%\";\n\n\t\tdocument.getElementsByClassName(\"t2-block-shot-name\")[0].innerHTML = \"<b>Blocked Shots: \" + T2.blockedShots + \"</b>\";\n\t}\n}", "constructor() {\n this.parentPop = []; // Main population - invariant : always sorted, best indiv on the front\n this.matingPool = []; // Individuals chosen as parents are temporarily stored here\n this.childPop = []; // Child population for step 3 - 'produceOffspring'\n \n this.#fitsum = 0;\n \n // Init parentPop with new random individuals\n for (let i = 0; i < popsize; i++) {\n this.parentPop[i] = new Song();\n }\n }", "getFoodLocation() {\n let x = Utils.rand(MARGIN, document.body.clientWidth - MARGIN, SIZE);\n let y = Utils.rand(MARGIN, document.body.clientHeight - MARGIN, SIZE);\n // If random spot is already filled, pick a new one\n // Pick until you find an empty spot\n // ..... nothing can go wrong with this\n if (Locations.has(x, y)) {\n [x, y] = this.getFoodLocation();\n }\n return [x, y];\n }", "function setupGridSpots() {\r\n /*Direction spots*/\r\n right = [32, 24, 17];\r\n up = [39, 30];\r\n left = [7, 14];\r\n down = [0, 9];\r\n \r\n /*End spot*/\r\n end = [21];\r\n \r\n /*Card spots*/\r\n card = [2, 6, 22, 23, 28, 34, 38];\r\n \r\n /*Trap Spots*/\r\n trap = [1, 3, 8, 10, 13, 15, 26, 27, 36];\r\n \r\n /*Fill grid*/\r\n fillGrid(\"right\", right);\r\n fillGrid(\"up\", up);\r\n fillGrid(\"left\", left);\r\n fillGrid(\"down\", down);\r\n \r\n fillGrid(\"end\", end);\r\n \r\n fillGrid(\"card\", card);\r\n \r\n fillGrid(\"trap\", trap);\r\n}", "calcTroops(villageId,buildings)\n {\n let barrackList =[]\n let barrackQ;\n let barrack = this.troopres['club'].split(',');\n let res = m.villageData[villageId][\"res\"];\n console.log(barrack)\n \n barrackList.push(parseInt(res.wood/barrack[0]))\n barrackList.push(parseInt(res.clay/barrack[1]))\n barrackList.push(parseInt(res.iron/barrack[2]))\n barrackList.push(parseInt(res.crop/barrack[3]))\n barrackQ = Math.min.apply(null, barrackList);\n console.log(barrackQ)\n let rcrop = parseInt(res.crop) - barrackQ*barrack[3]; \n if(rcrop>200)\n {\n \n return barrackQ;\n }\n else\n {\n return 0;\n }\n }", "get hitbox_x1() { return -7; }", "function updateShotsOnGoal()\n{\n\tvar totalShotsOnGoal = 0;\n\n\tif(currTeam == 1) \n\t{\n\t\tT1.shotsOnGoal += 1;\n\n\t\t//Step 1: Update total attempts\n\t\tupdateGoalAttempts();\n\n\t\t//Step 2: Update shots on goal\n\t\ttotalShotsOnGoal = T1.shotsOnGoal + T2.shotsOnGoal;\n\n\t\tvar t1_bar = Math.floor((T1.shotsOnGoal / totalShotsOnGoal) * 100);\n\t\tvar t2_bar = 100 - t1_bar;\n\n\t\tdocument.getElementsByClassName(\"t1-shots-on-bar\")[0].style.width = t1_bar.toString() + \"%\";\n\t\tdocument.getElementsByClassName(\"t2-shots-on-bar\")[0].style.width = t2_bar.toString() + \"%\";\n\n\t\tdocument.getElementsByClassName(\"t1-shots-on-name\")[0].innerHTML = \"<b>Shots on Goal: \" + T1.shotsOnGoal + \"</b>\";\n\t}\n\telse\n\t{\n\t\tT2.shotsOnGoal += 1;\n\n\t\t//Step 1: Update total attempts\n\t\tupdateGoalAttempts();\n\t\n\t\t//Step 2: Update shots on goal\n\t\ttotalShotsOnGoal = T1.shotsOnGoal + T2.shotsOnGoal;\n\n\t\tvar t2_bar = Math.floor((T2.shotsOnGoal / totalShotsOnGoal) * 100);\n\t\tvar t1_bar = 100 - t2_bar;\n\n\t\tdocument.getElementsByClassName(\"t2-shots-on-bar\")[0].style.width = t2_bar.toString() + \"%\";\n\t\tdocument.getElementsByClassName(\"t1-shots-on-bar\")[0].style.width = t1_bar.toString() + \"%\";\n\n\t\tdocument.getElementsByClassName(\"t2-shots-on-name\")[0].innerHTML = \"<b>Shots on Goal: \" + T2.shotsOnGoal + \"</b>\";\n\t}\n}", "function allPossibleWinPositions(size)\n{\n let wins = []\n let onewin = []\n let coords = []\n for (let y = 1; y <= size; y++) {\n for (let x = 1; x <= size; x++) {\n coords.push(x)\n coords.push(y)\n onewin.push(coords)\n coords = []\n }\n wins.push(onewin)\n onewin = []\n }\n for (let x = 1; x <= size; x++) {\n for (let y = 1; y <= size; y++) {\n coords.push(x)\n coords.push(y)\n onewin.push(coords)\n coords = []\n }\n wins.push(onewin)\n onewin = []\n }\n for (let a = 1; a <= size; a++) {\n coords.push(a,a)\n onewin.push(coords)\n coords = []\n }\n wins.push(onewin)\n onewin=[]\n for (let a = 1; a <= size; a++) {\n coords.push(size-a+1,a)\n onewin.push(coords)\n coords = []\n }\n wins.push(onewin)\n onewin=[]\n\n return wins\n}", "function cal_posi(hashtag) {\n top_height = height / 6\n gap_y = height / 10\n max_tags_y = 5 // criteria 1: max num of tags permitted within the same height\n max_gap = 5 // criteria 2: |sum1-sum2| <= max_gap\n max_tags = 25 // max num of tags permiited in total\n hashtag.length = max_tags\n\n cnter = 0\n curr_value = hashtag[0][1]\n curr_height = top_height\n\n for (d in hashtag) {\n if (cnter < max_tags_y && curr_value - hashtag[d][1] <= max_gap) {\n cnter += 1\n }\n else {\n curr_height += gap_y\n curr_value = hashtag[d][1]\n cnter = 1\n }\n\n hashtag[d].push(curr_height)\n hashtag[d][2] = hashtag[d][2] / hashtag[d][1]\n }\n}", "getMove() {\n if (this.infected) {\n let nearby = this.world.characters.filter((character) => Math.abs(character.x - this.x) <= 2 && Math.abs(character.y - this.y) <= 2 && character != this)\n for (let c of nearby) {\n let probability = 1 / (Math.sqrt((c.x - this.x) * (c.x - this.x) + (c.y - this.y) * (c.y - this.y))) * this.world.outsideInfectionRate\n if (Math.random() < probability) {\n c.particlesIn()\n }\n }\n }\n\n let distances = this.currentBuilding.distancesFrom;\n if (distances[this.x][this.y] == 1) {\n this.world.intoBuilding(this.currentBuilding, this)\n return\n }\n\n // Make sure every coordinate is in the map and valid\n let possibleValues = moves.map((diff) => [this.x + diff[0], this.y + diff[1]]).filter((coord) => this.world.isEmpty(coord[0], coord[1]))\n\n // Sort by rating\n possibleValues.sort((first, second) => distances[second[0]][second[1]] - distances[first[0]][first[1]])\n\n if (possibleValues.length == 0) {\n return\n }\n\n var distancing = this.world.sdRange\n let nearbies = this.world.characters.filter((character) => Math.abs(character.x - this.x) <= 3 && Math.abs(character.y - this.y) <= 3).filter((c) => c != this)\n\n let maxVal = distances[possibleValues[0][0]][possibleValues[0][1]]\n // score based on how it can get to the home\n let scores = possibleValues.map((coord) => Math.abs(distances[coord[0]][coord[1]] - maxVal - 1))\n\n\n scores = scores.map(function (currentScore, i) {\n let [x, y] = possibleValues[i]\n if (nearbies.length == 0) {\n return currentScore\n }\n let closestDistance = Math.sqrt(nearbies.map((char) => (char.x - x) * (char.x - x) + (char.y - y) * (char.y - y)).reduce((last, current) => Math.min(last, current)))\n\n let multiplier = Math.pow(1 - distancing / 3 / (Math.pow(2, 2 * (closestDistance - 2.5)) + 1), 2)\n return currentScore * multiplier\n })\n\n let maxScore = scores.reduce((last, cur) => Math.max(last, cur))\n for (let i = 0; i < scores.length; ++i) {\n if (scores[i] == maxScore) {\n this.world.move(this, possibleValues[i][0], possibleValues[i][1])\n }\n }\n }", "getVisitsGraphics() {\n return 90 + ',' + 70 + ',' + 90 + ',' + 70+ ',' + 75 + ',' + 80 + ',' + 70;\n }", "function setupGenetic(){\r\n orderGA = [];\r\n\r\n for (var i = 0; i < totalVertices; i++) {\r\n orderGA[i] = i;\r\n }\r\n \r\n population = [];\r\n fitness = [];\r\n recordDistanceGA = Infinity;\r\n\r\n generation = document.getElementById('numGen').value;;\r\n popSize = document.getElementById('sizePop').value;\r\n\r\n for (var i = 0; i < popSize; i++) {\r\n population[i] = customShuffle(orderGA, orderGA[0]);\r\n }\r\n\r\n mutationRate = document.getElementById('rateMut').value;\r\n indexPopulation = 0;\r\n countGA = 0;\r\n\r\n totalCountGA = (totalVertices-1)*generation*popSize;\r\n}", "function createFreePointsMap(){\n var index=0;\n for (var i = 0; i < 20; i++){\n for (var j = 0; j < 20; j++){\n /*if((j==0 && i == 1) || (j==0 && i == 18) || (j==1 && i >=1 && i <= 8) || (j==1 && i == 11) || (j==1 && i == 14) || (j==1 && i == 18) || (j>=2 && j<=3 && i == 1) || (j>=2 && j<=3 && i == 11) || (j==3 && i>=9 && i<=10) || (j==5 && i==0) ||\n (i==1 && j>=5 && j<=7) || (j==3 && i>=9 && i<=10) || (j==4 && i>=3 && i<=6)|| (j==5 && i>=10 && i<=14)||\n (j==5 && i>=16 && i<=18) || (j==7 && i>=3 && i<=9)|| (j==7 && i>=10 && i<=18) || (j==9 && i>=5 && i<=9) ||\n (j==9 && i>=11 && i<=12) || (j==11 && i>=11 && i<=18) || (j==14 && i>=1 && i<=3) || (j==13 && i>=11 && i<=14) ||\n (j==15 && i>=11 && i<=14) || (j==3 && i>=9 && i<=10) || (j==16 && i>=1 && i<=5) || (j==16 && i>=7 && i<=9) ||\n (j==18 && i>=1 && i<=10) || (j==18 && i>=12 && i<=18) || (i==14 && j>=2 && j<=4) || (i==16 && j>=2 && j<=4) ||\n (i==5 && j>=5 && j<=6) || (i==8 && j>=5 && j<=6) || (i==3 && j>=8 && j<=10) || (i==15 && j>=8 && j<=10) ||\n (i==18 && j>=8 && j<=9) || (i==18 && j>=12 && j<=17) || (i==1 && j>=11 && j<=13) || (i==5 && j>=10 && j<=15) || (i==7 && j>=11 && j<=15) || (i==9 && j>=10 && j<=15) || (i==3 && j>=12 && j<=13) || (i==12 && j>=16 && j<=17) ||\n (i==16 && j>=14 && j<=15) || (i==1 && j==17) || (i==14 && j==14))*/\n if((j>=1 && j<=2 && i>=1 && i<=3) || (j>=1 && j<=2 && i>=5 && i<=7) || (j>=1 && j<=2 && i>=11 && i<=13) || (j>=1 && j<=2 && i>=15 && i<=18) ||\n (j>=0 && j<=2 && i==9) || (j==4 && i>=1 && i<=3) || (j==4 && i>=15 && i<=18) ||(j>=6 && j<=8 && i>=1 && i<=3) || (j>=6 && j<=8 && i>=15 && i<=18) ||\n (j>=10 && j<=12 && i>=1 && i<=3) || (j>=10 && j<=12 && i>=15 && i<=18) || (j>=8 && j<=10 && i>=7 && i<=11) || (j==18 && i>=1 && i<=7) ||\n (j==18 && i>=11 && i<=13) || (j==18 && i>=15 && i<=18) || (j==16 && i>=0 && i<=1) || (j==16 && i>=7 && i<=11) || (j==16 && i>=17 && i<=18) ||\n (j==14 && i>=1 && i<=3) || (j==14 && i>=5 && i<=7) || (j==14 && i>=11 && i<=13) || (j==14 && i>=15 && i<=18) || (j==12 && i>=7 && i<=11) ||\n (j==4 && i>=7 && i<=11) || (j==6 && i>=6 && i<=7) || (j==6 && i>=11 && i<=12) || (i==3 && j>=15 && j<=16) || (i==15 && j>=15 && j<=16) ||\n (i==5 && j>=16 && j<=17) || (i==5 && j>=10 && j<=12) || (i==5 && j>=4 && j<=8) || (i==9 && j>=5 && j<=6) || (i==9 && j>=13 && j<=14) ||\n (i==9 && j>=17 && j<=18) || (i==13 && j>=4 && j<=8) || (i==13 && j>=10 && j<=12) || (i==13 && j>=16 && j<=17) )\n {\n if(i==9 && j==8){\n\n }\n else if(i==9 && j==10){\n\n }\n else{\n continue;\n }\n\n }\n else{\n freePointsMap.points[index] = j;\n freePointsMap.points[index + 1] = i;\n index+=2;\n }\n }\n }\n}", "generateHousingOccupancy() {\n if (this._occupiedHouses <= 99) {\n this._hv = [0, 0, 0, 0, 0, 0, 0, 0];\n return;\n } else {\n // Generate tiny fluctuations for the housing weights, but only do so if\n // the number of occupied houses is above 100\n let wVector = this.HOUSING_WEIGHTS; // Copy of the housing weights\n let fVector = [0, 0, 0, 0, 0, 0, 0, 0]; // Fluctuations vector\n let wSum = 0;\n if (this._occupiedHouses > 10) {\n for (let i = 0; i < wVector.length; i++) {\n // Divide by 40 for +/- 1%\n fVector[i] = wVector[i] * (1 + ((Math.random() - 0.5) / 40));\n wSum += fVector[i];\n }\n } else {\n fVector = wVector;\n wSum = 1;\n }\n\n // Generate the housing vector\n let vSum = 0; // The sum of the housing vector's elements\n for (let i = 0; i < wVector.length; i++) {\n this._hv[i] = Math.round(this._occupiedHouses * fVector[i] / wSum);\n vSum += this._hv[i];\n }\n\n // Correct the rounding error here\n // A positive rDiff means there are more houses than there should be\n // A negative rDiff means there are fewer houses than there should be\n // Rounding errors are corrected by ideally adding/removing houses of the\n // smallest household size, which only adds/removes one person at a time\n let rDiff = vSum - this._occupiedHouses;\n if (this._occupiedHouses === 1) {\n // This is to introduce the really interesting case of having a city with\n // a population of 1\n this._hv = [1, 0, 0, 0, 0, 0, 0, 0];\n } else {\n if (rDiff !== 0) {\n // Traverse the array from beginning to end\n // Find the first element such that adding/subtracting rDiff produces\n // zero or a positive number\n let i = 0;\n for (; i < this._hv.length; i++)\n if (this._hv[i] - rDiff >= 0) break;\n\n this._hv[i] -= rDiff;\n\n // console.log(\"[HousingManager]: Corrected a rounding error of \" + rDiff + \" by adjusting index \" + i);\n }\n }\n }\n }", "function pairingZeroTwoSide(RoundName) {\n var scoreBoardSheet = ss.getSheetByName(SHEET_SCOREBOARD);\n var range = scoreBoardSheet.getRange(4, 2, TEAM_NUMBER);\n var values = range.getValues();\n shuffleArray(values);\n var rand;\n var properOpponent;\n var govIndex=0;\n var newGov = [];\n var newOpp = [];\n var itr=TEAM_NUMBER*40;\n var RepresentativeArray=obtainAffiliationNumbers();\n var non_affiliated_rounds=nonAffiliatedMatches(RepresentativeArray,TEAM_NUMBER);\n while(values.length>Number(non_affiliated_rounds*2)&&LIMIT_INTER_AFF_ROUNDS)\n {\n rand= values.indexOf(findTeamRepresented(RepresentativeArray,values));// assignation before looping on random values\n properOpponent=false;\n var random = Math.ceil(Math.random() *2 );//To allow most represented to be opposition and gov\n if(random%2==0){\n newGov.push(values[rand]);\n values.splice(rand,1);\n while(!properOpponent){\n rand= randomIndexTeam(values.length);\n if(obtainAffiliationDebater(newGov[govIndex])!=obtainAffiliationDebater(values[rand])){\n updateRepresented(RepresentativeArray,values[rand]);// Counterpart to keep findTeamRepresented from getting out of sync with the values array.\n newOpp.push(values[rand]);\n values.splice(rand,1);\n govIndex+=1;\n properOpponent=true;\n }\n itr-=1;\n if(itr<0)\n throw \"Computation limit exceeded. Regenerate round\";// Prevents infinite looping when randomness doesnt prioritize spreading big teams.\n }\n }\n else{\n newOpp.push(values[rand]);\n values.splice(rand,1);\n while(!properOpponent){\n rand= randomIndexTeam(values.length);\n if(obtainAffiliationDebater(newOpp[govIndex])!=obtainAffiliationDebater(values[rand])){\n updateRepresented(RepresentativeArray,values[rand]);// Counterpart to keep findTeamRepresented from getting out of sync with the values array\n newGov.push(values[rand]);\n values.splice(rand,1);\n govIndex+=1;\n properOpponent=true;\n }\n itr-=1;\n if(itr<0)\n throw \"Computation limit exceeded. Regenerate round\";// Prevents infinite looping when unforseen bugs occur.\n }\n }\n }\n for (var row in values) {\n var rand = Math.ceil(Math.random() *2 );//(Number(TEAM_NUMBER))\n if(rand%2==0&&newGov.length<Number(TEAM_NUMBER/2)){\n newGov.push(values[row]);\n }\n else if(newOpp.length<Number(TEAM_NUMBER/2)){\n newOpp.push(values[row]);\n }\n else{\n newGov.push(values[row]);\n }\n }\n ss.getSheetByName(RoundName).getRange(3, 2,newGov.length,1).setValues(newGov);\n ss.getSheetByName(RoundName).getRange(3, 3,newOpp.length,1).setValues(newOpp);\n}", "function bishops (positions, w) {\n\n}", "calcSlices(newActiveIndex) {\n const {frames} = this.state;\n const {rangeUp, rangeDown} = this.calcRangeUpAndDown(newActiveIndex);\n const up = frames.slice(newActiveIndex - rangeUp, newActiveIndex);\n const down = frames.slice(newActiveIndex, newActiveIndex + rangeDown);\n return {up, down};\n }", "function getSystemDistance(g1, s1, g2, s2) {\r\n\t//correct count when galaxies are differents\r\n\tif (g2 == g1) {\r\n\t\treturn s2 - s1;\r\n\t} else if (g2 > g1) {\r\n\t\treturn Math.max(0, g2 - g1 - 1) * 499 \r\n\t\t\t\t+ parseInt(500 - s1, 10)\r\n\t\t\t\t+ parseInt(s2, 10);\r\n\t} else { //g1 > g2\r\n\t\treturn Math.max(0, g1 - g2 - 1) * 499 \r\n\t\t\t\t+ parseInt(500 - s2, 10)\r\n\t\t\t\t+ parseInt(s1, 10);\r\n\t}\r\n}", "getSecondFittest() {\n var maxFit1 = 0;\n var maxFit2 = 0;\n for (var i = 0; i < this.individuals.length; i++) {\n if (this.individuals[i].fitness > this.individuals[maxFit1].fitness) {\n maxFit2 = maxFit1;\n maxFit1 = i;\n } else if (this.individuals[i].fitness > this.individuals[maxFit2].fitness) {\n maxFit2 = i;\n }\n }\n return this.individuals[maxFit2];\n }", "function makeGraves() {\n for (i=0;i<smallGravePositionsBack.length;i++) {\n smallGraves.push({posX:(smallGravePositionsBack[i]),posY:360,sizeX:53,sizeY:15});\n }\n for (i=0;i<smallGravePositionsFront.length;i++) {\n smallGraves.push({posX:(smallGravePositionsFront[i]),posY:470,sizeX:53,sizeY:15});\n }\n}", "function identifyNeighbours(x_max,y_max){\n\t \t\tvar traversalIndex = 0;\n\n\t \t\t//inner square\n\t \t\tfor (var i = 0; i < x_max*y_max; i++) {\n\t \t\t\ttraversalIndex = (i % y_max);\n\n\t \t\tif((traversalIndex != 0) && (traversalIndex != (y_max-1)) \n\t \t\t&& (i <= ((y_max)*(x_max-1)-1)) && (i >= y_max+1) ){\n\t \t\t\tspaces[i].adjacentNeighbours = spaces[(i-1)].holdsMine\n\t \t\t\t\t\t\t\t\t\t + spaces[i+1].holdsMine\n\t \t\t\t\t\t\t\t\t\t + spaces[i+y_max].holdsMine\n\t \t\t\t\t\t\t\t\t\t + spaces[i-y_max].holdsMine\n\t \t\t\t\t\t\t\t\t\t + spaces[(i-1)+y_max].holdsMine\n\t \t\t\t\t\t\t\t\t\t + spaces[(i-1)-y_max].holdsMine\n\t \t\t\t\t\t\t\t\t\t + spaces[(i+1)+y_max].holdsMine\n\t \t\t\t\t\t\t\t\t\t + spaces[(i+1)-y_max].holdsMine;\n\t \t\t\tspaces[i].neighbourIndexList.push( (i+1),(i-1),(i+y_max),(i-y_max),\n\t \t\t\t\t\t\t\t\t\t\t\t\t(i-1+y_max),(i-1-y_max),\n\t \t\t\t\t\t\t\t\t\t\t\t\t(i+1+y_max),(i+1-y_max));\n\t\t\t\t}\n\t\t\t// console.log(isNaN(spaces[i].holdsMine))\n\t\t\t}\n\n\t\t\t//four courners\n\t\t\tspaces[0].adjacentNeighbours = spaces[y_max].holdsMine\n\t\t\t\t\t\t\t\t\t + spaces[y_max+1].holdsMine\n\t\t\t\t\t\t\t\t\t + spaces[1].holdsMine;\n\n\t\t\tspaces[0].neighbourIndexList.push(y_max,(y_max+1),1);\n\n\t\t\tspaces[y_max-1].adjacentNeighbours = spaces[(y_max-1) - 1].holdsMine\n\t\t\t\t\t\t\t\t\t\t\t + spaces[(y_max-1) + y_max].holdsMine\n\t\t\t\t\t\t\t\t\t\t\t + spaces[(y_max-1) + y_max-1].holdsMine;\n\n\t\t\tspaces[(y_max-1)].neighbourIndexList.push((y_max-1-1), (y_max-1+y_max), (y_max-1+y_max-1));\n\n\n\t\t\tspaces[y_max*x_max-1].adjacentNeighbours = spaces[(y_max*x_max-1)-1].holdsMine\n\t\t\t\t\t\t\t\t\t\t\t\t + spaces[(y_max*x_max-1)-y_max].holdsMine\n\t\t\t\t\t\t\t\t\t\t\t\t + spaces[(y_max*x_max-1)-(y_max-1)].holdsMine;\n\n\t\t\tspaces[y_max*x_max-1].neighbourIndexList.push((y_max*x_max-1)-1, (y_max*x_max-1)-y_max, (y_max*x_max-1)-(y_max-1));\n\n\n\t\t\tspaces[(x_max *(y_max-1))].adjacentNeighbours = spaces[(x_max *(y_max-1))+ 1].holdsMine\n + spaces[(x_max *(y_max-1))-y_max].holdsMine\n + spaces[(x_max *(y_max-1))-(y_max)+1].holdsMine; \n\n spaces[(x_max *(y_max-1))].neighbourIndexList.push((x_max *(y_max-1))+ 1, (x_max *(y_max-1))-y_max,(x_max *(y_max-1))-(y_max)+1);\n\n\n for(var k = 1; k < y_max-1; k++){\n\n\t\t \t\t//left column\n\t\t \t\tspaces[k].adjacentNeighbours = spaces[k-1].holdsMine\n\t\t \t\t\t\t\t\t\t\t + spaces[k+1].holdsMine\n\t\t \t\t\t\t\t\t\t\t + spaces[k+y_max].holdsMine\n\t\t \t\t\t\t\t\t\t\t + spaces[k+y_max - 1].holdsMine\n\t\t \t\t\t\t\t\t\t\t + spaces[k+y_max + 1].holdsMine;\n\n\t\t \t\tspaces[k].neighbourIndexList.push(k-1,k+1,k+y_max,k+y_max-1,k-y_max+1);\n\n\n\t\t \t\t//right column\n\t\t \t\tspaces[x_max *(y_max-1) + k].adjacentNeighbours = spaces[ (x_max *(y_max-1) + k) + 1].holdsMine\n\t\t \t\t\t\t\t\t\t\t+ spaces[x_max *(y_max-1) + k - 1].holdsMine\n\t\t\t\t\t\t\t\t\t + spaces[x_max *(y_max-1) + k - y_max].holdsMine\n\t\t\t\t\t\t\t\t\t + spaces[x_max *(y_max-1) + k - y_max + 1].holdsMine\n\t\t\t\t\t\t\t\t\t + spaces[x_max *(y_max-1) + k - y_max - 1].holdsMine;\n\n\t\t\t\tspaces[x_max *(y_max-1) + k].neighbourIndexList.push((x_max *(y_max-1) + k) + 1,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t x_max *(y_max-1) + k - 1,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t x_max *(y_max-1) + k - y_max,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t x_max *(y_max-1) + k - y_max + 1,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t x_max *(y_max-1) + k - y_max - 1);\n\t\t \t\t\n\t\t \t\t//top row\n\t\t \t\tspaces[k*y_max].adjacentNeighbours = spaces[k*y_max + 1].holdsMine\n\t\t \t\t\t\t\t\t\t\t\t + spaces[(k+1)*y_max].holdsMine\n\t\t \t\t\t\t\t\t\t\t\t + spaces[(k-1)*y_max].holdsMine\n\t\t \t\t\t\t\t\t\t\t\t + spaces[(k+1)*y_max + 1].holdsMine\n\t\t \t\t\t\t\t\t\t\t\t + spaces[(k-1)*y_max + 1].holdsMine;\n\n\t\t \t\tspaces[k*y_max].neighbourIndexList.push(k*y_max + 1,\n\t\t \t\t\t\t\t\t\t\t\t\t\t\t(k+1)*y_max,\n\t\t \t\t\t\t\t\t\t\t\t\t\t\t(k-1)*y_max,\n\t\t \t\t\t\t\t\t\t\t\t\t\t\t(k+1)*y_max + 1,\n\t\t \t\t\t\t\t\t\t\t\t\t\t\t(k-1)*y_max + 1);\n\n\t\t \t\t//bottom row\n\t\t \t\tspaces[(k+1)*(y_max)-1].adjacentNeighbours = spaces[(k+1)*(y_max)-1 - 1].holdsMine\n\t\t \t\t\t\t\t\t\t\t\t\t\t+ spaces[(k+1)*(y_max)-1 - y_max].holdsMine\n\t\t \t\t\t\t\t\t\t\t\t\t + spaces[(k+1)*(y_max)-1 + y_max].holdsMine\n\t\t \t\t\t\t\t\t\t\t\t\t\t+ spaces[(k+1)*(y_max)-1 - y_max-1].holdsMine\n\t\t \t\t\t\t\t\t\t\t\t\t + spaces[(k+1)*(y_max)-1 +y_max-1].holdsMine;\n\n\n\t\t\t\tspaces[(k+1)*(y_max)-1].neighbourIndexList.push((k+1)*(y_max)-1 - 1,\n\t\t\t\t\t\t\t\t\t\t\t\t \t\t\t (k+1)*(y_max)-1 - y_max,\n\t\t\t\t\t\t\t\t\t\t\t\t (k+1)*(y_max)-1 + y_max,\n\t\t\t\t\t\t\t\t\t\t\t\t (k+1)*(y_max)-1 - y_max-1,\n\t\t\t\t\t\t\t\t\t\t\t\t (k+1)*(y_max)-1 + y_max-1);\n\t \t\t}\n\t \t}", "generateScan() {\n //let scan = [];\n const rows = [this.shipLocation.qy - 1, this.shipLocation.qy, this.shipLocation.qy + 1];\n const cols = [this.shipLocation.qx - 1, this.shipLocation.qx, this.shipLocation.qx + 1];\n let scan = rows.map( (row) => {\n let result = cols.map( (col) => {\n if( row >= 1 && row <= 8 && col >= 1 && col <= 8 ) {\n const numEnemies = this.findNearby( row, col );\n if( row === this.shipLocation.qy && col === this.shipLocation.qx ) {\n return <div className=\"col warp-cell player-cell\">{numEnemies}</div>\n }\n else {\n return <div className=\"col warp-cell\">{numEnemies}</div>\n }\n }\n else {\n return <div className=\"col warp-cell cannot-warp\">-</div>\n }\n });\n return <div className=\"row\">{result}</div>;\n });\n return scan;\n }", "function topple() {\n for (let x = 0; x < width; x++) {\n for (let y = 0; y < height; y++) {\n nextpiles[x][y] = sandpiles[x][y];\n }\n }\n\n // adjust the critical height if needed\n criticalHeight = 4;\n for (let x = 0; x < width; x++) {\n for (let y = 0; y < height; y++) {\n let num = sandpiles[x][y];\n if (num >= criticalHeight) {\n nextpiles[x][y] -= 4;\n if (x + 1 < width)\n nextpiles[x + 1][y]++;\n if (x - 1 >= 0)\n nextpiles[x - 1][y]++;\n if (y + 1 < height)\n nextpiles[x][y + 1]++;\n if (y - 1 >= 0)\n nextpiles[x][y - 1]++;\n }\n }\n }\n\n let tmp = sandpiles;\n sandpiles = nextpiles;\n nextpiles = tmp;\n}", "function control2Sides(dataGrid,newGov,newOpp){\n var indexGov;\n var indexOpp;\n var temp;\n var deficiencyTeams=createArray(2,TEAM_NUMBER);\n for(var i=0;i<TEAM_NUMBER;i++){\n deficiencyTeams[0][i]=String(dataGrid[i][1]);\n deficiencyTeams[1][i]=Number(dataGrid[i][4]-dataGrid[i][5]);\n }\n for(var i=0;i<newGov.length;i++){\n indexGov=deficiencyTeams[0].indexOf(String(newGov[i]));\n indexOpp=deficiencyTeams[0].indexOf(String(newOpp[i])); \n if(indexGov==-1||indexOpp==-1){\n throw \"Error : Invalid state function control2sides\";\n }else{\n if(Number(deficiencyTeams[1][indexGov])>Number(deficiencyTeams[1][indexOpp])){\n temp=newGov[i];\n newGov[i]=newOpp[i];\n newOpp[i]=temp;\n }\n }\n }\n}", "function robotStep(){\n \n if (difficulty==1){\n let stepCords = free_coordinates[Math.floor(Math.random()*free_coordinates.length)];\n drawStep(stepCords[0],stepCords[1],robot_symbol)\n }\n else if (difficulty==3){\n\n var bb = 0\n let matches = 0\n var best_matches = {}\n for (let i = 0; i < wins.length; i++) {\n matches = 0\n for (let j = 0; j < size; j++) {\n if (isArrayInArray(x_coordinates,wins[i][j])) {\n matches += 1\n bb=i\n }\n }\n best_matches[wins[bb]] = matches\n\n }\n\n for (let i = 0; i < wins.length; i++) {\n matches = 0\n for (let j = 0; j < size; j++) {\n if (isArrayInArray(o_coordinates,wins[i][j])) {\n matches += 1\n bb=i\n }\n }\n best_matches[wins[bb]] = matches\n }\n\n let maxValue = 0\n let maxKey = 0\n for (const [key, value] of Object.entries(best_matches)) {\n if (value>=maxValue) {\n maxValue=value\n maxKey = key\n }\n }\n let nums = []\n let num = \"\"\n for (let i = 0; i < maxKey.length; i++) {\n if (maxKey[i]==\",\"){\n nums.push(+num)\n num = \"\"\n }\n else{\n num+=maxKey[i]\n }\n }\n nums.push(+num)\n\n best_matches = []\n\n let sm = []\n for (let i = 0; i <= nums.length/2+2; i+=2) {\n sm.push(nums[i])\n sm.push(nums[i+1])\n best_matches.push(sm)\n sm = []\n \n }\n for (let i = 0; i < best_matches.length; i++) {\n if(isArrayInArray(free_coordinates,best_matches[i])){\n let stepCords2 = best_matches[i]\n drawStep(stepCords2[0],stepCords2[1],robot_symbol)\n return\n }\n }\n if (true){\n try {\n let stepCords = free_coordinates[Math.floor(Math.random()*free_coordinates.length)];\n drawStep(stepCords[0],stepCords[1],robot_symbol)\n } catch (error) {\n winner()\n }\n\n \n }\n }\n else if (difficulty==2){\n if (Math.random()>=0.5) {\n \n var bb = 0\n let matches = 0\n var best_matches = {}\n for (let i = 0; i < wins.length; i++) {\n matches = 0\n for (let j = 0; j < size; j++) {\n if (isArrayInArray(x_coordinates,wins[i][j])) {\n matches += 1\n bb=i\n }\n }\n best_matches[wins[bb]] = matches\n\n }\n\n for (let i = 0; i < wins.length; i++) {\n matches = 0\n for (let j = 0; j < size; j++) {\n if (isArrayInArray(o_coordinates,wins[i][j])) {\n matches += 1\n bb=i\n }\n }\n best_matches[wins[bb]] = matches\n }\n\n let maxValue = 0\n let maxKey = 0\n for (const [key, value] of Object.entries(best_matches)) {\n if (value>=maxValue) {\n maxValue=value\n maxKey = key\n }\n }\n let nums = []\n let num = \"\"\n for (let i = 0; i < maxKey.length; i++) {\n if (maxKey[i]==\",\"){\n nums.push(+num)\n num = \"\"\n }\n else{\n num+=maxKey[i]\n }\n }\n nums.push(+num)\n\n best_matches = []\n\n let sm = []\n for (let i = 0; i <= nums.length/2+2; i+=2) {\n sm.push(nums[i])\n sm.push(nums[i+1])\n best_matches.push(sm)\n sm = []\n \n }\n\n for (let i = 0; i < best_matches.length; i++) {\n if(isArrayInArray(free_coordinates,best_matches[i])){\n let stepCords2 = best_matches[i]\n drawStep(stepCords2[0],stepCords2[1],robot_symbol)\n return\n }\n \n }\n if (true){\n try {\n let stepCords = free_coordinates[Math.floor(Math.random()*free_coordinates.length)];\n drawStep(stepCords[0],stepCords[1],robot_symbol)\n } catch (error) {\n winner()\n }\n }\n}\n \n else{\n let stepCords = free_coordinates[Math.floor(Math.random()*free_coordinates.length)];\n drawStep(stepCords[0],stepCords[1],robot_symbol)\n }\n\n \n }\n\n}", "function greedyPoo(items) {\n var resultsGreed = [];\n let currentSize = 0;\n let currentValue = 0;\n \n sortedStuff(greedItems).forEach(item => {\n if(currentSize + item.size <= capacity) {\n resultsGreed.push(item.index);\n currentSize += item.size;\n currentValue += item.value;\n } \n })\n return {resultsGreed, currentSize, currentValue};\n }", "function getGaps(requestedFloor) {\n for (var i = 0; i < listElevators.length; i++) {\n gapList.push(Math.abs(requestedFloor - listElevators[i].current_position));\n }\n}", "moves2() {\n if (this.lastMove !== null) {\n return nextMoves2[this.lastMove / 3 | 0];\n } else {\n return allMoves2;\n }\n }", "get pointsToApply() {\n let pointsToApply = this.unmodifiedPointsToApply\n if (this._parent.useLocationModifiers) {\n if ([hitlocation.EXTREMITY, hitlocation.LIMB].includes(this._parent.hitLocationRole)) {\n return Math.min(pointsToApply, Math.floor(this._parent.locationMaxHP))\n }\n }\n return pointsToApply\n }", "computeFitness()\n {\n this.MaxFitnessGeneration = 0;\n this.sumOfFitness = 0;\n let boardValues = [];\n let temp_intersection = 0;\n let tempCounter = 0;\n for (let i = 0 ; i < this.genomeLength ; i++)\n boardValues[i] = [];\n \n for ( let player = 0 ; player < this.maxPopulation ; player++)\n {\n // Make the interference board zero \n for(let i = 0 ; i < this.genomeLength ;i++)\n for(let j = 0 ; j < this.genomeLength ;j++)\n boardValues[i][j] = 0;\n // Variable to Track the number of paths being Intersected.\n \n for ( let queen = 0 ; queen < this.genomeLength ; queen++)\n this.computeIntersectionScores(boardValues,queen,this.population[player].genomeSequence[queen])\n \n let interference = 0; \n // Compute interference Scores\n for( let i = 0 ; i < this.genomeLength ; i++)\n {\n let posOfQueen = this.population[player].genomeSequence[i];\n interference += boardValues[i][posOfQueen]\n }\n \n \n \n let score = this.N*((this.N)-1) - interference;\n\n var arr = this.population[player].genomeSequence;\n var unique = arr.filter((v, i, a) => a.indexOf(v) === i);\n\n // if(unique.length != this.genomeLength)\n // {\n // score = score - 4*(this.genomeLength - unique.length );\n // if(score < 0) score = 1\n // console.log(\"Errrorrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr\")\n // }\n\n // if( (this.genomeLength - unique.length) > 2 )\n // {\n // tempCounter++;\n // }\n \n \n this.population[player].matchedChar = score;\n\n // Compute Fitness Score\n let fitnessScore = this.fitnessFunction(score,this.fitnessMethod);\n \n // Assign the score to the GENE Class \n this.population[player].fitnessScore = fitnessScore;\n\n // Compute Total Sum of \n this.sumOfFitness += fitnessScore\n\n // Identify Maximum Fitness and the Gene which has max fitness\n if(fitnessScore > this.MaxFitnessGeneration)\n {\n this.MaxFitnessGeneration = fitnessScore;\n this.bestGeneindex = player;\n this.bestGeneScore = score;\n }\n }\n\n\n for ( let i = 0 ; i < this.maxPopulation; i++)\n this.population[i].fitnessProbabilty = this.population[i].fitnessScore / this.sumOfFitness;\n \n // console.log(\" PENALTY AWARDECD: \", tempCounter);\n return this.MaxFitnessGeneration ;\n }", "function placeVerticalPlayerTwo(n, boat) {\n for (let i = 0; i < boat * 8; i+=8) {\n let square = $('#sqTwo' + (n + i));\n $(square).addClass('ship-two');\n square.click(function(e) {\n e.preventDefault();\n hitShip();\n playerOneScore += 1;\n $('.second').html(playerOneScore);\n })\n }\n}", "function countDoublesPR(){\n for(i = 0; i < window.targetsToAttackPR.length; i++){\n \n var isDouble = false;\n var xi = window.targetsToAttackPR[i].x;\n var yi = window.targetsToAttackPR[i].y;\n \n for(j = 0; j < window.targetsToAttackPR.length; j++){\n \n var xj = window.targetsToAttackPR[j].x;\n var yj = window.targetsToAttackPR[j].y;\n \n if(i != j && xi == xj && yi == yj){\n isDouble = true;\n break;\n }\n }\n \n if(isDouble)\n alert(xi + \"|\" + yi);\n }\n}", "efficiency(pt1, pt2) {\n\t\t\tvar intermediatePt = new psych.PointBuilder()\n\t\t\t\t.withElevation(pt2.properties.elevation)\n\t\t\t\t.withHumidityRatio(pt1.properties.W)\n\t\t\t\t.withEnthalpy(pt2.properties.h)\n\t\t\t\t.build();\n\t\t\tvar saturationPt = new psych.PointBuilder()\n\t\t\t\t.withElevation(pt2.properties.elevation)\n\t\t\t\t.withRelativeHumidity(100)\n\t\t\t\t.withEnthalpy(pt2.properties.h)\n\t\t\t\t.build();\n\t\t\treturn (pt2.properties.W - intermediatePt.properties.W) /\n\t\t\t\t(saturationPt.properties.W - intermediatePt.properties.W); // %\n\t\t}", "function GetPath2() : int {\n\t\tnumberOfHops = 0; \n\t\tnumberOfHops1 = 0; \n\t\tvar ToMovePos : int; \n\t\tvar ToMovePos2 : int; \n\n\t\tvar i : int = 0;\n\t\tfor(var a : int = 0; a < ClosedNodes.Length; a++){ \n\t\t\tif (ClosedNodes[a] != 0){ \n\t\t\t\ti++; \n\t\t\t\t//Debug.Log(parent_Closed[a]+\" \"+ClosedNodes[a]);\n\t\t\t\t} }\n\n\t\tvar match_name = targetLeaf;\n\t\tfor(var b : int = (i-1); b >= 0 ; b--){\n\t\t\tif (ClosedNodes[b] == match_name){\n\t\t\t\tnumberOfHops++;\n\t\t\t\tmatch_name = parent_Closed[b];\n\t\t\t\tif (match_name == frogLeaf ){\n\t\t\t\t\tToMovePos = ClosedNodes[b];\n\t\t\t\t\tb = -20;\n\t\t\t\t\t//Debug.Log(\"ToMovePos \"+ToMovePos);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t\tvar match_name2 = targetLeaf2;\n\t\t\tfor(var c : int = (i-1); c >= 0 ; c--){\n\t\t\tif (ClosedNodes[c] == match_name2){\n\t\t\t\tnumberOfHops1++;\n\t\t\t\t//Debug.Log(parent_Closed[b]);\n\t\t\t\tmatch_name2 = parent_Closed[c];\n\t\t\t\tif (match_name2 == frogLeaf ){\n\t\t\t\t\tToMovePos2 = ClosedNodes[c];\n\t\t\t\t\tc = -20;\n\t\t\t\t\t//Debug.Log(\"ToMovePos \"+ToMovePos);\n\t\t\t\t}\n\t\t\t}\n\t\t} \n\n\t\tif (numberOfHops1 !=0){\n\t\t\tif (numberOfHops1 < numberOfHops){\n\t\t\t\t//Debug.Log(\"ToMovePos2 \"+ToMovePos2);\n\t\t\t\treturn ToMovePos2;\n\t\t\t\t}\n\t\t\telse if(numberOfHops !=0){\n\t\t\t\t\t//Debug.Log(\"ToMovePos \"+ToMovePos); \n\t\t\t\t\treturn ToMovePos;\n\t\t\t\t\t}\n\t\t\t\t else{\n\t\t\t\t \t//Debug.Log(\"ToMovePos2 \"+ToMovePos2); \n\t\t\t\t \treturn ToMovePos2;\n\t\t\t\t \t}\n\t\t\t}\n\t\telse {\n\t\t\t//Debug.Log(\"ToMovePos \"+ToMovePos); \n\t\t\treturn ToMovePos;\n\t\t\t}\n\t}", "function placeVertical(n, boat) {\n for (let i = 0; i < boat * 8; i+=8) {\n let square = $('#sqOne' + (n + i));\n $(square).addClass('ship');\n square.click(function(e) {\n e.preventDefault();\n hitShip();\n playerTwoScore += 1;\n $('.second').html(playerTwoScore);\n })\n }\n}", "calc_range() {\n let z = this.zoom / this.drug.z\n let zk = (1 / z - 1) / 2\n\n let range = this.y_range.slice()\n let delta = range[0] - range[1]\n range[0] = range[0] + delta * zk\n range[1] = range[1] - delta * zk\n\n return range\n }", "function setUpSpotLinks() {\n\t\n\t\tvar spotsPerLine = [1,2,3,4,13,12,11,10,9,10,11,12,13,4,3,2,1];\n\t\n\t\tfor(var y = 0; y < 17; y++){\n \n\t\t\tfor(var x = 0; x < spotsPerLine[y]; x++){\n \n\t\t\t\tvar neighbores = getNeighboreSpots(spotMatrix[y][x]);\n\t\t\t\tif(neighbores.length > 6 || neighbores.length < 2) {\n \n\t\t\t\t\tconsole.debug(\"Linking Neighbores Length Error:\" + neighbores.length);\n \n } // end if statement\n\t\t\t\t\n\t\t\t\tfor(var i = 0; i<neighbores.length; i++) {\n \n\t\t\t\t\tif(neighbores[i].screenX > spotMatrix[y][x].screenX && neighbores[i].screenY < spotMatrix[y][x].screenY) { //Northeast\n \n\t\t\t\t\t\tspotMatrix[y][x].northeast = neighbores[i];\n \n\t\t\t\t\t} else if(neighbores[i].screenX > spotMatrix[y][x].screenX && neighbores[i].screenY == spotMatrix[y][x].screenY) { //East\n \n\t\t\t\t\t\tspotMatrix[y][x].east = neighbores[i];\n \n\t\t\t\t\t} else if(neighbores[i].screenX > spotMatrix[y][x].screenX && neighbores[i].screenY > spotMatrix[y][x].screenY) { //Southeast\n \n\t\t\t\t\t\tspotMatrix[y][x].southeast = neighbores[i];\n \n\t\t\t\t\t} else if(neighbores[i].screenX < spotMatrix[y][x].screenX && neighbores[i].screenY > spotMatrix[y][x].screenY) { //Southwest\n \n\t\t\t\t\t\tspotMatrix[y][x].southwest = neighbores[i];\n \n\t\t\t\t\t} else if(neighbores[i].screenX < spotMatrix[y][x].screenX && neighbores[i].screenY == spotMatrix[y][x].screenY) { //West\n \n\t\t\t\t\t\tspotMatrix[y][x].west = neighbores[i];\n \n\t\t\t\t\t} else if(neighbores[i].screenX < spotMatrix[y][x].screenX && neighbores[i].screenY < spotMatrix[y][x].screenY) { //Northwest\n \n\t\t\t\t\t\tspotMatrix[y][x].northwest = neighbores[i];\n \n\t\t\t\t\t} else {\n \n\t\t\t\t\t\tconsole.debug(\"Spot Linking Error! No Direction For: From-(\" + x + \",\" + y + \") To-(\" + neighbores[i].x + \",\" + neighbores[i].y + \")\");\n \n } // end if else statement\n \n\t\t\t\t} // end for loop i\n \n\t\t\t} // end for loop x\n \n\t\t} // end for loop y\n \n\t} // end function setUpSpotLinks()", "function setColors(){\n let randNum;\n let randNum0;\n var thePlace;\n var vCount = 0;\n var pop1Count = 0;\n var pop2Count = 0;\n // finds random spots for population 1\n while(pop1Count != calculatePop1()){\n randNum = Math.floor(Math.random() * (dims.value));\n randNum0 = Math.floor(Math.random() * (dims.value));\n thePlace = table.children[0].children[randNum].children[randNum0];\n if(thePlace.innerHTML != \"1\"){\n thePlace.style.backgroundColor = popXcolor.value;\n thePlace.innerHTML = \"1\";\n thePlace.style.color = popXcolor.value;\n thePlace.style.fontSize = '5px';\n pop1Count++;\n }\n }\n // finds random spots for population 2\n while(pop2Count != calculatePop2()){\n randNum = Math.floor(Math.random() * (dims.value));\n randNum0 = Math.floor(Math.random() * (dims.value));\n thePlace = table.children[0].children[randNum].children[randNum0];\n if(thePlace.innerHTML != \"1\" && thePlace.innerHTML != \"2\"){\n thePlace.style.backgroundColor = popYcolor.value;\n thePlace.innerHTML = \"2\";\n thePlace.style.color = popYcolor.value;\n thePlace.style.fontSize = '5px';\n pop2Count++;\n }\n }\n // finds vacant spots & only sets them in spots that have not been filled\n // by population 2\n while(vCount != calculateV()){\n randNum = Math.floor(Math.random() * (dims.value));\n randNum0 = Math.floor(Math.random() * (dims.value));\n thePlace = table.children[0].children[randNum].children[randNum0];\n if(thePlace.innerHTML != \"1\" && thePlace.innerHTML != \"2\" && thePlace.innerHTML != \"0\"){\n thePlace.style.backgroundColor = \"#FFFFFF\";\n thePlace.innerHTML = \"0\";\n thePlace.style.color = \"#FFFFFF\";\n thePlace.style.fontSize = '5px';\n vCount++;\n }\n }\n}", "function checkSpace()\n\t\t{\n\n\t\t\tvar nb =random(3) ;\n\t\t\tvar nb2 = random(3);\n\t\t\tvar tileNew = $('body').find('[data-x='+nb+'][data-y='+nb2+']');\n\t\t\tif(tileNew.length === 0)\n\t\t\t{\n\t\t\t\treturn {x:nb , y: nb2};\n\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tcheckSpace();\n\t\t\t}\n\t\t}", "function PopulateMapTunnels() {\n\tvar roomPositions = [];\n\tfor(var i = 0; i < gridArr.length; i++) { // find and store the start position\n\t\tif(gridArr[i].room == \"ST\"){\n\t\t\troomPositions.push(i);\n\t\t\tbreak;\n\t\t}\n\t}\n\tfor(var i = 0; i < gridArr.length; i++) { // find and store the central postion\n\t\tif(gridArr[i].room == \"CN\"){\n\t\t\troomPositions.push(i);\n\t\t\tbreak;\n\t\t}\n\t}\n\tfor(var i = 0; i < gridArr.length; i++) { // find and store the north west postion\n\t\tif(gridArr[i].room == \"NW\"){\n\t\t\troomPositions.push(i);\n\t\t\tbreak;\n\t\t}\n\t}\n\tfor(var i = 0; i < gridArr.length; i++) { // find and store the north east position\n\t\tif(gridArr[i].room == \"NE\"){\n\t\t\troomPositions.push(i);\n\t\t\tbreak;\n\t\t}\n\t}\n\tfor(var i = 0; i < gridArr.length; i++) { // find and store the south west postion\n\t\tif(gridArr[i].room == \"SW\"){\n\t\t\troomPositions.push(i);\n\t\t\tbreak;\n\t\t}\n\t}\n\tfor(var i = 0; i < gridArr.length; i++) { // find and store the south east position\n\t\tif(gridArr[i].room == \"SE\"){\n\t\t\troomPositions.push(i);\n\t\t\tbreak;\n\t\t}\n\t}\n\tswitch(Dice(3)) { // randomly pick the shape \n\t\tcase 1: // S pattern\n\t\t\ttunnel = BestPathXY(roomPositions[0],roomPositions[3]); // ST to NE\n\t\t\tfor(i = 0; i < tunnel.length; i++) {\n\t\t\t\tgridArr[tunnel[i]].open = 1;\n\t\t\t\tif(gridArr[tunnel[i]].room == \"\") {\n\t\t\t\t\tgridArr[tunnel[i]].room = \"T\";\n\t\t\t\t}\n\t\t\t}\n\t\t\ttunnel = BestPathXY(roomPositions[3],roomPositions[2]); // NE to NW\n\t\t\tfor(i = 0; i < tunnel.length; i++) {\n\t\t\t\tgridArr[tunnel[i]].open = 1;\n\t\t\t\tif(gridArr[tunnel[i]].room == \"\") {\n\t\t\t\t\tgridArr[tunnel[i]].room = \"T\";\n\t\t\t\t}\n\t\t\t}\n\t\t\ttunnel = BestPathXY(roomPositions[2],roomPositions[1]); // NW to CN\n\t\t\tfor(i = 0; i < tunnel.length; i++) {\n\t\t\t\tgridArr[tunnel[i]].open = 1;\n\t\t\t\tif(gridArr[tunnel[i]].room == \"\") {\n\t\t\t\t\tgridArr[tunnel[i]].room = \"T\";\n\t\t\t\t}\n\t\t\t}\n\t\t\ttunnel = BestPathXY(roomPositions[1],roomPositions[5]); // CN to SE\n\t\t\tfor(i = 0; i < tunnel.length; i++) {\n\t\t\t\tgridArr[tunnel[i]].open = 1;\n\t\t\t\tif(gridArr[tunnel[i]].room == \"\") {\n\t\t\t\t\tgridArr[tunnel[i]].room = \"T\";\n\t\t\t\t}\n\t\t\t}\n\t\t\ttunnel = BestPathXY(roomPositions[5],roomPositions[4]); // SE to SW\n\t\t\tfor(i = 0; i < tunnel.length; i++) {\n\t\t\t\tgridArr[tunnel[i]].open = 1;\n\t\t\t\tif(gridArr[tunnel[i]].room == \"\") {\n\t\t\t\t\tgridArr[tunnel[i]].room = \"T\";\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak;\n\t\tcase 2: // X pattern\n\t\t\ttunnel = BestPathXY(roomPositions[0],roomPositions[1]); // ST to CN\n\t\t\tfor(i = 0; i < tunnel.length; i++) {\n\t\t\t\tgridArr[tunnel[i]].open = 1;\n\t\t\t\tif(gridArr[tunnel[i]].room == \"\") {\n\t\t\t\t\tgridArr[tunnel[i]].room = \"T\";\n\t\t\t\t}\n\t\t\t}\n\t\t\ttunnel = BestPathXY(roomPositions[1],roomPositions[2]); // CN to NW\n\t\t\tfor(i = 0; i < tunnel.length; i++) {\n\t\t\t\tgridArr[tunnel[i]].open = 1;\n\t\t\t\tif(gridArr[tunnel[i]].room == \"\") {\n\t\t\t\t\tgridArr[tunnel[i]].room = \"T\";\n\t\t\t\t}\n\t\t\t}\n\t\t\ttunnel = BestPathXY(roomPositions[1],roomPositions[3]); // CN to NE\n\t\t\tfor(i = 0; i < tunnel.length; i++) {\n\t\t\t\tgridArr[tunnel[i]].open = 1;\n\t\t\t\tif(gridArr[tunnel[i]].room == \"\") {\n\t\t\t\t\tgridArr[tunnel[i]].room = \"T\";\n\t\t\t\t}\n\t\t\t}\n\t\t\ttunnel = BestPathXY(roomPositions[1],roomPositions[4]); // CN to SW\n\t\t\tfor(i = 0; i < tunnel.length; i++) {\n\t\t\t\tgridArr[tunnel[i]].open = 1;\n\t\t\t\tif(gridArr[tunnel[i]].room == \"\") {\n\t\t\t\t\tgridArr[tunnel[i]].room = \"T\";\n\t\t\t\t}\n\t\t\t}\n\t\t\ttunnel = BestPathXY(roomPositions[1],roomPositions[5]); // CN to SE\n\t\t\tfor(i = 0; i < tunnel.length; i++) {\n\t\t\t\tgridArr[tunnel[i]].open = 1;\n\t\t\t\tif(gridArr[tunnel[i]].room == \"\") {\n\t\t\t\t\tgridArr[tunnel[i]].room = \"T\";\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak;\n\t\tdefault: // spiral pattern\n\t\t\ttunnel = BestPathXY(roomPositions[0],roomPositions[3]); // ST to NE\n\t\t\tfor(i = 0; i < tunnel.length; i++) {\n\t\t\t\tgridArr[tunnel[i]].open = 1;\n\t\t\t\tif(gridArr[tunnel[i]].room == \"\") {\n\t\t\t\t\tgridArr[tunnel[i]].room = \"T\";\n\t\t\t\t}\n\t\t\t}\n\t\t\ttunnel = BestPathXY(roomPositions[3],roomPositions[5]); // NE to SE\n\t\t\tfor(i = 0; i < tunnel.length; i++) {\n\t\t\t\tgridArr[tunnel[i]].open = 1;\n\t\t\t\tif(gridArr[tunnel[i]].room == \"\") {\n\t\t\t\t\tgridArr[tunnel[i]].room = \"T\";\n\t\t\t\t}\n\t\t\t}\n\t\t\ttunnel = BestPathXY(roomPositions[5],roomPositions[4]); // SE to SW\n\t\t\tfor(i = 0; i < tunnel.length; i++) {\n\t\t\t\tgridArr[tunnel[i]].open = 1;\n\t\t\t\tif(gridArr[tunnel[i]].room == \"\") {\n\t\t\t\t\tgridArr[tunnel[i]].room = \"T\";\n\t\t\t\t}\n\t\t\t}\n\t\t\ttunnel = BestPathXY(roomPositions[4],roomPositions[2]); // SW to NW\n\t\t\tfor(i = 0; i < tunnel.length; i++) {\n\t\t\t\tgridArr[tunnel[i]].open = 1;\n\t\t\t\tif(gridArr[tunnel[i]].room == \"\") {\n\t\t\t\t\tgridArr[tunnel[i]].room = \"T\";\n\t\t\t\t}\n\t\t\t}\n\t\t\ttunnel = BestPathXY(roomPositions[2],roomPositions[1]); // NW to CN\n\t\t\tfor(i = 0; i < tunnel.length; i++) {\n\t\t\t\tgridArr[tunnel[i]].open = 1;\n\t\t\t\tif(gridArr[tunnel[i]].room == \"\") {\n\t\t\t\t\tgridArr[tunnel[i]].room = \"T\";\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak;\n\t}\n}", "computeBestSupportingPosition() {\n\n\t\tthis._supportSpotCalculator.computeBestSupportingPosition();\n\n\t}", "function bestSpot(){\r\n return minimax(origBoard, aiPlayer).index;\r\n}", "function preCalculate2(){\n\t\tvar edificiosPorFila = 2;\n\t\tvar datos = 0;\n\t\tvar buildingsImages = new Array();\n\t\tvar buildingsDescs = new Array();\n\t\tvar buildingsLinks = new Array();\n\n\t\t// recoge los nombres de cada uno\n\t\txpathResult = find('//map[@name=\"map1\"]/area/@title', XPIter);\n\t\twhile ((buildingsDescs[buildingsDescs.length] = xpathResult.iterateNext())) {}\n\n\t\t// los enlaces para acceder directamente a ellos\n\t\txpathResult = find('//map[@name=\"map1\"]/area/@href', XPIter);\n\t\twhile ((buildingsLinks[buildingsLinks.length] = xpathResult.iterateNext())) {}\n\n\t\t// Procesa as imagenes de los edificios\n\t\tvar xpathResult = find('//td[@class=\"s3\"]/img/@src', XPIter);\n\t\tbuildingsImages[0] = document.createTextNode(img(\"g/g16.gif\"));\n\t\twhile ((buildingsImages[buildingsImages.length] = xpathResult.iterateNext())) {}\n\t\t// Soporte para murallas\n\t\tvar a = find(\"//div[starts-with(@class, 'd2_x')]\", XPFirst);\n\t\tif (a){\n\t\t\tswitch(a.className){\n\t\t\t\tcase 'd2_x d2_0': break;\n\t\t\t\tcase 'd2_x d2_1': var b = \"g/g31.gif\"; break;\n\t\t\t\tcase 'd2_x d2_11': var b = \"g/g32.gif\"; break;\n\t\t\t\tcase 'd2_x d2_12': var b = \"g/g33.gif\"; break;\n\t\t\t}\n\t\t\tif (b) buildingsImages[buildingsDescs.length - 4] = document.createTextNode(img(b));\n\t\t}\n\n\t\tvar table = document.createElement('TABLE');\n\t\ttable.setAttribute(\"class\", \"tbg\");\n\t\ttable.setAttribute(\"align\", \"center\");\n\t\ttable.setAttribute(\"cellspacing\", \"1\");\n\t\ttable.setAttribute(\"cellpadding\", \"2\");\n\n\t\tvar j = 0;\n\t\tfor(var i = 0; i < buildingsDescs.length - 3; i++) {\n\t\t\tif(buildingsDescs[i] != null && basename(buildingsImages[i].nodeValue) != 'iso.gif') {\n\t\t\t\t// Por cada edificio se recoge su nivel y su codigo en el juego\n\t\t\t\tbuildingLevel = buildingsDescs[i].nodeValue.split(\" \");\n\t\t\t\tbuildingLevel = parseInt(buildingLevel[buildingLevel.length-1]);\n\n\t\t\t\tbuildingCode = buildingsImages[i].nodeValue.split(\"/\");\n\t\t\t\tbuildingCode = buildingCode[buildingCode.length-1].split(\".\");\n\t\t\t\tbuildingCode = parseInt(buildingCode[0].substring(1, buildingCode[0].length));\n\n\t\t\t\t// Si es actualizable se muestra junto con los recursos que necesita\n\t\t\t\tif (buildingCost[buildingCode] != null && buildingCost[buildingCode][buildingLevel+1] != null){\n\t\t\t\t\t// Se reparten los edificios entre las columnas disponibles en las filas que haga falta\n\t\t\t\t\tif (j % edificiosPorFila == 0){\n\t\t\t\t\t\tvar fila = document.createElement('TR');\n\t\t\t\t\t\ttable.appendChild(fila);\n\t\t\t\t\t}\n\t\t\t\t\tj++;\n\t\t\t\t\tdatos = 1;\n\n\t\t\t\t\t// Soporte para murallas\n\t\t\t\t\tswitch(buildingCode){\n\t\t\t\t\t\tcase 31: buildingsImages[i].nodeValue = 'data:image/gif;base64,' + imagenes[\"empalizada\"]; break;\n\t\t\t\t\t\tcase 32: buildingsImages[i].nodeValue = 'data:image/gif;base64,' + imagenes[\"muralla\"]; break;\n\t\t\t\t\t\tcase 33: buildingsImages[i].nodeValue = 'data:image/gif;base64,' + imagenes[\"terraplen\"]; break;\n\t\t\t\t\t}\n\n\t\t\t\t\tvar td = document.createElement(\"TD\");\n\t\t\t\t\tfila.appendChild(td);\n\n\t\t\t\t\tvar table2 = document.createElement('TABLE');\n\t\t\t\t\ttable2.setAttribute(\"align\", \"center\");\n\t\t\t\t\ttd.appendChild(table2);\n\n\t\t\t\t\tvar fila2 = document.createElement('TR');\n\t\t\t\t\ttable2.appendChild(fila2);\n\n\t\t\t\t\tvar td2 = document.createElement(\"TD\");\n\t\t\t\t\ttd2.setAttribute('class', 'f10');\n\t\t\t\t\ttd2.innerHTML = '<a href=\"' + buildingsLinks[i].nodeValue + '\">' + buildingsDescs[i].nodeValue + '<br/><img src=\"' + buildingsImages[i].nodeValue + '\" border=\"0\"></a>';\n\t\t\t\t\tfila2.appendChild(td2);\n\n\t\t\t\t\tvar restante = calculateResourceTime(buildingCost[buildingCode][buildingLevel+1]);\n\t\t\t\t\tvar td3 = document.createElement(\"TD\");\n\t\t\t\t\ttd3.setAttribute('class', 'c f7');\n\t\t\t\t\tfila2.appendChild(td3);\n\t\t\t\t\tif (restante != null){\n\t\t\t\t\t\ttd3.innerHTML = restante;\n\t\t\t\t\t}else{\n\t\t\t\t\t\ttd3.innerHTML = T('SUBIR_NIVEL');\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (j % edificiosPorFila != 0) fila.appendChild(document.createElement(\"TD\"));\n\t\ttable.style.position = 'absolute';\n\t\ttable.setAttribute(\"id\", \"resumen\");\n\t\t// Se desplaza la tabla hacia abajo para no interferir con la lista de aldeas / enlaces derecha\n\t\ttable.style.top = 625 + longitudPantalla() + 'px';\n\t\tif (datos == 1) document.body.appendChild(table);\n\t}", "function computeBounds(x1, x2, y1, y2) {\n return [[x1, y1], [x2, y1], [x2, y2], [x1,y2]];\n }", "function nextGeneration() {\n generation += 1;\n calculateFitness();\n\n for (let i = pop_total / 2; i < pop_total; i++) {\n boards[i] = pickOne();\n }\n\n for(let i = 0; i < pop_total / 2; i++){\n boards[i] = pickMax();\n }\n \n for(let i = 0; i < pop_total; i++){\n saveBoards[i].dispose();\n }\n\n saveBoards = [];\n}", "function squaresNeeded(grains){\n\n let squares = [1]\n let acc = 1;\n for (i = 1; i < 65; i++){\n acc *= 2\n squares.push(acc)\n }\n\n let ans = 0;\n for (i = 0; i < squares.length; i++){\n if (grains >= squares[i]){\n ans = i+1;\n }\n }\n\n return ans\n}", "function bestSpot() {\r\n return minimax(origBoard, aiPlayer).index;\r\n}" ]
[ "0.6188649", "0.58718324", "0.5776655", "0.57472926", "0.5745746", "0.57187366", "0.56426907", "0.55958927", "0.54943436", "0.5474894", "0.5471708", "0.5380923", "0.53719765", "0.53561246", "0.53238344", "0.52860296", "0.5282473", "0.5272119", "0.52712524", "0.52661526", "0.52604914", "0.5260346", "0.5253068", "0.5252939", "0.5252512", "0.5249961", "0.5234669", "0.5231949", "0.522339", "0.52225703", "0.5218544", "0.5216238", "0.52154374", "0.5203717", "0.52024966", "0.52013767", "0.52003753", "0.5199155", "0.51980174", "0.51768005", "0.5173936", "0.5166106", "0.51398325", "0.513958", "0.5129189", "0.5126811", "0.51219803", "0.51208293", "0.5115029", "0.511218", "0.5106002", "0.5101763", "0.50957876", "0.5093198", "0.50928307", "0.50883424", "0.5084979", "0.50819904", "0.508084", "0.507785", "0.5076926", "0.50766575", "0.5073904", "0.5068343", "0.5064698", "0.50637245", "0.5060699", "0.50605035", "0.5052575", "0.50484395", "0.50475174", "0.50411844", "0.5039412", "0.5036022", "0.5034682", "0.50318617", "0.50307274", "0.50177443", "0.501628", "0.5010609", "0.5008075", "0.50069773", "0.5004954", "0.50034326", "0.4996502", "0.49959508", "0.499315", "0.49889275", "0.49855298", "0.49830234", "0.49823904", "0.49808347", "0.49781463", "0.49777117", "0.49763313", "0.49731523", "0.49699906", "0.49686757", "0.4967411", "0.49610734" ]
0.6639376
0
This function sets the colors into place on the grid
function setColors(){ let randNum; let randNum0; var thePlace; var vCount = 0; var pop1Count = 0; var pop2Count = 0; // finds random spots for population 1 while(pop1Count != calculatePop1()){ randNum = Math.floor(Math.random() * (dims.value)); randNum0 = Math.floor(Math.random() * (dims.value)); thePlace = table.children[0].children[randNum].children[randNum0]; if(thePlace.innerHTML != "1"){ thePlace.style.backgroundColor = popXcolor.value; thePlace.innerHTML = "1"; thePlace.style.color = popXcolor.value; thePlace.style.fontSize = '5px'; pop1Count++; } } // finds random spots for population 2 while(pop2Count != calculatePop2()){ randNum = Math.floor(Math.random() * (dims.value)); randNum0 = Math.floor(Math.random() * (dims.value)); thePlace = table.children[0].children[randNum].children[randNum0]; if(thePlace.innerHTML != "1" && thePlace.innerHTML != "2"){ thePlace.style.backgroundColor = popYcolor.value; thePlace.innerHTML = "2"; thePlace.style.color = popYcolor.value; thePlace.style.fontSize = '5px'; pop2Count++; } } // finds vacant spots & only sets them in spots that have not been filled // by population 2 while(vCount != calculateV()){ randNum = Math.floor(Math.random() * (dims.value)); randNum0 = Math.floor(Math.random() * (dims.value)); thePlace = table.children[0].children[randNum].children[randNum0]; if(thePlace.innerHTML != "1" && thePlace.innerHTML != "2" && thePlace.innerHTML != "0"){ thePlace.style.backgroundColor = "#FFFFFF"; thePlace.innerHTML = "0"; thePlace.style.color = "#FFFFFF"; thePlace.style.fontSize = '5px'; vCount++; } } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function fnSetCellColors(ctx, grid) {\n for (var x = 0; x <= (gridSize - 1); x++) {\n for (var y = 0; y <= (gridSize - 1); y++) {\n fnColorCells(ctx, grid, x, y);\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 }", "function setAllGrey() {\n for (let i = 0; i < squares.length; i++) {\n squares[i].style.background = \"grey\";\n }\n rotateGrid();\n setTimeout(() => toggleGridClickable(), 500);\n \n}", "function setColors () {\r\n for (let i = 0; i<squares.length; i++) {\r\n squares[i].style.backgroundColor = colors[i];\r\n}}", "setMovesColor(color, newGrid) {\n\t\tfor (let i = 0; i < this.moves.length; i++) {\n\t\t\tthis.baseboard[this.moves[i].x][this.moves[i].y] = color;\n\t\t}\n\t\tthis.baseboard[newGrid.x][newGrid.y] = color;\n\n\t\tthis.updateGame();\n\t}", "function setColors() {\n var len = points.length / 3;\n for (var i = 0; i < len; i++) {\n colors.push(1.0);\n colors.push(0.0);\n colors.push(0.0);\n colors.push(1.0);\n }\n}", "function setAllColors(){\n\tfor (i=0; i<squares.length; i++){\n\t\tsquares[i].style.background = pickColor;\n\t}\n\th1.style.background = pickColor;\n}", "function setColours() {\r\n\tfor(var i = 0; i < colours.length; i++) {\r\n\t\tsquares[i].style.backgroundColor = colours[i]\r\n\t}\r\n}", "function setColors(gl) {\n\n var int8Arr = initializeColorGrid(4, 3);\n gl.bufferData(gl.ARRAY_BUFFER, int8Arr, gl.STATIC_DRAW);\n\n}", "function fillBackgroundColorOfSalvoGrid(gridLocation, eachTurn, hitsOnYourOpponent) {\n\n //console.log(gridLocation);\n\n $(\"#\" + gridLocation).css(\"background-color\", \"green\");\n //$('#' + gridLocation).text(\"X\");\n\n //ADD TURN NUMBER TO SHOTS FIRED\n var turnNumber = eachTurn;\n $(\"#\" + gridLocation).html(\"X\");\n\n for(var x = 0; x < hitsOnYourOpponent.length; x++){\n\n var currentLocation = hitsOnYourOpponent[x].hitLocation;\n\n //CHANGE COLOR OF SQUARE IF U HIT YOUR OPPONENT!\n //$(\"#\" + currentLocation + currentLocation).css(\"background-color\", \"red\");\n //$(\"#\" + currentLocation + currentLocation).html(\"hit\");\n $(\"#\" + currentLocation + currentLocation).addClass(\"firePic\");\n\n }\n }", "function colorGrid(i) {\n if(i < 400) {\n document.getElementsByClassName('square')[visitedNodes[i] * 40 + visitedNodes[i + 1]].style = 'background-color: #FF9AA2';\n } else if(i < 800) {\n document.getElementsByClassName('square')[visitedNodes[i] * 40 + visitedNodes[i + 1]].style = 'background-color: #FFB7B2';\n } else if(i < 1200) {\n document.getElementsByClassName('square')[visitedNodes[i] * 40 + visitedNodes[i + 1]].style = 'background-color: #FFDAC1';\n } else {\n document.getElementsByClassName('square')[visitedNodes[i] * 40 + visitedNodes[i + 1]].style = 'background-color: #E2F0CB';\n }\n}", "function setColor(colNr){\r\n currentColor = colNr;\r\n\r\n pixels.children.forEach(pixel => {\r\n pixel.tweenTo({ fillColor: colors[currentColor][pixel.colStep]}, { duration: _.random(200, 1000)});\r\n });\r\n}", "function updateColors() {\n\tfor (var i=0; i<allTissues.length; i++){\n\t\tchangeFillColor(allTissues[i].tissue, allTissues[i].color);\n\t\t//console.log(allTissues[i].tissue+\" \"+allTissues[i].value+\" \"+allTissues[i].color);\n\t}\n\tif(searchByTable){\n\t\tgenerateSelectionTable();\n\t}\n}", "function assignColors() {\r\n\t// assign the right color\r\n\trightColor = colors[Math.floor(Math.random()*mode)];\r\n\t// display it\r\n\tcolorDisplay.textContent = rightColor;\r\n\r\n\t// loop through colors array and assign rgb to squares\r\n\tfor(var i = 0; i < colors.length; i++){\r\n\t\tsquares[i].style.backgroundColor = colors[i];\r\n\t} \r\n}", "function fnColorCells(ctx, grid, x, y) {\n var color = fnColorFromStatus(grid[x][y]);\n var xStartRectangle, yStartRectangle;\n xStartRectangle = (x * cellSize) + 1;\n yStartRectangle = (y * cellSize) + 1;\n ctx.fillStyle = color;\n ctx.fillRect(xStartRectangle, yStartRectangle, cellSize - ctx.lineWidth, cellSize - ctx.lineWidth);\n}", "function draw(grid){\n grid.style.backgroundColor = \"black\";\n}", "function setupGridColors(size) {\n\t// \"5x5\" grid for regular game\n\tlet assassins = 1, blues = 8, reds = 8, amount = 25;\n\tif (size == \"5x4\") {\n\t\tblues = 7;\n\t\treds = 7;\n\t\tamount = 20;\n\t}\n\n\t// Determine which team has the extra tile and starts.\n\tlet coinflip = Math.random();\n\tlet starter = null;\n\tif (coinflip >= 0.5) {\n\t\tblues++;\n\t\tstarter = \"B\";\n\t} else {\n\t\treds++;\n\t\tstarter = \"R\";\n\t}\n\n\tlet whites = amount - assassins - blues - reds;\n\tlet colorGrid = \"W\".repeat(whites)\n\t\t+ \"A\".repeat(assassins)\n\t\t+ \"B\".repeat(blues)\n\t\t+ \"R\".repeat(reds);\n\tcolorGrid = colorGrid.split(\"\").sort((a, b) => {\n\t\treturn Math.random() - 0.5;\n\t});\n\n\treturn [starter, colorGrid];\n}", "function setColor(squares){\n squares.each(function(){\n $(this).css( \"backgroundColor\",randomRGB());\n });\n}", "function setColor() {\n \t\t\t$(this).setPixels({\n\t \t\tx: 260, y: 30,\n\t \t\twidth: 60, height: 40,\n\t \t\t// loop through each pixel\n\t \t\teach: function(px) {\n\t \t\t\tpx.r = rgb_r;\n\t \t\t\tpx.g = rgb_g;\n\t \t\t\tpx.b = rgb_b;\n\t \t\t}\n \t\t\t});\n\t\t}", "function changeColors(color){\n\tfor(i = 0; i < 6; i++){\n\t\tsquares[i].style.backgroundColor = color;\n\t}\n}", "function changeColor(tmp_stage,tmp_arr){\n tmp_arr.forEach(function (item) {\n tmp_stage.find(\"#\" + item[0]).fill(DICT_COLORS[item[1]]);\n tmp_stage.find(\"#main_l\").draw();\n });\n}", "function gridInk(target) {\n target.style.backgroundColor = 'black';\n }", "function shading() {\n var $cells = $('.grid-cell');\n $cells.each(function () {\n if ((columns % 2) == 0) {\n if ((Math.floor($i / columns) + $i) % 2 == 1) $(this).addClass('black')\n else $(this).addClass('white');\n $i++;\n } else {\n if (($i % 2) == 1) $(this).addClass('black')\n else $(this).addClass('white');\n $i++;\n }\n\n });\n $i = 0;\n }", "function myAfterLoadGrid(iDW){\n\t//setColor(iDW,sEvenColor);\n\t//Add you code\n}", "set_colors()\r\n {\r\n /* colors */\r\n let colors = [\r\n Color.of( 0.9,0.9,0.9,1 ), /*white*/\r\n Color.of( 1,0,0,1 ), /*red*/\r\n Color.of( 1,0.647,0,1 ), /*orange*/\r\n Color.of( 1,1,0,1 ), /*yellow*/\r\n Color.of( 0,1,0,1 ), /*green*/\r\n Color.of( 0,0,1,1 ), /*blue*/\r\n Color.of( 1,0,1,1 ), /*purple*/\r\n Color.of( 0.588,0.294,0,1 ) /*brown*/\r\n ]\r\n\r\n this.boxColors = Array();\r\n for (let i = 0; i < 8; i++ ) {\r\n let randomIndex = Math.floor(Math.random() * colors.length);\r\n this.boxColors.push(colors[randomIndex]);\r\n colors[randomIndex] = colors[colors.length-1];\r\n colors.pop();\r\n }\r\n\r\n }", "function changeColors(color) {\n\tfor (var i = 0; i < squares.length; i++) {\n\t\tsquares[i].style.background = color;\n\t}\n}", "function changeColors(color){\n\tfor(var i = 0; i < squares.length ; i++){\n\t\tsquares[i].style.backgroundColor = color;\n\t}\n}", "function updateColors () {\n // ADJUST COLOR VARIABLES FOR COLOR VALUE\n r = redSlider.value;\n g = greenSlider.value;\n b = blueSlider.value;\n\n // UPDATE ALL COLORS WITH NEW VALUES\n setColors(r, g, b);\n}", "function applyArrayToGrid(array) {\r\n\tfor(let i=0 ; i<array.length ; i++) {\r\n\t\tfor(let j=0 ; j<array[i].length ; j++) {\r\n\t\t\tvar cellId = \"#cell\"+i+\"-\"+j;\r\n\t\t\t$( cellId ).css(\"background-color\", colors[array[i][j]]);\r\n\t\t}\r\n\t}\r\n}", "function changeColors(color) {\n for (var i = 0; i < squares.length; i++) {\n squares[i].style.backgroundColor = color;\n }\n}", "function changeSquareColors(colors){\n\tfor(var i = 0; i < squares.length; i++){\n\t\tsquares[i].style.background = colors[i];\n\t}\n}", "function setColor() {\n // Set the event of clicking in the grid\n $('td').on('click',function(){\n if ($(this).hasClass('colored')){ // Check if its'a coloured square\n $(this).css(\"background-color\", 'white') // Erase if coloured\n }\n else {$(this).css(\"background-color\", colorVal)} // Set if not\n $(this).toggleClass('colored'); // Toggle this square to colored or not\n })\n}", "function changeColors(x) {\n for (var i = colors.length - 1; i >= 0; i--) {\n squares[i].style.backgroundColor = x;\n }\n}", "function setColors () {\n // SET ALL COLOR VARIABLES\n setColorValues();\n\n // UPDATE CSS COLOR STYLES\n setColorStyles();\n\n // SET CONTRAST COLOR STYLES\n setContrastStyles();\n}", "function changeColors(color){\n\tfor(let i = 0; i< squares.length; i++){\n\t\tsquares[i].style.backgroundColor = color;\n\t}\n}", "function changeColors ( color ) {\n // loop through all colors.\n // change each color to match given color. \n\n for ( var i=0 ; i < colors.length ; i++ ) {\n squares[i].style.background = color ; \n }\n\n}", "function refreshHardColors(){\n\t colors = createHardColors(squares.length , range);\n\t\treset();\n}", "function piece2Grid() {\n for (var i = 0; i < active.location.length; i++) {\n grid[active.location[i][0]][active.location[i][1]] = active.color;\n\n }\n}", "setColor(color) { \n this.cells[this.position].style.backgroundColor = color; \n this.color = color; \n }", "function changeColors(color){\n\t//Change colors of all squares using for loop\n\tfor(var i = 0; i < squares.length; i++) {\n\t\tsquares[i].style.background = color;\n\t}\n}", "function changeColors(color){\n\tfor (var i =0; i <squares.length; i++) {\n\t\tsquares[i].style.background=color;\n\t}\n}", "function changeColors(color){\n //loop through all squares\n for(var i = 0; i < squares.length; i++){\n //change each other square color to match given color\n squares[i].style.backgroundColor = color;\n }\n}", "function changeColors(color){\n\tfor(var i = 0; i<squares.length;i++){\n\t\t// change colors\n\t\tsquares[i].style.backgroundColor = color;\n\t}\n}", "setColours() {\n this.colourNeutral = 'colourNeutral';\n this.colourGo = 'colourGo';\n this.colourNoGo = 'colourNoGo';\n this.setStartColour();\n }", "function setGridNumRC(row, col, value) {\n\tgrid[row][col] = value;\n\t$(gridSpans[row][col]).parent().css(\"opacity\",\".5\");\n\t$(gridSpans[row][col]).text(value);\n\t$(gridSpans[row][col]).parent().css(\"background-color\", colorArray[value]);\n\t$(gridSpans[row][col]).parent().fadeTo(\"fast\",1);\n\treturn true;\n}", "function changeColors(color) {\n\t//loop through all squares\n\tfor(var i = 0; i < squares.length; i++) {\n\t\t//change each color to match given color\n\t\tsquares[i].style.backgroundColor = color;\n\t}\n}", "function fillAllUncolored() {\n var cells = grid.getElementsByTagName(\"td\")\n for (let i = 0; i < cells.length; i++) {\n currentStyle = getComputedStyle(cells[i])\n currentColor = currentStyle.backgroundColor\n if (currentColor == \"rgb(255, 255, 255)\") {\n cells[i].style.backgroundColor = colorSelected\n }\n }\n}", "setColors() {\n var squares = document.querySelectorAll('.square');\n\n for (var square of squares) {\n square.style.backgroundColor = 'hsl(' + this.fg + ',50%,50%)';\n }\n\n var hands = document.querySelectorAll('.hand');\n\n for (var hand of hands) {\n hand.style.backgroundColor = 'hsl(' + this.fg + ',20%,50%)';\n }\n\n var backColorFlr = Math.floor(this.bg);\n document.body.style.backgroundImage = 'linear-gradient(to bottom right, hsl(' + backColorFlr + ',50%,80%), hsl(' + backColorFlr + ',50%,50%))';\n }", "function colorGridToSetColor(){\n let gridFieldsElements = document.getElementsByClassName('grid-field');\n for (i = 0; i < gridFieldsElements.length; i++) {\n gridFieldsElements[i].style.backgroundColor = gridFields[i].color;\n }\n}", "function newColors() {\n for (var i = 0; i < squares.length; i++) {\n squares[i].style.backgroundColor = randomColor();\n }\n}", "function changeColors(color){\n\t//loop through all squares\n\tfor(let i=0; i < squares.length; i++){\n\t\t//change each color to match given color\n\t\tsquares[i].style.backgroundColor = color;\n\t}\n}", "function mainDraw(){\r\n for (var i = 0; i < gridSize; ++i) {\r\n for (var j = 0; j < gridSize; ++j) {\r\n // Actually do the draw operation only if color differs\r\n var color = colorConfiguration[i][j];\r\n if ( colorConfiguration[i][j] != drawnConfiguration[i][j] ) {\r\n ctx.fillStyle = colorArray[ color ];\r\n ctx.fillRect(j * siteSize, i * siteSize, siteSize, siteSize);\r\n drawnConfiguration[i][j] = color;\r\n }\r\n }\r\n }\r\n}", "function changeColors(color){\n //loop through all squares\n for (var i = 0; i < squares.length; i++) {\n //change each square color to match given color\n squares[i].style.backgroundColor = color;\n }\n}", "function changeColors(color){\r\nfor(var i=0 ; i<squares.length; i++){\r\n\tsquares[i].style.background=color;\r\n}\r\n}", "function colorSwap(){\n myCenter.color = col.value;\n for(var i=0; i<myDots.length; i++){\n myDots[i].color = col.value;\n }\n}", "function changeColors(color){\r\n\tfor(var i = 0; i < squares.length; i++){\r\n\t\tsquares[i].style.backgroundColor = color;\r\n\t}\r\n}", "function paint(){\r\n\t\t\tfor (var i=4; i<20; i++){\r\n\t\t\t\tvar grid = document.getElementById(\"grid\");\r\n\t\t\t\tvar cella = document.getElementById(\"casella\" + i);\r\n\t\t\t\tvar riga = Math.floor(i/4);\r\n\t\t\t\tvar colonna = i%4;\r\n\t\t\t\tvar n = grid.childNodes[riga].childNodes[colonna].value;\r\n\t\t\t\tcella.style.backgroundColor = colors[n];\r\n\t\t\t\t} \r\n\t\t}", "function changeColors(square){\n\t// loop through all squares\n\tfor(var i = 0; i < square.length; i++){\n\n\t// change each color to match the given color\n\tsquare[i].style.backgroundColor = pickedColor;\n}\n}", "function setColors(n) { //give colors to blocks\r\n for (var i = 0; i < color.length; i++) {\r\n square[i].style.background = color[i];\r\n square[i].style.display = \"block\";\r\n\r\n }\r\n\r\n}", "function changeColors(color) {\n for (let i = 0; i < squares.length; i++) {\n squares[i].style.backgroundColor = color;\n heading.style.backgroundColor = color;\n }\n}", "function changeEachColor(pickedColor){\r\n for (var i=0;i<squares.length;i++){\r\n squares[i].style.background=pickedColor;\r\n }\r\n}", "function drawGrid() { \n\t//count += 1;\n\t//var red = Math.floor(Math.random() * 256);\n\t//var green = Math.floor(Math.random() * 256);\n\t//var blue = Math.floor(Math.random() * 256);\n\tvar liveCount = 0;\n\tctx.clearRect(0, 0, gridHeight, gridWidth); //this should clear the canvas ahead of each redraw\n\tfor (var i = 1; i < gridHeight; i++) { \n\t\tfor (var j = 1; j < gridWidth; j++) { \n\t\t\t//draw colony 1\n\t\t\tif (theGrid[i][j] === 1) {\n\t\t\t\tctx.fillRect(i, j, 1, 1);\n\t\t\t\tliveCount++;\n\t\t\t\t//ctx.fillStyle = \"#f7a576\";\n\t\t\t\tctx.fillStyle = \"#849324\";\t\t\t\t\n\t\t\t}\n\t\t\t//draw colony 2\n\t\t\tif(theGrid[i][j] === 2){\n\t\t\t\tctx.fillRect(i, j, 1, 1);\n\t\t\t\tliveCount++;\n\t\t\t\t//ctx.fillStyle = \"#25b28a\";\n\t\t\t\tctx.fillStyle = \"#FFB30F\";\n\t\t\t}\n\t\t\t//draw colony 3\n\t\t\tif(theGrid[i][j] === 3){\n\t\t\t\tctx.fillRect(i, j, 1, 1);\n\t\t\t\tliveCount++;\n\t\t\t\t//ctx.fillStyle = \"#b589f4\";\n\t\t\t\tctx.fillStyle = \"#01295F\";\n\t\t\t}\n\t\t\t//draw colony 4\n\t\t\tif(theGrid[i][j] === 4){\n\t\t\t\tctx.fillRect(i, j, 1, 1);\n\t\t\t\tliveCount++;\n\t\t\t\t//ctx.fillStyle = \"#b589f4\";\n\t\t\t\tctx.fillStyle = \"#FD151B\";\n\t\t\t}\n\t\t\t//draw colony 5\n\t\t\tif(theGrid[i][j] === 5){\n\t\t\t\tctx.fillRect(i, j, 1, 1);\n\t\t\t\tliveCount++;\n\t\t\t\t//ctx.fillStyle = \"#b589f4\";\n\t\t\t\tctx.fillStyle = \"#437F97\";\n\t\t\t}\n\t\t}\n\t}\n\t//if(count % 50 === 0){\n\t//\tctx.fillStyle = \"rgba(\"+ red + \", \" + green + \", \" + blue + \", 1)\";\n\t//}\n\t//console.log(liveCount/100);\n}", "function changeColors(color) {\r\n\t//loop through all squares:\r\n\tfor(var i = 0; i < squares.length; i++) {\r\n\t//change each color to match given color\r\n\tsquares[i].style.background = color;\r\n\t}\r\n\t\r\n}", "function changeColors(color){\n\tsquares.forEach(function(square){\n\t\tsquare.style.background = color;\n\t});\n}", "function changeColors(color) {\n for (let i = 0; i < colors.length; i++) {\n squares[i].style.backgroundColor = color\n }\n}", "function changeColors(color){\n //loop through all squares\n for (let i = 0; i < squares.length; i++) {\n //change each color to match given color\n squares[i].style.backgroundColor = color;\n }\n}", "function changeColors(color) {\n // loop through all squares\n for (var i = 0; i < squares.length; i++) {\n // change each color to match given color \n squares[i].style.backgroundColor = color;\n };\n}", "function drawActiveGrid() {\n for (let a = 0; a < height; a++) {\n row = canvas.insertRow(a);\n // sets a click event listener and which sets color\n //from the user input\n row.addEventListener(\"click\", e => {\n //function setColor\n var clicked = e.target;\n color.addEventListener(\"change\", e =>\n //function onColorUpdate\n {\n selectedColor = e.target.value;\n }\n );\n clicked.style.backgroundColor = selectedColor;\n });\n for (let b = 0; b < width; b++) {\n cell = row.insertCell(b);\n }\n }\n }", "function updateColors() {\n var data = document.getElementsByClassName(\"gridjs-td\");\n var headers = document.getElementsByClassName(\"gridjs-th gridjs-th-sort\");\n\n var i = 1;\n //loop through each column\n while (i < headers.length) {\n var currentColumn = []\n var opacity = 0.05\n\n //collect all data of a column into a single array\n for (var j = i; j < data.length; j += (headers.length)) {\n currentColumn.push(data[j])\n }\n\n //get the column sorted but only their indices\n var indexArray = selectionSortIndex(currentColumn)\n //document.write(indexArray)\n\n for (var idx = 0; idx < currentColumn.length; idx++) {\n //get color for the sport\n var color = checkColor(headers[i].getAttribute(\"data-column-id\"))\n\n //check if previous is the same number\n var k = idx\n if ((k - 1) >= 0) {\n if (currentColumn[indexArray[idx]].innerHTML === currentColumn[indexArray[idx - 1]].innerHTML) {\n opacity -= 0.15\n if (opacity < 0) {\n opacity = 0.05\n }\n\n }\n }\n\n //set background color\n currentColumn[indexArray[idx]].style.backgroundColor = \"rgba(\" + color + \",\" + String(opacity) + \")\";\n opacity += 0.15\n }\n\n i += 1\n }\n}", "function changeColors(color){\r\n\t//loop through all squares\r\n\tfor(var i = 0; i < squares.length; i++){\r\n\t\t//change each color to match given color\r\n\t\tsquares[i].style.background = color;\r\n\t}\r\n}", "function resetGrid () {\nlet gridSquares = document.querySelectorAll(\".cell\");\nfor(i = 0; i < gridSquares.length; i++) {\n gridSquares[i].style.backgroundColor = \"white\";\n}\n}", "function setColors(rgbList, totalColors) {\n var color = \"\";\n for (let i = 0; i < totalColors; i++) {\n var curr = rgbList[i];\n color = \"rgb(\" + curr[0] + \", \" + curr[1] + \", \" + curr[2] + \")\";\n labelList[i].style.background = color;\n }\n if (totalColors == 3) {\n for (let i = 3; i < 6; i++) {\n labelList[i].classList.add(\".hidden\");\n }\n }\n}", "function changeColors(color){\n for (var i = 0; i<colors.length; i++){\n squares[i].style.backgroundColor = color;\n }\n}", "function drawCurrentGrid() {\n\n\n for (var i = 0; i < 20; i++) {\n for (var j = 0; j < 10; j++) {\n if (grid[i][j] > 0) {\n var num = grid[i][j];\n var color = colors[num - 1];\n\n var y = 1 + j * 32;\n var x = 612 - (1 + i * 32);\n\n\n $canvas.drawRect({\n fillStyle: color,\n strokeStyle: color,\n strokeWidth: 4,\n x: y,\n y: x, // 1+i*32, j*32\n fromCenter: false,\n width: 30,\n height: 28\n });\n } else if (placed[i][j] > 0) {\n var num = placed[i][j];\n var color = colors[num - 1];\n\n var y = 1 + j * 32;\n var x = 612 - (1 + i * 32);\n\n $canvas.drawRect({\n fillStyle: color,\n strokeStyle: color,\n strokeWidth: 4,\n x: y,\n y: x, // 1+i*32, j*32\n fromCenter: false,\n width: 30,\n height: 28\n });\n }\n\n }\n }\n\n}", "function staticUpdateCells(grid) {\r\n var new_canvas = getCanvas();\r\n for (var i = 0; i < NUM_ROWS; i += 1) {\r\n for (var j = 0; j < NUM_COLS; j += 1) {\r\n new_canvas.fillStyle = grid[i][j].fillStyle;\r\n new_canvas.fillRect(grid[i][j].xPosition, grid[i][j].yPosition, CELL_SIZE, CELL_SIZE);\r\n }\r\n }\r\n }", "function finalColors(){\n\treset.textContent=\"Play Again?\";\n\th1.style.backgroundColor=pickedColor;\n\tfor(var i=0;i<squares.length;i++)\n\t\tsquares[i].style.backgroundColor=pickedColor;\n}", "function setUpRed() {\n for(j = 0 ; j < 3; j += 1){\n if( j === 1){\n for(i = 1; i < 8; i += 2){\n checkerboard[j][i] = 'R';\n }\n } else {\n for(i =0 ; i < 8; i += 2){\n checkerboard[j][i] ='R';\n }\n }\n }\n}", "function changeColors(color){\n //loop through squares \n for(var i = 0; i < squares.length; i++){\n //change each color to match given color\n squares[i].style.backgroundColor = color;\n }\n}", "function reset_color()\n\t{\n\t\tfor (i=0;i<=max;i++)\n\t\t{\n\t\t\tvar x=document.getElementById(\"col\"+i);\n\t\t\tif(x)\tx.style.backgroundColor=\"white\";\n\t\t}\n\t}", "function changeColor (color) {\n // -(7.1)- Loop through all squares \n for (let index = 0; index < squares.length; index++) {\n\n // -(7.2)- Change each color to match goal color\n squares[index].style.backgroundColor = color;\n }\n}", "function changeColors(color1) {\n for(var i = 0; i < squares.length; i++) {\n squares[i].style.backgroundColor = color1;\n }\n}", "function setStyle(){\r\n\tif(clickNumber % 2 == 0){\r\n\t\tconsole.log('This is an even click -> black!')\t\t\r\n\t\t// Layer colors\r\n\t\tcurrentLayer.styleMap = b_style;\r\n\t\toldLayer.styleMap = w_style;\r\n\t\t// Chart colors\r\n\t\tcol1 = '#DBD8D8';\t\t\t// white\r\n\t\tcol2 = '#363434';\t\t\t// black - also tried this #808080\r\n\t\tcol1_borderColor = '#7B7B7B';\r\n\t\tcol2_borderColor = '#BDBDBD';\r\n\t}\r\n\telse{\r\n\t\tconsole.log('This is an odd click -> white!')\t\t\t\t\r\n\t\t// Layer colors\r\n\t\tcurrentLayer.styleMap = w_style;\r\n\t\toldLayer.styleMap = b_style;\t\t\r\n\t\t// Chart colors\r\n\t\tcol1 = '#363434';\t\t\t// black\t\r\n\t\tcol2 = '#DBD8D8';\t\t\t// white\r\n\t\tcol1_borderColor = '#BDBDBD';\r\n\t\tcol2_borderColor = '#7B7B7B';\r\n\t}\r\n}", "setColours() {\n this.colourNeutral = 'colourNeutral';\n this.colourGo = 'colourNeutralShadow';\n this.colourNoGo = 'colourNoGo';\n this.setStartColour();\n }", "function setAllTractColors(data) {\n\t\t//\tconsole.log(\"setAllTractColors()\",data);\n\n\n\t\t// update the color scale for the map\n\n\t}", "function fillCanvas() {\n for (let i = 1; i <= gridSquares.length-1; i++) {\n\n if (blueSquares.includes(gridSquares[i])) {\n ctx.fillStyle = \"blue\";\n }\n else {\n ctx.fillStyle = \"gray\";\n }\n ctx.fillRect(gridSquares[i].x, gridSquares[i].y, 10, 10);\n }\n }", "function changeColorsWin(color){\r\n for(let i =0;i<squares.length;i++){\r\n squares[i].style.backgroundColor=color;\r\n }\r\n document.querySelector(\"h1\").style.backgroundColor=color;\r\n }", "function setColor(elmt) {\n for (i = 0; i < elmt.length; i++) {\n j=i%(tags.length);\n elmt[i].css(\"backgroundColor\", tags[sortd[j]]);\n }\n}", "displayGrid(color) {\n rectMode(CORNER);\n strokeWeight(0);\n fill(color);\n if (this.wall) {\n fill(\"green\");\n }\n rect(this.x * cellWidth, this.y * cellHeight, cellWidth - 1, cellHeight - 1);\n }", "function resetGrid() {\n let reset = document.getElementsByClassName('grid-column');\n for (let i = 0; i < reset.length; i++) {\n //reset[i].style.backgroundColor = \"white\";\n reset[i].style.backgroundColor = 'white';\n\n }\n}", "function drawOnGrid(gridItems, color) //something not right about this function\n{\n //taking the current HTML collection of grid items, making in array out of it. Giving each grid item the ability to be moused over...and have that colors classlist added to it\n Array.from(gridItems).forEach((item, idx) => item.addEventListener('mouseover', () =>\n {\n // colorGridItem(item, color)\n item.style.backgroundColor = `${color}`\n }))\n}", "function colorChange(){\n Array.from(rows).forEach(row => {\n let\n rowIdString = row.id,\n rowHour;\n if (rowIdString) {\n rowHour = parseInt(rowIdString);\n }\n if(rowHour){\n if(currentHour === rowHour){\n setColor(row, \"red\");\n }else if ((currentHour < rowHour) && (currentHour > rowHour -6)){\n setColor(row, \"green\");\n }else if ((currentHour > rowHour) && (currentHour < rowHour +6)){\n setColor(row, \"lightgrey\");\n }else{\n setColor(row, \"white\");\n }\n }\n })\n}", "function setColorValues () {\n // CONVERT RGB AND SET HEXIDECIMAL\n hex = rgbToHex(r, g, b);\n\n // CONVERT RGB AND SET HSL\n var hslvalues = rgbToHsl(r, g, b);\n h = hslvalues[0];\n s = hslvalues[1];\n l = hslvalues[2];\n}", "function changeColor(color)\n{\n for(let i=0; i<num ; i++){\n squares[i].style.backgroundColor=color;\n }\n heading.style.backgroundColor=color;\n}", "function clearGrid() {\n for(let i = 0; i < grid.length; i++) {\n grid[i].style.backgroundColor = '#FFF';\n }\n}", "function drawGrid() {\n ctx.clearRect(0, 0, 500, 500);\n for (let i = 0; i < dimension; i++) {\n for (let j = 0; j < dimension; j++) {\n if (grid[i][j] === 1) {\n ctx.fillStyle = '#384e72';\n ctx.fillRect(i * 10, j * 10, 10, 10);\n }\n ctx.strokeStyle = '#696969';\n ctx.strokeRect(i * 10, j * 10, 10, 10);\n }\n }\n}", "function hoverColor(gridNum){\n document.getElementById(gridNum).style.backgroundColor = color;\n document.getElementById(\"selectedColor\").setAttribute(\"value\", color)\n}", "function setColor() { //function to set color and position, called by var start\n\n var index;\n var gamesquare = [gs1, gs2, gs3, gs4, gs5, gs6, gs7, gs8, gs9];\n for (index = 0; index < gamesquare.length; index++) {\n gamesquare[index].style.backgroundColor = \"white\"; }; // resets square before start of loop \n\n console.log ('Round count ' + (x+1));\n console.log ('Position ' + (levelArr[x][1]+1) + ' Color ' + colors[levelArr[x][0]]);\n gamesquare[levelArr[x][1]].style.backgroundColor = colors[levelArr[x][0]]; // sets color and position for square\n x++; // increments x on each loop iteration\n\n\n if(x >= rounds){\n console.log('Level complete, stopping engine');\n clearInterval(start); // stops engine after x is above rounds\n }; \n\n}", "function correctColorDisplay(){\r\n\theader.style.backgroundColor = colorPicked;\t\r\n\tfor(var x=0; x<squares.length; x++){\r\n\t\tsquares[x].style.backgroundColor = colorPicked;\r\n\t\tsquares[x].style.opacity = \"1\";\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\r\n\t}\r\n}", "function colorGrid(color){\n let gridFieldsElements = document.getElementsByClassName('grid-field');\n for (i = 0; i < gridFieldsElements.length; i++) {\n gridFieldsElements[i].style.backgroundColor = color;\n }\n}", "function fill(){\n // Loop through the whole table and set the background to color selected \n for (var i =0; i < numRows; i++){\n for (var j =0; j < numCols; j++){\n document.getElementById(\"grid\").children[i].children[j].style.backgroundColor= colorSelected;\n }\n }\n}" ]
[ "0.7835942", "0.7699534", "0.7496164", "0.7225622", "0.7089933", "0.70365363", "0.7029064", "0.7012479", "0.69936824", "0.6963187", "0.6938045", "0.69317466", "0.6926818", "0.69044054", "0.6902957", "0.6897035", "0.68494576", "0.6848265", "0.6821114", "0.68049157", "0.6774159", "0.6773014", "0.6762916", "0.67549306", "0.67075175", "0.6702377", "0.66991204", "0.6693972", "0.66728026", "0.6664051", "0.6661236", "0.66476184", "0.6646942", "0.664461", "0.6642046", "0.66392255", "0.66337484", "0.6631691", "0.6624764", "0.6624559", "0.6617175", "0.66155833", "0.66126126", "0.6609416", "0.66076607", "0.6599349", "0.6594443", "0.65942967", "0.65927964", "0.65916634", "0.6581329", "0.6576886", "0.6575852", "0.65752864", "0.6571852", "0.6571084", "0.6563182", "0.6560492", "0.65588266", "0.655624", "0.6555004", "0.65532684", "0.65442556", "0.6540689", "0.6539347", "0.6539044", "0.65380025", "0.6536953", "0.65354997", "0.65260905", "0.65227276", "0.6522517", "0.6520512", "0.6508596", "0.64944494", "0.6493993", "0.6491026", "0.6489332", "0.6488095", "0.64807063", "0.6471919", "0.6463352", "0.64608884", "0.64586365", "0.6454607", "0.6452164", "0.6448158", "0.64439327", "0.6427175", "0.64265907", "0.6416809", "0.64147216", "0.6410653", "0.64052474", "0.64028734", "0.6399516", "0.6387545", "0.6386612", "0.6382224", "0.6380901" ]
0.65653676
56
Function to find whether the spaces around the particular cell has the specified percentage of the same color surrounding it
function isCorrectPercentage(){ let x = table.children[0]; let theSpot; let leftD, leftM, leftU, upM, rightU, rightM, rightD, downM; for(let i=0; i<val; i++){ for(let j=0; j<val; j++){ let totalX = 0; let totalY = 0; theSpot = x.children[i].children[j]; if(i!=0 && j!=0){ leftD = x.children[i-1].children[j-1]; }if(i!=0){ leftM = x.children[i-1].children[j]; }if(i!=0 && j<val-1){ leftU = x.children[i-1].children[j+1]; }if(j<val-1){ upM = x.children[i].children[j+1]; }if(i<val-1 && j!=0){ rightU = x.children[i+1].children[j+1]; }if(i<val-1){ rightM = x.children[i+1].children[j]; }if(i<val-1 && j!=0){ rightD = x.children[i+1].children[j-1]; }if(i!=0){ downM = x.children[i].children[j-1]; } if(theSpot.innerHTML == "1"){ if(typeof(leftD) != "undefined"){ if(leftD.innerHTML == "1"){ totalX++; }}if(typeof(leftM) != "undefined"){ if(leftM.innerHTML == "1"){ totalX++; }}if(typeof(leftU) != "undefined"){ if(leftU.innerHTML == "1"){ totalX++; }}if(typeof(upM) != "undefined"){ if(upM.innerHTML == "1"){ totalX++; }}if(typeof(rightU) != "undefined"){ if(rightU.innerHTML == "1"){ totalX++; }}if(typeof(rightM) != "undefined"){ if(rightM.innerHTML == "1"){ totalX++; }}if(typeof(rightD) != "undefined"){ if(rightD.innerHTML == "1"){ totalX++; }}if(typeof(downM) != "undefined"){ if(downM.innerHTML == "1"){ totalX++; }} }if(theSpot.innerHTML == "2"){ if(typeof(leftD) != "undefined"){ if(leftD.innerHTML == "2"){ totalY++; }}if(typeof(leftM) != "undefined"){ if(leftM.innerHTML == "2"){ totalY++; }}if(typeof(leftU) != "undefined"){ if(leftU.innerHTML == "2"){ totalY++; }}if(typeof(upM) != "undefined"){ if(upM.innerHTML == "2"){ totalY++; }}if(typeof(rightU) != "undefined"){ if(rightU.innerHTML == "2"){ totalY++; }}if(typeof(rightM) != "undefined"){ if(rightM.innerHTML == "2"){ totalY++; }}if(typeof(rightD) != "undefined"){ if(rightD.innerHTML == "2"){ totalY++; }}if(typeof(downM) != "undefined"){ if(downM.innerHTML == "2"){ totalY++; }} } console.log(totalX); console.log(totalY); if(totalX<(threshold.value*8)){ theSpot.style.backgroundColor = "#ffffff"; theSpot.innerHTML = "0"; changeLocation(popXcolor.value); }if(totalY<(threshold.value*8)){ theSpot.style.backgroundColor = "#ffffff"; theSpot.innerHTML = "0"; changeLocation(popYcolor.value); } } } /** * This function changes the location of the population to a vacant spot * @param {*} color */ function changeLocation(color){ let x = table.children[0]; let theSpot; for (let i=0;i<val;i++){ for(let j=0;j<val;j++){ theSpot = x.children[i].children[j]; if(theSpot.innerHTML == "0"){ theSpot.style.backgroundColor = color; thePlace.style.color = "#FFFFFF"; break; } } } } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function testCells() //Checks if all cells which are part of solution are colored.\n{\n for(var k=0; k<solutions.length; k++)\n {\n if(solutions[k].style.backgroundColor == \"gray\")\n {\n continue;\n }\n else {\n return false;\n }\n }\n return true;\n}", "checkColor(checkColor, cell1) {\n if (checkColor == \"-\") return \n let num = Number(checkColor);\n for (let j = 0; j < spectrum.length; j++) { \n if (num <= spectrum[j].a) {\n cell1.style.backgroundColor = spectrum[j].b;\n cell1.style.color = spectrum[j].f;\n break\n } \n }\n }", "function check_horizontal(row, col, color) {\n let count = 1\n let temp = col\n while (col > 0) {\n let $left_cell = get_cell(row, --col)\n console.log(col, color, 'left count')\n console.log($left_cell)\n if ($left_cell.css('backgroundColor') == color) {\n count += 1\n console.log('count +++ left')\n }\n else {\n break\n }\n }\n col = temp\n while (col < that.col) {\n let $right_cell = get_cell(row, ++col)\n console.log(col, color, 'right count')\n console.log($right_cell)\n if ($right_cell.css('backgroundColor') == color) {\n count += 1\n console.log('count +++ right')\n }\n else {\n break\n }\n }\n if (count >= 4) {\n return true\n }\n return false\n }", "function check_top_left_bottom_right(row, col, color) {\n let count = 1\n let temp_row = row\n let temp_col = col\n while (row > 0 && col > 0) {\n let $next_cell = get_cell(--row, --col)\n if ($next_cell.css('backgroundColor') == color) {\n count += 1\n }\n else {\n break\n }\n }\n row = temp_row\n col = temp_col\n while (row < that.row && col < that.col) {\n let $up_cell = get_cell(++row, ++col)\n if ($up_cell.css('backgroundColor') == color) {\n count += 1\n }\n else {\n break\n }\n }\n if (count >= 4) {\n return true\n }\n return false\n }", "function checkColumn4() {\n // loop over 3 edges\n for (let i = 0; i < 39; i++) {\n let columnOfFour = [i, i + width, i + 2 * width, i + 3 * width];\n let decidedcolor = squares[i].style.backgroundImage;\n const isBlank = squares[i].style.backgroundImage === \"\";\n if (\n // if all the three colors are same then we make them as blank\n columnOfFour.every(\n (index) => squares[index].style.backgroundImage === decidedcolor\n ) &&\n !isBlank\n ) {\n score += 4;\n scoreDisplay.innerHTML = score;\n columnOfFour.forEach((index) => {\n squares[index].style.backgroundImage = \"\";\n });\n }\n }\n }", "function checkColumn3() {\n // loop over 3 edges\n for (let i = 0; i < 47; i++) {\n let columnOfThree = [i, i + width, i + 2 * width];\n let decidedcolor = squares[i].style.backgroundImage;\n const isBlank = squares[i].style.backgroundImage === \"\";\n\n if (\n // if all the three colors are same then we make them as blank\n columnOfThree.every(\n (index) => squares[index].style.backgroundImage === decidedcolor\n ) &&\n !isBlank\n ) {\n score += 3;\n scoreDisplay.innerHTML = score;\n columnOfThree.forEach((index) => {\n squares[index].style.backgroundImage = \"\";\n });\n }\n }\n }", "function colorInColors(col, cols, tolerance) {\n for (var i = 0; i < cols.length; i++) {\n if (similarColors(col, cols[i], tolerance) === true) {\n return true;\n }\n }\n return false;\n}", "function check_top_right_bottom_left(row, col, color) {\n let count = 1\n let temp_row = row\n let temp_col = col\n while (row < that.row && col > 0) {\n let $next_cell = get_cell(++row, --col)\n if ($next_cell.css('backgroundColor') == color) {\n count += 1\n }\n else {\n break\n }\n }\n row = temp_row\n col = temp_col\n while (row > 0 && col < that.col) {\n let $up_cell = get_cell(--row, ++col)\n if ($up_cell.css('backgroundColor') == color) {\n count += 1\n }\n else {\n break\n }\n }\n if (count >= 4) {\n return true\n }\n return false\n }", "function checkColumnForThree(){\n for(i=0; i<47; i++){\n\n let columnOfThree = [i, i+width, i+width*2]\n let decidedColor = squares[i].style.backgroundImage\n const isBlack = squares[i].style.backgroundImage === ''\n\n if (columnOfThree.every(index => squares[index].style.backgroundImage === decidedColor && !isBlack)){\n score += 3\n squareDisplay.innerHTML= score\n columnOfThree.forEach(index => {\n squares[index].style.backgroundImage = ''\n })\n }\n }\n}", "function squareHasChecker(td) {\n \tif (td.hasClass('black') || td.hasClass('red')) {\n \t\treturn 1;\n \t} else {\n \t\treturn 0;\n \t}\n }", "checkShouldChangeColor() {\r\n const greenNeighbors = this.neighbors.filter(neighbor => neighbor.color == '1').length;\r\n // console.log(`has [${redNeighbors}] red neighbors and [${greenNeighbors}] green neighbors.`);\r\n\r\n\r\n if (this.color == 0 && [3, 6].includes(greenNeighbors)) {\r\n // console.log(`Cell color is RED AND HAS ${greenNeighbors} GREEN neighbors and should change color to GREEN`);\r\n this.shouldChangeColor = true;\r\n }\r\n\r\n if (this.color == 1 && [0, 1, 4, 5, 7, 8].includes(greenNeighbors)) {\r\n // console.log(`Cell color is GREEN AND HAS ${redNeighbors} RED neighbors and should change color to RED`);\r\n this.shouldChangeColor = true;\r\n }\r\n }", "function diagnolCheck1(){\n for (let col = 0; col < 4; col++){\n for (row = 0; row <3; row++){\n if (colorMatchCheck(tableRow[row].children[col].style.backgroundColor, tableRow[row+1].children[col+1].style.backgroundColor,\n tableRow[row+2].children[col+2].style.backgroundColor,tableRow[row+3].children[col+3].style.backgroundColor)){\n return true;\n }\n }\n}\n}", "function colorInAllColors(col, cols, tolerance) {\n for (var i = 0; i < cols.length; i++) {\n if (similarColors(col, cols[i], tolerance) === false) {\n return false;\n }\n }\n return true;\n}", "function checkColumnForFour(){\n for(i=0; i<39; i++){\n\n let columnOfFour = [i,i+width, i+width*2, i+width*3]\n let decidedColor = squares[i].style.backgroundImage\n const isBlack = squares[i].style.backgroundImage === ''\n\n if (columnOfFour.every(index => squares[index].style.backgroundImage === decidedColor && !isBlack)){\n score += 4\n squareDisplay.innerHTML= score\n columnOfFour.forEach(index => {\n squares[index].style.backgroundImage = ''\n })\n }\n }\n}", "function IsSpaceTheGivenColor(_Game, _X, _Y, _ColorToCheck) {\r\n return IsSpaceExistingOnBoard(_Game, _X, _Y) && \r\n _Game.BoardArray[_X][_Y].OccupiedBy === _ColorToCheck;\r\n}", "function checkColForFour() {\n for (i = 0; i < 40; i++) {\n //if we use indexes to draw our row, it would look like this\n let colOfFour = [i, i + width, i + 2 * width, i + 3 * width];\n //this is the color to eliminate\n let decidedColor = squares[i].style.backgroundImage;\n let isBlank = squares[i].style.backgroundImage === '';\n\n if (\n colOfFour.every(\n (index) =>\n squares[index].style.backgroundImage === decidedColor && !isBlank\n )\n ) {\n score += 8;\n playConfrimSound();\n scoreDisplay.innerHTML = score;\n colOfFour.forEach((index) => {\n squares[index].style.backgroundImage = '';\n });\n }\n }\n }", "function checkColumnForFour() {\n for (i = 0; i < 39; i ++) {\n let columnFour = [i, i+width, i+width*2,i+width*3]\n let decidedColor = squares[i].style.backgroundImage\n const isBlank = squares[i].style.backgroundImage === ''\n\n if(columnFour.every(index => squares[index].style.backgroundImage === decidedColor && !isBlank)) {\n score += 4\n scoreDisplay.innerHTML = score\n columnFour.forEach(index => {\n squares[index].style.backgroundImage = ''\n })\n }\n }\n }", "checkHorizontalWin(color) {\n let colorSlots = this.getSlots(color);\n let rowMap = this.createRowMap(colorSlots);\n for (const key in rowMap) {\n const value = rowMap[key];\n value.sort();\n // if there aren't at least 4 filled slots in this row, there isn't a row-based win\n if (value.length > 3) {\n for (let i = 0; i < value.length - 3; i++) {\n // look through slots in chunks of 4\n const arr = value.slice(i, i + 4);\n // check that the 4 slots are next to each other\n let num = arr[3];\n if ((arr[0] + 3 === num) && (arr[1] + 2 === num) && (arr[2] + 1 === num)) {\n const arr2 = [(arr[0] + (7 * key)), (arr[1] + (7 * key)), (arr[2] + (7 * key)), (arr[3] + (7 * key))];\n this.boldWinningSlots(arr2);\n return true;\n }\n }\n }\n }\n return false;\n }", "function checkGreenColor(callback) {\n\t\t\tcp.countPixels([0, 255, 0], \n\t\t\t\twin, \n\t\t\t\tfunction(count){\n\t\t\t\t\tvalueOf(testRun, count).shouldBe(parentView.rect.width*parentView.rect.height - expectedRed);\n\t\t\t\t\tcallback();\t\n\t\t\t\t}\n\t\t\t);\n\t\t}", "function checkColForFive() {\n for (i = 0; i < 32; i++) {\n //if we use indexes to draw our row, it would look like this\n let colOfFive = [\n i,\n i + width,\n i + 2 * width,\n i + 3 * width,\n i + 4 * width,\n ];\n //this is the color to eliminate\n let decidedColor = squares[i].style.backgroundImage;\n let isBlank = squares[i].style.backgroundImage === '';\n\n if (\n colOfFive.every(\n (index) =>\n squares[index].style.backgroundImage === decidedColor && !isBlank\n )\n ) {\n score += 15;\n playYaySound();\n scoreDisplay.innerHTML = score;\n colOfFive.forEach((index) => {\n squares[index].style.backgroundImage = '';\n });\n }\n }\n }", "check(x, y, board = this.map) {\n let color = board[y][x];\n if (color === \"⚪\") return 1;\n //horizontal\n if (\n this.search(x, y, color, 1, 0, 0) +\n this.search(x, y, color, -1, 0, 0) - 1 >= 4\n ) {\n return 2;\n }\n //lt-rb diagonal\n if (\n this.search(x, y, color, 1, 1, 0) +\n this.search(x, y, color, -1, -1, 0) - 1 >= 4\n ) {\n return 2;\n }\n //lt-rb diagonal\n if (\n this.search(x, y, color, -1, 1, 0) +\n this.search(x, y, color, 1, -1, 0) - 1 >= 4\n ) {\n return 2;\n }\n //vertical\n if (\n this.search(x, y, color, 0, 1, 0) +\n this.search(x, y, color, 0, -1, 0) - 1 >= 4\n ) {\n return 2;\n }\n\n // check how many pieces in a column\n let countstack = 0;\n for (let i = 0; i < 7; i++) {\n if (this.stack[i] === -1) {\n countstack++;\n }\n }\n\n // a column is full\n if (countstack === 7) return 3;\n\n return 1;\n }", "function checkAdjacent(row, col, checkerId, color) {\n if ((currentCheckerId != null) && (checkerId != currentCheckerId)) {\n return false;\n }\n if (isAKing(checkerId)) {\n if (!outOfBounds(row + 2, col + 2) && (!cellIsVacant(row + 1, col + 1)) && (cellIsVacant(row + 2, col + 2))) {\n var adjacentId = occupiedArray[row + 1][col + 1].id;\n if (document.getElementById(adjacentId).classList.contains(\"black\") && (color == \"red\")) {\n return true;\n }\n else if (document.getElementById(adjacentId).classList.contains(\"red\") && (color == \"black\")) {\n return true;\n }\n }\n if (!outOfBounds(row + 2, col - 2) && (!cellIsVacant(row + 1, col - 1)) && (cellIsVacant(row + 2, col - 2))) {\n var adjacentId = occupiedArray[row + 1][col - 1].id;\n if (document.getElementById(adjacentId).classList.contains(\"black\") && (color == \"red\")) {\n return true;\n }\n else if (document.getElementById(adjacentId).classList.contains(\"red\") && (color == \"black\")) {\n return true;\n }\n }\n if (!outOfBounds(row - 2, col - 2) && (!cellIsVacant(row - 1, col - 1)) && (cellIsVacant(row - 2, col - 2))) {\n var adjacentId = occupiedArray[row - 1][col - 1].id;\n if (document.getElementById(adjacentId).classList.contains(\"black\") && (color == \"red\")) {\n return true;\n }\n else if (document.getElementById(adjacentId).classList.contains(\"red\") && (color == \"black\")) {\n return true;\n }\n }\n if (!outOfBounds(row - 2, col + 2) && (!cellIsVacant(row - 1, col + 1)) && (cellIsVacant(row - 2, col + 2))) {\n var adjacentId = occupiedArray[row - 1][col + 1].id;\n if (document.getElementById(adjacentId).classList.contains(\"black\") && (color == \"red\")) {\n return true;\n }\n else if (document.getElementById(adjacentId).classList.contains(\"red\") && (color == \"black\")) {\n return true;\n }\n }\n }\n if (document.getElementById(checkerId).classList.contains(\"black\")) {\n if (!outOfBounds(row + 2, col - 2) && (!cellIsVacant(row + 1, col - 1)) && (cellIsVacant(row + 2, col - 2))) {\n var adjacentId = occupiedArray[row + 1][col - 1].id;\n if (document.getElementById(adjacentId).classList.contains(\"red\")) {\n return true;\n }\n }\n if (!outOfBounds(row + 2, col + 2) && (!cellIsVacant(row + 1, col + 1)) && (cellIsVacant(row + 2, col + 2))) {\n var adjacentId = occupiedArray[row + 1][col + 1].id;\n if (document.getElementById(adjacentId).classList.contains(\"red\")) {\n return true;\n }\n }\n }\n if (document.getElementById(checkerId).classList.contains(\"red\")) {\n if (!outOfBounds(row - 2, col + 2) && (!cellIsVacant(row - 1, col + 1)) && (cellIsVacant(row - 2, col + 2))) {\n var adjacentId = occupiedArray[row - 1][col + 1].id;\n if (document.getElementById(adjacentId).classList.contains(\"black\")) {\n return true;\n }\n }\n if (!outOfBounds(row - 2, col - 2) && (!cellIsVacant(row - 1, col - 1)) && (cellIsVacant(row - 2, col - 2))) {\n var adjacentId = occupiedArray[row - 1][col - 1].id;\n if (document.getElementById(adjacentId).classList.contains(\"black\")) {\n return true;\n }\n }\n }\n return false;\n}", "function color() {\n //get all the cells in the table\n var currentCell = document.getElementsByTagName(\"td\");\n //We start from the seventh cell because that's where our number is and loop\n for (var i = 7; i < currentCell.length; i++) {\n if (parseInt(currentCell[i].textContent) >= 95) {\n currentCell[i].classList.add(\"pass\");\n }else if (parseInt(currentCell[i].textContent) >= 80) {\n currentCell[i].classList.add(\"average\");\n }else {\n currentCell[i].classList.add(\"fail\");\n }\n i += 3;\n }\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 calculateDiscoveredPercent() {\n\t// Zähler für die Zellen\n\tvar cellCount = 0;\n\t// Zähler für die aufgedeckten Zellen\n\tvar openCells = 0;\n\t\n\t// Über alle Zeilen iterieren...\n\tfor(var i = 0; i < arrayDimensionLine; i++) {\n\t\t// ...über alle spalten iterieren ...\n\t\tfor(var j = 0; j < arrayDimensionColumn; j++) {\n\t\t\t// ...prüfen, ob die Zelle auf der Map liegt...\n\t\t\tif(hexatileOnMap(i, j)) {\n\t\t\t\t// ...prüfen, ob die Zelle keine Miene ist...\n\t\t\t\tif(!gameField[i][j].isMine) {\n\t\t\t\t\t// ...Zähler für die Zellen hoch zählen\n\t\t\t\t\tcellCount++;\n\t\t\t\t}\n\t\t\t\t// ...prüfen, ob die Zelle aufgedeckt ist...\n\t\t\t\tif(gameField[i][j].isOpen) {\n\t\t\t\t\t// ...Zähler für die aufgedeckten Zellen hochzählen\n\t\t\t\t\topenCells++;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t\n\t// Gibt zurück, wieviel % der Zellen, welche keine Mienen sind aufgedeckt wurden\n\treturn (openCells * 100) / cellCount;\n}", "function chessBoardCellColor(cell1, cell2) {\n const sum =\n Math.abs(cell1.charCodeAt(0) - cell2.charCodeAt(0)) +\n Math.abs(parseInt(cell1[1]) - parseInt(cell2[1]));\n return sum % 2 === 0;\n}", "function checkColForThree() {\n for (i = 0; i < 48; i++) {\n //if we use indexes to draw our row, it would look like this\n let colOfThree = [i, i + width, i + 2 * width];\n //this is the color to eliminate\n let decidedColor = squares[i].style.backgroundImage;\n\n //below is a variable to confirm that we have cleared the colored squares\n //we'll use it as a boolean\n let isBlank = squares[i].style.backgroundImage === '';\n\n //if every index in our row of three array is\n // equal to squares grid color based on decided color\n // and we make sure it's not blank\n // index was created on the fly and passed through an arrow\n // funcion to act as index 0 to confirm the first box\n // has the same color as the decided color.\n if (\n colOfThree.every(\n (index) =>\n squares[index].style.backgroundImage === decidedColor && !isBlank\n )\n ) {\n //so, for each box in row of three we will set to\n // a blank color on the grid and give points\n score += 3;\n playScoreSound();\n scoreDisplay.innerHTML = score;\n colOfThree.forEach((index) => {\n squares[index].style.backgroundImage = '';\n });\n }\n }\n }", "checkInDiagonalTopRightBottomLeft(color){\n for(let col = 0; col < 15; col++){\n if(col>4){\n for(let row = 0; row < 10; row++)\n {\n let match = true;\n for(let i = 0; i < 5; i++)\n {\n if(color != game.board[row + i][col - i]){\n match = false;\n } \n }\n \n if(match){\n this.announceWinner();\n return;\n }\n }\n }\n } \n }", "function checkVictory(cléIndex) {\n var currentColor = cellProperties[cléIndex].couleur;\n var currentCol = cellProperties[cléIndex].col;\n var currentRow = cellProperties[cléIndex].row;\n var tokenHorizontal = 0;\n var tokenVertical = 0;\n var tokenDiagonalPositive = 0;\n var tokenDiagonalNegative = 0;\n var emptyCellFound = 0;\n\n\n // horizontal \n // coté gauche(check les cases à gauche du jeton joué)\n if (currentCol > 1) {\n for (i = currentCol; i > 1; i--) {\n colTest = \"col\" + (i - 1);\n if (cellProperties[colTest + 'row' + currentRow].couleur === currentColor) {\n tokenHorizontal += 1;\n }\n if (cellProperties[colTest + 'row' + currentRow].couleur != currentColor) {\n break;\n }\n if (tokenHorizontal >= 3) {\n victoire = true;\n console.log(\"Victoire Horizontale\");\n break;\n }\n }\n }\n // coté droit(check les cases à droite du jeton joué)\n if (currentCol < x && tokenHorizontal < 3 && x - currentCol > (3 - tokenHorizontal)) {\n for (i = currentCol; i > 0; i++) {\n colTest = \"col\" + (i + 1);\n if (cellProperties[colTest + 'row' + currentRow].couleur === currentColor) {\n tokenHorizontal += 1;\n }\n if (cellProperties[colTest + 'row' + currentRow].couleur != currentColor) {\n break;\n }\n if (tokenHorizontal >= 3) {\n victoire = true;\n console.log(\"Victoire Horizontale\");\n break;\n }\n }\n }\n\n // vertical (check les cases sous le jeton joué)\n if (currentRow <= (y - 3)) {\n for (i = currentRow; i < y; i++) {\n rowTest = \"row\" + (i + 1);\n if (cellProperties[\"col\" + currentCol + rowTest].couleur === currentColor) {\n tokenVertical += 1;\n }\n if (cellProperties[\"col\" + currentCol + rowTest].couleur != currentColor) {\n break;\n }\n if (tokenVertical >= 3) {\n victoire = true;\n console.log(\"Victoire Verticale\");\n break;\n }\n }\n }\n\n // diagonaux\n //diagonale positive\n // bas gauche (check les cases en bas à gauche en diagonale du jeton joué)\n if (currentRow < y && currentCol > 1) {\n for (i = currentRow, j = currentCol; i < y && j > 1; i++ , j--) {\n rowTest = \"row\" + (i + 1);\n colTest = \"col\" + (j - 1)\n\n if (cellProperties[colTest + rowTest].couleur === currentColor) {\n tokenDiagonalPositive += 1;\n }\n if (cellProperties[colTest + rowTest].couleur != currentColor) {\n break;\n }\n if (tokenDiagonalPositive >= 3) {\n victoire = true;\n console.log(\"Victoire Diagonale+\");\n break;\n }\n }\n }\n //diagonale positive\n // haut droit (check les cases en haut à droite en diagonale du jeton joué)\n if (currentRow > 1 && currentCol < x && (x - currentCol) > (3 - tokenDiagonalPositive) && currentRow > (3 - tokenDiagonalPositive)) {\n for (i = currentRow, j = currentCol; i > 1 && j < x; i-- , j++) {\n rowTest = \"row\" + (i - 1);\n colTest = \"col\" + (j + 1)\n\n if (cellProperties[colTest + rowTest].couleur === currentColor) {\n tokenDiagonalPositive += 1;\n }\n if (cellProperties[colTest + rowTest].couleur != currentColor) {\n break;\n }\n if (tokenDiagonalPositive >= 3) {\n victoire = true;\n console.log(\"Victoire Diagonale+\");\n break;\n }\n }\n }\n\n //diagonale negative\n // bas droite (check les cases en bas à droite en diagonale du jeton joué)\n if (currentRow < y && currentCol < x) {\n for (i = currentRow, j = currentCol; i < y && j < x; i++ , j++) {\n rowTest = \"row\" + (i + 1);\n colTest = \"col\" + (j + 1)\n\n if (cellProperties[colTest + rowTest].couleur === currentColor) {\n tokenDiagonalNegative += 1;\n }\n if (cellProperties[colTest + rowTest].couleur != currentColor) {\n break;\n }\n if (tokenDiagonalNegative >= 3) {\n victoire = true;\n console.log(\"Victoire Diagonale-\");\n break;\n }\n }\n }\n\n // diagonale negative\n // haut gauche (check les cases en bas à droite en diagonale du jeton joué)\n if (currentRow > 1 && currentCol > 1 && (currentCol - 1) > (3 - tokenDiagonalNegative) && currentRow > (3 - tokenDiagonalNegative)) {\n for (i = currentRow, j = currentCol; i > 1 && j > 1; i-- , j--) {\n rowTest = \"row\" + (i - 1);\n colTest = \"col\" + (j - 1)\n\n if (cellProperties[colTest + rowTest].couleur === currentColor) {\n tokenDiagonalNegative += 1;\n }\n if (cellProperties[colTest + rowTest].couleur != currentColor) {\n break;\n }\n if (tokenDiagonalNegative >= 3) {\n victoire = true;\n console.log(\"Victoire Diagonale-\");\n break;\n }\n }\n }\n\n // vérification du match nul en cas de complétion de grille\n if (currentRow == 1 && !victoire) {\n for (i = 1; i <= x; i++) {\n colTest = \"col\" + (i);\n if (cellProperties[colTest + 'row1'].couleur == 0) {\n emptyCellFound += 1;\n break;\n }\n }\n if (emptyCellFound == 0) {\n console.log('Match Nul')\n matchNul = true;\n }\n }\n\n } // crochet fin de fonction condition de victoire", "function canJump(row, col) {\n // true if cell is occupied, if a king check if in one of four directions the next checker is the opposite color and the next cell after that is empty...\n if (isAKing(occupiedArray[row][col].id)) {\n if (cellIsVacant(row + 2, col + 2) && (hasOppositeChecker(row + 1, col + 1, currentColor))) {\n return true;\n }\n if (cellIsVacant(row + 2, col - 2) && (hasOppositeChecker(row + 1, col - 1, currentColor))) {\n return true;\n }\n if (cellIsVacant(row - 2, col + 2) && (hasOppositeChecker(row - 1, col + 1, currentColor))) {\n return true;\n }\n if (cellIsVacant(row - 2, col - 2) && (hasOppositeChecker(row - 1, col - 1, currentColor))) {\n return true;\n }\n }\n else if (occupiedArray[row][col].classList.contains(\"red\")) {\n if (cellIsVacant(row - 2, col + 2) && (hasOppositeChecker(row - 1, col + 1, currentColor))) {\n return true;\n }\n if (cellIsVacant(row - 2, col - 2) && (hasOppositeChecker(row - 1, col - 1, currentColor))) {\n return true;\n }\n }\n else if (occupiedArray[row][col].classList.contains(\"black\")) {\n if (cellIsVacant(row + 2, col + 2) && (hasOppositeChecker(row + 1, col + 1, currentColor))) {\n return true;\n }\n if (cellIsVacant(row + 2, col - 2) && (hasOppositeChecker(row + 1, col - 1, currentColor))) {\n return true;\n }\n }\n return false;\n}", "function colorWithinRange(margin, webR, webG, webB, toReplace) {\n var distanceBetween = Math.sqrt(Math.pow(webR-toReplace.r,2)+Math.pow(webG-toReplace.g,2)+Math.pow(webB-toReplace.b,2));\n return distanceBetween<=margin;\n}", "function horizontalWinCheck() {\n for(var row=0;row<6;row++) {\n for(var col = 0;col < 4;col++){\n if(colorMatchCheck(returnColor(row,col), returnColor(row,col+1), returnColor(row,col+2))) {\n console.log('horizontal');\n reportWin(row,col);\n return true;\n }else {\n continue;\n }\n }\n }\n}", "checkInDiagonalTopLeftBottomRight(color){\n for(let col = 0; col < 10; col++){\n for(let row = 0; row < 10; row++)\n {\n let match = true;\n for(let i = 0; i < 5; i++)\n {\n if(color != game.board[row + i][col + i]){\n match = false;\n } \n }\n if(match){\n this.announceWinner();\n return;\n }\n }\n } \n }", "function check($cell){\n ['A','B','C'].forEach(function(dim){\n var failure = dim+'-failure',\n success = dim+'-success',\n cells = [];\n\n var c, d;\n \n // find the edge regex\n for (c = $cell; d = c.data('-'+dim); c = d) ;\n var regex = new RegExp('^'+ c.find('text').text() + '$');\n\n // find the row text\n while ((c = c.data('+'+dim)) && c.is('[class~=cell]'))\n cells.push(c);\n\n var str = cells.map(function(cell){ return $('text', cell).text(); }).join('');\n var $cells = $(cells).map(function(){ return this.toArray(); });\n\n if (str.length < $cells.length) {\n // incomplete\n $cells.removeClassSVG(success);\n $cells.removeClassSVG(failure);\n } else if (str.match(regex)) {\n // success\n $cells.addClassSVG(success);\n $cells.removeClassSVG(failure);\n } else {\n // failure\n $cells.addClassSVG(failure);\n $cells.removeClassSVG(success);\n }\n });\n }", "function check_vertical(row, col, color) {\n let count = 1\n let temp = row\n while (row > 0) {\n let $down_cell = get_cell(--row, col)\n if ($down_cell.css('backgroundColor') == color) {\n count += 1\n console.log('count +++ down')\n }\n else {\n break\n }\n }\n row = temp\n while (row < that.row) {\n let $up_cell = get_cell(++row, col)\n if ($up_cell.css('backgroundColor') == color) {\n count += 1\n console.log('count +++ right')\n }\n else {\n break\n }\n }\n if (count >= 4) {\n return true\n }\n return false\n }", "check_win(last_move) {\n let that = this\n console.log('this is in check win', this)\n let $last_cell = last_move\n if ($last_cell) {\n let row = $last_cell.attr('row')\n let col = $last_cell.attr('col')\n let color = $last_cell.css('backgroundColor')\n return (check_horizontal(row, col, color) ||\n check_vertical(row, col, color) ||\n check_top_left_bottom_right(row, col, color) ||\n check_top_right_bottom_left(row, col, color))\n }\n // get the cell with given row and col\n function get_cell(row, col) {\n return $(`.col[row='${row}'][col='${col}']`)\n }\n //check horizontal direction of this piece, if there is another piece with same color, count++\n //check left and right, break the loop if the piece next to it has a different color\n //if count >=3 which mean plus the last dropped piece, we have 4 pieces with same color, this is a win\n function check_horizontal(row, col, color) {\n let count = 1\n let temp = col\n while (col > 0) {\n let $left_cell = get_cell(row, --col)\n console.log(col, color, 'left count')\n console.log($left_cell)\n if ($left_cell.css('backgroundColor') == color) {\n count += 1\n console.log('count +++ left')\n }\n else {\n break\n }\n }\n col = temp\n while (col < that.col) {\n let $right_cell = get_cell(row, ++col)\n console.log(col, color, 'right count')\n console.log($right_cell)\n if ($right_cell.css('backgroundColor') == color) {\n count += 1\n console.log('count +++ right')\n }\n else {\n break\n }\n }\n if (count >= 4) {\n return true\n }\n return false\n }\n //check vertical direction of this piece\n function check_vertical(row, col, color) {\n let count = 1\n let temp = row\n while (row > 0) {\n let $down_cell = get_cell(--row, col)\n if ($down_cell.css('backgroundColor') == color) {\n count += 1\n console.log('count +++ down')\n }\n else {\n break\n }\n }\n row = temp\n while (row < that.row) {\n let $up_cell = get_cell(++row, col)\n if ($up_cell.css('backgroundColor') == color) {\n count += 1\n console.log('count +++ right')\n }\n else {\n break\n }\n }\n if (count >= 4) {\n return true\n }\n return false\n }\n //check top left to bottom right direction of this piece\n function check_top_left_bottom_right(row, col, color) {\n let count = 1\n let temp_row = row\n let temp_col = col\n while (row > 0 && col > 0) {\n let $next_cell = get_cell(--row, --col)\n if ($next_cell.css('backgroundColor') == color) {\n count += 1\n }\n else {\n break\n }\n }\n row = temp_row\n col = temp_col\n while (row < that.row && col < that.col) {\n let $up_cell = get_cell(++row, ++col)\n if ($up_cell.css('backgroundColor') == color) {\n count += 1\n }\n else {\n break\n }\n }\n if (count >= 4) {\n return true\n }\n return false\n }\n //check top right to bottom left direction of this piece\n function check_top_right_bottom_left(row, col, color) {\n let count = 1\n let temp_row = row\n let temp_col = col\n while (row < that.row && col > 0) {\n let $next_cell = get_cell(++row, --col)\n if ($next_cell.css('backgroundColor') == color) {\n count += 1\n }\n else {\n break\n }\n }\n row = temp_row\n col = temp_col\n while (row > 0 && col < that.col) {\n let $up_cell = get_cell(--row, ++col)\n if ($up_cell.css('backgroundColor') == color) {\n count += 1\n }\n else {\n break\n }\n }\n if (count >= 4) {\n return true\n }\n return false\n }\n }", "function checkRow3() {\n // loop over 3 edges\n for (let i = 0; i < 61; i++) {\n let rowOfThree = [i, i + 1, i + 2];\n let decidedcolor = squares[i].style.backgroundImage;\n const isBlank = squares[i].style.backgroundImage === \"\";\n const notValid = [6, 7, 14, 15, 22, 23, 30, 31, 38, 39, 46, 47, 54, 55];\n if (notValid.includes(i)) {\n continue;\n }\n if (\n // if all the three colors are same then we make them as blank\n rowOfThree.every(\n (index) => squares[index].style.backgroundImage === decidedcolor\n ) &&\n !isBlank\n ) {\n score += 3;\n scoreDisplay.innerHTML = score;\n rowOfThree.forEach((index) => {\n squares[index].style.backgroundImage = \"\";\n });\n }\n }\n }", "function horizontalWinCheck() {\r\n for (var row = 0; row < 6; row++) {\r\n for (var col = 0; col < 4; col++) {\r\n if (colorMatchCheck(returnColor(row,col), returnColor(row,col+1) ,returnColor(row,col+2), returnColor(row,col+3))) {\r\n console.log('horiz');\r\n reportWin(row,col);\r\n return true;\r\n }else {\r\n continue;\r\n }\r\n }\r\n }\r\n}", "function compareColor(pixR, pixG, pixB, opacity, refR, refG, refB, marginOfError) {\n if (opacity == 0) {\n return true;\n }\n if (Math.max(Math.abs(pixR-refR), Math.abs(pixG-refG), Math.abs(pixB - refB)) <= marginOfError) {\n return true;\n }\n return false;\n}", "checkCollision(x, y, excludedColorId, mouseX, mouseY) {\n for (let i = 0; i < colors.length; i++) { \n if (i == excludedColorId) {\n continue;\n }\n\n var elementX = x + (2 * i * this.cellPadding) - ((i == this.currentColorIndex) * 10), \n elementY = y - ((i == this.currentColorIndex) * 10), \n elementWidth = this.cellWidth + ((i == this.currentColorIndex) * 20), \n elementHeight = this.cellHeight + ((i == this.currentColorIndex) * 20);\n\n if (mouseY > elementY && mouseY < elementY + elementHeight\n && mouseX > elementX && mouseX < elementX + elementWidth) {\n return i;\n }\n }\n\n return -1;\n }", "function foodSpace(x,y){\n buffer = 7;\n for(let a = -buffer; a <= buffer; a++){\n for(let b = -buffer; b<=buffer; b++){\n predictedColor = _this.textures.getPixel(x + a, y + b,'map');\n if(predictedColor.g == 64 && predictedColor.b == 245){\n return false;\n }\n }\n }\n return true;\n }", "function checkVertical(){\n let winCount=0;\n let cell=table.rows[0].cells[0];\n for(let i=0; i<7; i++)\n {\n for(let j=0; j<6; j++)\n {\n cell=table.rows[j].cells[i];\n if(playerRed==true && cell.isRed)\n {\n winCount++;\n if(winCount>=4)\n {\n return(winCount);\n }\n }\n else if(playerYellow==true && cell.isYellow)\n {\n winCount++;\n if(winCount>=4)\n {\n return(winCount);\n }\n }\n else\n {\n winCount=0;\n }\n }\n }\n return(winCount);\n}", "isWhite (row, col) {\n let positionHash = (row * 31) ^ col;\n\n if (this.grid[positionHash] === 'W') {\n return true;\n } else if (this.grid[positionHash] === 'B') {\n return false;\n } else if ((row + col) % 2 === 0) {\n this.grid[positionHash] = 'W';\n return true;\n } else {\n this.grid[positionHash] = 'B';\n return false;\n }\n }", "function checkColForSix() {\n for (i = 0; i < 24; i++) {\n //if we use indexes to draw our row, it would look like this\n let colOfSix = [\n i,\n i + width,\n i + 2 * width,\n i + 3 * width,\n i + 4 * width,\n i + 5 * width,\n ];\n //this is the color to eliminate\n let decidedColor = squares[i].style.backgroundImage;\n let isBlank = squares[i].style.backgroundImage === '';\n\n if (\n colOfSix.every(\n (index) =>\n squares[index].style.backgroundImage === decidedColor && !isBlank\n )\n ) {\n score += 24;\n play8BitSound();\n scoreDisplay.innerHTML = score;\n colOfSix.forEach((index) => {\n squares[index].style.backgroundImage = '';\n });\n }\n }\n }", "function canMove(row, col) {\n if (!hasOppositeChecker(row, col, currentColor)) {\n if (isAKing(occupiedArray[row][col].id)) {\n if (!cellIsVacant(row + 1, col + 1) && !cellIsVacant(row + 1, col - 1) && !cellIsVacant(row - 1, col + 1) && !cellIsVacant(row - 1, col - 1)) {\n return false;\n }\n }\n else if (occupiedArray[row][col].classList.contains(\"black\")) {\n if (!cellIsVacant(row + 1, col - 1) && !cellIsVacant(row + 1, col + 1)) {\n return false;\n }\n }\n else if (occupiedArray[row][col].classList.contains(\"red\")) {\n if (!cellIsVacant(row - 1, col - 1) && !cellIsVacant(row - 1, col + 1)) {\n return false;\n }\n }\n return true;\n }\n}", "function isPercentage(range, value) {\n return ((value * (range[1] - range[0])) / 100) + range[0];\n }", "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 finds(i) {\n if (i >= 0 && i < 1464) {\n if (\n d[i].style.backgroundColor == scanColor ||\n d[i].style.backgroundColor == destinationColor ||\n d[i].style.backgroundColor == sourceColor\n ) {\n return true;\n }\n }\n return false;\n}", "function columnOfThree() {\n for (let i = 0; i < 47; i++) {\n decidedColor = squares[i].style.backgroundImage;\n decidedColor2 = squares[i + width].style.backgroundImage;\n decidedColor3 = squares[i + width * 2].style.backgroundImage;\n\n if (\n decidedColor !== \"\" &&\n decidedColor === decidedColor2 &&\n decidedColor2 === decidedColor3 &&\n decidedColor3 === decidedColor\n ) {\n score += 3;\n resultDisplay.innerHTML = score;\n squares[i].style.backgroundImage = \"\";\n squares[i + width].style.backgroundImage = \"\";\n squares[i + width * 2].style.backgroundImage = \"\";\n }\n }\n }", "function verticalWinCheck() {\r\n for (var col = 0; col < 7; col++) {\r\n for (var row = 0; row < 3; row++) {\r\n if (colorMatchCheck(returnColor(row,col), returnColor(row+1,col) ,returnColor(row+2,col), returnColor(row+3,col))) {\r\n console.log('vertical');\r\n reportWin(row,col);\r\n return true;\r\n }else {\r\n continue;\r\n }\r\n }\r\n }\r\n}", "function comparison(){\n\n var a1,a2,a3,a4,b1,b2,b3,b4,hint1,hint2,hint3,hint4;\n a1 = row[nbrOfRows].h1;\n a2 = row[nbrOfRows].h2;\n a3 = row[nbrOfRows].h3;\n a4 = row[nbrOfRows].h4;\n b1 = row[0].h1;\n b2 = row[0].h2;\n b3 = row[0].h3;\n b4 = row[0].h4;\n\n\n correctPosition=0; //Nbr of correct colors on correct position\n if (a1 == b1){correctPosition++;a1=1;b1=0;hint1=1}\n if (a2 == b2){correctPosition++;a2=1;b2=0;hint2=1}\n if (a3 == b3){correctPosition++;a3=1;b3=0;hint3=1}\n if (a4 == b4){correctPosition++;a4=1;b4=0;hint4=1}\n\n correctColour=0; //Nbr of correct colors on wrong position\n if (a1 == b2){correctColour++;a1=1;b2=0}\n if (a1 == b3){correctColour++;a1=1;b3=0}\n if (a1 == b4){correctColour++;a1=1;b4=0}\n\n if (a2 == b1){correctColour++;a2=1;b1=0}\n if (a2 == b3){correctColour++;a2=1;b3=0}\n if (a2 == b4){correctColour++;a2=1;b4=0}\n\n if (a3 == b1){correctColour++;a3=1;b1=0}\n if (a3 == b2){correctColour++;a3=1;b2=0}\n if (a3 == b4){correctColour++;a3=1;b4=0}\n\n if (a4 == b1){correctColour++;a4=1;b1=0}\n if (a4 == b2){correctColour++;a4=1;b2=0}\n if (a4 == b3){correctColour++;a4=1;b3=0}\n\n //Draw the hints on the side of the board\n var p = 9*box+4.8;\n for (i=0;i<4;i++){\n if (i<correctPosition){\n ctx.drawImage(red,p,selectedHole.y+8,box/2.5,box/2.5)}\n else if (i<correctPosition+correctColour){ctx.drawImage(white,p,selectedHole.y+8,box/2.5,box/2.5)}\n else {ctx.drawImage(empty,p,selectedHole.y+8,box/2.5,box/2.5)}\n p += 16.8;\n }\n \n if (correctPosition == 4){ // If colors correspond than we display the \"victory\" box\n document.getElementById(\"victoryMenu\").style.visibility=\"visible\";\n ctx.drawImage(row[0].h1,box*3,box*23,box,box);\n ctx.drawImage(row[0].h2,box*5,box*23,box,box);\n ctx.drawImage(row[0].h3,box*7,box*23,box,box);\n ctx.drawImage(row[0].h4,box*9,box*23,box,box);\n selectedHole.y = undefined; selectedHole.x = undefined;\n }\n else if (nbrOfRows == 11) { //If the colors are wrong and the it's the 11th row we display the \"defeat\" box\n document.getElementById(\"defeatMenu\").style.visibility=\"visible\";\n ctx.drawImage(row[0].h1,box*3,box*23,box,box);\n ctx.drawImage(row[0].h2,box*5,box*23,box,box);\n ctx.drawImage(row[0].h3,box*7,box*23,box,box);\n ctx.drawImage(row[0].h4,box*9,box*23,box,box);\n selectedHole.y = undefined; selectedHole.x = undefined;\n\n }\n\n document.getElementById(\"pts\").innerHTML=(-nbrOfRows+12)\n}", "function checkBottom(colIndex){\r\n var colorReport = returnColor(5, colIndex);\r\n for (var row = 5; row > -1; row--) {\r\n colorReport = returnColor(row, colIndex);\r\n if (colorReport === 'rgb(128, 128, 128)'){\r\n return row;\r\n }\r\n }\r\n}", "checkInVertical(color){\n let value = 0;\n for(let col=0; col<15; col++){\n value = 0;\n for(let row=0; row<15; row++){\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 isCollision(col, elem){\n var elementBottom = pixelToInt(elem.style.top) + pixelToInt(elem.style.height);\n var elementTop = pixelToInt(elem.style.top);\n\n for(var i = 0; i<col.length; i++){\n var eventBottom = pixelToInt(col[i].style.top) + pixelToInt(col[i].style.height);\n var eventTop = pixelToInt(col[i].style.top);\n\n if ((elementTop >= eventTop && elementTop < eventBottom) ||\n (elementBottom > eventTop && elementBottom <= eventBottom) ||\n (elementTop <= eventTop && elementBottom >= eventBottom) ) {\n return true;\n }\n }\n\n return false;\n }", "function checkRowForThree(){\n for(i=0; i<61; i++){\n\n let rowOfThree = [i, i+1, i+2]\n let decidedColor = squares[i].style.backgroundImage\n const isBlack = squares[i].style.backgroundImage === ''\n\n const notValid =[6, 7,14,15,22,30,31,38,39,46,47,54,55]\n if (notValid.includes(i)) continue\n\n if (rowOfThree.every(index => squares[index].style.backgroundImage === decidedColor && !isBlack)){\n score += 3\n squareDisplay.innerHTML= score\n rowOfThree.forEach(index => {\n squares[index].style.backgroundImage = ''\n })\n }\n }\n}", "function isPixelColored(imageData, pixel){\n return imageData[pixel] > 100 || imageData[pixel + 1] > 100 || imageData[pixel + 2] > 100;\n}", "hasOppReachedCenter(color, board) {\n if(color == \"white\")\n for(x = 3; x < 7; x++) {\n for(y = 0; y < 7; y++) {\n let piece = board.getPieceAtXY(x, y);\n if(piece != null && piece.color == this.oppColor) {\n return true;\n }\n }\n }\n return false;\n }", "function isPercentage(range, value) {\n return ((value * (range[1] - range[0])) / 100) + range[0];\n }", "function colormatch(){\n\n\nreminder = Math.abs(change % (2*Math.PI));\n\nif (reminder > 0 && reminder < quarter) obcolor= (by-b > 0)? paint[1]: paint[3];\nelse if (reminder > quarter && reminder < quarter*2) obcolor= (by-b > 0)? paint[2]: paint[0];\nelse if (reminder > quarter*2 && reminder < quarter*3 ) obcolor= (by-b > 0)? paint[3]: paint[1];\nelse if (reminder > quarter*3 && reminder < quarter*4) obcolor= (by-b > 0)? paint[0]: paint[2];\n\nif (bcolor == obcolor) return 0;\nelse return 1;\n}", "formatPrime(x, y){\n\t\tvar cell = this.tbl.rows[y].cells[x]\n\t\tif(this.primes.includes(parseInt(cell.innerHTML))){\n\t\t\tcell.style.backgroundColor = \"blue\"\n\t\t\tcell.style.color = \"white\"\n\t\t}\n\t}", "function isValidCellDev(row, col)\n{\n // IS IT OUTSIDE THE GRID?\n if ( (row < 0) ||\n (col < 0) ||\n (row >= gridHeightDev) ||\n (col >= gridWidthDev))\n {\n return false;\n }\n // IT'S INSIDE THE GRID\n else\n {\n return true;\n }\n}", "hit(cellIndex) {\n // The cell id puts the whole table into a single dimension. It simply needs to be between the topLeft and the bottomRight to qualify.\n return ((this.topLeft <= cellIndex) &&\n (cellIndex <= this.bottomRight));\n }", "getPercentageActOfCell( t, cellindices, threshold ){\n\t\tif( cellindices.length == 0 ){ return }\n\t\tvar i, count = 0\n\n\t\tfor( i = 0 ; i < cellindices.length ; i ++ ){\n\t\t\tif( this.C.pxact( cellindices[i] ) > threshold ){\n\t\t\t\tcount++\n\t\t\t}\n\t\t}\n\t\treturn 100*(count/cellindices.length)\n\t\n\t}", "function scoreCell(grid, r, c) {\n let maxRange;\n let cellScore;\n maxRange = Math.min(columns - c - 1, Math.min(c, Math.min(r, rows - r - 1)));\n for (let i = 1; i <= maxRange; i++) {\n if (grid[r - i][c] != 'G' ||\n grid[r + i][c] != 'G' ||\n grid[r][c - i] != 'G' ||\n grid[r][c + i] != 'G') {\n maxRange = i - 1;\n break;\n }\n }\n\n return maxRange;\n}", "function rule_check(cell_value)\r\n{\r\n // we could implement to just check if can be black since the squares are already white\r\n // but we want to show we understand the problem :)\r\n switch(cell_value)\r\n {\r\n case 0:\r\n return 0;\r\n case 1:\r\n return 1;\r\n case 2:\r\n return 0;\r\n case 3:\r\n return 1;\r\n case 4:\r\n return 1;\r\n case 5:\r\n return 0;\r\n case 6:\r\n return 1;\r\n default :\r\n return 0;\r\n }\r\n}", "function checkSubGridForWin(beginCol, endCol, beginRow, endRow, checkFunction) {\n var allColumns = $('div.column');\n for (var i = beginCol; i <= endCol; i++) {\n var currentColumnCircles = allColumns.eq(i).children();\n for(var j = beginRow; j <= endRow; j++) {\n var currentCircle = currentColumnCircles.eq(j);\n if(checkFunction(currentCircle)) { return true; };\n };\n };\n return false;\n}", "function checkRowForFour(){\n for(i=0; i<60; i++){\n\n let rowOfFour = [i,i+1, i+2, i+3]\n let decidedColor = squares[i].style.backgroundImage\n const isBlack = squares[i].style.backgroundImage === ''\n\n const notValid =[5,6,7,13,14,15,21,22,23,29,30,31,37,38,39,45,46,47,53,54,55]\n if (notValid.includes(i)) continue\n\n if (rowOfFour.every(index => squares[index].style.backgroundImage === decidedColor && !isBlack)){\n score += 4\n squareDisplay.innerHTML= score\n rowOfFour.forEach(index => {\n squares[index].style.backgroundImage = ''\n })\n }\n }\n}", "function checkRed(z,i,j) {\n var count = 0;\n try {\n count = (z[i][j+1] == 'red')? count+1 : count;\n } catch (e) {\n }\n try {\n count = (z[i][j-1] == 'red')? count+1 : count;\n } catch (e) {\n }\n try {\n count = (z[i+1][j] == 'red')? count+1 : count;\n } catch (e) {\n }\n try {\n count = (z[i-1][j] == 'red')? count+1 : count;\n } catch (e) {\n }\n return ((count ==1 )||(count == 2)||(count == 3))? true : false;\n}", "function isPercentage(range, value) {\n return (value * (range[1] - range[0])) / 100 + range[0];\n }", "function isPercentage(range, value) {\n return (value * (range[1] - range[0])) / 100 + range[0];\n }", "function isPercentage(range, value) {\n return (value * (range[1] - range[0])) / 100 + range[0];\n }", "function isPercentage(range, value) {\n return (value * (range[1] - range[0])) / 100 + range[0];\n }", "function isPercentage(range, value) {\n return (value * (range[1] - range[0])) / 100 + range[0];\n }", "function isPercentage(range, value) {\n return ((value * (range[1] - range[0])) / 100) + range[0];\n }", "function color_pct (ct) {\r\n return ct == \"Muy alto\" ? '#08519c':\r\n ct == \"Alto\" ? '#3182bd':\r\n ct == \"Medio\" ? '#6baed6':\r\n\t\t ct == \"Bajo\" ? '#bdd7e7':\r\n ct == \"Muy bajo\" ? '#eff3ff':\r\n '#fdfcfd';\r\n}", "function checkDiagUp(){\n let cell=table.rows[0].cells[0];\n for(let i=3; i<6; i++)\n {\n for(let j=3; j<7; j++)\n {\n cell=table.rows[i].cells[j];\n\n if(playerRed==true)\n {\n if(cell.isRed && table.rows[i-1].cells[j-1].isRed && table.rows[i-2].cells[j-2].isRed && table.rows[i-3].cells[j-3].isRed)\n {\n return(true);\n }\n }\n else\n {\n if(cell.isYellow && table.rows[i-1].cells[j-1].isYellow && table.rows[i-2].cells[j-2].isYellow && table.rows[i-3].cells[j-3].isYellow)\n {\n return(true);\n }\n }\n\n }\n }\n return(false);\n}", "capture_check(space) {\r\n if(space.occupied === this.color) {\r\n return false;\r\n } else if(space.occupied === 0) {\r\n return false;\r\n } else {\r\n return true;\r\n };\r\n }", "function checkVertical(board, color, row, col) {\n let counter = 0;\n for (let i = 0; i < 5; i++) {\n if (board[row + i][col] === color) {\n counter++;\n }\n }\n if (counter === 5)\n return true;\n return false;\n}", "checkCell( grid ){\n let flag = true;\n\n if( grid.x < 0 || grid.y < 0 || grid.x > this.const.m - 1 || grid.y > this.const.n - 1 )\n flag = false;\n\n return flag;\n }", "function hasOppositeChecker(row, col, color) {\n if ((row > 7) || (row < 0) || (col > 7) || (col < 0) || (occupiedArray[row][col] == null) || (occupiedArray[row][col].classList.contains(color))) {\n return false;\n }\n return true;\n}", "function verticalWinCheck() {\n for(var col=0;col<7;col++) {\n for(var row=0;row<3;row++) {\n if(colorMatchCheck(returnColor(row,col),returnColor(row+1,col),returnColor(row+2,col))) {\n console.log('vertical');\n reportWin(row,col);\n return true;\n }else {\n continue;\n }\n }\n }\n}", "function checkBelow(row, column) {\n if (!isEdge(row + 1, column) && tileArray[row][column] != null) {\n if (document.getElementById(\"center-tile\").style.backgroundColor == tileArray[row][column].style.backgroundColor) {\n return true;\n } else {\n return false;\n }\n } else {\n return !tileArray[row + 1][column];\n }\n }", "function isApproximately(a, b, withinPercent) {\n let percent = a / b * 100;\n Phoenix.log(percent);\n return percent > 100 - withinPercent && percent < 100 + withinPercent \n}", "function checkRowForThree() {\n for (i = 0; i < 61; i ++) {\n let rowOfThree = [i, i+1, i+2]\n let decidedColor = squares[i].style.backgroundImage\n const isBlank = squares[i].style.backgroundImage === ''\n const notValid=[6,7,14,15,30,31,38,39,46,47,54,55]\n if(notValid.includes(i))continue\n\n if(rowOfThree.every(index => squares[index].style.backgroundImage === decidedColor && !isBlank)) {\n score += 3\n scoreDisplay.innerHTML = score\n rowOfThree.forEach(index => {\n squares[index].style.backgroundImage = ''\n })\n }\n }\n }", "function isPercentage ( range, value ) {\n\t\treturn ((value * ( range[1] - range[0] )) / 100) + range[0];\n\t}", "function isPercentage ( range, value ) {\n\t\treturn ((value * ( range[1] - range[0] )) / 100) + range[0];\n\t}", "function isPercentage ( range, value ) {\n\t\treturn ((value * ( range[1] - range[0] )) / 100) + range[0];\n\t}", "function isPercentage ( range, value ) {\n\t\treturn ((value * ( range[1] - range[0] )) / 100) + range[0];\n\t}", "function isPercentage ( range, value ) {\n\t\treturn ((value * ( range[1] - range[0] )) / 100) + range[0];\n\t}", "function isPercentage ( range, value ) {\n\t\treturn ((value * ( range[1] - range[0] )) / 100) + range[0];\n\t}", "function isPercentage ( range, value ) {\n\t\treturn ((value * ( range[1] - range[0] )) / 100) + range[0];\n\t}", "function isPercentage ( range, value ) {\n\t\treturn ((value * ( range[1] - range[0] )) / 100) + range[0];\n\t}", "function isPercentage ( range, value ) {\n\t\treturn ((value * ( range[1] - range[0] )) / 100) + range[0];\n\t}", "function isPercentage ( range, value ) {\n\t\treturn ((value * ( range[1] - range[0] )) / 100) + range[0];\n\t}", "function isPercentage ( range, value ) {\n\t\treturn ((value * ( range[1] - range[0] )) / 100) + range[0];\n\t}", "function isPercentage ( range, value ) {\n\t\treturn ((value * ( range[1] - range[0] )) / 100) + range[0];\n\t}", "function isPercentage ( range, value ) {\n\t\treturn ((value * ( range[1] - range[0] )) / 100) + range[0];\n\t}", "function isPercentage ( range, value ) {\n\t\treturn ((value * ( range[1] - range[0] )) / 100) + range[0];\n\t}", "cellsOnNetwork(){\n\t\tvar px = this.C.cellborderpixels.elements, i,j, N, r = {}, t\n\t\tfor( i = 0 ; i < px.length ; i ++ ){\n\t\t\tt = this.C.pixti( px[i] )\n\t\t\tif( r[t] ) continue\n\t\t\tN = this.C.neighi( px[i] )\n\t\t\tfor( j = 0 ; j < N.length ; j ++ ){\n\t\t\t\tif( this.C.pixti( N[j] ) < 0 ){\n\t\t\t\t\tr[t]=1; break\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn r\n\t}", "function checkRow4() {\n // loop over 4 adjacent\n for (let i = 0; i < 60; i++) {\n let rowOfFour = [i, i + 1, i + 2, i + 3];\n let decidedcolor = squares[i].style.backgroundImage;\n const isBlank = squares[i].style.backgroundImage === \"\";\n const notValid = [\n 5, 6, 7, 13, 14, 15, 21, 22, 23, 29, 30, 31, 37, 38, 39, 45, 46, 47, 53,\n 54, 55,\n ];\n if (notValid.includes(i)) {\n continue;\n }\n if (\n // if all the four colors are same then we make them as blank\n rowOfFour.every(\n (index) => squares[index].style.backgroundImage === decidedcolor\n ) &&\n !isBlank\n ) {\n score += 4;\n scoreDisplay.innerHTML = score;\n rowOfFour.forEach((index) => {\n squares[index].style.backgroundImage = \"\";\n });\n }\n }\n }" ]
[ "0.6406898", "0.6222122", "0.61729646", "0.6170448", "0.6154012", "0.6141928", "0.61248255", "0.6078453", "0.6069174", "0.60585034", "0.6043805", "0.6043218", "0.6040962", "0.60309166", "0.60159826", "0.601457", "0.598948", "0.5909673", "0.59022063", "0.58996695", "0.5872446", "0.5836742", "0.5811671", "0.57976496", "0.5776682", "0.57678497", "0.57674336", "0.5761399", "0.57600296", "0.57481605", "0.5743737", "0.57349056", "0.5722964", "0.5718952", "0.57171357", "0.5713476", "0.5694836", "0.5694472", "0.5680315", "0.56795645", "0.56397974", "0.56191266", "0.5618684", "0.56180257", "0.5616659", "0.560226", "0.56004393", "0.55826014", "0.5576821", "0.5572006", "0.55706996", "0.5568399", "0.55654323", "0.5564726", "0.55633163", "0.55597776", "0.55543584", "0.5554198", "0.5545829", "0.55425197", "0.55409956", "0.55379105", "0.55357623", "0.5533317", "0.55249107", "0.5521305", "0.55064255", "0.55063146", "0.55036116", "0.55036116", "0.55036116", "0.55036116", "0.55036116", "0.5498435", "0.54932296", "0.54848194", "0.5484279", "0.5475001", "0.54730403", "0.545738", "0.5452255", "0.54513067", "0.5450375", "0.5442305", "0.5441379", "0.5441379", "0.5441379", "0.5441379", "0.5441379", "0.5441379", "0.5441379", "0.5441379", "0.5441379", "0.5441379", "0.5441379", "0.5441379", "0.5441379", "0.5441379", "0.54321605", "0.54321486" ]
0.6431092
0
Ensure that our bucket exists
async init() { this.debug(`creating ${this.bucket}`); await createS3Bucket(this.s3, this.bucket, this.region, this.acl, this.lifespan); this.debug(`creating ${this.bucket}`); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "async createBucketIfNotExists() {\n const bucket = this.templates.create.Resources[this.getBucketId()].Properties;\n const foundBucket = await this.provider.getBucket(bucket.BucketName);\n if (foundBucket) {\n this.serverless.cli.log(`Bucket ${bucket.BucketName} already exists.`);\n } else {\n this.serverless.cli.log(`Creating bucket ${bucket.BucketName}...`);\n await this.provider.createBucket(bucket.BucketName);\n await this.setBucketWebsite(bucket.BucketName);\n await this.setBucketPublic(bucket.BucketName);\n this.serverless.cli.log(`Created bucket ${bucket.BucketName}`);\n }\n\n this.provider.resetOssClient(bucket.BucketName);\n }", "bucketExists(bucket, cb) {\n if (!validateBucketName(bucket)) {\n throw new errors.InvalidateBucketNameException('Invalid bucket name: ' + bucket)\n }\n this.bucketRequest('HEAD', bucket, cb)\n }", "bucketExists(bucketName, cb) {\n if (!isValidBucketName(bucketName)) {\n throw new errors.InvalidBucketNameError('Invalid bucket name: ' + bucketName)\n }\n if (!isFunction(cb)) {\n throw new TypeError('callback should be of type \"function\"')\n }\n var method = 'HEAD'\n this.makeRequest({ method, bucketName }, '', [200], '', false, (err) => {\n if (err) {\n if (err.code == 'NoSuchBucket' || err.code == 'NotFound') {\n return cb(null, false)\n }\n return cb(err)\n }\n cb(null, true)\n })\n }", "function check_if_the_bucket_exists(container)\n{\n\treturn new Promise(function(resolve, reject) {\n\n\t\t//\n\t\t// 1. List all buckets.\n\t\t//\n\t\ts3.listBuckets(function(req_error, data) {\n\n\t\t\t//\n\t\t\t// 1. Check for an error.\n\t\t\t//\n\t\t\tif(req_error)\n\t\t\t{\n\t\t\t\treturn reject(req_error);\n\t\t\t}\n\n\t\t\t//\n\t\t\t// 2. Create a variable that will help us understand if the bucket\n\t\t\t// that we care about exists.\n\t\t\t//\n\t\t\tlet was_bucket_found = false;\n\n\t\t\t//\n\t\t\t// 3. Loop over the buckets that we got back to see if there is\n\t\t\t// the one that we care about.\n\t\t\t//\n\t\t\tfor(let index in data.Buckets)\n\t\t\t{\n\t\t\t\t//\n\t\t\t\t// 1. Compare each bucket with what we want.\n\t\t\t\t//\n\t\t\t\tif(\"repos.dev\" == data.Buckets[index].Name)\n\t\t\t\t{\n\t\t\t\t\twas_bucket_found = true;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t//\n\t\t\t// 4. Check if the bucket still exists before we try to save to\n\t\t\t// it.\n\t\t\t//\n\t\t\tif(!was_bucket_found)\n\t\t\t{\n\t\t\t\tlet error = new Error(\"The bucket with the repos disappeared\");\n\n\t\t\t\treturn reject(error);\n\t\t\t}\n\n\t\t\t//\n\t\t\t// -> Move to the next chain.\n\t\t\t//\n\t\t\treturn resolve(container);\n\n\t\t});\n\n\t});\n}", "function onInitialized(response) {\n\n var createIfNotExists = true;\n\n var bucketCreationData = {\n bucketKey: config.defaultBucketKey,\n servicesAllowed: [],\n policy: 'persistent' //['temporary', 'transient', 'persistent']\n };\n\n lmv.getBucket(config.defaultBucketKey,\n createIfNotExists,\n bucketCreationData).then(\n onBucketCreated,\n onError);\n }", "function insertBucket() {\n resource = {\n 'name': BUCKET\n };\n\n var request = gapi.client.storage.buckets.insert({\n 'project': PROJECT,\n 'resource': resource\n });\n executeRequest(request, 'insertBucket');\n}", "function createBucket() {\n metadata\n .buckets.set(bucketName, new BucketInfo(bucketName, ownerID, '', ''));\n metadata.keyMaps.set(bucketName, new Map);\n}", "function createBucket(){\n // Create S3 service object\n s3 = new AWS.S3({apiVersion: '2006-03-01'});\n\n // Create the parameters for calling createBucket\n var bucketParams = {\n Bucket : process.argv[2],\n ACL : 'public-read'\n };\n\n // call S3 to create the bucket\n s3.createBucket(bucketParams, function(err, data) {\n if (err) {\n console.log(\"Error\", err);\n } else {\n console.log(\"Success\", data.Location);\n }\n });\n}", "function validateBucket(name) {\n if (!validBucketRe.test(name)) {\n throw new Error(`invalid bucket name: ${name}`);\n }\n}", "* exists (path) {\n return new Promise((resolve, reject) => {\n this.s3.headObject({\n Bucket: this.disk.bucket,\n Key: path\n }, (err, data) => {\n if (err) {\n if (err.code === 'NotFound') {\n return resolve(false)\n }\n return reject(err)\n }\n return resolve(true)\n })\n })\n }", "manageBucketPointer(){\n if (fs.existsSync(this.file_bucket_path)) {\n let data=fs.readFileSync(this.file_bucket_path);\n this.bucket=JSON.parse(data);\n this.updateFilePointerBucket();\n }else{\n this.createFilePointerBucket();\n } \n }", "function before (s3, bucket, keys, done) {\n createBucket(s3, bucket)\n .then(function () {\n return when.all(\n // Swallow deleteObject errors here incase the files don't yet exist\n keys.map(function (key) { return deleteObject(s3, bucket, key).catch(function () {}); })\n )\n }).then(function () { done(); });\n}", "function getBucket() {\n var request = gapi.client.storage.buckets.get({\n 'bucket': BUCKET\n });\n executeRequest(request, 'getBucket');\n}", "function createBucket(region, bucket) {\n return regionBucket(region, bucket, {\n create: true,\n ACL: 'private'\n });\n}", "getBucket() {\n const headers = {\n Date: this._buildDateHeader(),\n };\n\n const authHeader = this._buildAuthHeader('GET', '', {}, headers);\n const fetchOptions = {\n method: 'GET',\n headers: {\n Authorization: authHeader,\n },\n };\n\n return new Promise((resolve, reject) => {\n fetch(this.bucketBaseUrl, fetchOptions)\n .then(res => resolve(res))\n .catch(err => reject(err));\n });\n }", "makeBucket(bucket, cb) {\n return this.makeBucketWithACL(bucket, 'private', cb)\n }", "function rememberToDeleteBucket(bucketName) {\n bucketsToDelete.push(bucketName);\n}", "function BucketEmptyError(bucket, limiterId) {\n Error.call(this);\n // captureStackTrace is V8-only (node, chrome)\n Error.captureStackTrace(this, BucketEmptyError);\n\n this.name = 'BucketEmptyError';\n this.message = util.format('%s - All {%d} tokens from this bucket have been used. Retry after %s',\n limiterId || 'anonymous limiter',\n bucket.limit,\n new Date(parseInt(bucket.reset, 10))\n );\n}", "async function fileExists (file) {\n // https://googlecloudplatform.github.io/google-cloud-node/#/docs/storage/1.2.0/storage/bucket?method=exists\n return file.exists().then((data) => {\n return data[0];\n })\n}", "function checkBucket() {\n\n // reset the file arrays\n missingFilesArry = []\n receivedFilesArry = []\n\n const paramsArray = FILE_NAMES\n .map(file => file.replace(PLACEHOLDER_DASH, checkDateDash))\n .map(file => file.replace(PLACEHOLDER_NODASH, checkDateNoDash))\n .map(fileName => ({Bucket: BUCKET, Key: fileName}))\n\n const RESULTS = waitAllFailSlow(paramsArray.map(getFile))\n .then(results => {\n // this is what happens when no fails...\n //console.log(\"WOOT WOOT!!!\")\n //console.log(results)\n console.log(\"SUCCESS: checkBucket() passed successfully.\")\n })\n .catch(err => {\n // this is the error for fail fast\n console.log(\"ERROR ENCOUNTERED: checkBucket()\")\n //console.log(err)\n //if (\"code\" in err[0] && err[0][\"code\"] == \"NoSuchKey\") { console.log(\"FILE NOT FOUND ACE\")} else {console.log(\"No code Ace\")}\n\n })\n //console.log(\"OUTSIDE=========1========\")\n return RESULTS\n\n}", "function _checkBucket ( routePathname, containerObject, successCallback ) {\n var routes = containerObject[Route.splitLength(routePathname)];\n return _checkRouteArray( routePathname, routes, successCallback );\n }", "function putBucketAcl() {\n const putBucketAclParams = {\n Bucket: bucket,\n ACL: 'authenticated-read',\n };\n s3Client.putBucketAcl(putBucketAclParams, (err, data) => {\n if (err) console.log('err:', err);\n else console.log('data:', data);\n });\n}", "function deleteBucket() {\n var request = gapi.client.storage.buckets.delete({\n 'bucket': BUCKET\n });\n executeRequest(request, 'deleteBucket');\n}", "async function emptyAndDeleteFolderOfBucket() {\n s3=new AWS.S3({apiVersion: '2006-03-01'});\n const listParams = {\n Bucket:process.argv[2],\n Prefix:process.argv[3]\n };\n\n const listedObjects = await s3.listObjectsV2(listParams).promise();\n\n if (listedObjects.Contents.length === 0) return;\n\n const deleteParams = {\n Bucket: process.argv[2],\n Delete: { Objects: [] }\n };\n\n listedObjects.Contents.forEach(({ Key }) => {\n deleteParams.Delete.Objects.push({ Key });\n });\n\n await s3.deleteObjects(deleteParams).promise();\n\n if (listedObjects.IsTruncated) await emptyAndDeleteFolderOfBucket(process.argv[2], process.argv[3]);\n}", "function createBucketWithReplication(hasStorageClass) {\n createBucket();\n const config = {\n role: 'arn:aws:iam::account-id:role/src-resource,' +\n 'arn:aws:iam::account-id:role/dest-resource',\n destination: 'arn:aws:s3:::source-bucket',\n rules: [{\n prefix: keyA,\n enabled: true,\n id: 'test-id',\n }],\n };\n if (hasStorageClass) {\n config.rules[0].storageClass = storageClassType;\n }\n Object.assign(metadata.buckets.get(bucketName), {\n _versioningConfiguration: { status: 'Enabled' },\n _replicationConfiguration: config,\n });\n}", "addBucket() {\n\t\tthis.setState({\n\t\t\tmodel_title: \"Add Bucket\",\n\t\t\tbucket_name: \"\",\n\t\t\tbucket_id: \"\"\n\t\t})\n\t}", "async function createS3Bucket(s3, name, region, acl, lifecycleDays = 1) {\n assert(s3);\n assert(name);\n assert(region);\n assert(acl);\n assert(typeof lifecycleDays === 'number');\n if (!validateS3BucketName(name, true)) {\n throw new Error(`Bucket ${name} is not valid`);\n }\n\n let params = {\n Bucket: name,\n ACL: acl,\n };\n\n if (region !== 'us-east-1') {\n params.CreateBucketConfiguration = {\n LocationConstraint: region,\n };\n }\n\n try {\n debug(`Creating S3 Bucket ${name} in ${region}`);\n await s3.createBucket(params).promise();\n debug(`Created S3 Bucket ${name} in ${region}`);\n } catch (err) {\n switch (err.code) {\n case 'BucketAlreadyExists':\n case 'BucketAlreadyOwnedByYou':\n break;\n default:\n throw err;\n }\n }\n\n params = {\n Bucket: name,\n LifecycleConfiguration: {\n Rules: [\n {\n ID: region + '-' + lifecycleDays + '-day',\n Prefix: '',\n Status: 'Enabled',\n Expiration: {\n Days: lifecycleDays,\n },\n },\n ],\n },\n };\n\n debug(`Setting S3 lifecycle configuration for ${name} in ${region}`);\n await s3.putBucketLifecycleConfiguration(params).promise();\n debug(`Set S3 lifecycle configuration for ${name} in ${region}`);\n}", "resetBucket() {\n this.cacheBucket = '';\n }", "function composable(callback: (err?: Error) => void) {\n bucket.upsert('key', {value: 1}, callback);\n}", "presignedPutObject(bucketName, objectName, expires, cb) {\n if (!isValidBucketName(bucketName)) {\n throw new errors.InvalidBucketNameError(`Invalid bucket name: ${bucketName}`)\n }\n if (!isValidObjectName(objectName)) {\n throw new errors.InvalidObjectNameError(`Invalid object name: ${objectName}`)\n }\n return this.presignedUrl('PUT', bucketName, objectName, expires, cb)\n }", "async exists(options = {}) {\n const { span, updatedOptions } = createSpan(\"BlobClient-exists\", options);\n try {\n ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps);\n await this.getProperties({\n abortSignal: options.abortSignal,\n customerProvidedKey: options.customerProvidedKey,\n conditions: options.conditions,\n tracingOptions: updatedOptions.tracingOptions,\n });\n return true;\n }\n catch (e) {\n if (e.statusCode === 404) {\n // Expected exception when checking blob existence\n return false;\n }\n else if (e.statusCode === 409 &&\n (e.details.errorCode === BlobUsesCustomerSpecifiedEncryptionMsg ||\n e.details.errorCode === BlobDoesNotUseCustomerSpecifiedEncryption)) {\n // Expected exception when checking blob existence\n return true;\n }\n span.setStatus({\n code: coreTracing.SpanStatusCode.ERROR,\n message: e.message,\n });\n throw e;\n }\n finally {\n span.end();\n }\n }", "async exists(options = {}) {\n const { span, updatedOptions } = createSpan(\"BlobClient-exists\", options);\n try {\n ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps);\n await this.getProperties({\n abortSignal: options.abortSignal,\n customerProvidedKey: options.customerProvidedKey,\n conditions: options.conditions,\n tracingOptions: updatedOptions.tracingOptions,\n });\n return true;\n }\n catch (e) {\n if (e.statusCode === 404) {\n // Expected exception when checking blob existence\n return false;\n }\n else if (e.statusCode === 409 &&\n (e.details.errorCode === BlobUsesCustomerSpecifiedEncryptionMsg ||\n e.details.errorCode === BlobDoesNotUseCustomerSpecifiedEncryption)) {\n // Expected exception when checking blob existence\n return true;\n }\n span.setStatus({\n code: coreTracing.SpanStatusCode.ERROR,\n message: e.message,\n });\n throw e;\n }\n finally {\n span.end();\n }\n }", "function putObject(keyName) {\n const putObjectParams = {\n Bucket: bucket,\n Key: keyName,\n Metadata: {\n importance: 'very',\n ranking: 'middling',\n },\n Body: 'putMe',\n };\n s3Client.putObject(putObjectParams, (err, data) => {\n if (err) console.log('err:', err);\n else console.log('data:', data);\n });\n}", "async function createCollectionIfNotExists (name) {\n // requires list buckets...\n const collections = await database.getCollectionNames()\n // console.log('Database collections', collections)\n\n if (!collections.includes(name)) {\n const collection = await database.createCollection(name)\n // console.log('collection: (created)', collection.getFQN())\n return collection\n }\n\n const collection = await database.getCollection(name)\n // console.log('collection: (existing)', collection.getFQN())\n return collection\n}", "function onBucketCreated(response) {\n\n console.log('[Uploading to A360 started...] ' +jobStatus.jobId);\n\n fs.stat(serverFile, function (err, stats) {\n if (err) {\n console.log('Uploading to A360 failed...' + err);\n }\n var total = stats.size;\n var chunkSize = config.fileResumableChunk * 1024 * 1024;\n\n if( total > chunkSize)\n {\n console.log(' Resumable uploading for large file...' +jobStatus.jobId);\n\n lmv.resumableUpload(serverFile,\n config.defaultBucketKey,\n jobStatus.jobId,uploadProgressCallback).then(onResumableUploadCompleted, onError);\n }\n else\n {\n //single uploading\n console.log(' Single uploading for small file...' +jobStatus.jobId);\n lmv.upload(serverFile,\n config.defaultBucketKey,\n jobStatus.jobId).then(onSingleUploadCompleted, onError);\n }\n });\n }", "function _isBucketStorage(storageType) {\n\treturn !!storageTypes[storageType];\n}", "async createIfNotExists(options = {}) {\n var _a, _b;\n const { span, updatedOptions } = createSpan(\"AppendBlobClient-createIfNotExists\", options);\n const conditions = { ifNoneMatch: ETagAny };\n try {\n const res = await this.create(Object.assign(Object.assign({}, updatedOptions), { conditions }));\n return Object.assign(Object.assign({ succeeded: true }, res), { _response: res._response });\n }\n catch (e) {\n if (((_a = e.details) === null || _a === void 0 ? void 0 : _a.errorCode) === \"BlobAlreadyExists\") {\n span.setStatus({\n code: coreTracing.SpanStatusCode.ERROR,\n message: \"Expected exception when creating a blob only if it does not already exist.\",\n });\n return Object.assign(Object.assign({ succeeded: false }, (_b = e.response) === null || _b === void 0 ? void 0 : _b.parsedHeaders), { _response: e.response });\n }\n span.setStatus({\n code: coreTracing.SpanStatusCode.ERROR,\n message: e.message,\n });\n throw e;\n }\n finally {\n span.end();\n }\n }", "async createIfNotExists(options = {}) {\n var _a, _b;\n const { span, updatedOptions } = createSpan(\"AppendBlobClient-createIfNotExists\", options);\n const conditions = { ifNoneMatch: ETagAny };\n try {\n const res = await this.create(Object.assign(Object.assign({}, updatedOptions), { conditions }));\n return Object.assign(Object.assign({ succeeded: true }, res), { _response: res._response });\n }\n catch (e) {\n if (((_a = e.details) === null || _a === void 0 ? void 0 : _a.errorCode) === \"BlobAlreadyExists\") {\n span.setStatus({\n code: coreTracing.SpanStatusCode.ERROR,\n message: \"Expected exception when creating a blob only if it does not already exist.\",\n });\n return Object.assign(Object.assign({ succeeded: false }, (_b = e.response) === null || _b === void 0 ? void 0 : _b.parsedHeaders), { _response: e.response });\n }\n span.setStatus({\n code: coreTracing.SpanStatusCode.ERROR,\n message: e.message,\n });\n throw e;\n }\n finally {\n span.end();\n }\n }", "function checkBucketConfig(config) {\n assert(config.bucket,\n '[egg-oss] Must set `bucket` in ess\\'s config');\n assert(config.ess_public_key && config.ess_private_key,\n '[egg-oss] Must set `ess_public_key` and `ess_private_key` in ess\\'s config');\n\n // if (config.endpoint && RE_HTTP_PROTOCOL.test(config.endpoint)) {\n // config.endpoint = config.endpoint.replace(RE_HTTP_PROTOCOL, '');\n // }\n}", "__validate(bucket, key) {\n return (!bucket.includes(DELIM)) && (!key.toString().includes(DELIM));\n }", "function uploadFileIntoBucket(){\n // Create S3 service object\n s3 = new AWS.S3({apiVersion: '2006-03-01'});\n\n // call S3 to retrieve upload file to specified bucket\n var uploadParams = {Bucket: process.argv[2], Key: '', Body: ''};\n var file = process.argv[3];\n\n // Configure the file stream and obtain the upload parameters\n var fs = require('fs');\n var fileStream = fs.createReadStream(file);\n fileStream.on('error', function(err) {\n console.log('File Error', err);\n });\n\n uploadParams.Body = fileStream;\n var path = require('path');\n uploadParams.Key = path.basename(file);\n\n // call S3 to retrieve upload file to specified bucket\n s3.upload (uploadParams, function (err, data) {\n if (err) {\n console.log(\"Error\", err);\n } if (data) {\n console.log(\"Upload Success\", data.Location);\n }\n });\n}", "function parseBucketName(url) {\n\n let bucket;\n let object;\n\n if (url.startsWith(\"gs://\")) {\n const i = url.indexOf('/', 5);\n if (i >= 0) {\n bucket = url.substring(5, i);\n const qIdx = url.indexOf('?');\n object = (qIdx < 0) ? url.substring(i + 1) : url.substring(i + 1, qIdx);\n }\n\n } else if (url.startsWith(\"https://storage.googleapis.com\") || url.startsWith(\"https://storage.cloud.google.com\")) {\n const bucketIdx = url.indexOf(\"/v1/b/\", 8)\n if (bucketIdx > 0) {\n const objIdx = url.indexOf(\"/o/\", bucketIdx);\n if (objIdx > 0) {\n const queryIdx = url.indexOf(\"?\", objIdx);\n bucket = url.substring(bucketIdx + 6, objIdx);\n object = queryIdx > 0 ? url.substring(objIdx + 3, queryIdx) : url.substring(objIdx + 3);\n }\n\n } else {\n const idx1 = url.indexOf(\"/\", 8);\n const idx2 = url.indexOf(\"/\", idx1+1);\n const idx3 = url.indexOf(\"?\", idx2);\n if (idx2 > 0) {\n bucket = url.substring(idx1+1, idx2);\n object = idx3 < 0 ? url.substring(idx2+1) : url.substring(idx2+1, idx3);\n }\n }\n\n } else if (url.startsWith(\"https://www.googleapis.com/storage/v1/b\")) {\n const bucketIdx = url.indexOf(\"/v1/b/\", 8);\n const objIdx = url.indexOf(\"/o/\", bucketIdx);\n if (objIdx > 0) {\n const queryIdx = url.indexOf(\"?\", objIdx);\n bucket = url.substring(bucketIdx + 6, objIdx);\n object = queryIdx > 0 ? url.substring(objIdx + 3, queryIdx) : url.substring(objIdx + 3);\n }\n }\n\n if (bucket && object) {\n return {\n bucket, object\n }\n } else {\n throw Error(`Unrecognized Google Storage URI: ${url}`)\n }\n\n}", "async AssetExists(ctx, key) {\n const value = await ctx.stub.getState(key);\n return value && value.length > 0;\n }", "async ensureDestroyed() {\n let exists = await this.checkExists()\n if (!exists) {\n return true\n } else {\n await this.destroy({credentials: {skipPermissionCheck: true}})\n return await this.ensureDestroyed()\n }\n }", "function DeleteBucket(filePath) {\n const bucket = functions.config().firebase.storageBucket\n const myBucket = gcs.bucket(bucket);\n const file = myBucket.file(filePath);\n console.log(`${myBucket},${filePath}, ${file}`)\n if (file.exists()){\n return file.delete();\n }\n else {\n return;\n }\n\n}", "function makeSureExists(path) {\n try {\n fs.mkdirSync(path);\n } catch (e) {\n if (e.code != 'EEXIST') {\n throw e;\n }\n }\n}", "removeBucket(bucket, cb) {\n if (!validateBucketName(bucket)) {\n throw new errors.InvalidateBucketNameException('Invalid bucket name: ' + bucket)\n }\n this.bucketRequest('DELETE', bucket, cb)\n }", "function onBucketCreated(response) {\n\n console.log('Uploading to A360 started...');\n\n fs.stat(serverFile, function (err, stats) {\n if (err) {\n console.log('Uploading to A360 failed...' + err);\n res.send('err',err);\n }\n var total = stats.size;\n var chunkSize = config.fileResumableChunk * 1024 * 1024;\n\n if( total > chunkSize)\n {\n console.log(' Resumable uploading for large file...');\n\n lmv.resumableUpload(serverFile,\n config.defaultBucketKey,\n filename,uploadProgressCallback).then(onResumableUploadCompleted, onError);\n }\n else\n {\n //single uploading\n console.log(' Single uploading for small file...');\n lmv.resumableUpload(serverFile,\n config.defaultBucketKey,\n filename).then(onSingleUploadCompleted, onError);\n }\n //guid for checking uploading status\n res.send({uploadguid:newGuid()});\n });\n }", "function verifyFileInS3(req, res) {\n function headReceived(err, data) {\n if (err) {\n res.status(500);\n console.log(err);\n res.end(JSON.stringify({error: \"Problem querying S3!\"}));\n }\n else if (expectedMaxSize != null && data.ContentLength > expectedMaxSize) {\n res.status(400);\n res.write(JSON.stringify({error: \"Too big!\"}));\n deleteFile(req.body.bucket, req.body.key, function(err) {\n if (err) {\n console.log(\"Couldn't delete invalid file!\");\n }\n\n res.end();\n });\n }\n else {\n res.end();\n }\n }\n\n callS3(\"head\", {\n bucket: req.body.bucket,\n key: req.body.key\n }, headReceived);\n}", "function checkExists(dir) {\n fs.exists(dir, function(exists) {\n if (!exists) {\n mkdirp(dir, function(err) {\n if (err) console.error(err);\n else console.log('The uploads folder was not present, we have created it for you [' + dir + ']');\n });\n //throw new Error(dir + ' does not exists. Please create the folder');\n }\n });\n}", "async createIfNotExists(size, options = {}) {\n var _a, _b;\n const { span, updatedOptions } = createSpan(\"PageBlobClient-createIfNotExists\", options);\n try {\n const conditions = { ifNoneMatch: ETagAny };\n const res = await this.create(size, Object.assign(Object.assign({}, options), { conditions, tracingOptions: updatedOptions.tracingOptions }));\n return Object.assign(Object.assign({ succeeded: true }, res), { _response: res._response });\n }\n catch (e) {\n if (((_a = e.details) === null || _a === void 0 ? void 0 : _a.errorCode) === \"BlobAlreadyExists\") {\n span.setStatus({\n code: coreTracing.SpanStatusCode.ERROR,\n message: \"Expected exception when creating a blob only if it does not already exist.\",\n });\n return Object.assign(Object.assign({ succeeded: false }, (_b = e.response) === null || _b === void 0 ? void 0 : _b.parsedHeaders), { _response: e.response });\n }\n span.setStatus({\n code: coreTracing.SpanStatusCode.ERROR,\n message: e.message,\n });\n throw e;\n }\n finally {\n span.end();\n }\n }", "async createIfNotExists(size, options = {}) {\n var _a, _b;\n const { span, updatedOptions } = createSpan(\"PageBlobClient-createIfNotExists\", options);\n try {\n const conditions = { ifNoneMatch: ETagAny };\n const res = await this.create(size, Object.assign(Object.assign({}, options), { conditions, tracingOptions: updatedOptions.tracingOptions }));\n return Object.assign(Object.assign({ succeeded: true }, res), { _response: res._response });\n }\n catch (e) {\n if (((_a = e.details) === null || _a === void 0 ? void 0 : _a.errorCode) === \"BlobAlreadyExists\") {\n span.setStatus({\n code: coreTracing.SpanStatusCode.ERROR,\n message: \"Expected exception when creating a blob only if it does not already exist.\",\n });\n return Object.assign(Object.assign({ succeeded: false }, (_b = e.response) === null || _b === void 0 ? void 0 : _b.parsedHeaders), { _response: e.response });\n }\n span.setStatus({\n code: coreTracing.SpanStatusCode.ERROR,\n message: e.message,\n });\n throw e;\n }\n finally {\n span.end();\n }\n }", "function makeEnsureExistsCallback(callback) {\n return function ensureExistsCallback(error,success) {\n //winston.log('info',sprintf(\"ensureExistsCallback:(%s,%s)\",JSON.stringify(error),JSON.stringify(success)));\n if (!error) {\n callback(null,1);\n }\n else if (error['code'] == mongo.errors.duplicateKeyError) {\n callback(null,0);\n } \n else {\n callback(error);\n }\n }\n }", "getBucketACL(bucket, cb) {\n if (!validateBucketName(bucket)) {\n throw new errors.InvalidateBucketNameException('Invalid bucket name: ' + bucket)\n }\n\n var query = `?acl`,\n requestParams = {\n host: this.params.host,\n port: this.params.port,\n protocol: this.params.protocol,\n method: 'GET',\n path: `/${bucket}${query}`\n }\n\n signV4(requestParams, '', this.params.accessKey, this.params.secretKey)\n var req = this.transport.request(requestParams, response => {\n var concater = transformers.getConcater()\n var errorTransformer = transformers.getErrorTransformer(response)\n var transformer = transformers.getAclTransformer()\n if (response.statusCode !== 200) {\n pipesetup(response, concater, errorTransformer)\n .on('error', e => cb(e))\n return\n }\n pipesetup(response, concater, transformer)\n .on('error', e => cb(e))\n .on('data', data => {\n var perm = data.acl.reduce(function(acc, grant) {\n if (grant.grantee.uri === 'http://acs.amazonaws.com/groups/global/AllUsers') {\n if (grant.permission === 'READ') {\n acc.publicRead = true\n } else if (grant.permission === 'WRITE') {\n acc.publicWrite = true\n }\n } else if (grant.grantee.uri === 'http://acs.amazonaws.com/groups/global/AuthenticatedUsers') {\n if (grant.permission === 'READ') {\n acc.authenticatedRead = true\n } else if (grant.permission === 'WRITE') {\n acc.authenticatedWrite = true\n }\n }\n return acc\n }, {})\n var cannedACL = 'unsupported-acl'\n if (perm.publicRead && perm.publicWrite && !perm.authenticatedRead && !perm.authenticatedWrite) {\n cannedACL = 'public-read-write'\n } else if (perm.publicRead && !perm.publicWrite && !perm.authenticatedRead && !perm.authenticatedWrite) {\n cannedACL = 'public-read'\n } else if (!perm.publicRead && !perm.publicWrite && perm.authenticatedRead && !perm.authenticatedWrite) {\n cannedACL = 'authenticated-read'\n } else if (!perm.publicRead && !perm.publicWrite && !perm.authenticatedRead && !perm.authenticatedWrite) {\n cannedACL = 'private'\n }\n cb(null, cannedACL)\n })\n })\n req.on('error', e => cb(e))\n req.end()\n }", "function upload(){\n const {Storage} = require('@google-cloud/storage');\n\n // Your Google Cloud Platform project ID\n const projectId = 'check-221407';\n\n // Creates a client\n const storage = new Storage({\n projectId: projectId,\n });\n\n /**\n * TODO(developer): Uncomment the following lines before running the sample.\n */\n const bucketName = 'cal_ballots';\n const filename = 'hint10.JPG';\n\n // Uploads a local file to the bucket\n await storage.bucket(bucketName).upload(filename, {\n // Support for HTTP requests made with `Accept-Encoding: gzip`\n gzip: true,\n metadata: {\n // Enable long-lived HTTP caching headers\n // Use only if the contents of the file will never change\n // (If the contents will change, use cacheControl: 'no-cache')\n cacheControl: 'public, max-age=31536000',\n },\n });\n\n console.log(`${filename} uploaded to ${bucketName}.`);\n}", "function parseBucketName(bucket) {\r\n // Amazon S3 - <bucket>.s3.amazonaws.com\r\n if (/[a-zA-Z0-9-\\.]*\\.(s3|s3-.*).amazonaws.com/g.test(bucket.hostname)) {\r\n bucketName = bucket.hostname.replace(/\\.(s3|s3-.*)\\.amazonaws\\.com/g, '');\r\n return bucketName;\r\n }\r\n // Amazon S3 - s3.amazonaws.com/<bucket> || s3-<region>.amazonaws.com/<bucket>\r\n if (/(s3-[a-zA-Z0-9-]*|s3)\\.([a-zA-Z0-9-]*\\.com|[a-zA-Z0-9-]*\\.amazonaws\\.com)\\/.*/g.test(bucket.hostname + bucket.pathname)) {\r\n a = bucket.pathname.split(\"/\");\r\n bucketName = a[1];\r\n return bucketName;\r\n }\r\n // Google - <bucket>.storage.googleapis.com\r\n if (/[a-zA-Z0-9-\\.]*\\.storage\\.googleapis\\.com/g.test(bucket.hostname)) {\r\n bucketName = bucket.hostname.replace(/\\.storage\\.googleapis\\.com/g, '');\r\n return bucketName;\r\n }\r\n // Google - storage.googleapiscom/<bucket>\r\n if (/storage.googleapis.com\\/[a-zA-Z0-9-\\.]*/g.test(bucket.hostname + bucket.pathname)) {\r\n a = bucket.pathname.split(\"/\");\r\n bucketName = a[1];\r\n return bucketName;\r\n }\r\n // return false if parsing fails\r\n return false;\r\n}", "function ensureExists(path) {\n if (!fs.existsSync(path))\n fs.mkdirSync(path);\n return path;\n}", "async syncDirectory() {\n const s3Bucket = this.serverless.variables.service.custom.s3Bucket;\n const args = ['s3', 'sync', 'build/', `s3://${s3Bucket}/`, '--delete'];\n const exitCode = await this.runAwsCommand(args);\n if (!exitCode) {\n this.serverless.cli.log('Successfully synced to the S3 bucket');\n } else {\n throw new Error('Failed syncing to the S3 bucket');\n }\n }", "static putFile (bucketName, objectKey, objectBody) {\n const s3 = Storage._getS3Instance();\n const params = {\n Bucket: bucketName,\n Key: objectKey,\n Body: objectBody\n };\n return new Promise((resolve, reject) => {\n s3.upload(params, (err, data) => err ? reject(err) : resolve(data.Location));\n });\n }", "async function imageUpload(filename,type, bucketName) {\n\n try{\n\n //create bucket if it isn't present.\n await bucketExists(bucketName);\n\n const bucket = storage.bucket(bucketName);\n \n const gcsname = type +'/'+Date.now() + filename.originalname;\n const file = bucket.file(gcsname);\n \n const stream = file.createWriteStream({\n metadata: {\n contentType: filename.mimetype,\n },\n resumable: false,\n });\n\n \n \n stream.on('error', err => {\n filename.cloudStorageError = err;\n console.log(err);\n });\n \n stream.on('finish', async () => {\n \n filename.cloudStorageObject = gcsname;\n await file.makePublic().then(() => {\n imageUrl = getPublicUrl(gcsname,bucketName);\n console.log(imageUrl);\n });\n \n\n });\n \n stream.end(filename.buffer);\n return getPublicUrl(gcsname,bucketName);\n\n }\n\n catch(error){\n console.log(error);\n \n }\n // [END process]\n\n}", "function main(bucketName = 'my-bucket') {\n // [START storage_get_uniform_bucket_level_access]\n /**\n * TODO(developer): Uncomment the following lines before running the sample.\n */\n // The ID of your GCS bucket\n // const bucketName = 'your-unique-bucket-name';\n\n // Imports the Google Cloud client library\n const {Storage} = require('@google-cloud/storage');\n\n // Creates a client\n const storage = new Storage();\n\n async function getUniformBucketLevelAccess() {\n // Gets Bucket Metadata and checks if uniform bucket-level access is enabled.\n const [metadata] = await storage.bucket(bucketName).getMetadata();\n\n if (metadata.iamConfiguration) {\n const uniformBucketLevelAccess =\n metadata.iamConfiguration.uniformBucketLevelAccess;\n console.log(`Uniform bucket-level access is enabled for ${bucketName}.`);\n console.log(\n `Bucket will be locked on ${uniformBucketLevelAccess.lockedTime}.`\n );\n } else {\n console.log(\n `Uniform bucket-level access is not enabled for ${bucketName}.`\n );\n }\n }\n\n getUniformBucketLevelAccess().catch(console.error);\n\n // [END storage_get_uniform_bucket_level_access]\n}", "insert(key, value) {\n let index = this.makeHash(key);\n let bucket = this.storage[index];\n let item = new Node(key, value);\n \n // Create a new bucket if none exist\n if (!bucket) {\n bucket = new List(item);\n this.storage[index] = bucket; \n bucket.count++;\n this.count++;\n \n return 'New bucket created';\n } \n else {\n let current = bucket.head;\n \n // If the head has null next it is there is only one node in the list\n if (!current.next) {\n current.next = item;\n }\n else {\n // move to the end of the list\n while(current.next) {\n current = current.next;\n }\n \n current.next = item;\n }\n bucket.count++;\n this.count++;\n \n return 'New item placed in bucket at position ' + bucket.count;\n }\n }", "removeIncompleteUpload(bucketName, objectName, cb) {\n if (!validateBucketName(bucketName)) {\n throw new errors.InvalidateBucketNameException('Invalid bucket name: ' + bucket)\n }\n\n if (objectName === null || objectName.trim() === '') {\n throw new errors.InvalidObjectNameException('Object name cannot be empty')\n }\n\n var self = this\n this.findUploadId(bucketName, objectName, (err, uploadId) => {\n if (err || !uploadId) {\n return cb(err)\n }\n var requestParams = {\n host: self.params.host,\n port: self.params.port,\n protocol: self.params.protocol,\n path: `/${bucketName}/${objectName}?uploadId=${uploadId}`,\n method: 'DELETE'\n }\n\n signV4(requestParams, '', self.params.accessKey, self.params.secretKey)\n\n var req = self.transport.request(requestParams, (response) => {\n if (response.statusCode !== 204) {\n var concater = transformers.getConcater()\n var errorTransformer = transformers.getErrorTransformer(response)\n pipesetup(response, concater, errorTransformer)\n .on('error', e => cb(e))\n return\n }\n cb()\n })\n req.on('error', e => cb(e))\n req.end()\n })\n }", "async function ensureCacheExists(client, cacheName) {\n const createResponse = await client.createCache(cacheName);\n if (createResponse instanceof sdk_1.CreateCache.Success ||\n createResponse instanceof sdk_1.CreateCache.AlreadyExists) {\n // pass\n }\n else if (createResponse instanceof sdk_1.CreateCache.Error) {\n throw createResponse.innerException();\n }\n else {\n throw new Error(`Unknown response type: ${createResponse.toString()}`);\n }\n}", "async checkIsSpilloverHasStatus(bucket_name, status) {\n console.log('Checking for spillover status ' + status + ' for bucket ' + bucket_name);\n try {\n const system_info = await this._client.system.read_system({});\n const buckets = system_info.buckets;\n const indexBucket = buckets.findIndex(values => values.name === bucket_name);\n const spilloverPool = system_info.buckets[indexBucket].spillover;\n if ((status) && (spilloverPool !== null)) {\n console.log('Spillover for bucket ' + bucket_name + ' enabled and uses ' + spilloverPool);\n } else if ((!status) && (spilloverPool === null)) {\n console.log('Spillover for bucket ' + bucket_name + ' disabled ');\n }\n } catch (err) {\n console.log('Failed to check spillover for bucket ' + bucket_name + err);\n throw err;\n }\n }", "async function ensureDirExists() {\n// await FileSystem.deleteAsync(FileSystem.documentDirectory + \"attachments/\", {idempotent: true})\n// await FileSystem.deleteAsync(FileSystem.documentDirectory + \"attachments\", {idempotent: true})\n const dirInfo = await FileSystem.getInfoAsync(attachmentsDir);\n if (!dirInfo.exists) {\n console.log(\"Attachments directory doesn't exist, creating...\");\n await FileSystem.makeDirectoryAsync(attachmentsDir, {\n intermediates: true,\n });\n }\n}", "function insertBucketAccessControls() {\n resource = {\n 'entity': ENTITY,\n 'role': ROLE\n };\n\n var request = gapi.client.storage.bucketAccessControls.insert({\n 'bucket': BUCKET,\n 'resource': resource\n });\n executeRequest(request, 'insertBucketAccessControls');\n}", "static isS3URL(url) {\n const s3Host =\n game.data.files.s3 &&\n game.data.files.s3 &&\n game.data.files.s3.endpoint &&\n game.data.files.s3.endpoint.host\n ? game.data.files.s3.endpoint.host\n : \"\";\n\n if (s3Host === \"\") return false;\n\n const regex = new RegExp(\"http[s]?://([^.]+)?.?\" + s3Host + \"(.+)\");\n const matches = regex.exec(url);\n\n const activeSource = matches ? \"s3\" : null; // can be data or remote\n const bucket = matches && matches[1] ? matches[1] : null;\n const current = matches && matches[2] ? matches[2] : null;\n\n if (activeSource === \"s3\") {\n return {\n activeSource,\n bucket,\n current,\n };\n } else {\n return false;\n }\n }", "function addS3bucket (req, res, next) {\n if (req.params.s3bucket) return next()\n req.params.s3bucket = [process.env.APP_NAME, req.params.appname].join('.')\n next()\n}", "validateRegionExists(stage, region) {\n return this.meta.validateRegionExists(stage, region);\n }", "removeBucketLifecycle(bucketName, cb) {\n if (!isValidBucketName(bucketName)) {\n throw new errors.InvalidBucketNameError('Invalid bucket name: ' + bucketName)\n }\n const method = 'DELETE'\n const query = 'lifecycle'\n this.makeRequest({ method, bucketName, query }, '', [204], '', false, cb)\n }", "addBucket() {\n let self = this;\n return co.wrap(function*(req, res, next) {\n let connection = null;\n try {\n let requestData = {\n bucketCode: req.body.bucketCode,\n bucketName: req.body.bucketName,\n isPublic: req.body.isPublic,\n hostName: req.body.hostName\n };\n self.validate(\n {\n bucketCode: {required: true, type: 'string'},\n bucketName: {required: true, type: 'string'},\n isPublic: {required: true, type: 'string'},\n hostName: {required: true, type: 'string'}\n },\n requestData\n );\n connection = yield self.getPoolConnection();\n let fileBucketService = new FileBucketService(connection);\n yield fileBucketService.addBucket(req.body);\n connection.release();\n let result = self.result();\n res.json(result);\n } catch (error) {\n if (connection) {\n connection.release();\n }\n next(error);\n }\n });\n }", "function InvalidBucketMappingError(repo, bucket) {\n Error.call(this);\n Error.captureStackTrace(this, InvalidBucketMappingError);\n this.message =\n `The repository \"${repo}\" is referencing an unknown bucket \"${bucket}\"`;\n}", "function InitAWSConfigurations()\n{\n bucketName = $(\"#hdnBucketName\").val();\n\n bucketStartURL = $(\"#hdnBucketStartURL\").val();\n\n AWS.config.update({\n accessKeyId: $(\"#hdnAWSAccessKey\").val(),\n secretAccessKey: $(\"#hdnAWSSecretKey\").val(),\n region: $(\"#hdnBucketRegion\").val()\n\n });\n\n\n bucket = new AWS.S3({\n params: { Bucket: bucketName }\n });\n // s3 = new AWS.S3();\n\n /****Image upload path initializations****/\n\n userProfileImagePath = $(\"#hdnUserProfileImagePath\").val();\n otherUserProfileFilePath = $(\"#hdnOtherUserProfileFilePath\").val();\n\n\n /***************************************/\n\n}", "async function listBuckets() {\r\n try {\r\n const results = await storage.getBuckets();\r\n\r\n const [buckets] = results;\r\n\r\n console.log('Buckets:');\r\n buckets.forEach(bucket => {\r\n console.log(bucket.name);\r\n });\r\n } catch (err) {\r\n console.error('ERROR:', err);\r\n }\r\n}", "function validateS3BucketName(name, sslVhost = false) {\n // http://docs.aws.amazon.com/AmazonS3/latest/dev/BucketRestrictions.html\n\n // Bucket names must be at least 3 and no more than 63 characters long.\n if (name.length < 3 || name.length > 63) {\n return false;\n }\n\n // Bucket names must be a series of one or more labels. Adjacent labels are\n // separated by a single period (.). Bucket names can contain lowercase\n // letters, numbers, and hyphens. Each label must start and end with a\n // lowercase letter or a number.\n if (/\\.\\./.exec(name) || /^[^a-z0-9]/.exec(name) || /[^a-z0-9]$/.exec(name)) {\n return false;\n };\n if (! /^[a-z0-9-\\.]*$/.exec(name)) {\n return false;\n }\n\n //Bucket names must not be formatted as an IP address (e.g., 192.168.5.4)\n // https://www.safaribooksonline.com/library/view/regular-expressions-cookbook/9780596802837/ch07s16.html\n if (/^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/.exec(name)) {\n return false;\n }\n\n // When using virtual hosted–style buckets with SSL, the SSL wild card\n // certificate only matches buckets that do not contain periods. To work\n // around this, use HTTP or write your own certificate verification logic.\n if (sslVhost) {\n if (/\\./.exec(name)) {\n return false;\n }\n }\n\n return true;\n}", "async _ensureFolder() {\n const dir = this._absoluteConfigDir();\n\n await ensureDirectoryExists(dir);\n }", "function uploadToS3(file) {\n let s3bucket = new AWS.S3({\n accessKeyId: ACCESS,\n secretAccessKey: SECRET,\n Bucket: BUCKET_NAME,\n });\n s3bucket.createBucket(function () {\n var params = {\n Bucket: BUCKET_NAME,\n Key: file.name,\n Body: file.data,\n };\n s3bucket.upload(params, function (err, data) {\n if (err) {\n console.log(\"error in callback\");\n console.log(err);\n }\n console.log(\"success\");\n console.log(data);\n });\n });\n}", "setBucketACL(bucket, acl, cb) {\n if (!validateBucketName(bucket)) {\n throw new errors.InvalidateBucketNameException('Invalid bucket name: ' + bucket)\n }\n\n if (acl === null || acl.trim() === '') {\n throw new errors.InvalidEmptyACLException('Acl name cannot be empty')\n }\n\n // we should make sure to set this query parameter, but on the other hand\n // the call apparently succeeds without it to s3. For clarity lets do it anyways\n var query = `?acl`,\n requestParams = {\n host: this.params.host,\n port: this.params.port,\n protocol: this.params.protocol,\n method: 'PUT',\n path: `/${bucket}${query}`,\n headers: {\n 'x-amz-acl': acl\n }\n }\n\n signV4(requestParams, '', this.params.accessKey, this.params.secretKey)\n\n var req = this.transport.request(requestParams, response => {\n var concater = transformers.getConcater()\n var errorTransformer = transformers.getErrorTransformer(response)\n if (response.statusCode !== 200) {\n pipesetup(response, concater, errorTransformer)\n .on('error', e => cb(e))\n return\n }\n cb()\n })\n // FIXME: the below line causes weird failure in 'gulp test'\n // req.on('error', e => cb(e))\n req.end()\n }", "statObject(bucketName, objectName, cb) {\n if (!validateBucketName(bucketName)) {\n throw new errors.InvalidateBucketNameException('Invalid bucket name: ' + bucketName)\n }\n\n if (objectName === null || objectName.trim() === '') {\n throw new errors.InvalidObjectNameException('Object name cannot be empty')\n }\n\n var requestParams = {\n host: this.params.host,\n port: this.params.port,\n protocol: this.params.protocol,\n path: `/${bucketName}/${uriResourceEscape(objectName)}`,\n method: 'HEAD'\n }\n\n signV4(requestParams, '', this.params.accessKey, this.params.secretKey)\n\n var req = this.transport.request(requestParams, (response) => {\n var errorTransformer = transformers.getErrorTransformer(response)\n var concater = transformers.getConcater()\n if (response.statusCode !== 200) {\n pipesetup(response, concater, errorTransformer)\n .on('error', e => cb(e))\n return\n }\n var result = {\n size: +response.headers['content-length'],\n etag: response.headers.etag.replace(/\"/g, ''),\n contentType: response.headers['content-type'],\n lastModified: response.headers['last-modified']\n }\n cb(null, result)\n })\n req.end()\n }", "function main(bucketName = 'my-bucket') {\n // [START storage_set_public_access_prevention_unspecified]\n /**\n * TODO(developer): Uncomment the following lines before running the sample.\n */\n // The name of your GCS bucket\n // const bucketName = 'Name of a bucket, e.g. my-bucket';\n // Imports the Google Cloud client library\n const {Storage} = require('@google-cloud/storage');\n\n // Creates a client\n const storage = new Storage();\n async function setPublicAccessPreventionUnspecified() {\n // Sets public access prevention to 'unspecified' for the bucket\n await storage.bucket(bucketName).setMetadata({\n iamConfiguration: {\n publicAccessPrevention: 'unspecified',\n },\n });\n\n console.log(`Public access prevention is 'unspecified' for ${bucketName}.`);\n }\n\n setPublicAccessPreventionUnspecified();\n // [END storage_set_public_access_prevention_unspecified]\n}", "function getBucketAcl() {\n const getBucketAclParams = {\n Bucket: bucket,\n };\n s3Client.getBucketAcl(getBucketAclParams, (err, data) => {\n if (err) console.log('err:', err);\n else console.log('data:', JSON.stringify(data));\n });\n}", "removeBucketTagging(bucketName, cb) {\n if (!isValidBucketName(bucketName)) {\n throw new errors.InvalidBucketNameError('Invalid bucket name: ' + bucketName)\n }\n if (!isFunction(cb)) {\n throw new TypeError('callback should be of type \"function\"')\n }\n return this.removeTagging({ bucketName, cb })\n }", "presignedPutObject(bucketName, objectName, expires) {\n if (!validateBucketName(bucketName)) {\n throw new errors.InvalidateBucketNameException('Invalid bucket name: ' + bucketName)\n }\n if (objectName === null || objectName.trim() === '') {\n throw new errors.InvalidObjectNameException('Object name cannot be empty')\n }\n var requestParams = {\n host: this.params.host,\n port: this.params.port,\n protocol: this.params.protocol,\n path: `/${bucketName}/${uriResourceEscape(objectName)}`,\n method: 'PUT',\n expires: expires\n }\n return presignSignatureV4(requestParams, this.params.accessKey, this.params.secretKey)\n }", "async function listBuckets() {\n try {\n const results = await storage.getBuckets();\n\n const [buckets] = results;\n\n console.log('Buckets:');\n buckets.forEach(bucket => {\n console.log(bucket.name);\n });\n } catch (err) {\n console.error('ERROR:', err);\n }\n}", "async function ensureDirExists() {\n const dirInfo = await FileSystem.getInfoAsync(Dir);\n if (!dirInfo.exists) {\n await FileSystem.makeDirectoryAsync(Dir, { intermediates: true });\n }\n}", "get bucketName() {\n return artifactAttribute(this, 'BucketName');\n }", "function uploadFileIntoFolderOfBucket(){\n // Create S3 service object\n s3 = new AWS.S3({apiVersion: '2006-03-01'});\n\n // call S3 to retrieve upload file to specified bucket\n var uploadParams = {Bucket: process.argv[2], Key: '', Body: ''};\n var file = process.argv[4];\n\n // Configure the file stream and obtain the upload parameters\n var fs = require('fs');\n var fileStream = fs.createReadStream(file);\n fileStream.on('error', function(err) {\n console.log('File Error', err);\n });\n\n uploadParams.Body = fileStream;\n var path = require('path');\n uploadParams.Key = process.argv[3]+\"/\"+path.basename(file);\n\n // call S3 to retrieve upload file to specified bucket\n s3.upload (uploadParams, function (err, data) {\n if (err) {\n console.log(\"Error\", err);\n } if (data) {\n console.log(\"Upload Success\", data.Location);\n }\n });\n}", "deleteBucket() {\n\n\t\tlet auth_token = sessionStorage.auth_token // Get the auth_token from the session storage.\n\n\t\taxios({\n\t\t\tmethod: \"DELETE\",\n\t\t\turl: BaseUrl + \"bucketlists/\" + this.state.bucket_id,\n\t\t\theaders: { \"Authorization\": auth_token }\n\t\t}).then(function (response) {\n\t\t\tvar data = response.data\n\t\t\tif (data.success) {\n\t\t\t\tlet buckets = this.state.buckets\n\t\t\t\t_.remove(buckets, {\n\t\t\t\t\t\"id\": this.state.bucket_id\n\t\t\t\t})\n\n\t\t\t\tthis.setState({\n\t\t\t\t\tbuckets: buckets,\n\t\t\t\t\tvisible: true,\n\t\t\t\t\tmessage: this.state.bucket_name + \" has been deleted successfully\",\n\t\t\t\t\talert_type: \"success\"\n\t\t\t\t})\n\t\t\t}\n\t\t}.bind(this))\n\t}", "function isAlexaHosted() \n {\n return process.env.S3_PERSISTENCE_BUCKET;\n }", "function createShadowBucket(key, uploadId) {\n const overviewKey = `overview${constants.splitter}` +\n `${key}${constants.splitter}${uploadId}`;\n metadata.buckets\n .set(mpuShadowBucket, new BucketInfo(mpuShadowBucket, ownerID, '', ''));\n // Set modelVersion to use the most recent splitter.\n Object.assign(metadata.buckets.get(mpuShadowBucket), {\n _mdBucketModelVersion: 5,\n });\n metadata.keyMaps.set(mpuShadowBucket, new Map);\n metadata.keyMaps.get(mpuShadowBucket).set(overviewKey, new Map);\n Object.assign(metadata.keyMaps.get(mpuShadowBucket).get(overviewKey), {\n id: uploadId,\n eventualStorageBucket: bucketName,\n initiator: {\n DisplayName: 'accessKey1displayName',\n ID: ownerID },\n key,\n uploadId,\n });\n}", "getObject(bucketName, objectName, cb) {\n if (!validateBucketName(bucketName)) {\n throw new errors.InvalidateBucketNameException('Invalid bucket name: ' + bucketName)\n }\n\n if (objectName === null || objectName.trim() === '') {\n throw new errors.InvalidObjectNameException('Object name cannot be empty')\n }\n this.getPartialObject(bucketName, objectName, 0, 0, cb)\n }", "function putObject(bucket, key, obkject) {\n\tif (bucket === null) {\n\t\tbucket = constants.defaultBucket;\n\t}\n\n\tvar params = {\n\t\tBucket : bucket, /* required */\n\t\tKey : key, /* required */\n\t\tBody : obkject\n\t};\n\tconsole.log(\"putObject for \" + JSON.stringify(obkject));\n\ts3.putObject(params, function(err, data) {\n\t\tif (err)\n\t\t\tconsole.log(err, err.stack); // an error occurred\n\t\telse\n\t\t\tconsole.log(data); // successful response\n\t});\n}", "async uploadArtifacts() {\n const objectId = this.getBucketId();\n const filesFolder = this.options.distributionFolder || 'client/dist/';\n const files = read(filesFolder);\n\n const objects = files.map((file) => {\n return {\n ObjectName: file.replace(filesFolder,''),\n LocalPath: file\n };\n });\n\n const bucket = this.templates.create.Resources[objectId].Properties;\n\n this.serverless.cli.log(`Uploading objects to OSS bucket ${bucket.BucketName}...`);\n await Promise.all(objects.map((object) => this.provider.uploadObject(object.ObjectName, object.LocalPath)));\n this.serverless.cli.log(`Uploaded objects to OSS bucket ${bucket.BucketName}`);\n }", "function ensureJob(job, done){\n\t\tfindJob(job, function(err, existingjob){\n\t\t\tif(err){\n\t\t\t\treturn done(err)\n\t\t\t}\n\t\t\tif(existingjob){\n\t\t\t\treturn done(null, existingjob)\n\t\t\t}\n\n\t\t\twriteJob(job, done)\n\t\t})\n\t\t\n\t}", "function keyExists(keyid) {\n\t\"use strict\";\n return nPathV.existsSync(config.getAikDir()) && nPathV.existsSync(getKeyPath(keyid));\n}", "static deleteFile (bucketName, objectKey) {\n const s3 = Storage._getS3Instance();\n const params = {\n Bucket: bucketName,\n Key: objectKey\n };\n return new Promise((resolve, reject) => {\n s3.deleteObject(params, (err, data) => err ? reject(err) : resolve());\n });\n }", "async function createSignedGsUrl(serviceAccountKey, {bucket, name}) {\n const storage = new Storage({ credentials: serviceAccountKey });\n const response = await storage.bucket(bucket).file(name).getSignedUrl({ action: 'read', expires: Date.now() + 36e5 });\n return response[0];\n}", "async storeInCloudStorage(file) {\n await uploadFile(BUCKET_NAME, file);\n }", "function CreateBucketCommand(input) {\n var _this = \n // Start section: command_constructor\n _super.call(this) || this;\n _this.input = input;\n return _this;\n // End section: command_constructor\n }" ]
[ "0.769745", "0.76768106", "0.73506474", "0.6886983", "0.6886604", "0.6732924", "0.6534127", "0.65127003", "0.62711924", "0.60038716", "0.5920388", "0.57440436", "0.57388884", "0.57125515", "0.56920826", "0.5639084", "0.563566", "0.55807775", "0.54767406", "0.54656553", "0.5375123", "0.53729635", "0.53692013", "0.5353469", "0.5331229", "0.5318711", "0.52973974", "0.52295154", "0.52162033", "0.52150714", "0.5159773", "0.5159773", "0.51438504", "0.5120166", "0.5105659", "0.51001817", "0.50974935", "0.50974935", "0.5096875", "0.50843555", "0.50708723", "0.50530416", "0.50453484", "0.503939", "0.503333", "0.5030314", "0.50268054", "0.50246346", "0.50117695", "0.50085133", "0.50068206", "0.50068206", "0.5006616", "0.49895963", "0.49889395", "0.4981839", "0.49810246", "0.49807033", "0.49669823", "0.49648312", "0.49605754", "0.4952316", "0.49444246", "0.493856", "0.4931214", "0.4917553", "0.49118832", "0.49020612", "0.49003428", "0.48927593", "0.48858026", "0.48837516", "0.4882259", "0.48648113", "0.48636356", "0.4863024", "0.48256806", "0.48206633", "0.48094904", "0.4808906", "0.480523", "0.4804446", "0.48015946", "0.48009318", "0.47961512", "0.47873652", "0.47808027", "0.4771375", "0.47704268", "0.47695163", "0.47682542", "0.47340164", "0.4697891", "0.46963283", "0.46900466", "0.46814606", "0.4679168", "0.46758494", "0.4650844", "0.46460402" ]
0.66250736
6
StorageProvider.put() implementation for S3
async put(rawUrl, inputStream, headers, storageMetadata) { assert(rawUrl, 'must provide raw input url'); assert(inputStream, 'must provide an input stream'); assert(headers, 'must provide HTTP headers'); assert(storageMetadata, 'must provide storage provider metadata'); // We decode the key because the S3 library 'helpfully' // URL encodes this value let request = { Bucket: this.bucket, Key: rawUrl, Body: inputStream, ACL: 'public-read', Metadata: storageMetadata, }; _.forEach(HTTPHeaderToS3Prop, (s3Prop, httpHeader) => { if (_.includes(DisallowedHTTPHeaders, httpHeader)) { throw new Error(`The HTTP header ${httpHeader} is not allowed`); } else if (_.includes(MandatoryHTTPHeaders, httpHeader)) { assert(headers[httpHeader], `HTTP Header ${httpHeader} must be specified`); } request[s3Prop] = headers[httpHeader]; }); let options = { partSize: this.partSize, queueSize: this.queueSize, }; let upload = this.s3.upload(request, options); this.debug('starting S3 upload'); let result = await wrapSend(upload); this.debug('completed S3 upload'); return result; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function putObject(keyName) {\n const putObjectParams = {\n Bucket: bucket,\n Key: keyName,\n Metadata: {\n importance: 'very',\n ranking: 'middling',\n },\n Body: 'putMe',\n };\n s3Client.putObject(putObjectParams, (err, data) => {\n if (err) console.log('err:', err);\n else console.log('data:', data);\n });\n}", "static putFile (bucketName, objectKey, objectBody) {\n const s3 = Storage._getS3Instance();\n const params = {\n Bucket: bucketName,\n Key: objectKey,\n Body: objectBody\n };\n return new Promise((resolve, reject) => {\n s3.upload(params, (err, data) => err ? reject(err) : resolve(data.Location));\n });\n }", "* put (path, contents, driverOpts={}) {\n return new Promise((resolve, reject) => {\n this.s3.upload(Object.assign({\n Bucket: this.disk.bucket,\n Key: path,\n Body: contents\n }, driverOpts), (err, data) => {\n if (err) return reject(err)\n return resolve(data.Location)\n })\n })\n }", "async function putS3(fileKey, data) {\n oLog.verbose(__filename, 'putS3');\n\n try {\n if (configs.aws.s3.active) {\n // set aws region:\n rAWS.config.update({\n region: configs.aws.s3.region\n });\n // bucket info:\n let s3Bucket = configs.aws.s3.s3bucket;\n let s3FileKey = fileKey;\n let s3Params = {\n Bucket: s3Bucket,\n Key: s3FileKey,\n Body: data\n };\n\n // get object and parse the JSON:\n return rS3.putObject(s3Params).promise();\n } else {\n // empty object if not active:\n return {};\n }\n } catch (error) {\n oLog.error(__filename, 'putS3', error);\n return error;\n }\n}", "function putObject(bucket, key, obkject) {\n\tif (bucket === null) {\n\t\tbucket = constants.defaultBucket;\n\t}\n\n\tvar params = {\n\t\tBucket : bucket, /* required */\n\t\tKey : key, /* required */\n\t\tBody : obkject\n\t};\n\tconsole.log(\"putObject for \" + JSON.stringify(obkject));\n\ts3.putObject(params, function(err, data) {\n\t\tif (err)\n\t\t\tconsole.log(err, err.stack); // an error occurred\n\t\telse\n\t\t\tconsole.log(data); // successful response\n\t});\n}", "presignedPutObject(bucketName, objectName, expires, cb) {\n if (!isValidBucketName(bucketName)) {\n throw new errors.InvalidBucketNameError(`Invalid bucket name: ${bucketName}`)\n }\n if (!isValidObjectName(objectName)) {\n throw new errors.InvalidObjectNameError(`Invalid object name: ${objectName}`)\n }\n return this.presignedUrl('PUT', bucketName, objectName, expires, cb)\n }", "function putS3File(bucketName, fileName, data, callback) {\n var expirationDate = new Date();\n // Assuming a user would not remain active in the same session for over 1 hr.\n expirationDate = new Date(expirationDate.setHours(expirationDate.getHours() + 1));\n var params = {\n Bucket: bucketName,\n Key: fileName,\n Body: data,\n ACL: 'public-read', // TODO: find way to restrict access to this lambda function\n Expires: expirationDate\n };\n s3.putObject(params, function (err, data) {\n callback(err, data);\n });\n}", "putObject(bucketName, objectName, stream, size, metaData, callback) {\n if (!isValidBucketName(bucketName)) {\n throw new errors.InvalidBucketNameError('Invalid bucket name: ' + bucketName)\n }\n if (!isValidObjectName(objectName)) {\n throw new errors.InvalidObjectNameError(`Invalid object name: ${objectName}`)\n }\n\n // We'll need to shift arguments to the left because of size and metaData.\n if (isFunction(size)) {\n callback = size\n metaData = {}\n } else if (isFunction(metaData)) {\n callback = metaData\n metaData = {}\n }\n\n // We'll need to shift arguments to the left because of metaData\n // and size being optional.\n if (isObject(size)) {\n metaData = size\n }\n\n // Ensures Metadata has appropriate prefix for A3 API\n metaData = prependXAMZMeta(metaData)\n if (typeof stream === 'string' || stream instanceof Buffer) {\n // Adapts the non-stream interface into a stream.\n size = stream.length\n stream = readableStream(stream)\n } else if (!isReadableStream(stream)) {\n throw new TypeError('third argument should be of type \"stream.Readable\" or \"Buffer\" or \"string\"')\n }\n\n if (!isFunction(callback)) {\n throw new TypeError('callback should be of type \"function\"')\n }\n\n if (isNumber(size) && size < 0) {\n throw new errors.InvalidArgumentError(`size cannot be negative, given size: ${size}`)\n }\n\n // Get the part size and forward that to the BlockStream. Default to the\n // largest block size possible if necessary.\n if (!isNumber(size)) {\n size = this.maxObjectSize\n }\n\n size = this.calculatePartSize(size)\n\n // s3 requires that all non-end chunks be at least `this.partSize`,\n // so we chunk the stream until we hit either that size or the end before\n // we flush it to s3.\n let chunker = new BlockStream2({ size, zeroPadding: false })\n\n // This is a Writable stream that can be written to in order to upload\n // to the specified bucket and object automatically.\n let uploader = new ObjectUploader(this, bucketName, objectName, size, metaData, callback)\n // stream => chunker => uploader\n pipesetup(stream, chunker, uploader)\n }", "presignedPutObject(bucketName, objectName, expires) {\n if (!validateBucketName(bucketName)) {\n throw new errors.InvalidateBucketNameException('Invalid bucket name: ' + bucketName)\n }\n if (objectName === null || objectName.trim() === '') {\n throw new errors.InvalidObjectNameException('Object name cannot be empty')\n }\n var requestParams = {\n host: this.params.host,\n port: this.params.port,\n protocol: this.params.protocol,\n path: `/${bucketName}/${uriResourceEscape(objectName)}`,\n method: 'PUT',\n expires: expires\n }\n return presignSignatureV4(requestParams, this.params.accessKey, this.params.secretKey)\n }", "function saveObjToS3(data, fileName, bucket, callback){\n console.log(\"saveObjToS3\", data);\n //save data to s3 \n var params = {Bucket: bucket, Key: fileName, Body: data, ContentType: 'text/plain'};\n s3.putObject(params, function(err, data) {\n if (err) {\n console.log(\"saveObjToS3 err\", err);\n } else {\n callback();\n }\n });\n}", "function fetchAndStoreObject(bucket, key, fn) {\n\tif (bucket === null) {\n\t\tbucket = constants.defaultBucket;\n\t}\n\tvar params = {\n\t\tBucket : bucket, /* required */\n\t\tKey : key\n\t/* required */\n\t};\n\tconsole.log(\"getObject for \" + JSON.stringify(params));\n\tvar file = fs.createWriteStream('/tmp/' + key);\n\ts3.getObject(params).on('httpData', function(chunk) {\n\t\tfile.write(chunk);\n\t\t// console.log(\"writing chunk in file.\"+key);\n\t}).on('httpDone', function() {\n\t\tfile.end();\n\t\tconsole.log(\"file end.\" + key);\n\t\tfn();\n\t}).send();\n}", "function S3Store(options) {\n options = options || {};\n\n this.options = extend({\n path: 'cache/',\n tryget: true,\n s3: {}\n }, options);\n\n\n // check storage directory for existence (or create it)\n if (!fs.existsSync(this.options.path)) {\n fs.mkdirSync(this.options.path);\n }\n\n this.name = 's3store';\n\n // internal array for informations about the cached files - resists in memory\n this.collection = {};\n\n // TODO: need implement!\n // fill the cache on startup with already existing files\n // if (!options.preventfill) {\n // this.intializefill(options.fillcallback);\n // }\n}", "put (url, data) {\n }", "function uploadToS3(name, file, successCallback, errorCallback, progressCallback) {\n\n if (typeof successCallback != 'function') {\n Ti.API.error('successCallback() is not defined');\n return false;\n }\n\n if (typeof errorCallback != 'function') {\n Ti.API.error('errorCallback() is not defined');\n return false;\n }\n\n var AWSAccessKeyID = 'AKIAJHRVU52E4GKVARCQ';\n var AWSSecretAccessKey = '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';\n var AWSBucketName = 'snapps';\n var AWSHost = AWSBucketName + '.s3.amazonaws.com';\n\n var currentDateTime = formatDate(new Date(),'E, d MMM yyyy HH:mm:ss') + ' ' + getOffsetAsInteger();\n\n var xhr = Ti.Network.createHTTPClient();\n\n xhr.onsendstream = function(e) {\n\n if (typeof debugStartTime != 'number') {\n debugStartTime = new Date().getTime();\n }\n\n debugUploadTime = Math.floor((new Date().getTime() - debugStartTime) / 1000);\n\n var progress = Math.floor(e.progress * 100);\n Ti.API.info('uploading (' + debugUploadTime + 's): ' + progress + '%');\n\n // run progressCallback function when available\n if (typeof progressCallback == 'function') {\n progressCallback(progress);\n }\n\n };\n\n xhr.onerror = function(e) {\n Ti.API.error({ errorlocation: 'onload', error: e, responseText: xhr.responseText, headers: xhr.getResponseHeaders() });\n errorCallback(e);\n };\n\n xhr.onload = function() {\n if (this.status >= 200 && this.status < 300) {\n\n var responseHeaders = xhr.getResponseHeaders();\n\n var filename = name;\n var url = 'https://' + AWSHost + '/' + name;\n\n if (responseHeaders['x-amz-version-id']) {\n url = url + '?versionId=' + responseHeaders['x-amz-version-id'];\n }\n\n successCallback({ url: url });\n }\n else {\n Ti.API.error({ errorlocation: 'onload', error: e, responseText: xhr.responseText, headers: xhr.getResponseHeaders() });\n errorCallback();\n }\n };\n\n //ensure we have time to upload\n xhr.setTimeout(99000);\n\n // An optional boolean parameter, defaulting to true, indicating whether or not to perform the operation asynchronously.\n // If this value is false, the send() method does not return until the response is received. If true, notification of a\n // completed transaction is provided using event listeners. This must be true if the multipart attribute is true, or\n // an exception will be thrown.\n xhr.open('PUT', 'https://' + AWSHost + '/' + name, true);\n\n //var StringToSign = 'PUT\\n\\nmultipart/form-data\\n' + currentDateTime + '\\nx-amz-acl:public-read\\n/' + AWSBucketName + '/' + name;\n var StringToSign = 'PUT\\n\\n\\n' + currentDateTime + '\\nx-amz-acl:public-read\\n/' + AWSBucketName + '/' + name;\n var AWSSignature = b64_hmac_sha1(AWSSecretAccessKey, Utf8.encode(StringToSign));\n var AuthorizationHeader = 'AWS ' + AWSAccessKeyID + ':' + AWSSignature;\n\n xhr.setRequestHeader('Authorization', AuthorizationHeader);\n //xhr.setRequestHeader('Content-Type', 'multipart/form-data');\n xhr.setRequestHeader('X-Amz-Acl', 'public-read');\n xhr.setRequestHeader('Host', AWSHost);\n xhr.setRequestHeader('Date', currentDateTime);\n\n xhr.send(file);\n\n return xhr;\n}", "function storeToS3(env, data, callback){\n // get the investigators cached version from AWS.\n if (!isValidEnv(env)){\n callback(\"Invalid env passed into storeToS3()\");\n return;\n }\n // construct the filename from the env\n var filename = getS3FilePath(env);\n var params = {\n Bucket: AWS_BUCKET_NAME,\n Key: filename,\n Body: JSON.stringify(data)\n };\n // upload the file...\n console.log(\"Uploading list to s3...\");\n s3.upload(params, function(err, data){\n if (err){\n callback(\"storeToS3 S3: \" + err);\n } else {\n console.log(\"S3 upload success: s3://\" + AWS_BUCKET_NAME + '/' + filename);\n callback(null, data);\n }\n });\n}", "putObject(image, options) {\n const params = {\n Bucket: image.bucketName,\n Key: image.fileName,\n Body: image.data,\n Metadata: Object.assign({}, image.headers.Metadata, {\"cdn-processed\": \"true\"}),\n ContentType: image.headers.ContentType,\n CacheControl: (options.cacheControl !== undefined) ? options.cacheControl : image.headers.CacheControl,\n ACL: image.acl || \"private\"\n };\n\n console.log(\"Uploading to: \" + params.Key + \" (\" + params.Body.length + \" bytes)\");\n\n return this.client.putObject(params).promise();\n }", "async putObject() {\n const { ContentLength } = this.object;\n this.resultData = await this.cosSdkInstance.putObjectRetry({\n ...this.object,\n GetBody: () => readStreamAddPassThrough(this.getReadStream(0, ContentLength)),\n });\n this.manageGlobalCacheData('remove');\n }", "async upload_file_toS3(filename, extension) {\n try {\n\n var username = await AsyncStorage.getItem(\"username\");\n var s3config = require(\"./config/AWSConfig.json\");\n var signedurl = await this.getsignedurl(s3config.s3bucketname, s3config.s3folder + \"/\" + username + \"/\" + filename + extension, \"put\");\n\n\n\n let dirs = RNFetchBlob.fs.dirs;\n\n const result = await RNFetchBlob.fetch('PUT', signedurl, {\n 'Content-Type': 'image/jpg',\n }, RNFetchBlob.wrap(dirs.DocumentDir + s3config.localimagestore + filename + extension));\n\n //alert(result.respInfo.status);\n if (result.respInfo.status == 200)\n return true;\n else\n return false;\n\n }\n catch (error) {\n return false;\n //alert(error.message);\n }\n\n }", "async uploadIfChanged(data, props) {\n const s3 = await this.props.sdk.s3(this.props.environment.account, this.props.environment.region, credentials_1.Mode.ForWriting);\n const s3KeyPrefix = props.s3KeyPrefix || '';\n const s3KeySuffix = props.s3KeySuffix || '';\n const bucket = this.props.bucketName;\n const hash = archive_1.contentHash(data);\n const filename = `${hash}${s3KeySuffix}`;\n const key = `${s3KeyPrefix}${filename}`;\n const url = `s3://${bucket}/${key}`;\n logging_1.debug(`${url}: checking if already exists`);\n if (await objectExists(s3, bucket, key)) {\n logging_1.debug(`${url}: found (skipping upload)`);\n return { filename, key, hash, changed: false };\n }\n const uploaded = { filename, key, hash, changed: true };\n // Upload if it's new or server-side copy if it was already uploaded previously\n const previous = this.previousUploads[hash];\n if (previous) {\n logging_1.debug(`${url}: copying`);\n await s3.copyObject({\n Bucket: bucket,\n Key: key,\n CopySource: `${bucket}/${previous.key}`\n }).promise();\n logging_1.debug(`${url}: copy complete`);\n }\n else {\n logging_1.debug(`${url}: uploading`);\n await s3.putObject({\n Bucket: bucket,\n Key: key,\n Body: data,\n ContentType: props.contentType\n }).promise();\n logging_1.debug(`${url}: upload complete`);\n this.previousUploads[hash] = uploaded;\n }\n return uploaded;\n }", "putSnapshot(key, body) {\n // The _active approach is providing a safeguard to minimize the number of requests made to Amazon as much as possible\n if(this._active) {\n // Make sure to include / in the Key when you call this\n if(key) {\n return new Promise((resolve, reject) => {\n this._s3.putObject(\n {\n Bucket: this._bucket,\n\n Body: body,\n\n ContentType: 'application/pdf',\n \n Key: key\n },\n \n (err, data) => {\n if(err) {\n console.error('Error with S3 request to put object \\n' + (err.body ? err.body.message : err.message));\n \n reject(err);\n }else {\n resolve(true);\n }\n }\n );\n });\n }else {\n console.error('Invalid S3 Key, currently a Falsy value');\n }\n }else {\n console.log('Cannot add folder to S3, because S3 is not active');\n }\n\n\n return result;\n }", "save(bucket, key, value) {\n\n if (!this.__validate(bucket, key)) {\n throw errors.InvalidStringFormat(`A bucket and key should not contain ${DELIM}`);\n }\n\n return this.store.put(`${bucket}${DELIM}${key}`, value);\n }", "async save(config) {\r\n this._logger.info(\"===> AmazonStorageConfigProvider::save\");\r\n if (objectHelper_1.ObjectHelper.isEmpty(this._credentials)) {\r\n throw new storageError_1.StorageError(\"The serviceAccountKey must be set for save operations\");\r\n }\r\n if (objectHelper_1.ObjectHelper.isEmpty(config)) {\r\n throw new storageError_1.StorageError(\"The config parameter can not be empty\");\r\n }\r\n const filename = `/${this._bucketName}/${this._configName}.json`;\r\n const content = JSON.stringify(config);\r\n const request = {\r\n service: \"s3\",\r\n region: this._region,\r\n method: \"PUT\",\r\n path: filename,\r\n headers: {\r\n \"Content-Type\": \"application/json\",\r\n \"Content-Length\": content.length.toString(),\r\n \"x-amz-acl\": \"public-read\"\r\n },\r\n body: content\r\n };\r\n const requestSigner = new amazonRequestSigner_1.AmazonRequestSigner(request, this._credentials);\r\n const signedRequest = requestSigner.sign();\r\n const networkEndpoint = new networkEndPoint_1.NetworkEndPoint(\"https\", signedRequest.hostname, 443);\r\n const networkClient = networkClientFactory_1.NetworkClientFactory.instance().create(\"default\", networkEndpoint, this._logger);\r\n await networkClient.doRequest(\"PUT\", content, filename, signedRequest.headers);\r\n this._logger.info(\"<=== AmazonStorageConfigProvider::save\");\r\n }", "function uploadAndFetch (s3, stream, filename, bucket, key) {\n var deferred = when.defer();\n exports.getFileStream(filename)\n .pipe(stream)\n .on(\"error\", deferred.reject)\n .on(\"finish\", function () {\n deferred.resolve(exports.getObject(s3, bucket, key));\n });\n return deferred.promise;\n}", "grantPut(identity, objectsKeyPattern = '*') {\n return this.grant(identity, perms.BUCKET_PUT_ACTIONS, perms.KEY_WRITE_ACTIONS, this.arnForObjects(objectsKeyPattern));\n }", "async function uploadImageToS3(imageUrl, idx) {\n\n const image = await readImageFromUrl(imageUrl, idx);\n\n const imagePath = imageUrl.split(`https://divisare-res.cloudinary.com/`)[1];\n const objectParams = {\n Bucket: 'bersling-divisaire',\n // i already created /aaa-testing, /testing and testing :)\n Key: `images6/${imagePath}`,\n Body: image,\n ContentType: 'image/jpg'\n };\n // Create object upload promise\n const uploadPromise = new AWS.S3({apiVersion: '2006-03-01', region: 'eu-central-1'})\n .putObject(objectParams)\n .promise();\n uploadPromise\n .then((data) => {\n // nothing to do...\n logger(`uploaded image...`);\n }).catch(err => {\n logger(\"ERROR\");\n logger(err);\n });\n return uploadPromise;\n\n\n}", "function combineObjectWithCachedS3File(config, upload, downloadDict, s3, key, newObj, callback) {\n var localFilename = config.workingDir + \"/\" + config.outBucket + \"/\" + key;\n var localDir = localFilename.substring(0, localFilename.lastIndexOf('/'));\n\n var inFlight = downloadDict[localFilename];\n if (inFlight) {\n //console.log(\"Download race condition avoided, queued\", key, newObj);\n inFlight.obj = tarasS3.combineObjects(newObj, inFlight.obj);\n inFlight.callbacks.push(callback);\n return; // we are done, our callback will get called as part of original inFlight request\n } else {\n downloadDict[localFilename] = inFlight = {'obj':newObj, 'callbacks':[callback]};\n }\n\n async.waterfall([\n // try to read file from local cache before we go to out to s3\n function (callback) {\n fs.readFile(localFilename, function (err, data) {\n function fallback() {\n var params = {'s3':s3, 'params':{'Bucket': config.outBucket, 'Key':key}};\n return tarasS3.S3GetObjectGunzip(params, function (err, data) {\n if (err) {\n // 404 on s3 means this object is new stuff\n if (err.statusCode == 404)\n return callback(null, {});\n else\n return callback(err);\n }\n callback(null, JSON.parse(data));\n })\n }\n // missing file or invalid json are both reasons for concern\n if (err) {\n return fallback()\n }\n var obj;\n try {\n obj = JSON.parse(data)\n }catch(e) {\n return fallback()\n }\n callback(null, obj);\n });\n },\n function (obj, callback) {\n inFlight.obj = tarasS3.combineObjects(inFlight.obj, obj);\n mkdirp.mkdirp(localDir, callback);\n },\n function(ignore, callback) {\n str = JSON.stringify(inFlight.obj);\n delete downloadDict[localFilename];\n upload(key, localFilename, str, callback);\n }\n ],function (err, data) {\n if (err)\n return callback(err);\n inFlight.callbacks.forEach(function (callback) {callback(null, key)});\n });\n}", "fPutObject(bucketName, objectName, filePath, metaData, callback) {\n if (!isValidBucketName(bucketName)) {\n throw new errors.InvalidBucketNameError('Invalid bucket name: ' + bucketName)\n }\n if (!isValidObjectName(objectName)) {\n throw new errors.InvalidObjectNameError(`Invalid object name: ${objectName}`)\n }\n\n if (!isString(filePath)) {\n throw new TypeError('filePath should be of type \"string\"')\n }\n if (isFunction(metaData)) {\n callback = metaData\n metaData = {} // Set metaData empty if no metaData provided.\n }\n if (!isObject(metaData)) {\n throw new TypeError('metaData should be of type \"object\"')\n }\n\n // Inserts correct `content-type` attribute based on metaData and filePath\n metaData = insertContentType(metaData, filePath)\n\n fs.lstat(filePath, (err, stat) => {\n if (err) {\n return callback(err)\n }\n return this.putObject(bucketName, objectName, fs.createReadStream(filePath), stat.size, metaData, callback)\n })\n }", "function putBucketAcl() {\n const putBucketAclParams = {\n Bucket: bucket,\n ACL: 'authenticated-read',\n };\n s3Client.putBucketAcl(putBucketAclParams, (err, data) => {\n if (err) console.log('err:', err);\n else console.log('data:', data);\n });\n}", "* url (path) {\n return `https://${this.disk.bucket}.s3.amazonaws.com/${path}`\n }", "function S3ObjectClass(configuration, createUploadRequestNamesFunction, redisClient)\n{\n\tvar self = this;\n\n\t//grab bucketname from config file\n\tvar bucketName = configuration.bucket;\n\tvar uploadExpiration = configuration.expires || 15*60;\n\n\tself.s3 = new AWS.S3({params: {Bucket: bucketName}, computeChecksums: false});\n\n\t//example for outside use or testing -- helpful if i forget my function logic later--or someone checking around from the outside\n\tself.requestFunctionExample = exampleUploadRequestFunction;\n\tself.createUploadRequests = createUploadRequestNamesFunction;\n\n\tself.uploadErrors = {\n\t\tnullUploadKey : 0,\n\t\tredisError : 1,\n\t\theadCheckUnfulfilledError : 2,\n\t\theadCheckMissingError : 3,\n\t\tredisDeleteError : 4\n\t}\n\n\n\tself.generateObjectAccess = function(fileLocations)\n\t{\n\n\t\t//we create a map of signed URLs\n\t\tvar fileAccess = {};\n\n\t\tfor(var i=0; i < fileLocations.length; i++)\n\t\t{\n\t\t\tvar fLocation = fileLocations[i];\n\n\t\t\tvar signedURLReq = {\n\t\t\t\tBucket: bucketName, \n\t\t\t\tKey: fLocation,\n\t\t\t\tExpires: uploadExpiration,\n\t\t\t};\n\n\t\t\tvar signed = self.s3.getSignedUrl('getObject', signedURLReq);\n\n\t\t\tfileAccess[fLocation] = signed;\n\t\t}\n\n\t\treturn fileAccess;\n\t}\n\n\t//in case the upload properties are failures\n\tself.asyncConfirmUploadComplete = function(uuid)\n\t{\n\t\tvar defer = Q.defer();\n\n\t\tvar isOver = false;\n\n\t\t//we have the uuid, lets fetch the existing request\n\t\tasyncRedisGet(uuid)\n\t\t\t.then(function(val)\n\t\t\t{\n\t\t\t\t//if we don't have a value -- the key doesn't exist or expired -- either way, it's a failure!\n\t\t\t\tif(!val)\n\t\t\t\t{\n\t\t\t\t\t//we're all done -- we didn't encounter an error, we just don't exist -- time to resubmit\n\t\t\t\t\tdefer.resolve({success: false, error: self.uploadErrors.nullUploadKey});\n\t\t\t\t\tisOver = true;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\t//so we have our object\n\t\t\t\tvar putRequest = JSON.parse(val);\n\n\t\t\t\t//these are all the requests we made\n\t\t\t\tvar allUploads = putRequest.uploads;\n\n\t\t\t\t//we have to check on all the objects\n\t\t\t\tvar uploadConfirmPromises = [];\n\n\t\t\t\tfor(var i=0; i < allUploads.length; i++)\n\t\t\t\t{\n\t\t\t\t\tvar req = allUploads[i].request;\n\n\t\t\t\t\tvar params = {Bucket: req.Bucket, Key: req.Key};\n\n\t\t\t\t\tuploadConfirmPromises.push(asyncHeadRequest(params));\n\t\t\t\t}\n\n\t\t\t\treturn Q.allSettled(uploadConfirmPromises);\n\t\t\t})\n\t\t\t.then(function(results)\n\t\t\t{\n\t\t\t\tif(isOver)\n\t\t\t\t\treturn;\n\n\t\t\t\t//check for existance\n\t\t\t\tvar missing = [];\n\n\t\t\t\t//now we have all the results -- we verify they're all fulfilled\n\t\t\t\tfor(var i=0; i < results.length; i++)\n\t\t\t\t{\n\t\t\t\t\tvar res = results[i];\n\t\t\t\t\tif(res.state !== \"fulfilled\")\n\t\t\t\t\t{\n\t\t\t\t\t\t// console.log(\"Results:\".red,results);\n\n\t\t\t\t\t\tdefer.resolve({success: false, error: self.uploadErrors.headCheckUnfulfilledError});\n\t\t\t\t\t\tisOver = true;\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\n\t\t\t\t\t//if one is false, we're all false\n\t\t\t\t\tif(!res.value.exists)\n\t\t\t\t\t\tmissing.push(i);\n\n\t\t\t\t}\n\n\t\t\t\t//are we missing anything???\n\t\t\t\tif(missing.length)\n\t\t\t\t{\n\t\t\t\t\tdefer.resolve({success: false, error: self.uploadErrors.headCheckMissingError, missing: missing});\n\t\t\t\t\tisOver = true;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\t//we're all confirmed, we delete the upload requests now\n\t\t\t\t//however, this is not a major concern -- it will expire shortly anyways\n\t\t\t\t//therefore, we resolve first, then delete second\n\n\t\t\t\tisOver = true;\n\t\t\t\tdefer.resolve({success: true});\n\n\t\t\t\t//if we're here, then we all exist -- it's confirmed yay!\n\t\t\t\t//we need to remove the key from our redis client -- but we're not too concerned -- they expire when they expire\n\t\t\t\treturn;//asyncRedisDelete(uuid);\n\t\t\t})\n\t\t\t.catch(function(err)\n\t\t\t{\n\t\t\t\tif(isOver)\n\t\t\t\t\treturn;\n\n\t\t\t\tdefer.reject(err);\n\t\t\t});\n\n\t\treturn defer.promise;\n\t}\n\n\tfunction asyncHeadRequest(params)\n\t{\n\t\tvar defer = Q.defer();\n\n\t\tself.s3.headObject(params, function (err, metadata) { \n\t\t\tif (err)\n\t\t\t{\n\t\t\t\t//error code is not found -- it doesn't exist!\n\t\t\t\tif(err.code === 'NotFound') { \n\t\t\t \t// Handle no object on cloud here \n\t\t\t\t\tdefer.resolve({exists: false});\n\t\t\t\t} \n\t\t\t\t//straight error -- reject\n\t\t\t\telse \n\t\t\t\t\tdefer.reject(err);\n\n\t\t\t}else { \n\t\t\t\tdefer.resolve({exists: true});\n\t\t\t}\n\t\t});\n\n\t\treturn defer.promise;\n\t}\n\n\n\tself.asyncInitializeUpload = function(uploadProperties)\n\t{\t\n\t\t//we promise to return\n\t\tvar defer = Q.defer();\n\n\t\t//create a unique ID for this upload\n\t\tvar uuid = cuid();\n\n\t\t//we send our upload properties onwards\n\t\tvar requestUploads = self.createUploadRequests(uploadProperties);\n\n\t\t//we now have a number of requests to make\n\t\t//lets process them and get some signed urls to put the objects there\n\t\tvar fullUploadRequests = [];\n\n\t\t//these will be everything we need to make a signed URL request\n\t\tfor(var i=0; i < requestUploads.length; i++)\n\t\t{\n\n\t\t\t//\n\t\t\tvar upReqName = requestUploads[i];\n\n\t\t\tvar signedURLReq = {\n\t\t\t\tBucket: bucketName, \n\t\t\t\tKey: upReqName.prepend + uuid + upReqName.append, \n\t\t\t\tExpires: uploadExpiration,\n\t\t\t\t// ACL: 'public-read'\n\t\t\t};\n\n\t\t\tvar signed = self.s3.getSignedUrl('putObject', signedURLReq);\n\n\t\t\t//store the requests here\n\t\t\tfullUploadRequests.push({url: signed, request: signedURLReq});\n\t\t}\n\n\t\t//now we have our full requests\n\t\t//let's store it in REDIS, then send it back\n\n\t\tvar inProgress = {\n\t\t\tuuid: uuid,\n\t\t\tstate : \"pending\",\n\t\t\tuploads: fullUploadRequests\n\t\t};\n\n\t\t//we set the object in our redis location\n\t\tasyncRedisSetEx(uuid, uploadExpiration, JSON.stringify(inProgress))\n\t\t\t.catch(function(err)\n\t\t\t{\n\t\t\t\tdefer.reject(err);\n\t\t\t})\n\t\t\t.done(function()\n\t\t\t{\n\t\t\t\tdefer.resolve(inProgress);\n\t\t\t});\n\n\t\t//promise for now -- return later\n\t\treturn defer.promise;\n\t}\n\n\tfunction asyncRedisSetEx(key, expire, val)\n\t{\n\t\tvar defer = Q.defer();\n\n\t\tredisClient.setex(key, expire, val, function(err)\n\t\t{\n\t\t\tif(!err)\n\t\t\t\tdefer.resolve();\n\t\t\telse\n\t\t\t\tdefer.reject(err);\n\t\t});\n\n\t\treturn defer.promise;\n\t}\n\n\tfunction asyncRedisGet(key, val)\n\t{\n\t\tvar defer = Q.defer();\n\n\t\tredisClient.get(key, function(err, val)\n\t\t{\n\t\t\tif(!err)\n\t\t\t\tdefer.resolve(val);\n\t\t\telse\n\t\t\t\tdefer.reject(err);\n\t\t});\n\n\t\treturn defer.promise;\n\t}\n\n\tfunction asyncRedisDelete(key, val)\n\t{\n\t\tvar defer = Q.defer();\n\n\t\tredisClient.del(key, function(err, reply)\n\t\t{\n\t\t\tif(!err)\n\t\t\t\tdefer.resolve();\n\t\t\telse\n\t\t\t\tdefer.reject(err);\n\t\t});\n\n\t\treturn defer.promise;\n\t}\n\n\treturn self;\n}", "function saveToS3(fileName) {\n // load in file;\n let logDir = './logs';\n let directory =`${logDir}/${fileName}`;\n let myKey = fileName;\n var myBody;\n console.log(directory);\n\n // read then save to s3 in one step (so no undefined errors)\n fs.readFile(directory, (err, data) => {\n if (err) throw err;\n myBody = data;\n console.log(\"save to s3 data is \" + data);\n var params = {Bucket: myBucket, Key: myKey, Body: myBody, ContentType: 'text/plain'};\n s3.putObject(params, function(err, data) {\n if (err) {\n console.log(err)\n } else {\n console.log(\"Successfully uploaded data to myBucket/myKey\");\n }\n });\n\n });\n fs.unlink(directory);\n\n // the create bucket stuff started to cause problems (error: \"BucketAlreadyOwnedByYou: Your previous request to create the named bucket succeeded and you already own it.\")\n // so I pulled it all out\n}", "function s3_upload_img(extension, file_in, try_in){\n var trynum = try_in;\n filename = file_in;\n var s3upload = new S3Upload({\n file_dom_selector: 'img_file',\n s3_sign_put_url: '/sign_s3_put/',\n s3_object_name: filename,\n onProgress: function(percent, message) {\n $('#img_status').text(\"Uploading: \" + percent + \"%\");\n },\n onFinishS3Put: function(url) {\n $(\"#id_img_url\").val(url);\n $('#image_preview').attr('src', url);\n enable_button();\n },\n onError: function(status) {\n if(trynum < 1){ //amount of tries\n console.log(\"upload error #\" + trynum + \" of type \" + status + \", retrying..\");\n trynum++;\n s3_upload_img(extension, file_in, trynum);\n }\n else{\n console.log(\"upload error #\" + trynum + \", giving up.\");\n $('#img_status').html('Upload error: ' + status);\n }\n }\n });\n}", "putObject(bucketName, objectName, contentType, size, r, cb) {\n if (!validateBucketName(bucketName)) {\n throw new errors.InvalidateBucketNameException('Invalid bucket name: ' + bucketName)\n }\n\n if (objectName === null || objectName.trim() === '') {\n throw new errors.InvalidObjectNameException('Object name cannot be empty')\n }\n\n if (contentType === null || contentType.trim() === '') {\n contentType = 'application/octet-stream'\n }\n\n function calculatePartSize(size) {\n var minimumPartSize = 5 * 1024 * 1024, // 5MB\n maximumPartSize = 5 * 1025 * 1024 * 1024,\n // using 10000 may cause part size to become too small, and not fit the entire object in\n partSize = Math.floor(size / 9999)\n\n if (partSize > maximumPartSize) {\n return maximumPartSize\n }\n return Math.max(minimumPartSize, partSize)\n }\n\n var self = this\n if (size <= 5*1024*1024) {\n var concater = transformers.getConcater()\n pipesetup(r, concater)\n .on('error', e => cb(e))\n .on('data', chunk => self.doPutObject(bucketName, objectName, contentType, null, null, chunk, cb))\n return\n }\n async.waterfall([\n function(cb) {\n self.findUploadId(bucketName, objectName, cb)\n },\n function(uploadId, cb) {\n if (uploadId) {\n self.listAllParts(bucketName, objectName, uploadId, (e, etags) => {\n return cb(e, uploadId, etags)\n })\n return\n }\n self.initiateNewMultipartUpload(bucketName, objectName, contentType, (e, uploadId) => {\n return cb(e, uploadId, [])\n })\n },\n function(uploadId, etags, cb) {\n var partSize = calculatePartSize(size)\n var sizeVerifier = transformers.getSizeVerifierTransformer(size)\n var chunker = BlockStream2({size: partSize, zeroPadding: false})\n var chunkUploader = self.chunkUploader(bucketName, objectName, contentType, uploadId, etags)\n pipesetup(r, chunker, sizeVerifier, chunkUploader)\n .on('error', e => cb(e))\n .on('data', etags => cb(null, etags, uploadId))\n },\n function(etags, uploadId, cb) {\n self.completeMultipartUpload(bucketName, objectName, uploadId, etags, cb)\n }\n ], function(err, etag) {\n if (err) {\n return cb(err)\n }\n cb(null, etag)\n })\n }", "function updateJSON(key, newObj, callback) {\n return combineObjectWithCachedS3File(config, upload, downloadDict, s3, key, newObj, callback);\n }", "uploadToS3(e) {\n this.setState({\n loading: true,\n serviceImageFlag: false\n });\n ReactS3.uploadFile(e.target.files[0], config)\n .then((response)=> {\n this.setState({\n image: response.location,\n loading: false,\n serviceImageFlag: true,\n imageHolder: \"\"\n })\n },\n )\n }", "manageBucketPointer(){\n if (fs.existsSync(this.file_bucket_path)) {\n let data=fs.readFileSync(this.file_bucket_path);\n this.bucket=JSON.parse(data);\n this.updateFilePointerBucket();\n }else{\n this.createFilePointerBucket();\n } \n }", "function uploadToS3(file_path, s3_file_path, cb)\n{\n\tconsole.log(\"Uploading to S3 file: \" + file_path, \"to: \" + s3_file_path);\n\n\theaders = {'x-amz-acl': 'public-read'};\n\ts3Client.putFile(file_path, s3_file_path, headers, function(err, s3Response) {\n\t if (err)\n \t{\n \t\tconsole.log(\"ERROR: \" + util.inspect(err));\n \t\tthrow err;\n \t}\n\t \n\t destUrl = s3Response.req.url;\n\n\t cb();\n\t});\n}", "async function storeOnS3(file) {\n // list acutal files\n const files = await fileListAsync('./output/');\n // if size is reached, gzip, send and rotate file\n for (const file of files) {\n const body = fs.createReadStream(`./output/${file}`);\n\n await new Promise((resolve, reject) => {\n // http://docs.amazonaws.cn/en_us/AWSJavaScriptSDK/guide/node-examples.html#Amazon_S3__Uploading_an_arbitrarily_sized_stream__upload_\n s3.upload({\n Bucket: process.env.S3_BUCKET,\n Key: file,\n Body: body\n })\n //.on('httpUploadProgress', (evt) => { console.log(evt); })\n .send(function (err, data) {\n // console.log(err, data); \n if (err) {\n reject(err);\n }\n resolve(data);\n });\n });\n await removeAsync(`./output/${file}`);\n }\n}", "getImageFromURL(URL, fileName, bucket, callback) {\n var options = {\n uri: URL,\n encoding: null\n };\n request(options, function (error, response, body) {\n if (error || response.statusCode !== 200) {\n console.log(\"failed to get image\", URL);\n console.log(error);\n if(response.statusCode !== 200){\n console.log(\"200 status not received for URL:\", options.uri);\n }\n } else {\n s3.putObject({\n Body: body,\n Key: fileName,\n Bucket: bucket\n }, function (error, data) {\n if (error) {\n console.log(\"error downloading image to s3\", fileName);\n } else {\n // console.log(\"body:\", body);\n // console.log(\"success uploading to s3\", fileName);\n }\n });\n }\n });\n }", "async uploadToS3(jsonFile) {\n const params = {\n Bucket: \"time-tracking-storage\",\n Key:\n TIME_PAGE_PREFIX +\n this.state.selectedFile.name.split(CSV_FILE_ATTACHMENT, 1).join(\"\"),\n ContentType: \"json\",\n Body: JSON.stringify(jsonFile),\n };\n\n s3.putObject(params, (err, data) => {\n if (data) {\n this.getListS3();\n } else {\n console.log(\"Error: \" + err);\n this.setState({ labelValue: params.Key + \" not uploaded.\" });\n }\n });\n\n this.setState({\n labelValue: params.Key + \" upload successfully.\",\n selectedFile: null,\n });\n }", "function s3Upload(files, bucketName, objectKeyPrefix, iamUserKey, iamUserSecret, callback) {\n var s3 = new AWS.S3({\n bucket: bucketName,\n accessKeyId: iamUserKey,\n secretAccessKey: iamUserSecret,\n apiVersion: '2006-03-01',\n });\n\n // s3.abortMultipartUpload(params, function (err, data) {\n // if (err) console.log(err, err.stack); // an error occurred\n // else console.log(data); // successful response\n // });\n\n // Setup the objects to upload to S3 & map the results into files\n var results = files.map(function(file) {\n // Upload file to bucket with name of Key\n s3.upload({\n Bucket: bucketName,\n Key: objectKeyPrefix + file.originalname, // Prefix should have \".\" on each end\n Body: file.buffer,\n ACL: 'public-read' // TODO: CHANGE THIS & READ FROM CLOUDFRONT INSTEAD\n },\n function(error, data) {\n // TODO: Maybe refine this to show only data care about elsewhere\n if(error) {\n console.log(\"Error uploading file to S3: \", error);\n return {error: true, data: error};\n } else {\n console.log('File uploaded. Data is:', data);\n return {error: false, data: data};\n }\n });\n });\n\n callback(results); // Results could be errors or successes\n}", "function insertBucket() {\n resource = {\n 'name': BUCKET\n };\n\n var request = gapi.client.storage.buckets.insert({\n 'project': PROJECT,\n 'resource': resource\n });\n executeRequest(request, 'insertBucket');\n}", "function getPutSignedUrl(key) {\n const signedUrlExpireSeconds = 60 * 5;\n return exports.s3.getSignedUrl('putObject', {\n Bucket: config_1.config.aws_media_bucket,\n Key: key,\n Expires: signedUrlExpireSeconds,\n });\n}", "function uploadFileIntoBucket(){\n // Create S3 service object\n s3 = new AWS.S3({apiVersion: '2006-03-01'});\n\n // call S3 to retrieve upload file to specified bucket\n var uploadParams = {Bucket: process.argv[2], Key: '', Body: ''};\n var file = process.argv[3];\n\n // Configure the file stream and obtain the upload parameters\n var fs = require('fs');\n var fileStream = fs.createReadStream(file);\n fileStream.on('error', function(err) {\n console.log('File Error', err);\n });\n\n uploadParams.Body = fileStream;\n var path = require('path');\n uploadParams.Key = path.basename(file);\n\n // call S3 to retrieve upload file to specified bucket\n s3.upload (uploadParams, function (err, data) {\n if (err) {\n console.log(\"Error\", err);\n } if (data) {\n console.log(\"Upload Success\", data.Location);\n }\n });\n}", "function StorageObject() {}", "function StorageObject() {}", "function StorageObject() {}", "function StorageObject() {}", "function StorageObject() {}", "function uploadToS3(file) {\n let s3bucket = new AWS.S3({\n accessKeyId: ACCESS,\n secretAccessKey: SECRET,\n Bucket: BUCKET_NAME,\n });\n s3bucket.createBucket(function () {\n var params = {\n Bucket: BUCKET_NAME,\n Key: file.name,\n Body: file.data,\n };\n s3bucket.upload(params, function (err, data) {\n if (err) {\n console.log(\"error in callback\");\n console.log(err);\n }\n console.log(\"success\");\n console.log(data);\n });\n });\n}", "function uploadS3File(bucketName, fileName, data, callback) {\n var params = {\n Bucket: bucketName,\n Key: fileName,\n Body: data,\n ACL: 'public-read', // TODO: find way to restrict access to this lambda function\n };\n s3.upload(params, function(err, data) {\n callback(err, data);\n });\n}", "function addS3bucket (req, res, next) {\n if (req.params.s3bucket) return next()\n req.params.s3bucket = [process.env.APP_NAME, req.params.appname].join('.')\n next()\n}", "function AmazonS3Extender(writer) {\n\t/// <summary>Extends Image Uploader with a direct upload to Amazon S3 storage.</summary>\n\t/// <param name=\"writer\" type=\"ImageUploaderWriter\">An instance of ImageUploaderWriter object.</param>\n\n\tBaseExtender.call(this, writer);\n\t\n\tthis._AWSAccessKeyId = \"\";\n\tthis._bucket = \"\";\n\tthis._bucketHostName = \"\";\t\n\n\tthis._writer.addEventListener(\"BeforeUpload\", IUCommon.createDelegate(this, this._control$BeforeUpload), true);\n\tthis._writer.addEventListener(\"Error\", IUCommon.createDelegate(this, this._control$Error), true);\n\n\tthis._sourceFile = new AmazonS3Extender.FileSettings(this, \"SourceFile\");\n\tthis._thumbnail1 = new AmazonS3Extender.FileSettings(this, \"Thumbnail1\");\n\tthis._thumbnail2 = new AmazonS3Extender.FileSettings(this, \"Thumbnail2\");\n\tthis._thumbnail3 = new AmazonS3Extender.FileSettings(this, \"Thumbnail3\");\n\t\n\tthis._postFields = [\"FileCount\", \"PackageIndex\"\n\t\t, \"PackageCount\", \"PackageGuid\"\n\t\t, \"Description_[ItemIndex]\", \"Width_[ItemIndex]\"\n\t\t, \"Height_[ItemIndex]\", \"Angle_[ItemIndex]\"\n\t\t, \"HorizontalResolution_[ItemIndex]\", \"VerticalResolution_[ItemIndex]\"\n\t\t, \"SourceFileSize_[ItemIndex]\", \"SourceFileCreatedDateTime_[ItemIndex]\"\n\t\t, \"SourceFileLastModifiedDateTime_[ItemIndex]\", \"SourceFileCreatedDateTimeLocal_[ItemIndex]\"\n\t\t, \"SourceFileLastModifiedDateTimeLocal_[ItemIndex]\", \"FileName_[ItemIndex]\"\n\t\t, \"UploadFile[ThumbnailIndex]CompressionMode_[ItemIndex]\", \"Thumbnail[ThumbnailIndex]FileSize_[ItemIndex]\"\n\t\t, \"Thumbnail[ThumbnailIndex]Width_[ItemIndex]\", \"Thumbnail[ThumbnailIndex]Height_[ItemIndex]\"\n\t\t, \"Thumbnail[ThumbnailIndex]Succeeded_[ItemIndex]\"];\n\n\tthis._postFieldsHash = {};\n\t\n\tthis._postFieldsAdded = {};\t\n\t\t\n\tfor (var i = 0; i < this._postFields.length; i++) {\n\t\tthis._postFieldsHash[this._postFields[i]] = 1;\n\t}\n}", "putFile(folder, key, file) {\r\n throw \"putFile(folder,key,file) Not Implemented\";\r\n }", "put(url, data = {}, succCb = null, errCb = null) {\n return this.request('PUT', url, data, succCb, errCb);\n }", "function putMPU(key, body, cb) {\n const uploadId = '9a0364b9e99bb480dd25e1f0284c8555';\n createShadowBucket(key, uploadId);\n const partBody = Buffer.from(body, 'utf8');\n const md5Hash = crypto.createHash('md5').update(partBody);\n const calculatedHash = md5Hash.digest('hex');\n const partKey = `${uploadId}${constants.splitter}00001`;\n const obj = {\n partLocations: [{\n key: 1,\n dataStoreName: 'scality-internal-mem',\n dataStoreETag: `1:${calculatedHash}`,\n }],\n key: partKey,\n };\n obj['content-md5'] = calculatedHash;\n obj['content-length'] = body.length;\n metadata.keyMaps.get(mpuShadowBucket).set(partKey, new Map);\n const partMap = metadata.keyMaps.get(mpuShadowBucket).get(partKey);\n Object.assign(partMap, obj);\n const postBody =\n '<CompleteMultipartUpload>' +\n '<Part>' +\n '<PartNumber>1</PartNumber>' +\n `<ETag>\"${calculatedHash}\"</ETag>` +\n '</Part>' +\n '</CompleteMultipartUpload>';\n const req = {\n bucketName,\n namespace,\n objectKey: key,\n parsedHost: 's3.amazonaws.com',\n url: `/${key}?uploadId=${uploadId}`,\n headers: { host: `${bucketName}.s3.amazonaws.com` },\n query: { uploadId },\n post: postBody,\n };\n return completeMultipartUpload(authInfo, req, log, cb);\n}", "put(file) {\n if (file.data.size > this.opts.maxFileSize) {\n return Promise.reject(new Error('File is too big to store.'));\n }\n\n return this.getSize().then(size => {\n if (size > this.opts.maxTotalSize) {\n return Promise.reject(new Error('No space left'));\n }\n\n return this.ready;\n }).then(db => {\n const transaction = db.transaction([STORE_NAME], 'readwrite');\n const request = transaction.objectStore(STORE_NAME).add({\n id: this.key(file.id),\n fileID: file.id,\n store: this.name,\n expires: Date.now() + this.opts.expires,\n data: file.data\n });\n return waitForRequest(request);\n });\n }", "function composable(callback: (err?: Error) => void) {\n bucket.upsert('key', {value: 1}, callback);\n}", "function PutObject(event, context) {\n base.Handler.call(this, event, context);\n}", "function uploadToS3 (file, infoId) {\n // var s3Credentials = appConfig.s3Credentials();\n // var POLICY = s3Credentials.POLICY\n // var SIGNATURE = s3Credentials.SIGNATURE\n // var ACCESS_KEY = s3Credentials.ACCESS_KEY\n var url = '//app.sitetheory.io:3000/?session=' +\n _.cookie('SITETHEORY') + (infoId ? ('&id=' + infoId) : '')\n\n return Upload.upload({\n url: url,\n method: 'POST',\n data: {\n // AWSAccessKeyId: ACCESS_KEY,\n key: file.name, // the key to store the file on S3, could be\n // file name or customized\n acl: 'private', // sets the access to the uploaded file in the\n // bucket: private, public-read, ...\n // policy: POLICY, // base64-encoded json policy\n // signature: SIGNATURE, // base64-encoded signature based on\n // policy string\n 'Content-Type': file.type !== ''\n ? file.type\n : 'application/octet-stream', // content type of the file\n // (NotEmpty)\n filename: file.name, // this is needed for Flash polyfill IE8-9\n file: file\n }\n })\n }", "function S3Fcty ($q, $upload, S3ResourceFcty) {\n var s3Upload = function(file, uploadData, uploadUrlPromise) {\n // Given the file to upload and an object containing the form\n // data needed to POST the file to S3, perform the upload.\n uploadData.upload_args.file = file;\n $upload.upload(uploadData.upload_args).then(function(response) {\n if (response.status === 201) {\n uploadUrlPromise.resolve(uploadData.cdn_url);\n } else {\n uploadUrlPromise.reject('upload failed');\n }\n });\n };\n var beginUpload = function(file, resourceName, resourceId, uploadName) {\n // Request the form data required to upload the file to S3\n // from the backend and then perform the upload.\n var uploadUrlPromise = $q.defer();\n S3ResourceFactory(resourceName).get({\n id: resourceId,\n fileName: file.name,\n uploadName: uploadName,\n mime_type: file.type\n }).$promise.then(function(uploadData) {\n s3Upload(file, uploadData, uploadUrlPromise);\n });\n return uploadUrlPromise.promise;\n };\n\n return {upload: beginUpload};\n}", "function StorageObject() { }", "function uploadFileIntoFolderOfBucket(){\n // Create S3 service object\n s3 = new AWS.S3({apiVersion: '2006-03-01'});\n\n // call S3 to retrieve upload file to specified bucket\n var uploadParams = {Bucket: process.argv[2], Key: '', Body: ''};\n var file = process.argv[4];\n\n // Configure the file stream and obtain the upload parameters\n var fs = require('fs');\n var fileStream = fs.createReadStream(file);\n fileStream.on('error', function(err) {\n console.log('File Error', err);\n });\n\n uploadParams.Body = fileStream;\n var path = require('path');\n uploadParams.Key = process.argv[3]+\"/\"+path.basename(file);\n\n // call S3 to retrieve upload file to specified bucket\n s3.upload (uploadParams, function (err, data) {\n if (err) {\n console.log(\"Error\", err);\n } if (data) {\n console.log(\"Upload Success\", data.Location);\n }\n });\n}", "function upload_private_S3_resource(file, folder, cFunc) {\n\tvar xhr = new XMLHttpRequest();\n\t// var amz_sign_s3 is defined in script on HTML page\n\txhr.open(\"GET\", amz_sign_s3+\"?file_name=\"+file.name+\"&file_type=\"+file.type+\"&folder=\"+folder);\n\txhr.onreadystatechange = function(){\n\t\tif(xhr.readyState === 4){\n\t\t\tif(xhr.status === 200){\n\t\t\t\tvar response = JSON.parse(xhr.responseText);\n\t\t\t\tupload_file(file, response.signed_request, response.url, cFunc);\n\t\t\t}\n\t\t\telse{\n\t\t\t\talert(\"Could not get signed URL.\");\n\t\t\t}\n\t\t}\n\t};\n\txhr.send();\n}", "function awsUpload() {\n\n //configuring the AWS environment\n AWS.config.update({\n accessKeyId: \"AKIAIYOTGRTBNHAJOWKQ\",\n secretAccessKey: \"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\"\n });\n var s3 = new AWS.S3();\n var filePath = \"./images/\" + imageLocation;\n\n //Configuring Parameters\n var params = {\n Bucket: 'pricefinder-bucket',\n Body: fs.createReadStream(filePath),\n Key: \"images/\" + Date.now() + \"_\" + path.basename(filePath)\n };\n\n //Uploading to s3 Bucket\n s3.upload(params, function (err, data) {\n //if an error occurs, handle it\n if (err) {\n console.log(\"Error\", err);\n }\n if (data) {\n console.log();\n console.log(\"Uploaded in:\", data.Location);\n console.log();\n }\n });\n\n customVision();\n\n}", "static _getS3Instance () {\n s3instance = s3instance || new AWS.S3({ apiVersion: S3_API_VERSION });\n return s3instance;\n }", "put(apiPath, parameters, options, callback) {\n let send = callback ? result.send : result.sendPromised\n return send(apiPath, parameters, 'PUT', options, callback)\n }", "function makeS3Request(fileUrl, signedRequestUrl, file) {\n return new Promise((resolve, reject) => {\n const xhr = new XMLHttpRequest()\n\n xhr.onreadystatechange = () => {\n if (xhr.readyState === 4) {\n if (xhr.status === 200) {\n resolve(fileUrl)\n } else {\n reject({\n status: xhr.status,\n statusText: xhr.statusText,\n })\n }\n }\n }\n\n xhr.open('PUT', signedRequestUrl)\n xhr.send(file)\n })\n}", "setItem(key, value) {\n this.storageObj.setItem(this.withScopePrefix(key), value);\n }", "async function uploadToS3(bucket, filePath) {\n let params = {\n Bucket: bucket,\n Body: fs.createReadStream(filePath),\n Key: path.basename(filePath)\n };\n\n //Converting async upload function to synchronous\n let s3Upload = Promise.promisify(s3.upload, { context: s3 });\n let uploadResult = await s3Upload(params);\n\n //Throw an error if the upload errored out \n if (!uploadResult.Location || uploadResult.Location.length === 0) {\n throw Error(uploadResult.err);\n }\n}", "put ( key, data,mimeType, ttl ) {\n\t\tlet _this = this;\n\t\ttry{\t\n\t\t\tvar st=this._gt();\n\t\t\tlet oBody = this._generateCacheObj (key,ttl,mimeType,(new Buffer(data).toString(ENCODINGS[ENC_B64])));\t\t\n \t\tlet req = http.request( this._requestOptions(HTTP_HEADER[HTTP_ROUTE_PUT],HTTP_HEADER[HTTP_METHOD_POST],oBody), function( res ) {\n\t\t\t\tvar buffer = \"\";\n \t\t\t\tres.on( EVT[EVT_HTTP_DATA], function( data ) \t{ buffer = buffer + data; });\n\t\t\t\tres.on( EVT[EVT_HTTP_END], \tfunction( data ) \t{ _this._st('put',st,_this._gt());_this.emit(EVT[EVT_TTCACHE_PUT],buffer); });\n\t\t\t\treq.on( EVT[EVT_HTTP_ERR],\tfunction( e) \t\t{ _this.emit(EVT[EVT_TTCACHE_ERR],e) });\n\t\t\t});\t\n\t\t\treq.write(oBody);\n\t\t\treq.end();\t\n\t\t} catch (err ){\n\t\t\tthrow err\n\t\t}\n\t}", "function uploadFile(bucket, key, fileLocation, callback) {\n fs.readFile(fileLocation, function(err, data) {\n if (err) {\n return callback(err);\n }\n\n var params = {\n Bucket: bucket,\n Key: key + '.webm',\n Body: data\n };\n\n s3.putObject(params, callback);\n });\n}", "function putStorage(time, lambda) {\n _storage.push({expired: time, lambda: lambda});\n }", "function createNewUpload(req, callback) {\n var params = {\n Bucket: config.s3.bucket,\n Key: (config.getPath(req) || '') + config.getFilename(req)\n };\n s3.createMultipartUpload(params, function(err, s3data) {\n if (err) {\n config.log(err, err.stack);\n return callback(err);\n }\n\n config.log('s3 data', JSON.stringify(s3data));\n\n config.setS3Id(req, s3data, function(err, response) {\n return callback(err, s3data);\n });\n /*\n data = {\n Bucket: \"examplebucket\",\n Key: \"largeobject\",\n UploadId: \"ibZBv_75gd9r8lH_gqXatLdxMVpAlj6ZQjEs.OwyF3953YdwbcQnMA2BLGn8Lx12fQNICtMw5KyteFeHw.Sjng--\"\n }\n */\n });\n }", "constructor (id, s3) {\n this.s3Prefix = process.env.S3_PREFIX // 'scores-bot'\n this._store = s3\n this.id = id\n this.touch(true)\n this.setDefaultState()\n }", "static Create(opts, cb) {\n new S3FileSystem(opts, cb)\n }", "async setFile({path, data, contentType, encoding, sensitivity, credentials}) {\n credentials = credentials || this.credentials\n await this.ensureIndexLoaded()\n this.ensurePermission({path, credentials, write: true})\n\n path = u.packKeys(path)\n\n // Generate fileID, store it on the index, set nodetype\n let fileID = u.uuid()\n this.index.setNodeType(path, u.NT_S3REF)\n this.index.setNodeProperty(path, 'fileID', fileID)\n this.index.setDontDelete(path, true)\n \n // Write the file to s3, write the url to the node\n let ref = await this.s3Client.write({key: fileID, body: data, contentType, encoding})\n let attributes = {}\n attributes[path] = ref\n await this.set({attributes, sensitivity})\n return ref\n }", "function StorageKey(storage, keyName)\r\n{\r\n this.get = function()\r\n {\r\n return this.storage.getItem(this.keyName);\r\n }\r\n\r\n this.set = function(value)\r\n {\r\n this.storage.setItem(this.keyName, value);\r\n }\r\n\r\n this.remove = function()\r\n {\r\n this.storage.removeItem(this.keyName);\r\n }\r\n\r\n this.storage = storage;\r\n this.keyName = keyName;\r\n}", "setItem(key, value) {\n if (arguments.length < 2) {\n throw new TypeError('Not enough arguments to \\'setItem\\'');\n }\n this._nativeObject._nativeCall('add', {\n key: encode(key),\n value: encode(value)\n });\n }", "put(key, val){\n let address = this._hash(key)\n if(!this.data[address]) {\n this.data[address] = [] \n this.data[address].push([key,val]) \n }else{\n // check for duplicate key in the bucket\n // if yes, update the value\n for(let i =0 ; i<this.data[address].length;i++){\n if(this.data[address][i][0]===key){\n this.data[address][i][1]=val\n return\n }\n }\n // if no duplicate, push new entry\n this.data[address].push([key,val])\n }\n \n }", "function put (_super, key, val, cb) {\n if (!val) {\n this.del(key, cb)\n } else {\n var hash = ethUtil.sha3(key)\n _super(hash, val, cb)\n }\n}", "function upload(file, remotePath) {\n\tvar deferred = q.defer();\n\tvar body = fs.createReadStream(file);\n\tvar params = {Bucket: bucketName, Key: remotePath, Body: body, ContentType: getContentTypeByFile(file)}\n\ts3.upload(params, function(err, data) {\n\t\tif (err) {\n\t\t\tbody.destroy();\n\t\t\tdeferred.reject(err);\n\t\t} else {\n\t\t\tbody.destroy();\n\t\t\tdeferred.resolve();\n\t\t}\n\t});\n\n\treturn deferred.promise;\n}", "_put(object, secure, validateId = true) {\n return __awaiter(this, void 0, void 0, function* () {\n if (object && validateId) {\n if (!this.validateModelId(object, 'Error putting a record. Invalid model ID.')) {\n return null;\n }\n }\n const headers = this.getHeader(secure);\n const result = yield this.httpClient\n .put(UrlUtil.join(this.apiRoot, this._baseEndpoint, object._id), object, {\n headers\n })\n .toPromise();\n if (Dto.isError(result.status.code)) {\n yield this.errorDialogService.openErrorDialog(result.status.text, result.status.message);\n return null;\n }\n return result.data;\n });\n }", "uploadImage(uploader, filename, file, encoding, mimeType, callback){\n if(mimeType.toLowerCase().indexOf(\"image\") >= 0){\n s3Client.upload({\n \"Bucket\" : \"purecloudkiosk\",\n \"Key\" : uploader.organization + \"/\" + uploader.personID + \"/\" + Date.now() + \"-\" + filename,\n \"Body\" : file,\n \"ContentEncoding\" : encoding,\n \"ContentType\" : mimeType\n }, callback);\n }\n else{\n callback({\"error\" : \"Incorrect Mimetype\"});\n }\n }", "function S3Move(s3, s3params, keys, limit, copy_tranformer, delete_transformer, callback) {\n async.waterfall([\n function(callback) {\n async.mapLimit(keys, limit, \n function (key, callback) {\n s3.copyObject(combineObjects(s3params, copy_tranformer(key)), callback);\n },\n callback)\n },\n function(ignore, callback) {\n var chunkedBy1000 = chunkArray(keys, 1000);\n async.mapLimit(chunkedBy1000, limit,\n function (keys, callback) {\n var keys = keys.map(delete_transformer)\n s3.deleteObjects(combineObjects(s3params, {'Delete':{'Objects':keys}}),\n function (err, data) {\n if (err)\n return callback(err);\n if (data.Errors && data.Errors.length)\n return callback(data.Errors)\n callback(null, data);\n });\n }, callback);\n }\n ], callback);\n}", "function uploadFile(file, signedRequest, url){\n const xhr = new XMLHttpRequest();\n xhr.open('PUT', signedRequest);\n xhr.setRequestHeader('Content-Type', \"text/csv\")\n xhr.onreadystatechange = () => {\n if(xhr.readyState === 4){\n if(xhr.status === 200){\n //console.log('upload to s3 success');\n }\n else{\n alert('Could not upload file.');\n }\n }\n };\n xhr.send(file);\n}", "put(url, data, opt = {}) {\n opt.method = 'PUT';\n opt.data = data;\n return this.sendRequest(url, opt);\n }", "function _put(path, body, params = {}) {\n const url = makeUrl(path, params);\n const token = getToken();\n if (getToken()) {\n return request.put(url).send(body).set('Accept', 'application/json').set('Content-Type', 'application/json')\n .set('Authorization', token);\n }\n return request.put(url).send(body).set('Accept', 'application/json').set('Content-Type', 'application/json');\n}", "function PutBucketPolicy(event, context) {\n base.Handler.call(this, event, context);\n}", "constructor(fileSystem, s3Object) {\n this.fileSystem = fileSystem;\n this.s3Object = s3Object;\n }", "update(id, struct, cb){\n this.get(id, (err, data) => {\n var model = {\n ...data,\n model:struct\n }\n this.bucket.upsert(id, model, (err) => {\n cb(err, model);\n });\n });\n }", "function getObjectPutReq(key, hasContent) {\n const bodyContent = hasContent ? 'body content' : '';\n return new DummyRequest({\n bucketName,\n namespace,\n objectKey: key,\n headers: {},\n url: `/${bucketName}/${key}`,\n }, Buffer.from(bodyContent, 'utf8'));\n}", "async function create_upload_thumbnail(storage_key) {\n\n const newThumbName = uuidv4()\n\n // Get owner and docId from storage_key\n const owner = storage_key.split('/')[1]\n const docId = storage_key.split('/')[2].split('.')[0]\n\n // 3. Save to file pipeline\n var file = gcsBucket.file(`users/${owner}/thumbnails/${newThumbName}.jpeg`).createWriteStream({ contentType: 'image/jpeg' })\n .on('error', (err) => {\n console.warn(err)\n return\n })\n .on('finish', () => {\n // Write thumbnail to firestore\n admin.firestore().collection('users').doc(owner).collection('files').doc(docId).update({\n thumbnail_key: `users/${owner}/thumbnails/${newThumbName}.jpeg`\n }).then(() => {\n return console.log(\"Thumbnail uploaded successfully.\")\n }).catch((err) => console.error('Could not upload ....', owner, err))\n\n });\n\n // 2. Resize\n const pipeline = sharp()\n pipeline.resize(450).jpeg({\n quality: 50\n }).pipe(file);\n\n // 1. Stream file from Wasabi\n const stream = s3.getObject({\n Bucket: project_id,\n Key: storage_key\n }).createReadStream().on('error', error => {\n return console.log(error)\n });\n stream.pipe(pipeline);\n\n}", "function pushToStorage(name, linkname, data, func, ptr) {\r\n if (ptr == null) { ptr = 0; }\r\n var req = digest.request({ protocol: settings.protocol, method: 'PUT', host: settings.hostname, path: ('/amt-storage/' + name + ((ptr != 0) ? '?append=' : '')), port: settings.localport });\r\n req.on('error', function (e) { console.log(\"Error occured: \" + JSON.stringify(e)); if (func != null) { func(null); } });\r\n req.on('response', function (response) {\r\n debug(1, 'Chunk Done', data.length, ptr);\r\n if ((response.statusCode == 200) && (ptr < data.length)) { pushToStorage(name, linkname, data, func, ptr); } else { if (func != null) { func(response.statusCode); } }\r\n });\r\n var header = (ptr > 0) ? '<metadata></metadata>' : '<metadata><headers><h>Content-Encoding:gzip</h><h>Content-Type:text/html</h></headers>' + ((linkname != null) ? ('<link>' + linkname + '</link>') : '') + '</metadata>';\r\n var blocklen = ((data.length - ptr) > (7000 - header.length)) ? (7000 - header.length) : (data.length - ptr);\r\n req.write(Buffer.concat([Buffer.from(header), data.slice(ptr, ptr + blocklen)]));\r\n ptr += blocklen;\r\n req.end();\r\n}", "function getSignedUrl(filename, filetype, foldername, operation) {\n const folderName = foldername;\n const params = {\n Bucket: 'gsg-image-uploads',\n Key: `${folderName}/` + filename,\n Expires: 604800\n };\n if(operation==='putObject'){\n params['ContentType'] = filetype;\n }\n return new Promise((resolve, reject) => {\n s3.getSignedUrl(operation, params, function(err, data) {\n if (err) {\n console.log(\"Error\",err);\n reject(err)\n } else {\n resolve(data)\n }\n });\n });\n}", "function putIndexedDB(objectStore, item, key) {\r\n let openDB = openIndexedDB();\r\n\r\n openDB.onsuccess = function() {\r\n let db = getStoreIndexedDB(openDB, objectStore);\r\n let putRequest = db.store.put(item, key);\r\n\r\n //console.log(\"The transaction that originated this request is \" + db.tx);\r\n\r\n putRequest.onsuccess = function() {\r\n console.log(\"IndexedDB put() request onSuccess\");\r\n }\r\n\r\n putRequest.onerror = function() {\r\n console.log(\"put request onError\");\r\n }\r\n\r\n }\r\n\r\n}", "function toS3Upload(req, res){\n\n req.s3Key = uuid.v4();\n\n //Set important params for s3 bucket upload\n const s3Params = {\n Bucket: config.awsBucketName,\n Key: `${req.s3Key}-${req.imageType}`,\n Body: req.file.buffer\n }\n\n //Promise to see whether or not the image upload was a success\n return new Promise( (resolve, reject) => {\n return s3.upload(s3Params, (err, data) => {\n if (err) return reject(err);\n return resolve({\n //File was uploaded successfully\n status: \"Everything OK\"\n })\n })\n })\n}", "static getFile (bucketName, objectKey) {\n const s3 = Storage._getS3Instance();\n const params = {\n Bucket: bucketName,\n Key: objectKey\n };\n return new Promise((resolve, reject) => {\n s3.getObject(params, (err, data) => {\n if (err) {\n reject(err);\n } else {\n resolve({\n content: data.Body, // buffer\n type: data.ContentType, // string\n encoding: data.ContentEncoding, // string\n size: data.ContentLength // integer\n });\n }\n });\n });\n }", "async function generateUrl(){\n let date = new Date();\n let id = parseInt(Math.random() * 10000000000);\n const imageName = `${id}${date.getTime()}.jpg`;\n\n const params = ({\n Bucket:buketName,\n Key:imageName,\n Expires:300,\n ContentType:'image/jpeg'\n })\n\n const uploadUrl = await s3.getSignedUrlPromise('putObject',params);\n return uploadUrl;\n}", "async function imageUpload(filename,type, bucketName) {\n\n try{\n\n //create bucket if it isn't present.\n await bucketExists(bucketName);\n\n const bucket = storage.bucket(bucketName);\n \n const gcsname = type +'/'+Date.now() + filename.originalname;\n const file = bucket.file(gcsname);\n \n const stream = file.createWriteStream({\n metadata: {\n contentType: filename.mimetype,\n },\n resumable: false,\n });\n\n \n \n stream.on('error', err => {\n filename.cloudStorageError = err;\n console.log(err);\n });\n \n stream.on('finish', async () => {\n \n filename.cloudStorageObject = gcsname;\n await file.makePublic().then(() => {\n imageUrl = getPublicUrl(gcsname,bucketName);\n console.log(imageUrl);\n });\n \n\n });\n \n stream.end(filename.buffer);\n return getPublicUrl(gcsname,bucketName);\n\n }\n\n catch(error){\n console.log(error);\n \n }\n // [END process]\n\n}" ]
[ "0.70302635", "0.6815252", "0.678542", "0.6688935", "0.6538359", "0.6529229", "0.6478697", "0.64470714", "0.6446966", "0.6408725", "0.63049763", "0.6297888", "0.62355083", "0.6096644", "0.6081681", "0.60771817", "0.6054547", "0.60463", "0.5980599", "0.59610456", "0.5956412", "0.59524125", "0.58829385", "0.5869803", "0.5868569", "0.58436555", "0.5839492", "0.58127093", "0.5809659", "0.5804338", "0.57909954", "0.57352906", "0.57225466", "0.5714226", "0.56958175", "0.5661882", "0.5644353", "0.5641708", "0.5640623", "0.563409", "0.5621418", "0.5606903", "0.55978906", "0.5591191", "0.5565238", "0.5565238", "0.5565238", "0.5565238", "0.5565238", "0.555572", "0.5520306", "0.5495402", "0.5489977", "0.54567677", "0.5446708", "0.541524", "0.54069227", "0.5397", "0.5392473", "0.5371657", "0.5363218", "0.536253", "0.53613454", "0.535655", "0.5353849", "0.5346285", "0.5343024", "0.5341815", "0.5314977", "0.53112704", "0.5289886", "0.5285343", "0.5278292", "0.5278164", "0.5256966", "0.52438617", "0.5240436", "0.5237468", "0.52314997", "0.52220446", "0.52192396", "0.52168715", "0.5212819", "0.5201623", "0.51977164", "0.51888955", "0.5176083", "0.5165614", "0.5157329", "0.51557434", "0.5154079", "0.5150266", "0.51476276", "0.5147173", "0.51465356", "0.5145503", "0.5145416", "0.5138072", "0.51253426", "0.5111693" ]
0.68142134
2
StorageProvider.purge() implementation for S3
async purge(rawUrl) { this.debug(`purging ${rawUrl} from ${this.bucket}`); await this.s3.deleteObject({ Bucket: this.bucket, Key: rawUrl, }).promise(); this.debug(`purged ${rawUrl} from ${this.bucket}`); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "async deleteInS3(params) {\n s3.deleteObject(params, function (err, data) {\n if (data) {\n console.log(params.Key + \" deleted successfully.\");\n } else {\n console.log(\"Error: \" + err);\n }\n });\n }", "function deleteObject() {\n const deleteParams = {\n Bucket: bucket,\n Key: key,\n };\n s3Client.deleteObject(deleteParams, (err, data) => {\n if (err) console.log('err:', err);\n else console.log('data:', data);\n });\n}", "static deleteFile (bucketName, objectKey) {\n const s3 = Storage._getS3Instance();\n const params = {\n Bucket: bucketName,\n Key: objectKey\n };\n return new Promise((resolve, reject) => {\n s3.deleteObject(params, (err, data) => err ? reject(err) : resolve());\n });\n }", "async function emptyAndDeleteFolderOfBucket() {\n s3=new AWS.S3({apiVersion: '2006-03-01'});\n const listParams = {\n Bucket:process.argv[2],\n Prefix:process.argv[3]\n };\n\n const listedObjects = await s3.listObjectsV2(listParams).promise();\n\n if (listedObjects.Contents.length === 0) return;\n\n const deleteParams = {\n Bucket: process.argv[2],\n Delete: { Objects: [] }\n };\n\n listedObjects.Contents.forEach(({ Key }) => {\n deleteParams.Delete.Objects.push({ Key });\n });\n\n await s3.deleteObjects(deleteParams).promise();\n\n if (listedObjects.IsTruncated) await emptyAndDeleteFolderOfBucket(process.argv[2], process.argv[3]);\n}", "function purge(days = 7) {\n const db = app.get('db');\n db('submission')\n .whereRaw(`create_timestamp < NOW() - INTERVAL '${days} DAYS'`)\n .del()\n .returning('*')\n .then(async (rows) => {\n try {\n await Promise.all(\n rows.map(async (row) => {\n const url = row.image_url;\n const s3ObjectKey = url.substring(url.lastIndexOf('/') + 1);\n await removeFromS3(s3ObjectKey);\n })\n );\n } catch (error) {\n console.error(error);\n }\n })\n .then(() => process.exit());\n}", "static async purgestorage() {\n if (StorageManager._storage) {\n for (let key in StorageManager._storage) {\n await StorageManager._internalClearStorageData(key)\n .then((response) => {\n if (!response) {\n throw response;\n }\n })\n .catch((error) => {\n throw error;\n })\n }\n }\n await StorageManager.initialize(StorageManager._mapping);\n return true;\n }", "resetBucket() {\n this.cacheBucket = '';\n }", "function after (s3, bucket, keys, done) {\n when.all(\n // Swallow deleteObject errors here incase the files don't yet exist\n keys.map(function (key) { return deleteObject(s3, bucket, key).catch(function() {}); })\n ).then(function () { done(); });\n}", "async function gcsDelete(bucket, file) {\n // console.log('Deleting file: '+file);\n storage.bucket(bucket).file(file).delete()\n .catch(function (error) {\n console.error(\"!!!!!!!!!!!! Failed to delete a file: \" + error);\n });\n}", "clear() {\n this._clear();\n delete this._storage()[get(this, '_storageKey')];\n }", "function purge()\n\t{\n\t\tif (maxRecords)\n\t\t{\n\t\t\tpurgeRecords();\n\t\t}\n\t\tif (maxSizeMb)\n\t\t{\n\t\t\tpurgeMemory();\n\t\t}\n\t}", "function purge() {\r\n captureTransactionDetails(\"PURGE\", \"purgePolicy\");\r\n}", "async function deleteFileFromFolder(){\n const params = {\n Bucket:process.argv[2],\n Key: process.argv[3] //if any sub folder-> path/of/the/folder.ext \n }\n s3=new AWS.S3({apiVersion: '2006-03-01'});\n try {\n await s3.headObject(params).promise()\n console.log(\"File Found in S3\")\n try {\n await s3.deleteObject(params).promise()\n console.log(\"file deleted Successfully\")\n }\n catch (err) {\n console.log(\"ERROR in file Deleting : \" + JSON.stringify(err))\n }\n } \n catch (err) {\n console.log(\"File not Found ERROR : \" + err.code)\n }\n\n}", "function before (s3, bucket, keys, done) {\n createBucket(s3, bucket)\n .then(function () {\n return when.all(\n // Swallow deleteObject errors here incase the files don't yet exist\n keys.map(function (key) { return deleteObject(s3, bucket, key).catch(function () {}); })\n )\n }).then(function () { done(); });\n}", "function destroyFromGCS(storageFilePath) {\n let promise = new Promise((resolve, reject) => {\n const bucket = admin.storage().bucket();\n const file = bucket.file(storageFilePath);\n\n // storage.bucket(bucketName).file(storageFilePath).delete();\n file.delete().then(() => {\n // Deleted\n resolve();\n }).catch(err => {\n reject(err);\n });\n });\n return promise;\n}", "deleteObject(image) {\n const params = {\n Bucket: image.bucketName,\n Key: image.fileName\n };\n\n console.log(\"Delete original object: \" + params.Key);\n\n return this.client.deleteObject(params).promise();\n }", "function deleteStoredImages() {\n let storageRef = storage.ref();\n for (var i = 0; i < imageURLs.length; i++)\n deleteRef = imageURLs[i].replace(\"https://firebasestorage.googleapis.com/v0/b/greenquest-\"\n + \"5f80c.appspot.com/o/images%2Fquests%2F\", \"\");\n deleteRef = deleteRef.substr(0, deleteRef.indexOf(\"?\"));\n deleteRef = storageRef.child(\"images/quests/\" + deleteRef);\n deleteRef.delete()\n .then(() => {\n console.log(\"Processed image successfully removed from storage!\");\n })\n .catch((error) => {\n console.error(\"Error removing processed image from storage: \", error);\n });\n}", "function deleteBucket() {\n var request = gapi.client.storage.buckets.delete({\n 'bucket': BUCKET\n });\n executeRequest(request, 'deleteBucket');\n}", "clearStorage() {\n this.storage.clear();\n }", "function DeleteBucket(filePath) {\n const bucket = functions.config().firebase.storageBucket\n const myBucket = gcs.bucket(bucket);\n const file = myBucket.file(filePath);\n console.log(`${myBucket},${filePath}, ${file}`)\n if (file.exists()){\n return file.delete();\n }\n else {\n return;\n }\n\n}", "function deleteFileFromS3(key) {\n const deleteParams = {\n Bucket: 'week18',\n Key: key,\n }\n return s3.deleteObject(deleteParams).promise()\n}", "async cleanUpStorage() {\n if(!this.storageAutoCleanSize) {\n return;\n }\n\n const storageInfoData = { tempUsed: false, tempFree: false };\n const storage = await this.getStorageInfo(storageInfoData);\n const needSize = this.storageAutoCleanSize - storage.free;\n\n if(needSize <= 0) {\n return;\n }\n\n this.logger.info(`It is necessary to clean ${needSize} byte(s)`);\n const tree = await this.getStorageCleaningUpTree();\n let node = tree.minNode();\n\n while(node) {\n const obj = node.data;\n\n try {\n await this.removeFileFromStorage(path.basename(obj.path));\n\n if((await this.getStorageInfo(storageInfoData)).free >= this.storageAutoCleanSize) {\n break;\n }\n }\n catch(err) {\n this.logger.warn(err.stack);\n }\n\n node = tree.next(node);\n }\n\n if((await this.getStorageInfo(storageInfoData)).free < this.storageAutoCleanSize) {\n this.logger.warn('Unable to free up space on the disk completely');\n }\n }", "function deleteStorage(name, func, noretry) {\r\n var req = digest.request({ protocol: settings.protocol, method: 'DELETE', host: settings.hostname, path: '/amt-storage/' + name, port: settings.localport });\r\n req.on('error', function (e) { if ((e == \"Error: Socket was unexpectedly closed\") && (noretry != true)) { deleteStorage(name, func, true); } else { if (func != null) { if (e.statusCode) { func(e.statusCode); } else { func(null); } } } });\r\n req.on('response', function (response) { if (func != null) { func(response.statusCode); } });\r\n req.end();\r\n}", "function deleteObject() {\n var request = gapi.client.storage.objects.delete({\n 'bucket': BUCKET,\n 'object': object\n });\n executeRequest(request, 'deleteObject');\n}", "function removeImageFromS3(imageKey) {\n s3.deleteObject(\n {\n Bucket: bucketName,\n Key: imageKey,\n },\n function (err, data) {\n winston.log(\n \"error\",\n `Error removing image ${imageKey} from S3 bucket ${bucketName}`,\n err\n );\n }\n );\n winston.info(`Removed image ${imageKey} from S3 bucket ${bucketName}`);\n}", "function deleteFile(fileKey) {\n var params = {\n Bucket: bucketName,\n Key: fileKey,\n };\n\n s3.deleteObject(params, function (err, data) {\n if (err) console.log(err, err.stack);\n console.log('deleted!');\n });\n}", "async purgeCache(urlArray, logger, purgeAll = false) {\n if (!Array.isArray(urlArray)) {\n throw new Error('Parameter `urlArray` needs to be an array of urls');\n }\n if (!purgeAll) {\n try {\n logger.save(`Purging URL's`);\n //retrieve surrogate key associated with each URL/file updated in push to S3\n const surrogateKeyPromises = urlArray.map(url => this.retrieveSurrogateKey(url));\n const surrogateKeyArray = await Promise.all(surrogateKeyPromises)\n\n //purge each surrogate key\n const purgeRequestPromises = surrogateKeyArray.map(surrogateKey => this.requestPurgeOfSurrogateKey(surrogateKey));\n await Promise.all(purgeRequestPromises);\n // GET request the URLs to warm cache for our users\n const warmCachePromises = urlArray.map(url => this.warmCache(url));\n await Promise.all(warmCachePromises)\n } catch (error) {\n logger.save(`${'(prod)'.padEnd(15)}error in purge urls: ${error}`);\n }\n\n } else {\n try {\n logger.save(`Purging all`);\n await this.requestPurgeAll()\n } catch (error) {\n logger.save(`${'(prod)'.padEnd(15)}error in purge all: ${error}`);\n }\n }\n }", "function deleteFileInAFolder(file_key,req,res,operation)\n{\n const params = {\n Bucket:GlobalVar.AWS_BUCKET_NAME,\n Key: file_key //if any sub folder-> path/of/the/folder.ext \n }\n s3.headObject(params).promise()\n .then(()=>{\n console.log(\"File Found in S3\");\n s3.deleteObject(params).promise()\n .then(()=>{\n console.log(\"file deleted Successfully\");\n res.json('Bug '+ operation + ' with file_key: '+file_key);\n }).catch((err)=>{\n console.log(\"ERROR in file \" + operation+ \"ing : \" + JSON.stringify(err));\n res.status(400).json('Error: '+err);\n })\n }).catch((err)=>{\n console.log(\"File not Found ERROR : \" + err.code);\n res.status(400).json('Error: '+err);\n })\n}", "function deleteStorage(property) {\r\n return new Deferred(\r\n createPromisefunction('delete', {\r\n 'property': property,\r\n 'value': null\r\n })\r\n );\r\n }", "async function cleanup() {\n const stacksToDelete = await deleteableStacks(exports.STACK_NAME_PREFIX);\n // Bootstrap stacks have buckets that need to be cleaned\n const bucketNames = stacksToDelete.map(stack => aws_helpers_1.outputFromStack('BucketName', stack)).filter(defined);\n await Promise.all(bucketNames.map(aws_helpers_1.emptyBucket));\n // Bootstrap stacks have ECR repositories with images which should be deleted\n const imageRepositoryNames = stacksToDelete.map(stack => aws_helpers_1.outputFromStack('ImageRepositoryName', stack)).filter(defined);\n await Promise.all(imageRepositoryNames.map(aws_helpers_1.deleteImageRepository));\n await aws_helpers_1.deleteStacks(...stacksToDelete.map(s => s.StackName));\n // We might have leaked some buckets by upgrading the bootstrap stack. Be\n // sure to clean everything.\n for (const bucket of bucketsToDelete) {\n await aws_helpers_1.deleteBucket(bucket);\n }\n bucketsToDelete = [];\n}", "clear() {\n AsyncStorage.clear(this.id, console.log);\n this.obj = {};\n }", "function destroyAllTransactionPhotosFromGCS(uid, transactionId) {\n // You do not have to use Promise constructor here, just return async function\n // return new Promise((resolve, reject) => {\n return (async (resolve, reject) => {\n const bucket = admin.storage().bucket();\n let folderRef = `/users/${uid}/transactions/${transactionId}/`;\n // List all the files under the bucket\n let files = await bucket.getFiles({\n prefix: folderRef\n });\n // Delete each one\n let response;\n for (let i in files) {\n try {\n response = await files[i].delete();\n } catch(err) {\n reject(err);\n }\n }\n resolve(response);\n });\n}", "deleteAll(storename) {\n this.cache.then((db) => {\n db.transaction(storename, \"readwrite\").objectStore(storename).clear();\n });\n }", "mfDelete_LabradorAwsS3Images(file){\n\t\treturn mf.modeDelete_LabradorAwsS3Images(this,file)\n\t}", "function S3Move(s3, s3params, keys, limit, copy_tranformer, delete_transformer, callback) {\n async.waterfall([\n function(callback) {\n async.mapLimit(keys, limit, \n function (key, callback) {\n s3.copyObject(combineObjects(s3params, copy_tranformer(key)), callback);\n },\n callback)\n },\n function(ignore, callback) {\n var chunkedBy1000 = chunkArray(keys, 1000);\n async.mapLimit(chunkedBy1000, limit,\n function (keys, callback) {\n var keys = keys.map(delete_transformer)\n s3.deleteObjects(combineObjects(s3params, {'Delete':{'Objects':keys}}),\n function (err, data) {\n if (err)\n return callback(err);\n if (data.Errors && data.Errors.length)\n return callback(data.Errors)\n callback(null, data);\n });\n }, callback);\n }\n ], callback);\n}", "delete(key) {\n this.storageMechanism.removeItem(key);\n }", "async purge() {\n\t\tconst res = await Api.purge(this.queueName)\n\t\treturn res\n\t}", "function destroyPrefixedStorageItemKeys(prefix) {\n var keys_to_destroy = retrievePrefixedStorageItemKeys(prefix);\n for (var key of keys_to_destroy) {\n localStorage.removeItem(key);\n }\n }", "function rememberToDeleteBucket(bucketName) {\n bucketsToDelete.push(bucketName);\n}", "async purgeAll() {\n const baseopts = this.options('/purge_all');\n const opts = Object.assign({\n method: 'POST',\n }, baseopts);\n return request(opts).then((r) => {\n this.tick(1, 'Purging entire cache');\n return r;\n })\n .catch((e) => {\n const message = 'Cache could not be purged';\n this.log.error(message, e);\n throw new Error(message, e);\n });\n }", "remove(key) {\n const index = getIndexBelowMax(key.toString(), this.limit);\n const bucket = this.storage.get(index);\n if (Array.isArray(bucket)) {\n for (let i = 0; i < bucket.length; i++) {\n const objKey = bucket[i][0];\n if (objKey === key) {\n bucket.splice(i, 1);\n }\n }\n }\n }", "remove(bucket, key) {\n return this.store.del(`${bucket}${DELIM}${key}`);\n }", "removeIncompleteUpload(bucketName, objectName, cb) {\n if (!validateBucketName(bucketName)) {\n throw new errors.InvalidateBucketNameException('Invalid bucket name: ' + bucket)\n }\n\n if (objectName === null || objectName.trim() === '') {\n throw new errors.InvalidObjectNameException('Object name cannot be empty')\n }\n\n var self = this\n this.findUploadId(bucketName, objectName, (err, uploadId) => {\n if (err || !uploadId) {\n return cb(err)\n }\n var requestParams = {\n host: self.params.host,\n port: self.params.port,\n protocol: self.params.protocol,\n path: `/${bucketName}/${objectName}?uploadId=${uploadId}`,\n method: 'DELETE'\n }\n\n signV4(requestParams, '', self.params.accessKey, self.params.secretKey)\n\n var req = self.transport.request(requestParams, (response) => {\n if (response.statusCode !== 204) {\n var concater = transformers.getConcater()\n var errorTransformer = transformers.getErrorTransformer(response)\n pipesetup(response, concater, errorTransformer)\n .on('error', e => cb(e))\n return\n }\n cb()\n })\n req.on('error', e => cb(e))\n req.end()\n })\n }", "clear() {\n return driver.storage[storageArea].remove(storageKey);\n }", "flush() {\n const { impl, cache } = this;\n if(!this.supportsStorage) return;\n\n impl.eachKey.call(this, key => impl.flushItem.call(this, key));\n }", "clearStorage() {\r\n return new Promise((resolve) => {\r\n const options = {\r\n storages: [\r\n 'appcache',\r\n 'cookies',\r\n 'filesystem',\r\n 'indexdb',\r\n 'localstorage',\r\n 'shadercache',\r\n 'websql',\r\n 'serviceworkers',\r\n ],\r\n quotas: [\r\n 'temporary',\r\n 'persistent',\r\n 'syncable',\r\n ],\r\n origin: '*',\r\n };\r\n eltr.session.defaultSession.clearStorageData(options, resolve);\r\n });\r\n }", "clearExpired() {\n let keys;\n \n //otestuji jestli je podporovana storage\n if(!this.isSupportsStorage()) {\n return null;\n }\n\n //pokud je neco v storage, tak pokracuji\n if (this._storage.length > 0) {\n\n //ziskam vsechny klice ktere odpovidaji prefixu\n keys = Object.keys(this._storage).filter( v => v.indexOf(this._options.prefix)===0 );\n\n if (keys.length > 0) {\n for (let i = 0, length = keys.length; i < length; i++){\n let key = keys[i].replace(this._options.prefix,''), //odeberu u klice prefix\n record = this._stringToJson(this._getItem(key)); \n\n //otestuji jestli je polozka expirovana\n if(record.expire && new Date().getTime() > record.expire) {\n console.info('Item \"' + key + '\" is expired. Item is removed.'); \n this._removeItem(key);\n }\n }\n }\n }\n }", "function clean () {\n const values = Object.values(resources);\n\n if (values.length < conf.CACHE_SIZE) {\n return\n }\n\n values.forEach(resource => {\n if (!resource.clean) {\n if (Object.keys(resource.callbacks).length === 0) {\n resource.clean = true;\n }\n return\n }\n if (resource.plugin.clean && resource.plugin.clean(resource)) {\n return\n }\n clearTimeout(resources[resource.url].timeout);\n delete resources[resource.url];\n });\n}", "function destroyAllPostPhotosFromGCS(uid, postId) {\n // You do not have to use Promise constructor here, just return async function\n // return new Promise((resolve, reject) => {\n return (async (resolve, reject) => {\n const bucket = admin.storage().bucket();\n let folderRef = `/users/${uid}/posts/${postId}/`;\n // List all the files under the bucket\n let files = await bucket.getFiles({\n prefix: folderRef\n });\n // Delete each one\n let response;\n for (let i in files) {\n try {\n response = await files[i].delete();\n } catch(err) {\n reject(err);\n }\n }\n resolve(response);\n });\n}", "flushExpired() {\n const { impl, cache } = this;\n if(!this.supportsStorage) return;\n\n impl.eachKey.call(this, key => flushExpiredItem.call(impl, key));\n }", "function delete_storage(){\n\tsimact.Algebrite.run(\"clearall\");\n\tfilloutputarea();\n}", "handleDeleteBucketlist(id){\n axios.delete(BASE_URL + `/bucketlist/${id}/`,\n {\n headers: {\"Authorization\": localStorage.getItem('token')}\n })\n .then((response) => {\n toast.success(response.data.message);\n this.getBucketlist();\n \n })\n .catch((error) => {\n toast.error(error.response.data.error);\n });\n }", "async cleanup() {\n // The cleanup logic is as follows:\n // - We first try to delete the resource using the delete() method\n // - However, it is possible that the user that created the resource does not have permission\n // to delete the resource or the user might have become inactive. Because of this we will\n // also try to perform the same delete() method but with default admin credentials\n\n try {\n await this.delete();\n } catch (error) {\n // Now we try with default admin credentials\n const adminSession = await this.setup.defaultAdminSession();\n this.axiosClient = adminSession.axiosClient;\n await this.delete();\n }\n }", "delete() {}", "clear() {\n return this.storageService.secureStorage.clear();\n }", "async function purgeQueue(opts) {\n opts = parseOptions(opts, ['sqs', 'queueUrl']);\n const _debug = debug('queue:purgeQueue:' + url.parse(opts.queueUrl).pathname.slice(1));\n\n await opts.sqs.purgeQueue({QueueUrl: opts.queueUrl}).promise();\n _debug('purged queue %s', opts.queueUrl);\n}", "async function cleanOrigin( origin ) {\n const fdb = await origin.fdb;\n // Iterate over deleted records, build lists of items to delete by category.\n const deleted = {};\n await fdb.forEach('status','deleted', record => {\n // Read values from the record.\n const { path, category } = record;\n // Construct a request URL.\n const url = origin.url+path;\n // Construct an deletion item.\n const item = { path, url };\n // Record the fileset category.\n const list = deleted[category];\n if( list ) {\n list.push( item );\n }\n else {\n deleted[category] = [ item ];\n }\n });\n // Iterate over each fileset category and remove deleted files from its cache.\n for( const category in deleted ) {\n // Get the fileset cache name..\n const { cacheName } = getFileset( origin, category );\n // Open the cache.\n const cache = await caches.open( cacheName );\n // Get the list of deleted items.\n const items = deleted[category];\n log('debug','%s Deleting %d files from fileset %s...', IconDelete, items.length, category );\n // Iterate over the deleted items.\n for( const { path, url } of items ) {\n const request = new Request( url );\n // Delete from the cache.\n cache.delete( request );\n // Delete the object store record.\n await fdb.remove( path );\n }\n }\n // Prune commit records - delete any commit record with no active file records.\n await fdb.forEach('category', '$commit', async ( record ) => {\n const { path, info: { commit } } = record;\n const count = await fdb.indexCount('commit', commit );\n log('debug','commit %s count %d', commit, count );\n if( count == 0 ) {\n log('debug','%s Deleting commit record for %s...', IconDelete, commit );\n await fdb.remove( path );\n }\n });\n}", "function ClearLocalStorage(){\n storageObject.clear();\n}", "remove () {\n // cleanup\n }", "async function remove(req, res, next) {\n const { mobile } = req.user;\n const { id } = req.params;\n Post.destroy({ where: { id, mobile } })\n .then(async () => {\n await emptyS3Directory(mobile, id);\n res.json(httpStatus[\"204_MESSAGE\"]);\n })\n .catch((err) => next(err));\n}", "static deregister() {\n delete __WEBPACK_IMPORTED_MODULE_0__common_plugin__[\"a\" /* PLUGINS */][\"FSStorage\"];\n }", "function clearStorageInfo() {\n var gettingAllStorageItems = browser.storage.local.get(null);\n gettingAllStorageItems.then((results) => {\n deleteAllUrlType(results);\n }, reportError);\n }", "cleanup() {\n\t\tclearTimeout(this._expirationTimer);\n\n\t\tif (this._stream) {\n\t\t\tthis._stream.abort();\n\t\t}\n\n\t\tthis._particle.deleteCurrentAccessToken({\n\t\t\tauth: this._accessToken\n\t\t});\n\t}", "clean(cb) {\n contract(arguments).params(\"function\").end();\n this.redis.keys(this.prefix + \"*\", (err, keys) => {\n if (keys.length) {\n this.redis.del(keys, function () {\n cb();\n });\n } else {\n cb();\n }\n });\n }", "function S3Store(options) {\n options = options || {};\n\n this.options = extend({\n path: 'cache/',\n tryget: true,\n s3: {}\n }, options);\n\n\n // check storage directory for existence (or create it)\n if (!fs.existsSync(this.options.path)) {\n fs.mkdirSync(this.options.path);\n }\n\n this.name = 's3store';\n\n // internal array for informations about the cached files - resists in memory\n this.collection = {};\n\n // TODO: need implement!\n // fill the cache on startup with already existing files\n // if (!options.preventfill) {\n // this.intializefill(options.fillcallback);\n // }\n}", "function baseAwsS3 (base, s3Bucket) {\n\n var recordsPath = path.join(base, '/outputs/records');\n\n utility.longWalk(recordsPath, function (hosts) {\n var hostsIndex = 0;\n\n function recursiveHost (host) {\n utility.longWalk(host, function (recs) {\n var recsCount = recs.length;\n var recsIndex = 0;\n\n function recursiveRecord (rec) {\n utility.longWalk(rec, function (files) {\n var fileCount = files.length;\n var fileIndex = 0;\n\n function recursiveUpload (file) {\n archiver.uploadToS3(file, s3Bucket, function (res) {\n console.log(res);\n fileIndex++;\n\n if (fileIndex < fileCount) {\n recursiveUpload(files[fileIndex]);\n }\n\n if (fileIndex === fileCount) {\n fs.rmrf(recs[recsIndex], function (err) {\n if (err) console.log(err);\n else {\n recsIndex++;\n if (recsIndex < recsCount) {\n recursiveRecord(recs[recsIndex]);\n }\n if (recsIndex === recsCount) {\n fs.rmrf(hosts[hostsIndex], function (err) {\n if (err) console.log(err);\n else {\n hostsIndex++;\n recursiveHost(hosts[hostsIndex]);\n }\n })\n }\n }\n })\n }\n })\n }\n if (fileCount === 0) {\n recsIndex++;\n recursiveRecord(recs[recsIndex]);\n } else {\n recursiveUpload(files[fileIndex]);\n }\n })\n }\n recursiveRecord(recs[recsIndex]);\n })\n }\n recursiveHost(hosts[hostsIndex]);\n })\n}", "deleteRecord() {\n this._super(...arguments);\n const gist = this.gist;\n if(gist) {\n gist.registerDeletedFile(this.id);\n\n // Following try/catch should not be necessary. Bug in ember data?\n try {\n gist.get('files').removeObject(this);\n } catch(e) {\n /* squash */\n }\n }\n }", "function deleteFolderOfImages(project_id) {\n const listObjectsParams = {\n Bucket: process.env.AWS_BUCKET_NAME,\n Prefix: `${project_id}/`,\n };\n s3.listObjects(listObjectsParams, (err, data) => {\n\n const deleteObjectsParams = {\n Bucket: process.env.AWS_BUCKET_NAME,\n Delete: { Objects: [] },\n };\n for (const content of data.Contents) {\n deleteObjectsParams.Delete.Objects.push({ Key: content.Key });\n }\n s3.deleteObjects(deleteObjectsParams, () => {});\n });\n}", "function S3ObjectClass(configuration, createUploadRequestNamesFunction, redisClient)\n{\n\tvar self = this;\n\n\t//grab bucketname from config file\n\tvar bucketName = configuration.bucket;\n\tvar uploadExpiration = configuration.expires || 15*60;\n\n\tself.s3 = new AWS.S3({params: {Bucket: bucketName}, computeChecksums: false});\n\n\t//example for outside use or testing -- helpful if i forget my function logic later--or someone checking around from the outside\n\tself.requestFunctionExample = exampleUploadRequestFunction;\n\tself.createUploadRequests = createUploadRequestNamesFunction;\n\n\tself.uploadErrors = {\n\t\tnullUploadKey : 0,\n\t\tredisError : 1,\n\t\theadCheckUnfulfilledError : 2,\n\t\theadCheckMissingError : 3,\n\t\tredisDeleteError : 4\n\t}\n\n\n\tself.generateObjectAccess = function(fileLocations)\n\t{\n\n\t\t//we create a map of signed URLs\n\t\tvar fileAccess = {};\n\n\t\tfor(var i=0; i < fileLocations.length; i++)\n\t\t{\n\t\t\tvar fLocation = fileLocations[i];\n\n\t\t\tvar signedURLReq = {\n\t\t\t\tBucket: bucketName, \n\t\t\t\tKey: fLocation,\n\t\t\t\tExpires: uploadExpiration,\n\t\t\t};\n\n\t\t\tvar signed = self.s3.getSignedUrl('getObject', signedURLReq);\n\n\t\t\tfileAccess[fLocation] = signed;\n\t\t}\n\n\t\treturn fileAccess;\n\t}\n\n\t//in case the upload properties are failures\n\tself.asyncConfirmUploadComplete = function(uuid)\n\t{\n\t\tvar defer = Q.defer();\n\n\t\tvar isOver = false;\n\n\t\t//we have the uuid, lets fetch the existing request\n\t\tasyncRedisGet(uuid)\n\t\t\t.then(function(val)\n\t\t\t{\n\t\t\t\t//if we don't have a value -- the key doesn't exist or expired -- either way, it's a failure!\n\t\t\t\tif(!val)\n\t\t\t\t{\n\t\t\t\t\t//we're all done -- we didn't encounter an error, we just don't exist -- time to resubmit\n\t\t\t\t\tdefer.resolve({success: false, error: self.uploadErrors.nullUploadKey});\n\t\t\t\t\tisOver = true;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\t//so we have our object\n\t\t\t\tvar putRequest = JSON.parse(val);\n\n\t\t\t\t//these are all the requests we made\n\t\t\t\tvar allUploads = putRequest.uploads;\n\n\t\t\t\t//we have to check on all the objects\n\t\t\t\tvar uploadConfirmPromises = [];\n\n\t\t\t\tfor(var i=0; i < allUploads.length; i++)\n\t\t\t\t{\n\t\t\t\t\tvar req = allUploads[i].request;\n\n\t\t\t\t\tvar params = {Bucket: req.Bucket, Key: req.Key};\n\n\t\t\t\t\tuploadConfirmPromises.push(asyncHeadRequest(params));\n\t\t\t\t}\n\n\t\t\t\treturn Q.allSettled(uploadConfirmPromises);\n\t\t\t})\n\t\t\t.then(function(results)\n\t\t\t{\n\t\t\t\tif(isOver)\n\t\t\t\t\treturn;\n\n\t\t\t\t//check for existance\n\t\t\t\tvar missing = [];\n\n\t\t\t\t//now we have all the results -- we verify they're all fulfilled\n\t\t\t\tfor(var i=0; i < results.length; i++)\n\t\t\t\t{\n\t\t\t\t\tvar res = results[i];\n\t\t\t\t\tif(res.state !== \"fulfilled\")\n\t\t\t\t\t{\n\t\t\t\t\t\t// console.log(\"Results:\".red,results);\n\n\t\t\t\t\t\tdefer.resolve({success: false, error: self.uploadErrors.headCheckUnfulfilledError});\n\t\t\t\t\t\tisOver = true;\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\n\t\t\t\t\t//if one is false, we're all false\n\t\t\t\t\tif(!res.value.exists)\n\t\t\t\t\t\tmissing.push(i);\n\n\t\t\t\t}\n\n\t\t\t\t//are we missing anything???\n\t\t\t\tif(missing.length)\n\t\t\t\t{\n\t\t\t\t\tdefer.resolve({success: false, error: self.uploadErrors.headCheckMissingError, missing: missing});\n\t\t\t\t\tisOver = true;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\t//we're all confirmed, we delete the upload requests now\n\t\t\t\t//however, this is not a major concern -- it will expire shortly anyways\n\t\t\t\t//therefore, we resolve first, then delete second\n\n\t\t\t\tisOver = true;\n\t\t\t\tdefer.resolve({success: true});\n\n\t\t\t\t//if we're here, then we all exist -- it's confirmed yay!\n\t\t\t\t//we need to remove the key from our redis client -- but we're not too concerned -- they expire when they expire\n\t\t\t\treturn;//asyncRedisDelete(uuid);\n\t\t\t})\n\t\t\t.catch(function(err)\n\t\t\t{\n\t\t\t\tif(isOver)\n\t\t\t\t\treturn;\n\n\t\t\t\tdefer.reject(err);\n\t\t\t});\n\n\t\treturn defer.promise;\n\t}\n\n\tfunction asyncHeadRequest(params)\n\t{\n\t\tvar defer = Q.defer();\n\n\t\tself.s3.headObject(params, function (err, metadata) { \n\t\t\tif (err)\n\t\t\t{\n\t\t\t\t//error code is not found -- it doesn't exist!\n\t\t\t\tif(err.code === 'NotFound') { \n\t\t\t \t// Handle no object on cloud here \n\t\t\t\t\tdefer.resolve({exists: false});\n\t\t\t\t} \n\t\t\t\t//straight error -- reject\n\t\t\t\telse \n\t\t\t\t\tdefer.reject(err);\n\n\t\t\t}else { \n\t\t\t\tdefer.resolve({exists: true});\n\t\t\t}\n\t\t});\n\n\t\treturn defer.promise;\n\t}\n\n\n\tself.asyncInitializeUpload = function(uploadProperties)\n\t{\t\n\t\t//we promise to return\n\t\tvar defer = Q.defer();\n\n\t\t//create a unique ID for this upload\n\t\tvar uuid = cuid();\n\n\t\t//we send our upload properties onwards\n\t\tvar requestUploads = self.createUploadRequests(uploadProperties);\n\n\t\t//we now have a number of requests to make\n\t\t//lets process them and get some signed urls to put the objects there\n\t\tvar fullUploadRequests = [];\n\n\t\t//these will be everything we need to make a signed URL request\n\t\tfor(var i=0; i < requestUploads.length; i++)\n\t\t{\n\n\t\t\t//\n\t\t\tvar upReqName = requestUploads[i];\n\n\t\t\tvar signedURLReq = {\n\t\t\t\tBucket: bucketName, \n\t\t\t\tKey: upReqName.prepend + uuid + upReqName.append, \n\t\t\t\tExpires: uploadExpiration,\n\t\t\t\t// ACL: 'public-read'\n\t\t\t};\n\n\t\t\tvar signed = self.s3.getSignedUrl('putObject', signedURLReq);\n\n\t\t\t//store the requests here\n\t\t\tfullUploadRequests.push({url: signed, request: signedURLReq});\n\t\t}\n\n\t\t//now we have our full requests\n\t\t//let's store it in REDIS, then send it back\n\n\t\tvar inProgress = {\n\t\t\tuuid: uuid,\n\t\t\tstate : \"pending\",\n\t\t\tuploads: fullUploadRequests\n\t\t};\n\n\t\t//we set the object in our redis location\n\t\tasyncRedisSetEx(uuid, uploadExpiration, JSON.stringify(inProgress))\n\t\t\t.catch(function(err)\n\t\t\t{\n\t\t\t\tdefer.reject(err);\n\t\t\t})\n\t\t\t.done(function()\n\t\t\t{\n\t\t\t\tdefer.resolve(inProgress);\n\t\t\t});\n\n\t\t//promise for now -- return later\n\t\treturn defer.promise;\n\t}\n\n\tfunction asyncRedisSetEx(key, expire, val)\n\t{\n\t\tvar defer = Q.defer();\n\n\t\tredisClient.setex(key, expire, val, function(err)\n\t\t{\n\t\t\tif(!err)\n\t\t\t\tdefer.resolve();\n\t\t\telse\n\t\t\t\tdefer.reject(err);\n\t\t});\n\n\t\treturn defer.promise;\n\t}\n\n\tfunction asyncRedisGet(key, val)\n\t{\n\t\tvar defer = Q.defer();\n\n\t\tredisClient.get(key, function(err, val)\n\t\t{\n\t\t\tif(!err)\n\t\t\t\tdefer.resolve(val);\n\t\t\telse\n\t\t\t\tdefer.reject(err);\n\t\t});\n\n\t\treturn defer.promise;\n\t}\n\n\tfunction asyncRedisDelete(key, val)\n\t{\n\t\tvar defer = Q.defer();\n\n\t\tredisClient.del(key, function(err, reply)\n\t\t{\n\t\t\tif(!err)\n\t\t\t\tdefer.resolve();\n\t\t\telse\n\t\t\t\tdefer.reject(err);\n\t\t});\n\n\t\treturn defer.promise;\n\t}\n\n\treturn self;\n}", "_cleanup() {\n this.readable = false;\n delete this._current;\n delete this._waiting;\n this._openQueue.die();\n\n this._queue.forEach((data) => {\n data.cleanup();\n });\n this._queue = [];\n }", "purgeCache() {\n this._bufferCache = {};\n }", "function clearStorageCache() {\n let counter = 0;\n let idArray = [];\n let now = new Date().getTime();\n let arrayOfKeys = GM_listValues();\n GM_setValue('LastCacheAccess', now);\n log(\"Clearing storage cache, 'timenow' = \" + now + ' Cache lifespan: ' + cacheMaxSecs/1000 + ' secs.');\n for (let i = 0; i < arrayOfKeys.length; i++) {\n let obj = GM_getValue(arrayOfKeys[i]);\n if ((now - obj.access) > cacheMaxSecs) {idArray.push(arrayOfKeys[i]);}\n }\n for (let i = 0; i < idArray.length; i++) {\n counter++;\n log('Cache entry for ID ' + idArray[i] + ' expired, deleting.');\n GM_deleteValue(idArray[i]);\n }\n log('Finished clearing cache, removed ' + counter + ' object.');\n }", "teardown(obj, keyName, meta$$1) {\n if (!this._volatile) {\n let cache = peekCacheFor(obj);\n\n if (cache !== undefined && cache.delete(keyName)) {\n removeDependentKeys(this, obj, keyName, meta$$1);\n }\n }\n\n super.teardown(obj, keyName, meta$$1);\n }", "function OnDelete(meta) {\n log('deleting document', meta.id);\n delete dst_bucket[meta.id]; // DELETE operation\n}", "deleteBucket() {\n\n\t\tlet auth_token = sessionStorage.auth_token // Get the auth_token from the session storage.\n\n\t\taxios({\n\t\t\tmethod: \"DELETE\",\n\t\t\turl: BaseUrl + \"bucketlists/\" + this.state.bucket_id,\n\t\t\theaders: { \"Authorization\": auth_token }\n\t\t}).then(function (response) {\n\t\t\tvar data = response.data\n\t\t\tif (data.success) {\n\t\t\t\tlet buckets = this.state.buckets\n\t\t\t\t_.remove(buckets, {\n\t\t\t\t\t\"id\": this.state.bucket_id\n\t\t\t\t})\n\n\t\t\t\tthis.setState({\n\t\t\t\t\tbuckets: buckets,\n\t\t\t\t\tvisible: true,\n\t\t\t\t\tmessage: this.state.bucket_name + \" has been deleted successfully\",\n\t\t\t\t\talert_type: \"success\"\n\t\t\t\t})\n\t\t\t}\n\t\t}.bind(this))\n\t}", "function purge(object) {\n\tif (object == null) {\n\t\treturn;\n\t}\n\tfor (var prop in object) {\n\t\ttry {\n\t\t\tdelete object[prop];\n\t\t} catch (e) {\n\t\t\talert(debug(e));\n\t\t}\n\t}\n\tdelete object;\n}", "function deleteObject(oci, bucket, object) {\n return oci.request(bucket + object, {\n method: 'DELETE'\n }).then(() => console.log(`DELETE Success: ${object}`));\n}", "function clearCache(url) {\n var apiUrl = \"https://api.cloudflare.com/client/v4/zones/\" + cloudflare.ZoneIdentifier + \"/purge_cache\";\n var data = {\n \"files\": [url]\n };\n\n debug('Clearing CloudFlare cache');\n\n request\n .del(apiUrl)\n .set('X-Auth-Key', cloudflare.APIKey)\n .set('X-Auth-Email', cloudflare.Email)\n .send(data)\n .end(function(err, rsp) {\n if(err) {\n return console.error(err);\n }\n\n if(rsp.body.success) {\n debug('CloudFlare Cache Cleared');\n } else {\n console.error(rsp);\n }\n })\n\n\n\n}", "function main(bucketName = 'my-bucket') {\n // [START storage_bucket_delete_default_kms_key]\n /**\n * TODO(developer): Uncomment the following lines before running the sample.\n */\n // The ID of your GCS bucket\n // const bucketName = 'your-unique-bucket-name';\n\n // Imports the Google Cloud client library\n const {Storage} = require('@google-cloud/storage');\n\n // Creates a client\n const storage = new Storage();\n\n async function removeDefaultKMSKey() {\n await storage.bucket(bucketName).setMetadata({\n encryption: {\n defaultKmsKeyName: null,\n },\n });\n\n console.log(`Default KMS key was removed from ${bucketName}`);\n }\n\n removeDefaultKMSKey().catch(console.error);\n // [END storage_bucket_delete_default_kms_key]\n}", "_purgeQueue(queue) {\n _.each(queue.tasks, task => delete this._taskIndex[task.id]);\n queue.tasks = [];\n queue.tasksActive = 0;\n }", "purgeQueues(callback) {\n const promise = this._queues.purgeQueues();\n if (callback)\n promise.then(callback, callback);\n else\n return promise;\n }", "function deleteActiveUpload() {\n\t\t \t\tif(scope.activeImage) {\n\t\t \t\t\tuploadService.deleteUpload(scope.activeImage.blobKey);\n\t\t \t\t\tscope.activeImage = null;\t\n\t\t \t\t}\t\t \n\t\t \t}", "async function deleteUrlImages(urls) {\n // console.log(\"deleteUrlImages: \", urls);\n // for (const index in urls) {\n // const url = urls[index];\n // const bucket = storage.bucket(bucketName);\n // const fullname = url.split(\"/\").pop();\n // const filename = fullname.substr(0, fullname.lastIndexOf(\".\"));\n // await deleteFile(filename);\n // }\n // return true;\n}", "function del_Face(){\n\t\t\t\t// The name of the bucket to access, e.g. \"my-bucket\"\n\t\t\t\tvar bucketName = 'smartmirrortest'\n\n\t\t\t\t// The name of the file to delete, e.g. \"file.txt\"\n\t\t\t\t const filename = formatted+'face.jpg';\n\n\t\t\t\t// Instantiates a client\n\t\t\t\n\n\t\t\t\t// Deletes the file from the bucket\n\t\t\t\tgcs\n\t\t\t\t .bucket(bucketName)\n\t\t\t\t .file(filename)\n\t\t\t\t .delete()\n\t\t\t\t .then(() => {\n\t\t\t\t\tconsole.log(`gs://${bucketName}/${filename} deleted.`);\n\t\t\t\t })\n\t\t\t\t .catch((err) => {\n\t\t\t\t\tconsole.error('ERROR:', err);\n\t\t\t\t });\n\t\t\t}", "cleanup() {}", "cleanup() {}", "syncDirectory() {\n const s3Bucket = this.serverless.variables.service.custom.s3Bucket;\n const args = [\n 's3',\n 'sync',\n 'app/',\n `s3://${s3Bucket}/`,\n '--delete',\n ];\n const { sterr } = this.runAwsCommand(args);\n if (!sterr) {\n this.serverless.cli.log('Successfully synced to the S3 bucket');\n } else {\n throw new Error('Failed syncing to the S3 bucket');\n }\n }", "function deleteAll(resource) {\n return new Promise(async function (resolve, reject) {\n\n if (config.uploads.provider !== 'atlas') {\n return reject({\n error: `Unsupported upload provider: ${config.uploads.provider}`\n });\n }\n\n log.warn({resource}, 'Deleting all files');\n fs.readdir(path.join(config.uploads.folder, resource), async function (err, items) {\n if (err) {\n reject(err);\n }\n await * items.map(fileName => fs.unlink(path.join(path.join(config.uploads.folder, resource), fileName)));\n resolve();\n });\n });\n}", "onClearStorage_(e) {\n if (this.hasUsage_(this.storedData_, this.numCookies_)) {\n this.websiteUsageProxy_.clearUsage(this.toUrl(this.origin_).href);\n this.storedData_ = '';\n this.numCookies_ = '';\n }\n\n this.onCloseDialog_(e);\n }", "function verifyFileInS3(req, res) {\n function headReceived(err, data) {\n if (err) {\n res.status(500);\n console.log(err);\n res.end(JSON.stringify({error: \"Problem querying S3!\"}));\n }\n else if (expectedMaxSize != null && data.ContentLength > expectedMaxSize) {\n res.status(400);\n res.write(JSON.stringify({error: \"Too big!\"}));\n deleteFile(req.body.bucket, req.body.key, function(err) {\n if (err) {\n console.log(\"Couldn't delete invalid file!\");\n }\n\n res.end();\n });\n }\n else {\n res.end();\n }\n }\n\n callS3(\"head\", {\n bucket: req.body.bucket,\n key: req.body.key\n }, headReceived);\n}", "del(transaction, bucket, keys) {\n contract(arguments).params(\"object\", \"string\", \"string|array\").end();\n\n keys = Array.isArray(keys) ? keys : [keys];\n\n keys = keys.map((key) => this.bucketKey(bucket, key));\n\n transaction.del(keys);\n }", "wipeCache() {\n\t\tthis.cached = null;\n\t}", "function clear () {\n entries(_storeNames)\n .forEach(([, store]) => {\n if (!store.permanent) {\n _removeItem(`${_storageName}.${store.name}`)\n }\n })\n}", "deleteImage() {\n const { image } = this.props.route.params;\n var imgRef = firebase.storage().refFromURL(image.downloadURL);\n imgRef.delete().then(() => {\n this.deleteRefFromFirestore();\n this.props.navigation.goBack(\"My Images\");\n }).catch(() => {\n Alert.alert(\"Could Not Delete\", \"There was an error deleting this image. Please Try again.\");\n });\n }", "async clean() {\n try {\n await util_1.default.promisify(fs_1.default.unlink)(this.file);\n }\n catch (e) {\n // noop\n }\n }", "delete() {\n\n }", "function revokeObjectURLs() {\n for (var i = 0; i < blobURLs.length; i++) {\n URL.revokeObjectURL(blobURLs[i]);\n }\n blobURLs.splice(0, blobURLs.length);\n}", "function clean(done) {\n del.sync(destination);\n done();\n}", "deleteOne(storename, key) {\n this.cache.then((db) => {\n db.transaction(storename, \"readwrite\").objectStore(storename).delete(key);\n });\n }", "clear() {\n return new Promise((resolve, reject) => {\n try {\n localStorage.removeItem(this.name);\n this.datastore = null;\n resolve(true);\n } catch (err) {\n reject(err);\n }\n });\n }" ]
[ "0.6377153", "0.62866443", "0.62267315", "0.6086894", "0.60853064", "0.5967813", "0.587745", "0.5859899", "0.5733911", "0.5720513", "0.57098585", "0.5678051", "0.5659861", "0.5623436", "0.5611293", "0.55387133", "0.55332714", "0.553273", "0.5497136", "0.5485037", "0.54763067", "0.54728484", "0.5466421", "0.5464317", "0.5450421", "0.5449188", "0.543729", "0.54312384", "0.5383746", "0.5354349", "0.53484535", "0.5342117", "0.53406906", "0.53205603", "0.5317072", "0.5315693", "0.52928346", "0.52826875", "0.5258533", "0.52418023", "0.5236822", "0.52223676", "0.5222203", "0.5202579", "0.519405", "0.51933557", "0.517535", "0.5172201", "0.5157573", "0.51479095", "0.51381713", "0.5120415", "0.5106852", "0.50977397", "0.50680214", "0.5049176", "0.50440043", "0.50351137", "0.50164044", "0.50133246", "0.4994966", "0.49948764", "0.49927288", "0.49839857", "0.4973937", "0.49658856", "0.49649855", "0.49609303", "0.4952594", "0.49355486", "0.49142352", "0.49027374", "0.48964122", "0.48920768", "0.4891072", "0.48704034", "0.48661652", "0.4865343", "0.48644486", "0.48605138", "0.48593405", "0.48570803", "0.48567083", "0.48539138", "0.4850296", "0.4850296", "0.4845335", "0.4845197", "0.48412922", "0.48368552", "0.48337448", "0.48288995", "0.4824336", "0.4813209", "0.48050845", "0.48033616", "0.4800916", "0.4797803", "0.4794997", "0.47931442" ]
0.7124481
0
Retreive the expiration time of object in S3 This is stored in the format: expirydate="Fri, 15 Jan 2016 00:00:00 GMT", ruleid="eucentral11day"
async expirationDate(response) { let header = response.headers['x-amz-expiration']; if (!header) { throw new Error(JSON.stringify(response.headers, null, 2)); } // This header is sent in such a silly format. Using cookie format or // sending the value without packing it in with a second value (rule-id) // would be way nicer. // The requirements for this to stop being valid are so obscure that I // would wager that the whole format of the header changes and this entire // function would need to be rewritten as oppsed to the string replacement // You'd need to have inside the expiry-date value or key an escaped quote // that's followed by a comma... header = cookie.parse(header.replace('",', '";')); return new Date(header['expiry-date']); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "getExpiresIn() {}", "function parse_expiration(expiration) {\n const output_expiration = {};\n if (expiration.Days && expiration.Days.length === 1) {\n output_expiration.days = parseInt(expiration.Days[0], 10);\n if (output_expiration.days < 1) {\n dbg.error('Minimum value for expiration days is 1, actual', expiration.Days,\n 'converted', output_expiration.days);\n throw new S3Error(S3Error.InvalidArgument);\n }\n } else if (expiration.Date && expiration.Date.length === 1) {\n output_expiration.date = (new Date(expiration.Date[0])).getTime();\n } else if (expiration.ExpiredObjectDeleteMarker &&\n expiration.ExpiredObjectDeleteMarker.length === 1 &&\n expiration.ExpiredObjectDeleteMarker[0] === 'true') {\n dbg.error('ExpiredObjectDeleteMarker is not implemented, expiration:', expiration);\n throw new S3Error(S3Error.NotImplemented);\n }\n return output_expiration;\n}", "get expiry() {\n this._logger.trace(\"[getter] expiry\");\n\n return this._expiry;\n }", "function getExpirationInSeconds () {\n const nowInSeconds = Math.floor(Date.now() / 1000)\n\n return {\n iat: nowInSeconds,\n exp: nowInSeconds + 30\n }\n}", "function calculateExpire() {\n var expiresIn = Math.round((((messageObject.expiresOn-new Date(Date.now())) % 86400000) % 3600000) / 60000); // minutes\n console.log(expiresIn);\n return expiresIn\n}", "get expirationDate() {\n if (typeof this.fields.expirationDate === 'string')\n return new Date(this.fields.expirationDate);\n return this.fields.expirationDate;\n }", "getExpiration() {\n const expiration = localStorage.getItem(\"expires_at\");\n const expiresAt = JSON.parse(expiration);\n return moment(expiresAt);\n }", "function calculateExpiryDate() {\n var now = new Date().getTime();\n var distance = expiryTimestamp - now;\n var days = Math.floor(distance / (1000 * 60 * 60 * 24));\n var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));\n var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));\n var seconds = Math.floor((distance % (1000 * 60)) / 1000);\n if(seconds < 0) {\n resetTimer();\n isValidOnExpire(onExpire) && onExpire();\n } else {\n setSeconds(seconds);\n setMinutes(minutes);\n setHours(hours);\n setDays(days);\n }\n }", "calculateExpirationDate(expiresIn) {\n return new Date(Date.now() + (expiresIn * 1000));\n }", "expiryTime(now) {\n if (this.maxAge != null) {\n const relativeTo = now || this.creation || new Date();\n const age = this.maxAge <= 0 ? -Infinity : this.maxAge * 1000;\n return relativeTo.getTime() + age;\n }\n\n if (this.expires == Infinity) {\n return Infinity;\n }\n return this.expires.getTime();\n }", "expiryTime(now) {\n if (this.maxAge != null) {\n const relativeTo = now || this.creation || new Date();\n const age = this.maxAge <= 0 ? -Infinity : this.maxAge * 1000;\n return relativeTo.getTime() + age;\n }\n\n if (this.expires == Infinity) {\n return Infinity;\n }\n return this.expires.getTime();\n }", "function parseExpiresOn(body) {\n if (typeof body.expires_on === \"number\") {\n return body.expires_on * 1000;\n }\n if (typeof body.expires_on === \"string\") {\n const asNumber = +body.expires_on;\n if (!isNaN(asNumber)) {\n return asNumber * 1000;\n }\n const asDate = Date.parse(body.expires_on);\n if (!isNaN(asDate)) {\n return asDate;\n }\n }\n if (typeof body.expires_in === \"number\") {\n return Date.now() + body.expires_in * 1000;\n }\n throw new Error(`Failed to parse token expiration from body. expires_in=\"${body.expires_in}\", expires_on=\"${body.expires_on}\"`);\n}", "async function getExpirationDate() {\n var error, result = await db.readDataPromise('settings', { User: \"Admin\" });\n return result[0].days\n}", "getExpiration() {\n if (localStorage.getItem('expiration') !== null) {\n return JSON.parse(localStorage.getItem('expiration'))\n } else {\n return null\n }\n }", "function calculateExpiry(date) {\n let currentDate = new Date();\n let dateparts = date.split('-');\n let deadline = new Date(dateparts[0], dateparts[1] - 1, dateparts[2]);\n return Math.ceil((deadline - currentDate) / (1000 * 3600 * 24))\n}", "cookieExpireDate(){\n const d = new Date();\n d.setTime(d.getTime() + (365*24*60*60*1000));\n const expires = \"expires=\" + d.toUTCString();\n return expires;\n }", "function computeExpires(str) {\n var expires = new Date();\n var lastCh = str.charAt(str.length - 1);\n var value = parseInt(str, 10);\n switch (lastCh) {\n case 'Y': expires.setFullYear(expires.getFullYear() + value); break;\n case 'M': expires.setMonth(expires.getMonth() + value); break;\n case 'D': expires.setDate(expires.getDate() + value); break;\n case 'h': expires.setHours(expires.getHours() + value); break;\n case 'm': expires.setMinutes(expires.getMinutes() + value); break;\n case 's': expires.setSeconds(expires.getSeconds() + value); break;\n default: expires = new Date(str);\n }\n return expires;\n }", "presignedGetObject(bucketName, objectName, expires) {\n if (!validateBucketName(bucketName)) {\n throw new errors.InvalidateBucketNameException('Invalid bucket name: ' + bucketName)\n }\n if (objectName === null || objectName.trim() === '') {\n throw new errors.InvalidObjectNameException('Object name cannot be empty')\n }\n var requestParams = {\n host: this.params.host,\n port: this.params.port,\n protocol: this.params.protocol,\n path: `/${bucketName}/${uriResourceEscape(objectName)}`,\n method: 'GET',\n expires: expires\n }\n return presignSignatureV4(requestParams, this.params.accessKey, this.params.secretKey)\n }", "function computeExpires(str) {\n var expires = new Date();\n var lastCh = str.charAt(str.length - 1);\n var value = parseInt(str, 10);\n\n switch (lastCh) {\n case 'Y': expires.setFullYear(expires.getFullYear() + value); break;\n case 'M': expires.setMonth(expires.getMonth() + value); break;\n case 'D': expires.setDate(expires.getDate() + value); break;\n case 'h': expires.setHours(expires.getHours() + value); break;\n case 'm': expires.setMinutes(expires.getMinutes() + value); break;\n case 's': expires.setSeconds(expires.getSeconds() + value); break;\n default: expires = new Date(str);\n }\n\n return expires;\n }", "function computeExpires(str) {\n var expires = new Date();\n var lastCh = str.charAt(str.length - 1);\n var value = parseInt(str, 10);\n\n switch (lastCh) {\n case 'Y': expires.setFullYear(expires.getFullYear() + value); break;\n case 'M': expires.setMonth(expires.getMonth() + value); break;\n case 'D': expires.setDate(expires.getDate() + value); break;\n case 'h': expires.setHours(expires.getHours() + value); break;\n case 'm': expires.setMinutes(expires.getMinutes() + value); break;\n case 's': expires.setSeconds(expires.getSeconds() + value); break;\n default: expires = new Date(str);\n }\n\n return expires;\n}", "TTL(now) {\n /* RFC6265 S4.1.2.2 If a cookie has both the Max-Age and the Expires\n * attribute, the Max-Age attribute has precedence and controls the\n * expiration date of the cookie.\n * (Concurs with S5.3 step 3)\n */\n if (this.maxAge != null) {\n return this.maxAge <= 0 ? 0 : this.maxAge * 1000;\n }\n\n let expires = this.expires;\n if (expires != Infinity) {\n if (!(expires instanceof Date)) {\n expires = parseDate(expires) || Infinity;\n }\n\n if (expires == Infinity) {\n return Infinity;\n }\n\n return expires.getTime() - (now || Date.now());\n }\n\n return Infinity;\n }", "TTL(now) {\n /* RFC6265 S4.1.2.2 If a cookie has both the Max-Age and the Expires\n * attribute, the Max-Age attribute has precedence and controls the\n * expiration date of the cookie.\n * (Concurs with S5.3 step 3)\n */\n if (this.maxAge != null) {\n return this.maxAge <= 0 ? 0 : this.maxAge * 1000;\n }\n\n let expires = this.expires;\n if (expires != Infinity) {\n if (!(expires instanceof Date)) {\n expires = parseDate(expires) || Infinity;\n }\n\n if (expires == Infinity) {\n return Infinity;\n }\n\n return expires.getTime() - (now || Date.now());\n }\n\n return Infinity;\n }", "function msToExpirationTime(ms){// Always subtract from the offset so that we don't clash with the magic number for NoWork.\nreturn MAGIC_NUMBER_OFFSET-(ms/UNIT_SIZE|0);}", "function msToExpirationTime(ms){// Always subtract from the offset so that we don't clash with the magic number for NoWork.\nreturn MAGIC_NUMBER_OFFSET-(ms/UNIT_SIZE|0);}", "function msToExpirationTime(ms){// Always subtract from the offset so that we don't clash with the magic number for NoWork.\nreturn MAGIC_NUMBER_OFFSET-(ms/UNIT_SIZE|0);}", "getTimeToExpiration(token) {\n if (token && token !== 'undefined') {\n const expDate = getJWTExpDate(token) // token expiration date\n return moment.utc(moment(expDate).diff(moment())).valueOf() // remaining token time\n }\n\n return 0\n }", "function msToExpirationTime(ms){// Always add an offset so that we don't clash with the magic number for NoWork.\nreturn MAGIC_NUMBER_OFFSET-(ms/UNIT_SIZE|0);}", "function msToExpirationTime(ms){// Always add an offset so that we don't clash with the magic number for NoWork.\nreturn MAGIC_NUMBER_OFFSET-(ms/UNIT_SIZE|0);}", "function msToExpirationTime(ms){// Always add an offset so that we don't clash with the magic number for NoWork.\nreturn MAGIC_NUMBER_OFFSET-(ms/UNIT_SIZE|0);}", "function getAccessTokenExpiration(tokenResponse, env) {\n const now = Math.floor(Date.now() / 1000); // Option 1 - using the expires_in property of the token response\n\n if (tokenResponse.expires_in) {\n return now + tokenResponse.expires_in;\n } // Option 2 - using the exp property of JWT tokens (must not assume JWT!)\n\n\n if (tokenResponse.access_token) {\n let tokenBody = jwtDecode(tokenResponse.access_token, env);\n\n if (tokenBody && tokenBody.exp) {\n return tokenBody.exp;\n }\n } // Option 3 - if none of the above worked set this to 5 minutes after now\n\n\n return now + 300;\n}", "function msToExpirationTime(ms){// Always add an offset so that we don't clash with the magic number for NoWork.\nreturn(ms/UNIT_SIZE|0)+MAGIC_NUMBER_OFFSET;}", "function msToExpirationTime(ms){// Always add an offset so that we don't clash with the magic number for NoWork.\nreturn(ms/UNIT_SIZE|0)+MAGIC_NUMBER_OFFSET;}", "function msToExpirationTime(ms){// Always add an offset so that we don't clash with the magic number for NoWork.\nreturn(ms/UNIT_SIZE|0)+MAGIC_NUMBER_OFFSET;}", "function msToExpirationTime(ms){// Always add an offset so that we don't clash with the magic number for NoWork.\nreturn(ms/UNIT_SIZE|0)+MAGIC_NUMBER_OFFSET;}", "get expires () {\n return parseInt(localStorage.getItem(this.keys.expires))\n }", "checkTTL() {\n\t\tlet now = Date.now();\n\t\tthis.cache.forEach((value, key) => {\n\t\t\tlet item = this.cache.get(key);\n\n\t\t\tif (item.expire && item.expire < now) {\n\t\t\t\tthis.logger.debug(`EXPIRED ${key}`);\n\t\t\t\tthis.metrics.increment(METRIC.MOLECULER_CACHER_EXPIRED_TOTAL);\n\t\t\t\tthis.cache.delete(key);\n\t\t\t}\n\t\t});\n\t}", "function _tokenExpiresIn(token) {\r\n const parsedToken = _parseToken(token);\r\n _assert(parsedToken, \"internal-error\" /* INTERNAL_ERROR */);\r\n _assert(typeof parsedToken.exp !== 'undefined', \"internal-error\" /* INTERNAL_ERROR */);\r\n _assert(typeof parsedToken.iat !== 'undefined', \"internal-error\" /* INTERNAL_ERROR */);\r\n return Number(parsedToken.exp) - Number(parsedToken.iat);\r\n}", "function _tokenExpiresIn(token) {\r\n const parsedToken = _parseToken(token);\r\n _assert(parsedToken, \"internal-error\" /* INTERNAL_ERROR */);\r\n _assert(typeof parsedToken.exp !== 'undefined', \"internal-error\" /* INTERNAL_ERROR */);\r\n _assert(typeof parsedToken.iat !== 'undefined', \"internal-error\" /* INTERNAL_ERROR */);\r\n return Number(parsedToken.exp) - Number(parsedToken.iat);\r\n}", "function getEventInfo(eventId) {\n var params = {\n Bucket: 'training-schedule',\n Key: 'ready/current-schedule.csv',\n Expression: 'select * from s3object s where \"Event ID\" = \\'' + eventId + '\\'',\n ExpressionType: \"SQL\", \n InputSerialization: { CSV: {} },\n OutputSerialization: { JSON: {} }\n };\n s3.selectObjectContent(params, function(err, data) {\n if (err) console.log(err, err.stack); // an error occurred\n else {\n console.log(data); // successful response\n var eventStream = data.Payload;\n\n eventStream.on('data', function(event) {\n // Check the top-level field to determine which event this is.\n if (event.Records) {\n // handle Records event\n console.log('this is the payload: ' + event.Records.Payload);\n }\n });\n \n } \n });\n}", "function getExpiresFromHeaders(headers) {\n // Try to use the Cache-Control header (and max-age)\n if (headers.get('cache-control')) {\n const maxAge = headers.get('cache-control').match(/max-age=(\\d+)/);\n return parseInt(maxAge ? maxAge[1] : 0, 10);\n }\n\n // Otherwise try to get expiration duration from the Expires header\n if (headers.get('expires')) {\n return (\n parseInt(\n (new Date(headers.get('expires'))).getTime() / 1000,\n 10,\n )\n - (new Date()).getTime()\n );\n }\n return null;\n}", "getAccessKeyAge(){\n return new Promise((resolve, reject)=>{\n if(this.haveCredentials) {\n getAccessKeyLastUsed(creds.accessKeyId)\n .then((data)=>{\n this.userName = data.UserName;\n return listAccessKeys(this.userName)\n }) \n .then((data)=>{\n var keyCount = data.AccessKeyMetadata.length;\n if(keyCount == 1){\n var keyCreateDate = new Date(data.AccessKeyMetadata[0].CreateDate);\n var keyAgeInDays = ((new Date((new Date()) - keyCreateDate)).getTime() / 86400000).toFixed(2)\n logit('The AWS IAM access Key for '+ this.userName +' created on ' + keyCreateDate.toDateString() + ', it is '+ keyAgeInDays + ' days old.');\n resolve(keyAgeInDays);\n } else {\n console.error('Error the AWS IAM account for ' + this.userName + ' is either missing or has more than one IAM access key.');\n reject('Error the AWS IAM account for ' + this.userName + ' is either missing or has more than one IAM access key.');\n };\n })\n .catch((err)=>{\n console.error('Error getting access key information ', err);\n reject('Getting access key information ' + err);\n });\n } else {\n console.error('AWS credentials missing. getAccessKeyInfo not allowed');\n reject('AWS credentials missing. getAccessKeyInfo not allowed');\n };\n });\n }", "static expiresOn( alert ) {\n var ex_date = new Date(alert.expiration_date);\n var options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric'};\n if (alert.expiration_date != null) {\n // Get that expiration date and display that expiration date\n return 'Expires On: ' + ex_date.toLocaleDateString(navigator.language, options);\n //else return no exipration date added\n }else{\n return 'No expiration date added '\n }\n}", "renderExpiresAt(now, at) {\n let when = moment(at);\n let diff = moment(when - now);\n return diff.format(\"D.hh:mm:ss\");\n }", "set_expire_seconds(sec) {\n if (this.tr_buffer) {\n throw new Error(\"already finalized\");\n }\n return (this.expiration = base_expiration_sec() + sec);\n }", "static getFile (bucketName, objectKey) {\n const s3 = Storage._getS3Instance();\n const params = {\n Bucket: bucketName,\n Key: objectKey\n };\n return new Promise((resolve, reject) => {\n s3.getObject(params, (err, data) => {\n if (err) {\n reject(err);\n } else {\n resolve({\n content: data.Body, // buffer\n type: data.ContentType, // string\n encoding: data.ContentEncoding, // string\n size: data.ContentLength // integer\n });\n }\n });\n });\n }", "function getObjFromS3(fileName, bucket, callback){\n let params = {Bucket: bucket, Key:fileName};\n s3.getObject(params, function(err, data){\n if(err){\n console.error(\"getObjFromS3 err\",err);\n } else {\n callback(data.Body.toString('utf-8'));\n }\n \n });\n\n}", "function msToExpirationTime(ms) {\n // Always subtract from the offset so that we don't clash with the magic number for NoWork.\n return MAGIC_NUMBER_OFFSET - ((ms / UNIT_SIZE) | 0);\n }", "set_expire_seconds(sec) {\n\t if (this.tr_buffer) {\n\t throw new Error(\"already finalized\");\n\t }\n\t return (this.expiration = base_expiration_sec() + sec);\n\t }", "getTokenExpDate() {\n if (this.accessTokenPayload && this.accessTokenPayload.hasOwnProperty('exp')) {\n const date = new Date(0);\n date.setUTCSeconds(this.accessTokenPayload.exp);\n return date;\n }\n else {\n return super.getTokenExpDate();\n }\n }", "_setCacheExpiry() {\n const oThis = this;\n oThis.cacheExpiry = cacheManagementConstants.largeExpiryTimeInterval; // 24 hours ;\n }", "_setCacheExpiry() {\n const oThis = this;\n oThis.cacheExpiry = cacheManagementConstants.largeExpiryTimeInterval; // 24 hours ;\n }", "async get(){\n try {\n let objectResult = await s3.getObject({\n Bucket: this.bucket,\n Key: this.key\n }).promise();\n \n let creds = JSON.parse(objectResult.Body);\n return creds;\n } catch(ex){\n if(ex.code === 'NoSuchKey'){\n return null;\n }\n console.error(ex);\n throw ex;\n }\n }", "function getClaimTime () {\r\n var claimTime = new Date();\r\n claimTime.setTime(parseInt(localStorage.getItem(\"lastClaim\")));\r\n return claimTime; \r\n}", "get etag() {\n return `${Math.trunc(this.fileInfo.mtimeMs).toString()}-${this.serialNumber || 0}`;\n }", "function msToExpirationTime(ms){// Always add an offset so that we don't clash with the magic number for NoWork.\n\treturn(ms/UNIT_SIZE|0)+MAGIC_NUMBER_OFFSET;}", "function checkExpire(todo){\n let dateNum\n if(todo.expire!=null){\n dateNum = Math.floor ( (new Date(todo.expire)-new Date()) / ( 24 * 3600 * 1000 ))+1\n }\n if(todo.expire==null || dateNum>=0){\n // console.log('no expire');\n return todo;\n }\n \n }", "function _createExpiryKey(key) {\n\t\treturn key + \"_time\";\n\t}", "async getFile(params) {\n try {\n console.log(\"s3.getObject Params: \", params);\n var s3 = new this.AWS.S3();\n let file = await s3.getObject(params).promise();\n return (file);\n } catch (error) {\n console.error('S3.getObject error: ', error);\n return (error);\n }\n }", "function setTrollExpiration(){ // Expire after one week. May need tuning.\r\n\t\tvar date = new Date();\r\n\t\tdate.setTime(date.getTime()+(7*24*60*60*1000));\r\n\t \treturn \"; expires=\"+date.toGMTString() + \";\";\r\n}", "function whenUsingItemToLastModifiedSec() {\n expect(jumpflowy.itemToLastModifiedSec).to.be.a(\"function\");\n\n const currentTime = jumpflowy.getCurrentTimeSec();\n\n function testWorkFlowyAssumptions(item) {\n if (item.getId() === WF.rootItem().getId()) {\n expect(item.getLastModifiedDate()).to.be(null);\n } else {\n expect(item.getLastModifiedDate()).to.be.a(Date);\n }\n }\n testWorkFlowyAssumptions(WF.rootItem());\n testWorkFlowyAssumptions(WF.rootItem().getChildren()[0]);\n\n function testItem(uuid) {\n const item = getUniqueItemByNoteOrFail(uuid);\n // The expected timestamp is the name of its first child item\n const expectedTimestampStr = item.getChildren()[0].getName();\n const expectedTimestamp = Number(expectedTimestampStr);\n const actualTimestamp = jumpflowy.itemToLastModifiedSec(item);\n expect(actualTimestamp).to.be(expectedTimestamp);\n expect(actualTimestamp).to.be.lessThan(currentTime + 1);\n }\n testItem(\"7685e7f0-122e-69ff-be9f-e03bcf7d84ca\"); // Internal\n testItem(\"9c6ede17-831d-b04c-7a97-a825f0fd4bf0\"); // Embedded\n\n function testRootItemJoinedDate() {\n const root = WF.rootItem();\n\n const child = root.getChildren()[0];\n const childLastMod = jumpflowy.itemToLastModifiedSec(child);\n expect(childLastMod).to.be.below(currentTime + 1);\n }\n testRootItemJoinedDate();\n }", "function msToExpirationTime(ms) {\n // Always subtract from the offset so that we don't clash with the magic number for NoWork.\n return MAGIC_NUMBER_OFFSET - (ms / UNIT_SIZE | 0);\n }", "function msToExpirationTime(ms) {\n // Always subtract from the offset so that we don't clash with the magic number for NoWork.\n return MAGIC_NUMBER_OFFSET - (ms / UNIT_SIZE | 0);\n }", "function msToExpirationTime(ms) {\n // Always subtract from the offset so that we don't clash with the magic number for NoWork.\n return MAGIC_NUMBER_OFFSET - (ms / UNIT_SIZE | 0);\n }", "function msToExpirationTime(ms) {\n // Always subtract from the offset so that we don't clash with the magic number for NoWork.\n return MAGIC_NUMBER_OFFSET - (ms / UNIT_SIZE | 0);\n }", "function msToExpirationTime(ms) {\n // Always subtract from the offset so that we don't clash with the magic number for NoWork.\n return MAGIC_NUMBER_OFFSET - (ms / UNIT_SIZE | 0);\n }", "function msToExpirationTime(ms) {\n // Always subtract from the offset so that we don't clash with the magic number for NoWork.\n return MAGIC_NUMBER_OFFSET - (ms / UNIT_SIZE | 0);\n }", "function checkVisaExpiry(){\r\n\r\n}", "updateExpiration() {\n if (defined(this.expireDate) && this.contentReady && !this.hasEmptyContent) {\n const now = Date.now(scratchDate);\n if (Date.lessThan(this.expireDate, now)) {\n this._contentState = TILE3D_CONTENT_STATE.EXPIRED;\n this._expiredContent = this._content;\n }\n }\n }", "_setCacheExpiry() {\n const oThis = this;\n oThis.cacheExpiry = 1 * 24 * 60 * 60; // 1 days;\n }", "function msToExpirationTime(ms) {\n // Always add an offset so that we don't clash with the magic number for NoWork.\n return MAGIC_NUMBER_OFFSET - (ms / UNIT_SIZE | 0);\n }", "function msToExpirationTime(ms) {\n // Always add an offset so that we don't clash with the magic number for NoWork.\n return MAGIC_NUMBER_OFFSET - (ms / UNIT_SIZE | 0);\n }", "function msToExpirationTime(ms) {\n // Always add an offset so that we don't clash with the magic number for NoWork.\n return MAGIC_NUMBER_OFFSET - (ms / UNIT_SIZE | 0);\n }", "function msToExpirationTime(ms) {\n // Always add an offset so that we don't clash with the magic number for NoWork.\n return MAGIC_NUMBER_OFFSET - (ms / UNIT_SIZE | 0);\n }", "function msToExpirationTime(ms) {\n // Always subtract from the offset so that we don't clash with the magic number for NoWork.\n return MAGIC_NUMBER_OFFSET - (ms / UNIT_SIZE | 0);\n}", "function msToExpirationTime(ms) {\n // Always subtract from the offset so that we don't clash with the magic number for NoWork.\n return MAGIC_NUMBER_OFFSET - (ms / UNIT_SIZE | 0);\n}", "function msToExpirationTime(ms) {\n // Always subtract from the offset so that we don't clash with the magic number for NoWork.\n return MAGIC_NUMBER_OFFSET - (ms / UNIT_SIZE | 0);\n}", "function msToExpirationTime(ms) {\n // Always subtract from the offset so that we don't clash with the magic number for NoWork.\n return MAGIC_NUMBER_OFFSET - (ms / UNIT_SIZE | 0);\n}", "function msToExpirationTime(ms) {\n // Always subtract from the offset so that we don't clash with the magic number for NoWork.\n return MAGIC_NUMBER_OFFSET - (ms / UNIT_SIZE | 0);\n}", "function msToExpirationTime(ms) {\n // Always subtract from the offset so that we don't clash with the magic number for NoWork.\n return MAGIC_NUMBER_OFFSET - (ms / UNIT_SIZE | 0);\n}", "function msToExpirationTime(ms) {\n // Always subtract from the offset so that we don't clash with the magic number for NoWork.\n return MAGIC_NUMBER_OFFSET - (ms / UNIT_SIZE | 0);\n}", "function msToExpirationTime(ms) {\n // Always subtract from the offset so that we don't clash with the magic number for NoWork.\n return MAGIC_NUMBER_OFFSET - (ms / UNIT_SIZE | 0);\n}", "function msToExpirationTime(ms) {\n // Always subtract from the offset so that we don't clash with the magic number for NoWork.\n return MAGIC_NUMBER_OFFSET - (ms / UNIT_SIZE | 0);\n}", "function msToExpirationTime(ms) {\n // Always subtract from the offset so that we don't clash with the magic number for NoWork.\n return MAGIC_NUMBER_OFFSET - (ms / UNIT_SIZE | 0);\n}", "function msToExpirationTime(ms) {\n // Always subtract from the offset so that we don't clash with the magic number for NoWork.\n return MAGIC_NUMBER_OFFSET - (ms / UNIT_SIZE | 0);\n}", "function msToExpirationTime(ms) {\n // Always subtract from the offset so that we don't clash with the magic number for NoWork.\n return MAGIC_NUMBER_OFFSET - (ms / UNIT_SIZE | 0);\n}", "function msToExpirationTime(ms) {\n // Always subtract from the offset so that we don't clash with the magic number for NoWork.\n return MAGIC_NUMBER_OFFSET - (ms / UNIT_SIZE | 0);\n}", "function msToExpirationTime(ms) {\n // Always subtract from the offset so that we don't clash with the magic number for NoWork.\n return MAGIC_NUMBER_OFFSET - (ms / UNIT_SIZE | 0);\n}", "function msToExpirationTime(ms) {\n // Always subtract from the offset so that we don't clash with the magic number for NoWork.\n return MAGIC_NUMBER_OFFSET - (ms / UNIT_SIZE | 0);\n}", "function msToExpirationTime(ms) {\n // Always subtract from the offset so that we don't clash with the magic number for NoWork.\n return MAGIC_NUMBER_OFFSET - (ms / UNIT_SIZE | 0);\n}", "function msToExpirationTime(ms) {\n // Always subtract from the offset so that we don't clash with the magic number for NoWork.\n return MAGIC_NUMBER_OFFSET - (ms / UNIT_SIZE | 0);\n}", "function msToExpirationTime(ms) {\n // Always subtract from the offset so that we don't clash with the magic number for NoWork.\n return MAGIC_NUMBER_OFFSET - (ms / UNIT_SIZE | 0);\n}", "function msToExpirationTime(ms) {\n // Always subtract from the offset so that we don't clash with the magic number for NoWork.\n return MAGIC_NUMBER_OFFSET - (ms / UNIT_SIZE | 0);\n}", "function msToExpirationTime(ms) {\n // Always subtract from the offset so that we don't clash with the magic number for NoWork.\n return MAGIC_NUMBER_OFFSET - (ms / UNIT_SIZE | 0);\n}", "function msToExpirationTime(ms) {\n // Always subtract from the offset so that we don't clash with the magic number for NoWork.\n return MAGIC_NUMBER_OFFSET - (ms / UNIT_SIZE | 0);\n}", "function msToExpirationTime(ms) {\n // Always subtract from the offset so that we don't clash with the magic number for NoWork.\n return MAGIC_NUMBER_OFFSET - (ms / UNIT_SIZE | 0);\n}", "function msToExpirationTime(ms) {\n // Always subtract from the offset so that we don't clash with the magic number for NoWork.\n return MAGIC_NUMBER_OFFSET - (ms / UNIT_SIZE | 0);\n}", "function msToExpirationTime(ms) {\n\t // Always add an offset so that we don't clash with the magic number for NoWork.\n\t return (ms / UNIT_SIZE | 0) + MAGIC_NUMBER_OFFSET;\n\t}", "checkExpiration() {\n const interval = Number(this.options.refreshInterval);\n if (interval) {\n const time = getTime(-interval);\n this.invalidate(time);\n }\n }", "updateExpiration() {\n if (defined(this.expireDate) && this.contentReady && !this.hasEmptyContent) {\n const now = Date.now(scratchDate);\n if (Date.lessThan(this.expireDate, now)) {\n this._contentState = _constants__WEBPACK_IMPORTED_MODULE_5__[\"TILE3D_CONTENT_STATE\"].EXPIRED;\n this._expiredContent = this._content;\n }\n }\n }", "function getRemainingTime(endtime) {\n let t = Date.parse(endtime) - Date.parse(new Date()),//difference between the date when timer expires and the moment when the function is executed (ms)\n seconds = Math.floor((t/1000) % 60),\n minutes = Math.floor((t/1000/60) % 60),\n hours = Math.floor((t/(1000*60*60)));\n\n if (t < 0){ //making the timer look nice on the page in case the date has expired\n seconds = 0;\n minutes = 0;\n hours = 0;\n }\n\n return {\n 'total' : t,\n 'seconds' : seconds,\n 'minutes' : minutes,\n 'hours' : hours\n };\n }" ]
[ "0.6579945", "0.6299584", "0.6151921", "0.60957336", "0.60068625", "0.57834154", "0.57559884", "0.57160443", "0.5694977", "0.56815714", "0.56815714", "0.56752396", "0.5547356", "0.5544932", "0.5303032", "0.5300711", "0.52713865", "0.52538186", "0.52489215", "0.5246365", "0.5233854", "0.5233854", "0.52287406", "0.52287406", "0.52287406", "0.5182164", "0.51599807", "0.51599807", "0.51599807", "0.51465535", "0.5132945", "0.5132945", "0.5132945", "0.5132945", "0.51132935", "0.5102732", "0.5089355", "0.5089355", "0.5075446", "0.50398487", "0.50308114", "0.5021563", "0.4985514", "0.4972485", "0.49633083", "0.49622825", "0.49505386", "0.49496257", "0.49386615", "0.4926321", "0.4926321", "0.49247056", "0.4916859", "0.49154615", "0.49130517", "0.49090824", "0.48998907", "0.48914576", "0.48555067", "0.4845684", "0.48309502", "0.48309502", "0.48309502", "0.48309502", "0.48309502", "0.48309502", "0.4830737", "0.48241386", "0.4768512", "0.4753513", "0.4753513", "0.4753513", "0.4753513", "0.47518402", "0.47518402", "0.47518402", "0.47518402", "0.47518402", "0.47518402", "0.47518402", "0.47518402", "0.47518402", "0.47518402", "0.47518402", "0.47518402", "0.47518402", "0.47518402", "0.47518402", "0.47518402", "0.47518402", "0.47518402", "0.47518402", "0.47518402", "0.47518402", "0.47518402", "0.47518402", "0.4747021", "0.4745756", "0.47456232", "0.47375953" ]
0.6835666
0
Create an S3 URL for an object stored in this S3 storage provider
worldAddress(rawUrl) { assert(rawUrl); let s3Domain; if (this.region === 'us-east-1') { s3Domain = 's3.amazonaws.com'; } else { s3Domain = `s3-${this.region}.amazonaws.com`; } let host = this.bucket + '.' + s3Domain; return url.format({ protocol: 'https:', host: host, pathname: encodeURIComponent(rawUrl), }); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "* url (path) {\n return `https://${this.disk.bucket}.s3.amazonaws.com/${path}`\n }", "async function generateUrl(){\n let date = new Date();\n let id = parseInt(Math.random() * 10000000000);\n const imageName = `${id}${date.getTime()}.jpg`;\n\n const params = ({\n Bucket:buketName,\n Key:imageName,\n Expires:300,\n ContentType:'image/jpeg'\n })\n\n const uploadUrl = await s3.getSignedUrlPromise('putObject',params);\n return uploadUrl;\n}", "static _getS3Instance () {\n s3instance = s3instance || new AWS.S3({ apiVersion: S3_API_VERSION });\n return s3instance;\n }", "function s3UrlFromUri(uri, region) {\n const url = (0, url_1.parse)(uri);\n return `https://${url.hostname}.s3.${region ? `${region}.` : ''}amazonaws.com${url.path}`;\n}", "function S3Store(options) {\n options = options || {};\n\n this.options = extend({\n path: 'cache/',\n tryget: true,\n s3: {}\n }, options);\n\n\n // check storage directory for existence (or create it)\n if (!fs.existsSync(this.options.path)) {\n fs.mkdirSync(this.options.path);\n }\n\n this.name = 's3store';\n\n // internal array for informations about the cached files - resists in memory\n this.collection = {};\n\n // TODO: need implement!\n // fill the cache on startup with already existing files\n // if (!options.preventfill) {\n // this.intializefill(options.fillcallback);\n // }\n}", "function getS3PreSignedUrl(s3ObjectKey) {\n\n const bucketName = process.env.S3_PERSISTENCE_BUCKET;\n \n const s3PreSignedUrl = s3SigV4Client.getSignedUrl('getObject', {\n Bucket: bucketName,\n Key: s3ObjectKey,\n Expires: 60*1 // the Expires is capped for 1 minute\n });\n\n console.log(`Util.s3PreSignedUrl: ${s3ObjectKey} URL ${s3PreSignedUrl}`); // you can see those on CloudWatch\n\n return s3PreSignedUrl;\n}", "presignedPutObject(bucketName, objectName, expires, cb) {\n if (!isValidBucketName(bucketName)) {\n throw new errors.InvalidBucketNameError(`Invalid bucket name: ${bucketName}`)\n }\n if (!isValidObjectName(objectName)) {\n throw new errors.InvalidObjectNameError(`Invalid object name: ${objectName}`)\n }\n return this.presignedUrl('PUT', bucketName, objectName, expires, cb)\n }", "static putFile (bucketName, objectKey, objectBody) {\n const s3 = Storage._getS3Instance();\n const params = {\n Bucket: bucketName,\n Key: objectKey,\n Body: objectBody\n };\n return new Promise((resolve, reject) => {\n s3.upload(params, (err, data) => err ? reject(err) : resolve(data.Location));\n });\n }", "function getSignedUrl(filename, filetype, foldername, operation) {\n const folderName = foldername;\n const params = {\n Bucket: 'gsg-image-uploads',\n Key: `${folderName}/` + filename,\n Expires: 604800\n };\n if(operation==='putObject'){\n params['ContentType'] = filetype;\n }\n return new Promise((resolve, reject) => {\n s3.getSignedUrl(operation, params, function(err, data) {\n if (err) {\n console.log(\"Error\",err);\n reject(err)\n } else {\n resolve(data)\n }\n });\n });\n}", "function getS3(awsAccessKey, awsSecretKey) {\n return new AWS.S3({\n accessKeyId: awsAccessKey,\n secretAccessKey: awsSecretKey\n });\n}", "getImageFromURL(URL, fileName, bucket, callback) {\n var options = {\n uri: URL,\n encoding: null\n };\n request(options, function (error, response, body) {\n if (error || response.statusCode !== 200) {\n console.log(\"failed to get image\", URL);\n console.log(error);\n if(response.statusCode !== 200){\n console.log(\"200 status not received for URL:\", options.uri);\n }\n } else {\n s3.putObject({\n Body: body,\n Key: fileName,\n Bucket: bucket\n }, function (error, data) {\n if (error) {\n console.log(\"error downloading image to s3\", fileName);\n } else {\n // console.log(\"body:\", body);\n // console.log(\"success uploading to s3\", fileName);\n }\n });\n }\n });\n }", "function getPutSignedUrl(key) {\n const signedUrlExpireSeconds = 60 * 5;\n return exports.s3.getSignedUrl('putObject', {\n Bucket: config_1.config.aws_media_bucket,\n Key: key,\n Expires: signedUrlExpireSeconds,\n });\n}", "function createS3(regionName) {\n var config = { apiVersion: '2006-03-01' };\n \n if (regionName != null)\n config.region = regionName;\n\n var s3 = new AWS.S3(config);\n return s3;\n}", "function getObjectUrl({\n cosInstance,\n bucket: Bucket,\n region: Region,\n key: Key,\n origin = \"\",\n}) {\n const url = cosInstance.getObjectUrl({\n Bucket,\n Region,\n Key,\n Sign: false,\n });\n const { protocol, host } = new URL(url);\n return url.replace(`${protocol}//${host}`, origin);\n}", "function get_s3_resource(element, signature_view_url) {\n\tvar resource_url = element.src;\n\tvar xhr = new XMLHttpRequest();\n\txhr.open(\"GET\", signature_view_url+\"?resource_url=\"+resource_url);\n\txhr.onreadystatechange = function() {\n\t\tif(xhr.readyState === 4) {\n\t\t\tif(xhr.status === 200) {\n\t\t\t\tvar response = JSON.parse(xhr.responseText);\n\t\t\t\telement.src = response.signed_request;\n\t\t\t}\n\t\t\telse {\n\t\t\t\talert(\"Could not get signed URL.\");\n\t\t\t}\n\t\t}\n\t};\n\txhr.send();\n}", "function putObject(keyName) {\n const putObjectParams = {\n Bucket: bucket,\n Key: keyName,\n Metadata: {\n importance: 'very',\n ranking: 'middling',\n },\n Body: 'putMe',\n };\n s3Client.putObject(putObjectParams, (err, data) => {\n if (err) console.log('err:', err);\n else console.log('data:', data);\n });\n}", "get bucketUrl() {\n return this.urlForObject();\n }", "constructor(fileSystem, s3Object) {\n this.fileSystem = fileSystem;\n this.s3Object = s3Object;\n }", "urlForObject(key) {\n const components = [`https://s3.${this.node.stack.region}.${this.node.stack.urlSuffix}/${this.bucketName}`];\n if (key) {\n // trim prepending '/'\n if (typeof key === 'string' && key.startsWith('/')) {\n key = key.substr(1);\n }\n components.push('/');\n components.push(key);\n }\n return components.join('');\n }", "function parseS3Url(url) {\n const [bucket, ...keyFragments] = url.replace(S3_PROTOCOL_PREFIX, '').split('/');\n return { bucket, key: keyFragments.join('/') };\n}", "function fetchAndStoreObject(bucket, key, fn) {\n\tif (bucket === null) {\n\t\tbucket = constants.defaultBucket;\n\t}\n\tvar params = {\n\t\tBucket : bucket, /* required */\n\t\tKey : key\n\t/* required */\n\t};\n\tconsole.log(\"getObject for \" + JSON.stringify(params));\n\tvar file = fs.createWriteStream('/tmp/' + key);\n\ts3.getObject(params).on('httpData', function(chunk) {\n\t\tfile.write(chunk);\n\t\t// console.log(\"writing chunk in file.\"+key);\n\t}).on('httpDone', function() {\n\t\tfile.end();\n\t\tconsole.log(\"file end.\" + key);\n\t\tfn();\n\t}).send();\n}", "async function uploadImageToS3(imageUrl, idx) {\n\n const image = await readImageFromUrl(imageUrl, idx);\n\n const imagePath = imageUrl.split(`https://divisare-res.cloudinary.com/`)[1];\n const objectParams = {\n Bucket: 'bersling-divisaire',\n // i already created /aaa-testing, /testing and testing :)\n Key: `images6/${imagePath}`,\n Body: image,\n ContentType: 'image/jpg'\n };\n // Create object upload promise\n const uploadPromise = new AWS.S3({apiVersion: '2006-03-01', region: 'eu-central-1'})\n .putObject(objectParams)\n .promise();\n uploadPromise\n .then((data) => {\n // nothing to do...\n logger(`uploaded image...`);\n }).catch(err => {\n logger(\"ERROR\");\n logger(err);\n });\n return uploadPromise;\n\n\n}", "function saveObjToS3(data, fileName, bucket, callback){\n console.log(\"saveObjToS3\", data);\n //save data to s3 \n var params = {Bucket: bucket, Key: fileName, Body: data, ContentType: 'text/plain'};\n s3.putObject(params, function(err, data) {\n if (err) {\n console.log(\"saveObjToS3 err\", err);\n } else {\n callback();\n }\n });\n}", "static getFile (bucketName, objectKey) {\n const s3 = Storage._getS3Instance();\n const params = {\n Bucket: bucketName,\n Key: objectKey\n };\n return new Promise((resolve, reject) => {\n s3.getObject(params, (err, data) => {\n if (err) {\n reject(err);\n } else {\n resolve({\n content: data.Body, // buffer\n type: data.ContentType, // string\n encoding: data.ContentEncoding, // string\n size: data.ContentLength // integer\n });\n }\n });\n });\n }", "static isS3URL(url) {\n const s3Host =\n game.data.files.s3 &&\n game.data.files.s3 &&\n game.data.files.s3.endpoint &&\n game.data.files.s3.endpoint.host\n ? game.data.files.s3.endpoint.host\n : \"\";\n\n if (s3Host === \"\") return false;\n\n const regex = new RegExp(\"http[s]?://([^.]+)?.?\" + s3Host + \"(.+)\");\n const matches = regex.exec(url);\n\n const activeSource = matches ? \"s3\" : null; // can be data or remote\n const bucket = matches && matches[1] ? matches[1] : null;\n const current = matches && matches[2] ? matches[2] : null;\n\n if (activeSource === \"s3\") {\n return {\n activeSource,\n bucket,\n current,\n };\n } else {\n return false;\n }\n }", "function getPublicUrl (filename,bucketName) {\n return `https://storage.googleapis.com/${bucketName}/${filename}`;\n}", "function createBucket(){\n // Create S3 service object\n s3 = new AWS.S3({apiVersion: '2006-03-01'});\n\n // Create the parameters for calling createBucket\n var bucketParams = {\n Bucket : process.argv[2],\n ACL : 'public-read'\n };\n\n // call S3 to create the bucket\n s3.createBucket(bucketParams, function(err, data) {\n if (err) {\n console.log(\"Error\", err);\n } else {\n console.log(\"Success\", data.Location);\n }\n });\n}", "function createPublicFileURL(storageName) {\n return `http://storage.googleapis.com/${bucketName}/${encodeURIComponent(storageName)}`;\n}", "function S3ObjectClass(configuration, createUploadRequestNamesFunction, redisClient)\n{\n\tvar self = this;\n\n\t//grab bucketname from config file\n\tvar bucketName = configuration.bucket;\n\tvar uploadExpiration = configuration.expires || 15*60;\n\n\tself.s3 = new AWS.S3({params: {Bucket: bucketName}, computeChecksums: false});\n\n\t//example for outside use or testing -- helpful if i forget my function logic later--or someone checking around from the outside\n\tself.requestFunctionExample = exampleUploadRequestFunction;\n\tself.createUploadRequests = createUploadRequestNamesFunction;\n\n\tself.uploadErrors = {\n\t\tnullUploadKey : 0,\n\t\tredisError : 1,\n\t\theadCheckUnfulfilledError : 2,\n\t\theadCheckMissingError : 3,\n\t\tredisDeleteError : 4\n\t}\n\n\n\tself.generateObjectAccess = function(fileLocations)\n\t{\n\n\t\t//we create a map of signed URLs\n\t\tvar fileAccess = {};\n\n\t\tfor(var i=0; i < fileLocations.length; i++)\n\t\t{\n\t\t\tvar fLocation = fileLocations[i];\n\n\t\t\tvar signedURLReq = {\n\t\t\t\tBucket: bucketName, \n\t\t\t\tKey: fLocation,\n\t\t\t\tExpires: uploadExpiration,\n\t\t\t};\n\n\t\t\tvar signed = self.s3.getSignedUrl('getObject', signedURLReq);\n\n\t\t\tfileAccess[fLocation] = signed;\n\t\t}\n\n\t\treturn fileAccess;\n\t}\n\n\t//in case the upload properties are failures\n\tself.asyncConfirmUploadComplete = function(uuid)\n\t{\n\t\tvar defer = Q.defer();\n\n\t\tvar isOver = false;\n\n\t\t//we have the uuid, lets fetch the existing request\n\t\tasyncRedisGet(uuid)\n\t\t\t.then(function(val)\n\t\t\t{\n\t\t\t\t//if we don't have a value -- the key doesn't exist or expired -- either way, it's a failure!\n\t\t\t\tif(!val)\n\t\t\t\t{\n\t\t\t\t\t//we're all done -- we didn't encounter an error, we just don't exist -- time to resubmit\n\t\t\t\t\tdefer.resolve({success: false, error: self.uploadErrors.nullUploadKey});\n\t\t\t\t\tisOver = true;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\t//so we have our object\n\t\t\t\tvar putRequest = JSON.parse(val);\n\n\t\t\t\t//these are all the requests we made\n\t\t\t\tvar allUploads = putRequest.uploads;\n\n\t\t\t\t//we have to check on all the objects\n\t\t\t\tvar uploadConfirmPromises = [];\n\n\t\t\t\tfor(var i=0; i < allUploads.length; i++)\n\t\t\t\t{\n\t\t\t\t\tvar req = allUploads[i].request;\n\n\t\t\t\t\tvar params = {Bucket: req.Bucket, Key: req.Key};\n\n\t\t\t\t\tuploadConfirmPromises.push(asyncHeadRequest(params));\n\t\t\t\t}\n\n\t\t\t\treturn Q.allSettled(uploadConfirmPromises);\n\t\t\t})\n\t\t\t.then(function(results)\n\t\t\t{\n\t\t\t\tif(isOver)\n\t\t\t\t\treturn;\n\n\t\t\t\t//check for existance\n\t\t\t\tvar missing = [];\n\n\t\t\t\t//now we have all the results -- we verify they're all fulfilled\n\t\t\t\tfor(var i=0; i < results.length; i++)\n\t\t\t\t{\n\t\t\t\t\tvar res = results[i];\n\t\t\t\t\tif(res.state !== \"fulfilled\")\n\t\t\t\t\t{\n\t\t\t\t\t\t// console.log(\"Results:\".red,results);\n\n\t\t\t\t\t\tdefer.resolve({success: false, error: self.uploadErrors.headCheckUnfulfilledError});\n\t\t\t\t\t\tisOver = true;\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\n\t\t\t\t\t//if one is false, we're all false\n\t\t\t\t\tif(!res.value.exists)\n\t\t\t\t\t\tmissing.push(i);\n\n\t\t\t\t}\n\n\t\t\t\t//are we missing anything???\n\t\t\t\tif(missing.length)\n\t\t\t\t{\n\t\t\t\t\tdefer.resolve({success: false, error: self.uploadErrors.headCheckMissingError, missing: missing});\n\t\t\t\t\tisOver = true;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\t//we're all confirmed, we delete the upload requests now\n\t\t\t\t//however, this is not a major concern -- it will expire shortly anyways\n\t\t\t\t//therefore, we resolve first, then delete second\n\n\t\t\t\tisOver = true;\n\t\t\t\tdefer.resolve({success: true});\n\n\t\t\t\t//if we're here, then we all exist -- it's confirmed yay!\n\t\t\t\t//we need to remove the key from our redis client -- but we're not too concerned -- they expire when they expire\n\t\t\t\treturn;//asyncRedisDelete(uuid);\n\t\t\t})\n\t\t\t.catch(function(err)\n\t\t\t{\n\t\t\t\tif(isOver)\n\t\t\t\t\treturn;\n\n\t\t\t\tdefer.reject(err);\n\t\t\t});\n\n\t\treturn defer.promise;\n\t}\n\n\tfunction asyncHeadRequest(params)\n\t{\n\t\tvar defer = Q.defer();\n\n\t\tself.s3.headObject(params, function (err, metadata) { \n\t\t\tif (err)\n\t\t\t{\n\t\t\t\t//error code is not found -- it doesn't exist!\n\t\t\t\tif(err.code === 'NotFound') { \n\t\t\t \t// Handle no object on cloud here \n\t\t\t\t\tdefer.resolve({exists: false});\n\t\t\t\t} \n\t\t\t\t//straight error -- reject\n\t\t\t\telse \n\t\t\t\t\tdefer.reject(err);\n\n\t\t\t}else { \n\t\t\t\tdefer.resolve({exists: true});\n\t\t\t}\n\t\t});\n\n\t\treturn defer.promise;\n\t}\n\n\n\tself.asyncInitializeUpload = function(uploadProperties)\n\t{\t\n\t\t//we promise to return\n\t\tvar defer = Q.defer();\n\n\t\t//create a unique ID for this upload\n\t\tvar uuid = cuid();\n\n\t\t//we send our upload properties onwards\n\t\tvar requestUploads = self.createUploadRequests(uploadProperties);\n\n\t\t//we now have a number of requests to make\n\t\t//lets process them and get some signed urls to put the objects there\n\t\tvar fullUploadRequests = [];\n\n\t\t//these will be everything we need to make a signed URL request\n\t\tfor(var i=0; i < requestUploads.length; i++)\n\t\t{\n\n\t\t\t//\n\t\t\tvar upReqName = requestUploads[i];\n\n\t\t\tvar signedURLReq = {\n\t\t\t\tBucket: bucketName, \n\t\t\t\tKey: upReqName.prepend + uuid + upReqName.append, \n\t\t\t\tExpires: uploadExpiration,\n\t\t\t\t// ACL: 'public-read'\n\t\t\t};\n\n\t\t\tvar signed = self.s3.getSignedUrl('putObject', signedURLReq);\n\n\t\t\t//store the requests here\n\t\t\tfullUploadRequests.push({url: signed, request: signedURLReq});\n\t\t}\n\n\t\t//now we have our full requests\n\t\t//let's store it in REDIS, then send it back\n\n\t\tvar inProgress = {\n\t\t\tuuid: uuid,\n\t\t\tstate : \"pending\",\n\t\t\tuploads: fullUploadRequests\n\t\t};\n\n\t\t//we set the object in our redis location\n\t\tasyncRedisSetEx(uuid, uploadExpiration, JSON.stringify(inProgress))\n\t\t\t.catch(function(err)\n\t\t\t{\n\t\t\t\tdefer.reject(err);\n\t\t\t})\n\t\t\t.done(function()\n\t\t\t{\n\t\t\t\tdefer.resolve(inProgress);\n\t\t\t});\n\n\t\t//promise for now -- return later\n\t\treturn defer.promise;\n\t}\n\n\tfunction asyncRedisSetEx(key, expire, val)\n\t{\n\t\tvar defer = Q.defer();\n\n\t\tredisClient.setex(key, expire, val, function(err)\n\t\t{\n\t\t\tif(!err)\n\t\t\t\tdefer.resolve();\n\t\t\telse\n\t\t\t\tdefer.reject(err);\n\t\t});\n\n\t\treturn defer.promise;\n\t}\n\n\tfunction asyncRedisGet(key, val)\n\t{\n\t\tvar defer = Q.defer();\n\n\t\tredisClient.get(key, function(err, val)\n\t\t{\n\t\t\tif(!err)\n\t\t\t\tdefer.resolve(val);\n\t\t\telse\n\t\t\t\tdefer.reject(err);\n\t\t});\n\n\t\treturn defer.promise;\n\t}\n\n\tfunction asyncRedisDelete(key, val)\n\t{\n\t\tvar defer = Q.defer();\n\n\t\tredisClient.del(key, function(err, reply)\n\t\t{\n\t\t\tif(!err)\n\t\t\t\tdefer.resolve();\n\t\t\telse\n\t\t\t\tdefer.reject(err);\n\t\t});\n\n\t\treturn defer.promise;\n\t}\n\n\treturn self;\n}", "async put(rawUrl, inputStream, headers, storageMetadata) {\n assert(rawUrl, 'must provide raw input url');\n assert(inputStream, 'must provide an input stream');\n assert(headers, 'must provide HTTP headers');\n assert(storageMetadata, 'must provide storage provider metadata');\n\n // We decode the key because the S3 library 'helpfully'\n // URL encodes this value\n let request = {\n Bucket: this.bucket,\n Key: rawUrl,\n Body: inputStream,\n ACL: 'public-read',\n Metadata: storageMetadata,\n };\n\n _.forEach(HTTPHeaderToS3Prop, (s3Prop, httpHeader) => {\n if (_.includes(DisallowedHTTPHeaders, httpHeader)) {\n throw new Error(`The HTTP header ${httpHeader} is not allowed`);\n } else if (_.includes(MandatoryHTTPHeaders, httpHeader)) {\n assert(headers[httpHeader], `HTTP Header ${httpHeader} must be specified`);\n }\n request[s3Prop] = headers[httpHeader];\n });\n\n let options = {\n partSize: this.partSize,\n queueSize: this.queueSize,\n };\n\n let upload = this.s3.upload(request, options);\n\n this.debug('starting S3 upload');\n let result = await wrapSend(upload);\n this.debug('completed S3 upload');\n return result;\n }", "putObject(bucketName, objectName, stream, size, metaData, callback) {\n if (!isValidBucketName(bucketName)) {\n throw new errors.InvalidBucketNameError('Invalid bucket name: ' + bucketName)\n }\n if (!isValidObjectName(objectName)) {\n throw new errors.InvalidObjectNameError(`Invalid object name: ${objectName}`)\n }\n\n // We'll need to shift arguments to the left because of size and metaData.\n if (isFunction(size)) {\n callback = size\n metaData = {}\n } else if (isFunction(metaData)) {\n callback = metaData\n metaData = {}\n }\n\n // We'll need to shift arguments to the left because of metaData\n // and size being optional.\n if (isObject(size)) {\n metaData = size\n }\n\n // Ensures Metadata has appropriate prefix for A3 API\n metaData = prependXAMZMeta(metaData)\n if (typeof stream === 'string' || stream instanceof Buffer) {\n // Adapts the non-stream interface into a stream.\n size = stream.length\n stream = readableStream(stream)\n } else if (!isReadableStream(stream)) {\n throw new TypeError('third argument should be of type \"stream.Readable\" or \"Buffer\" or \"string\"')\n }\n\n if (!isFunction(callback)) {\n throw new TypeError('callback should be of type \"function\"')\n }\n\n if (isNumber(size) && size < 0) {\n throw new errors.InvalidArgumentError(`size cannot be negative, given size: ${size}`)\n }\n\n // Get the part size and forward that to the BlockStream. Default to the\n // largest block size possible if necessary.\n if (!isNumber(size)) {\n size = this.maxObjectSize\n }\n\n size = this.calculatePartSize(size)\n\n // s3 requires that all non-end chunks be at least `this.partSize`,\n // so we chunk the stream until we hit either that size or the end before\n // we flush it to s3.\n let chunker = new BlockStream2({ size, zeroPadding: false })\n\n // This is a Writable stream that can be written to in order to upload\n // to the specified bucket and object automatically.\n let uploader = new ObjectUploader(this, bucketName, objectName, size, metaData, callback)\n // stream => chunker => uploader\n pipesetup(stream, chunker, uploader)\n }", "function makeS3Request(fileUrl, signedRequestUrl, file) {\n return new Promise((resolve, reject) => {\n const xhr = new XMLHttpRequest()\n\n xhr.onreadystatechange = () => {\n if (xhr.readyState === 4) {\n if (xhr.status === 200) {\n resolve(fileUrl)\n } else {\n reject({\n status: xhr.status,\n statusText: xhr.statusText,\n })\n }\n }\n }\n\n xhr.open('PUT', signedRequestUrl)\n xhr.send(file)\n })\n}", "static Create(opts, cb) {\n new S3FileSystem(opts, cb)\n }", "function fetchFromS3(env, callback){\n // get the investigators cached version from AWS.\n if (!isValidEnv(env)){\n callback(\"Invalid env passed into fetchFromS3()\");\n return;\n }\n // construct the filename from the env\n var filename = getS3FilePath(env);\n var params = {\n Bucket: AWS_BUCKET_NAME,\n Key: filename\n };\n // get the file\n console.log(\"Calling s3....\");\n s3.getObject(params, function(err,data){\n if (err){\n callback(\"InvestigatorService S3: \" + err.code);\n } else {\n var text = data.Body.toString('ascii');\n callback(null, text);\n }\n });\n}", "function InitAWSConfigurations()\n{\n bucketName = $(\"#hdnBucketName\").val();\n\n bucketStartURL = $(\"#hdnBucketStartURL\").val();\n\n AWS.config.update({\n accessKeyId: $(\"#hdnAWSAccessKey\").val(),\n secretAccessKey: $(\"#hdnAWSSecretKey\").val(),\n region: $(\"#hdnBucketRegion\").val()\n\n });\n\n\n bucket = new AWS.S3({\n params: { Bucket: bucketName }\n });\n // s3 = new AWS.S3();\n\n /****Image upload path initializations****/\n\n userProfileImagePath = $(\"#hdnUserProfileImagePath\").val();\n otherUserProfileFilePath = $(\"#hdnOtherUserProfileFilePath\").val();\n\n\n /***************************************/\n\n}", "constructor (id, s3) {\n this.s3Prefix = process.env.S3_PREFIX // 'scores-bot'\n this._store = s3\n this.id = id\n this.touch(true)\n this.setDefaultState()\n }", "presignedPutObject(bucketName, objectName, expires) {\n if (!validateBucketName(bucketName)) {\n throw new errors.InvalidateBucketNameException('Invalid bucket name: ' + bucketName)\n }\n if (objectName === null || objectName.trim() === '') {\n throw new errors.InvalidObjectNameException('Object name cannot be empty')\n }\n var requestParams = {\n host: this.params.host,\n port: this.params.port,\n protocol: this.params.protocol,\n path: `/${bucketName}/${uriResourceEscape(objectName)}`,\n method: 'PUT',\n expires: expires\n }\n return presignSignatureV4(requestParams, this.params.accessKey, this.params.secretKey)\n }", "uploadToS3(e) {\n this.setState({\n loading: true,\n serviceImageFlag: false\n });\n ReactS3.uploadFile(e.target.files[0], config)\n .then((response)=> {\n this.setState({\n image: response.location,\n loading: false,\n serviceImageFlag: true,\n imageHolder: \"\"\n })\n },\n )\n }", "function uploadToS3(name, file, successCallback, errorCallback, progressCallback) {\n\n if (typeof successCallback != 'function') {\n Ti.API.error('successCallback() is not defined');\n return false;\n }\n\n if (typeof errorCallback != 'function') {\n Ti.API.error('errorCallback() is not defined');\n return false;\n }\n\n var AWSAccessKeyID = 'AKIAJHRVU52E4GKVARCQ';\n var AWSSecretAccessKey = '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';\n var AWSBucketName = 'snapps';\n var AWSHost = AWSBucketName + '.s3.amazonaws.com';\n\n var currentDateTime = formatDate(new Date(),'E, d MMM yyyy HH:mm:ss') + ' ' + getOffsetAsInteger();\n\n var xhr = Ti.Network.createHTTPClient();\n\n xhr.onsendstream = function(e) {\n\n if (typeof debugStartTime != 'number') {\n debugStartTime = new Date().getTime();\n }\n\n debugUploadTime = Math.floor((new Date().getTime() - debugStartTime) / 1000);\n\n var progress = Math.floor(e.progress * 100);\n Ti.API.info('uploading (' + debugUploadTime + 's): ' + progress + '%');\n\n // run progressCallback function when available\n if (typeof progressCallback == 'function') {\n progressCallback(progress);\n }\n\n };\n\n xhr.onerror = function(e) {\n Ti.API.error({ errorlocation: 'onload', error: e, responseText: xhr.responseText, headers: xhr.getResponseHeaders() });\n errorCallback(e);\n };\n\n xhr.onload = function() {\n if (this.status >= 200 && this.status < 300) {\n\n var responseHeaders = xhr.getResponseHeaders();\n\n var filename = name;\n var url = 'https://' + AWSHost + '/' + name;\n\n if (responseHeaders['x-amz-version-id']) {\n url = url + '?versionId=' + responseHeaders['x-amz-version-id'];\n }\n\n successCallback({ url: url });\n }\n else {\n Ti.API.error({ errorlocation: 'onload', error: e, responseText: xhr.responseText, headers: xhr.getResponseHeaders() });\n errorCallback();\n }\n };\n\n //ensure we have time to upload\n xhr.setTimeout(99000);\n\n // An optional boolean parameter, defaulting to true, indicating whether or not to perform the operation asynchronously.\n // If this value is false, the send() method does not return until the response is received. If true, notification of a\n // completed transaction is provided using event listeners. This must be true if the multipart attribute is true, or\n // an exception will be thrown.\n xhr.open('PUT', 'https://' + AWSHost + '/' + name, true);\n\n //var StringToSign = 'PUT\\n\\nmultipart/form-data\\n' + currentDateTime + '\\nx-amz-acl:public-read\\n/' + AWSBucketName + '/' + name;\n var StringToSign = 'PUT\\n\\n\\n' + currentDateTime + '\\nx-amz-acl:public-read\\n/' + AWSBucketName + '/' + name;\n var AWSSignature = b64_hmac_sha1(AWSSecretAccessKey, Utf8.encode(StringToSign));\n var AuthorizationHeader = 'AWS ' + AWSAccessKeyID + ':' + AWSSignature;\n\n xhr.setRequestHeader('Authorization', AuthorizationHeader);\n //xhr.setRequestHeader('Content-Type', 'multipart/form-data');\n xhr.setRequestHeader('X-Amz-Acl', 'public-read');\n xhr.setRequestHeader('Host', AWSHost);\n xhr.setRequestHeader('Date', currentDateTime);\n\n xhr.send(file);\n\n return xhr;\n}", "function putObject(bucket, key, obkject) {\n\tif (bucket === null) {\n\t\tbucket = constants.defaultBucket;\n\t}\n\n\tvar params = {\n\t\tBucket : bucket, /* required */\n\t\tKey : key, /* required */\n\t\tBody : obkject\n\t};\n\tconsole.log(\"putObject for \" + JSON.stringify(obkject));\n\ts3.putObject(params, function(err, data) {\n\t\tif (err)\n\t\t\tconsole.log(err, err.stack); // an error occurred\n\t\telse\n\t\t\tconsole.log(data); // successful response\n\t});\n}", "function uploadAndFetch (s3, stream, filename, bucket, key) {\n var deferred = when.defer();\n exports.getFileStream(filename)\n .pipe(stream)\n .on(\"error\", deferred.reject)\n .on(\"finish\", function () {\n deferred.resolve(exports.getObject(s3, bucket, key));\n });\n return deferred.promise;\n}", "async function createSignedGsUrl(serviceAccountKey, {bucket, name}) {\n const storage = new Storage({ credentials: serviceAccountKey });\n const response = await storage.bucket(bucket).file(name).getSignedUrl({ action: 'read', expires: Date.now() + 36e5 });\n return response[0];\n}", "async function putS3(fileKey, data) {\n oLog.verbose(__filename, 'putS3');\n\n try {\n if (configs.aws.s3.active) {\n // set aws region:\n rAWS.config.update({\n region: configs.aws.s3.region\n });\n // bucket info:\n let s3Bucket = configs.aws.s3.s3bucket;\n let s3FileKey = fileKey;\n let s3Params = {\n Bucket: s3Bucket,\n Key: s3FileKey,\n Body: data\n };\n\n // get object and parse the JSON:\n return rS3.putObject(s3Params).promise();\n } else {\n // empty object if not active:\n return {};\n }\n } catch (error) {\n oLog.error(__filename, 'putS3', error);\n return error;\n }\n}", "function ImageProcessor(s3Object) {\n this.s3Object = s3Object;\n}", "presignedGetObject(bucketName, objectName, expires) {\n if (!validateBucketName(bucketName)) {\n throw new errors.InvalidateBucketNameException('Invalid bucket name: ' + bucketName)\n }\n if (objectName === null || objectName.trim() === '') {\n throw new errors.InvalidObjectNameException('Object name cannot be empty')\n }\n var requestParams = {\n host: this.params.host,\n port: this.params.port,\n protocol: this.params.protocol,\n path: `/${bucketName}/${uriResourceEscape(objectName)}`,\n method: 'GET',\n expires: expires\n }\n return presignSignatureV4(requestParams, this.params.accessKey, this.params.secretKey)\n }", "function putS3File(bucketName, fileName, data, callback) {\n var expirationDate = new Date();\n // Assuming a user would not remain active in the same session for over 1 hr.\n expirationDate = new Date(expirationDate.setHours(expirationDate.getHours() + 1));\n var params = {\n Bucket: bucketName,\n Key: fileName,\n Body: data,\n ACL: 'public-read', // TODO: find way to restrict access to this lambda function\n Expires: expirationDate\n };\n s3.putObject(params, function (err, data) {\n callback(err, data);\n });\n}", "function cfnDataSourceS3PathPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnDataSource_S3PathPropertyValidator(properties).assertSuccess();\n return {\n Bucket: cdk.stringToCloudFormation(properties.bucket),\n Key: cdk.stringToCloudFormation(properties.key),\n };\n}", "async init() {\n this.debug(`creating ${this.bucket}`);\n await createS3Bucket(this.s3, this.bucket, this.region, this.acl, this.lifespan);\n this.debug(`creating ${this.bucket}`);\n }", "function storeToS3(env, data, callback){\n // get the investigators cached version from AWS.\n if (!isValidEnv(env)){\n callback(\"Invalid env passed into storeToS3()\");\n return;\n }\n // construct the filename from the env\n var filename = getS3FilePath(env);\n var params = {\n Bucket: AWS_BUCKET_NAME,\n Key: filename,\n Body: JSON.stringify(data)\n };\n // upload the file...\n console.log(\"Uploading list to s3...\");\n s3.upload(params, function(err, data){\n if (err){\n callback(\"storeToS3 S3: \" + err);\n } else {\n console.log(\"S3 upload success: s3://\" + AWS_BUCKET_NAME + '/' + filename);\n callback(null, data);\n }\n });\n}", "static awsUrl(options) {\n return new GraphqlType(schema_base_1.Type.AWS_URL, options);\n }", "function getPublicUrl (filename) {\n return `https://storage.googleapis.com/${config.CLOUD_BUCKET}/${filename}`;\n}", "function S3Fcty ($q, $upload, S3ResourceFcty) {\n var s3Upload = function(file, uploadData, uploadUrlPromise) {\n // Given the file to upload and an object containing the form\n // data needed to POST the file to S3, perform the upload.\n uploadData.upload_args.file = file;\n $upload.upload(uploadData.upload_args).then(function(response) {\n if (response.status === 201) {\n uploadUrlPromise.resolve(uploadData.cdn_url);\n } else {\n uploadUrlPromise.reject('upload failed');\n }\n });\n };\n var beginUpload = function(file, resourceName, resourceId, uploadName) {\n // Request the form data required to upload the file to S3\n // from the backend and then perform the upload.\n var uploadUrlPromise = $q.defer();\n S3ResourceFactory(resourceName).get({\n id: resourceId,\n fileName: file.name,\n uploadName: uploadName,\n mime_type: file.type\n }).$promise.then(function(uploadData) {\n s3Upload(file, uploadData, uploadUrlPromise);\n });\n return uploadUrlPromise.promise;\n };\n\n return {upload: beginUpload};\n}", "function combineObjectWithCachedS3File(config, upload, downloadDict, s3, key, newObj, callback) {\n var localFilename = config.workingDir + \"/\" + config.outBucket + \"/\" + key;\n var localDir = localFilename.substring(0, localFilename.lastIndexOf('/'));\n\n var inFlight = downloadDict[localFilename];\n if (inFlight) {\n //console.log(\"Download race condition avoided, queued\", key, newObj);\n inFlight.obj = tarasS3.combineObjects(newObj, inFlight.obj);\n inFlight.callbacks.push(callback);\n return; // we are done, our callback will get called as part of original inFlight request\n } else {\n downloadDict[localFilename] = inFlight = {'obj':newObj, 'callbacks':[callback]};\n }\n\n async.waterfall([\n // try to read file from local cache before we go to out to s3\n function (callback) {\n fs.readFile(localFilename, function (err, data) {\n function fallback() {\n var params = {'s3':s3, 'params':{'Bucket': config.outBucket, 'Key':key}};\n return tarasS3.S3GetObjectGunzip(params, function (err, data) {\n if (err) {\n // 404 on s3 means this object is new stuff\n if (err.statusCode == 404)\n return callback(null, {});\n else\n return callback(err);\n }\n callback(null, JSON.parse(data));\n })\n }\n // missing file or invalid json are both reasons for concern\n if (err) {\n return fallback()\n }\n var obj;\n try {\n obj = JSON.parse(data)\n }catch(e) {\n return fallback()\n }\n callback(null, obj);\n });\n },\n function (obj, callback) {\n inFlight.obj = tarasS3.combineObjects(inFlight.obj, obj);\n mkdirp.mkdirp(localDir, callback);\n },\n function(ignore, callback) {\n str = JSON.stringify(inFlight.obj);\n delete downloadDict[localFilename];\n upload(key, localFilename, str, callback);\n }\n ],function (err, data) {\n if (err)\n return callback(err);\n inFlight.callbacks.forEach(function (callback) {callback(null, key)});\n });\n}", "async function fetchInputFromS3(s3URL) {\n const tmpDir = await tmp.dir({ dir: \"/tmp\" });\n const parsedS3URL = url.parse(s3URL);\n const localFile = path.join(tmpDir.path, path.basename(parsedS3URL.path));\n console.log(`Downloading ${s3URL} to ${localFile}...`);\n\n const params = {\n Bucket: parsedS3URL.host,\n Key: parsedS3URL.path.slice(1),\n };\n const s3 = new AWS.S3();\n const readStream = s3.getObject(params).createReadStream();\n await new Promise((resolve, reject) => {\n readStream.on(\"error\", reject);\n readStream.on(\"end\", resolve);\n const file = fs.createWriteStream(localFile);\n readStream.pipe(file);\n });\n return localFile;\n}", "getURL() {\n return Meteor.absoluteUrl(`${ UploadFS.config.storesPath }/${ this.name }`, {\n secure: UploadFS.config.https\n });\n }", "function getObjFromS3(fileName, bucket, callback){\n let params = {Bucket: bucket, Key:fileName};\n s3.getObject(params, function(err, data){\n if(err){\n console.error(\"getObjFromS3 err\",err);\n } else {\n callback(data.Body.toString('utf-8'));\n }\n \n });\n\n}", "mfGet_LabradorAwsS3ImageUrlUpload(replace=false){\n\t\treturn mf.modeGet_LabradorAwsS3ImageUrlUpload(this,replace)\n\t}", "function addS3bucket (req, res, next) {\n if (req.params.s3bucket) return next()\n req.params.s3bucket = [process.env.APP_NAME, req.params.appname].join('.')\n next()\n}", "async function downloadFile(s3Object) {\n const getParams = {Bucket: bucketName, Key: s3Object.Key};\n const fileWriteStream = fs.createWriteStream(path.join(cryptoFolder, s3Object.Key));\n return new Promise((resolve, reject) => {\n s3.getObject(getParams).createReadStream()\n .on('end', () => {\n return resolve();\n }).on('error', (error) => {\n return reject(error);\n }).pipe(fileWriteStream)\n });\n}", "function StorageObject() {}", "function StorageObject() {}", "function StorageObject() {}", "function StorageObject() {}", "function StorageObject() {}", "async function imageUpload(filename,type, bucketName) {\n\n try{\n\n //create bucket if it isn't present.\n await bucketExists(bucketName);\n\n const bucket = storage.bucket(bucketName);\n \n const gcsname = type +'/'+Date.now() + filename.originalname;\n const file = bucket.file(gcsname);\n \n const stream = file.createWriteStream({\n metadata: {\n contentType: filename.mimetype,\n },\n resumable: false,\n });\n\n \n \n stream.on('error', err => {\n filename.cloudStorageError = err;\n console.log(err);\n });\n \n stream.on('finish', async () => {\n \n filename.cloudStorageObject = gcsname;\n await file.makePublic().then(() => {\n imageUrl = getPublicUrl(gcsname,bucketName);\n console.log(imageUrl);\n });\n \n\n });\n \n stream.end(filename.buffer);\n return getPublicUrl(gcsname,bucketName);\n\n }\n\n catch(error){\n console.log(error);\n \n }\n // [END process]\n\n}", "function ImageObject(catName, url)\n{\n var obj = JSON.parse(httpGet(url + '/' + catName));\n this.catName = catName;\n this.imageUrl = obj.image.thumbnail; \n}", "function upload_private_S3_resource(file, folder, cFunc) {\n\tvar xhr = new XMLHttpRequest();\n\t// var amz_sign_s3 is defined in script on HTML page\n\txhr.open(\"GET\", amz_sign_s3+\"?file_name=\"+file.name+\"&file_type=\"+file.type+\"&folder=\"+folder);\n\txhr.onreadystatechange = function(){\n\t\tif(xhr.readyState === 4){\n\t\t\tif(xhr.status === 200){\n\t\t\t\tvar response = JSON.parse(xhr.responseText);\n\t\t\t\tupload_file(file, response.signed_request, response.url, cFunc);\n\t\t\t}\n\t\t\telse{\n\t\t\t\talert(\"Could not get signed URL.\");\n\t\t\t}\n\t\t}\n\t};\n\txhr.send();\n}", "function prepareUrl(imgObject) {\n return 'https://farm8.staticflickr.com/' + imgObject.server + '/'+ imgObject.id + '_' + imgObject.secret + '.jpg';\n}", "function getUriTypeFromEndpoint(endpoint) {\n return endpoint?.credential?.type === showType.s3 ? S3 : endpoint?.uri.split(\":\")[0].toLowerCase()\n}", "async upload_file_toS3(filename, extension) {\n try {\n\n var username = await AsyncStorage.getItem(\"username\");\n var s3config = require(\"./config/AWSConfig.json\");\n var signedurl = await this.getsignedurl(s3config.s3bucketname, s3config.s3folder + \"/\" + username + \"/\" + filename + extension, \"put\");\n\n\n\n let dirs = RNFetchBlob.fs.dirs;\n\n const result = await RNFetchBlob.fetch('PUT', signedurl, {\n 'Content-Type': 'image/jpg',\n }, RNFetchBlob.wrap(dirs.DocumentDir + s3config.localimagestore + filename + extension));\n\n //alert(result.respInfo.status);\n if (result.respInfo.status == 200)\n return true;\n else\n return false;\n\n }\n catch (error) {\n return false;\n //alert(error.message);\n }\n\n }", "function cfnFaqS3PathPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnFaq_S3PathPropertyValidator(properties).assertSuccess();\n return {\n Bucket: cdk.stringToCloudFormation(properties.bucket),\n Key: cdk.stringToCloudFormation(properties.key),\n };\n}", "function cfnApiS3LocationPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnApi_S3LocationPropertyValidator(properties).assertSuccess();\n return {\n Bucket: cdk.stringToCloudFormation(properties.bucket),\n Key: cdk.stringToCloudFormation(properties.key),\n Version: cdk.numberToCloudFormation(properties.version),\n };\n}", "function cfnApiS3LocationPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnApi_S3LocationPropertyValidator(properties).assertSuccess();\n return {\n Bucket: cdk.stringToCloudFormation(properties.bucket),\n Key: cdk.stringToCloudFormation(properties.key),\n Version: cdk.numberToCloudFormation(properties.version),\n };\n}", "create_object_upload(params, object_sdk) {\n if (this.target_bucket) params = _.defaults({ bucket: this.target_bucket }, params);\n return object_sdk.rpc_client.object.create_object_upload(params);\n }", "function getPublicUrl (filename) {\n // IF CLOUD_BUCKET has dots \".\" its a real domain, isn't neccessary https://storage.googleapis.com/\n if (CLOUD_BUCKET.indexOf('.') !== -1 && CLOUD_BUCKET.indexOf('.appspot.com') === -1) {\n return 'http://' + CLOUD_BUCKET + '/' + filename\n } else {\n return 'https://storage.googleapis.com/' + CLOUD_BUCKET + '/' + filename\n }\n}", "async function uploadFileToS3(file, getSignedUrl) {\n try {\n const {fileUrl, signedRequestUrl} = await getSignedUrl(file)\n const url = await makeS3Request(fileUrl, signedRequestUrl, file)\n\n return url\n } catch (e) {\n return alert('Could not upload file.')\n }\n}", "function StorageObject() { }", "function setupAws(profile) {\n\tvar credentials = new aws.SharedIniFileCredentials({ profile: profile });\n\taws.config.credentials = credentials;\n\n\ts3 = new aws.S3({\n\t\tparams: { Bucket: Config.bucketName }\n\t});\n}", "function uploadToS3 (file, infoId) {\n // var s3Credentials = appConfig.s3Credentials();\n // var POLICY = s3Credentials.POLICY\n // var SIGNATURE = s3Credentials.SIGNATURE\n // var ACCESS_KEY = s3Credentials.ACCESS_KEY\n var url = '//app.sitetheory.io:3000/?session=' +\n _.cookie('SITETHEORY') + (infoId ? ('&id=' + infoId) : '')\n\n return Upload.upload({\n url: url,\n method: 'POST',\n data: {\n // AWSAccessKeyId: ACCESS_KEY,\n key: file.name, // the key to store the file on S3, could be\n // file name or customized\n acl: 'private', // sets the access to the uploaded file in the\n // bucket: private, public-read, ...\n // policy: POLICY, // base64-encoded json policy\n // signature: SIGNATURE, // base64-encoded signature based on\n // policy string\n 'Content-Type': file.type !== ''\n ? file.type\n : 'application/octet-stream', // content type of the file\n // (NotEmpty)\n filename: file.name, // this is needed for Flash polyfill IE8-9\n file: file\n }\n })\n }", "function uploadToS3(file_path, s3_file_path, cb)\n{\n\tconsole.log(\"Uploading to S3 file: \" + file_path, \"to: \" + s3_file_path);\n\n\theaders = {'x-amz-acl': 'public-read'};\n\ts3Client.putFile(file_path, s3_file_path, headers, function(err, s3Response) {\n\t if (err)\n \t{\n \t\tconsole.log(\"ERROR: \" + util.inspect(err));\n \t\tthrow err;\n \t}\n\t \n\t destUrl = s3Response.req.url;\n\n\t cb();\n\t});\n}", "downloadFile(bucket, fileNameToDownload, fileNameToSaveAs) {\n return new Promise((resolve, reject) => {\n var download = this.client.downloadFile({\n localFile: fileNameToSaveAs,\n s3Params: {\n Bucket: bucket,\n Key: fileNameToDownload\n }\n });\n\n download.on('error', error => {\n reject(error);\n });\n\n download.on('end', () => {\n resolve();\n });\n });\n }", "function getGSUrls(bucket, filename) {\n return `https://storage.googleapis.com/${bucket}/${filename}`;\n}", "getUrl() {\n if (this.state != remote_file) {\n return undefined;\n }\n let [ssName, storageService] = getStorageService();\n return storageService.getUrl(this._obj.location);\n }", "async getFile(params) {\n try {\n console.log(\"s3.getObject Params: \", params);\n var s3 = new this.AWS.S3();\n let file = await s3.getObject(params).promise();\n return (file);\n } catch (error) {\n console.error('S3.getObject error: ', error);\n return (error);\n }\n }", "* getStream (path) {\n return this.s3.getObject({\n Bucket: this.disk.bucket,\n Key: path\n }).createReadStream()\n }", "function cfnFunctionS3LocationPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnFunction_S3LocationPropertyValidator(properties).assertSuccess();\n return {\n Bucket: cdk.stringToCloudFormation(properties.bucket),\n Key: cdk.stringToCloudFormation(properties.key),\n Version: cdk.numberToCloudFormation(properties.version),\n };\n}", "function cfnFunctionS3LocationPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnFunction_S3LocationPropertyValidator(properties).assertSuccess();\n return {\n Bucket: cdk.stringToCloudFormation(properties.bucket),\n Key: cdk.stringToCloudFormation(properties.key),\n Version: cdk.numberToCloudFormation(properties.version),\n };\n}", "function StorageObject() {\n}", "function s3_upload_img(extension, file_in, try_in){\n var trynum = try_in;\n filename = file_in;\n var s3upload = new S3Upload({\n file_dom_selector: 'img_file',\n s3_sign_put_url: '/sign_s3_put/',\n s3_object_name: filename,\n onProgress: function(percent, message) {\n $('#img_status').text(\"Uploading: \" + percent + \"%\");\n },\n onFinishS3Put: function(url) {\n $(\"#id_img_url\").val(url);\n $('#image_preview').attr('src', url);\n enable_button();\n },\n onError: function(status) {\n if(trynum < 1){ //amount of tries\n console.log(\"upload error #\" + trynum + \" of type \" + status + \", retrying..\");\n trynum++;\n s3_upload_img(extension, file_in, trynum);\n }\n else{\n console.log(\"upload error #\" + trynum + \", giving up.\");\n $('#img_status').html('Upload error: ' + status);\n }\n }\n });\n}", "function getFileStream(fileKey) {\n const downloadParams = {\n Key: fileKey,\n Bucket: bucketName\n }\n var object = s3.getObject(downloadParams).createReadStream().on('error', (err) => console.log(err + 'ERROR GET FILE FROM 3S'))\n return object\n}", "function AmazonS3Extender(writer) {\n\t/// <summary>Extends Image Uploader with a direct upload to Amazon S3 storage.</summary>\n\t/// <param name=\"writer\" type=\"ImageUploaderWriter\">An instance of ImageUploaderWriter object.</param>\n\n\tBaseExtender.call(this, writer);\n\t\n\tthis._AWSAccessKeyId = \"\";\n\tthis._bucket = \"\";\n\tthis._bucketHostName = \"\";\t\n\n\tthis._writer.addEventListener(\"BeforeUpload\", IUCommon.createDelegate(this, this._control$BeforeUpload), true);\n\tthis._writer.addEventListener(\"Error\", IUCommon.createDelegate(this, this._control$Error), true);\n\n\tthis._sourceFile = new AmazonS3Extender.FileSettings(this, \"SourceFile\");\n\tthis._thumbnail1 = new AmazonS3Extender.FileSettings(this, \"Thumbnail1\");\n\tthis._thumbnail2 = new AmazonS3Extender.FileSettings(this, \"Thumbnail2\");\n\tthis._thumbnail3 = new AmazonS3Extender.FileSettings(this, \"Thumbnail3\");\n\t\n\tthis._postFields = [\"FileCount\", \"PackageIndex\"\n\t\t, \"PackageCount\", \"PackageGuid\"\n\t\t, \"Description_[ItemIndex]\", \"Width_[ItemIndex]\"\n\t\t, \"Height_[ItemIndex]\", \"Angle_[ItemIndex]\"\n\t\t, \"HorizontalResolution_[ItemIndex]\", \"VerticalResolution_[ItemIndex]\"\n\t\t, \"SourceFileSize_[ItemIndex]\", \"SourceFileCreatedDateTime_[ItemIndex]\"\n\t\t, \"SourceFileLastModifiedDateTime_[ItemIndex]\", \"SourceFileCreatedDateTimeLocal_[ItemIndex]\"\n\t\t, \"SourceFileLastModifiedDateTimeLocal_[ItemIndex]\", \"FileName_[ItemIndex]\"\n\t\t, \"UploadFile[ThumbnailIndex]CompressionMode_[ItemIndex]\", \"Thumbnail[ThumbnailIndex]FileSize_[ItemIndex]\"\n\t\t, \"Thumbnail[ThumbnailIndex]Width_[ItemIndex]\", \"Thumbnail[ThumbnailIndex]Height_[ItemIndex]\"\n\t\t, \"Thumbnail[ThumbnailIndex]Succeeded_[ItemIndex]\"];\n\n\tthis._postFieldsHash = {};\n\t\n\tthis._postFieldsAdded = {};\t\n\t\t\n\tfor (var i = 0; i < this._postFields.length; i++) {\n\t\tthis._postFieldsHash[this._postFields[i]] = 1;\n\t}\n}", "function uploadToS3(file) {\n let s3bucket = new AWS.S3({\n accessKeyId: ACCESS,\n secretAccessKey: SECRET,\n Bucket: BUCKET_NAME,\n });\n s3bucket.createBucket(function () {\n var params = {\n Bucket: BUCKET_NAME,\n Key: file.name,\n Body: file.data,\n };\n s3bucket.upload(params, function (err, data) {\n if (err) {\n console.log(\"error in callback\");\n console.log(err);\n }\n console.log(\"success\");\n console.log(data);\n });\n });\n}", "function deleteObject() {\n const deleteParams = {\n Bucket: bucket,\n Key: key,\n };\n s3Client.deleteObject(deleteParams, (err, data) => {\n if (err) console.log('err:', err);\n else console.log('data:', data);\n });\n}", "function getGetSignedUrl(key) {\n const signedUrlExpireSeconds = 60 * 5;\n return exports.s3.getSignedUrl('getObject', {\n Bucket: config_1.config.aws_media_bucket,\n Key: key,\n Expires: signedUrlExpireSeconds,\n });\n}", "download(fName){\n let client = this.s3Client;\n\n return new Promise((resolve, reject) => {\n client.getFile(fName, (err, res) => {\n if(err) reject(err);\n resolve(res);\n }); \n });\n }", "function awsUpload() {\n\n //configuring the AWS environment\n AWS.config.update({\n accessKeyId: \"AKIAIYOTGRTBNHAJOWKQ\",\n secretAccessKey: \"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\"\n });\n var s3 = new AWS.S3();\n var filePath = \"./images/\" + imageLocation;\n\n //Configuring Parameters\n var params = {\n Bucket: 'pricefinder-bucket',\n Body: fs.createReadStream(filePath),\n Key: \"images/\" + Date.now() + \"_\" + path.basename(filePath)\n };\n\n //Uploading to s3 Bucket\n s3.upload(params, function (err, data) {\n //if an error occurs, handle it\n if (err) {\n console.log(\"Error\", err);\n }\n if (data) {\n console.log();\n console.log(\"Uploaded in:\", data.Location);\n console.log();\n }\n });\n\n customVision();\n\n}", "function s3Upload(files, bucketName, objectKeyPrefix, iamUserKey, iamUserSecret, callback) {\n var s3 = new AWS.S3({\n bucket: bucketName,\n accessKeyId: iamUserKey,\n secretAccessKey: iamUserSecret,\n apiVersion: '2006-03-01',\n });\n\n // s3.abortMultipartUpload(params, function (err, data) {\n // if (err) console.log(err, err.stack); // an error occurred\n // else console.log(data); // successful response\n // });\n\n // Setup the objects to upload to S3 & map the results into files\n var results = files.map(function(file) {\n // Upload file to bucket with name of Key\n s3.upload({\n Bucket: bucketName,\n Key: objectKeyPrefix + file.originalname, // Prefix should have \".\" on each end\n Body: file.buffer,\n ACL: 'public-read' // TODO: CHANGE THIS & READ FROM CLOUDFRONT INSTEAD\n },\n function(error, data) {\n // TODO: Maybe refine this to show only data care about elsewhere\n if(error) {\n console.log(\"Error uploading file to S3: \", error);\n return {error: true, data: error};\n } else {\n console.log('File uploaded. Data is:', data);\n return {error: false, data: data};\n }\n });\n });\n\n callback(results); // Results could be errors or successes\n}", "function getSignedUrl(urlData) {\n var params = { Bucket: urlData.bucket, Key: urlData.key };\n return new Promise(function (resolve, reject) {\n s3.getSignedUrl(urlData.action, params, function (err, url) {\n if (err) {\n console.log('Error getting signed url:', err);\n reject(err);\n } else {\n console.log('The URL is', url);\n resolve(url);\n }\n });\n });\n}", "function cfnStreamingDistributionS3OriginPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnStreamingDistribution_S3OriginPropertyValidator(properties).assertSuccess();\n return {\n DomainName: cdk.stringToCloudFormation(properties.domainName),\n OriginAccessIdentity: cdk.stringToCloudFormation(properties.originAccessIdentity),\n };\n}", "static deleteFile (bucketName, objectKey) {\n const s3 = Storage._getS3Instance();\n const params = {\n Bucket: bucketName,\n Key: objectKey\n };\n return new Promise((resolve, reject) => {\n s3.deleteObject(params, (err, data) => err ? reject(err) : resolve());\n });\n }" ]
[ "0.714807", "0.67041886", "0.63533825", "0.6322735", "0.6225527", "0.62006474", "0.6193148", "0.6139079", "0.61067826", "0.6056675", "0.6053044", "0.602172", "0.60092586", "0.5986327", "0.59813935", "0.59729314", "0.59724915", "0.59661627", "0.59575886", "0.5949311", "0.58686435", "0.58516395", "0.5815956", "0.58049107", "0.5756379", "0.57207006", "0.5690715", "0.56795645", "0.5665108", "0.56605995", "0.56370234", "0.56184214", "0.5610913", "0.5607003", "0.5596761", "0.5593157", "0.553603", "0.55231863", "0.5490034", "0.5489189", "0.54752755", "0.54540265", "0.5444684", "0.54352313", "0.5428609", "0.5424506", "0.5416346", "0.54115444", "0.5404192", "0.53816754", "0.53729844", "0.53625596", "0.5359278", "0.5355072", "0.53319824", "0.5325739", "0.5318809", "0.53167176", "0.5296495", "0.5292911", "0.5292911", "0.5292911", "0.5292911", "0.5292911", "0.52774394", "0.5262107", "0.5256339", "0.5236707", "0.52241164", "0.5216621", "0.5214782", "0.52105457", "0.52105457", "0.5210193", "0.5194839", "0.5165204", "0.51560783", "0.51458424", "0.5132508", "0.5112382", "0.51109123", "0.5103787", "0.50774044", "0.50763", "0.50732994", "0.50714123", "0.50714123", "0.50655925", "0.5056732", "0.503487", "0.50322866", "0.5027155", "0.5018057", "0.4989485", "0.4986394", "0.4984169", "0.49797314", "0.4979725", "0.49755245", "0.4974814" ]
0.62361306
4
Validate an S3 bucket
function validateS3BucketName(name, sslVhost = false) { // http://docs.aws.amazon.com/AmazonS3/latest/dev/BucketRestrictions.html // Bucket names must be at least 3 and no more than 63 characters long. if (name.length < 3 || name.length > 63) { return false; } // Bucket names must be a series of one or more labels. Adjacent labels are // separated by a single period (.). Bucket names can contain lowercase // letters, numbers, and hyphens. Each label must start and end with a // lowercase letter or a number. if (/\.\./.exec(name) || /^[^a-z0-9]/.exec(name) || /[^a-z0-9]$/.exec(name)) { return false; }; if (! /^[a-z0-9-\.]*$/.exec(name)) { return false; } //Bucket names must not be formatted as an IP address (e.g., 192.168.5.4) // https://www.safaribooksonline.com/library/view/regular-expressions-cookbook/9780596802837/ch07s16.html if (/^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/.exec(name)) { return false; } // When using virtual hosted–style buckets with SSL, the SSL wild card // certificate only matches buckets that do not contain periods. To work // around this, use HTTP or write your own certificate verification logic. if (sslVhost) { if (/\./.exec(name)) { return false; } } return true; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function validateBucket(name) {\n if (!validBucketRe.test(name)) {\n throw new Error(`invalid bucket name: ${name}`);\n }\n}", "function CfnStreamingDistribution_S3OriginPropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n errors.collect(cdk.propertyValidator('domainName', cdk.requiredValidator)(properties.domainName));\n errors.collect(cdk.propertyValidator('domainName', cdk.validateString)(properties.domainName));\n errors.collect(cdk.propertyValidator('originAccessIdentity', cdk.requiredValidator)(properties.originAccessIdentity));\n errors.collect(cdk.propertyValidator('originAccessIdentity', cdk.validateString)(properties.originAccessIdentity));\n return errors.wrap('supplied properties not correct for \"S3OriginProperty\"');\n}", "function CfnDataSource_S3PathPropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n if (typeof properties !== 'object') {\n errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.stringify(properties)));\n }\n errors.collect(cdk.propertyValidator('bucket', cdk.requiredValidator)(properties.bucket));\n errors.collect(cdk.propertyValidator('bucket', cdk.validateString)(properties.bucket));\n errors.collect(cdk.propertyValidator('key', cdk.requiredValidator)(properties.key));\n errors.collect(cdk.propertyValidator('key', cdk.validateString)(properties.key));\n return errors.wrap('supplied properties not correct for \"S3PathProperty\"');\n}", "function CfnFunction_S3LocationPropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n errors.collect(cdk.propertyValidator('bucket', cdk.requiredValidator)(properties.bucket));\n errors.collect(cdk.propertyValidator('bucket', cdk.validateString)(properties.bucket));\n errors.collect(cdk.propertyValidator('key', cdk.requiredValidator)(properties.key));\n errors.collect(cdk.propertyValidator('key', cdk.validateString)(properties.key));\n errors.collect(cdk.propertyValidator('version', cdk.validateNumber)(properties.version));\n return errors.wrap('supplied properties not correct for \"S3LocationProperty\"');\n}", "function CfnDatastore_CustomerManagedS3StoragePropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n if (typeof properties !== 'object') {\n errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.stringify(properties)));\n }\n errors.collect(cdk.propertyValidator('bucket', cdk.requiredValidator)(properties.bucket));\n errors.collect(cdk.propertyValidator('bucket', cdk.validateString)(properties.bucket));\n errors.collect(cdk.propertyValidator('keyPrefix', cdk.validateString)(properties.keyPrefix));\n return errors.wrap('supplied properties not correct for \"CustomerManagedS3StorageProperty\"');\n}", "function CfnApi_S3LocationPropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n errors.collect(cdk.propertyValidator('bucket', cdk.requiredValidator)(properties.bucket));\n errors.collect(cdk.propertyValidator('bucket', cdk.validateString)(properties.bucket));\n errors.collect(cdk.propertyValidator('key', cdk.requiredValidator)(properties.key));\n errors.collect(cdk.propertyValidator('key', cdk.validateString)(properties.key));\n errors.collect(cdk.propertyValidator('version', cdk.requiredValidator)(properties.version));\n errors.collect(cdk.propertyValidator('version', cdk.validateNumber)(properties.version));\n return errors.wrap('supplied properties not correct for \"S3LocationProperty\"');\n}", "function parseBucketName(bucket) {\r\n // Amazon S3 - <bucket>.s3.amazonaws.com\r\n if (/[a-zA-Z0-9-\\.]*\\.(s3|s3-.*).amazonaws.com/g.test(bucket.hostname)) {\r\n bucketName = bucket.hostname.replace(/\\.(s3|s3-.*)\\.amazonaws\\.com/g, '');\r\n return bucketName;\r\n }\r\n // Amazon S3 - s3.amazonaws.com/<bucket> || s3-<region>.amazonaws.com/<bucket>\r\n if (/(s3-[a-zA-Z0-9-]*|s3)\\.([a-zA-Z0-9-]*\\.com|[a-zA-Z0-9-]*\\.amazonaws\\.com)\\/.*/g.test(bucket.hostname + bucket.pathname)) {\r\n a = bucket.pathname.split(\"/\");\r\n bucketName = a[1];\r\n return bucketName;\r\n }\r\n // Google - <bucket>.storage.googleapis.com\r\n if (/[a-zA-Z0-9-\\.]*\\.storage\\.googleapis\\.com/g.test(bucket.hostname)) {\r\n bucketName = bucket.hostname.replace(/\\.storage\\.googleapis\\.com/g, '');\r\n return bucketName;\r\n }\r\n // Google - storage.googleapiscom/<bucket>\r\n if (/storage.googleapis.com\\/[a-zA-Z0-9-\\.]*/g.test(bucket.hostname + bucket.pathname)) {\r\n a = bucket.pathname.split(\"/\");\r\n bucketName = a[1];\r\n return bucketName;\r\n }\r\n // return false if parsing fails\r\n return false;\r\n}", "function CfnFaq_S3PathPropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n if (typeof properties !== 'object') {\n errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.stringify(properties)));\n }\n errors.collect(cdk.propertyValidator('bucket', cdk.requiredValidator)(properties.bucket));\n errors.collect(cdk.propertyValidator('bucket', cdk.validateString)(properties.bucket));\n errors.collect(cdk.propertyValidator('key', cdk.requiredValidator)(properties.key));\n errors.collect(cdk.propertyValidator('key', cdk.validateString)(properties.key));\n return errors.wrap('supplied properties not correct for \"S3PathProperty\"');\n}", "function CfnDeploymentGroup_S3LocationPropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n if (typeof properties !== 'object') {\n errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.stringify(properties)));\n }\n errors.collect(cdk.propertyValidator('bucket', cdk.requiredValidator)(properties.bucket));\n errors.collect(cdk.propertyValidator('bucket', cdk.validateString)(properties.bucket));\n errors.collect(cdk.propertyValidator('bundleType', cdk.validateString)(properties.bundleType));\n errors.collect(cdk.propertyValidator('eTag', cdk.validateString)(properties.eTag));\n errors.collect(cdk.propertyValidator('key', cdk.requiredValidator)(properties.key));\n errors.collect(cdk.propertyValidator('key', cdk.validateString)(properties.key));\n errors.collect(cdk.propertyValidator('version', cdk.validateString)(properties.version));\n return errors.wrap('supplied properties not correct for \"S3LocationProperty\"');\n}", "function CfnInstanceStorageConfig_S3ConfigPropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n if (typeof properties !== 'object') {\n errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.stringify(properties)));\n }\n errors.collect(cdk.propertyValidator('bucketName', cdk.requiredValidator)(properties.bucketName));\n errors.collect(cdk.propertyValidator('bucketName', cdk.validateString)(properties.bucketName));\n errors.collect(cdk.propertyValidator('bucketPrefix', cdk.requiredValidator)(properties.bucketPrefix));\n errors.collect(cdk.propertyValidator('bucketPrefix', cdk.validateString)(properties.bucketPrefix));\n errors.collect(cdk.propertyValidator('encryptionConfig', CfnInstanceStorageConfig_EncryptionConfigPropertyValidator)(properties.encryptionConfig));\n return errors.wrap('supplied properties not correct for \"S3ConfigProperty\"');\n}", "function CfnFunction_S3LocationPropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n if (typeof properties !== 'object') {\n errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.stringify(properties)));\n }\n errors.collect(cdk.propertyValidator('bucket', cdk.requiredValidator)(properties.bucket));\n errors.collect(cdk.propertyValidator('bucket', cdk.validateString)(properties.bucket));\n errors.collect(cdk.propertyValidator('key', cdk.requiredValidator)(properties.key));\n errors.collect(cdk.propertyValidator('key', cdk.validateString)(properties.key));\n errors.collect(cdk.propertyValidator('version', cdk.validateNumber)(properties.version));\n return errors.wrap('supplied properties not correct for \"S3LocationProperty\"');\n}", "function CfnDistribution_S3OriginConfigPropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n errors.collect(cdk.propertyValidator('originAccessIdentity', cdk.validateString)(properties.originAccessIdentity));\n return errors.wrap('supplied properties not correct for \"S3OriginConfigProperty\"');\n}", "function CfnApi_S3LocationPropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n if (typeof properties !== 'object') {\n errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.stringify(properties)));\n }\n errors.collect(cdk.propertyValidator('bucket', cdk.requiredValidator)(properties.bucket));\n errors.collect(cdk.propertyValidator('bucket', cdk.validateString)(properties.bucket));\n errors.collect(cdk.propertyValidator('key', cdk.requiredValidator)(properties.key));\n errors.collect(cdk.propertyValidator('key', cdk.validateString)(properties.key));\n errors.collect(cdk.propertyValidator('version', cdk.requiredValidator)(properties.version));\n errors.collect(cdk.propertyValidator('version', cdk.validateNumber)(properties.version));\n return errors.wrap('supplied properties not correct for \"S3LocationProperty\"');\n}", "static isS3URL(url) {\n const s3Host =\n game.data.files.s3 &&\n game.data.files.s3 &&\n game.data.files.s3.endpoint &&\n game.data.files.s3.endpoint.host\n ? game.data.files.s3.endpoint.host\n : \"\";\n\n if (s3Host === \"\") return false;\n\n const regex = new RegExp(\"http[s]?://([^.]+)?.?\" + s3Host + \"(.+)\");\n const matches = regex.exec(url);\n\n const activeSource = matches ? \"s3\" : null; // can be data or remote\n const bucket = matches && matches[1] ? matches[1] : null;\n const current = matches && matches[2] ? matches[2] : null;\n\n if (activeSource === \"s3\") {\n return {\n activeSource,\n bucket,\n current,\n };\n } else {\n return false;\n }\n }", "bucketExists(bucket, cb) {\n if (!validateBucketName(bucket)) {\n throw new errors.InvalidateBucketNameException('Invalid bucket name: ' + bucket)\n }\n this.bucketRequest('HEAD', bucket, cb)\n }", "function CfnLayerVersion_S3LocationPropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n if (typeof properties !== 'object') {\n errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.stringify(properties)));\n }\n errors.collect(cdk.propertyValidator('bucket', cdk.requiredValidator)(properties.bucket));\n errors.collect(cdk.propertyValidator('bucket', cdk.validateString)(properties.bucket));\n errors.collect(cdk.propertyValidator('key', cdk.requiredValidator)(properties.key));\n errors.collect(cdk.propertyValidator('key', cdk.validateString)(properties.key));\n errors.collect(cdk.propertyValidator('version', cdk.validateNumber)(properties.version));\n return errors.wrap('supplied properties not correct for \"S3LocationProperty\"');\n}", "__validate(bucket, key) {\n return (!bucket.includes(DELIM)) && (!key.toString().includes(DELIM));\n }", "function CfnDatastore_CustomerManagedS3PropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n if (typeof properties !== 'object') {\n errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.stringify(properties)));\n }\n errors.collect(cdk.propertyValidator('bucket', cdk.requiredValidator)(properties.bucket));\n errors.collect(cdk.propertyValidator('bucket', cdk.validateString)(properties.bucket));\n errors.collect(cdk.propertyValidator('keyPrefix', cdk.validateString)(properties.keyPrefix));\n errors.collect(cdk.propertyValidator('roleArn', cdk.requiredValidator)(properties.roleArn));\n errors.collect(cdk.propertyValidator('roleArn', cdk.validateString)(properties.roleArn));\n return errors.wrap('supplied properties not correct for \"CustomerManagedS3Property\"');\n}", "function CfnFunction_S3EventPropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n errors.collect(cdk.propertyValidator('bucket', cdk.requiredValidator)(properties.bucket));\n errors.collect(cdk.propertyValidator('bucket', cdk.validateString)(properties.bucket));\n errors.collect(cdk.propertyValidator('events', cdk.requiredValidator)(properties.events));\n errors.collect(cdk.propertyValidator('events', cdk.unionValidator(cdk.unionValidator(cdk.validateString), cdk.listValidator(cdk.unionValidator(cdk.validateString))))(properties.events));\n errors.collect(cdk.propertyValidator('filter', CfnFunction_S3NotificationFilterPropertyValidator)(properties.filter));\n return errors.wrap('supplied properties not correct for \"S3EventProperty\"');\n}", "function CfnChannel_CustomerManagedS3PropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n if (typeof properties !== 'object') {\n errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.stringify(properties)));\n }\n errors.collect(cdk.propertyValidator('bucket', cdk.requiredValidator)(properties.bucket));\n errors.collect(cdk.propertyValidator('bucket', cdk.validateString)(properties.bucket));\n errors.collect(cdk.propertyValidator('keyPrefix', cdk.validateString)(properties.keyPrefix));\n errors.collect(cdk.propertyValidator('roleArn', cdk.requiredValidator)(properties.roleArn));\n errors.collect(cdk.propertyValidator('roleArn', cdk.validateString)(properties.roleArn));\n return errors.wrap('supplied properties not correct for \"CustomerManagedS3Property\"');\n}", "function CfnStateMachine_S3LocationPropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n if (typeof properties !== 'object') {\n errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.stringify(properties)));\n }\n errors.collect(cdk.propertyValidator('bucket', cdk.requiredValidator)(properties.bucket));\n errors.collect(cdk.propertyValidator('bucket', cdk.validateString)(properties.bucket));\n errors.collect(cdk.propertyValidator('key', cdk.requiredValidator)(properties.key));\n errors.collect(cdk.propertyValidator('key', cdk.validateString)(properties.key));\n errors.collect(cdk.propertyValidator('version', cdk.validateNumber)(properties.version));\n return errors.wrap('supplied properties not correct for \"S3LocationProperty\"');\n}", "function CfnResourceDataSync_S3DestinationPropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n if (typeof properties !== 'object') {\n errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.stringify(properties)));\n }\n errors.collect(cdk.propertyValidator('bucketName', cdk.requiredValidator)(properties.bucketName));\n errors.collect(cdk.propertyValidator('bucketName', cdk.validateString)(properties.bucketName));\n errors.collect(cdk.propertyValidator('bucketPrefix', cdk.validateString)(properties.bucketPrefix));\n errors.collect(cdk.propertyValidator('bucketRegion', cdk.requiredValidator)(properties.bucketRegion));\n errors.collect(cdk.propertyValidator('bucketRegion', cdk.validateString)(properties.bucketRegion));\n errors.collect(cdk.propertyValidator('kmsKeyArn', cdk.validateString)(properties.kmsKeyArn));\n errors.collect(cdk.propertyValidator('syncFormat', cdk.requiredValidator)(properties.syncFormat));\n errors.collect(cdk.propertyValidator('syncFormat', cdk.validateString)(properties.syncFormat));\n return errors.wrap('supplied properties not correct for \"S3DestinationProperty\"');\n}", "function verifyFileInS3(req, res) {\n function headReceived(err, data) {\n if (err) {\n res.status(500);\n console.log(err);\n res.end(JSON.stringify({error: \"Problem querying S3!\"}));\n }\n else if (expectedMaxSize != null && data.ContentLength > expectedMaxSize) {\n res.status(400);\n res.write(JSON.stringify({error: \"Too big!\"}));\n deleteFile(req.body.bucket, req.body.key, function(err) {\n if (err) {\n console.log(\"Couldn't delete invalid file!\");\n }\n\n res.end();\n });\n }\n else {\n res.end();\n }\n }\n\n callS3(\"head\", {\n bucket: req.body.bucket,\n key: req.body.key\n }, headReceived);\n}", "function CfnFunction_S3EventPropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n if (typeof properties !== 'object') {\n errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.stringify(properties)));\n }\n errors.collect(cdk.propertyValidator('bucket', cdk.requiredValidator)(properties.bucket));\n errors.collect(cdk.propertyValidator('bucket', cdk.validateString)(properties.bucket));\n errors.collect(cdk.propertyValidator('events', cdk.requiredValidator)(properties.events));\n errors.collect(cdk.propertyValidator('events', cdk.unionValidator(cdk.unionValidator(cdk.validateString), cdk.listValidator(cdk.unionValidator(cdk.validateString))))(properties.events));\n errors.collect(cdk.propertyValidator('filter', CfnFunction_S3NotificationFilterPropertyValidator)(properties.filter));\n return errors.wrap('supplied properties not correct for \"S3EventProperty\"');\n}", "function CfnFunction_S3KeyFilterPropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n errors.collect(cdk.propertyValidator('rules', cdk.requiredValidator)(properties.rules));\n errors.collect(cdk.propertyValidator('rules', cdk.listValidator(CfnFunction_S3KeyFilterRulePropertyValidator))(properties.rules));\n return errors.wrap('supplied properties not correct for \"S3KeyFilterProperty\"');\n}", "function CfnFunction_S3KeyFilterPropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n if (typeof properties !== 'object') {\n errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.stringify(properties)));\n }\n errors.collect(cdk.propertyValidator('rules', cdk.requiredValidator)(properties.rules));\n errors.collect(cdk.propertyValidator('rules', cdk.listValidator(CfnFunction_S3KeyFilterRulePropertyValidator))(properties.rules));\n return errors.wrap('supplied properties not correct for \"S3KeyFilterProperty\"');\n}", "function parseS3Url(url) {\n const [bucket, ...keyFragments] = url.replace(S3_PROTOCOL_PREFIX, '').split('/');\n return { bucket, key: keyFragments.join('/') };\n}", "function isAwsS3Path(path) {\n return path && (path.startsWith(s3AwsUrl+'/') || path == s3AwsUrl);\n}", "function createBucket(){\n // Create S3 service object\n s3 = new AWS.S3({apiVersion: '2006-03-01'});\n\n // Create the parameters for calling createBucket\n var bucketParams = {\n Bucket : process.argv[2],\n ACL : 'public-read'\n };\n\n // call S3 to create the bucket\n s3.createBucket(bucketParams, function(err, data) {\n if (err) {\n console.log(\"Error\", err);\n } else {\n console.log(\"Success\", data.Location);\n }\n });\n}", "verifyS3Key(value) {\n let regex = RegExp('^[a-zA-Z0-9 \\-\\'\\/!_.*()]*$');\n return regex.test(value);\n }", "bucketExists(bucketName, cb) {\n if (!isValidBucketName(bucketName)) {\n throw new errors.InvalidBucketNameError('Invalid bucket name: ' + bucketName)\n }\n if (!isFunction(cb)) {\n throw new TypeError('callback should be of type \"function\"')\n }\n var method = 'HEAD'\n this.makeRequest({ method, bucketName }, '', [200], '', false, (err) => {\n if (err) {\n if (err.code == 'NoSuchBucket' || err.code == 'NotFound') {\n return cb(null, false)\n }\n return cb(err)\n }\n cb(null, true)\n })\n }", "function CfnFunction_BucketSAMPTPropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n errors.collect(cdk.propertyValidator('bucketName', cdk.requiredValidator)(properties.bucketName));\n errors.collect(cdk.propertyValidator('bucketName', cdk.validateString)(properties.bucketName));\n return errors.wrap('supplied properties not correct for \"BucketSAMPTProperty\"');\n}", "function putBucketAcl() {\n const putBucketAclParams = {\n Bucket: bucket,\n ACL: 'authenticated-read',\n };\n s3Client.putBucketAcl(putBucketAclParams, (err, data) => {\n if (err) console.log('err:', err);\n else console.log('data:', data);\n });\n}", "function CfnFunction_BucketSAMPTPropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n if (typeof properties !== 'object') {\n errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.stringify(properties)));\n }\n errors.collect(cdk.propertyValidator('bucketName', cdk.requiredValidator)(properties.bucketName));\n errors.collect(cdk.propertyValidator('bucketName', cdk.validateString)(properties.bucketName));\n return errors.wrap('supplied properties not correct for \"BucketSAMPTProperty\"');\n}", "function CfnDataSource_S3DataSourceConfigurationPropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n if (typeof properties !== 'object') {\n errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.stringify(properties)));\n }\n errors.collect(cdk.propertyValidator('accessControlListConfiguration', CfnDataSource_AccessControlListConfigurationPropertyValidator)(properties.accessControlListConfiguration));\n errors.collect(cdk.propertyValidator('bucketName', cdk.requiredValidator)(properties.bucketName));\n errors.collect(cdk.propertyValidator('bucketName', cdk.validateString)(properties.bucketName));\n errors.collect(cdk.propertyValidator('documentsMetadataConfiguration', CfnDataSource_DocumentsMetadataConfigurationPropertyValidator)(properties.documentsMetadataConfiguration));\n errors.collect(cdk.propertyValidator('exclusionPatterns', cdk.listValidator(cdk.validateString))(properties.exclusionPatterns));\n errors.collect(cdk.propertyValidator('inclusionPatterns', cdk.listValidator(cdk.validateString))(properties.inclusionPatterns));\n errors.collect(cdk.propertyValidator('inclusionPrefixes', cdk.listValidator(cdk.validateString))(properties.inclusionPrefixes));\n return errors.wrap('supplied properties not correct for \"S3DataSourceConfigurationProperty\"');\n}", "function parseS3Arn(arn = '') {\n // arn:aws:s3:::123456789012-study/studies/Organization/org-study-a1/*\n let trimmed = _.trim(arn);\n if (_.isEmpty(arn)) return;\n\n if (!_.startsWith(trimmed, 'arn:')) return;\n\n // Remove the 'arn:' part\n trimmed = trimmed.substring('arn:'.length);\n\n // Get the partition part\n const partition = _.nth(_.split(trimmed, ':'), 0);\n\n // Check if it is still an s3 arn\n if (!_.startsWith(trimmed, `${partition}:s3:::`)) return;\n\n // Remove the partition part\n trimmed = trimmed.substring(`${partition}:s3:::`.length);\n\n // Get the bucket part\n const bucket = _.nth(_.split(trimmed, '/'), 0);\n\n // Check if the bucket is not an empty string\n if (_.isEmpty(bucket)) return;\n\n // Remove the bucket part\n trimmed = trimmed.substring(bucket.length);\n\n let prefix = '/';\n if (!_.isEmpty(trimmed)) {\n prefix = chopLeft(trimmed, '/');\n prefix = chopRight(prefix, '*');\n prefix = _.endsWith(prefix, '/') ? prefix : `${prefix}/`;\n }\n\n // eslint-disable-next-line consistent-return\n return {\n awsPartition: partition,\n bucket,\n prefix,\n };\n}", "function CfnDataset_S3DestinationConfigurationPropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n if (typeof properties !== 'object') {\n errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.stringify(properties)));\n }\n errors.collect(cdk.propertyValidator('bucket', cdk.requiredValidator)(properties.bucket));\n errors.collect(cdk.propertyValidator('bucket', cdk.validateString)(properties.bucket));\n errors.collect(cdk.propertyValidator('glueConfiguration', CfnDataset_GlueConfigurationPropertyValidator)(properties.glueConfiguration));\n errors.collect(cdk.propertyValidator('key', cdk.requiredValidator)(properties.key));\n errors.collect(cdk.propertyValidator('key', cdk.validateString)(properties.key));\n errors.collect(cdk.propertyValidator('roleArn', cdk.requiredValidator)(properties.roleArn));\n errors.collect(cdk.propertyValidator('roleArn', cdk.validateString)(properties.roleArn));\n return errors.wrap('supplied properties not correct for \"S3DestinationConfigurationProperty\"');\n}", "function normalizeBucketArn(s3Arn) {\n const parsed = parseS3Arn(s3Arn);\n if (_.isEmpty(parsed)) return s3Arn;\n\n const { awsPartition, bucket } = parsed;\n\n return `arn:${awsPartition}:s3:::${bucket}`;\n}", "function CfnFunction_S3KeyFilterRulePropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n errors.collect(cdk.propertyValidator('name', cdk.requiredValidator)(properties.name));\n errors.collect(cdk.propertyValidator('name', cdk.validateString)(properties.name));\n errors.collect(cdk.propertyValidator('value', cdk.requiredValidator)(properties.value));\n errors.collect(cdk.propertyValidator('value', cdk.validateString)(properties.value));\n return errors.wrap('supplied properties not correct for \"S3KeyFilterRuleProperty\"');\n}", "function uploadFileIntoBucket(){\n // Create S3 service object\n s3 = new AWS.S3({apiVersion: '2006-03-01'});\n\n // call S3 to retrieve upload file to specified bucket\n var uploadParams = {Bucket: process.argv[2], Key: '', Body: ''};\n var file = process.argv[3];\n\n // Configure the file stream and obtain the upload parameters\n var fs = require('fs');\n var fileStream = fs.createReadStream(file);\n fileStream.on('error', function(err) {\n console.log('File Error', err);\n });\n\n uploadParams.Body = fileStream;\n var path = require('path');\n uploadParams.Key = path.basename(file);\n\n // call S3 to retrieve upload file to specified bucket\n s3.upload (uploadParams, function (err, data) {\n if (err) {\n console.log(\"Error\", err);\n } if (data) {\n console.log(\"Upload Success\", data.Location);\n }\n });\n}", "function CfnFunction_S3NotificationFilterPropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n errors.collect(cdk.propertyValidator('s3Key', cdk.requiredValidator)(properties.s3Key));\n errors.collect(cdk.propertyValidator('s3Key', CfnFunction_S3KeyFilterPropertyValidator)(properties.s3Key));\n return errors.wrap('supplied properties not correct for \"S3NotificationFilterProperty\"');\n}", "function parseBucketName(url) {\n\n let bucket;\n let object;\n\n if (url.startsWith(\"gs://\")) {\n const i = url.indexOf('/', 5);\n if (i >= 0) {\n bucket = url.substring(5, i);\n const qIdx = url.indexOf('?');\n object = (qIdx < 0) ? url.substring(i + 1) : url.substring(i + 1, qIdx);\n }\n\n } else if (url.startsWith(\"https://storage.googleapis.com\") || url.startsWith(\"https://storage.cloud.google.com\")) {\n const bucketIdx = url.indexOf(\"/v1/b/\", 8)\n if (bucketIdx > 0) {\n const objIdx = url.indexOf(\"/o/\", bucketIdx);\n if (objIdx > 0) {\n const queryIdx = url.indexOf(\"?\", objIdx);\n bucket = url.substring(bucketIdx + 6, objIdx);\n object = queryIdx > 0 ? url.substring(objIdx + 3, queryIdx) : url.substring(objIdx + 3);\n }\n\n } else {\n const idx1 = url.indexOf(\"/\", 8);\n const idx2 = url.indexOf(\"/\", idx1+1);\n const idx3 = url.indexOf(\"?\", idx2);\n if (idx2 > 0) {\n bucket = url.substring(idx1+1, idx2);\n object = idx3 < 0 ? url.substring(idx2+1) : url.substring(idx2+1, idx3);\n }\n }\n\n } else if (url.startsWith(\"https://www.googleapis.com/storage/v1/b\")) {\n const bucketIdx = url.indexOf(\"/v1/b/\", 8);\n const objIdx = url.indexOf(\"/o/\", bucketIdx);\n if (objIdx > 0) {\n const queryIdx = url.indexOf(\"?\", objIdx);\n bucket = url.substring(bucketIdx + 6, objIdx);\n object = queryIdx > 0 ? url.substring(objIdx + 3, queryIdx) : url.substring(objIdx + 3);\n }\n }\n\n if (bucket && object) {\n return {\n bucket, object\n }\n } else {\n throw Error(`Unrecognized Google Storage URI: ${url}`)\n }\n\n}", "function CfnFunction_S3KeyFilterRulePropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n if (typeof properties !== 'object') {\n errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.stringify(properties)));\n }\n errors.collect(cdk.propertyValidator('name', cdk.requiredValidator)(properties.name));\n errors.collect(cdk.propertyValidator('name', cdk.validateString)(properties.name));\n errors.collect(cdk.propertyValidator('value', cdk.requiredValidator)(properties.value));\n errors.collect(cdk.propertyValidator('value', cdk.validateString)(properties.value));\n return errors.wrap('supplied properties not correct for \"S3KeyFilterRuleProperty\"');\n}", "function insertBucket() {\n resource = {\n 'name': BUCKET\n };\n\n var request = gapi.client.storage.buckets.insert({\n 'project': PROJECT,\n 'resource': resource\n });\n executeRequest(request, 'insertBucket');\n}", "presignedPutObject(bucketName, objectName, expires, cb) {\n if (!isValidBucketName(bucketName)) {\n throw new errors.InvalidBucketNameError(`Invalid bucket name: ${bucketName}`)\n }\n if (!isValidObjectName(objectName)) {\n throw new errors.InvalidObjectNameError(`Invalid object name: ${objectName}`)\n }\n return this.presignedUrl('PUT', bucketName, objectName, expires, cb)\n }", "function CfnConnector_S3LogDeliveryPropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n if (typeof properties !== 'object') {\n errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.stringify(properties)));\n }\n errors.collect(cdk.propertyValidator('bucket', cdk.validateString)(properties.bucket));\n errors.collect(cdk.propertyValidator('enabled', cdk.requiredValidator)(properties.enabled));\n errors.collect(cdk.propertyValidator('enabled', cdk.validateBoolean)(properties.enabled));\n errors.collect(cdk.propertyValidator('prefix', cdk.validateString)(properties.prefix));\n return errors.wrap('supplied properties not correct for \"S3LogDeliveryProperty\"');\n}", "function CfnReceiptRule_S3ActionPropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n if (typeof properties !== 'object') {\n errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.stringify(properties)));\n }\n errors.collect(cdk.propertyValidator('bucketName', cdk.requiredValidator)(properties.bucketName));\n errors.collect(cdk.propertyValidator('bucketName', cdk.validateString)(properties.bucketName));\n errors.collect(cdk.propertyValidator('kmsKeyArn', cdk.validateString)(properties.kmsKeyArn));\n errors.collect(cdk.propertyValidator('objectKeyPrefix', cdk.validateString)(properties.objectKeyPrefix));\n errors.collect(cdk.propertyValidator('topicArn', cdk.validateString)(properties.topicArn));\n return errors.wrap('supplied properties not correct for \"S3ActionProperty\"');\n}", "function uploadS3File(bucketName, fileName, data, callback) {\n var params = {\n Bucket: bucketName,\n Key: fileName,\n Body: data,\n ACL: 'public-read', // TODO: find way to restrict access to this lambda function\n };\n s3.upload(params, function(err, data) {\n callback(err, data);\n });\n}", "function checkBucketConfig(config) {\n assert(config.bucket,\n '[egg-oss] Must set `bucket` in ess\\'s config');\n assert(config.ess_public_key && config.ess_private_key,\n '[egg-oss] Must set `ess_public_key` and `ess_private_key` in ess\\'s config');\n\n // if (config.endpoint && RE_HTTP_PROTOCOL.test(config.endpoint)) {\n // config.endpoint = config.endpoint.replace(RE_HTTP_PROTOCOL, '');\n // }\n}", "function CfnFunction_S3NotificationFilterPropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n if (typeof properties !== 'object') {\n errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.stringify(properties)));\n }\n errors.collect(cdk.propertyValidator('s3Key', cdk.requiredValidator)(properties.s3Key));\n errors.collect(cdk.propertyValidator('s3Key', CfnFunction_S3KeyFilterPropertyValidator)(properties.s3Key));\n return errors.wrap('supplied properties not correct for \"S3NotificationFilterProperty\"');\n}", "function s3Upload(files, bucketName, objectKeyPrefix, iamUserKey, iamUserSecret, callback) {\n var s3 = new AWS.S3({\n bucket: bucketName,\n accessKeyId: iamUserKey,\n secretAccessKey: iamUserSecret,\n apiVersion: '2006-03-01',\n });\n\n // s3.abortMultipartUpload(params, function (err, data) {\n // if (err) console.log(err, err.stack); // an error occurred\n // else console.log(data); // successful response\n // });\n\n // Setup the objects to upload to S3 & map the results into files\n var results = files.map(function(file) {\n // Upload file to bucket with name of Key\n s3.upload({\n Bucket: bucketName,\n Key: objectKeyPrefix + file.originalname, // Prefix should have \".\" on each end\n Body: file.buffer,\n ACL: 'public-read' // TODO: CHANGE THIS & READ FROM CLOUDFRONT INSTEAD\n },\n function(error, data) {\n // TODO: Maybe refine this to show only data care about elsewhere\n if(error) {\n console.log(\"Error uploading file to S3: \", error);\n return {error: true, data: error};\n } else {\n console.log('File uploaded. Data is:', data);\n return {error: false, data: data};\n }\n });\n });\n\n callback(results); // Results could be errors or successes\n}", "function publicReadPolicyForBucket(bucketName) {\n return {\n Version: \"2012-10-17\",\n Statement: [{\n Effect: \"Allow\",\n Principal: \"*\",\n Action: [\n \"s3:GetObject\"\n ],\n Resource: [\n `arn:aws:s3:::${bucketName}/*` // policy refers to bucket name explicitly\n ]\n }]\n };\n}", "async function createS3Bucket(s3, name, region, acl, lifecycleDays = 1) {\n assert(s3);\n assert(name);\n assert(region);\n assert(acl);\n assert(typeof lifecycleDays === 'number');\n if (!validateS3BucketName(name, true)) {\n throw new Error(`Bucket ${name} is not valid`);\n }\n\n let params = {\n Bucket: name,\n ACL: acl,\n };\n\n if (region !== 'us-east-1') {\n params.CreateBucketConfiguration = {\n LocationConstraint: region,\n };\n }\n\n try {\n debug(`Creating S3 Bucket ${name} in ${region}`);\n await s3.createBucket(params).promise();\n debug(`Created S3 Bucket ${name} in ${region}`);\n } catch (err) {\n switch (err.code) {\n case 'BucketAlreadyExists':\n case 'BucketAlreadyOwnedByYou':\n break;\n default:\n throw err;\n }\n }\n\n params = {\n Bucket: name,\n LifecycleConfiguration: {\n Rules: [\n {\n ID: region + '-' + lifecycleDays + '-day',\n Prefix: '',\n Status: 'Enabled',\n Expiration: {\n Days: lifecycleDays,\n },\n },\n ],\n },\n };\n\n debug(`Setting S3 lifecycle configuration for ${name} in ${region}`);\n await s3.putBucketLifecycleConfiguration(params).promise();\n debug(`Set S3 lifecycle configuration for ${name} in ${region}`);\n}", "presignedPutObject(bucketName, objectName, expires) {\n if (!validateBucketName(bucketName)) {\n throw new errors.InvalidateBucketNameException('Invalid bucket name: ' + bucketName)\n }\n if (objectName === null || objectName.trim() === '') {\n throw new errors.InvalidObjectNameException('Object name cannot be empty')\n }\n var requestParams = {\n host: this.params.host,\n port: this.params.port,\n protocol: this.params.protocol,\n path: `/${bucketName}/${uriResourceEscape(objectName)}`,\n method: 'PUT',\n expires: expires\n }\n return presignSignatureV4(requestParams, this.params.accessKey, this.params.secretKey)\n }", "function normalizeS3Arn(s3Arn) {\n const parsed = parseS3Arn(s3Arn);\n if (_.isEmpty(parsed)) return s3Arn;\n\n const { awsPartition, bucket, prefix } = parsed;\n\n return prefix === '/' ? `arn:${awsPartition}:s3:::${bucket}/` : `arn:${awsPartition}:s3:::${bucket}/${prefix}`;\n}", "function getBucketAcl() {\n const getBucketAclParams = {\n Bucket: bucket,\n };\n s3Client.getBucketAcl(getBucketAclParams, (err, data) => {\n if (err) console.log('err:', err);\n else console.log('data:', JSON.stringify(data));\n });\n}", "async init() {\n this.debug(`creating ${this.bucket}`);\n await createS3Bucket(this.s3, this.bucket, this.region, this.acl, this.lifespan);\n this.debug(`creating ${this.bucket}`);\n }", "function upload_private_S3_resource(file, folder, cFunc) {\n\tvar xhr = new XMLHttpRequest();\n\t// var amz_sign_s3 is defined in script on HTML page\n\txhr.open(\"GET\", amz_sign_s3+\"?file_name=\"+file.name+\"&file_type=\"+file.type+\"&folder=\"+folder);\n\txhr.onreadystatechange = function(){\n\t\tif(xhr.readyState === 4){\n\t\t\tif(xhr.status === 200){\n\t\t\t\tvar response = JSON.parse(xhr.responseText);\n\t\t\t\tupload_file(file, response.signed_request, response.url, cFunc);\n\t\t\t}\n\t\t\telse{\n\t\t\t\talert(\"Could not get signed URL.\");\n\t\t\t}\n\t\t}\n\t};\n\txhr.send();\n}", "function uploadToS3(file) {\n let s3bucket = new AWS.S3({\n accessKeyId: ACCESS,\n secretAccessKey: SECRET,\n Bucket: BUCKET_NAME,\n });\n s3bucket.createBucket(function () {\n var params = {\n Bucket: BUCKET_NAME,\n Key: file.name,\n Body: file.data,\n };\n s3bucket.upload(params, function (err, data) {\n if (err) {\n console.log(\"error in callback\");\n console.log(err);\n }\n console.log(\"success\");\n console.log(data);\n });\n });\n}", "function uploadFileIntoFolderOfBucket(){\n // Create S3 service object\n s3 = new AWS.S3({apiVersion: '2006-03-01'});\n\n // call S3 to retrieve upload file to specified bucket\n var uploadParams = {Bucket: process.argv[2], Key: '', Body: ''};\n var file = process.argv[4];\n\n // Configure the file stream and obtain the upload parameters\n var fs = require('fs');\n var fileStream = fs.createReadStream(file);\n fileStream.on('error', function(err) {\n console.log('File Error', err);\n });\n\n uploadParams.Body = fileStream;\n var path = require('path');\n uploadParams.Key = process.argv[3]+\"/\"+path.basename(file);\n\n // call S3 to retrieve upload file to specified bucket\n s3.upload (uploadParams, function (err, data) {\n if (err) {\n console.log(\"Error\", err);\n } if (data) {\n console.log(\"Upload Success\", data.Location);\n }\n });\n}", "function InitAWSConfigurations()\n{\n bucketName = $(\"#hdnBucketName\").val();\n\n bucketStartURL = $(\"#hdnBucketStartURL\").val();\n\n AWS.config.update({\n accessKeyId: $(\"#hdnAWSAccessKey\").val(),\n secretAccessKey: $(\"#hdnAWSSecretKey\").val(),\n region: $(\"#hdnBucketRegion\").val()\n\n });\n\n\n bucket = new AWS.S3({\n params: { Bucket: bucketName }\n });\n // s3 = new AWS.S3();\n\n /****Image upload path initializations****/\n\n userProfileImagePath = $(\"#hdnUserProfileImagePath\").val();\n otherUserProfileFilePath = $(\"#hdnOtherUserProfileFilePath\").val();\n\n\n /***************************************/\n\n}", "function publicReadPolicyForBucket(bucketName) {\n return JSON.stringify({\n Version: \"2012-10-17\",\n Statement: [{\n Effect: \"Allow\",\n Principal: \"*\",\n Action: [\n \"s3:GetObject\"\n ],\n Resource: [\n `arn:aws:s3:::${bucketName}/*` // policy refers to bucket name explicitly\n ]\n }]\n })\n }", "function check_if_the_bucket_exists(container)\n{\n\treturn new Promise(function(resolve, reject) {\n\n\t\t//\n\t\t// 1. List all buckets.\n\t\t//\n\t\ts3.listBuckets(function(req_error, data) {\n\n\t\t\t//\n\t\t\t// 1. Check for an error.\n\t\t\t//\n\t\t\tif(req_error)\n\t\t\t{\n\t\t\t\treturn reject(req_error);\n\t\t\t}\n\n\t\t\t//\n\t\t\t// 2. Create a variable that will help us understand if the bucket\n\t\t\t// that we care about exists.\n\t\t\t//\n\t\t\tlet was_bucket_found = false;\n\n\t\t\t//\n\t\t\t// 3. Loop over the buckets that we got back to see if there is\n\t\t\t// the one that we care about.\n\t\t\t//\n\t\t\tfor(let index in data.Buckets)\n\t\t\t{\n\t\t\t\t//\n\t\t\t\t// 1. Compare each bucket with what we want.\n\t\t\t\t//\n\t\t\t\tif(\"repos.dev\" == data.Buckets[index].Name)\n\t\t\t\t{\n\t\t\t\t\twas_bucket_found = true;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t//\n\t\t\t// 4. Check if the bucket still exists before we try to save to\n\t\t\t// it.\n\t\t\t//\n\t\t\tif(!was_bucket_found)\n\t\t\t{\n\t\t\t\tlet error = new Error(\"The bucket with the repos disappeared\");\n\n\t\t\t\treturn reject(error);\n\t\t\t}\n\n\t\t\t//\n\t\t\t// -> Move to the next chain.\n\t\t\t//\n\t\t\treturn resolve(container);\n\n\t\t});\n\n\t});\n}", "function s3_upload_img(extension, file_in, try_in){\n var trynum = try_in;\n filename = file_in;\n var s3upload = new S3Upload({\n file_dom_selector: 'img_file',\n s3_sign_put_url: '/sign_s3_put/',\n s3_object_name: filename,\n onProgress: function(percent, message) {\n $('#img_status').text(\"Uploading: \" + percent + \"%\");\n },\n onFinishS3Put: function(url) {\n $(\"#id_img_url\").val(url);\n $('#image_preview').attr('src', url);\n enable_button();\n },\n onError: function(status) {\n if(trynum < 1){ //amount of tries\n console.log(\"upload error #\" + trynum + \" of type \" + status + \", retrying..\");\n trynum++;\n s3_upload_img(extension, file_in, trynum);\n }\n else{\n console.log(\"upload error #\" + trynum + \", giving up.\");\n $('#img_status').html('Upload error: ' + status);\n }\n }\n });\n}", "setBucketACL(bucket, acl, cb) {\n if (!validateBucketName(bucket)) {\n throw new errors.InvalidateBucketNameException('Invalid bucket name: ' + bucket)\n }\n\n if (acl === null || acl.trim() === '') {\n throw new errors.InvalidEmptyACLException('Acl name cannot be empty')\n }\n\n // we should make sure to set this query parameter, but on the other hand\n // the call apparently succeeds without it to s3. For clarity lets do it anyways\n var query = `?acl`,\n requestParams = {\n host: this.params.host,\n port: this.params.port,\n protocol: this.params.protocol,\n method: 'PUT',\n path: `/${bucket}${query}`,\n headers: {\n 'x-amz-acl': acl\n }\n }\n\n signV4(requestParams, '', this.params.accessKey, this.params.secretKey)\n\n var req = this.transport.request(requestParams, response => {\n var concater = transformers.getConcater()\n var errorTransformer = transformers.getErrorTransformer(response)\n if (response.statusCode !== 200) {\n pipesetup(response, concater, errorTransformer)\n .on('error', e => cb(e))\n return\n }\n cb()\n })\n // FIXME: the below line causes weird failure in 'gulp test'\n // req.on('error', e => cb(e))\n req.end()\n }", "function S3ObjectClass(configuration, createUploadRequestNamesFunction, redisClient)\n{\n\tvar self = this;\n\n\t//grab bucketname from config file\n\tvar bucketName = configuration.bucket;\n\tvar uploadExpiration = configuration.expires || 15*60;\n\n\tself.s3 = new AWS.S3({params: {Bucket: bucketName}, computeChecksums: false});\n\n\t//example for outside use or testing -- helpful if i forget my function logic later--or someone checking around from the outside\n\tself.requestFunctionExample = exampleUploadRequestFunction;\n\tself.createUploadRequests = createUploadRequestNamesFunction;\n\n\tself.uploadErrors = {\n\t\tnullUploadKey : 0,\n\t\tredisError : 1,\n\t\theadCheckUnfulfilledError : 2,\n\t\theadCheckMissingError : 3,\n\t\tredisDeleteError : 4\n\t}\n\n\n\tself.generateObjectAccess = function(fileLocations)\n\t{\n\n\t\t//we create a map of signed URLs\n\t\tvar fileAccess = {};\n\n\t\tfor(var i=0; i < fileLocations.length; i++)\n\t\t{\n\t\t\tvar fLocation = fileLocations[i];\n\n\t\t\tvar signedURLReq = {\n\t\t\t\tBucket: bucketName, \n\t\t\t\tKey: fLocation,\n\t\t\t\tExpires: uploadExpiration,\n\t\t\t};\n\n\t\t\tvar signed = self.s3.getSignedUrl('getObject', signedURLReq);\n\n\t\t\tfileAccess[fLocation] = signed;\n\t\t}\n\n\t\treturn fileAccess;\n\t}\n\n\t//in case the upload properties are failures\n\tself.asyncConfirmUploadComplete = function(uuid)\n\t{\n\t\tvar defer = Q.defer();\n\n\t\tvar isOver = false;\n\n\t\t//we have the uuid, lets fetch the existing request\n\t\tasyncRedisGet(uuid)\n\t\t\t.then(function(val)\n\t\t\t{\n\t\t\t\t//if we don't have a value -- the key doesn't exist or expired -- either way, it's a failure!\n\t\t\t\tif(!val)\n\t\t\t\t{\n\t\t\t\t\t//we're all done -- we didn't encounter an error, we just don't exist -- time to resubmit\n\t\t\t\t\tdefer.resolve({success: false, error: self.uploadErrors.nullUploadKey});\n\t\t\t\t\tisOver = true;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\t//so we have our object\n\t\t\t\tvar putRequest = JSON.parse(val);\n\n\t\t\t\t//these are all the requests we made\n\t\t\t\tvar allUploads = putRequest.uploads;\n\n\t\t\t\t//we have to check on all the objects\n\t\t\t\tvar uploadConfirmPromises = [];\n\n\t\t\t\tfor(var i=0; i < allUploads.length; i++)\n\t\t\t\t{\n\t\t\t\t\tvar req = allUploads[i].request;\n\n\t\t\t\t\tvar params = {Bucket: req.Bucket, Key: req.Key};\n\n\t\t\t\t\tuploadConfirmPromises.push(asyncHeadRequest(params));\n\t\t\t\t}\n\n\t\t\t\treturn Q.allSettled(uploadConfirmPromises);\n\t\t\t})\n\t\t\t.then(function(results)\n\t\t\t{\n\t\t\t\tif(isOver)\n\t\t\t\t\treturn;\n\n\t\t\t\t//check for existance\n\t\t\t\tvar missing = [];\n\n\t\t\t\t//now we have all the results -- we verify they're all fulfilled\n\t\t\t\tfor(var i=0; i < results.length; i++)\n\t\t\t\t{\n\t\t\t\t\tvar res = results[i];\n\t\t\t\t\tif(res.state !== \"fulfilled\")\n\t\t\t\t\t{\n\t\t\t\t\t\t// console.log(\"Results:\".red,results);\n\n\t\t\t\t\t\tdefer.resolve({success: false, error: self.uploadErrors.headCheckUnfulfilledError});\n\t\t\t\t\t\tisOver = true;\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\n\t\t\t\t\t//if one is false, we're all false\n\t\t\t\t\tif(!res.value.exists)\n\t\t\t\t\t\tmissing.push(i);\n\n\t\t\t\t}\n\n\t\t\t\t//are we missing anything???\n\t\t\t\tif(missing.length)\n\t\t\t\t{\n\t\t\t\t\tdefer.resolve({success: false, error: self.uploadErrors.headCheckMissingError, missing: missing});\n\t\t\t\t\tisOver = true;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\t//we're all confirmed, we delete the upload requests now\n\t\t\t\t//however, this is not a major concern -- it will expire shortly anyways\n\t\t\t\t//therefore, we resolve first, then delete second\n\n\t\t\t\tisOver = true;\n\t\t\t\tdefer.resolve({success: true});\n\n\t\t\t\t//if we're here, then we all exist -- it's confirmed yay!\n\t\t\t\t//we need to remove the key from our redis client -- but we're not too concerned -- they expire when they expire\n\t\t\t\treturn;//asyncRedisDelete(uuid);\n\t\t\t})\n\t\t\t.catch(function(err)\n\t\t\t{\n\t\t\t\tif(isOver)\n\t\t\t\t\treturn;\n\n\t\t\t\tdefer.reject(err);\n\t\t\t});\n\n\t\treturn defer.promise;\n\t}\n\n\tfunction asyncHeadRequest(params)\n\t{\n\t\tvar defer = Q.defer();\n\n\t\tself.s3.headObject(params, function (err, metadata) { \n\t\t\tif (err)\n\t\t\t{\n\t\t\t\t//error code is not found -- it doesn't exist!\n\t\t\t\tif(err.code === 'NotFound') { \n\t\t\t \t// Handle no object on cloud here \n\t\t\t\t\tdefer.resolve({exists: false});\n\t\t\t\t} \n\t\t\t\t//straight error -- reject\n\t\t\t\telse \n\t\t\t\t\tdefer.reject(err);\n\n\t\t\t}else { \n\t\t\t\tdefer.resolve({exists: true});\n\t\t\t}\n\t\t});\n\n\t\treturn defer.promise;\n\t}\n\n\n\tself.asyncInitializeUpload = function(uploadProperties)\n\t{\t\n\t\t//we promise to return\n\t\tvar defer = Q.defer();\n\n\t\t//create a unique ID for this upload\n\t\tvar uuid = cuid();\n\n\t\t//we send our upload properties onwards\n\t\tvar requestUploads = self.createUploadRequests(uploadProperties);\n\n\t\t//we now have a number of requests to make\n\t\t//lets process them and get some signed urls to put the objects there\n\t\tvar fullUploadRequests = [];\n\n\t\t//these will be everything we need to make a signed URL request\n\t\tfor(var i=0; i < requestUploads.length; i++)\n\t\t{\n\n\t\t\t//\n\t\t\tvar upReqName = requestUploads[i];\n\n\t\t\tvar signedURLReq = {\n\t\t\t\tBucket: bucketName, \n\t\t\t\tKey: upReqName.prepend + uuid + upReqName.append, \n\t\t\t\tExpires: uploadExpiration,\n\t\t\t\t// ACL: 'public-read'\n\t\t\t};\n\n\t\t\tvar signed = self.s3.getSignedUrl('putObject', signedURLReq);\n\n\t\t\t//store the requests here\n\t\t\tfullUploadRequests.push({url: signed, request: signedURLReq});\n\t\t}\n\n\t\t//now we have our full requests\n\t\t//let's store it in REDIS, then send it back\n\n\t\tvar inProgress = {\n\t\t\tuuid: uuid,\n\t\t\tstate : \"pending\",\n\t\t\tuploads: fullUploadRequests\n\t\t};\n\n\t\t//we set the object in our redis location\n\t\tasyncRedisSetEx(uuid, uploadExpiration, JSON.stringify(inProgress))\n\t\t\t.catch(function(err)\n\t\t\t{\n\t\t\t\tdefer.reject(err);\n\t\t\t})\n\t\t\t.done(function()\n\t\t\t{\n\t\t\t\tdefer.resolve(inProgress);\n\t\t\t});\n\n\t\t//promise for now -- return later\n\t\treturn defer.promise;\n\t}\n\n\tfunction asyncRedisSetEx(key, expire, val)\n\t{\n\t\tvar defer = Q.defer();\n\n\t\tredisClient.setex(key, expire, val, function(err)\n\t\t{\n\t\t\tif(!err)\n\t\t\t\tdefer.resolve();\n\t\t\telse\n\t\t\t\tdefer.reject(err);\n\t\t});\n\n\t\treturn defer.promise;\n\t}\n\n\tfunction asyncRedisGet(key, val)\n\t{\n\t\tvar defer = Q.defer();\n\n\t\tredisClient.get(key, function(err, val)\n\t\t{\n\t\t\tif(!err)\n\t\t\t\tdefer.resolve(val);\n\t\t\telse\n\t\t\t\tdefer.reject(err);\n\t\t});\n\n\t\treturn defer.promise;\n\t}\n\n\tfunction asyncRedisDelete(key, val)\n\t{\n\t\tvar defer = Q.defer();\n\n\t\tredisClient.del(key, function(err, reply)\n\t\t{\n\t\t\tif(!err)\n\t\t\t\tdefer.resolve();\n\t\t\telse\n\t\t\t\tdefer.reject(err);\n\t\t});\n\n\t\treturn defer.promise;\n\t}\n\n\treturn self;\n}", "function putObject(keyName) {\n const putObjectParams = {\n Bucket: bucket,\n Key: keyName,\n Metadata: {\n importance: 'very',\n ranking: 'middling',\n },\n Body: 'putMe',\n };\n s3Client.putObject(putObjectParams, (err, data) => {\n if (err) console.log('err:', err);\n else console.log('data:', data);\n });\n}", "static _getS3Instance () {\n s3instance = s3instance || new AWS.S3({ apiVersion: S3_API_VERSION });\n return s3instance;\n }", "async function uploadToS3(bucket, filePath) {\n let params = {\n Bucket: bucket,\n Body: fs.createReadStream(filePath),\n Key: path.basename(filePath)\n };\n\n //Converting async upload function to synchronous\n let s3Upload = Promise.promisify(s3.upload, { context: s3 });\n let uploadResult = await s3Upload(params);\n\n //Throw an error if the upload errored out \n if (!uploadResult.Location || uploadResult.Location.length === 0) {\n throw Error(uploadResult.err);\n }\n}", "function getS3(awsAccessKey, awsSecretKey) {\n return new AWS.S3({\n accessKeyId: awsAccessKey,\n secretAccessKey: awsSecretKey\n });\n}", "function addS3bucket (req, res, next) {\n if (req.params.s3bucket) return next()\n req.params.s3bucket = [process.env.APP_NAME, req.params.appname].join('.')\n next()\n}", "function getObjFromS3(fileName, bucket, callback){\n let params = {Bucket: bucket, Key:fileName};\n s3.getObject(params, function(err, data){\n if(err){\n console.error(\"getObjFromS3 err\",err);\n } else {\n callback(data.Body.toString('utf-8'));\n }\n \n });\n\n}", "function putObject(bucket, key, obkject) {\n\tif (bucket === null) {\n\t\tbucket = constants.defaultBucket;\n\t}\n\n\tvar params = {\n\t\tBucket : bucket, /* required */\n\t\tKey : key, /* required */\n\t\tBody : obkject\n\t};\n\tconsole.log(\"putObject for \" + JSON.stringify(obkject));\n\ts3.putObject(params, function(err, data) {\n\t\tif (err)\n\t\t\tconsole.log(err, err.stack); // an error occurred\n\t\telse\n\t\t\tconsole.log(data); // successful response\n\t});\n}", "async function putS3(fileKey, data) {\n oLog.verbose(__filename, 'putS3');\n\n try {\n if (configs.aws.s3.active) {\n // set aws region:\n rAWS.config.update({\n region: configs.aws.s3.region\n });\n // bucket info:\n let s3Bucket = configs.aws.s3.s3bucket;\n let s3FileKey = fileKey;\n let s3Params = {\n Bucket: s3Bucket,\n Key: s3FileKey,\n Body: data\n };\n\n // get object and parse the JSON:\n return rS3.putObject(s3Params).promise();\n } else {\n // empty object if not active:\n return {};\n }\n } catch (error) {\n oLog.error(__filename, 'putS3', error);\n return error;\n }\n}", "removeBucket(bucket, cb) {\n if (!validateBucketName(bucket)) {\n throw new errors.InvalidateBucketNameException('Invalid bucket name: ' + bucket)\n }\n this.bucketRequest('DELETE', bucket, cb)\n }", "presignedGetObject(bucketName, objectName, expires) {\n if (!validateBucketName(bucketName)) {\n throw new errors.InvalidateBucketNameException('Invalid bucket name: ' + bucketName)\n }\n if (objectName === null || objectName.trim() === '') {\n throw new errors.InvalidObjectNameException('Object name cannot be empty')\n }\n var requestParams = {\n host: this.params.host,\n port: this.params.port,\n protocol: this.params.protocol,\n path: `/${bucketName}/${uriResourceEscape(objectName)}`,\n method: 'GET',\n expires: expires\n }\n return presignSignatureV4(requestParams, this.params.accessKey, this.params.secretKey)\n }", "function CfnAssociation_S3OutputLocationPropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n if (typeof properties !== 'object') {\n errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.stringify(properties)));\n }\n errors.collect(cdk.propertyValidator('outputS3BucketName', cdk.validateString)(properties.outputS3BucketName));\n errors.collect(cdk.propertyValidator('outputS3KeyPrefix', cdk.validateString)(properties.outputS3KeyPrefix));\n errors.collect(cdk.propertyValidator('outputS3Region', cdk.validateString)(properties.outputS3Region));\n return errors.wrap('supplied properties not correct for \"S3OutputLocationProperty\"');\n}", "function before (s3, bucket, keys, done) {\n createBucket(s3, bucket)\n .then(function () {\n return when.all(\n // Swallow deleteObject errors here incase the files don't yet exist\n keys.map(function (key) { return deleteObject(s3, bucket, key).catch(function () {}); })\n )\n }).then(function () { done(); });\n}", "function isValidRestRequest(headerStr, version) {\n if (version === 4) {\n return new RegExp(\"host:\" + expectedHostname).exec(headerStr) != null;\n }\n\n return new RegExp(\"\\/\" + expectedBucket + \"\\/.+$\").exec(headerStr) != null;\n}", "function putS3File(bucketName, fileName, data, callback) {\n var expirationDate = new Date();\n // Assuming a user would not remain active in the same session for over 1 hr.\n expirationDate = new Date(expirationDate.setHours(expirationDate.getHours() + 1));\n var params = {\n Bucket: bucketName,\n Key: fileName,\n Body: data,\n ACL: 'public-read', // TODO: find way to restrict access to this lambda function\n Expires: expirationDate\n };\n s3.putObject(params, function (err, data) {\n callback(err, data);\n });\n}", "function CfnAssetPropsValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n if (typeof properties !== 'object') {\n errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.stringify(properties)));\n }\n errors.collect(cdk.propertyValidator('assetDescription', cdk.validateString)(properties.assetDescription));\n errors.collect(cdk.propertyValidator('assetHierarchies', cdk.listValidator(CfnAsset_AssetHierarchyPropertyValidator))(properties.assetHierarchies));\n errors.collect(cdk.propertyValidator('assetModelId', cdk.requiredValidator)(properties.assetModelId));\n errors.collect(cdk.propertyValidator('assetModelId', cdk.validateString)(properties.assetModelId));\n errors.collect(cdk.propertyValidator('assetName', cdk.requiredValidator)(properties.assetName));\n errors.collect(cdk.propertyValidator('assetName', cdk.validateString)(properties.assetName));\n errors.collect(cdk.propertyValidator('assetProperties', cdk.listValidator(CfnAsset_AssetPropertyPropertyValidator))(properties.assetProperties));\n errors.collect(cdk.propertyValidator('tags', cdk.listValidator(cdk.validateCfnTag))(properties.tags));\n return errors.wrap('supplied properties not correct for \"CfnAssetProps\"');\n}", "async function emptyAndDeleteFolderOfBucket() {\n s3=new AWS.S3({apiVersion: '2006-03-01'});\n const listParams = {\n Bucket:process.argv[2],\n Prefix:process.argv[3]\n };\n\n const listedObjects = await s3.listObjectsV2(listParams).promise();\n\n if (listedObjects.Contents.length === 0) return;\n\n const deleteParams = {\n Bucket: process.argv[2],\n Delete: { Objects: [] }\n };\n\n listedObjects.Contents.forEach(({ Key }) => {\n deleteParams.Delete.Objects.push({ Key });\n });\n\n await s3.deleteObjects(deleteParams).promise();\n\n if (listedObjects.IsTruncated) await emptyAndDeleteFolderOfBucket(process.argv[2], process.argv[3]);\n}", "function uploadToS3(name, file, successCallback, errorCallback, progressCallback) {\n\n if (typeof successCallback != 'function') {\n Ti.API.error('successCallback() is not defined');\n return false;\n }\n\n if (typeof errorCallback != 'function') {\n Ti.API.error('errorCallback() is not defined');\n return false;\n }\n\n var AWSAccessKeyID = 'AKIAJHRVU52E4GKVARCQ';\n var AWSSecretAccessKey = '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';\n var AWSBucketName = 'snapps';\n var AWSHost = AWSBucketName + '.s3.amazonaws.com';\n\n var currentDateTime = formatDate(new Date(),'E, d MMM yyyy HH:mm:ss') + ' ' + getOffsetAsInteger();\n\n var xhr = Ti.Network.createHTTPClient();\n\n xhr.onsendstream = function(e) {\n\n if (typeof debugStartTime != 'number') {\n debugStartTime = new Date().getTime();\n }\n\n debugUploadTime = Math.floor((new Date().getTime() - debugStartTime) / 1000);\n\n var progress = Math.floor(e.progress * 100);\n Ti.API.info('uploading (' + debugUploadTime + 's): ' + progress + '%');\n\n // run progressCallback function when available\n if (typeof progressCallback == 'function') {\n progressCallback(progress);\n }\n\n };\n\n xhr.onerror = function(e) {\n Ti.API.error({ errorlocation: 'onload', error: e, responseText: xhr.responseText, headers: xhr.getResponseHeaders() });\n errorCallback(e);\n };\n\n xhr.onload = function() {\n if (this.status >= 200 && this.status < 300) {\n\n var responseHeaders = xhr.getResponseHeaders();\n\n var filename = name;\n var url = 'https://' + AWSHost + '/' + name;\n\n if (responseHeaders['x-amz-version-id']) {\n url = url + '?versionId=' + responseHeaders['x-amz-version-id'];\n }\n\n successCallback({ url: url });\n }\n else {\n Ti.API.error({ errorlocation: 'onload', error: e, responseText: xhr.responseText, headers: xhr.getResponseHeaders() });\n errorCallback();\n }\n };\n\n //ensure we have time to upload\n xhr.setTimeout(99000);\n\n // An optional boolean parameter, defaulting to true, indicating whether or not to perform the operation asynchronously.\n // If this value is false, the send() method does not return until the response is received. If true, notification of a\n // completed transaction is provided using event listeners. This must be true if the multipart attribute is true, or\n // an exception will be thrown.\n xhr.open('PUT', 'https://' + AWSHost + '/' + name, true);\n\n //var StringToSign = 'PUT\\n\\nmultipart/form-data\\n' + currentDateTime + '\\nx-amz-acl:public-read\\n/' + AWSBucketName + '/' + name;\n var StringToSign = 'PUT\\n\\n\\n' + currentDateTime + '\\nx-amz-acl:public-read\\n/' + AWSBucketName + '/' + name;\n var AWSSignature = b64_hmac_sha1(AWSSecretAccessKey, Utf8.encode(StringToSign));\n var AuthorizationHeader = 'AWS ' + AWSAccessKeyID + ':' + AWSSignature;\n\n xhr.setRequestHeader('Authorization', AuthorizationHeader);\n //xhr.setRequestHeader('Content-Type', 'multipart/form-data');\n xhr.setRequestHeader('X-Amz-Acl', 'public-read');\n xhr.setRequestHeader('Host', AWSHost);\n xhr.setRequestHeader('Date', currentDateTime);\n\n xhr.send(file);\n\n return xhr;\n}", "function CfnChannel_ChannelStoragePropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n if (typeof properties !== 'object') {\n errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.stringify(properties)));\n }\n errors.collect(cdk.propertyValidator('customerManagedS3', CfnChannel_CustomerManagedS3PropertyValidator)(properties.customerManagedS3));\n errors.collect(cdk.propertyValidator('serviceManagedS3', cdk.validateObject)(properties.serviceManagedS3));\n return errors.wrap('supplied properties not correct for \"ChannelStorageProperty\"');\n}", "static fromCfnBucketPolicy(cfnBucketPolicy) {\n try {\n jsiiDeprecationWarnings.aws_cdk_lib_aws_s3_CfnBucketPolicy(cfnBucketPolicy);\n }\n catch (error) {\n if (process.env.JSII_DEBUG !== \"1\" && error.name === \"DeprecationError\") {\n Error.captureStackTrace(error, this.fromCfnBucketPolicy);\n }\n throw error;\n }\n // use a \"weird\" id that has a higher chance of being unique\n const id = '@FromCfnBucketPolicy';\n // if fromCfnBucketPolicy() was already called on this CfnBucketPolicy,\n // return the same L2\n // (as different L2s would conflict, because of the mutation of the document property of the L1 below)\n const existing = cfnBucketPolicy.node.tryFindChild(id);\n if (existing) {\n return existing;\n }\n // resolve the Bucket this Policy references\n let bucket;\n if (core_1.Token.isUnresolved(cfnBucketPolicy.bucket)) {\n const bucketIResolvable = core_1.Tokenization.reverse(cfnBucketPolicy.bucket);\n if (bucketIResolvable instanceof cfn_reference_1.CfnReference) {\n const cfnElement = bucketIResolvable.target;\n if (cfnElement instanceof s3_generated_1.CfnBucket) {\n bucket = bucket_1.Bucket.fromCfnBucket(cfnElement);\n }\n }\n }\n if (!bucket) {\n bucket = bucket_1.Bucket.fromBucketName(cfnBucketPolicy, '@FromCfnBucket', cfnBucketPolicy.bucket);\n }\n const ret = new class extends BucketPolicy {\n constructor() {\n super(...arguments);\n this.document = aws_iam_1.PolicyDocument.fromJson(cfnBucketPolicy.policyDocument);\n }\n }(cfnBucketPolicy, id, {\n bucket,\n });\n // mark the Bucket as having this Policy\n bucket.policy = ret;\n return ret;\n }", "function createBucket(region, bucket) {\n return regionBucket(region, bucket, {\n create: true,\n ACL: 'private'\n });\n}", "function createS3(regionName) {\n var config = { apiVersion: '2006-03-01' };\n \n if (regionName != null)\n config.region = regionName;\n\n var s3 = new AWS.S3(config);\n return s3;\n}", "putObject(bucketName, objectName, stream, size, metaData, callback) {\n if (!isValidBucketName(bucketName)) {\n throw new errors.InvalidBucketNameError('Invalid bucket name: ' + bucketName)\n }\n if (!isValidObjectName(objectName)) {\n throw new errors.InvalidObjectNameError(`Invalid object name: ${objectName}`)\n }\n\n // We'll need to shift arguments to the left because of size and metaData.\n if (isFunction(size)) {\n callback = size\n metaData = {}\n } else if (isFunction(metaData)) {\n callback = metaData\n metaData = {}\n }\n\n // We'll need to shift arguments to the left because of metaData\n // and size being optional.\n if (isObject(size)) {\n metaData = size\n }\n\n // Ensures Metadata has appropriate prefix for A3 API\n metaData = prependXAMZMeta(metaData)\n if (typeof stream === 'string' || stream instanceof Buffer) {\n // Adapts the non-stream interface into a stream.\n size = stream.length\n stream = readableStream(stream)\n } else if (!isReadableStream(stream)) {\n throw new TypeError('third argument should be of type \"stream.Readable\" or \"Buffer\" or \"string\"')\n }\n\n if (!isFunction(callback)) {\n throw new TypeError('callback should be of type \"function\"')\n }\n\n if (isNumber(size) && size < 0) {\n throw new errors.InvalidArgumentError(`size cannot be negative, given size: ${size}`)\n }\n\n // Get the part size and forward that to the BlockStream. Default to the\n // largest block size possible if necessary.\n if (!isNumber(size)) {\n size = this.maxObjectSize\n }\n\n size = this.calculatePartSize(size)\n\n // s3 requires that all non-end chunks be at least `this.partSize`,\n // so we chunk the stream until we hit either that size or the end before\n // we flush it to s3.\n let chunker = new BlockStream2({ size, zeroPadding: false })\n\n // This is a Writable stream that can be written to in order to upload\n // to the specified bucket and object automatically.\n let uploader = new ObjectUploader(this, bucketName, objectName, size, metaData, callback)\n // stream => chunker => uploader\n pipesetup(stream, chunker, uploader)\n }", "async deleteInS3(params) {\n s3.deleteObject(params, function (err, data) {\n if (data) {\n console.log(params.Key + \" deleted successfully.\");\n } else {\n console.log(\"Error: \" + err);\n }\n });\n }", "async function ListObject(bucketName, prefix) {\n let response;\n var params = {\n Bucket: bucketName,\n Delimiter: '/',\n MaxKeys: 1,\n Prefix: prefix\n };\n\n try {\n response = await S3.listObjectsV2(params).promise();\n }\n catch (error) {\n console.log(\"list error:\", error);\n }\n\n return response;\n}", "async function deleteFileFromFolder(){\n const params = {\n Bucket:process.argv[2],\n Key: process.argv[3] //if any sub folder-> path/of/the/folder.ext \n }\n s3=new AWS.S3({apiVersion: '2006-03-01'});\n try {\n await s3.headObject(params).promise()\n console.log(\"File Found in S3\")\n try {\n await s3.deleteObject(params).promise()\n console.log(\"file deleted Successfully\")\n }\n catch (err) {\n console.log(\"ERROR in file Deleting : \" + JSON.stringify(err))\n }\n } \n catch (err) {\n console.log(\"File not Found ERROR : \" + err.code)\n }\n\n}", "function CfnDatastore_DatastoreStoragePropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n if (typeof properties !== 'object') {\n errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.stringify(properties)));\n }\n errors.collect(cdk.propertyValidator('customerManagedS3', CfnDatastore_CustomerManagedS3PropertyValidator)(properties.customerManagedS3));\n errors.collect(cdk.propertyValidator('iotSiteWiseMultiLayerStorage', CfnDatastore_IotSiteWiseMultiLayerStoragePropertyValidator)(properties.iotSiteWiseMultiLayerStorage));\n errors.collect(cdk.propertyValidator('serviceManagedS3', cdk.validateObject)(properties.serviceManagedS3));\n return errors.wrap('supplied properties not correct for \"DatastoreStorageProperty\"');\n}", "getBucketACL(bucket, cb) {\n if (!validateBucketName(bucket)) {\n throw new errors.InvalidateBucketNameException('Invalid bucket name: ' + bucket)\n }\n\n var query = `?acl`,\n requestParams = {\n host: this.params.host,\n port: this.params.port,\n protocol: this.params.protocol,\n method: 'GET',\n path: `/${bucket}${query}`\n }\n\n signV4(requestParams, '', this.params.accessKey, this.params.secretKey)\n var req = this.transport.request(requestParams, response => {\n var concater = transformers.getConcater()\n var errorTransformer = transformers.getErrorTransformer(response)\n var transformer = transformers.getAclTransformer()\n if (response.statusCode !== 200) {\n pipesetup(response, concater, errorTransformer)\n .on('error', e => cb(e))\n return\n }\n pipesetup(response, concater, transformer)\n .on('error', e => cb(e))\n .on('data', data => {\n var perm = data.acl.reduce(function(acc, grant) {\n if (grant.grantee.uri === 'http://acs.amazonaws.com/groups/global/AllUsers') {\n if (grant.permission === 'READ') {\n acc.publicRead = true\n } else if (grant.permission === 'WRITE') {\n acc.publicWrite = true\n }\n } else if (grant.grantee.uri === 'http://acs.amazonaws.com/groups/global/AuthenticatedUsers') {\n if (grant.permission === 'READ') {\n acc.authenticatedRead = true\n } else if (grant.permission === 'WRITE') {\n acc.authenticatedWrite = true\n }\n }\n return acc\n }, {})\n var cannedACL = 'unsupported-acl'\n if (perm.publicRead && perm.publicWrite && !perm.authenticatedRead && !perm.authenticatedWrite) {\n cannedACL = 'public-read-write'\n } else if (perm.publicRead && !perm.publicWrite && !perm.authenticatedRead && !perm.authenticatedWrite) {\n cannedACL = 'public-read'\n } else if (!perm.publicRead && !perm.publicWrite && perm.authenticatedRead && !perm.authenticatedWrite) {\n cannedACL = 'authenticated-read'\n } else if (!perm.publicRead && !perm.publicWrite && !perm.authenticatedRead && !perm.authenticatedWrite) {\n cannedACL = 'private'\n }\n cb(null, cannedACL)\n })\n })\n req.on('error', e => cb(e))\n req.end()\n }", "static putFile (bucketName, objectKey, objectBody) {\n const s3 = Storage._getS3Instance();\n const params = {\n Bucket: bucketName,\n Key: objectKey,\n Body: objectBody\n };\n return new Promise((resolve, reject) => {\n s3.upload(params, (err, data) => err ? reject(err) : resolve(data.Location));\n });\n }", "function deleteObject() {\n const deleteParams = {\n Bucket: bucket,\n Key: key,\n };\n s3Client.deleteObject(deleteParams, (err, data) => {\n if (err) console.log('err:', err);\n else console.log('data:', data);\n });\n}", "function setPolicy (s3, bucket, cb) {\n var publicRead = {\n Sid: 'AddPublicReadPermissions',\n Effect: 'Allow',\n Principal: '*',\n Action: 's3:GetObject',\n Resource: 'arn:aws:s3:::' + bucket + '/*'\n }\n\n s3.getBucketPolicy({ Bucket: bucket }, function (err, data) {\n if (err && err.code !== 'NoSuchBucketPolicy') return cb(err)\n\n var newPolicy = { Statement: [] }\n var oldPolicy\n\n try {\n oldPolicy = JSON.parse(data.Policy)\n } catch (err) {}\n\n var found = false\n\n if (oldPolicy) {\n newPolicy.Statement = oldPolicy.Statement.map(function (item) {\n if (item.Sid === 'AddPublicReadPermissions') {\n found = true\n return publicRead\n }\n return item\n })\n }\n\n if (!found) newPolicy.Statement.push(publicRead)\n\n var dirty = diff(oldPolicy || {}, newPolicy, function (path, key) {\n if (key === 'Version') return true\n })\n\n if (dirty) {\n var policy = assign(oldPolicy || {}, newPolicy)\n s3.putBucketPolicy({ Bucket: bucket, Policy: JSON.stringify(policy) }, cb)\n } else {\n process.nextTick(cb)\n }\n })\n}", "save(bucket, key, value) {\n\n if (!this.__validate(bucket, key)) {\n throw errors.InvalidStringFormat(`A bucket and key should not contain ${DELIM}`);\n }\n\n return this.store.put(`${bucket}${DELIM}${key}`, value);\n }", "* exists (path) {\n return new Promise((resolve, reject) => {\n this.s3.headObject({\n Bucket: this.disk.bucket,\n Key: path\n }, (err, data) => {\n if (err) {\n if (err.code === 'NotFound') {\n return resolve(false)\n }\n return reject(err)\n }\n return resolve(true)\n })\n })\n }", "function FunctionResource_CodePropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n errors.collect(cdk.propertyValidator('s3Bucket', cdk.validateString)(properties.s3Bucket));\n errors.collect(cdk.propertyValidator('s3Key', cdk.validateString)(properties.s3Key));\n errors.collect(cdk.propertyValidator('s3ObjectVersion', cdk.validateString)(properties.s3ObjectVersion));\n errors.collect(cdk.propertyValidator('zipFile', cdk.validateString)(properties.zipFile));\n return errors.wrap('supplied properties not correct for \"CodeProperty\"');\n }", "makeBucket(bucket, cb) {\n return this.makeBucketWithACL(bucket, 'private', cb)\n }" ]
[ "0.7035866", "0.68394333", "0.6689597", "0.6677605", "0.6658934", "0.6605327", "0.6548209", "0.6532611", "0.6503798", "0.6477707", "0.64578265", "0.6446875", "0.64413005", "0.64227134", "0.6396272", "0.638612", "0.6352736", "0.6345922", "0.634141", "0.6318501", "0.63066953", "0.6292875", "0.6194507", "0.6190407", "0.61784637", "0.610136", "0.6075847", "0.6032711", "0.6008513", "0.5989921", "0.5938904", "0.59297854", "0.5875026", "0.5872595", "0.5869611", "0.5867899", "0.5842714", "0.5829697", "0.5798681", "0.5771961", "0.57297915", "0.57268405", "0.5696504", "0.5692579", "0.5658677", "0.56260556", "0.5616264", "0.5588728", "0.5583074", "0.55818033", "0.5542475", "0.55399305", "0.55360264", "0.55263263", "0.5513842", "0.5509211", "0.55088806", "0.5493103", "0.549273", "0.5478802", "0.54751635", "0.5447249", "0.5438153", "0.5418048", "0.54135627", "0.5400677", "0.5400588", "0.5390115", "0.5385747", "0.536672", "0.53564656", "0.53536993", "0.5340291", "0.5335477", "0.5321641", "0.5319704", "0.5317954", "0.531493", "0.5308575", "0.5301175", "0.52773345", "0.52584887", "0.5229903", "0.5218995", "0.5193014", "0.51887697", "0.5188256", "0.5169968", "0.51646936", "0.516133", "0.5155616", "0.5148816", "0.5130256", "0.51279217", "0.5125272", "0.5123312", "0.51203537", "0.5102914", "0.50950825", "0.50945705" ]
0.7268729
0
Create an S3 Bucket in a specified region with the given name and ACL. All objects will expire after 'lifecycleDays' days have elapsed.
async function createS3Bucket(s3, name, region, acl, lifecycleDays = 1) { assert(s3); assert(name); assert(region); assert(acl); assert(typeof lifecycleDays === 'number'); if (!validateS3BucketName(name, true)) { throw new Error(`Bucket ${name} is not valid`); } let params = { Bucket: name, ACL: acl, }; if (region !== 'us-east-1') { params.CreateBucketConfiguration = { LocationConstraint: region, }; } try { debug(`Creating S3 Bucket ${name} in ${region}`); await s3.createBucket(params).promise(); debug(`Created S3 Bucket ${name} in ${region}`); } catch (err) { switch (err.code) { case 'BucketAlreadyExists': case 'BucketAlreadyOwnedByYou': break; default: throw err; } } params = { Bucket: name, LifecycleConfiguration: { Rules: [ { ID: region + '-' + lifecycleDays + '-day', Prefix: '', Status: 'Enabled', Expiration: { Days: lifecycleDays, }, }, ], }, }; debug(`Setting S3 lifecycle configuration for ${name} in ${region}`); await s3.putBucketLifecycleConfiguration(params).promise(); debug(`Set S3 lifecycle configuration for ${name} in ${region}`); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function createBucket(){\n // Create S3 service object\n s3 = new AWS.S3({apiVersion: '2006-03-01'});\n\n // Create the parameters for calling createBucket\n var bucketParams = {\n Bucket : process.argv[2],\n ACL : 'public-read'\n };\n\n // call S3 to create the bucket\n s3.createBucket(bucketParams, function(err, data) {\n if (err) {\n console.log(\"Error\", err);\n } else {\n console.log(\"Success\", data.Location);\n }\n });\n}", "function createS3(regionName) {\n var config = { apiVersion: '2006-03-01' };\n \n if (regionName != null)\n config.region = regionName;\n\n var s3 = new AWS.S3(config);\n return s3;\n}", "function createBucket(region, bucket) {\n return regionBucket(region, bucket, {\n create: true,\n ACL: 'private'\n });\n}", "function createBucket() {\n metadata\n .buckets.set(bucketName, new BucketInfo(bucketName, ownerID, '', ''));\n metadata.keyMaps.set(bucketName, new Map);\n}", "async init() {\n this.debug(`creating ${this.bucket}`);\n await createS3Bucket(this.s3, this.bucket, this.region, this.acl, this.lifespan);\n this.debug(`creating ${this.bucket}`);\n }", "function insertBucket() {\n resource = {\n 'name': BUCKET\n };\n\n var request = gapi.client.storage.buckets.insert({\n 'project': PROJECT,\n 'resource': resource\n });\n executeRequest(request, 'insertBucket');\n}", "function putS3File(bucketName, fileName, data, callback) {\n var expirationDate = new Date();\n // Assuming a user would not remain active in the same session for over 1 hr.\n expirationDate = new Date(expirationDate.setHours(expirationDate.getHours() + 1));\n var params = {\n Bucket: bucketName,\n Key: fileName,\n Body: data,\n ACL: 'public-read', // TODO: find way to restrict access to this lambda function\n Expires: expirationDate\n };\n s3.putObject(params, function (err, data) {\n callback(err, data);\n });\n}", "function putBucketAcl() {\n const putBucketAclParams = {\n Bucket: bucket,\n ACL: 'authenticated-read',\n };\n s3Client.putBucketAcl(putBucketAclParams, (err, data) => {\n if (err) console.log('err:', err);\n else console.log('data:', data);\n });\n}", "function insertBucketAccessControls() {\n resource = {\n 'entity': ENTITY,\n 'role': ROLE\n };\n\n var request = gapi.client.storage.bucketAccessControls.insert({\n 'bucket': BUCKET,\n 'resource': resource\n });\n executeRequest(request, 'insertBucketAccessControls');\n}", "setBucketLifecycle(bucketName, lifeCycleConfig = null, cb) {\n if (!isValidBucketName(bucketName)) {\n throw new errors.InvalidBucketNameError('Invalid bucket name: ' + bucketName)\n }\n if (_.isEmpty(lifeCycleConfig)) {\n this.removeBucketLifecycle(bucketName, cb)\n } else {\n this.applyBucketLifecycle(bucketName, lifeCycleConfig, cb)\n }\n }", "async createBucketIfNotExists() {\n const bucket = this.templates.create.Resources[this.getBucketId()].Properties;\n const foundBucket = await this.provider.getBucket(bucket.BucketName);\n if (foundBucket) {\n this.serverless.cli.log(`Bucket ${bucket.BucketName} already exists.`);\n } else {\n this.serverless.cli.log(`Creating bucket ${bucket.BucketName}...`);\n await this.provider.createBucket(bucket.BucketName);\n await this.setBucketWebsite(bucket.BucketName);\n await this.setBucketPublic(bucket.BucketName);\n this.serverless.cli.log(`Created bucket ${bucket.BucketName}`);\n }\n\n this.provider.resetOssClient(bucket.BucketName);\n }", "function uploadS3File(bucketName, fileName, data, callback) {\n var params = {\n Bucket: bucketName,\n Key: fileName,\n Body: data,\n ACL: 'public-read', // TODO: find way to restrict access to this lambda function\n };\n s3.upload(params, function(err, data) {\n callback(err, data);\n });\n}", "function uploadToS3(file) {\n let s3bucket = new AWS.S3({\n accessKeyId: ACCESS,\n secretAccessKey: SECRET,\n Bucket: BUCKET_NAME,\n });\n s3bucket.createBucket(function () {\n var params = {\n Bucket: BUCKET_NAME,\n Key: file.name,\n Body: file.data,\n };\n s3bucket.upload(params, function (err, data) {\n if (err) {\n console.log(\"error in callback\");\n console.log(err);\n }\n console.log(\"success\");\n console.log(data);\n });\n });\n}", "function putObject(keyName) {\n const putObjectParams = {\n Bucket: bucket,\n Key: keyName,\n Metadata: {\n importance: 'very',\n ranking: 'middling',\n },\n Body: 'putMe',\n };\n s3Client.putObject(putObjectParams, (err, data) => {\n if (err) console.log('err:', err);\n else console.log('data:', data);\n });\n}", "applyBucketLifecycle(bucketName, policyConfig, cb) {\n const method = 'PUT'\n const query = 'lifecycle'\n\n const encoder = new TextEncoder()\n const headers = {}\n const builder = new xml2js.Builder({\n rootName: 'LifecycleConfiguration',\n headless: true,\n renderOpts: { pretty: false },\n })\n let payload = builder.buildObject(policyConfig)\n payload = Buffer.from(encoder.encode(payload))\n const requestOptions = { method, bucketName, query, headers }\n headers['Content-MD5'] = toMd5(payload)\n\n this.makeRequest(requestOptions, payload, [200], '', false, cb)\n }", "presignedPutObject(bucketName, objectName, expires, cb) {\n if (!isValidBucketName(bucketName)) {\n throw new errors.InvalidBucketNameError(`Invalid bucket name: ${bucketName}`)\n }\n if (!isValidObjectName(objectName)) {\n throw new errors.InvalidObjectNameError(`Invalid object name: ${objectName}`)\n }\n return this.presignedUrl('PUT', bucketName, objectName, expires, cb)\n }", "function before (s3, bucket, keys, done) {\n createBucket(s3, bucket)\n .then(function () {\n return when.all(\n // Swallow deleteObject errors here incase the files don't yet exist\n keys.map(function (key) { return deleteObject(s3, bucket, key).catch(function () {}); })\n )\n }).then(function () { done(); });\n}", "function uploadFileIntoBucket(){\n // Create S3 service object\n s3 = new AWS.S3({apiVersion: '2006-03-01'});\n\n // call S3 to retrieve upload file to specified bucket\n var uploadParams = {Bucket: process.argv[2], Key: '', Body: ''};\n var file = process.argv[3];\n\n // Configure the file stream and obtain the upload parameters\n var fs = require('fs');\n var fileStream = fs.createReadStream(file);\n fileStream.on('error', function(err) {\n console.log('File Error', err);\n });\n\n uploadParams.Body = fileStream;\n var path = require('path');\n uploadParams.Key = path.basename(file);\n\n // call S3 to retrieve upload file to specified bucket\n s3.upload (uploadParams, function (err, data) {\n if (err) {\n console.log(\"Error\", err);\n } if (data) {\n console.log(\"Upload Success\", data.Location);\n }\n });\n}", "presignedPutObject(bucketName, objectName, expires) {\n if (!validateBucketName(bucketName)) {\n throw new errors.InvalidateBucketNameException('Invalid bucket name: ' + bucketName)\n }\n if (objectName === null || objectName.trim() === '') {\n throw new errors.InvalidObjectNameException('Object name cannot be empty')\n }\n var requestParams = {\n host: this.params.host,\n port: this.params.port,\n protocol: this.params.protocol,\n path: `/${bucketName}/${uriResourceEscape(objectName)}`,\n method: 'PUT',\n expires: expires\n }\n return presignSignatureV4(requestParams, this.params.accessKey, this.params.secretKey)\n }", "create_object_upload(params, object_sdk) {\n if (this.target_bucket) params = _.defaults({ bucket: this.target_bucket }, params);\n return object_sdk.rpc_client.object.create_object_upload(params);\n }", "function saveToS3(fileName) {\n // load in file;\n let logDir = './logs';\n let directory =`${logDir}/${fileName}`;\n let myKey = fileName;\n var myBody;\n console.log(directory);\n\n // read then save to s3 in one step (so no undefined errors)\n fs.readFile(directory, (err, data) => {\n if (err) throw err;\n myBody = data;\n console.log(\"save to s3 data is \" + data);\n var params = {Bucket: myBucket, Key: myKey, Body: myBody, ContentType: 'text/plain'};\n s3.putObject(params, function(err, data) {\n if (err) {\n console.log(err)\n } else {\n console.log(\"Successfully uploaded data to myBucket/myKey\");\n }\n });\n\n });\n fs.unlink(directory);\n\n // the create bucket stuff started to cause problems (error: \"BucketAlreadyOwnedByYou: Your previous request to create the named bucket succeeded and you already own it.\")\n // so I pulled it all out\n}", "removeBucketLifecycle(bucketName, cb) {\n if (!isValidBucketName(bucketName)) {\n throw new errors.InvalidBucketNameError('Invalid bucket name: ' + bucketName)\n }\n const method = 'DELETE'\n const query = 'lifecycle'\n this.makeRequest({ method, bucketName, query }, '', [204], '', false, cb)\n }", "static Create(opts, cb) {\n new S3FileSystem(opts, cb)\n }", "function uploadFileIntoFolderOfBucket(){\n // Create S3 service object\n s3 = new AWS.S3({apiVersion: '2006-03-01'});\n\n // call S3 to retrieve upload file to specified bucket\n var uploadParams = {Bucket: process.argv[2], Key: '', Body: ''};\n var file = process.argv[4];\n\n // Configure the file stream and obtain the upload parameters\n var fs = require('fs');\n var fileStream = fs.createReadStream(file);\n fileStream.on('error', function(err) {\n console.log('File Error', err);\n });\n\n uploadParams.Body = fileStream;\n var path = require('path');\n uploadParams.Key = process.argv[3]+\"/\"+path.basename(file);\n\n // call S3 to retrieve upload file to specified bucket\n s3.upload (uploadParams, function (err, data) {\n if (err) {\n console.log(\"Error\", err);\n } if (data) {\n console.log(\"Upload Success\", data.Location);\n }\n });\n}", "makeBucket(bucket, cb) {\n return this.makeBucketWithACL(bucket, 'private', cb)\n }", "function onInitialized(response) {\n\n var createIfNotExists = true;\n\n var bucketCreationData = {\n bucketKey: config.defaultBucketKey,\n servicesAllowed: [],\n policy: 'persistent' //['temporary', 'transient', 'persistent']\n };\n\n lmv.getBucket(config.defaultBucketKey,\n createIfNotExists,\n bucketCreationData).then(\n onBucketCreated,\n onError);\n }", "putObject(bucketName, objectName, stream, size, metaData, callback) {\n if (!isValidBucketName(bucketName)) {\n throw new errors.InvalidBucketNameError('Invalid bucket name: ' + bucketName)\n }\n if (!isValidObjectName(objectName)) {\n throw new errors.InvalidObjectNameError(`Invalid object name: ${objectName}`)\n }\n\n // We'll need to shift arguments to the left because of size and metaData.\n if (isFunction(size)) {\n callback = size\n metaData = {}\n } else if (isFunction(metaData)) {\n callback = metaData\n metaData = {}\n }\n\n // We'll need to shift arguments to the left because of metaData\n // and size being optional.\n if (isObject(size)) {\n metaData = size\n }\n\n // Ensures Metadata has appropriate prefix for A3 API\n metaData = prependXAMZMeta(metaData)\n if (typeof stream === 'string' || stream instanceof Buffer) {\n // Adapts the non-stream interface into a stream.\n size = stream.length\n stream = readableStream(stream)\n } else if (!isReadableStream(stream)) {\n throw new TypeError('third argument should be of type \"stream.Readable\" or \"Buffer\" or \"string\"')\n }\n\n if (!isFunction(callback)) {\n throw new TypeError('callback should be of type \"function\"')\n }\n\n if (isNumber(size) && size < 0) {\n throw new errors.InvalidArgumentError(`size cannot be negative, given size: ${size}`)\n }\n\n // Get the part size and forward that to the BlockStream. Default to the\n // largest block size possible if necessary.\n if (!isNumber(size)) {\n size = this.maxObjectSize\n }\n\n size = this.calculatePartSize(size)\n\n // s3 requires that all non-end chunks be at least `this.partSize`,\n // so we chunk the stream until we hit either that size or the end before\n // we flush it to s3.\n let chunker = new BlockStream2({ size, zeroPadding: false })\n\n // This is a Writable stream that can be written to in order to upload\n // to the specified bucket and object automatically.\n let uploader = new ObjectUploader(this, bucketName, objectName, size, metaData, callback)\n // stream => chunker => uploader\n pipesetup(stream, chunker, uploader)\n }", "function createBucketWithReplication(hasStorageClass) {\n createBucket();\n const config = {\n role: 'arn:aws:iam::account-id:role/src-resource,' +\n 'arn:aws:iam::account-id:role/dest-resource',\n destination: 'arn:aws:s3:::source-bucket',\n rules: [{\n prefix: keyA,\n enabled: true,\n id: 'test-id',\n }],\n };\n if (hasStorageClass) {\n config.rules[0].storageClass = storageClassType;\n }\n Object.assign(metadata.buckets.get(bucketName), {\n _versioningConfiguration: { status: 'Enabled' },\n _replicationConfiguration: config,\n });\n}", "function uploadToS3(name, file, successCallback, errorCallback, progressCallback) {\n\n if (typeof successCallback != 'function') {\n Ti.API.error('successCallback() is not defined');\n return false;\n }\n\n if (typeof errorCallback != 'function') {\n Ti.API.error('errorCallback() is not defined');\n return false;\n }\n\n var AWSAccessKeyID = 'AKIAJHRVU52E4GKVARCQ';\n var AWSSecretAccessKey = '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';\n var AWSBucketName = 'snapps';\n var AWSHost = AWSBucketName + '.s3.amazonaws.com';\n\n var currentDateTime = formatDate(new Date(),'E, d MMM yyyy HH:mm:ss') + ' ' + getOffsetAsInteger();\n\n var xhr = Ti.Network.createHTTPClient();\n\n xhr.onsendstream = function(e) {\n\n if (typeof debugStartTime != 'number') {\n debugStartTime = new Date().getTime();\n }\n\n debugUploadTime = Math.floor((new Date().getTime() - debugStartTime) / 1000);\n\n var progress = Math.floor(e.progress * 100);\n Ti.API.info('uploading (' + debugUploadTime + 's): ' + progress + '%');\n\n // run progressCallback function when available\n if (typeof progressCallback == 'function') {\n progressCallback(progress);\n }\n\n };\n\n xhr.onerror = function(e) {\n Ti.API.error({ errorlocation: 'onload', error: e, responseText: xhr.responseText, headers: xhr.getResponseHeaders() });\n errorCallback(e);\n };\n\n xhr.onload = function() {\n if (this.status >= 200 && this.status < 300) {\n\n var responseHeaders = xhr.getResponseHeaders();\n\n var filename = name;\n var url = 'https://' + AWSHost + '/' + name;\n\n if (responseHeaders['x-amz-version-id']) {\n url = url + '?versionId=' + responseHeaders['x-amz-version-id'];\n }\n\n successCallback({ url: url });\n }\n else {\n Ti.API.error({ errorlocation: 'onload', error: e, responseText: xhr.responseText, headers: xhr.getResponseHeaders() });\n errorCallback();\n }\n };\n\n //ensure we have time to upload\n xhr.setTimeout(99000);\n\n // An optional boolean parameter, defaulting to true, indicating whether or not to perform the operation asynchronously.\n // If this value is false, the send() method does not return until the response is received. If true, notification of a\n // completed transaction is provided using event listeners. This must be true if the multipart attribute is true, or\n // an exception will be thrown.\n xhr.open('PUT', 'https://' + AWSHost + '/' + name, true);\n\n //var StringToSign = 'PUT\\n\\nmultipart/form-data\\n' + currentDateTime + '\\nx-amz-acl:public-read\\n/' + AWSBucketName + '/' + name;\n var StringToSign = 'PUT\\n\\n\\n' + currentDateTime + '\\nx-amz-acl:public-read\\n/' + AWSBucketName + '/' + name;\n var AWSSignature = b64_hmac_sha1(AWSSecretAccessKey, Utf8.encode(StringToSign));\n var AuthorizationHeader = 'AWS ' + AWSAccessKeyID + ':' + AWSSignature;\n\n xhr.setRequestHeader('Authorization', AuthorizationHeader);\n //xhr.setRequestHeader('Content-Type', 'multipart/form-data');\n xhr.setRequestHeader('X-Amz-Acl', 'public-read');\n xhr.setRequestHeader('Host', AWSHost);\n xhr.setRequestHeader('Date', currentDateTime);\n\n xhr.send(file);\n\n return xhr;\n}", "static putFile (bucketName, objectKey, objectBody) {\n const s3 = Storage._getS3Instance();\n const params = {\n Bucket: bucketName,\n Key: objectKey,\n Body: objectBody\n };\n return new Promise((resolve, reject) => {\n s3.upload(params, (err, data) => err ? reject(err) : resolve(data.Location));\n });\n }", "function saveObjToS3(data, fileName, bucket, callback){\n console.log(\"saveObjToS3\", data);\n //save data to s3 \n var params = {Bucket: bucket, Key: fileName, Body: data, ContentType: 'text/plain'};\n s3.putObject(params, function(err, data) {\n if (err) {\n console.log(\"saveObjToS3 err\", err);\n } else {\n callback();\n }\n });\n}", "setBucketACL(bucket, acl, cb) {\n if (!validateBucketName(bucket)) {\n throw new errors.InvalidateBucketNameException('Invalid bucket name: ' + bucket)\n }\n\n if (acl === null || acl.trim() === '') {\n throw new errors.InvalidEmptyACLException('Acl name cannot be empty')\n }\n\n // we should make sure to set this query parameter, but on the other hand\n // the call apparently succeeds without it to s3. For clarity lets do it anyways\n var query = `?acl`,\n requestParams = {\n host: this.params.host,\n port: this.params.port,\n protocol: this.params.protocol,\n method: 'PUT',\n path: `/${bucket}${query}`,\n headers: {\n 'x-amz-acl': acl\n }\n }\n\n signV4(requestParams, '', this.params.accessKey, this.params.secretKey)\n\n var req = this.transport.request(requestParams, response => {\n var concater = transformers.getConcater()\n var errorTransformer = transformers.getErrorTransformer(response)\n if (response.statusCode !== 200) {\n pipesetup(response, concater, errorTransformer)\n .on('error', e => cb(e))\n return\n }\n cb()\n })\n // FIXME: the below line causes weird failure in 'gulp test'\n // req.on('error', e => cb(e))\n req.end()\n }", "function s3Upload(files, bucketName, objectKeyPrefix, iamUserKey, iamUserSecret, callback) {\n var s3 = new AWS.S3({\n bucket: bucketName,\n accessKeyId: iamUserKey,\n secretAccessKey: iamUserSecret,\n apiVersion: '2006-03-01',\n });\n\n // s3.abortMultipartUpload(params, function (err, data) {\n // if (err) console.log(err, err.stack); // an error occurred\n // else console.log(data); // successful response\n // });\n\n // Setup the objects to upload to S3 & map the results into files\n var results = files.map(function(file) {\n // Upload file to bucket with name of Key\n s3.upload({\n Bucket: bucketName,\n Key: objectKeyPrefix + file.originalname, // Prefix should have \".\" on each end\n Body: file.buffer,\n ACL: 'public-read' // TODO: CHANGE THIS & READ FROM CLOUDFRONT INSTEAD\n },\n function(error, data) {\n // TODO: Maybe refine this to show only data care about elsewhere\n if(error) {\n console.log(\"Error uploading file to S3: \", error);\n return {error: true, data: error};\n } else {\n console.log('File uploaded. Data is:', data);\n return {error: false, data: data};\n }\n });\n });\n\n callback(results); // Results could be errors or successes\n}", "logAccessLogs(bucket, prefix) {\n try {\n jsiiDeprecationWarnings.aws_cdk_lib_aws_s3_IBucket(bucket);\n }\n catch (error) {\n if (process.env.JSII_DEBUG !== \"1\" && error.name === \"DeprecationError\") {\n Error.captureStackTrace(error, this.logAccessLogs);\n }\n throw error;\n }\n prefix = prefix || '';\n this.setAttribute('access_logs.s3.enabled', 'true');\n this.setAttribute('access_logs.s3.bucket', bucket.bucketName.toString());\n this.setAttribute('access_logs.s3.prefix', prefix);\n const logsDeliveryServicePrincipal = new aws_iam_1.ServicePrincipal('delivery.logs.amazonaws.com');\n bucket.grantPut(this.resourcePolicyPrincipal(), `${(prefix ? prefix + '/' : '')}AWSLogs/${core_1.Stack.of(this).account}/*`);\n bucket.addToResourcePolicy(new aws_iam_1.PolicyStatement({\n actions: ['s3:PutObject'],\n principals: [logsDeliveryServicePrincipal],\n resources: [\n bucket.arnForObjects(`${prefix ? prefix + '/' : ''}AWSLogs/${this.env.account}/*`),\n ],\n conditions: {\n StringEquals: { 's3:x-amz-acl': 'bucket-owner-full-control' },\n },\n }));\n bucket.addToResourcePolicy(new aws_iam_1.PolicyStatement({\n actions: ['s3:GetBucketAcl'],\n principals: [logsDeliveryServicePrincipal],\n resources: [bucket.bucketArn],\n }));\n // make sure the bucket's policy is created before the ALB (see https://github.com/aws/aws-cdk/issues/1633)\n this.node.addDependency(bucket);\n }", "function addS3bucket (req, res, next) {\n if (req.params.s3bucket) return next()\n req.params.s3bucket = [process.env.APP_NAME, req.params.appname].join('.')\n next()\n}", "function rememberToDeleteBucket(bucketName) {\n bucketsToDelete.push(bucketName);\n}", "function create(files){\n\tvar AWS = require('aws-sdk');\n\n\tvar awsConfig = new AWS.Config({\n\t\taccessKeyId: config.accessKeyId, \n\t\tsecretAccessKey:config.secretAccessKey,\n\t\tregion: config.region\n\t});\n\n\tAWS.config=awsConfig;\n\n\tvar s3 = new AWS.S3( { params: {Bucket: config.s3BucketName} } );\t\n\n\tvar date = new Date();\n\tfiles.forEach(function(item){\n\t\tvar options={\n\t\t\tKey:item.filename,\n\t\t Body:new Buffer(item.data.replace(/^data:image\\/\\w+;base64,/, \"\"),'base64'),\n\t\t ContentEncoding: 'base64',\n\t\t ContentType: 'image/jpeg'\n\t\t};\n\n\t\ts3.putObject(options, function(err,data){\n\t\t\tif(err){\n\t\t\t\tconsole.log('~~error~',err);\n\t\t\t}else{\n\t\t\t\tconsole.log('~~success~'+date.toTimeString());\n\t\t\t}\n\t\t});\n\t});\n}", "addBucket() {\n\t\tthis.setState({\n\t\t\tmodel_title: \"Add Bucket\",\n\t\t\tbucket_name: \"\",\n\t\t\tbucket_id: \"\"\n\t\t})\n\t}", "function validateBucket(name) {\n if (!validBucketRe.test(name)) {\n throw new Error(`invalid bucket name: ${name}`);\n }\n}", "async function generateUrl(){\n let date = new Date();\n let id = parseInt(Math.random() * 10000000000);\n const imageName = `${id}${date.getTime()}.jpg`;\n\n const params = ({\n Bucket:buketName,\n Key:imageName,\n Expires:300,\n ContentType:'image/jpeg'\n })\n\n const uploadUrl = await s3.getSignedUrlPromise('putObject',params);\n return uploadUrl;\n}", "function InitAWSConfigurations()\n{\n bucketName = $(\"#hdnBucketName\").val();\n\n bucketStartURL = $(\"#hdnBucketStartURL\").val();\n\n AWS.config.update({\n accessKeyId: $(\"#hdnAWSAccessKey\").val(),\n secretAccessKey: $(\"#hdnAWSSecretKey\").val(),\n region: $(\"#hdnBucketRegion\").val()\n\n });\n\n\n bucket = new AWS.S3({\n params: { Bucket: bucketName }\n });\n // s3 = new AWS.S3();\n\n /****Image upload path initializations****/\n\n userProfileImagePath = $(\"#hdnUserProfileImagePath\").val();\n otherUserProfileFilePath = $(\"#hdnOtherUserProfileFilePath\").val();\n\n\n /***************************************/\n\n}", "function CreateBucketCommand(input) {\n var _this = \n // Start section: command_constructor\n _super.call(this) || this;\n _this.input = input;\n return _this;\n // End section: command_constructor\n }", "async function uploadS3(filePath, folderName, deleteFile, callback) {\n\n var s3 = new AWS.S3({useAccelerateEndpoint: true});\n //configuring parameters\n var params = {\n Bucket: 'docintact',\n Body: fs.createReadStream(filePath),\n Key: folderName + \"/\" + Date.now() + \"_\" + path.basename(filePath)\n };\n s3.upload(params, function(err, data) {\n //handle error\n if (err) {}\n //success\n if (data) {\n if (deleteFile)\n if (fs.existsSync(filePath)) fs.unlinkSync(filePath)\n if (callback) callback(data.Location);\n else return data.Location;\n }\n });\n}", "function createNewUpload(req, callback) {\n var params = {\n Bucket: config.s3.bucket,\n Key: (config.getPath(req) || '') + config.getFilename(req)\n };\n s3.createMultipartUpload(params, function(err, s3data) {\n if (err) {\n config.log(err, err.stack);\n return callback(err);\n }\n\n config.log('s3 data', JSON.stringify(s3data));\n\n config.setS3Id(req, s3data, function(err, response) {\n return callback(err, s3data);\n });\n /*\n data = {\n Bucket: \"examplebucket\",\n Key: \"largeobject\",\n UploadId: \"ibZBv_75gd9r8lH_gqXatLdxMVpAlj6ZQjEs.OwyF3953YdwbcQnMA2BLGn8Lx12fQNICtMw5KyteFeHw.Sjng--\"\n }\n */\n });\n }", "async function putContainers() {\n const subscriptionId = process.env[\"STORAGE_SUBSCRIPTION_ID\"] || \"{subscription-id}\";\n const resourceGroupName = process.env[\"STORAGE_RESOURCE_GROUP\"] || \"res3376\";\n const accountName = \"sto328\";\n const containerName = \"container6185\";\n const blobContainer = {};\n const credential = new DefaultAzureCredential();\n const client = new StorageManagementClient(credential, subscriptionId);\n const result = await client.blobContainers.create(\n resourceGroupName,\n accountName,\n containerName,\n blobContainer\n );\n console.log(result);\n}", "function putObject(bucket, key, obkject) {\n\tif (bucket === null) {\n\t\tbucket = constants.defaultBucket;\n\t}\n\n\tvar params = {\n\t\tBucket : bucket, /* required */\n\t\tKey : key, /* required */\n\t\tBody : obkject\n\t};\n\tconsole.log(\"putObject for \" + JSON.stringify(obkject));\n\ts3.putObject(params, function(err, data) {\n\t\tif (err)\n\t\t\tconsole.log(err, err.stack); // an error occurred\n\t\telse\n\t\t\tconsole.log(data); // successful response\n\t});\n}", "function cfnApiS3LocationPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnApi_S3LocationPropertyValidator(properties).assertSuccess();\n return {\n Bucket: cdk.stringToCloudFormation(properties.bucket),\n Key: cdk.stringToCloudFormation(properties.key),\n Version: cdk.numberToCloudFormation(properties.version),\n };\n}", "function cfnApiS3LocationPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnApi_S3LocationPropertyValidator(properties).assertSuccess();\n return {\n Bucket: cdk.stringToCloudFormation(properties.bucket),\n Key: cdk.stringToCloudFormation(properties.key),\n Version: cdk.numberToCloudFormation(properties.version),\n };\n}", "constructor(region, bucketName, configName, credentials, logger) {\r\n if (stringHelper_1.StringHelper.isEmpty(region)) {\r\n throw new storageError_1.StorageError(\"The region must not be an empty string\");\r\n }\r\n if (stringHelper_1.StringHelper.isEmpty(bucketName)) {\r\n throw new storageError_1.StorageError(\"The bucketName must not be an empty string\");\r\n }\r\n if (stringHelper_1.StringHelper.isEmpty(configName)) {\r\n throw new storageError_1.StorageError(\"The configName must not be an empty string\");\r\n }\r\n this._region = region;\r\n this._bucketName = bucketName;\r\n this._configName = configName;\r\n this._credentials = credentials;\r\n this._logger = logger || new nullLogger_1.NullLogger();\r\n }", "function cfnStateMachineS3LocationPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnStateMachine_S3LocationPropertyValidator(properties).assertSuccess();\n return {\n Bucket: cdk.stringToCloudFormation(properties.bucket),\n Key: cdk.stringToCloudFormation(properties.key),\n Version: cdk.numberToCloudFormation(properties.version),\n };\n}", "function PutBucketAclCommand(input) {\n var _this = \n // Start section: command_constructor\n _super.call(this) || this;\n _this.input = input;\n return _this;\n // End section: command_constructor\n }", "function getS3(awsAccessKey, awsSecretKey) {\n return new AWS.S3({\n accessKeyId: awsAccessKey,\n secretAccessKey: awsSecretKey\n });\n}", "function cfnFunctionS3EventPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnFunction_S3EventPropertyValidator(properties).assertSuccess();\n return {\n Bucket: cdk.stringToCloudFormation(properties.bucket),\n Events: cdk.unionMapper([cdk.unionValidator(cdk.validateString), cdk.listValidator(cdk.unionValidator(cdk.validateString))], [cdk.unionMapper([cdk.validateString], [cdk.stringToCloudFormation]), cdk.listMapper(cdk.unionMapper([cdk.validateString], [cdk.stringToCloudFormation]))])(properties.events),\n Filter: cfnFunctionS3NotificationFilterPropertyToCloudFormation(properties.filter),\n };\n}", "function cfnFunctionS3EventPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnFunction_S3EventPropertyValidator(properties).assertSuccess();\n return {\n Bucket: cdk.stringToCloudFormation(properties.bucket),\n Events: cdk.unionMapper([cdk.unionValidator(cdk.validateString), cdk.listValidator(cdk.unionValidator(cdk.validateString))], [cdk.unionMapper([cdk.validateString], [cdk.stringToCloudFormation]), cdk.listMapper(cdk.unionMapper([cdk.validateString], [cdk.stringToCloudFormation]))])(properties.events),\n Filter: cfnFunctionS3NotificationFilterPropertyToCloudFormation(properties.filter),\n };\n}", "async function createWebConfig(event) {\n try {\n var webConfig = {\n version: \"1.1\",\n api_base: event.ResourceProperties.APIGateway.Url,\n language: process.env.TRANSCRIBE_LANGUAGE,\n api_videos: \"/videos\",\n api_vocabulary: \"/vocabulary\",\n api_tweaks: \"/tweaks\",\n api_video: \"/video\",\n api_videostatus: \"/videostatus\",\n api_videoname: \"/videoname\",\n api_videodescription: \"/videodescription\",\n api_burned_video: \"/burnedvideo\",\n api_captions: \"/caption\",\n api_language: \"/language\",\n api_translate: \"/translate\",\n api_upload: \"/upload\",\n api_burn: \"/burn\",\n };\n\n var webDeployTarget = event.ResourceProperties.WebDeployTarget;\n\n var putObjectRequest = {\n Body: JSON.stringify(webConfig),\n Bucket: webDeployTarget.Bucket,\n // ACL: 'public-read',\n Key: \"site_config.json\",\n ContentType: \"application/json\",\n };\n console.log(\"createWebConfig start, request %j\", putObjectRequest);\n\n await s3.putObject(putObjectRequest).promise();\n } catch (error) {\n console.log(\"[ERROR] failed to create web config\", error);\n throw error;\n }\n}", "function cfnInstanceStorageConfigS3ConfigPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnInstanceStorageConfig_S3ConfigPropertyValidator(properties).assertSuccess();\n return {\n BucketName: cdk.stringToCloudFormation(properties.bucketName),\n BucketPrefix: cdk.stringToCloudFormation(properties.bucketPrefix),\n EncryptionConfig: cfnInstanceStorageConfigEncryptionConfigPropertyToCloudFormation(properties.encryptionConfig),\n };\n}", "function cfnDeploymentGroupS3LocationPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnDeploymentGroup_S3LocationPropertyValidator(properties).assertSuccess();\n return {\n Bucket: cdk.stringToCloudFormation(properties.bucket),\n BundleType: cdk.stringToCloudFormation(properties.bundleType),\n ETag: cdk.stringToCloudFormation(properties.eTag),\n Key: cdk.stringToCloudFormation(properties.key),\n Version: cdk.stringToCloudFormation(properties.version),\n };\n}", "async function emptyAndDeleteFolderOfBucket() {\n s3=new AWS.S3({apiVersion: '2006-03-01'});\n const listParams = {\n Bucket:process.argv[2],\n Prefix:process.argv[3]\n };\n\n const listedObjects = await s3.listObjectsV2(listParams).promise();\n\n if (listedObjects.Contents.length === 0) return;\n\n const deleteParams = {\n Bucket: process.argv[2],\n Delete: { Objects: [] }\n };\n\n listedObjects.Contents.forEach(({ Key }) => {\n deleteParams.Delete.Objects.push({ Key });\n });\n\n await s3.deleteObjects(deleteParams).promise();\n\n if (listedObjects.IsTruncated) await emptyAndDeleteFolderOfBucket(process.argv[2], process.argv[3]);\n}", "function S3ObjectClass(configuration, createUploadRequestNamesFunction, redisClient)\n{\n\tvar self = this;\n\n\t//grab bucketname from config file\n\tvar bucketName = configuration.bucket;\n\tvar uploadExpiration = configuration.expires || 15*60;\n\n\tself.s3 = new AWS.S3({params: {Bucket: bucketName}, computeChecksums: false});\n\n\t//example for outside use or testing -- helpful if i forget my function logic later--or someone checking around from the outside\n\tself.requestFunctionExample = exampleUploadRequestFunction;\n\tself.createUploadRequests = createUploadRequestNamesFunction;\n\n\tself.uploadErrors = {\n\t\tnullUploadKey : 0,\n\t\tredisError : 1,\n\t\theadCheckUnfulfilledError : 2,\n\t\theadCheckMissingError : 3,\n\t\tredisDeleteError : 4\n\t}\n\n\n\tself.generateObjectAccess = function(fileLocations)\n\t{\n\n\t\t//we create a map of signed URLs\n\t\tvar fileAccess = {};\n\n\t\tfor(var i=0; i < fileLocations.length; i++)\n\t\t{\n\t\t\tvar fLocation = fileLocations[i];\n\n\t\t\tvar signedURLReq = {\n\t\t\t\tBucket: bucketName, \n\t\t\t\tKey: fLocation,\n\t\t\t\tExpires: uploadExpiration,\n\t\t\t};\n\n\t\t\tvar signed = self.s3.getSignedUrl('getObject', signedURLReq);\n\n\t\t\tfileAccess[fLocation] = signed;\n\t\t}\n\n\t\treturn fileAccess;\n\t}\n\n\t//in case the upload properties are failures\n\tself.asyncConfirmUploadComplete = function(uuid)\n\t{\n\t\tvar defer = Q.defer();\n\n\t\tvar isOver = false;\n\n\t\t//we have the uuid, lets fetch the existing request\n\t\tasyncRedisGet(uuid)\n\t\t\t.then(function(val)\n\t\t\t{\n\t\t\t\t//if we don't have a value -- the key doesn't exist or expired -- either way, it's a failure!\n\t\t\t\tif(!val)\n\t\t\t\t{\n\t\t\t\t\t//we're all done -- we didn't encounter an error, we just don't exist -- time to resubmit\n\t\t\t\t\tdefer.resolve({success: false, error: self.uploadErrors.nullUploadKey});\n\t\t\t\t\tisOver = true;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\t//so we have our object\n\t\t\t\tvar putRequest = JSON.parse(val);\n\n\t\t\t\t//these are all the requests we made\n\t\t\t\tvar allUploads = putRequest.uploads;\n\n\t\t\t\t//we have to check on all the objects\n\t\t\t\tvar uploadConfirmPromises = [];\n\n\t\t\t\tfor(var i=0; i < allUploads.length; i++)\n\t\t\t\t{\n\t\t\t\t\tvar req = allUploads[i].request;\n\n\t\t\t\t\tvar params = {Bucket: req.Bucket, Key: req.Key};\n\n\t\t\t\t\tuploadConfirmPromises.push(asyncHeadRequest(params));\n\t\t\t\t}\n\n\t\t\t\treturn Q.allSettled(uploadConfirmPromises);\n\t\t\t})\n\t\t\t.then(function(results)\n\t\t\t{\n\t\t\t\tif(isOver)\n\t\t\t\t\treturn;\n\n\t\t\t\t//check for existance\n\t\t\t\tvar missing = [];\n\n\t\t\t\t//now we have all the results -- we verify they're all fulfilled\n\t\t\t\tfor(var i=0; i < results.length; i++)\n\t\t\t\t{\n\t\t\t\t\tvar res = results[i];\n\t\t\t\t\tif(res.state !== \"fulfilled\")\n\t\t\t\t\t{\n\t\t\t\t\t\t// console.log(\"Results:\".red,results);\n\n\t\t\t\t\t\tdefer.resolve({success: false, error: self.uploadErrors.headCheckUnfulfilledError});\n\t\t\t\t\t\tisOver = true;\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\n\t\t\t\t\t//if one is false, we're all false\n\t\t\t\t\tif(!res.value.exists)\n\t\t\t\t\t\tmissing.push(i);\n\n\t\t\t\t}\n\n\t\t\t\t//are we missing anything???\n\t\t\t\tif(missing.length)\n\t\t\t\t{\n\t\t\t\t\tdefer.resolve({success: false, error: self.uploadErrors.headCheckMissingError, missing: missing});\n\t\t\t\t\tisOver = true;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\t//we're all confirmed, we delete the upload requests now\n\t\t\t\t//however, this is not a major concern -- it will expire shortly anyways\n\t\t\t\t//therefore, we resolve first, then delete second\n\n\t\t\t\tisOver = true;\n\t\t\t\tdefer.resolve({success: true});\n\n\t\t\t\t//if we're here, then we all exist -- it's confirmed yay!\n\t\t\t\t//we need to remove the key from our redis client -- but we're not too concerned -- they expire when they expire\n\t\t\t\treturn;//asyncRedisDelete(uuid);\n\t\t\t})\n\t\t\t.catch(function(err)\n\t\t\t{\n\t\t\t\tif(isOver)\n\t\t\t\t\treturn;\n\n\t\t\t\tdefer.reject(err);\n\t\t\t});\n\n\t\treturn defer.promise;\n\t}\n\n\tfunction asyncHeadRequest(params)\n\t{\n\t\tvar defer = Q.defer();\n\n\t\tself.s3.headObject(params, function (err, metadata) { \n\t\t\tif (err)\n\t\t\t{\n\t\t\t\t//error code is not found -- it doesn't exist!\n\t\t\t\tif(err.code === 'NotFound') { \n\t\t\t \t// Handle no object on cloud here \n\t\t\t\t\tdefer.resolve({exists: false});\n\t\t\t\t} \n\t\t\t\t//straight error -- reject\n\t\t\t\telse \n\t\t\t\t\tdefer.reject(err);\n\n\t\t\t}else { \n\t\t\t\tdefer.resolve({exists: true});\n\t\t\t}\n\t\t});\n\n\t\treturn defer.promise;\n\t}\n\n\n\tself.asyncInitializeUpload = function(uploadProperties)\n\t{\t\n\t\t//we promise to return\n\t\tvar defer = Q.defer();\n\n\t\t//create a unique ID for this upload\n\t\tvar uuid = cuid();\n\n\t\t//we send our upload properties onwards\n\t\tvar requestUploads = self.createUploadRequests(uploadProperties);\n\n\t\t//we now have a number of requests to make\n\t\t//lets process them and get some signed urls to put the objects there\n\t\tvar fullUploadRequests = [];\n\n\t\t//these will be everything we need to make a signed URL request\n\t\tfor(var i=0; i < requestUploads.length; i++)\n\t\t{\n\n\t\t\t//\n\t\t\tvar upReqName = requestUploads[i];\n\n\t\t\tvar signedURLReq = {\n\t\t\t\tBucket: bucketName, \n\t\t\t\tKey: upReqName.prepend + uuid + upReqName.append, \n\t\t\t\tExpires: uploadExpiration,\n\t\t\t\t// ACL: 'public-read'\n\t\t\t};\n\n\t\t\tvar signed = self.s3.getSignedUrl('putObject', signedURLReq);\n\n\t\t\t//store the requests here\n\t\t\tfullUploadRequests.push({url: signed, request: signedURLReq});\n\t\t}\n\n\t\t//now we have our full requests\n\t\t//let's store it in REDIS, then send it back\n\n\t\tvar inProgress = {\n\t\t\tuuid: uuid,\n\t\t\tstate : \"pending\",\n\t\t\tuploads: fullUploadRequests\n\t\t};\n\n\t\t//we set the object in our redis location\n\t\tasyncRedisSetEx(uuid, uploadExpiration, JSON.stringify(inProgress))\n\t\t\t.catch(function(err)\n\t\t\t{\n\t\t\t\tdefer.reject(err);\n\t\t\t})\n\t\t\t.done(function()\n\t\t\t{\n\t\t\t\tdefer.resolve(inProgress);\n\t\t\t});\n\n\t\t//promise for now -- return later\n\t\treturn defer.promise;\n\t}\n\n\tfunction asyncRedisSetEx(key, expire, val)\n\t{\n\t\tvar defer = Q.defer();\n\n\t\tredisClient.setex(key, expire, val, function(err)\n\t\t{\n\t\t\tif(!err)\n\t\t\t\tdefer.resolve();\n\t\t\telse\n\t\t\t\tdefer.reject(err);\n\t\t});\n\n\t\treturn defer.promise;\n\t}\n\n\tfunction asyncRedisGet(key, val)\n\t{\n\t\tvar defer = Q.defer();\n\n\t\tredisClient.get(key, function(err, val)\n\t\t{\n\t\t\tif(!err)\n\t\t\t\tdefer.resolve(val);\n\t\t\telse\n\t\t\t\tdefer.reject(err);\n\t\t});\n\n\t\treturn defer.promise;\n\t}\n\n\tfunction asyncRedisDelete(key, val)\n\t{\n\t\tvar defer = Q.defer();\n\n\t\tredisClient.del(key, function(err, reply)\n\t\t{\n\t\t\tif(!err)\n\t\t\t\tdefer.resolve();\n\t\t\telse\n\t\t\t\tdefer.reject(err);\n\t\t});\n\n\t\treturn defer.promise;\n\t}\n\n\treturn self;\n}", "putObject(bucketName, objectName, contentType, size, r, cb) {\n if (!validateBucketName(bucketName)) {\n throw new errors.InvalidateBucketNameException('Invalid bucket name: ' + bucketName)\n }\n\n if (objectName === null || objectName.trim() === '') {\n throw new errors.InvalidObjectNameException('Object name cannot be empty')\n }\n\n if (contentType === null || contentType.trim() === '') {\n contentType = 'application/octet-stream'\n }\n\n function calculatePartSize(size) {\n var minimumPartSize = 5 * 1024 * 1024, // 5MB\n maximumPartSize = 5 * 1025 * 1024 * 1024,\n // using 10000 may cause part size to become too small, and not fit the entire object in\n partSize = Math.floor(size / 9999)\n\n if (partSize > maximumPartSize) {\n return maximumPartSize\n }\n return Math.max(minimumPartSize, partSize)\n }\n\n var self = this\n if (size <= 5*1024*1024) {\n var concater = transformers.getConcater()\n pipesetup(r, concater)\n .on('error', e => cb(e))\n .on('data', chunk => self.doPutObject(bucketName, objectName, contentType, null, null, chunk, cb))\n return\n }\n async.waterfall([\n function(cb) {\n self.findUploadId(bucketName, objectName, cb)\n },\n function(uploadId, cb) {\n if (uploadId) {\n self.listAllParts(bucketName, objectName, uploadId, (e, etags) => {\n return cb(e, uploadId, etags)\n })\n return\n }\n self.initiateNewMultipartUpload(bucketName, objectName, contentType, (e, uploadId) => {\n return cb(e, uploadId, [])\n })\n },\n function(uploadId, etags, cb) {\n var partSize = calculatePartSize(size)\n var sizeVerifier = transformers.getSizeVerifierTransformer(size)\n var chunker = BlockStream2({size: partSize, zeroPadding: false})\n var chunkUploader = self.chunkUploader(bucketName, objectName, contentType, uploadId, etags)\n pipesetup(r, chunker, sizeVerifier, chunkUploader)\n .on('error', e => cb(e))\n .on('data', etags => cb(null, etags, uploadId))\n },\n function(etags, uploadId, cb) {\n self.completeMultipartUpload(bucketName, objectName, uploadId, etags, cb)\n }\n ], function(err, etag) {\n if (err) {\n return cb(err)\n }\n cb(null, etag)\n })\n }", "async function uploadImageToS3(imageUrl, idx) {\n\n const image = await readImageFromUrl(imageUrl, idx);\n\n const imagePath = imageUrl.split(`https://divisare-res.cloudinary.com/`)[1];\n const objectParams = {\n Bucket: 'bersling-divisaire',\n // i already created /aaa-testing, /testing and testing :)\n Key: `images6/${imagePath}`,\n Body: image,\n ContentType: 'image/jpg'\n };\n // Create object upload promise\n const uploadPromise = new AWS.S3({apiVersion: '2006-03-01', region: 'eu-central-1'})\n .putObject(objectParams)\n .promise();\n uploadPromise\n .then((data) => {\n // nothing to do...\n logger(`uploaded image...`);\n }).catch(err => {\n logger(\"ERROR\");\n logger(err);\n });\n return uploadPromise;\n\n\n}", "function cfnFunctionS3LocationPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnFunction_S3LocationPropertyValidator(properties).assertSuccess();\n return {\n Bucket: cdk.stringToCloudFormation(properties.bucket),\n Key: cdk.stringToCloudFormation(properties.key),\n Version: cdk.numberToCloudFormation(properties.version),\n };\n}", "function cfnFunctionS3LocationPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnFunction_S3LocationPropertyValidator(properties).assertSuccess();\n return {\n Bucket: cdk.stringToCloudFormation(properties.bucket),\n Key: cdk.stringToCloudFormation(properties.key),\n Version: cdk.numberToCloudFormation(properties.version),\n };\n}", "function createShadowBucket(key, uploadId) {\n const overviewKey = `overview${constants.splitter}` +\n `${key}${constants.splitter}${uploadId}`;\n metadata.buckets\n .set(mpuShadowBucket, new BucketInfo(mpuShadowBucket, ownerID, '', ''));\n // Set modelVersion to use the most recent splitter.\n Object.assign(metadata.buckets.get(mpuShadowBucket), {\n _mdBucketModelVersion: 5,\n });\n metadata.keyMaps.set(mpuShadowBucket, new Map);\n metadata.keyMaps.get(mpuShadowBucket).set(overviewKey, new Map);\n Object.assign(metadata.keyMaps.get(mpuShadowBucket).get(overviewKey), {\n id: uploadId,\n eventualStorageBucket: bucketName,\n initiator: {\n DisplayName: 'accessKey1displayName',\n ID: ownerID },\n key,\n uploadId,\n });\n}", "async uploadToS3(jsonFile) {\n const params = {\n Bucket: \"time-tracking-storage\",\n Key:\n TIME_PAGE_PREFIX +\n this.state.selectedFile.name.split(CSV_FILE_ATTACHMENT, 1).join(\"\"),\n ContentType: \"json\",\n Body: JSON.stringify(jsonFile),\n };\n\n s3.putObject(params, (err, data) => {\n if (data) {\n this.getListS3();\n } else {\n console.log(\"Error: \" + err);\n this.setState({ labelValue: params.Key + \" not uploaded.\" });\n }\n });\n\n this.setState({\n labelValue: params.Key + \" upload successfully.\",\n selectedFile: null,\n });\n }", "removeBucketTagging(bucketName, cb) {\n if (!isValidBucketName(bucketName)) {\n throw new errors.InvalidBucketNameError('Invalid bucket name: ' + bucketName)\n }\n if (!isFunction(cb)) {\n throw new TypeError('callback should be of type \"function\"')\n }\n return this.removeTagging({ bucketName, cb })\n }", "function main(\n bucketName = 'my-bucket',\n maxAgeSeconds = 3600,\n method = 'POST',\n origin = 'http://example.appspot.com',\n responseHeader = 'content-type'\n) {\n // [START storage_cors_configuration]\n // Imports the Google Cloud client library\n const {Storage} = require('@google-cloud/storage');\n\n // Creates a client\n const storage = new Storage();\n\n /**\n * TODO(developer): Uncomment the following lines before running the sample.\n */\n // The ID of your GCS bucket\n // const bucketName = 'your-unique-bucket-name';\n\n // The origin for this CORS config to allow requests from\n // const origin = 'http://example.appspot.com';\n\n // The response header to share across origins\n // const responseHeader = 'Content-Type';\n\n // The maximum amount of time the browser can make requests before it must\n // repeat preflighted requests\n // const maxAgeSeconds = 3600;\n\n // The name of the method\n // See the HttpMethod documentation for other HTTP methods available:\n // https://cloud.google.com/appengine/docs/standard/java/javadoc/com/google/appengine/api/urlfetch/HTTPMethod\n // const method = 'GET';\n\n async function configureBucketCors() {\n await storage.bucket(bucketName).setCorsConfiguration([\n {\n maxAgeSeconds,\n method: [method],\n origin: [origin],\n responseHeader: [responseHeader],\n },\n ]);\n\n console.log(`Bucket ${bucketName} was updated with a CORS config\n to allow ${method} requests from ${origin} sharing \n ${responseHeader} responses across origins`);\n }\n\n configureBucketCors().catch(console.error);\n // [END storage_cors_configuration]\n}", "async function createOrUpdateAVaultWithNetworkAcls() {\n const subscriptionId =\n process.env[\"KEYVAULT_SUBSCRIPTION_ID\"] || \"00000000-0000-0000-0000-000000000000\";\n const resourceGroupName = process.env[\"KEYVAULT_RESOURCE_GROUP\"] || \"sample-resource-group\";\n const vaultName = \"sample-vault\";\n const parameters = {\n location: \"westus\",\n properties: {\n enabledForDeployment: true,\n enabledForDiskEncryption: true,\n enabledForTemplateDeployment: true,\n networkAcls: {\n bypass: \"AzureServices\",\n defaultAction: \"Deny\",\n ipRules: [{ value: \"124.56.78.91\" }, { value: \"'10.91.4.0/24'\" }],\n virtualNetworkRules: [\n {\n id: \"/subscriptions/subid/resourceGroups/rg1/providers/Microsoft.Network/virtualNetworks/test-vnet/subnets/subnet1\",\n },\n ],\n },\n sku: { name: \"standard\", family: \"A\" },\n tenantId: \"00000000-0000-0000-0000-000000000000\",\n },\n };\n const credential = new DefaultAzureCredential();\n const client = new KeyVaultManagementClient(credential, subscriptionId);\n const result = await client.vaults.beginCreateOrUpdateAndWait(\n resourceGroupName,\n vaultName,\n parameters\n );\n console.log(result);\n}", "getBucketACL(bucket, cb) {\n if (!validateBucketName(bucket)) {\n throw new errors.InvalidateBucketNameException('Invalid bucket name: ' + bucket)\n }\n\n var query = `?acl`,\n requestParams = {\n host: this.params.host,\n port: this.params.port,\n protocol: this.params.protocol,\n method: 'GET',\n path: `/${bucket}${query}`\n }\n\n signV4(requestParams, '', this.params.accessKey, this.params.secretKey)\n var req = this.transport.request(requestParams, response => {\n var concater = transformers.getConcater()\n var errorTransformer = transformers.getErrorTransformer(response)\n var transformer = transformers.getAclTransformer()\n if (response.statusCode !== 200) {\n pipesetup(response, concater, errorTransformer)\n .on('error', e => cb(e))\n return\n }\n pipesetup(response, concater, transformer)\n .on('error', e => cb(e))\n .on('data', data => {\n var perm = data.acl.reduce(function(acc, grant) {\n if (grant.grantee.uri === 'http://acs.amazonaws.com/groups/global/AllUsers') {\n if (grant.permission === 'READ') {\n acc.publicRead = true\n } else if (grant.permission === 'WRITE') {\n acc.publicWrite = true\n }\n } else if (grant.grantee.uri === 'http://acs.amazonaws.com/groups/global/AuthenticatedUsers') {\n if (grant.permission === 'READ') {\n acc.authenticatedRead = true\n } else if (grant.permission === 'WRITE') {\n acc.authenticatedWrite = true\n }\n }\n return acc\n }, {})\n var cannedACL = 'unsupported-acl'\n if (perm.publicRead && perm.publicWrite && !perm.authenticatedRead && !perm.authenticatedWrite) {\n cannedACL = 'public-read-write'\n } else if (perm.publicRead && !perm.publicWrite && !perm.authenticatedRead && !perm.authenticatedWrite) {\n cannedACL = 'public-read'\n } else if (!perm.publicRead && !perm.publicWrite && perm.authenticatedRead && !perm.authenticatedWrite) {\n cannedACL = 'authenticated-read'\n } else if (!perm.publicRead && !perm.publicWrite && !perm.authenticatedRead && !perm.authenticatedWrite) {\n cannedACL = 'private'\n }\n cb(null, cannedACL)\n })\n })\n req.on('error', e => cb(e))\n req.end()\n }", "bucketExists(bucketName, cb) {\n if (!isValidBucketName(bucketName)) {\n throw new errors.InvalidBucketNameError('Invalid bucket name: ' + bucketName)\n }\n if (!isFunction(cb)) {\n throw new TypeError('callback should be of type \"function\"')\n }\n var method = 'HEAD'\n this.makeRequest({ method, bucketName }, '', [200], '', false, (err) => {\n if (err) {\n if (err.code == 'NoSuchBucket' || err.code == 'NotFound') {\n return cb(null, false)\n }\n return cb(err)\n }\n cb(null, true)\n })\n }", "bucketExists(bucket, cb) {\n if (!validateBucketName(bucket)) {\n throw new errors.InvalidateBucketNameException('Invalid bucket name: ' + bucket)\n }\n this.bucketRequest('HEAD', bucket, cb)\n }", "function deleteBucket() {\n var request = gapi.client.storage.buckets.delete({\n 'bucket': BUCKET\n });\n executeRequest(request, 'deleteBucket');\n}", "function insertObjectAccessControls() {\n resource = {\n 'entity': ENTITY,\n 'role': ROLE_OBJECT\n };\n\n var request = gapi.client.storage.objectAccessControls.insert({\n 'bucket': BUCKET,\n 'object': object,\n 'resource': resource\n });\n executeRequest(request, 'insertObjectAccessControls');\n}", "async syncDirectory() {\n const s3Bucket = this.serverless.variables.service.custom.s3Bucket;\n const args = ['s3', 'sync', 'build/', `s3://${s3Bucket}/`, '--delete'];\n const exitCode = await this.runAwsCommand(args);\n if (!exitCode) {\n this.serverless.cli.log('Successfully synced to the S3 bucket');\n } else {\n throw new Error('Failed syncing to the S3 bucket');\n }\n }", "async function putContainerWithDefaultEncryptionScope() {\n const subscriptionId = process.env[\"STORAGE_SUBSCRIPTION_ID\"] || \"{subscription-id}\";\n const resourceGroupName = process.env[\"STORAGE_RESOURCE_GROUP\"] || \"res3376\";\n const accountName = \"sto328\";\n const containerName = \"container6185\";\n const blobContainer = {\n defaultEncryptionScope: \"encryptionscope185\",\n denyEncryptionScopeOverride: true,\n };\n const credential = new DefaultAzureCredential();\n const client = new StorageManagementClient(credential, subscriptionId);\n const result = await client.blobContainers.create(\n resourceGroupName,\n accountName,\n containerName,\n blobContainer\n );\n console.log(result);\n}", "function cfnFaqS3PathPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnFaq_S3PathPropertyValidator(properties).assertSuccess();\n return {\n Bucket: cdk.stringToCloudFormation(properties.bucket),\n Key: cdk.stringToCloudFormation(properties.key),\n };\n}", "function cfnDatastoreCustomerManagedS3StoragePropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnDatastore_CustomerManagedS3StoragePropertyValidator(properties).assertSuccess();\n return {\n Bucket: cdk.stringToCloudFormation(properties.bucket),\n KeyPrefix: cdk.stringToCloudFormation(properties.keyPrefix),\n };\n}", "function startNewUpload(cb){\n\tgenerateNewUploadParameters(function(err, params){\n\t\tif(err){\n\t\t\tcb(err)\n\t\t} else {\n\t\t\ts3.createMultiPartUpload(uploadParameters, function(err, data){\n\t\t\t\tcb(err, data)\n\t\t\t})\n\t\t}\n\t})\n}", "async function uploadToBucket(userId, file, fileType) {\n if (![AUDIO_TYPE, IMAGE_TYPE].includes(fileType)) {\n throw Error(\"File type is invalid!\");\n }\n const params = {\n Bucket: BUCKET_NAME,\n Key: `${fileType}/${userId}/${file.filename}`,\n // I'm running windows so the replacement will be removed when on production\n Body: fs.createReadStream(file.path.replace(\"\\\\\", \"/\"))\n };\n await S3_CONTROL.upload(params).promise();\n fs.unlinkSync(file.path);\n}", "function storeToS3(env, data, callback){\n // get the investigators cached version from AWS.\n if (!isValidEnv(env)){\n callback(\"Invalid env passed into storeToS3()\");\n return;\n }\n // construct the filename from the env\n var filename = getS3FilePath(env);\n var params = {\n Bucket: AWS_BUCKET_NAME,\n Key: filename,\n Body: JSON.stringify(data)\n };\n // upload the file...\n console.log(\"Uploading list to s3...\");\n s3.upload(params, function(err, data){\n if (err){\n callback(\"storeToS3 S3: \" + err);\n } else {\n console.log(\"S3 upload success: s3://\" + AWS_BUCKET_NAME + '/' + filename);\n callback(null, data);\n }\n });\n}", "function cfnFunctionBucketSAMPTPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnFunction_BucketSAMPTPropertyValidator(properties).assertSuccess();\n return {\n BucketName: cdk.stringToCloudFormation(properties.bucketName),\n };\n}", "function cfnFunctionBucketSAMPTPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnFunction_BucketSAMPTPropertyValidator(properties).assertSuccess();\n return {\n BucketName: cdk.stringToCloudFormation(properties.bucketName),\n };\n}", "function after (s3, bucket, keys, done) {\n when.all(\n // Swallow deleteObject errors here incase the files don't yet exist\n keys.map(function (key) { return deleteObject(s3, bucket, key).catch(function() {}); })\n ).then(function () { done(); });\n}", "function cfnDataSourceS3PathPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnDataSource_S3PathPropertyValidator(properties).assertSuccess();\n return {\n Bucket: cdk.stringToCloudFormation(properties.bucket),\n Key: cdk.stringToCloudFormation(properties.key),\n };\n}", "async function putS3(fileKey, data) {\n oLog.verbose(__filename, 'putS3');\n\n try {\n if (configs.aws.s3.active) {\n // set aws region:\n rAWS.config.update({\n region: configs.aws.s3.region\n });\n // bucket info:\n let s3Bucket = configs.aws.s3.s3bucket;\n let s3FileKey = fileKey;\n let s3Params = {\n Bucket: s3Bucket,\n Key: s3FileKey,\n Body: data\n };\n\n // get object and parse the JSON:\n return rS3.putObject(s3Params).promise();\n } else {\n // empty object if not active:\n return {};\n }\n } catch (error) {\n oLog.error(__filename, 'putS3', error);\n return error;\n }\n}", "function upload(object, name) {\n var params = {\n localFile: object.path,\n s3Params: {\n Bucket: 'giscollective',\n Key: 'projectlinework/' + name + '.zip',\n ACL: 'public-read'\n },\n };\n var uploader = client.uploadFile(params);\n uploader.on('error', function(err) {\n console.error(\"unable to upload:\", err.stack);\n });\n uploader.on('progress', function() {\n console.log(\"progress\", uploader.progressMd5Amount, uploader.progressAmount, uploader.progressTotal);\n });\n uploader.on('end', function() {\n console.log(\"done uploading\");\n });\n}", "function uploadToS3(file_path, s3_file_path, cb)\n{\n\tconsole.log(\"Uploading to S3 file: \" + file_path, \"to: \" + s3_file_path);\n\n\theaders = {'x-amz-acl': 'public-read'};\n\ts3Client.putFile(file_path, s3_file_path, headers, function(err, s3Response) {\n\t if (err)\n \t{\n \t\tconsole.log(\"ERROR: \" + util.inspect(err));\n \t\tthrow err;\n \t}\n\t \n\t destUrl = s3Response.req.url;\n\n\t cb();\n\t});\n}", "function cfnDatasetS3DestinationConfigurationPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnDataset_S3DestinationConfigurationPropertyValidator(properties).assertSuccess();\n return {\n Bucket: cdk.stringToCloudFormation(properties.bucket),\n GlueConfiguration: cfnDatasetGlueConfigurationPropertyToCloudFormation(properties.glueConfiguration),\n Key: cdk.stringToCloudFormation(properties.key),\n RoleArn: cdk.stringToCloudFormation(properties.roleArn),\n };\n}", "function cfnDatastoreCustomerManagedS3PropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnDatastore_CustomerManagedS3PropertyValidator(properties).assertSuccess();\n return {\n Bucket: cdk.stringToCloudFormation(properties.bucket),\n KeyPrefix: cdk.stringToCloudFormation(properties.keyPrefix),\n RoleArn: cdk.stringToCloudFormation(properties.roleArn),\n };\n}", "function validateS3BucketName(name, sslVhost = false) {\n // http://docs.aws.amazon.com/AmazonS3/latest/dev/BucketRestrictions.html\n\n // Bucket names must be at least 3 and no more than 63 characters long.\n if (name.length < 3 || name.length > 63) {\n return false;\n }\n\n // Bucket names must be a series of one or more labels. Adjacent labels are\n // separated by a single period (.). Bucket names can contain lowercase\n // letters, numbers, and hyphens. Each label must start and end with a\n // lowercase letter or a number.\n if (/\\.\\./.exec(name) || /^[^a-z0-9]/.exec(name) || /[^a-z0-9]$/.exec(name)) {\n return false;\n };\n if (! /^[a-z0-9-\\.]*$/.exec(name)) {\n return false;\n }\n\n //Bucket names must not be formatted as an IP address (e.g., 192.168.5.4)\n // https://www.safaribooksonline.com/library/view/regular-expressions-cookbook/9780596802837/ch07s16.html\n if (/^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/.exec(name)) {\n return false;\n }\n\n // When using virtual hosted–style buckets with SSL, the SSL wild card\n // certificate only matches buckets that do not contain periods. To work\n // around this, use HTTP or write your own certificate verification logic.\n if (sslVhost) {\n if (/\\./.exec(name)) {\n return false;\n }\n }\n\n return true;\n}", "getBucketLifecycle(bucketName, cb) {\n if (!isValidBucketName(bucketName)) {\n throw new errors.InvalidBucketNameError('Invalid bucket name: ' + bucketName)\n }\n const method = 'GET'\n const query = 'lifecycle'\n const requestOptions = { method, bucketName, query }\n\n this.makeRequest(requestOptions, '', [200], '', true, (e, response) => {\n const transformer = transformers.lifecycleTransformer()\n if (e) {\n return cb(e)\n }\n let lifecycleConfig\n pipesetup(response, transformer)\n .on('data', (result) => (lifecycleConfig = result))\n .on('error', (e) => cb(e))\n .on('end', () => cb(null, lifecycleConfig))\n })\n }", "function upload_private_S3_resource(file, folder, cFunc) {\n\tvar xhr = new XMLHttpRequest();\n\t// var amz_sign_s3 is defined in script on HTML page\n\txhr.open(\"GET\", amz_sign_s3+\"?file_name=\"+file.name+\"&file_type=\"+file.type+\"&folder=\"+folder);\n\txhr.onreadystatechange = function(){\n\t\tif(xhr.readyState === 4){\n\t\t\tif(xhr.status === 200){\n\t\t\t\tvar response = JSON.parse(xhr.responseText);\n\t\t\t\tupload_file(file, response.signed_request, response.url, cFunc);\n\t\t\t}\n\t\t\telse{\n\t\t\t\talert(\"Could not get signed URL.\");\n\t\t\t}\n\t\t}\n\t};\n\txhr.send();\n}", "function cfnLayerVersionS3LocationPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnLayerVersion_S3LocationPropertyValidator(properties).assertSuccess();\n return {\n Bucket: cdk.stringToCloudFormation(properties.bucket),\n Key: cdk.stringToCloudFormation(properties.key),\n Version: cdk.numberToCloudFormation(properties.version),\n };\n}", "function createCity( name, region ) {\n\treturn {\n\t\tname,\n\t\tregion\n\t}\n}", "function insert(item, user, request) {\n var accountName = ''; // add your storage account name\n var accountKey = ''; // add your storage account key\n var host = accountName + '.blob.core.windows.net';\n var canonicalizedResource = '/' + item.ContainerName + '/' + item.ResourceName;\n item.ContainerName = item.ContainerName.toLowerCase(); // must be lowercase\n\n // create the container if it does not exist\n // we will use public read access for the blobs and will use a SAS to upload \n var blobService = azure.createBlobService(accountName, accountKey, host);\n blobService.createContainerIfNotExists(\n item.ContainerName, { publicAccessLevel: 'blob' },\n function (error) {\n if (!error) {\n // container exists now define a policy that provides write access \n // that starts immediately and expires in 5 mins \n var sharedAccessPolicy = {\n AccessPolicy: {\n Permissions: azure.Constants.BlobConstants.SharedAccessPermissions.WRITE,\n Expiry: formatDate(new Date(new Date().getTime() + 5 * 60 * 1000)) //5 minutes from now\n }\n };\n\n // generate the SAS for your BLOB\n var sasQueryString = getSAS(accountName, accountKey, canonicalizedResource, azure.Constants.BlobConstants.ResourceTypes.BLOB, sharedAccessPolicy);\n\n // Store blob URL and SAS\n item.BlobUrl = 'https://' + host + canonicalizedResource;\n item.SAS = sasQueryString;\n\n } else { console.error(error); }\n\n request.execute();\n });\n}", "_manageCronJob (evt, region) {\n let _this = this;\n\n _this.stage = evt.options.stage;\n _this._initAws(region);\n\n if (_this.S.cli.action != 'deploy' || (_this.S.cli.context != 'function' && _this.S.cli.context != 'dash'))\n return;\n\n _this.cronJobSettings = _this._getFunctionsCronJobSettings(evt, region);\n\n // no cron.json found\n if (_this.cronJobSettings.length == 0) {\n return;\n }\n\n for (var i in _this.cronJobSettings) { \n var params = {\n \"Name\": _this.cronJobSettings[i].cronjob.name,\n \"Description\": _this.cronJobSettings[i].cronjob.description,\n \"ScheduleExpression\": _this.cronJobSettings[i].cronjob.schedule,\n \"State\": (_this.cronJobSettings[i].cronjob.enabled == true ? \"ENABLED\" : \"DISABLED\")\n };\n\n _this.cloudWatchEvents.putRuleAsync(params)\n .then(function(result){\n return _this.lambda.addPermissionAsync({\n FunctionName: _this._getFunctionArn(_this.cronJobSettings[i]),\n StatementId: Date.now().toString(),\n Action: 'lambda:InvokeFunction',\n Principal: 'events.amazonaws.com',\n Qualifier: _this.stage\n })\n .then(function(){\n console.log('permissions added');\n })\n .catch(function(e) {\n console.log('error during adding permission to Lambda');\n console.log(e);\n });\n })\n .then(function(result){\n var _this = this;\n\n return _this.cloudWatchEvents.putTargetsAsync({\n Rule: _this.cronJobSettings[i].cronjob.name,\n Targets: [\n {\n Arn: _this.cronJobSettings[i].deployed.Arn,\n Id: _this._getTargetId(_this.cronJobSettings[i])\n }\n ]\n })\n .then(function(){\n console.log('cronjob created');\n })\n .catch(function(e) {\n console.log('error during creation of cronjob targets');\n console.log(e);\n });\n }.bind(_this))\n .catch(function(e) {\n console.log('error during creation of cronjob rules');\n console.log(e);\n });\n }\n }", "presignedGetObject(bucketName, objectName, expires) {\n if (!validateBucketName(bucketName)) {\n throw new errors.InvalidateBucketNameException('Invalid bucket name: ' + bucketName)\n }\n if (objectName === null || objectName.trim() === '') {\n throw new errors.InvalidObjectNameException('Object name cannot be empty')\n }\n var requestParams = {\n host: this.params.host,\n port: this.params.port,\n protocol: this.params.protocol,\n path: `/${bucketName}/${uriResourceEscape(objectName)}`,\n method: 'GET',\n expires: expires\n }\n return presignSignatureV4(requestParams, this.params.accessKey, this.params.secretKey)\n }", "function cfnResourceDataSyncS3DestinationPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnResourceDataSync_S3DestinationPropertyValidator(properties).assertSuccess();\n return {\n BucketName: cdk.stringToCloudFormation(properties.bucketName),\n BucketPrefix: cdk.stringToCloudFormation(properties.bucketPrefix),\n BucketRegion: cdk.stringToCloudFormation(properties.bucketRegion),\n KMSKeyArn: cdk.stringToCloudFormation(properties.kmsKeyArn),\n SyncFormat: cdk.stringToCloudFormation(properties.syncFormat),\n };\n}", "function awsUpload() {\n\n //configuring the AWS environment\n AWS.config.update({\n accessKeyId: \"AKIAIYOTGRTBNHAJOWKQ\",\n secretAccessKey: \"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\"\n });\n var s3 = new AWS.S3();\n var filePath = \"./images/\" + imageLocation;\n\n //Configuring Parameters\n var params = {\n Bucket: 'pricefinder-bucket',\n Body: fs.createReadStream(filePath),\n Key: \"images/\" + Date.now() + \"_\" + path.basename(filePath)\n };\n\n //Uploading to s3 Bucket\n s3.upload(params, function (err, data) {\n //if an error occurs, handle it\n if (err) {\n console.log(\"Error\", err);\n }\n if (data) {\n console.log();\n console.log(\"Uploaded in:\", data.Location);\n console.log();\n }\n });\n\n customVision();\n\n}", "function parseS3Arn(arn = '') {\n // arn:aws:s3:::123456789012-study/studies/Organization/org-study-a1/*\n let trimmed = _.trim(arn);\n if (_.isEmpty(arn)) return;\n\n if (!_.startsWith(trimmed, 'arn:')) return;\n\n // Remove the 'arn:' part\n trimmed = trimmed.substring('arn:'.length);\n\n // Get the partition part\n const partition = _.nth(_.split(trimmed, ':'), 0);\n\n // Check if it is still an s3 arn\n if (!_.startsWith(trimmed, `${partition}:s3:::`)) return;\n\n // Remove the partition part\n trimmed = trimmed.substring(`${partition}:s3:::`.length);\n\n // Get the bucket part\n const bucket = _.nth(_.split(trimmed, '/'), 0);\n\n // Check if the bucket is not an empty string\n if (_.isEmpty(bucket)) return;\n\n // Remove the bucket part\n trimmed = trimmed.substring(bucket.length);\n\n let prefix = '/';\n if (!_.isEmpty(trimmed)) {\n prefix = chopLeft(trimmed, '/');\n prefix = chopRight(prefix, '*');\n prefix = _.endsWith(prefix, '/') ? prefix : `${prefix}/`;\n }\n\n // eslint-disable-next-line consistent-return\n return {\n awsPartition: partition,\n bucket,\n prefix,\n };\n}" ]
[ "0.6601366", "0.6447514", "0.6321086", "0.6151867", "0.59054697", "0.5812531", "0.56383574", "0.55606496", "0.52550286", "0.5231392", "0.52298784", "0.5211462", "0.5177788", "0.5154573", "0.5074082", "0.5033663", "0.5000525", "0.49613637", "0.49590954", "0.49452496", "0.49071693", "0.48953682", "0.48701298", "0.48532036", "0.4832342", "0.4824571", "0.48073322", "0.4790019", "0.47608578", "0.4754329", "0.4754212", "0.4725087", "0.46950924", "0.46805388", "0.46525413", "0.46456993", "0.46387833", "0.45928895", "0.45714706", "0.45557895", "0.45498964", "0.45479587", "0.45301986", "0.4454941", "0.44472307", "0.44391343", "0.4433668", "0.4433668", "0.44101113", "0.44030032", "0.4402407", "0.4401596", "0.4391208", "0.4391208", "0.43862268", "0.43611237", "0.4360637", "0.43573654", "0.43434513", "0.43370163", "0.4330934", "0.43267447", "0.43267447", "0.43180528", "0.43148944", "0.43107355", "0.4310349", "0.429728", "0.4286705", "0.42835295", "0.42739782", "0.42515376", "0.4247428", "0.42413497", "0.42393658", "0.42350307", "0.42321503", "0.4223934", "0.42149678", "0.42115343", "0.4199757", "0.4199757", "0.41909745", "0.4189702", "0.41879416", "0.41788077", "0.41776302", "0.41735974", "0.41713923", "0.41585302", "0.41579777", "0.41544023", "0.41505998", "0.41503218", "0.4134589", "0.41336024", "0.4132458", "0.4124839", "0.4119846", "0.4117824" ]
0.8114524
0