query
stringlengths
9
34k
document
stringlengths
8
5.39M
negatives
sequencelengths
19
20
metadata
dict
Constructor: pmaLayout Constructs a new fast pma layout for the specified graph.
function pmaLayout(graph) { mxGraphLayout.call(this, graph); }
[ "function GraphArea(graphManager){\n\tthis.svgManager = graphManager.svgManager;\n\tthis.graphManager = graphManager;\n\t// this.padding = 0.1;\n\t// this.paddingLeft=0.1;\n\t// this.paddingRight = 0.02;\n\tthis.paddingRightPx = 25;\n\t// this.paddingBottom = 0.15;\n\t// this.paddingTop = 0.01;\n\tthis.graphPadding = 0.1;\n\t\n}", "function wfExpandLayout(graph, spacing, ltrEdges) {\r\n\tmxGraphLayout.call(this, graph);\r\n\tthis.spacing = spacing || 0;\r\n\tthis.ltrEdges = ltrEdges;\r\n}", "constructor() {\n this.graph = {};\n }", "function createLayout(members, alignment) {\n if (alignment === void 0) alignment = 1;\n\n var offset = 0;\n var maxSize = 0;\n var layoutMembers = members.map(function (member) {\n assert_1(member.name.length);\n var typeSize = sizeOf(member.type);\n var memberOffset = offset = align(offset, Math.max(alignment, typeSize));\n var components = member.components || 1;\n\n maxSize = Math.max(maxSize, typeSize);\n offset += typeSize * components;\n\n return {\n name: member.name,\n type: member.type,\n components: components,\n offset: memberOffset\n };\n });\n\n var size = align(offset, Math.max(maxSize, alignment));\n\n return {\n members: layoutMembers,\n size: size,\n alignment: alignment\n };\n }", "static allocate(params) {\n let data;\n let keys;\n\n if ('basePubkey' in params) {\n const type = SYSTEM_INSTRUCTION_LAYOUTS.AllocateWithSeed;\n data = encodeData(type, {\n base: toBuffer(params.basePubkey.toBuffer()),\n seed: params.seed,\n space: params.space,\n programId: toBuffer(params.programId.toBuffer())\n });\n keys = [{\n pubkey: params.accountPubkey,\n isSigner: false,\n isWritable: true\n }, {\n pubkey: params.basePubkey,\n isSigner: true,\n isWritable: false\n }];\n } else {\n const type = SYSTEM_INSTRUCTION_LAYOUTS.Allocate;\n data = encodeData(type, {\n space: params.space\n });\n keys = [{\n pubkey: params.accountPubkey,\n isSigner: true,\n isWritable: true\n }];\n }\n\n return new TransactionInstruction({\n keys,\n programId: this.programId,\n data\n });\n }", "function updateInputGraph (inputGraph, layoutGraph) {\n _.forEach(inputGraph.nodes(), function (v) {\n var inputLabel = inputGraph.node(v)\n var layoutLabel = layoutGraph.node(v)\n\n if (inputLabel) {\n inputLabel.x = layoutLabel.x\n inputLabel.y = layoutLabel.y\n\n if (layoutGraph.children(v).length) {\n inputLabel.width = layoutLabel.width\n inputLabel.height = layoutLabel.height\n }\n }\n })\n\n _.forEach(inputGraph.edges(), function (e) {\n var inputLabel = inputGraph.edge(e)\n var layoutLabel = layoutGraph.edge(e)\n\n inputLabel.points = layoutLabel.points\n if (_.has(layoutLabel, 'x')) {\n inputLabel.x = layoutLabel.x\n inputLabel.y = layoutLabel.y\n }\n })\n\n inputGraph.graph().width = layoutGraph.graph().width\n inputGraph.graph().height = layoutGraph.graph().height\n}", "function renderQueryGraph(dataSourceInfo,resultData){\n \t\n \tvar width = 650;\n var height = 175;\n var cx=0;var cy=0;\n \tvar tmpGY=0,tmpFY=0;\n //Testing Purpose\n Graph.Layout.Fixed = function(graph) {\n this.graph = graph;\n this.layout();\n };\n Graph.Layout.Fixed.prototype = {\n layout: function() {\n this.layoutPrepare();\n this.layoutCalcBounds();\n },\n\n layoutPrepare: function() {\n for (i in this.graph.nodes) {\n var node = this.graph.nodes[i];\n if (node.x) {\n node.layoutPosX = node.x;\n } else {\n node.layoutPosX = 0;\n }\n if (node.y) {\n node.layoutPosY = node.y;\n } else {\n node.layoutPosY = 0;\n }\n }\n },\n\n layoutCalcBounds: function() {\n var minx = Infinity, maxx = -Infinity, miny = Infinity, maxy = -Infinity;\n\n for (i in this.graph.nodes) {\n var x = this.graph.nodes[i].layoutPosX;\n var y = this.graph.nodes[i].layoutPosY;\n \n if(x > maxx) maxx = x;\n if(y > maxy) maxy = y;\n if(y < miny) miny = y;\n if(x < minx) minx = x;\n }\n //minx=20;\n this.graph.layoutMinX = minx;\n this.graph.layoutMaxX = maxx;\n\n this.graph.layoutMinY = miny;\n this.graph.layoutMaxY = maxy;\n }\n };\n //Testing Purpose\t\n var g = new Graph();\n g.edgeFactory.template.style.directed = true;\n\n var render = function(r, n) {\n var label = r.text(0, 30, n.label).attr({opacity:0});\n var yourSet=r.set();\n //the Raphael set is obligatory, containing all you want to display \n var set = r.set().push(\n r.rect(-30, -13, 52, 26)\n .attr({\"fill\": \"#fa8\",\n \"stroke-width\": 2\n , r : 5}))\n .push(r.text(-5, 0, n.label).attr({\"fill\": \"#000000\"}));\n return set;\n \t\t};\n\n \t$.each(datasourceList , function() {\n\t\t// Label Name to Make \"START\"\n\t\tif(this.label==\"DS0\")\n\t\t{\n\t\t\tlabelName=\"START\";\n\t\t\tcx= 0;cy=250;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif(this.type==\"Filter\")\n\t\t\t{\n\t\t\t\tcx=50;\n\t\t\t\ttmpFY=tmpFY+75;\n\t\t\t\tcy=tmpFY;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tcx=100;\n\t\t\t\ttmpGY=tmpGY+75;\n\t\t\t\tcy=tmpGY;\n\t\t\t}\n\t\t\tlabelName=this.label;\t\n\t\t}\n\t\t// Adding the Node\n\t\tg.addNode(this.label,{x:cx, y:cy, label : labelName, render : render});\n\t\tif (this.edge.length > 0) {\n\t\t\tfor (j=0;j<this.edge.length;j++) {\t\n\t\t\t\t//To make a connection between two nodes\n\t\t\t\tg.addEdge(this.edge[j][0],this.edge[j][1],{stroke : this.color});\n\t\t\t}\n\t\t}\n });\n\t// to make a connection between Result and other Nodes\n\tif(resultData.length>0)\n\t{\n\t\tg.addNode(\"RESULT\",{x:170,y:250,label:\"RESULT\",directed : false, render : render})\n\t\tfor(var k=0; k< resultData.length;k++)\n\t\t{\n\t\t\tg.addEdge(resultData[k],\"RESULT\",{stroke:\"black\"});\t\n\t\t}\n\t}\n\t//Empty the Query Graph Area\t\n $(\"#canvas\").html(\" \");\n //Generating a Query Graph\n //var layouter = new Graph.Layout.Ordered(g, topological_sort(g));\n //Testing Purpose\n var layouter = new Graph.Layout.Fixed(g, topological_sort(g));\n var renderer = new Graph.Renderer.Raphael('canvas', g, width, height);\n}", "_createPako() {\n const params = {\n raw: true,\n level: this._pakoOptions.level || -1 // default compression\n };\n this._pako = this._pakoAction === 'Deflate' ? new Deflate(params) : new Inflate(params);\n this._pako.onData = (data) => {\n this.push({\n data: data,\n meta: this.meta\n });\n };\n }", "function Graph() {\n this.vertices = [];\n this.adjacencyList = {};\n}", "static newMx(ar) { \r\n\t\tvar res = new mx4(); \t\t\r\n\t\tfor (var i=0; i<16; ++i) { res.M[i] = ar[i]; }\r\n\t\treturn res; \r\n\t}", "setDefaultLayout(){\n this.set('layoutName' , LayoutConfig.defaultLayoutFolderName)\n }", "function createLayout() {\n if (process.argv.length < 3) {\n console.log('Usage: node ' + process.argv[1] + ' [col # row #] *max for both 4');\n process.exit(1);\n }\n /*Create base layout with 1 row for header */\n var layoutWrapper = $('<center class=\"wrapper\"></center>');\n var webkitWrapper = $('<div class=\"webkit\"></div>');\n var outlookWrapperStart = $('<!--[if (gte mso 9)|(IE)]><table width=\"600\" align=\"center\" cellpadding=\"0\" cellspacing=\"0\" border=\"0\"><tr><td> <![endif]-->');\n /* Append to the end after everything is done place out side outermost Table but inside webkit-wrapper*/\n var outlookWrapperEnd = $('<!--[if (gte mso 9)|(IE)]></td></tr></table> <![endif]-->');\n var outerTable = $('<table class=\"outer\" align=\"center\"></table>');\n var header = $('<tr><td class=\"full-width-image\"> <img src=\"https://raw.githubusercontent.com/tutsplus/creating-a-future-proof-responsive-email-without-media-queries/master/images/header.jpg\" width=\"600\"/></td></tr>');\n webkitWrapper.append(outlookWrapperStart);\n outerTable.append(header);\n /*Here the user will pass in 2 numbers. The ith argument corresponds to the ith row\n the actual value of the argument itself corresponds to number of columns in the ith row.*/\n var layoutSetupList = process.argv;\n /*Iterating through the command line (process.argv) args. Note we start at 2 because in the\n array process.argv[0] holds the path , process.argv[1] holds the process name*/\n for (var position = 2; position < layoutSetupList.length; position += 1) {\n var columnCount = layoutSetupList[position];\n /* Table cannot contain negative or 0 cols*/\n if (columnCount < 1) {\n throw new Error(\"The argument value has to be at least 1!\");\n process.exit(1);\n }\n if (columnCount == 1) {\n outerTable.append('<tr><td class=\"one-column\"><table width=\"100%\"><tr><td class=\"inner contents\"><p class=\"h1\">Lorem ipsum dolor sit amet</p><p>Maecenas sed ante pellentesque, posuere leo id, eleifend dolor. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Praesent laoreet malesuada cursus. Maecenas scelerisque congue eros eu posuere. Praesent in felis ut velit pretium lobortis rhoncus ut erat.</p></td></tr></table></td></tr>');\n } else if (columnCount == 2) {\n outerTable.append('<tr><td class=\"two-column\"> <!--[if (gte mso 9)|(IE)]><table width=\"100%\" cellpadding=\"0\" cellspacing=\"0\" border=\"0\"><tr><td width=\"50%\" valign=\"top\"> <![endif]--><div class=\"column\"><table width=\"100%\"><tr><td class=\"inner\"><table class=\"contents\"><tr><td> <img src=\"https://raw.githubusercontent.com/tutsplus/creating-a-future-proof-responsive-email-without-media-queries/master/images/two-column-01.jpg\" width=\"280\" alt=\"\"></td></tr><tr><td class=\"text\"> Maecenas sed ante pellentesque, posuere leo id, eleifend dolor. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos.</td></tr></table></td></tr></table></div> <!--[if (gte mso 9)|(IE)]></td><td width=\"50%\" valign=\"top\"> <![endif]--><div class=\"column\"><table width=\"100%\"><tr><td class=\"inner\"><table class=\"contents\"><tr><td> <img src=\"https://raw.githubusercontent.com/tutsplus/creating-a-future-proof-responsive-email-without-media-queries/master/images/two-column-02.jpg\" width=\"280\" alt=\"\"></td></tr><tr><td class=\"text\"> Maecenas sed ante pellentesque, posuere leo id, eleifend dolor. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos.</td></tr></table></td></tr></table></div> <!--[if (gte mso 9)|(IE)]></td></tr></table> <![endif]--></td></tr>');\n } else if (columnCount == 3) {\n outerTable.append('<tr><td class=\"three-column\"> <!--[if (gte mso 9)|(IE)]><table width=\"100%\" cellpadding=\"0\" cellspacing=\"0\" border=\"0\"><tr><td width=\"200\" valign=\"top\"> <![endif]--><div class=\"column\"><table width=\"100%\"><tr><td class=\"inner\"><table class=\"contents\"><tr><td> <img src=\"https://raw.githubusercontent.com/tutsplus/creating-a-future-proof-responsive-email-without-media-queries/master/images/three-column-01.jpg\" width=\"180\" alt=\"\"></td></tr><tr><td class=\"text\"> Scelerisque congue eros eu posuere. Praesent in felis ut velit pretium lobortis rhoncus ut erat.</td></tr></table></td></tr></table></div> <!--[if (gte mso 9)|(IE)]></td><td width=\"200\" valign=\"top\"> <![endif]--><div class=\"column\"><table width=\"100%\"><tr><td class=\"inner\"><table class=\"contents\"><tr><td> <img src=\"https://raw.githubusercontent.com/tutsplus/creating-a-future-proof-responsive-email-without-media-queries/master/images/three-column-02.jpg\" width=\"180\" alt=\"\"></td></tr><tr><td class=\"text\"> Scelerisque congue eros eu posuere. Praesent in felis ut velit pretium lobortis rhoncus ut erat.</td></tr></table></td></tr></table></div> <!--[if (gte mso 9)|(IE)]></td><td width=\"200\" valign=\"top\"> <![endif]--><div class=\"column\"><table width=\"100%\"><tr><td class=\"inner\"><table class=\"contents\"><tr><td> <img src=\"https://raw.githubusercontent.com/tutsplus/creating-a-future-proof-responsive-email-without-media-queries/master/images/three-column-03.jpg\" width=\"180\" alt=\"\"></td></tr><tr><td class=\"text\"> Scelerisque congue eros eu posuere. Praesent in felis ut velit pretium lobortis rhoncus ut erat.</td></tr></table></td></tr></table></div> <!--[if (gte mso 9)|(IE)]></td></tr></table> <![endif]--></td></tr>');\n } else if (columnCount == 4) {\n outerTable.append('<tr><td class=\"four-column\"> <!--[if (gte mso 9)|(IE)]><table width=\"100%\" cellpadding=\"0\" cellspacing=\"0\" border=\"0\"><tr><td width=\"150\" valign=\"top\"> <![endif]--><div class=\"column\"><table width=\"100%\"><tbody><tr><td class=\"inner\"><table class=\"contents\"><tbody><tr><td> <img src=\"http://icons.iconarchive.com/icons/iynque/ios7-style/128/App-Store-icon.png\" width=\"180\" alt=\"\"></td></tr><tr><td class=\"text\"> Scelerisque congue eros eu posuere. Praesent in felis ut velit pretium lobortis rhoncus ut erat.</td></tr></tbody></table></td></tr></tbody></table></div> <!--[if (gte mso 9)|(IE)]></td><td width=\"150\" valign=\"top\"> <![endif]--><div class=\"column\"><table width=\"100%\"><tbody><tr><td class=\"inner\"><table class=\"contents\"><tbody><tr><td> <img src=\"http://icons.iconarchive.com/icons/iynque/ios7-style/128/Camera-icon.png\" width=\"180\" alt=\"\"></td></tr><tr><td class=\"text\"> Scelerisque congue eros eu posuere. Praesent in felis ut velit pretium lobortis rhoncus ut erat.</td></tr></tbody></table></td></tr></tbody></table></div> <!--[if (gte mso 9)|(IE)]></td><td width=\"150\" valign=\"top\"> <![endif]--><div class=\"column\"><table width=\"100%\"><tbody><tr><td class=\"inner\"><table class=\"contents\"><tbody><tr><td> <img src=\"http://icons.iconarchive.com/icons/iynque/ios7-style/128/iTunes-Store-icon.png\" width=\"180\" alt=\"\"></td></tr><tr><td class=\"text\"> Scelerisque congue eros eu posuere. Praesent in felis ut velit pretium lobortis rhoncus ut erat.</td></tr></tbody></table></td></tr></tbody></table></div> <!--[if (gte mso 9)|(IE)]></td><td width=\"150\" valign=\"top\"> <![endif]--><div class=\"column\"><table width=\"100%\"><tbody><tr><td class=\"inner\"><table class=\"contents\"><tbody><tr><td> <img src=\"http://icons.iconarchive.com/icons/iynque/ios7-style/128/Messages-icon.png\" width=\"180\" alt=\"\"></td></tr><tr><td class=\"text\"> Scelerisque congue eros eu posuere. Praesent in felis ut velit pretium lobortis rhoncus ut erat.</td></tr></tbody></table></td></tr></tbody></table></div> <!--[if (gte mso 9)|(IE)]></td></tr></table> <![endif]--></td></tr><tr>');\n }\n\n }\n webkitWrapper.append(outerTable);\n webkitWrapper.append(outlookWrapperEnd);\n layoutWrapper.append(webkitWrapper);\n return layoutWrapper;\n}", "layoutHandler(node) {\n\t\tconst category = get(node, \"app_data.explain_data.category\");\n\t\tconst index = get(node, \"app_data.explain_data.index\");\n\t\tconst cost = get(node, \"app_data.explain_data.cost\");\n\n\t\tconst className = this.getClassNameForCategory(category);\n\t\tconst { bodyPath, selectionPath, width } = this.getPaths(node);\n\n\t\tconst nodeFormat = {\n\t\t\tdefaultNodeWidth: width, // Override default width with calculated width\n\t\t\tlabelPosX: (width / 2), // Specify center of label as center of node Note: text-align is set to center in the CSS for this label\n\t\t\tlabelWidth: width, // Set big enough so that label is not truncated and so no ... appears\n\t\t\tellipsisPosX: width - 25, // Always position 25px in from the right side\n\t\t\tbodyPath: bodyPath,\n\t\t\tselectionPath: selectionPath,\n\t\t\tclassName: className,\n\t\t\tdecorations: [\n\t\t\t\t{\n\t\t\t\t\tid: \"labelDecoration1\",\n\t\t\t\t\tx_pos: 10,\n\t\t\t\t\ty_pos: 15,\n\t\t\t\t\twidth: 28,\n\t\t\t\t\tlabel: \"(\" + index + \")\",\n\t\t\t\t\tclass_name: \"small_text\",\n\t\t\t\t\ttemporary: true\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tid: \"labelDecoration2\",\n\t\t\t\t\tposition: \"bottomCenter\",\n\t\t\t\t\tx_pos: -25,\n\t\t\t\t\ty_pos: -19,\n\t\t\t\t\twidth: 50,\n\t\t\t\t\tlabel: cost,\n\t\t\t\t\tclass_name: \"small_text\",\n\t\t\t\t\ttemporary: true\n\t\t\t\t}\n\t\t\t]\n\t\t};\n\n\t\treturn nodeFormat;\n\t}", "create() {\n this.scaleColor = d3.scaleOrdinal().range(getColor(this.color));\n this.canvas = this.mainCanvas();\n this.transformGroup = this.transformGroup();\n this.addTitles(this.data.title, this.data.subtitle);\n this.addPieArcs(this.data.percentages);\n this.addSideStrokes();\n\n return this;\n }", "setLayoutName(name){\n this.set('layoutName' , name)\n }", "function patternLayout(layoutConfig, globalConfig) {\n\n var pattern = layoutConfig.pattern;\n var levels = globalConfig.levels;\n var colors = globalConfig.colors;\n var basedir = globalConfig.basedir || process.cwd();\n\n var formatters = {\n utctime: function(level, now) {\n return now.toISOString();\n },\n yyyy: function(level, now) {\n return now.getFullYear();\n },\n MM: function(level, now) {\n return padZero(now.getMonth()+1, 2);\n },\n dd: function(level, now) {\n return padZero(now.getDate(), 2);\n },\n T: function() {\n return 'T';\n },\n HH: function(level, now) {\n return padZero(now.getHours(), 2);\n },\n hh: function(level, now) {\n return padZero(now.getHours()%12, 2);\n },\n mm: function(level, now) {\n return padZero(now.getMinutes(), 2);\n },\n ss: function(level, now) {\n return padZero(now.getSeconds(), 2);\n },\n sss: function(level, now) {\n return padZero(now.getMilliseconds(), 3);\n },\n Z: function(level, now) {\n var offset = -now.getTimezoneOffset();\n if (offset === 0) {\n return 'Z';\n }\n var hour = Math.abs(offset / 60);\n var min = Math.abs(offset % 60);\n var sign = offset < 0 ? '-' : '+';\n return sign + padZero(hour, 2) + ':' + padZero(min, 2);\n },\n level: function(level) {\n return levels[level];\n },\n levelc: function(level) {\n return colors[level](levels[level]);\n },\n msg: function(level, now, msg) {\n return msg;\n },\n logger: function() {\n var logger = this;\n return logger.name || '-';\n },\n loggerc: function() {\n var logger = this;\n return chalk.gray(logger.name || '-');\n },\n args: function(level, now, msg, args) {\n return join(args);\n },\n argsc: function(level, now, msg, args) {\n return chalk.magenta(join(args));\n },\n line: function() {\n var stack = new Error().stack;\n if (stack) {\n stack = stack.split('\\n')[5];\n if (stack && stack.match(/\\/([^\\/]+?:[0-9]+)/)) {\n return RegExp.$1;\n }\n }\n return 'unknown';\n },\n linec: function() {\n var stack = new Error().stack;\n if (stack) {\n stack = stack.split('\\n')[5];\n if (stack && stack.match(/\\/([^\\/]+?:[0-9]+)/)) {\n return chalk.gray(RegExp.$1);\n }\n }\n return chalk.gray('unknown');\n },\n path: function() {\n var stack = new Error().stack;\n if (stack) {\n stack = stack.split('\\n')[5];\n if (stack && stack.match(/(\\/.+?:[0-9]+)/)) {\n return path.relative(basedir, RegExp.$1);\n }\n }\n return 'unknown';\n },\n pathc: function() {\n var stack = new Error().stack;\n if (stack) {\n stack = stack.split('\\n')[5];\n if (stack && stack.match(/(\\/.+?:[0-9]+)/)) {\n return chalk.gray(path.relative(basedir, RegExp.$1));\n }\n }\n return chalk.gray('unknown');\n },\n error: function(level, now, msg, args) {\n if (msg && msg.message) {\n return msg.message;\n }\n for (var i = 0; i < args.length; i++) {\n if (args[i] && args[i].message) {\n return args[i].message;\n }\n }\n return '';\n },\n stack: function(level, now, msg, args) {\n if (msg && msg.stack) {\n return msg.stack.replace(/\\n/g,'\\\\n');\n }\n for (var i = 0; i < args.length; i++) {\n if (args[i] && args[i].stack) {\n return args[i].stack.replace(/\\n/g,'\\\\n');\n }\n }\n return '';\n },\n nstack: function(level, now, msg, args) {\n if (msg && msg.stack) {\n return '\\n'+msg.stack;\n }\n for (var i = 0; i < args.length; i++) {\n var arg = args[i];\n if (arg && args[i].stack) {\n return '\\n' + args[i].stack;\n }\n }\n return '';\n },\n pid: function() {\n return ''+process.pid;\n },\n n: function n() {\n return EOL;\n }\n };\n for (var name in formatters) {\n formatters[name]._name = name;\n }\n\n var list = [];\n var curr = 0;\n\n pattern.replace(/%([a-zA-Z]+)/g, function(text, match, offset, whole) {\n if (offset > curr) {\n list.push(whole.substring(curr, offset));\n }\n var format = formatters[match];\n if (format) {\n list.push(format);\n } else {\n list.push(text);\n }\n curr = offset + text.length;\n });\n if (curr < pattern.length) {\n list.push(pattern.substring(curr));\n }\n\n if (layoutConfig.object) {\n // for worker\n return function() {\n var args = arguments;\n var obj = {};\n for (var i = 0; i < list.length; i++) {\n var item = list[i];\n if (item._name) {\n obj[item._name] = item.apply(this, args);\n }\n }\n return obj;\n };\n } else {\n // for master\n return function() {\n var args = arguments;\n if (args.length === 4) {\n var obj = args[2];\n if (obj && obj.type === '_PROTEUS_LOG_') {\n var data = obj.data;\n var line = pattern;\n for (var name in data) {\n line = line.replace('%'+name, data[name]);\n }\n return line;\n }\n }\n\n // parse and composite log text\n var text = '';\n for (var i = 0; i < list.length; i++) {\n var item = list[i];\n if (typeof item === 'function') {\n text += item.apply(this, args);\n } else {\n if (item) {\n text += item;\n }\n }\n }\n return text;\n };\n }\n}", "function preprocessGraphLayout(g) {\n g.graph().ranksep = \"70\";\n var nodes = g.nodes();\n for (var i = 0; i < nodes.length; i++) {\n var node = g.node(nodes[i]);\n node.padding = \"5\";\n\n var firstSeparator;\n var secondSeparator;\n var splitter;\n if (node.isCluster) {\n firstSeparator = secondSeparator = labelSeparator;\n splitter = \"\\\\n\";\n } else {\n firstSeparator = \"<span class='stageId-and-taskId-metrics'>\";\n secondSeparator = \"</span>\";\n splitter = \"<br>\";\n }\n\n node.label.split(splitter).forEach(function(text, i) {\n var newTexts = text.match(stageAndTaskMetricsPattern);\n if (newTexts) {\n node.label = node.label.replace(\n newTexts[0],\n newTexts[1] + firstSeparator + newTexts[2] + secondSeparator + newTexts[3]);\n }\n });\n }\n // Curve the edges\n var edges = g.edges();\n for (var j = 0; j < edges.length; j++) {\n var edge = g.edge(edges[j]);\n edge.lineInterpolate = \"basis\";\n }\n}", "function layFlat(p) {\n\tcurrentZ = new CSG.Connector([0,0,0],[0,0,1],[1,0,0]);\n\treturn p.connectTo(p.properties._originalZ, currentZ, false, 0);\n}", "function setup() {\r\n var dimensions = [SIZE, SIZE];\r\n var range = [X_RANGE, Y_RANGE];\r\n var step = STEP;\r\n if (step === \"auto\") {\r\n step = _.map(range, function(extent, i) {\r\n return Perseus.Util.tickStepFromExtent(\r\n extent, dimensions[i]);\r\n });\r\n }\r\n var gridConfig = _.map(range, function(extent, i) {\r\n return Perseus.Util.gridDimensionConfig(\r\n step[i],\r\n extent,\r\n dimensions[i]);\r\n });\r\n var scale = _.pluck(gridConfig, \"scale\");\r\n xScale = scale[0];\r\n yScale = scale[1];\r\n var paddedRange = _.map(range, function(extent, i) {\r\n var padding = 25 / scale[i];\r\n return [extent[0], extent[1] + padding];\r\n });\r\n graphInit({\r\n gridRange: range,\r\n range: paddedRange,\r\n scale: scale,\r\n axisArrows: \"<->\",\r\n labelFormat: function(s) {\r\n return \"\\\\small{\" + s + \"}\";\r\n },\r\n gridStep: _.pluck(gridConfig, \"gridStep\"),\r\n tickStep: _.pluck(gridConfig, \"tickStep\"),\r\n labelStep: 1,\r\n unityLabels: _.pluck(gridConfig, \"unityLabel\")\r\n });\r\n style({\r\n clipRect: [[X_RANGE[0], Y_RANGE[0]],\r\n [X_RANGE[1] - X_RANGE[0],\r\n Y_RANGE[1] - Y_RANGE[0]]]\r\n });\r\n\r\n label([0, Y_RANGE[1]], \"y\", \"above\");\r\n label([X_RANGE[1], 0], \"x\", \"right\");\r\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets the average of the last `number` elements of the given array.
function getAverage(elements, number){ var sum = 0; //taking `number` elements from the end to make the average, if there are not enought, 1 var lastElements = elements.slice(Math.max(elements.length - number, 1)); for(var i = 0; i < lastElements.length; i++){ sum = sum + lastElements[i]; } return Math.ceil(sum/number); }
[ "function averageNumbers(array){\n let sum = 0;\n let avg;\n for ( let i = 0 ; i < array.length ; i++ ){\n sum = sum + array[i];\n avg = sum / array.length\n }\n return avg\n}", "function avgValue(array)\n{\n\tvar sum = 0;\n\tfor(var i = 0; i <= array.length - 1; i++)\n\t{\n\t\tsum += array[i];\n\t}\n\tvar arrayLength = array.length;\n\treturn sum/arrayLength;\n}", "function averages(numbers){\n let avgNums = [];\n if(!numbers) return avgNums;\n for(let i = 1; i < numbers.length; i++){\n let avg = (numbers[i - 1] + numbers[i]) / 2;\n avgNums.push(avg);\n }\n return avgNums;\n}", "function lastEntry (array, n) {\n const lastEntryIndex = array.length;\n\n if (n === undefined){\n return array[lastEntryIndex-1];\n }\n return array.slice(lastEntryIndex - n);\n}", "function maxSubarraySum(arr, number) {\n\tif(arr.length < number) {\n\t\treturn null;\n\t}\n\tlet endPos = arr.length - number;\n\tlet sum = 0, tempSum = 0;\n\tfor(let i = 0; i < number; i++) {\n\t\tsum = sum + arr[i];\n\t}\n\ttempSum = sum;\n\tfor(let i = 1; i <= endPos; i++) {\n\t\ttempSum = tempSum - arr[i - 1] + arr[i + number - 1];\n\t\tif(tempSum > sum) {\n\t\t\tsum = tempSum;\n\t\t}\n\t}\n\treturn sum;\n}", "function modifyAverage(number) {\n let getAverage = function getAverage(num) {\n let arr = Array.from(Math.abs(num).toString());\n let size = arr.length;\n let sum = 0;\n for (let index = 0; index < arr.length; index++) {\n sum += +arr[index];\n }\n return sum / size;\n }\n let increaseNumber = function increaseNumber(num) {\n let arr = Array.from(num.toString());\n arr.push(9);\n return arr.join('');\n }\n\n let curAverage = getAverage(number);\n while (curAverage <=5 ) {\n number = increaseNumber(number);\n curAverage = getAverage(number);\n }\n console.log(number); \n}", "function moreThanAverage(arr) {\n return filter(arr, function(element){\n return element>arr.length;\n })\n}", "function lastNumber(array) {\n //numbers are in descending order\n if(array.length>=(Math.pow(10,5))){\n return 0; //base case where; 1 < n < 10^5\n }\n array = array.sort((a,b)=>a-b);\n while(true){\n if(array.length==1) return array[0];\n if(array.length==0) return 0;\n let num1 = array.pop();\n let num2 = array.pop();\n\n if(num1!=num2){\n let newNumber = Math.abs( Number(num1) - Number(num2) );\n \n // insert this number back\n if(newNumber>=array[array.length-1]){\n array.push(newNumber);\n }else if( newNumber<=array[0]){\n array.splice(0,0,newNumber);\n }else{\n //place new number in sorted position in array\n let findIndex = array.findIndex(value=>value>newNumber);\n array.splice(findIndex,0,newNumber);\n }\n }\n }\n}", "function calcAveragePages (arr) {\r\n let total = 0\r\n arr.forEach(number => {\r\n total += number\r\n return total\r\n })\r\n return Math.round(total / arr.length)\r\n}", "function getLastNItems(arr,num){\n \n return (num > 0) ? arr.slice(-num) : [];\n}", "function lastNElements(array, n) {\n // TODO: your code here\n if(array.length===0){\n return [];\n }\n else if(array.length<n)\n return array;\n\nelse \nreturn array.slice(array.length-n,array.length);\n}", "function avg(v){\n s = 0.0;\n for(var i=0; i<v.length; i++)\n s += v[i];\n return s/v.length;\n}", "function mean(num) {\n\treturn [...num.toString()].reduce((x, i) => (Number(x) + Number(i))) / num.toString().length; \n}", "function aperture(num, arr){\n let result = [];\n if (num > arr.length || num < 1) return result;\n for(let i=0; i < arr.length; i++){\n let subArr = [];\n for(let j=i; j < i+num; j++){\n if (i+num <= arr.length) subArr.push(arr[j]);\n }\n if (subArr.length > 0) result.push(subArr);\n }\n return result;\n}", "function five_match_average(array_of_scores){\n five_match_score=array_of_scores.slice(0,5)\n total=0\n for(var x in five_match_score){\n total+=five_match_score[x]\n }\n console.log(total/5)\n}", "function lastElement(array){\n if (array.length > 0){\n return array[array.length-1];\n }\n return null;\n}", "function averageWeeksAtNumberOne(songs) {\n let sumWeeks = songs.reduce(weeks, song => {\n return weeks + weekssong.weeksAtNumberOne;\n });\n return sumWeeks / songs.length;\n}", "function getMedianValue(array) {\n array = array.sort((a, b) => a - b);\n return array.length % 2 !== 0 ? array[Math.floor(array.length / 2)] :\n (array[array.length / 2 - 1] + array[array.length / 2]) / 2;\n}", "function calculateAverage(grades) {\n // grades is an array of numbers\n total = 0\n for(let i = 0; i <grades.length; i++){\n total += grades[i];\n }\n return Math.round(total / grades.length);\n}", "function absAvg(arr){\n // arr is a typed array! \n var abs_avg = arr.reduce((a,b) => (a+Math.abs(b))) / arr.length;\n return abs_avg; \n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
do a quick gc of a thread: reset the stack (possibly shrinking storage for it) reset all global data checks all known threads if t is null, but not h$currentThread
function h$gcQuick(t) { if(h$currentThread !== null) throw "h$gcQuick: GC can only run when no thread is running"; h$resetRegisters(); h$resetResultVars(); var i; if(t !== null) { // reset specified threads if(t instanceof h$Thread) { // only thread t h$resetThread(t); } else { // assume it's an array for(var i=0;i<t.length;i++) h$resetThread(t[i]); } } else { // all threads, h$currentThread assumed unused var nt, runnable = h$threads.iter(); while((nt = runnable()) !== null) h$resetThread(nt); var iter = h$blocked.iter(); while((nt = iter.next()) !== null) h$resetThread(nt); } }
[ "function cleanup() {\n if (global.gc) {\n global.gc();\n }\n}", "function h$finalizeMVars() {\n ;\n var i, t, iter = h$blocked.iter();\n while((t = iter.next()) !== null) {\n if(t.status === h$threadBlocked && t.blockedOn instanceof h$MVar) {\n // if h$unboxFFIResult is the top of the stack, then we cannot kill\n // the thread since it's waiting for async FFI\n if(t.blockedOn.m !== h$gcMark && t.stack[t.sp] !== h$unboxFFIResult) {\n h$killThread(t, h$ghcjszmprimZCGHCJSziPrimziInternalziblockedIndefinitelyOnMVar);\n return t;\n }\n }\n }\n return null;\n}", "clearAll() {\n this._stack.length = 0;\n\n // stuff the stack to mimic always needed registers\n for (let i = 0; i < MINIMUM_STACK; i++) {\n this._stack.push(0);\n }\n\n this._lastX = 0;\n this._clearMemory();\n }", "finalize() {\n for (const tile of this._cache.values()) {\n if (tile.isLoading) {\n tile.abort();\n }\n }\n this._cache.clear();\n this._tiles = [];\n this._selectedTiles = null;\n }", "ensureCleanupTask() {\n var _a, _b;\n if (this.cleanupTimer === null) {\n this.cleanupTimer = setInterval(() => {\n this.unrefUnusedSubchannels();\n }, REF_CHECK_INTERVAL);\n // Unref because this timer should not keep the event loop running.\n // Call unref only if it exists to address electron/electron#21162\n (_b = (_a = this.cleanupTimer).unref) === null || _b === void 0 ? void 0 : _b.call(_a);\n }\n }", "function clearMemory(){ memory = [] }", "function sessiongc() {\n\tsessionmgr.sessiongc();\n}", "resetEverything() {\n this.resetLoader();\n this.remove(0, Infinity);\n }", "_clearMemory() {\n for (let i = 0; i < this._memory.length; i++) {\n this._memory[i] = 0;\n }\n }", "function gc(){\r\n $videos = $(\".dynamic-slide video\");\r\n console.log('Garbage collecting ' + $videos.length + ' videos...');\r\n $videos.each(function(){\r\n this.pause();\r\n delete(this);\r\n $(this).remove();\r\n });\r\n}", "unrefUnusedSubchannels() {\n let allSubchannelsUnrefed = true;\n /* These objects are created with Object.create(null), so they do not\n * have a prototype, which means that for (... in ...) loops over them\n * do not need to be filtered */\n // eslint-disable-disable-next-line:forin\n for (const channelTarget in this.pool) {\n const subchannelObjArray = this.pool[channelTarget];\n const refedSubchannels = subchannelObjArray.filter(value => !value.subchannel.unrefIfOneRef());\n if (refedSubchannels.length > 0) {\n allSubchannelsUnrefed = false;\n }\n /* For each subchannel in the pool, try to unref it if it has\n * exactly one ref (which is the ref from the pool itself). If that\n * does happen, remove the subchannel from the pool */\n this.pool[channelTarget] = refedSubchannels;\n }\n /* Currently we do not delete keys with empty values. If that results\n * in significant memory usage we should change it. */\n // Cancel the cleanup task if all subchannels have been unrefed.\n if (allSubchannelsUnrefed && this.cleanupTimer !== null) {\n clearInterval(this.cleanupTimer);\n this.cleanupTimer = null;\n }\n }", "_resetThreadPane() {\n if (gDBView)\n gCurrentlyDisplayedMessage = gDBView.currentlyDisplayedMessage;\n\n ClearThreadPaneSelection();\n ClearThreadPane();\n ClearMessagePane();\n }", "static resetInstanceCount() {\n /* This should not be part of the coverage report: test util */\n /* istanbul ignore next */\n if (process.env.NODE_ENV === 'test') {\n __instanceCount = 0;\n }\n }", "function cleansCounters() {\n\tn = 0;\n\tmachinePlay = [];\n\tuserPlay = [];\n\tcount = 0;\n\tcounter = 0;\n\tuserCount = 0;\n}", "async reset() {\n if (!testInternal.initialized)\n throw new Error('Call initialize() before reset().');\n testInternal.MockFaceDetectionProvider.reset();\n testInternal.MockFaceDetectionProvider = null;\n testInternal.initialized = false;\n\n await new Promise(resolve => setTimeout(resolve, 0));\n }", "resetTargetObject () {\r\n this._targetObject = null;\r\n }", "_reset() {\n this._uploadState = {\n // exponential backoff, coming soon!\n inBackoff: false,\n backoffFactor: 0,\n\n // available pool of workers that are ready to perform, or are performing\n idleWorkers: this._generateMaxIdleWorkers(),\n workerAssignments: {}, // { chunkNumber: UploadWorker, ... }\n\n // the state of this UploadManager\n inProgress: false,\n\n // chunk state\n nextChunkNumber: 0, // the next chunk number to assign (!= the number uploaded as there could be uploads in flight)\n numChunksUploaded: 0,\n expectedNumChunksToUpload: 0, // the total number of chunks that should be uploaded, set in perform()\n };\n }", "function resetEntities() {\n entities = [];\n player = null;\n Building.timeSinceLastBuilding = 1000;\n}", "flush () {\n this.cacheStore = {}\n }", "function reInitializeGlobalVariable(){\n\t//empty all row in the designer area\n\t//$('#box-body').empty();\n\n\t//re-initialize the global values\t\n\t//delete gblEntityDesignJson[wrkTgtCollection];\n\tmstEntityDesignArr = [];\n\tselParentNodeArr = [];\n\twrkTgtCollection = '';\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return original URL for req. If index specified, then set it as _index query param
function requestUrl(req, index) { const port = req.app.locals.port; let url = `${req.protocol}://${req.hostname}:${port}${req.originalUrl}`; if (index !== undefined) { if (url.match(/_index=\d+/)) { url = url.replace(/_index=\d+/, `_index=${index}`); } else { url += url.indexOf('?') < 0 ? '?' : '&'; url += `_index=${index}`; } } return url; }
[ "function getListIndex()\n{\n\tvar prmstr = window.location.search.substr(1);\n\tvar prmarr = prmstr.split (\"&\");\n\tvar params = {};\n\n\tfor ( var i = 0; i < prmarr.length; i++) {\n\t var tmparr = prmarr[i].split(\"=\");\n\t params[tmparr[0]] = tmparr[1];\n\t}\n\tlistIndex = params.listindex;\n}", "function mashapeURL(req, config){\n var url;\n if(config.multipleParams){\n\tconsole.log(\"Considering multiple params\");\n\tvar params = req.url.split(\"/\");\n\tparams.splice(0,1); //get rid of first empty string since url starts with \"/\"\n\t//\tconsole.log(\"Are these the guys????\", params);\n\tparams = _.map(params, _.flow(mashapeTexterize,decodeURI))\n //\tconsole.log(\"How about these????\", params);\n\tparams = config.urlDefault.concat(params);\n\t//\tconsole.log(\"READY NOW???\", params);\n\tvar zipped = _.zip(config.urlParams, params);\n\tvar paramObj = {};\n\t_.map(zipped, function(x){ return paramObj[x[0]] = x[1] });\n\tconsole.log(\"paramObj:\\n\", paramObj);\n\turl = config.url + \"?\" + querystring.stringify(paramObj);\n\t//console.log(\"MUST BE NOW!!!!!!!!\", url);\n } else {\n\tconsole.log(\"Only a single param\");\n\tvar preText = mashapeTexterize(decodeURI(req.url.substring(1)));\n\tconsole.log(\"preText: \", preText);\n\turl = config.url + \"?\" + config.urlParams + \"=\" + preText;\n }\n return url;\n}", "function runIndexQuickFilter(preserveParams, url, target) {\n if (typeof passedArgsArray === \"undefined\") {\n var passedArgsArray = [];\n }\n var searchKey = 'searchall';\n if ($('#quickFilterField').length > 0) {\n if ($('#quickFilterField').data('searchkey')) {\n searchKey = $('#quickFilterField').data('searchkey');\n }\n if ($('#quickFilterField').val().trim().length > 0) {\n passedArgsArray[searchKey] = encodeURIComponent($('#quickFilterField').val().trim());\n }\n }\n if (typeof url === \"undefined\") {\n url = here;\n }\n if (typeof preserveParams === \"string\") {\n preserveParams = String(preserveParams);\n if (!preserveParams.startsWith('/')) {\n preserveParams = '/' + preserveParams;\n }\n url += preserveParams;\n } else if (typeof preserveParams === \"object\") {\n for (var key in preserveParams) {\n if (typeof key == 'number') {\n url += \"/\" + preserveParams[key];\n } else if (key !== 'page') {\n if (key !== searchKey || !(searchKey in passedArgsArray)) {\n url += \"/\" + key + \":\" + preserveParams[key];\n }\n }\n }\n }\n for (var key in passedArgsArray) {\n if (typeof key == 'number') {\n url += \"/\" + passedArgsArray[key];\n } else if (key !== 'page') {\n url += \"/\" + key + \":\" + passedArgsArray[key];\n }\n }\n if (target !== undefined) {\n $.ajax({\n beforeSend: function () {\n $(\".loading\").show();\n },\n success: function (data) {\n $(target).html(data);\n },\n error: function () {\n showMessage('fail', 'Could not fetch the requested data.');\n },\n complete: function () {\n $(\".loading\").hide();\n },\n type: \"get\",\n url: url\n });\n } else {\n window.location.href = url;\n }\n}", "function get_UrlArg() {\n var loc = $(location).attr('href');\n var loc_separator = loc.indexOf('#');\n return (loc_separator == -1) ? '' : loc.substr(loc_separator + 1);\n }", "function lower(req, res, next) {\n req.url = req.url.toLowerCase();\n next();\n}", "function getRequestArgs(req) {\n args = req.path.split(\"/\");\n args.splice(0,3);\n if(args.length > 0) {\n if(args[args.length-1] == '')\n // Path ended with slash. Just skip this one\n args.pop();\n \n for(var i = 0; i < args.length; ++i)\n args[i] = urlDecode(args[i]);\n }\n args.unshift('-w');\n return args;\n}", "function fixURI(uri) {\n if (uri[uri.length - 1] === \"/\") {\n uri = uri.substr(0, uri.length - 1);\n }\n if (uri.endsWith(\"index\")) {\n uri = uri.substr(0, uri.length - 6);\n }\n if (uri.length === 0) {\n uri = \"/\";\n }\n return uri;\n}", "function getFullRequestPathWithoutPaging(div, sort, idlist, knownCount) {\n var request = getRequest(div), params = getUrlParamsForAllRecords(div);\n $.each(params, function (key, val) {\n if (typeof knownCount === 'undefined' || knownCount === true || key !== 'knownCount') {\n if (!idlist && key === 'idlist') {\n // skip the idlist param value as we want the whole map\n val = '';\n }\n request += '&' + key + '=' + encodeURIComponent(val);\n }\n });\n if (sort && div.settings.orderby !== null) {\n request += '&orderby=' + div.settings.orderby + '&sortdir=' + div.settings.sortdir;\n }\n return request;\n }", "function rewriteApiUrl(url) {\n if (url === '/v1') {\n return '/index.json';\n } else if (url.indexOf('/v1') === 0) {\n url = url.substring(4);\n url = url.replace('/', '_');\n url = '/' + url + '.json';\n }\n\n return url;\n}", "_updateUrl() {\n const { pathname } = window.document.location,\n { id } = this._presentQuote,\n existingParams = qs.parse(window.location.search),\n newParams = { ...existingParams, q: id };\n history.pushState(undefined, document.title, `${pathname}?${qs.stringify(newParams)}`);\n return this;\n }", "function index_url2index_data(index_url, cb) {\n log(arguments.callee.name);\n var err_resp_body2index_data = function(err, resp, body) {\n if(!err && resp.statusCode == 200) {\n var index_data = JSON.parse(body);\n cb(null, index_data);\n }\n };\n request(index_url, err_resp_body2index_data);\n}", "function formatActionURI(req) {\n\t\tconst str = getFirstAction(req);\n\t\tif (str) {\n\t\t\tconst parts = str.split('.');\n\t\t\tif (parts && parts.length >= 2) {\n\t\t\t\treturn (parts[0] + '/' + parts[1]).toLowerCase();\n\t\t\t}\n\t\t}\n\t\treturn ev.STR.SERVICE_NAME + '/' + get_last_word_in_path(req);\t\t\t// fallback\n\t}", "function switchIndex(){\n\twindow.location.href=(\"./servletIndex.html\")\n}", "function retarget (req, res, next) {\n const cfurl = req.headers['x-cf-forwarded-url']\n if (! cfurl) {\n next()\n return\n }\n\n let h = cfurl.indexOf('://')\n if (h >= 0) {\n h += 3\n }\n else {\n h = 0\n }\n\n let p = cfurl.indexOf('/', h)\n if (p < 0) {\n p = cfurl.length\n }\n\n const cfHostname = cfurl.slice(h, p)\n const cfPath = cfurl.slice(p) || '/'\n\n debug('x-cf-forwarded-url: ' + cfurl);\n debug('old targetHostname: '+req.targetHostname);\n debug('old targetPath: ' + req.targetPath);\n\n if (cfHostname && !pathOnly) {\n req.targetHostname = cfHostname\n }\n req.targetPath = cfPath\n\n debug('new targetHostname: '+req.targetHostname);\n debug('new targetPath: ' + req.targetPath);\n\n next()\n}", "function postSearchIndexHandler(req, res) {\n\n var site = req.body.site;\n var token = req.body.token;\n var data = req.body.data;\n var id = req.body.id;\n var typeName = req.body.typeName;\n var oneOff = req.body.oneOff || false;\n\n async.series([\n siteBillingActive.bind(null, site),\n siteKeyEqualsToken.bind(null, { siteName: site, token: token }),\n elasticSearchIndexItem.bind(null, { siteName: site, typeName: typeName, id: id, doc: data, oneOff: oneOff })\n ], handleResponseForSeries.bind(null, res))\n\n function elasticSearchIndexItem(options, callback) {\n elastic.index(options)\n .then(callback)\n .catch(handleSearchIndexError)\n\n function handleSearchIndexError() {\n callback({ statusCode: 500, message: 'Could not index item for site.' })\n }\n }\n }", "indexAction(req, res) {\n this.jsonResponse(res, 200, { 'message': 'Default API route!' });\n }", "overrideUrl(iUrl) {\n return iUrl;\n }", "redirect (req, res, url, queryParams) {\n res.redirect(302, req.protocol + '://' + req.headers['host'] + '/' + url + (queryParams ? '?' + QueryString.stringify(queryParams) : ''));\n }", "function ajaxGotoNext20Index(startIdx, path, divName) {\n\tif (startIdx.length < 1) {\n\t\tstartIdx = 0;\n\t}\n\t// next 20 page value as start index value\n\tparameter1 = startIdx;\n\t// set the start index value\n\tstartIndexValue = (startIdx - 1) * 10;\n\t// submit the ajax action\n\tajaxCommonActionSubmit(path, divName, DIV_DEFAULT_WIDTH, DIV_DEFAULT_HEIGHT);\n}", "function trx_addons_options_clone_replace_index(name, idx_new) {\n\t\t\tname = name.replace(/\\[\\d\\]/, '['+idx_new+']');\n\t\t\treturn name;\n\t\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
buildDatabaseAndCollections() This function will build out our database (by attempting to connect to it, which creates it if it doesn't already exist. It will then call three events asyncronisly to ensure the proper collections are created for us, before closing the connection.
async function buildDatabaseAndCollections(error, database) { // If we have an error... if (error) { // Log it console.log('database error: ', error); // Otherwise... } else { // Setup a database object let databaseObject = database.db(config.database.name); // Call our creation events asyncronishly try { await createCollection( databaseObject, 'users' ); await createCollection( databaseObject, 'tasks' ); // await createCollection( databaseObject, 'authentication' ); // Creating a seperate JWT Database so we can log history of user tokens } catch (creationError) { console.log("Unhandled Error in Collection Creation Run", creationError); } // Once they've finished, close the DB. database.close(); } }
[ "function databaseInitialize() {\n if (!db.getCollection(collections.PLACES)) {\n db.addCollection(collections.PLACES);\n }\n\n if (!db.getCollection(collections.RATINGS)) {\n db.addCollection(collections.RATINGS);\n }\n}", "init() {\n\t\ttry {\n\t\t\tthis.database = new lokijs(consts.databasePath, {\n\t\t\t\tautosave: true,\n\t\t\t\tautosaveInterval: consts.autosaveInterval\n\t\t\t});\n\t\t\tthis.profiles = this.database.addCollection(consts.collectionName, {indeces: ['id']});\n\t\t\tthis.profiles.ensureUniqueIndex('id');\n\t\t\treturn Promise.resolve();\n\t\t} catch (error) {\n\t\t\tlogger.error({error}, 'Error occurred during database initialization');\n\t\t\treturn Promise.reject(error);\n\t\t}\n\t}", "pushRefreshedDatas() {\n var tt = this;\n MongoClient.connect(this.uri, function(err, db) {\n if (err) throw err;\n //Looking for a db called test\n var dbo = db.db(\"test\");\n for (var i = 0; i < tt.collections.length; ++i) {\n dbo.collection(\"rss\").insertOne(tt.collections[i],function(err, result) {\n if (err) throw err;\n });\n }\n db.close();\n });\n }", "function dropDBCollections() {\n\t//console.log( \"dropDBCollections\" ) ;\n\treturn Promise.all( [\n\t\tdropCollection( versions ) ,\n\t\tdropCollection( users ) ,\n\t\tdropCollection( jobs ) ,\n\t\tdropCollection( schools ) ,\n\t\tdropCollection( towns ) ,\n\t\tdropCollection( lockables ) ,\n\t\tdropCollection( nestedLinks ) ,\n\t\tdropCollection( anyCollectionLinks ) ,\n\t\tdropCollection( images ) ,\n\t\tdropCollection( versionedItems ) ,\n\t\tdropCollection( extendables )\n\t] ) ;\n}", "function initDb() {\n\n\t\tif(fs.existsSync(path.join(cloudDir ,dbName))){\n\t\t\t//TODO: catch errors\n\t\t\tfs.createReadStream(path.join(cloudDir ,dbName))\n\t\t\t\t.pipe(fs.createWriteStream(path.join(tempDir, dbName)));\n\t\t\n\t\t}\n\t\n\t}", "_setupDBEvents() {\n this.db.on('connected', ()=>{\n this._status='connected';\n this.logger.info(`DB connected.`);\n });\n\n this.db.on('error', (err)=>{\n this.lastError=err;\n this.logger.error('DB error', err);\n });\n\n this.db.on('reconnected', ()=>{\n this._status='connected';\n this.logger.warn('DB reconnected');\n });\n\n this.db.on('disconnected', ()=>{\n this._status='disconnected';\n this.logger.error('DB disconnected');\n });\n }", "async createCollection(name) {\n\t \tthis.db.createCollection( name )\n\t}", "function ensureNoMoreCollections(args) {\n if (DBS_WITH_SERVER.has(args.database)) {\n var err = newRxError('S1', {\n collection: args.name,\n database: args.database.name\n });\n throw err;\n }\n}", "close() {\n\t\tlogger.info('Started database closure procedure');\n\t\tthis.database.removeCollection('profiles');\n\t\tlogger.info('Removed collection from database');\n\t\tthis.database.close(() => {\n\t\t\tlogger.info('Closed database');\n\t\t\tthis.database.deleteDatabase(() => {\n\t\t\t\tlogger.info('deleted database from files system. Done database closure procedure.');\n\t\t\t});\n\t\t});\n\t}", "function seedDB() {\n console.log(\"Processing all files.\");\n // Read files\n var fighters = fsReadFileSynchToArray(fighterPath);\n var stages = fsReadFileSynchToArray(stagePath);\n console.log(chalk.green('success') + \": Loaded all files.\");\n console.log(\"Attempting to delete all documents\");\n\n // Add all documents\n deleteDocuments()\n .then(() => {\n console.log(chalk.green('success') + \": Successfully deleted all Collections.\");\n console.log(\"Attempting to seed all Collections.\");\n return seedFighters(fighters);\n }).then((fighterNumber) => {\n console.log(`Successfully seeded ${fighterNumber} Fighters.`);\n return seedStages(stages);\n }).then((stageNumber) => {\n console.log(`Successfully seeded ${stageNumber} Stages.`);\n console.log(chalk.green('success') + \": Successfully seeded the database.\");\n cleanUp(0);\n }).catch((err) => {\n console.log(chalk.red('error') + \": Error seeding database.\");\n console.log(err);\n console.log(\"Could not successfully seed the database...\");\n cleanUp(1);\n });\n}", "async function createArtistDB() {\n for (var i = 0; i < artistLink.length; i++) {\n await timeoutPromise(1000);\n scraper(artistLink[i], ArtistDB);\n }\n await timeoutPromise(5000);\n console.log(ArtistDB);\n enrichingArtistDB(ArtistDB);\n}", "function onReady() {\n // Signal if there was a fault\n if (this._readyError) {\n if (callback != null)\n callback(this._readyError)\n return;\n }\n\n // Process the queue\n this._ready = true;\n async.series(deferredQueue, function(err,result){\n // NOT passing any errors since these should have been originally handled by the caller\n if (callback != null)\n callback(null, db);\n });\n }", "function createCollection( databaseObject, collectionName ) {\r\n\treturn new Promise(function(resolve, reject) {\r\n\t\t// Create a collection to store users\r\n\t\tdatabaseObject.createCollection(collectionName, function(error, response) {\r\n\t\t\t// If we have an error...\r\n\t\t\tif (error) {\r\n\t\t\t\t// Reject the promise\r\n\t\t\t\treject('Error creating ' + collectionName);\r\n\t\t\t// Otherwise...\r\n\t\t\t} else {\r\n\t\t\t\t// Resolve as succesfully created\r\n\t\t\t\tresolve('Created collection ' + collectionName);\r\n\t\t\t}\r\n\t\t});\r\n\t});\r\n}", "static init() {\n\t\tconst oThis = this;\n\t\t// looping over all databases\n\t\tfor (let dbName in mysqlConfig['databases']) {\n\t\t\tlet dbClusters = mysqlConfig['databases'][dbName];\n\t\t\t// looping over all clusters for the database\n\t\t\tfor (let i = 0; i < dbClusters.length; i++) {\n\t\t\t\tlet cName = dbClusters[i],\n\t\t\t\t\tcConfig = mysqlConfig['clusters'][cName];\n\n\t\t\t\t// creating pool cluster object in poolClusters map\n\t\t\t\toThis.generateCluster(cName, dbName, cConfig);\n\t\t\t}\n\t\t}\n\t}", "function ensure_database_exists(callback) {\n var options = {\n host: config.couch.host,\n port: config.couch.port,\n path: '/' + config.couch.db,\n method: 'PUT',\n headers: {\n \"Content-Type\": \"application/json\",\n \"User-Agent\": user_agent,\n \"Accept\": \"application/json\"\n }\n };\n http.request(options, function(response) {\n /* CouchDB returns 201 if the DB was created or 412 if it already exists. */\n if (response.statusCode === 201 || response.statusCode === 412) {\n response.on('end', callback);\n } else {\n util.error(\"couldn't make database; request returned \" + response.statusCode);\n }\n }).end();\n}", "createNewCollection(){\n // return this.db.createCollection(name)\n }", "function websqlInit() {\n db = window.openDatabase(dbName, dbVersion, dbDescription, dbAmount);\n //if (db.version != '1.0.0') {\n db.transaction(function(tx) {\n console.log(\"SUCCESS: Init websql database.\");\n tx.executeSql('CREATE TABLE IF NOT EXISTS users (id integer primary key autoincrement, name, surname, email)');\n });\n //}\n\n if (!db) {\n alert(\"Your browser doesn't support a stable version of Web SQL Database. Such and such feature will not be available.\");\n }\n // list saved data\n websqlListData();\n}", "function createDb() {\n pluses_db.run(\"CREATE TABLE pluses (nick text, pluses)\", function(err) {\n if (err) {\n console.log(err);\n }\n });\n}", "static createIDBObjects(){\r\n\r\n\t\treturn idb.open(DBHelper.IDB_DATABASE, 1, upgradeDb => {\r\n\r\n\t\t\tvar restaurantsStore = upgradeDb.createObjectStore('restaurants',{\r\n\t\t\t\tkeyPath: 'id'\r\n\t\t\t});\r\n\r\n\t\t\tvar reviewsStore = upgradeDb.createObjectStore('reviews',{\r\n\t\t\t\tkeyPath: 'id'\r\n\t\t\t});\r\n\t\t\treviewsStore.createIndex(\"restaurant_id\", \"restaurant_id\");\r\n\r\n\t\t\tvar offlineStore = upgradeDb.createObjectStore('offlineRequests',{\r\n\t\t\t\tkeyPath: 'id',\r\n\t\t\t\tautoIncrement: true\r\n\t\t\t});\r\n\r\n\t\t});\r\n\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
set up the events if we have a colision between monster and arrow
function colisionMonsterAndArrow(monster, arrow){ if(monster !== undefined && arrow !== undefined){ if(bump.hit(monster, arrow)){ log("colision ok"); // //remove heart // stage.removeChild(hearts[monsterLives-1]); // hearts.splice(monsterLives-1, 1); // //get live // monsterLives -= 1; // //play sound // getHeartSound.play(); // //destroy arrow // stage.removeChild(arrow); // arrow = undefined; // // vibrate fow 300 ms // window.navigator.vibrate(300); } } }
[ "createInteractionZones() {\n this.r3a1_graphics = this.add.graphics({fillStyle: {color: 0xFFFFFF, alpha: 0.0}});\n //this.graphicsTest = this.add.graphics({fillStyle: {color: 0x4F4F4F, alpha: 1.0}});\n //TOP ZONES\n //xpos ypos x y\n this.r3a1_increaseAssets = new Phaser.Geom.Rectangle(425,300,100,100);\n this.r3a1_graphics.fillRectShape(this.r3a1_increaseAssets);\n\n this.r3a1_decreaseAssets = new Phaser.Geom.Rectangle(425,500,100,100);\n this.r3a1_graphics.fillRectShape(this.r3a1_decreaseAssets);\n\n this.r3a1_increaseLiabilities = new Phaser.Geom.Rectangle(525,300,100,100);\n this.r3a1_graphics.fillRectShape(this.r3a1_increaseLiabilities);\n\n this.r3a1_decreaseLiabilities = new Phaser.Geom.Rectangle(525,500,100,100);\n this.r3a1_graphics.fillRectShape(this.r3a1_decreaseLiabilities);\n\n this.r3a1_increaseStock = new Phaser.Geom.Rectangle(625,300,100,100);\n this.r3a1_graphics.fillRectShape(this.r3a1_increaseStock);\n\n this.r3a1_decreaseStock = new Phaser.Geom.Rectangle(625,500,100,100);\n this.r3a1_graphics.fillRectShape(this.r3a1_decreaseStock);\n\n this.r3a1_increaseRevenue = new Phaser.Geom.Rectangle(725,300,100,100);\n this.r3a1_graphics.fillRectShape(this.r3a1_increaseRevenue);\n\n this.r3a1_decreaseRevenue = new Phaser.Geom.Rectangle(725,500,100,100);\n this.r3a1_graphics.fillRectShape(this.r3a1_decreaseRevenue);\n\n this.r3a1_increaseExpenses = new Phaser.Geom.Rectangle(825,300,100,100);\n this.r3a1_graphics.fillRectShape(this.r3a1_increaseExpenses);\n\n this.r3a1_decreaseExpenses = new Phaser.Geom.Rectangle(825,500,100,100);\n this.r3a1_graphics.fillRectShape(this.r3a1_decreaseExpenses);\n\n this.r3a1_increaseDividend = new Phaser.Geom.Rectangle(925,300,100,100);\n this.r3a1_graphics.fillRectShape(this.r3a1_increaseDividend);\n\n this.r3a1_decreaseDividend = new Phaser.Geom.Rectangle(925,500,100,100);\n this.r3a1_graphics.fillRectShape(this.r3a1_decreaseDividend);\n\n //this.r3a1_holeInteract = new Phaser.Geom.Rectangle(1300, 400, 100, 100);\n //this.r3a1_graphics.fillRectShape(this.r3a1_holeInteract);\n\n this.r3a1_exitDoor_zone = new Phaser.Geom.Rectangle(113,320,100,100);\n this.r3a1_graphics.fillRectShape(this.r3a1_exitDoor_zone);\n }", "implementMouseInteractions() {\t\t\n\t\t// mouse click interactions\n\t\tthis.ctx.canvas.addEventListener(\"click\", this.towerStoreClick, false);\n\t\t\n\t\t// mouse move interactions\n\t\tthis.ctx.canvas.addEventListener(\"mousemove\", this.towerStoreMove, false);\t\n\t}", "function newEvent() {\n\n\t\t//console.log('here'+i);\n\n\t\t//use the value i to set when a background &/or character should change\n\t\tif (i >= 0 && i < 4) {\n\t\t\tchangeBackground('url(\"./images/bgs/clockbg.png\")'); \n\t\t}\n\n\t\tif (i == 0) {\n\t\t\tchangeCharacter('url(\"\")'); //emtpy\n\t\t\tplayAudio('\"./audio/effect/clock.m4a\"', false);\t\t\t\t\n\t\t}\n\n\t\tif (i == 1) {\n\t\t\tshakeScreen();\n\t\t}\n\n\t\tif (i >= 1 && i <= 4) {\n\t\t\tchangeCharacter('url(\"\")'); //empty\n\t\t\tchangeBackground('url(\"./images/bgs/room_interior2.jpg\")'); \t\t\t\t\n\t\t}\n\n\t\tif (i < 5) {\n\t\t\tbgMusic.volume = 0.5;\n\t\t\tbgAudio.volume = 0;\n\t\t\tbgAudio2.volume = 0;\n\t\t}\n\n\t\tif (i >= 5 && i < 23) {\n\t\t\tbgAudio.volume = 0.5;\n\t\t\tbgMusic.volume = 0;\n\t\t\tbgAudio2.volume = 0;\n\t\t}\n\n\t\tif (i >= 23 && i < 47) {\n\t\t\tbgAudio2.volume = 0.5;\n\t\t\tbgMusic.volume = 0;\n\t\t\tbgAudio.volume = 0;\n\t\t}\n\n\t\tif (i >= 47) {\n\t\t\tbgAudio.volume = 0.5;\n\t\t\tbgMusic.volume = 0;\n\t\t\tbgAudio2.volume = 0;\n\t\t}\n\n\t\t\n\t\tif (i >= 5 && i <= 7) {\n\t\t\tchangeCharacter('url(\"\")'); //empty\n\t\t\tchangeBackground('url(\"./images/bgs/street6.jpg\")'); \t\t\t\t\t\t\n\t\t}\n\n\t\tif (i >= 8 && i <= 20) {\n\t\t\tchangeCharacter('url(\"./images/characters/Boss.png\")');\n\t\t\tchangeBackground('url(\"./images/bgs/shop_interior1.jpg\")');\n\t\t} \n\t\tif (i >= 21 && i <= 22){\n\t\t\tchangeCharacter('url(\"\")'); //empty\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t} \n\n\t\tif (i == 21) {\n\t\t\tplayAudio(\"./audio/effect/Creeky-Interior-Door.mp3\");\n\t\t}\n\t\tif (i >= 23 && i <= 35){\n\t\t\tchangeCharacter('url(\"./images/characters/Sora.gif\")');\t\t\t\n\t\t} \n\t\tif (i >= 36 && i <= 38){\n\t\t\tchangeCharacter('url(\"\")'); //empty\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t} \n\t\tif (i >= 39 && i <= 46){\n\t\t\tchangeCharacter('url(\"./images/characters/Sora.gif\")');\t\n\t\t} \n\t\tif (i >= 47 && i <= 50){\n\t\t\tchangeCharacter('url(\"./images/characters/BusinessCard.png\")'); //empty\t\n\t\t} \n\t\tif (i >= 51){\n\t\t\tchangeCharacter('url(\"./images/characters/BossAngry.png\")');\n\t\t}\n\n\t}", "_setupCollision () {\n this.PhysicsManager.getEventHandler().on(this.PhysicsManager.getEngine(), 'collisionStart', (e) => {\n\n for (let pair of e.pairs) {\n let bodyA = pair.bodyA\n let bodyB = pair.bodyB\n\n if (bodyB === this.body) {\n this.onCollisionWith(bodyA)\n }\n }\n })\n }", "function ReadyToFire(){\n\tif(!anim.IsInTransition(3))\n\t\tanim.SetBool(\"charged\", true); \n}", "manageCollitions () {\n var paramRobot = this.robot.getParameters();\n for (var i = 0; i < this.maxFly; ++i) {\n var paramFly = this.fly[i].getParameters();\n var distance = Math.sqrt(Math.pow((paramFly.x - paramRobot.pos.x),2) + Math.pow((paramFly.y - paramRobot.pos.y),2)\n + Math.pow((paramFly.z - paramRobot.pos.z),2));\n\n if (distance <= (paramRobot.radio + paramFly.radio)) {\n this.fly[i].setCollision();\n this.lastHealth = this.health;\n\n if (!paramFly.behaviour) {\n this.health -= 10;\n if (this.health < 0) this.health = 0;\n } else if (paramFly.behaviour) {\n var scorePlus = Math.floor(Math.random()*(5+1))\n this.health += 5 - scorePlus;\n this.score += scorePlus;\n this.setScore();\n if(this.health > 100) this.health = 100;\n }\n this.manageHUD();\n this.hud.changeSize(this.health);\n this.hudRobot.changeSize(this.health);\n }\n }\n }", "function moveSomething(e) {\n\t\t\tfunction moveLeftRight(xVal){\n\t\t\t\tvar newX = xVal;\n\t\t\t\tboard.player.xPrev = board.player.x;\n\t\t\t\tboard.player.yPrev = board.player.y;\n\t\t\t\tboard.player.x = newX;\n\t\t\t\tboard.player.y = board.player.y;\n\t\t\t\tboard.position[newX][board.player.y] = 4;\n\t\t\t\tboard.position[board.player.xPrev][board.player.yPrev] = 0;\n\t\t\t\tboard.player.erasePrevious();\n\t\t\t\tboard.player.render();\n\t\t\t}\n\t\t\tfunction moveUpDown(yVal){\n\t\t\t\tvar newY = yVal;\n\t\t\t\tboard.player.xPrev = board.player.x;\n\t\t\t\tboard.player.yPrev = board.player.y;\n\t\t\t\tboard.player.x = board.player.x;\n\t\t\t\tboard.player.y = newY;\n\t\t\t\tboard.position[board.player.x][newY] = 4;\n\t\t\t\tboard.position[board.player.xPrev][board.player.yPrev] = 0;\n\t\t\t\tboard.player.erasePrevious();\n\t\t\t\tboard.player.render();\n\t\t\t}\n\t\t\tfunction enemiesMove(){\n\t\t\t\tif (!board.enemy1.enemyDead)\n\t\t\t\t\tenemy1Move.makeMove();\n\t\t\t\tif (!board.enemy2.enemyDead)\n\t\t\t\t\tenemy2Move.makeMove();\n\t\t\t\tif (!board.enemy3.enemyDead)\n\t\t\t\t\tenemy3Move.makeMove();\n\t\t\t}\n\t\t\tfunction checkForWin(){\n\t\t\t\tif (board.enemy1.enemyDead && board.enemy2.enemyDead && board.enemy3.enemyDead){\n\t\t\t\t\tconsole.log(\"You Win!!!!! *airhorn*\" )\n\t\t\t\t\tboard.player.eraseThis();\n\t\t\t\t\t//board.potion1.eraseThis();\n\t\t\t\t\t//board.potion2.eraseThis();\n\t\t\t\t\tctx.beginPath();\n\t\t\t\t\tctx.font = \"128px Georgia\";\n\t\t\t\t\tctx.fillStyle = \"#00F\";\n\t\t\t\t\tctx.fillText(\"You Win!!\", 40, 320);\n\t\t\t}\n\t\t\t}\n\t\t\tfunction restoreHealth(xVal,yVal){\n\t\t\t\tvar x = xVal;\n\t\t\t\tvar y = yVal;\n\t\t\t\tif (board.position[x][y] == 5){\n\t\t\t\t\tboard.player.restoreHealth();\n\t\t\t\t\tif(board.potion1.x == x && board.potion1.y == y)\n\t\t\t\t\t\tboard.potion1.eraseThis()\n\t\t\t\t\telse \n\t\t\t\t\t\tboard.potion2.eraseThis();\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\tif(!board.player.playerDead || board.enemy1.enemyDead && board.enemy2.enemyDead && board.enemy3.enemyDead){\n\t\t\tswitch(e.keyCode) {\n\t\t\t\tcase 37:\n\t\t\t\t\t// left key pressed\n\t\t\t\t\tvar newX = board.player.x - 1;\n\t\t\t\t\tif(board.player.x == 0)\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tif(board.position[newX][board.player.y] == 0 || board.position[newX][board.player.y] == 5)\n\t\t\t\t\t{\n\t\t\t\t\t\tconsole.log(\"Left was pressed...\\n\");\n\t\t\t\t\t\trestoreHealth(newX,board.player.y);\n\t\t\t\t\t\tmoveLeftRight(newX);\n\t\t\t\t\t\tenemiesMove();\n\t\t\t\t\t}\n\t\t\t\t\telse if(board.position[newX][board.player.y] == 3){\n\t\t\t\t\t\tconsole.log(\"Enemy is taking damage...\");\n\t\t\t\t\t\tif(board.enemy1.x == newX && board.enemy1.y == board.player.y){\n\t\t\t\t\t\t\tboard.enemy1.takeDamage();\n\t\t\t\t\t\t\tif(board.enemy1.enemyDead)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tmoveLeftRight(newX);\n\t\t\t\t\t\t\t\tcheckForWin();\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if(board.enemy2.x == newX && board.enemy2.y == board.player.y){\n\t\t\t\t\t\t\tboard.enemy2.takeDamage();\n\t\t\t\t\t\t\t\tif(board.enemy2.enemyDead)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tmoveLeftRight(newX);\n\t\t\t\t\t\t\t\tcheckForWin();\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if(board.enemy3.x == newX && board.enemy3.y == board.player.y){\n\t\t\t\t\t\t\tboard.enemy3.takeDamage();\n\t\t\t\t\t\t\t\tif(board.enemy3.enemyDead)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tmoveLeftRight(newX);\n\t\t\t\t\t\t\t\tcheckForWin();\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tenemiesMove();\n\t\t\t\t\t}\n\t\t\t\t\t\t\n\t\t\t\t\tbreak;\n\t\t\t\tcase 38:\n\t\t\t\t\t// up key \n\t\t\t\t\tvar newY = board.player.y - 1;\n\t\t\t\t\tif(board.player.y == 0)\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tif(board.position[board.player.x][newY] == 0 || board.position[board.player.x][newY] == 5)\n\t\t\t\t\t{\n\t\t\t\t\t console.log(\"Up was pressed...\\n\");\n\t\t\t\t\t\trestoreHealth(board.player.x,newY);\n\t\t\t\t\t\tmoveUpDown(newY);\n\t\t\t\t\t\tenemiesMove();\n\t\t\t\t\t}\n\t\t\t\t\telse if(board.position[board.player.x][newY] == 3){\n\t\t\t\t\t\tconsole.log(\"Enemy is taking damage...\");\n\t\t\t\t\t\tif(board.enemy1.x == board.player.x && board.enemy1.y == newY){\n\t\t\t\t\t\t\tboard.enemy1.takeDamage();\n\t\t\t\t\t\t\tif(board.enemy1.enemyDead){\n\t\t\t\t\t\t\t\tmoveUpDown(newY);\n\t\t\t\t\t\t\t\tcheckForWin();\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if(board.enemy2.x == board.player.x && board.enemy2.y == newY){\n\t\t\t\t\t\t\tboard.enemy2.takeDamage();\n\t\t\t\t\t\t\tif(board.enemy2.enemyDead){\n\t\t\t\t\t\t\t\tmoveUpDown(newY);\n\t\t\t\t\t\t\t\tcheckForWin();\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if(board.enemy3.x == board.player.x && board.enemy3.y == newY){\n\t\t\t\t\t\t\tboard.enemy3.takeDamage();\n\t\t\t\t\t\t\tif(board.enemy3.enemyDead){\n\t\t\t\t\t\t\t\tmoveUpDown(newY);\n\t\t\t\t\t\t\t\tcheckForWin();\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tenemiesMove();\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tcase 39:\n\t\t\t\t\t// right key pressed\n\t\t\t\t\tvar newX = board.player.x + 1;\n\t\t\t\t\tif(board.player.x == 9)\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tif(board.position[newX][board.player.y] == 0 || board.position[newX][board.player.y] == 5)\n\t\t\t\t\t{\n\t\t\t\t\t\tconsole.log(\"Right was pressed...\\n\");\n\t\t\t\t\t\trestoreHealth(newX,board.player.y);\n\t\t\t\t\t\tmoveLeftRight(newX);\n\t\t\t\t\t\tenemiesMove();\n\t\t\t\t\t\t\n\t\t\t\t\t}\n\t\t\t\t\telse if(board.position[newX][board.player.y] == 3){\n\t\t\t\t\t\tconsole.log(\"Enemy is taking damage...\");\n\t\t\t\t\t\t\tif(board.enemy1.x == newX && board.enemy1.y == board.player.y){\n\t\t\t\t\t\t\tboard.enemy1.takeDamage();\n\t\t\t\t\t\t\tif(board.enemy1.enemyDead){\n\t\t\t\t\t\t\t\tmoveLeftRight(newX);\n\t\t\t\t\t\t\t\tcheckForWin();\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if(board.enemy2.x == newX && board.enemy2.y == board.player.y){\n\t\t\t\t\t\t\tboard.enemy2.takeDamage();\n\t\t\t\t\t\t\t\tif(board.enemy2.enemyDead){\n\t\t\t\t\t\t\t\tmoveLeftRight(newX);\n\t\t\t\t\t\t\t\tcheckForWin();\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if(board.enemy3.x == newX && board.enemy3.y == board.player.y){\n\t\t\t\t\t\t\tboard.enemy3.takeDamage();\n\t\t\t\t\t\t\t\tif(board.enemy3.enemyDead){\n\t\t\t\t\t\t\t\tmoveLeftRight(newX);\n\t\t\t\t\t\t\t\tcheckForWin();\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tenemiesMove();\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tcase 40:\n\t\t\t\t\t// down key pressed\n\t\t\t\t\tvar newY = board.player.y + 1;\n\t\t\t\t\tif(board.player.y == 9)\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tif(board.position[board.player.x][newY] == 0 || board.position[board.player.x][newY] == 5)\n\t\t\t\t\t{\n\t\t\t\t\t\tconsole.log(\"Down was pressed...\\n\");\n\t\t\t\t\t\trestoreHealth(board.player.x,newY);\n\t\t\t\t\t\tmoveUpDown(newY);\n\t\t\t\t\t\tenemiesMove();\n\t\t\t\t\t\t\n\t\t\t\t\t}\n\t\t\t\t\telse if(board.position[board.player.x][newY] == 3){\n\t\t\t\t\t\tconsole.log(\"Enemy is taking damage...\");\n\t\t\t\t\t\t\tif(board.enemy1.x == board.player.x && board.enemy1.y == newY){\n\t\t\t\t\t\t\tboard.enemy1.takeDamage();\n\t\t\t\t\t\t\tif(board.enemy1.enemyDead){\n\t\t\t\t\t\t\t\tmoveUpDown(newY);\n\t\t\t\t\t\t\t\tcheckForWin();\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if(board.enemy2.x == board.player.x && board.enemy2.y == newY){\n\t\t\t\t\t\t\tboard.enemy2.takeDamage();\n\t\t\t\t\t\t\tif(board.enemy2.enemyDead){\n\t\t\t\t\t\t\t\tmoveUpDown(newY);\n\t\t\t\t\t\t\t\tcheckForWin();\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if(board.enemy3.x == board.player.x && board.enemy3.y == newY){\n\t\t\t\t\t\t\tboard.enemy3.takeDamage();\n\t\t\t\t\t\t\tif(board.enemy3.enemyDead){\n\t\t\t\t\t\t\t\tmoveUpDown(newY);\n\t\t\t\t\t\t\t\tcheckForWin();\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tenemiesMove();\n\t\t\t\t\t}\n\t\t\t\t\tbreak; \n\t\t\t}\n\t\t\t//console.log(\"heres our current player position in moveSomething \"+board.player.x + board.player.y);\n\t\t\t}\t//console.log(\"heres our previous player position in moveSomething \"+board.player.xPrev + board.player.yPrev);\t\t\n\t\t}", "function handleMouseDownEvent(){\n board.selectAll(\".void, .wall, .start, .end\").on(\"mousemove\", handleMouseMoveEvent);\n}", "function checkEnergyCollision() {\r\n energies.forEach(function (e) {\r\n if ((player.X < e.x + energyRadius) &&\r\n (player.X + player.width > e.x) &&\r\n (player.Y < e.y + energyRadius) &&\r\n (player.Y + player.height > e.y)) {\r\n e.onCollide();\r\n //startSound();\r\n }\r\n })\r\n}", "function initializeEvents(){\n var images = getImgArray(); \n images.forEach(addConcentrationHandler);\n}", "function collitest() {\r\n var topGap = 0; // écart entre le tornaTop et le missiTop\r\n var tornaPos = $(\"#tornado\").position(); // récup de la position de l'avion\r\n var missiPos = $(\"#missile\").position(); // récup de la position du missile\r\n var tornaTop = parseInt(tornaPos.top); // récup du top de l'avion\r\n var missiTop = parseInt(missiPos.top); // récup du top du missile\r\n var missiLeft = parseInt(missiPos.left); // récup de la partie gauche du missile\r\n\r\n if (missiLeft > 87 && missiLeft < 150) {\r\n // test de collision du nez de l'avion qui déclenche un DOH! en cas d'impact\r\n topGap = tornaTop - missiTop; // calcul de l'écart vertical entre l'avion et le missile\r\n\r\n if (topGap < -16 && topGap > -48) {\r\n // trigger pour le déclenchement de la collision du nez\r\n dohSound.play(); // déclenchement du DOH\r\n }\r\n }\r\n\r\n if (missiLeft < 86) {\r\n // si l'impact a lieu entre l'arriere de la verriere et les réacteurs on entend le beep.mp3\r\n topGap = tornaTop - missiTop; // calcul de l'écart vertical entre l'avion et le missile\r\n\r\n if (topGap < 28 && topGap > -92) {\r\n // trigger pour le déclenchement de la collision du reste de l'avion\r\n crashSound.play(); // déclenchement du crash.mp3\r\n }\r\n }\r\n}", "function draw() {\n background (50, 255, 50);\n\n//shape outline\n noStroke()\n\n//kermit image\n imageMode(CENTER);\n image(kermitImage, mouseX, mouseY);\n\n\n // covid 19 movement\n covid19.x = covid19.x + covid19.vx;\n covid19.y = covid19.y + covid19.vy;\n\n if (covid19.x > width) {\n covid19.x = 0;\n covid19.y = random(0,height);\n }\n\n //covid 19 growth\n if (covid19.x < width/1.002){\n covid19.size = covid19.size + 3;\n }\n else {\n covid19.size = 100;\n }\n\n // covid 20 movement\n covid20.x = covid20.x + covid20.vx;\n covid20.y = covid20.y + covid20.vy;\n\n if (covid20.x > width) {\n covid20.x = 0;\n covid20.y = random(0,height);\n }\n\n //covid 20 growth\n if (covid20.x < width/1.002){\n covid20.size = covid20.size + 1;\n }\n else {\n covid20.size = 100;\n }\n\n //user movement\n user.x = mouseX;\n user.y = mouseY;\n\n // check for bumping covid19\n let d = dist(user.x,user.y,covid19.x,covid19.y);\n if (d < covid19.size/2 + user.size/2) {\n noLoop();\n }\n\n // display covid 19\n fill(covid19.fill.r, covid19.fill.g, covid19.fill.b);\n ellipse(covid19.x, covid19.y, covid19.size);\n\n // display covid 20\n fill(covid20.fill.r, covid20.fill.g, covid20.fill.b);\n ellipse(covid20.x, covid20.y, covid20.size);\n\n // display user\n fill(user.fill);\n square(user.x, user.y, user.size);\n\n}", "setColliders() {\n this.physics.add.collider(this.player, this.platforms);\n this.physics.add.collider(this.stars, this.platforms);\n this.physics.add.collider(this.bombs, this.platforms);\n this.physics.add.collider(this.player, this.bombs, this.endGame, null, this);\n this.physics.add.overlap(this.player, this.stars, this.collectStar, null, this);\n }", "function lineCollisionVertical(){\n for (let i = 0; i < verticalDoorList.length; i++){\n if(verticalCollisionLine1 && !verticalDoorList[i].collision()){\n //console.log(\"yeet\")\n if (previousXPerson > person.x){\n backwardX = 0;\n }\n if (previousXPerson < person.x){\n forwardX = 0;\n }\n if (previousYPerson < person.y){\n downY = 0;\n }\n if (previousYPerson > person.y){\n upY = 0;\n }\n }\n else if(verticalCollisionLine2 && !verticalDoorList[i].collision()){\n if (previousXPerson > person.x){\n backwardX = 0;\n }\n if (previousXPerson < person.x){\n forwardX = 0;\n }\n if (previousYPerson < person.y){\n downY = 0;\n }\n if (previousYPerson > person.y){\n upY = 0;\n }\n }\n else if(verticalCollisionLine3 && !verticalDoorList[i].collision()){\n if (previousXPerson > person.x){\n backwardX = 0;\n }\n if (previousXPerson < person.x){\n forwardX = 0;\n }\n if (previousYPerson < person.y){\n downY = 0;\n }\n if (previousYPerson > person.y){\n upY = 0;\n }\n }\n else if(verticalCollisionLine4 && !verticalDoorList[i].collision()){\n if (previousXPerson > person.x){\n backwardX = 0;\n }\n if (previousXPerson < person.x){\n forwardX = 0;\n }\n if (previousYPerson < person.y){\n downY = 0;\n }\n if (previousYPerson > person.y){\n upY = 0;\n }\n }\n else if(verticalCollisionLine5 && !verticalDoorList[i].collision()){\n if (previousXPerson > person.x){\n backwardX = 0;\n }\n if (previousXPerson < person.x){\n forwardX = 0;\n }\n if (previousYPerson < person.y){\n downY = 0;\n }\n if (previousYPerson > person.y){\n upY = 0;\n }\n }\n else if(verticalCollisionLine6 && !verticalDoorList[i].collision()){\n if (previousXPerson > person.x){\n backwardX = 0;\n }\n if (previousXPerson < person.x){\n forwardX = 0;\n }\n if (previousYPerson < person.y){\n downY = 0;\n }\n if (previousYPerson > person.y){\n upY = 0;\n }\n }\n else if(verticalCollisionLine7 && !verticalDoorList[i].collision()){\n if (previousXPerson > person.x){\n backwardX = 0;\n }\n if (previousXPerson < person.x){\n forwardX = 0;\n }\n if (previousYPerson < person.y){\n downY = 0;\n }\n if (previousYPerson > person.y){\n upY = 0;\n }\n }\n else if(verticalCollisionLine8 && !verticalDoorList[i].collision()){\n if (previousXPerson > person.x){\n backwardX = 0;\n }\n if (previousXPerson < person.x){\n forwardX = 0;\n }\n if (previousYPerson < person.y){\n downY = 0;\n }\n if (previousYPerson > person.y){\n upY = 0;\n }\n }\n else if(verticalCollisionLine9 && !verticalDoorList[i].collision()){\n if (previousXPerson > person.x){\n backwardX = 0;\n }\n if (previousXPerson < person.x){\n forwardX = 0;\n }\n if (previousYPerson < person.y){\n downY = 0;\n }\n if (previousYPerson > person.y){\n upY = 0;\n }\n }\n else if(verticalCollisionLine10 && !verticalDoorList[i].collision()){\n if (previousXPerson > person.x){\n backwardX = 0;\n }\n if (previousXPerson < person.x){\n forwardX = 0;\n }\n if (previousYPerson < person.y){\n downY = 0;\n }\n if (previousYPerson > person.y){\n upY = 0;\n }\n }\n else if(verticalCollisionLine11 && !verticalDoorList[i].collision()){\n if (previousXPerson > person.x){\n backwardX = 0;\n }\n if (previousXPerson < person.x){\n forwardX = 0;\n }\n if (previousYPerson < person.y){\n downY = 0;\n }\n if (previousYPerson > person.y){\n upY = 0;\n }\n }\n else if(verticalCollisionLine12 && !verticalDoorList[i].collision()){\n if (previousXPerson > person.x){\n backwardX = 0;\n }\n if (previousXPerson < person.x){\n forwardX = 0;\n }\n if (previousYPerson < person.y){\n downY = 0;\n }\n if (previousYPerson > person.y){\n upY = 0;\n }\n }\n else if(verticalCollisionLine13 && !verticalDoorList[i].collision()){\n if (previousXPerson > person.x){\n backwardX = 0;\n }\n if (previousXPerson < person.x){\n forwardX = 0;\n }\n if (previousYPerson < person.y){\n downY = 0;\n }\n if (previousYPerson > person.y){\n upY = 0;\n }\n }\n else if(verticalCollisionLine14 && !verticalDoorList[i].collision()){\n if (previousXPerson > person.x){\n backwardX = 0;\n }\n if (previousXPerson < person.x){\n forwardX = 0;\n }\n if (previousYPerson < person.y){\n downY = 0;\n }\n if (previousYPerson > person.y){\n upY = 0;\n }\n }\n else if(verticalCollisionLine15 && !verticalDoorList[i].collision()){\n if (previousXPerson > person.x){\n backwardX = 0;\n }\n if (previousXPerson < person.x){\n forwardX = 0;\n }\n if (previousYPerson < person.y){\n downY = 0;\n }\n if (previousYPerson > person.y){\n upY = 0;\n }\n }\n else if(verticalCollisionLine16 && !verticalDoorList[i].collision()){\n if (previousXPerson > person.x){\n backwardX = 0;\n }\n if (previousXPerson < person.x){\n forwardX = 0;\n }\n if (previousYPerson < person.y){\n downY = 0;\n }\n if (previousYPerson > person.y){\n upY = 0;\n }\n }\n else if(verticalCollisionLine17 && !verticalDoorList[i].collision()){\n if (previousXPerson > person.x){\n backwardX = 0;\n }\n if (previousXPerson < person.x){\n forwardX = 0;\n }\n if (previousYPerson < person.y){\n downY = 0;\n }\n if (previousYPerson > person.y){\n upY = 0;\n }\n }\n else if(verticalCollisionLine18 && !verticalDoorList[i].collision()){\n if (previousXPerson > person.x){\n backwardX = 0;\n }\n if (previousXPerson < person.x){\n forwardX = 0;\n }\n if (previousYPerson < person.y){\n downY = 0;\n }\n if (previousYPerson > person.y){\n upY = 0;\n }\n }\n else if(verticalCollisionLine19 && !verticalDoorList[i].collision()){\n console.log(\"yeet\")\n if (previousXPerson > person.x){\n console.log(\"yeet2\")\n backwardX = 0;\n }\n if (previousXPerson < person.x){\n console.log(\"yeet2\")\n forwardX = 0;\n }\n if (previousYPerson < person.y){\n console.log(\"yeet2\")\n downY = 0;\n }\n if (previousYPerson > person.y){\n console.log(\"yeet2\")\n upY = 0;\n }\n }\n else if(verticalCollisionLine20 && !verticalDoorList[i].collision()){\n if (previousXPerson > person.x){\n backwardX = 0;\n }\n if (previousXPerson < person.x){\n forwardX = 0;\n }\n if (previousYPerson < person.y){\n downY = 0;\n }\n if (previousYPerson > person.y){\n upY = 0;\n }\n }\n else if(verticalCollisionLine21 && !verticalDoorList[i].collision()){\n if (previousXPerson > person.x){\n backwardX = 0;\n }\n if (previousXPerson < person.x){\n forwardX = 0;\n }\n if (previousYPerson < person.y){\n downY = 0;\n }\n if (previousYPerson > person.y){\n upY = 0;\n }\n }\n else{\n backwardX = 1;\n forwardX = 1;\n //downY = 1;\n //upY = 1;\n }\n }\n}", "checkPortalCollision() {\n /*\n If the player steps in a portal:\n 1. Deactivate the player to prevent retriggering portal. \n 2. Trigger transitionRoom(target_room). \n 3. Emit the ROOM_TRANISITION event, passing the room to transition to. \n Note: (the following steps are handled by an event listener for the camera fade finish).\n 4. Jump the player to the specified spawn position. \n 5. Reactivate the player. \n */\n let room = this.scene.rooms[this.scene.curRoomKey];\n room.portalsArr.forEach((portal) => {\n if (Phaser.Geom.Rectangle.Overlaps(this.sprite.getBounds(), portal)) {\n // this.targetSpawn = portal.to_spawn;\n this.setActive(false);\n this.scene.transitionRoom(portal.to_room);\n this.to_spawn = portal.to_spawn;\n this.emitter.emit(events.ROOM_TRANSITION_START, portal.to_room);\n return;\n }\n });\n }", "function drawDirectionObjA(shapeName, line, xPos, yPos, arrow, scope) {\n shapeName.cursor = \"pointer\";\n shapeName.name = \"objA\";\n shapeName.on(\"pressmove\", function(evt) {\n this.x = evt.stageX;\n this.y = evt.stageY;\n line.graphics.clear();\n if (this.y > final_pos_direction_y) {\n this.y = final_pos_direction_y;\n }\n line.graphics.moveTo(xPos, yPos).setStrokeStyle(5).beginStroke(\"red\").lineTo(this.x, this.y);\n collision_stage.addChild(line);\n scope.start_disable = false;\n objDirectionArrow(arrow, this.x, this.y, xPos, yPos, \"objA\");\n })\n}", "buildTeamBoxes(){\n new TeamBox(this, \"team goes here\", 80, 70).create()\n .setInteractive().on('pointerup', ()=>{\n this.scene.sleep('battle')\n this.scene.launch('switch')\n },this);\n new TeamBox(this, \"enemy team goes here\", 530, 70).create();\n }", "ontick(movementCallback, eventCallback, queryEnemiesinRadius, queryTowersinRadius) {}", "function master_controller() {\n\tthis.base_levels = [];\n\tthis.base_levels['frog'] = 1;\n\tthis.base_levels['bunny'] =1;\n\tthis.base_levels['bird'] = 1;\n\tthis.base_levels['deer'] = 1;\n\t\n\tthis.animals = [];\n\t\n\tthis.party_limit = 5;\n\t\n\t\n\tthis.timer = 0;\n\t\n\tthis.area_level = 1;\n\tthis.areaSeason = 'spring';\n\t\n\tthis.usableEvents = badEventsSpringDay.slice();\n\tvar evR = roll(2,0);\n\tthis.usableEvents.push(badEventsCatastrophe[evR]);\n\t\n\t\n\t\n\tthis.removalQ = [];\n\t\n\t//this.lifespans = new p_queue();\n\t\n\tthis.animations = [];\n\t\n\tthis.getAreaLevel = function(){\n\t\treturn this.area_level;\n\t}\n\t\n\tthis.areaLevelUp = function(){\n\t\tthis.area_level+=1;\n\t\tif(this.area_level % 10 == 1){\n\t\t\tswitch(this.areaSeason){\n\t\t\t\tcase 'spring':\n\t\t\t\t this.areaSeason = 'summer';\n\t\t\t\t\tbackground.layer2.setSrc(\"image_resources/layer2_sumer.png\")\n\t\t\t\t\tbackground.layer3.setSrc(\"image_resources/layer3_summer.png\")\n\t\t\t\t break;\n\t\t\t\tcase 'summer':\n\t\t\t\t this.areaSeason = 'fall';\n\t\t\t\t\tbackground.layer2.setSrc(\"image_resources/layer2_fall.png\")\n\t\t\t\t\tbackground.layer3.setSrc(\"image_resources/layer3_fall.png\")\n\t\t\t\t break;\n\t\t\t\tcase 'fall':\n\t\t\t\t this.areaSeason = 'winter'\n\t\t\t\t background.layer1.setSrc(\"image_resources/moun_snow.png\")\n\t\t\t\t\tbackground.layer2.setSrc(\"image_resources/layer2_winter.png\")\n\t\t\t\t\tbackground.layer3.setSrc(\"image_resources/layer3_winter.png\")\n\t\t\t\t break;\n\t\t\t\tcase 'winter': \n\t\t\t\t this.areaSeason = 'spring';\n\t\t\t\t background.layer1.setSrc(\"image_resources/mountain.png\")\n\t\t\t\t\tbackground.layer2.setSrc(\"image_resources/layer2_spring.png\")\n\t\t\t\t\tbackground.layer3.setSrc(\"image_resources/layer3_spring.png\")\n\t\t\t\t break;\n\t\t\t}\n\t\t}\n\t\tswitch(this.areaSeason){\n\t\t\t\tcase 'spring':\n\t\t\t\t if(this.areaLevel % 2 == 0){\n\t\t\t\t \tthis.usableEvents = badEventsSpringNight.slice();\n\t\t\t\t } else {\n\t\t\t\t \tthis.usableEvents = badEventsSpringDay.slice();\n\t\t\t\t }\n\t\t\t\t break;\n\t\t\t\tcase 'summer':\n\t\t\t\t if(this.areaLevel % 2 == 0){\n\t\t\t\t \tthis.usableEvents = badEventsSummerNight.slice();\n\t\t\t\t } else {\n\t\t\t\t \tthis.usableEvents = badEventsSummerDay.slice();\n\t\t\t\t }\n\t\t\t\t break;\n\t\t\t\tcase 'fall':\n\t\t\t\t if(this.areaLevel % 2 == 0){\n\t\t\t\t \tthis.usableEvents = badEventsFallNight.slice();\n\t\t\t\t } else {\n\t\t\t\t \tthis.usableEvents = badEventsFallDay.slice();\n\t\t\t\t }\n\t\t\t\t break;\n\t\t\t\tcase 'winter': \n\t\t\t\t if(this.areaLevel % 2 == 0){\n\t\t\t\t \tthis.usableEvents = badEventsWinterNight.slice();\n\t\t\t\t } else {\n\t\t\t\t \tthis.usableEvents = badEventsWinterDay.slice();\n\t\t\t\t }\n\t\t\t\t break;\n\t\t}\n\tvar cata = roll(2,0);\n\t//this.usableEvents.push(badEventsCatastrophe[cata]);\n\t}\n\t\n\tthis.areaLevelDown = function(){\n\t\tthis.area_level-=1;\n\t\tif(this.area_level % 10 == 0){\n\t\t\tswitch(this.areaSeason){\n\t\t\t\tcase 'spring':\n\t\t\t\t this.areaSeason = 'winter';\n\t\t\t\t break;\n\t\t\t\tcase 'summer':\n\t\t\t\t this.areaSeason = 'spring';\n\t\t\t\t break;\n\t\t\t\tcase 'fall':\n\t\t\t\t this.areaSeason = 'summer'\n\t\t\t\t break;\n\t\t\t\tcase 'winter': \n\t\t\t\t this.areaSeason = 'fall';\n\t\t\t\t break;\n\t\t\t}\n\t\t}\n\t\tswitch(this.areaSeason){\n\t\t\t\tcase 'spring':\n\t\t\t\t if(this.areaLevel % 2 == 0){\n\t\t\t\t \tthis.usableEvents = badEventsSpringNight.slice();\n\t\t\t\t } else {\n\t\t\t\t \tthis.usableEvents = badEventsSpringDay.slice();\n\t\t\t\t }\n\t\t\t\t break;\n\t\t\t\tcase 'summer':\n\t\t\t\t if(this.areaLevel % 2 == 0){\n\t\t\t\t \tthis.usableEvents = badEventsSummerNight.slice();\n\t\t\t\t } else {\n\t\t\t\t \tthis.usableEvents = badEventsSummerDay.slice();\n\t\t\t\t }\n\t\t\t\t break;\n\t\t\t\tcase 'fall':\n\t\t\t\t if(this.areaLevel % 2 == 0){\n\t\t\t\t \tthis.usableEvents = badEventsFallNight.slice();\n\t\t\t\t } else {\n\t\t\t\t \tthis.usableEvents = badEventsFallDay.slice();\n\t\t\t\t }\n\t\t\t\t break;\n\t\t\t\tcase 'winter': \n\t\t\t\t if(this.areaLevel % 2 == 0){\n\t\t\t\t \tthis.usableEvents = badEventsWinterNight.slice();\n\t\t\t\t } else {\n\t\t\t\t \tthis.usableEvents = badEventsWinterDay.slice();\n\t\t\t\t }\n\t\t\t\t break;\n\t\t}\n\tvar cata = roll(2,0);\n\tthis.usableEvents.push(badEventsCatastrophe[cata]);\n\t}\n\t\n\tthis.getBadEvents = function(){\n\t\treturn this.usableEvents;\n\t}\n\t\n\tthis.query = function(){\n\t\tfor(var i = 0; i < this.animals.length; i++){\n\t\t\tif(this.animals[i].canDie == true){\n\t\t\t\tif(Date.now() >= this.animals[i].deathTime){\n\t\t\t\t\tvar arr = this.animals[i].name.concat(\" died peacefully of old age.\")\n\t\t\t\t\teventLogAry.push(arr);\n\t\t\t\t\t//this.removeAnimal[i];\n\t\t\t\t\t//i--;\n\t\t\t\t\tthis.queueRemove(i);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tthis.removeAllQueue();\n\t\t\n\t\t\n\t}\n\t\n\tthis.baseLevelUp = function(animal){\n\t\tthis.base_levels[animal] += 1;\n\t}\n\t\n\tthis.levelUpAnimal = function(num){\n\t\tthis.animals[num].levelUp();\n\t}\n\t\n\tthis.partySizeUp = function(){\n\t\tthis.party_limit += 1;\n\t}\n\t\n\tthis.addAnimal = function(animal){\n\t\tif(this.animals.length < this.party_limit) {\n\t\t\tvar ani = new animalClass(animal);\n\t\t\t//console.log(animal);\n\t\t\tani.setLevel(this.base_levels[animal]);\n\n\t\t\tvar text = \"\";\n\n\t\t switch(ani.type) {\n \t\t\tcase \"frog\":\n \t\t\ttext = nameFrog();\n \t\t\tbreak;\n \t\t\tcase \"bunny\":\n \t\t\ttext = nameBunny();\n \t\t\tbreak;\n \t\tcase \"bird\":\n \t\t\ttext = nameBird();\n \t\t\tbreak;\n \t\tcase \"deer\":\n \t\t\ttext = nameDeer();\n \t\t\tbreak;\n \t\t\tdefault:\n \t\t\ttext = \"random name\";\n\t\t\t}\n\t\t \n\t\t \n\t\t ani.name= text;\n\t\t\tthis.animals.push(ani);\n\t\t\treturn true;\n\t\t} else {\n\t\t\treturn false;\n\t\t}\n \n\t}\n\t\n\tthis.queueRemove = function(index){\n\t\tthis.removalQ.push(index);\n\t}\n\t\n\tthis.removeAllQueue = function(){\n\t\tvar numInd = 0;\n\t\tfor(var i = 0; i < this.removalQ.length; i++){\n\t\t\tthis.removeAnimal(this.removalQ[i] - numInd);\n\t\t\tnumInd++;\n\t\t}\n\t\tthis.removalQ = [];\n\t}\n\t\n\tthis.removeAnimal = function(num){\n\t\tif(num < this.animals.length){\n\t\t\tthis.animals.splice(num,1);\n\t\t\treturn true;\n\t\t} else {\n\t\t\treturn false;\n\t\t}\n\t}\n\t\n\tthis.getAnimalData = function(){\n\t\tvar data = [];\n\t\tfor(var i = 0; i < this.animals.length; i++){\n\t\t\tvar dat = [];\n\n\t\t\tdat.push(this.animals[i].type)\n\t\t\tdat.push(this.animals[i].level)\n\t\t\tfor(var j = 0; j < 3; j++){\n\t\t\t\tvar stat = 1;\n\t\t\t\tfor(var k = 0; k < this.animals[i].level; k++){\n\t\t\t\t\tstat = Math.ceil(stat * animal_data[this.animals[i].type][j]);\n\t\t\t\t}\n\t\t\t\tdat.push(stat);\n\t\t\t}\n\t\t\tdat.push(this.animals[i].name)\n\t\t\tdata.push(dat);\n\t\t}\n\t\treturn data;\n\t}\n\n\tthis.getBaseData = function(animal) {\n var data = [];\n data.push(this.base_levels[animal]);\n for(var i = 0; i < 3; i++){\n var stat = 1;\n for(var k = 0; k < this.base_levels[animal]; k++){\n stat = Math.ceil(stat * animal_data[animal][i]);\n }\n data.push(stat);\n }\n return data;\n }\n\n\t\n\tthis.getAnimalBaseLevel = function(animal){\n\t\treturn this.base_levels[animal];\n\t}\n\t\n\tthis.getNumAnimals = function(){\n\t\treturn this.animals.length;\n\t\t\n\t}\n\t\n\t//get the amount of a certain animal\n\tthis.getAnimalCount = function(animal) {\n\t\tvar count = 0;\n\t\tfor (var a=0; a < this.getNumAnimals();a++ ) {\n\t\t\tif (this.animals[a].type == animal) count++;\n\t\t}\n\t\treturn count;\n\t}\n\n\tthis.update = function() {\n\t\tthis.timer++;\n\t\t//console.log(this.lifespans)\n\t\tif(this.timer == 15){\n\t\t\tthis.query();\n\t\t\tthis.timer = 0;\t\n\t\t}\t\n\t\t\n\t}\n\t\n\tthis.draw = function() {\n\n\t}\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get all the seminars
function getSeminars(req, res) { Seminar.find({},(err, Seminar) => { if (err) { res.send(err); } res.json(Seminar); }); }
[ "function retrieveStations() {\n stationsPromise = allStations()\n .then((stns) => {\n stations = stns;\n stationsPromise = null;\n return stns;\n });\n return stationsPromise;\n}", "static async listStations(req, res) {\n const stations = await Station.retrieve();\n return res.json(stations);\n }", "function orksAllStratagems() {\r\n return document.getElementById('orks').getElementsByClassName('orks-stratagem');\r\n}", "function get_all_sucursals(req, res) {\n var sucursal_list = DBController.getData(\"sucursals.json\");\n var sucursals = Object.keys(sucursal_list).map(sucursal_id => ({ \"sucursal_id\": sucursal_id, \"city\": sucursal_list[sucursal_id][\"city\"] }))\n res.send({ \"sucursals\": sucursals });\n}", "async getEmiSputteringSiteGroupList(ctx) {\n try {\n\n let { productTypeId = 1 } = ctx.request.query\n\n const result = await plasticService.getEmiSputteringSiteGroupList(productTypeId)\n ctx.body = result\n ctx.status = 200\n\n } catch (err) {\n logger.warn('error request for Database Plastic getEmiSputteringSiteGroupList function', err)\n throwApiError(err.message, err.status)\n }\n }", "function stationsCollection() {\n if (stations) {\n return Promise.resolve(stations);\n } else if (stationsPromise) {\n return stationsPromise;\n }\n\n return retrieveStations();\n}", "async function getVendors() {\n return Vendor.findAll()\n}", "async getAllSnowboards(req, res) {\n console.log(\"getAllSnowboards()\")\n\n const docs = await Snowboard.find({})\n\n if (docs) res.json(docs)\n else res.status(404).send(\"not found\")\n }", "function getAllStudents() {\n return __awaiter(this, void 0, void 0, function* () {\n try {\n return yield db_1.Student.findAll();\n }\n catch (err) {\n console.error(err);\n }\n });\n}", "function getAllStocks() {\n var deferred = $q.defer();\n $http.get(REST_SERVICE_URI + 'stocks')\n .then(\n function (response) {\n deferred.resolve(response.data);\n },\n function (err) {\n console.error('Error while fetching Stocks');\n deferred.reject(err);\n }\n );\n return deferred.promise;\n }", "get sets() {\n return TermSets(this, \"sets\");\n }", "function getPricingSchemesList() {\n $.get(\"api/pricing\", function(pricingSchemes) {\n console.log(pricingSchemes);\n });\n\n }", "get sets() {\n return TermSets(this);\n }", "async getProsumerList(){\n this.prosumerList = new Array()\n var role = AppSettings.database.roles.indexOf(\"prosumer\")\n var prosumers = await this.users.getWhere(\"id, name\", \"role=\"+role).then( (res) => {\n res.forEach(pro => {\n this.prosumerList.push(pro)\n });\n })\n }", "findAll() {\n return db.many(`\n SELECT parks.id, parks.name, parks.state, states.name AS state\n FROM parks\n JOIN states\n ON states.code = parks.state\n `);\n }", "getSelectedRegions() {\r\n const regions = this.lookupSelectedRegions().map((region) => {\r\n return {\r\n id: region.ID,\r\n regionData: region.regionData,\r\n };\r\n });\r\n return regions;\r\n }", "function getCompanySpecies() {\r\n return get('/companyspecies/getall').then(function (res) {\r\n return res.data;\r\n }).catch(function (err) {\r\n return err.response.data;\r\n });\r\n}", "function servicesList() {\n connection.query(\"SELECT * FROM servicesList\", function (err, results) {\n\n if (err) throw err;\n \n }\n\n )}", "function getCollectionSites() {\n\t\n\t\tvar querySites = new google.visualization.Query('http://spreadsheets.google.com/tq?key=0AiCvi3B8ANGfdFZwZjMybTAteHA5bFVPSjhBamVhN1E&pub=1');\n\t\t\n\t\t//if want to refresh query every minute...\n\t\t//querySites.setRefreshInterval(60);\n\n\t\t//selected each column in spreadsheet\n\t\tquerySites.setQuery('SELECT A, B, C, D');\n\t\tquerySites.send(responseHandler);\n\t\t\n\t\tfunction responseHandler(responseSites) {\n\t\t\tif (responseSites.isError()) {\n\t\t\t\t//console.log(responseSites);\n\t \t\t\t//alert('Error in query: ' + responseSites.getMessage() + ' ' + responseSites.getDetailedMessage());\n\t \t\t\treturn;\n\t\t\t}else{\n\t\t\t\t//set a local variable to store this crazy table data datatable\n\t\t\t\tvar data = responseSites.getDataTable();\n\n\t\t\t\t//sort the sites alphabetically by name (first column)\n\t\t\t\tdata.sort([{column: 0}]);\n\n\t\t\t\t//first for loop loops through each row in the table, effectively one site\n\t\t\t\tfor(var i=0; i<data.getNumberOfRows(); i++){\n\t\t\t\t\t\n\t\t\t\t\t//set up an object for each site, looks at columns in REQUIRED order from master collection site list spreadsheet\n\t\t\t\t\tvar site = {\n\t\t\t\t\t\tname: data.getFormattedValue(i, 0),\n\t\t\t\t\t\tlat: data.getFormattedValue(i, 1),\n\t\t\t\t\t\tlong: data.getFormattedValue(i, 2),\n\t\t\t\t\t\tkey: data.getFormattedValue(i, 3)\n\t\t\t\t\t}\n\n\t\t\t\t\tsites.push(site);\n\t\t\t\t}\n\n\t\t\t\t//now that we have all the site data, let's make buttons and load a map\n\t\t\t\tgenerateRadioButtons();\n\t\t\t\tloadMapScript();\n\t\t\t}\t\t\n\t\t}\t\n\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Executes a MySQL query to insert a new assignment into the database. Returns a Promise that resolves to the ID of the newlycreated assignment entry.
function insertNewAssignment(assignment) { return new Promise((resolve, reject) => { assignment = extractValidFields(assignment, AssignmentSchema); assignment.id = null; mysqlPool.query( 'INSERT INTO assignments SET ?', assignment, (err, result) => { if (err) { reject(err); } else { resolve(result.insertId); } } ); }); }
[ "async insertNewTask(task){\r\n try {\r\n const insertId = await new Promise((resolve, reject) => {\r\n const query = \"INSERT INTO task (Title, List_ID, Done, Task_Date) VALUES (?,?,?,?)\";\r\n\r\n connection.query(query, [task.Title, task.ListID, task.Done, task.TaskDate], (err, result) => {\r\n if(err) reject(new Error(err.message))\r\n resolve(result.insertId);\r\n })\r\n });\r\n\r\n return {\r\n id: insertId,\r\n title: task.Title,\r\n ListID: task.ListID,\r\n Done: task.Done,\r\n TaskDate: task.TaskDate\r\n };\r\n }catch (error){\r\n console.log(error)\r\n }\r\n }", "function createAssignment(classID, assignObj) {\n // Clean and verify input\n // console.log(`[LOG] assignment-db: ${JSON.stringify(assignObj, null, 2)}`)\n if (isNaN(assignObj.expires) || assignObj.expires < 0){\n return new Promise((res, rej) => {res(null)});\n }\n if (isNaN(assignObj.workload) || assignObj.workload < 0) {\n return new Promise((res, rej) => {res(null)});\n }\n assignObj.expires = parseInt(assignObj.expires);\n assignObj.workload = parseInt(assignObj.workload);\n assignObj.created = Math.floor(Date.now()/1000);\n // Valid input, create doc\n let assignRef = db.collection('classes').doc(classID).collection('assignments');\n let addDoc = assignRef.add(assignObj);\n return addDoc;\n}", "async function insertNewArtist(artist) {\n artist = extractValidFields(artist, ArtistSchema);\n const [ result ] = await mysqlPool.query(\n 'INSERT INTO artist SET ?',\n artist\n );\n\n return result.insertId;\n}", "async insert() {\n const { rows } = await db.query(`SELECT * FROM new_perfume($1);`, [this]); \n this.id = rows[0].id;\n }", "async function insertNewOrder(order) {\n order = extractValidFields(order, OrderSchema);\n const [ result ] = await mysqlPool.query(\n 'INSERT INTO orders SET ?',\n order\n );\n return result.insertId;\n}", "function create_experiment(err, client, done, req, res) {\n if(err) {\n return console.error('error fetching client from pool', err);\n }\n var reqArr = [req.query.envSide, req.query.envSize, req.query.duration, req.query.startFood, req.query.maxFood];\n client\n .query('INSERT INTO \"ACSchema\".\"Experiment\"(\"Env_Side\", \"Env_Size\", \"SIM_Duration\", \"Start_Ant_Food\", \"Max_Ant_Food\")VALUES ($1, $2, $3, $4, $5) RETURNING \"Exp_ID\"',\n reqArr,\n function(err, result) {\n done();\n if(err) {\n res.send('error running query');\n return console.error('error running query', err);\n } else {\n console.log(result.rows);\n res.json(result.rows[0].Exp_ID);\n }\n });\n}", "function saveSubmission (req) {\n //open DB connection\n const pool = db.connection.INSTANCE();\n \n var name = [req.body.email];\n var sql = \"INSERT INTO tokenswap(email) VALUES($1)\";\n //Save to DB and close connection\n pool.query(sql, name, (err, res) => {\n console.log(err, res);\n });\n return;\n}", "function create_entity(err, client, done, req, res) {\n if(err) {\n return console.error('error fetching client from pool', err);\n }\n var reqArr = [req.query.genBorn, req.query.genDied];\n client\n .query('INSERT INTO \"ACSchema\".\"Entity\"( \"Gen_Born\", \"Gen_Died\") VALUES ($1, $2) RETURNING \"Ant_ID\"',\n reqArr,\n function(err, result) {\n done();\n if(err) {\n res.send('error running query');\n return console.error('error running query', err);\n } else {\n console.log(result.rows);\n res.json(result.rows[0].Ant_ID);\n }\n });\n}", "insert(task, date, process) {\n let sql = `\n INSERT INTO tasks(task, date, process)\n VALUES (?, ?, ?)\n `;\n return this.dao.run(sql, [task, date, process]);\n }", "insertWorkout(knex, newWorkout) {\n return knex\n .insert(newWorkout)\n .into(\"workouts\")\n .returning(\"*\")\n .then((rows) => {\n return rows[0];\n });\n }", "async function insertNewLike(like) {\n like = extractValidFields(like, LikeSchema);\n console.log(\"v!!! \", like);\n const [result] = await mysqlPool.query(\"INSERT INTO likes SET ?\", like);\n\n return result.insertId;\n}", "function create_generation(err, client, done, req, res) {\n if(err) {\n return console.error('error fetching client from pool', err);\n }\n var reqArr = [req.query.expID, req.query.parents, req.query.envs, req.query.genCM];\n console.log(req.query);\n client\n .query('INSERT INTO \"ACSchema\".\"Generation\"( \"Exp_ID\", \"Parents\", \"Environments\", \"Gen_CM\") VALUES ($1, $2, $3, $4) RETURNING \"Gen_ID\"',\n reqArr,\n function(err, result) {\n done();\n if(err) {\n res.send('error running query' + err.detail);\n return console.error('error running query', err);\n } else {\n console.log(result.rows);\n res.json(result.rows[0].Gen_ID);\n }\n });\n}", "async function addSchedule(ctx) {\n const { usernamect, availdate} = ctx.params;\n try {\n const sqlQuery = `INSERT INTO parttime_schedules VALUES ('${usernamect}', '${availdate}')`;\n await pool.query(sqlQuery);\n ctx.body = {\n 'username_caretaker': usernamect,\n 'availdate': availdate\n };\n } catch (e) {\n console.log(e);\n ctx.status = 403;\n }\n}", "function addAction(action) {\n return db('actions')\n .insert(action)\n .then(ids => ({id: ids[0]}));\n}", "async insert (entry) {\n try {\n console.log('entry: ', entry)\n\n // Add the entry to the Oribit DB.\n const hash = await _this.orbit.db.put(entry.key, entry.value)\n console.log('hash: ', hash)\n\n return hash\n } catch (err) {\n console.error('Error in p2wdb.js/insert()')\n throw err\n }\n }", "async function addNewMatch(date, hour, host_team, away_team,\n league_id, season_id, stage_id, stadium) {\n await DButils.execQuery(\n `INSERT INTO dbo.Matches (date,hour,host_team,away_team,league_id, season_id,\n stage_id,stadium)\n VALUES ('${date}','${hour}','${host_team}','${away_team}',\n '${league_id}','${season_id}',\n '${stage_id}','${stadium}');`\n );\n}", "reserve(attraction, account_id, num_people, res_time, res_date) {\n //console.log(\"RESERVINg\");\n let sql = \"INSERT INTO reservations(attractionRideName, numPeople, time, date, user) VALUES ($attraction, $num_people, $time, $date, $user)\";\n this.db.run(sql, {\n $attraction: attraction,\n $num_people: num_people,\n $time: res_time,\n $date: res_date,\n $user: account_id,\n }, (err) => {\n if(err) {\n throw(err);\n }\n });\n }", "function insertEmail (email,callback){\n console.log('insertEmail: ' + email);\n db.connect(function(error){\n if (error){\n return console.log('CONNECTION error: ' + error);\n }\n this.query().insert('emails', ['email'], [email] )\n .execute(function(error, result) {\n if (error) {\n return console.log('ERROR: ' + error);\n }\n console.log('GENERATED id: ' + result.id);\n callback(result);\n })\n });\n}", "function createChiefComplaintEntry(){\r\n\tdb.transaction(\r\n\t\tfunction(transaction) {\r\n\t\t\ttransaction.executeSql(\r\n\t\t\t\t'INSERT INTO chief_complaint (patient, assessed, primary_complaint, primary_other, secondary_complaint, diff_breathing, chest_pain, nausea, vomiting, diarrhea, dizziness, ' +\r\n\t\t\t\t' headache, loc, numb_tingling, gal_weakness, lethargy, neck_pain, time) ' +\r\n\t\t\t\t' VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);', \r\n\t\t\t\t[getCurrentPatientId(), 'false', '0', '', '', '', '', '', '', '', '', '', '', '', '', '', '', getSystemTime()], \r\n\t\t\t\tnull,\r\n\t\t\t\terrorHandler\r\n\t\t\t);\r\n\t\t}\r\n\t);\r\n}", "function create(band_id, tour_date, venue_id) {\n return db.one(`INSERT INTO tours (band_id, tour_date, venue_id) VALUES ($1,$2,$3) RETURNING *`, [band_id, tour_date, venue_id]);\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Handler for Earth's frameend event.
function frameend() { shuttle.update(); }
[ "function endCallback() {\n logger.log('[whois][' + session.getID() + '] whois server connection ended');\n session.clientEnd();\n }", "function endCallback() {\n endIANA(session);\n }", "function video_done(e) {\n\tthis.currentTime = 0;\n}", "function onSocketEnd() {\n // XXX Should not have to do as much crap in this function.\n // ended should already be true, since this is called *after*\n // the EOF errno and onread has eof'ed\n this._readableState.ended = true;\n if (this._readableState.endEmitted) {\n this.readable = false;\n maybeDestroy(this);\n } else {\n this.once('end', function() {\n this.readable = false;\n maybeDestroy(this);\n });\n this.read(0);\n }\n\n if (!this.allowHalfOpen) {\n this.write = writeAfterFIN;\n this.destroySoon();\n }\n}", "function mapStopped(){\n\t\t\tclearInterval(service.intervalHandle);\n\n\t\t\t// TODO fire off our event?\n\t\t\t//service.bounds.extent;\n\n\t\t\tconsole.log(\"stopped\");\n\t\t}", "handleNewFrame(this_frame) {\n //this.log.debug('handleNewFrame', this_frame);\n switch (this_frame.command) {\n case \"MESSAGE\":\n if (this.isMessage(this_frame)) {\n /*this.log.debug('MESSAGE');\n this.log.debug(util.inspect(this_frame));*/\n this.shouldRunMessageCallback(this_frame);\n this.emit('message', this_frame);\n }\n break;\n case \"CONNECTED\":\n this.log.debug('Connected to STOMP');\n this.session = this_frame.headers.session;\n\n const serverHeartBeat = this.parseServerHeartBeat(this_frame.headers);\n\n const timeout = serverHeartBeat * this.waitHeartbeatsNumber;\n //parse heart beats\n if (timeout) {\n this.log.debug('Adjust socket timeout using server heart-beat:');\n this.log.debug(timeout);\n this.setSocketTimeout(timeout);\n }\n\n this.emit('connected');\n break;\n case \"RECEIPT\":\n this.emit('receipt', this_frame.headers['receipt-id']);\n break;\n case \"ERROR\":\n const isErrorFrame = true;\n this.emit('error', this_frame, isErrorFrame);\n break;\n default:\n this.log.debug(\"Could not parse command: \" + this_frame.command);\n }\n }", "function pjaxloadEndCallback() {\n $('.pjaxContents').on(TML.data.eventHandler['transitionEnd'], function () {\n resizeEvent();\n });\n }", "onAnimationEnd() {\n return null;\n }", "frame () {\n\t\t// This is to call the parent class's delete method\n\t\tsuper.frame();\n\n\t\tif (this.state === 'swinging') this.swing();\n\t\telse if (this.state === 'pulling' && this.shouldStopPulling()) this.stopPulling();\n\t\telse if (this.state === 'pulling' && this.shouldRemoveLastChain()) this.removeLastChain();\n\t\telse if (this.state === 'throwing' && this.shouldGenerateAnotherChain()) this.generateChain();\n\n\t\tif (this.hookedObject) {\n\t\t\t// Updates the hooked object's position to follow the hook at every frame.\n\t\t\tthis.hookedObject.position = this.position.add(this.hookedObject.offset);\n\t\t}\n\t}", "function end() {\n this._end();\n log(\n new Date().toISOString(),\n this.req.method,\n this.req.url,\n this.statusCode,\n http.STATUS_CODES[this.statusCode],\n this.logType,\n this.logLength\n );\n}", "function sendInfoFrameToUpperLayer(receivedFrame) {\n // Sending the frame to upper layer for further processing\n //log(\"Receiver: Upper layer received - \" + receivedFrame.text());\n}", "theEnd() {\n\t\t// quest end phases\n\t\tfor(let quest of this.prioritizedQuestList) {\n\t\t\ttry {\n\t\t\t\tquest.questEnd();\n\t\t\t} catch(e) {\n\t\t\t\tLogger.errorLog(\"error caught in quest end phase, colony:\" + this.name + \", quest:\" + quest.nameId, ERR_TIRED, 5);\n\t\t\t\tLogger.log(e.stack, 5);\n\t\t\t}\n\t\t}\n\n\t\ttry {\n\t\t\tthis.colonyEnd();\n\t\t} catch(e) {\n\t\t\tLogger.errorLog(\"error caught in end colony phase, colony:\" + this.name, ERR_TIRED, 5);\n\t\t\tLogger.log(e.stack, 5);\n\t\t}\n }", "function resizeend() {\n if (new Date() - rtime < delta) {\n setTimeout(resizeend, delta);\n } else {\n timeout = false;\n\t\talreadyDone = false;\n\t\tdoMobileStuff();\n } \n}", "function contentEndedListener() {\n adsLoader.contentComplete();\n}", "function returnToEarth(){\n\tnavigation.x = parseInt(decodeMessage(broadcast(\"x\")),16);\n\tnavigation.y = parseInt(decodeMessage(broadcast(\"y\")),16);\n\tnavigation.z = parseInt(decodeMessage(broadcast(\"z\")),16);\n}", "gameEnd() {\n\t\tthis.gameDataList.push(this.curGameData);\n\t\tthis.curGameData = null;\n this.fitness = null;\n\t}", "async afterBrowserStopped() {}", "function end_game(){\n\tsocket.emit(\"leave_game\");\n}", "handleBreakClipEnded(event) {\n let data = {};\n data.id = this.breakClipId;\n this.breakClipStarted = false;\n this.breakClipLength = null;\n this.breakClipId = null;\n this.qt1 = null;\n this.qt2 = null;\n this.qt3 = null;\n\n data.action = event.endedReason;\n this.sendData(data);\n }", "function uploadDone(name, myRId) {\r\n var frame = frames[name];\r\n if (frame) {\r\n var ret = frame.document.getElementsByTagName(\"body\")[0].innerHTML;\r\n if (ret.length) {\r\n alert(ret);\r\n frame.document.getElementsByTagName(\"body\")[0].innerHTML = \"\";\r\n showRecordView(myRId);\r\n }\r\n }\r\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
return the path where to store the qr images
function getQrImagePathToSave() { return path.join(__dirname,'../../../client/qr-images/'); }
[ "function getImagePath(source){\n\tvar urlPath = url.parse(source).path;\n\tvar lastPath = _.last(urlPath.split(\"/\"));\n\tvar savePath = ORGINAL_IMAGE_PATH + lastPath;\n\treturn savePath;\n}", "function pngPath(size) {\n\t\treturn path.join(cacheDir, baseName + '-' + size + '.png')\n\t}", "function findcardimg(card){\r\n var cardname = card.join(\"\");\r\n return \"img/cards/\" + cardname + \".png\";\r\n }", "function imagePath(item_id, image_index, sold) {\n item_id = ITEM_TO_MASTER_ID_MAP[item_id];\n var path_str = \"\";\n var outlet_code = process.env.OUTLET_CODE\n if (fs.existsSync(source_folder + '/' + outlet_code + '/menu_items/' + item_id)) {\n path_str = source_folder + '/' + outlet_code + '/menu_items/' + item_id;\n } else {\n path_str = source_folder + '/' + item_id;\n }\n var sold_suffix = '';\n if (sold) {\n sold_suffix = '_sold';\n }\n path_str += '/{}{}.png'.format(image_index, sold_suffix);\n return path_str;\n}", "function getFilePath() {\n let lastExecCommand = execSync('tail ' + getHistoryPath() + ' | grep imgcat | tail -n 1').toString();\n let home = execSync('echo $HOME | tr -d \"\\n\"').toString() + '/';\n let commands = lastExecCommand.split('imgcat');\n let absolutePath = commands.pop().replace('~/', home);\n return absolutePath;\n}", "function getFilePath(fileName) {\n return os.userInfo().homedir + \"\\\\AppData\\\\Roaming\\\\.minecraft\\\\mcpipy\\\\\" + fileName + \".py\";\n}", "function imageFolder(device, icon) {\n\tvar sep = air.File.separator;\n\tvar str;\n\tif(device == \"android\") {\n\t\tif(icon) {\n\t\t\tstr = (icon == 1) ? sep + 'res' + sep + 'drawable-ldpi' + sep :\n\t\t\t\t (icon == 2) ? sep + 'res' + sep + 'drawable-hdpi' + sep :\n\t\t\t\t \t\t\t\tsep + 'res' + sep + 'drawable-mdpi' + sep;\n\t\t} else\n\t\t\tstr = sep + 'assets' + sep + 'www' + sep + 'img' + sep + 'menu' + sep;\n\t}\n\telse\n\t\tif(icon) {\n\t\t\tstr = sep + 'images' + sep;\t\n\t\t} else {\n\t\t\tstr = sep + 'www' + sep + 'img' + sep + 'menu' + sep;\n\t\t}\n\treturn str;\t\n}", "write(contents,width,height,hints){if(contents.length===0){throw new IllegalArgumentException('Found empty contents');}// if (format != BarcodeFormat.QR_CODE) {\n// throw new IllegalArgumentException(\"Can only encode QR_CODE, but got \" + format)\n// }\nif(width<0||height<0){throw new IllegalArgumentException('Requested dimensions are too small: '+width+'x'+height);}let errorCorrectionLevel=ErrorCorrectionLevel.L;let quietZone=BrowserQRCodeSvgWriter.QUIET_ZONE_SIZE;if(hints){if(undefined!==hints.get(EncodeHintType$1.ERROR_CORRECTION)){const correctionStr=hints.get(EncodeHintType$1.ERROR_CORRECTION).toString();errorCorrectionLevel=ErrorCorrectionLevel.fromString(correctionStr);}if(undefined!==hints.get(EncodeHintType$1.MARGIN)){quietZone=Number.parseInt(hints.get(EncodeHintType$1.MARGIN).toString(),10);}}const code=Encoder.encode(contents,errorCorrectionLevel,hints);return this.renderResult(code,width,height,quietZone);}", "get icon_path() {\n return this.args.icon_path;\n }", "getPathCsvUrlsFile() {\n return (0, _path.join)(this.getUrlsPath(), \"urls.csv\");\n }", "static smallImageUrlForRestaurant(restaurant) {\r\n return (`/img/small/${restaurant.photograph}.jpg`);\r\n }", "saveToPNG() {\n this.downloadEl.download = 'pattar.png';\n this.downloadEl.href = this.renderCanvas.toDataURL(\"image/png\").replace(\"image/png\", \"image/octet-stream\");\n this.downloadEl.click();\n }", "function saveImage() {\n var data = canvas.toDataURL();\n $(\"#url\").val(data);\n }", "static imageSrcUrlForRestaurant(restaurant) {\r\n return (`/img2/${restaurant.id}` + `-300_small.webp`);\r\n }", "function saveLastDrawing() {\n lastImage.src = canvas.toDataURL('image/png');\n }", "function getCacheLocation() {\n if (cacheLocation == undefined || cacheLocation == \"default\")\n return \"./cache/\"\n\n return cacheLocation\n}", "getPaths(projectName, imagesCount) {\n const srcsetWidths = [320, 480, 640, 960, 1280];\n const fallbackWidth = 640;\n\n let imagesPaths = [];\n\n // This would build the images path for how they appear in the folder\n // The assumption is that the cloudinary folder contains images that are sequenced\n // the way we want them. And, that they share the same name as the folder they are placed\n // in\n for (i = 1; i < imagesCount + 1; i++) {\n imagesPaths.push(`${projectName}\\/${projectName}-${i}`);\n }\n\n // We grab and set the srcset widths for all the images we want to show\n const finalPaths = [];\n imagesPaths.forEach((path) => {\n const fetchBase = `https://res.cloudinary.com/yesh/image/upload/`;\n const src = `${fetchBase}q_auto,f_auto,w_${fallbackWidth}/${path}.jpg`;\n\n const srcset = srcsetWidths\n .map((w) => {\n return `${fetchBase}q_auto:eco,f_auto,w_${w}/${path}.jpg ${w}w`;\n })\n .join(', ');\n finalPaths.push(\n `<img src=\"${src}\" srcset=\"${srcset}\" sizes=\"(max-width: 400px) 320px, 480px\" alt=\"images for project ${projectName}\">`\n );\n });\n\n return finalPaths;\n }", "function exportImages() {\n let frontImage = frontCanvas.toDataURL({format: 'jpeg'});\n let backImage = backCanvas.toDataURL({format: 'jpeg'});\n\n clearGuides();\n\n console.log('Exporting canvases as images...');\n\n // return front and back images\n return(\n {\n 'front' : frontImage,\n 'back': backImage\n }\n )\n}", "toSVG(opt) {\n const options = { ...this.options, ...opt };\n const {\n width,\n height,\n padding,\n color,\n background,\n container,\n xmlDeclaration,\n pretty,\n join,\n swap,\n predefined,\n } = options;\n\n const { modules } = this.qrcode;\n const { length } = modules;\n const indent = pretty ? ' ' : '';\n const eol = pretty ? '\\r\\n' : '';\n const xsize = width / (length + 2 * padding);\n const ysize = height / (length + 2 * padding);\n const defs = predefined ? `${indent}<defs><path id=\"qrmodule\" d=\"M0 0 h${ysize} v${xsize} H0 z\" fill=\"${color}\" shape-rendering=\"crispEdges\"/></defs>${eol}` : '';\n // Background rectangle\n const bgrect = `${indent}<rect x=\"0\" y=\"0\" width=\"${width}\" height=\"${height}\" fill=\"${background}\" shape-rendering=\"crispEdges\"/>${eol}`;\n\n // Rectangles representing modules\n let modrect = '';\n let pathdata = '';\n\n for (let y = 0; y < length; y++) {\n for (let x = 0; x < length; x++) {\n if (modules[x][y]) {\n let px = round(x * xsize + padding * xsize);\n let py = round(y * ysize + padding * ysize);\n\n // Some users have had issues with the QR Code, thanks to @danioso for the solution\n if (swap) {\n [px, py] = [py, px];\n }\n\n if (join) {\n // Module as a part of svg path data, thanks to @danioso\n const w = round(xsize + px);\n const h = round(ysize + py);\n\n pathdata += `M${px},${py} V${h} H${w} V${py} H${px} Z `;\n } else if (predefined) {\n // Module as a predefined shape, thanks to @kkocdko\n modrect += `${indent}<use x=\"${px}\" y=\"${py}\" href=\"#qrmodule\"/>${eol}`;\n } else {\n // Module as rectangle element\n modrect += `${indent}<rect x=\"${px}\" y=\"${py}\" width=\"${xsize}\" height=\"${ysize}\" fill=\"${color}\" shape-rendering=\"crispEdges\"/>${eol}`;\n }\n }\n }\n }\n\n if (join) modrect = `${indent}<path x=\"0\" y=\"0\" fill=\"${color}\" shape-rendering=\"crispEdges\" d=\"${pathdata}\"/>${eol}`;\n\n const rect = defs + bgrect + modrect;\n\n let svg = '';\n let box = `width=\"${width}\" height=\"${height}\"`;\n if (container === 'viewbox') box = `viewBox=\"0 0 ${width} ${height}\"`;\n\n if (['svg', 'viewbox'].includes(container)) {\n // Wrapped in SVG document\n // or viewbox for responsive use in a browser, thanks to @danioso\n if (xmlDeclaration) svg += `<?xml version=\"1.0\" standalone=\"yes\"?>${eol}`;\n svg += `<svg xmlns=\"http://www.w3.org/2000/svg\" version=\"1.1\" ${box}>${eol}${rect}</svg>`;\n } else if (container === 'g') {\n // Wrapped in group element\n svg += `<g ${box}>${eol}${rect}</g>`;\n } else {\n // Without a container\n svg += rect.replace(/^\\s+/, ''); // Clear indents on each line\n }\n\n return svg;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
add message node before passed second node or to beginning
_addMessageNode(messageNode, nextNode = null) { if (nextNode) { this.container.insertBefore(messageNode, nextNode); } else if (this.left > 0) { this.container.insertBefore(messageNode, this.buttonLoadMore); } else { this.container.appendChild(messageNode); } }
[ "function insertAboveConversation(node) {\n let threadNode = document.getElementById('discussion_bucket');\n threadNode.parentNode.insertBefore(node, threadNode);\n}", "function bringNodeToFront(p) {\n\tlet i, j;\n\tp.selection.bringToFront();\n\tfor (i = 0; i < p.channels.length; ++i) {\n\t\tfor (j = 1; j < p.channels[i].parts.length; ++j)\n\t\t\tp.channels[i].parts[j].bringToFront();\n\t\tp.channels[i].node1.bringToFront();\n\t\tp.channels[i].node2.bringToFront()\n\t}\n\tp.label.bringToFront();\n\tif (p.delete)\n\t\tp.delete.bringToFront();\n\tif (p.split)\n\t\tp.split.bringToFront()\n}", "_insertAsFirstChild(element, referenceElement) {\n referenceElement.parentElement.insertBefore(element, referenceElement);\n // bump up element above nodes which are not element nodes (if any)\n while (element.previousSibling) {\n element.parentElement.insertBefore(element, element.previousSibling);\n }\n }", "insertBefore(node) {\n\n // Checks if argument is a node:\n if (node instanceof YngwieNode) {\n\n // Set relations\n node._prev = this._prev;\n node._next = this;\n node._parent = this._parent;\n\n // Set previous sibling relations:\n if (this._prev) {\n this._prev._next = node;\n } else {\n if (this._parent) {\n this._parent._first = node;\n }\n }\n\n // Set previous sibling:\n this._prev = node;\n\n return this;\n\n }\n\n throw new _Error_main_js__WEBPACK_IMPORTED_MODULE_0__.default(\"Can only insert a YngwieNode before other YngwieNodes\", node);\n\n }", "addBefore(key, data) {\n if (this.head == null) return;\n \n let currentNode = this.head;\n let prevNode = null;\n\n while (currentNode != null && currentNode.data != key) {\n prevNode = currentNode;\n currentNode = currentNode.next;\n }\n\n if (currentNode) {\n let tempNode = new Node(data);\n tempNode.next = currentNode;\n if (prevNode) {\n prevNode.next = tempNode;\n } else {\n this.head = tempNode;\n }\n return;\n }\n }", "prependData(target, data){\n var node = new DLLNode(data);\n var runner = this.head;\n while(runner){\n if(runner === target){\n node.next = runner;\n node.prev = runner.prev;\n runner.prev.next = node;\n runner.prev = node;\n this.length++;\n if(runner === this.head){\n this.head = node;\n }\n }else{\n runner = runner.next;\n }\n }\n }", "function insertBefore(newNode, referenceNode){\n referenceNode.parentNode.insertBefore(newNode, referenceNode);\n}", "function add(node, parent) {\n var children = parent ? parent.children : tokens;\n var prev = children[children.length - 1];\n\n if (\n prev &&\n node.type === prev.type &&\n node.type in MERGEABLE_NODES &&\n mergeable(prev) &&\n mergeable(node)\n ) {\n node = MERGEABLE_NODES[node.type].call(self, prev, node);\n }\n\n if (node !== prev) {\n children.push(node);\n }\n\n if (self.atStart && tokens.length !== 0) {\n self.exitStart();\n }\n\n return node;\n }", "insertMessage(message) {\n pushSorted(this.messages, message, (a, b) => a.date - b.date);\n }", "isPreceding(node) {\n var nodePos, thisPos;\n nodePos = this.treePosition(node);\n thisPos = this.treePosition(this);\n if (nodePos === -1 || thisPos === -1) {\n return false;\n } else {\n return nodePos < thisPos;\n }\n }", "prependDataBeforeVal(val, data){\n var node = new DLLNode(data);\n var runner = this.head;\n while(runner){\n if(runner.data === val){\n node.next = runner;\n node.prev = runner.prev;\n runner.prev.next = node;\n runner.prev = node;\n this.length++;\n if(runner === this.head){\n this.head = node;\n }\n }else{\n runner = runner.next;\n }\n }\n }", "function moveNodeForNew(node) {\n // when create new box dom, move pass to 150 right\n var first_sub_node_x = getFirstSubNodePosition(node).x;\n // move each node position\n // add paret node, then sub node change position\n // add sub node, then parent node do not change position\n $('g[data-object-id=\"'+node.parent_id+'\"]>use').each(function(index_g, element_g){\n var x = first_sub_node_x + index_g * 150;\n $(element_g).attr(\"x\", x);\n });\n $('g[data-object-id=\"'+node.parent_id+'\"]>text').each(function(index_g, element_g){\n var x = first_sub_node_x + index_g * 150;\n $(element_g).attr(\"x\", x+30);\n });\n $('g[data-object-id=\"'+node.parent_id+'\"]>line').each(function(index_g, element_g){\n var x = first_sub_node_x + index_g * 150;\n $(element_g).attr(\"x2\", x+50);\n });\n // moving px\n var px = 0;\n $('use[data-object-id=\"'+node.object_id+'\"]').parent().find('g').children('use').each(function(index_g, element_g){\n var x = parseInt($(element_g).attr(\"x\"));\n px = x - parseInt($(element_g).attr(\"x\"));\n $(element_g).attr(\"x\", x-75);\n });\n $('use[data-object-id=\"'+node.object_id+'\"]').parent().find('g').children('text').each(function(index_g, element_g){\n var x = parseInt($(element_g).attr(\"x\"));\n $(element_g).attr(\"x\", x-75);\n });\n $('use[data-object-id=\"'+node.object_id+'\"]').parent().find('g').children('line').each(function(index_g, element_g){\n var x1 = parseInt($(element_g).attr(\"x1\"));\n var x2 = parseInt($(element_g).attr(\"x2\"));\n $(element_g).attr(\"x1\", x1-75);\n $(element_g).attr(\"x2\", x2-75);\n });\n }", "function showNodeOrMessage() {\n var update = false;\n status.collection.forEach(function (item) {\n if (item.get(\"id\") === newNode.get(\"id\")) {\n item.set(newNode.attributes);\n update = true;\n }\n });\n if (!update) {\n var folder_id = status.collection.node.get('id'),\n parent_id = newNode.get('parent_id'),\n sub_folder_id = newNode.get('sub_folder_id');\n if (folder_id === parent_id || folder_id === -parent_id) {\n status.collection.add(newNode, {at: 0});\n } else {\n if ( folder_id !== sub_folder_id && sub_folder_id !== 0 ) { //CWS-5155\n var sub_folder = new NodeModel( {id: sub_folder_id }, { connector: status.container.connector, collection: status.collection });\n sub_folder.fetch( { success: function () {\n if ( sub_folder.get('parent_id') === folder_id ) {\n if (status.collection.findWhere({id: sub_folder.get(\"id\")}) === undefined) {\n sub_folder.isLocallyCreated = true;\n status.collection.add(sub_folder, {at: 0});\n }\n }\n // as the workspace got created at different place\n // show message after subFolder added to the nodes table\n successWithLinkMessage();\n }, error: function(err) {\n ModalAlert.showError(lang.ErrorAddingSubfolderToNodesTable);\n successWithLinkMessage();\n }});\n } else {\n // simply show message If the workspace got created\n // in target location (XYZ folder) but created from (ABC folder)\n successWithLinkMessage();\n }\n }\n }\n }", "function orderHeaders(newChild, currentNodeRef, headerOrder, title, counter) {\n currentNodeRef = newChild;\n for (let x = 2; x <= headerOrder; x++) {\n if (x != headerOrder) {\n if (currentNodeRef.children.length == 0) {\n currentNodeRef.children.push(new treeNode());\n currentNodeRef.children[0].order = x;\n }\n currentNodeRef = currentNodeRef.children[currentNodeRef.children.length - 1];\n }\n else {\n currentNodeRef.children.push(new treeNode(title.trim(), false, counter.counter, x, []))\n break;\n }\n }\n}", "function assert_previous_nodes(aNodeType, aStart, aNum) {\n let node = aStart;\n for (let i = 0; i < aNum; ++i) {\n node = node.previousSibling;\n if (node.localName != aNodeType)\n throw new Error(\"The node should be preceded by \" + aNum + \" nodes of \" +\n \"type \" + aNodeType);\n }\n return node;\n}", "_createMessageNode({author, time, body}) {\n // header of item\n var header = document.createElement(\"header\");\n header.className = \"list-group-item-heading\";\n header.innerHTML = `<strong>${myEscape(author)}</strong> <i class=\"text-muted\">${time}</i>`;\n // body of message\n var content = document.createElement(\"p\");\n content.className = \"list-group-item-text\";\n content.innerHTML = smilify(myEscape(body).replace(/\\n/g, \"<br>\"));\n // node o message\n var node = document.createElement(\"li\");\n node.className = \"list-group-item\";\n node.appendChild(header);\n node.appendChild(content);\n return node;\n }", "function insert_elt_after(new_elt, old_elt){\n old_elt.parentNode.insertBefore(new_elt, old_elt.nextSibling);\n}", "static async insert(newMessage) {\n let messageData = await Message.read();\n messageData = messageData || {};\n let history = messageData.history ? messageData.history : [];\n history.push(newMessage);\n\n messageData.history = history;\n\n return Storage.write(Message.NAMESPACE, messageData);\n }", "function emitTagAndPreviousTextNode() {\n var textBeforeTag = html.slice(currentDataIdx, currentTag.idx);\n if (textBeforeTag) {\n // the html tag was the first element in the html string, or two\n // tags next to each other, in which case we should not emit a text\n // node\n onText(textBeforeTag, currentDataIdx);\n }\n if (currentTag.type === 'comment') {\n onComment(currentTag.idx);\n }\n else if (currentTag.type === 'doctype') {\n onDoctype(currentTag.idx);\n }\n else {\n if (currentTag.isOpening) {\n onOpenTag(currentTag.name, currentTag.idx);\n }\n if (currentTag.isClosing) {\n // note: self-closing tags will emit both opening and closing\n onCloseTag(currentTag.name, currentTag.idx);\n }\n }\n // Since we just emitted a tag, reset to the data state for the next char\n resetToDataState();\n currentDataIdx = charIdx + 1;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Makes sure the table representing the PeerConnection event log is created and appended to peerConnectionElement.
function ensurePeerConnectionLog(peerConnectionElement) { var logId = peerConnectionElement.id + '-log'; var logElement = $(logId); if (!logElement) { var container = document.createElement('div'); container.className = 'log-container'; peerConnectionElement.appendChild(container); logElement = document.createElement('table'); logElement.id = logId; logElement.className = 'log-table'; logElement.border = 1; container.appendChild(logElement); logElement.innerHTML = '<tr><th>Time</th>' + '<th class="log-header-event">Event</th></tr>'; } return logElement; }
[ "function ensureStatsTableContainer(peerConnectionElement) {\n var containerId = peerConnectionElement.id + '-table-container';\n var container = $(containerId);\n if (!container) {\n container = document.createElement('div');\n container.id = containerId;\n container.className = 'stats-table-container';\n peerConnectionElement.appendChild(container);\n }\n return container;\n}", "function ensureStatsTable(peerConnectionElement, statsId) {\n var tableId = peerConnectionElement.id + '-table-' + statsId;\n var table = $(tableId);\n if (!table) {\n var container = ensureStatsTableContainer(peerConnectionElement);\n table = document.createElement('table');\n container.appendChild(table);\n table.id = tableId;\n table.border = 1;\n table.innerHTML = '<th>Statistics ' + statsId + '</th>';\n }\n return table;\n}", "function addToTable(to, message) {\n let tableRow = document.createElement(\"tr\");\n let dataName = document.createElement(\"td\");\n let dataMess = document.createElement(\"td\");\n\n dataName.innerHTML = to;\n dataMess.innerHTML = message;\n\n tableRow.appendChild(dataName);\n tableRow.appendChild(dataMess);\n let table = document.getElementById(\"eveTable\");\n table.appendChild(tableRow);\n }", "function initializeMessageLogTable()\n{\n clearTimeout(timeOutMessageLog);\n clearMessageLogTable();\n maxLogTime=0;\n setLog();\n}", "function recordTableRecords()\n{\n ula.ul.pushOne(CF.mongo.db.colles.table.name,\n {\n // updateTime: new Date().toISOString(),\n updateTime: new Date(),\n // records: _.extend([], tableRecords)\n records: _merge([], tableRecords)\n },\n ()=>{});\n}", "function addAllToTables() {\n\n let table = document.getElementById(\"eveTable\");\n\n // reset eve's table\n table.innerHTML = \"\";\n let tr = document.createElement(\"tr\");\n let th1 = document.createElement(\"th\");\n let th2 = document.createElement(\"th\");\n th1.innerHTML = \"Recipient\";\n th2.innerHTML = \"Message\";\n tr.appendChild(th1);\n tr.appendChild(th2);\n table.appendChild(tr);\n\n for (let i = 0; i < messageList.names.length; i++) {\n addToTable(messageList.names[i], messageList.messages[i]);\n }\n }", "function appendListToTable(mPortArr,lineId,destinationDevice,sourceDevice){\t\n\tsetTimeout(function(){\n\t\tif (globalDeviceType == 'Mobile'){\n\t\t\t$(document).on('pagebeforeshow', '#manageConnectionDiv', function (e, ui) {\n\t\t\t\t$('#manageConnectionDiv div[role=\"dialog\"]').css({\"max-width\":\"60%\"});\n\t\t\t\t$('ul').css({\"max-width\":\"350px\"});\n\t\t\t});\t\n\t\t\t$.mobile.changePage($('#manageConnectionDiv'),{\n\t\t\t\ttransition: \"pop\"\n\t\t\t});\n\t\t\tsubAppendToList(mPortArr,lineId,destinationDevice,sourceDevice);\n\t\t} else {\n\t\t\t$( \"#configPopUp\" ).dialog({\n\t\t\t\tmodal: true,\n\t\t\t\tautoResize:true,\n\t\t\t\twidth: \"500px\",\n\t\t\t\theight: \"auto\"\n\t\t\t});\n\t\t\t$( \"#configPopUp\" ).dialog(\"open\");\n\t\t\t$( \"#configPopUp\" ).empty().load('pages/ConfigEditor/manageConnectivity.html',function(){\n\t\t\t\tsetTimeout(function(){\n\t\t\t\t\t$('#manageConnectionDiv div[role=\"dialog\"]').css({\"max-width\":\"60%\"});\n\t\t\t\t\t$('ul').css({\"max-width\":\"350px\"});\t\t\n\t\t\t\t\tsubAppendToList(mPortArr,lineId,destinationDevice,sourceDevice);\n\t\t\t\t},1000);\n\t\t\t});\n\t\t}\n\t\t\n\t},1500);\n\t\t\n}", "function createConnectionDialog(cell, source, target) {\n\t\t\n\t\tvar content = '<table class=\"connectionInOut\"><tr><td>' +\n\t\t \t\t\t\t'<table class=\"connectionOut\">' + \n\t\t\t\t\t\t\t'<tr>' +\n\t\t\t\t\t\t\t\t'<th>out: ' + source.attr('name/text') + '</th></tr>';\n\t\t\n\t\t//Generate out ports\n\t\t$.each(source.attributes.outPorts, function(index, value){\n\t\t\t\n\t\t\tvar outPort = source.attributes.outPorts[index];\n\t\t\t\n\t\t\tif(source.attributes.connectedPorts[index]) {\n\t\t\t\tvar inPortIndex = source.attributes.connectedPorts[index][\"id\"];\n\t\t\t\tvar inPort = source.attributes.connectedPorts[index][\"name\"];\n\t\t\t\tcontent = content + '<tr><td class=\"connected\" id=\"'+ index + '\">' + outPort + '<span class=\"tag\" id=\"' + inPortIndex + '\">' + inPort + '</span></td></tr>';\n\t\t\t}\n\t\t\telse {\n\t\t\t\tcontent = content + '<tr><td class=\"disconnected\" id=\"'+ index + '\">' + outPort + '</td></tr>';\n\t\t\t}\n\t\t});\n\t\t\t\n\t\tcontent = content + '</table></td>';\n\t\t\n\t\tcontent = content + '<td><table class=\"connectionIn\">' + \n\t\t\t\t\t\t\t\t'<tr><th>in: ' + target.attr('name/text') + '</th></tr>' + \n\t\t\t\t\t\t\t'</table></td></tr></table>';\n\t\t\n\t\t//Create dialog\n\t\tvar dialog = new joint.ui.Dialog({\n\t\t\twidth: 500,\n\t\t\ttype: 'neutral',\n\t\t\ttitle: 'Create Connection',\n\t\t\tcontent: content,\n\t\t\tbuttons: [\n\t\t\t { action: 'cancel', content: 'Cancel', position: 'left' },\n\t\t\t ]\n\t\t});\n\t\tdialog.on('action:cancel', cancel);\n\t\tdialog.on('action:close', cancel);\n\t\tdialog.open();\n\t\t\n\t\tfunction cancel() {\n\t\t\tcell.remove();\n\t\t\tdialog.close();\n\t\t};\n\t\t\n\t\t//Generate in ports when click on out port\n\t\t$('.connectionOut').delegate('td.disconnected', 'click', function() {\n\t\t\t\n\t\t\t$('.connectionOut td').removeClass('active');\n\t\t\t\n\t\t\t$(this).toggleClass('active');\n\t\t\tvar index = $(this).attr('id');\n\t\t\tconsole.log($(this));\n\t\t\tvar content = '';\n\t\t\t$.each(target.attributes.inPorts, function(index, value){\n\t\t\t\t\n\t\t\t\tvar inPort = target.attributes.inPorts[index];\n\t\t\t\t\n\t\t\t\tif(target.attributes.connectedPorts[index]) {\n\t\t\t\t\tvar outPortIndex = target.attributes.connectedPorts[index][\"id\"];\n\t\t\t\t\tvar outPort = target.attributes.connectedPorts[index][\"name\"];\n\t\t\t\t\tcontent = content + '<tr><td class=\"connected\" id=\"'+ index + '\">' + inPort + ' <span class=\"tag\" id=\"' + outPortIndex + '\">' + outPort + ' </span></td></tr>';\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\tcontent = content + '<tr><td class=\"disconnected\" id=\"'+ index + '\">' + inPort + '</td></tr>';\n\t\t\t\t}\n\t\t\t});\n\t\t\t\n\t\t\t$(\".connectionIn\").find(\"tr:gt(0)\").remove();\n\t\t\t$(\".connectionIn\").append(content);\n\t\t\t\n\t\t\tconsole.log(\"SHOW: \" + target.attr('name/text'));\n\t\t\tconsole.log(\"ID: \" + index);\n\t\t\tconsole.log(\"NAME: \" + source.attributes.outPorts[index]);\n\t\t});\n\t\t\n\t\t//delete connections\n\t\t$('.connectionInOut').delegate('span.tag', 'click', function(){\n\t\t\tif(confirm(\"Really delete this connection?\")) { \n\t\t\t\t$(this).parent().switchClass('connected', 'disconnected');\n\t\t\t\t\n\t\t\t\tvar id = $(this).attr('id');\n\t\t\t\tvar idParent = $(this).parent().attr('id');\n\t\t\t\t\n\t\t\t\tconsole.log('ID: ' + id);\n\t\t\t\tconsole.log('idParent: ' + idParent);\n\t\t\t\t\n\t\t\t\tvar port1 = undefined, port2 = undefined;\n\t\t\t\t$.each(graph.getElements(), function(index, c) {\n\t\t\t\t\t\n\t\t\t\t\t//delete ports\n\t\t\t\t\tif(c.get('subType') === 'Card') {\n\t\t\t\t\t\tif(c.attributes.connectedPorts[id]) {\n\t\t\t\t\t\t\tport1 = c.id;\n\t\t\t\t\t\t\tdelete c.attributes.connectedPorts[id];\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif(c.attributes.connectedPorts[idParent]){\n\t\t\t\t\t\t\tport2 = c.id;\n\t\t\t\t\t\t\tdelete c.attributes.connectedPorts[idParent];\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\t\n\t\t\t\tvar removed = false;\n\t\t\t\t$.each(graph.getLinks(), function(index, l) {\n\t\t\t\t\t//check if link already removed\n\t\t\t\t\t\n\t\t\t\t\tconsole.log('LINK: ' + JSON.stringify(l));\n\t\t\t\t\t\n\t\t\t\t\tif(!removed) {\n\t\t\t\t\t\tif(l.get('source').id === port1 && l.get('target').id === port2) {\n\t\t\t\t\t\t\tl.remove();\n\t\t\t\t\t\t\tremoved = true;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if(l.get('target').id === port1 && l.get('source').id === port2) {\n\t\t\t\t\t\t\tl.remove();\n\t\t\t\t\t\t\tremoved = true;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t\t\n\t\t\t\t//remove tag\n\t\t\t\t$(this).remove(); \n\t\t\t}\n\t\t});\n\t\t\n\t\t//handle with in connections\n\t\t$('.connectionIn').delegate('td.disconnected', 'click', function() {\n\t\t\t\n\t\t\t\n\t\t\tvar sourceIndex = $('.connectionOut td.active').attr('id');\n\t\t\tvar targetIndex = $(this).attr('id');\n\t\t\t\n\t\t\t\n\t\t\tvar targetName = target.attributes.inPorts[targetIndex];\n\t\t\tvar targetType = \"Input_Card\";\n\t\t\t\n\t\t\tvar sourceName = source.attributes.outPorts[sourceIndex]\n\t\t\tvar sourceType = \"Output_Card\";\n\t\t\t\n\t\t\tvar result = EquipStudioPerformBind(sourceIndex, sourceName, sourceType, targetIndex, targetName, targetType);\n \t\n \tif(result === \"success\") {\n \t\tdialog.close();\n\t\t\t} else {\n\t\t\t\treturn new joint.ui.Dialog({\n\t\t\t\t\ttype: 'alert',\n\t\t\t\t\twidth: 400,\n\t\t\t\t\ttitle: 'Error',\n\t\t\t\t\tcontent: result,\n\t\t\t\t}).open();\t\t\n\t\t\t}\n\t\t\t\n\t\t\t\n\t\t\t//outPort index -> inPort index\n \t//connect source -> target\n\t\t\tsource.attributes.connectedPorts[sourceIndex] = {\n\t\t\t\t\t'id' : targetIndex,\n\t\t\t\t\t'name' : target.attributes.inPorts[targetIndex],\n\t\t\t\t\t'type' : 'Input_Card',\n\t\t\t\t\t'edge' : 'target',\n\t\t\t};\n\t\t\t\n\t\t\ttarget.attributes.connectedPorts[targetIndex] = {\n\t\t\t\t\t'id' : sourceIndex,\n\t\t\t\t\t'name' : source.attributes.outPorts[sourceIndex],\n\t\t\t\t\t'type' : 'Output_Card',\n\t\t\t\t\t'edge' : 'source',\n\t\t\t};\n\t\t\t\n//\t\t\tconsole.log(\"CONNECTION: \" + source.attributes.connectedPorts[sourceIndex]);\n//\t\t\tconsole.log(\"CONNECTION \" + source.attributes.outPorts[sourceIndex] + \" > \" + target.attributes.inPorts[targetIndex] + \" CREATED\")\n\t\t\t\n\t\t\tconsole.log(JSON.stringify(source.attributes.connectedPorts[sourceIndex]));\n\t\t\tconsole.log(JSON.stringify(target.attributes.connectedPorts[targetIndex]));\n\t\n\t\t\t\n\t\t});\n\t\t\n\t}", "addConnection(connection){\r\n this.connections.push(connection);\r\n this.hasChildren = true;\r\n }", "function initializeRows() {\n eventContainer.empty();\n var eventsToAdd = [];\n for (var i = 0; i < events.length; i++) {\n eventsToAdd.push(createNewRow(events[i]));\n }\n eventContainer.append(eventsToAdd);\n }", "function connSanInit(){\n\tvar connStat='';\n\tvar connSanityStat='';\n\tif(globalInfoType == \"JSON\"){\n var devices = getDevicesNodeJSON();\n }else{\n var devices =devicesArr;\n }\n\tfor(var i = 0; i < devices.length; i++){\n\t\tconnStat+=\"<tr>\";\n\t\tconnStat+=\"<td>\"+devices[i].HostName+\"</td>\";\n\t\tconnStat+=\"<td>\"+devices[i].ManagementIp+\"</td>\";\n\t\tconnStat+=\"<td>\"+devices[i].ConsoleIp+\"</td>\";\n\t\tconnStat+=\"<td>\"+devices[i].Manufacturer+\"</td>\";\n\t\tconnStat+=\"<td>\"+devices[i].Model+\"</td>\";\n\t\tconnStat+=\"<td>Init</td>\";\n\t\tconnStat+=\"</tr>\";\n\t}\n//2nd Table of Device Sanity\n\tif(globalInfoType == \"JSON\"){\n var devices = getDevicesNodeJSON();\n }else{\n var devices =devicesArr;\n }\n var allline =[];\n for(var i = 0; i < devices.length; i++){ // checks if the hitted object is equal to the array\n allline = gettargetmap(devices[i].ObjectPath,allline);\n }\n for(var t=0; t<allline.length; t++){\n var source = allline[t].Source;\n var destination = allline[t].Destination;\n var srcArr = source.split(\".\");\n\t\tvar srcObj = getDeviceObject2(srcArr[0]);\n var dstArr = destination.split(\".\");\n\t\tvar dstObj = getDeviceObject2(dstArr[0]);\n var portobject = getPortObject2(source);\n var portobject2 = getPortObject2(destination);\n\t\tif(portobject.SwitchInfo != \"\" && portobject2.SwitchInfo != \"\"){\n\t\t\tconnSanityStat+=\"<tr>\";\n\t\t\tconnSanityStat+=\"<td></td>\";\n\t\t\tconnSanityStat+=\"<td>\"+srcObj.DeviceName+\"</td>\";\n\t\t\tconnSanityStat+=\"<td>\"+portobject.PortName+\"</td>\";\n\t\t\tconnSanityStat+=\"<td></td>\";\n\t\t\tconnSanityStat+=\"<td></td>\";\n\t\t\t\t\n\t\t\tconnSanityStat+=\"<td>\"+dstObj.DeviceName+\"</td>\";\n\t\t\tconnSanityStat+=\"<td>\"+portobject2.PortName+\"</td>\";\n\n\t\t\tconnSanityStat+=\"<td></td>\";\n\t\t\tconnSanityStat+=\"<td></td>\";\n\t\t\tconnSanityStat+=\"<td></td>\";\n\t\t\tconnSanityStat+=\"<td></td>\";\n\t\t\tconnSanityStat+=\"<td></td>\";\n\t\t\tconnSanityStat+=\"</tr>\";\n\t\t}\n\t}\n\t$(\"#connSanityTableStat > tbody\").empty().append(connSanityStat);\n\t$(\"#connSanityTable > tbody\").empty().append(connStat);\n\tif(globalInfoType == \"JSON\"){\n\n var devices = getDevicesNodeJSON();\n }else{\n var devices =devicesArr;\n }\n\t$('#connTotalNo').empty().append(devices.length);\n\tif(globalDeviceType ==\"Mobile\"){\n\t\t$(\"#connSanityTableStat\").table(\"refresh\");\n\t\t$(\"#connSanityTable\").table(\"refresh\");\t\n\t}\n}", "tableListenersOn() {\n this.node.addEventListener(\"click\", this.clickHandler.bind(this));\n }", "function createTableElements(){\n\tvar table = document.getElementById('spectrum');\n\tvar tbdy = document.createElement('tbody');\n\n\tlet l_scans = prsm_data.prsm.ms.ms_header.scans.split(\" \") ;\n\tlet l_specIds = prsm_data.prsm.ms.ms_header.ids.split(\" \") ;\n\tconsole.log(\"l_scans : \", l_scans);\n\tconsole.log(\"l_specIds : \", l_specIds);\n\tlet l_matched_peak_count = 0;\n\tprsm_data.prsm.ms.peaks.peak.forEach(function(peak,i){\n\t\t/*\tCheck if peak contain matched_ions_num attribute\t*/\n\t\tif(peak.hasOwnProperty('matched_ions_num') && parseInt(peak.matched_ions_num)>1)\n\t\t{\n\t\t\tpeak.matched_ions.matched_ion.forEach(function(matched_ion,i){\n\t\t\t\tpeak.matched_ions.matched_ion = matched_ion ;\n\t\t\t\tloop_matched_ions(peak,i) ;\n\t\t\t})\n\t\t}\n\t\telse\n\t\t{\n\t\t\tloop_matched_ions(peak,i) ;\n\t\t}\n\t})\n\tfunction loop_matched_ions(peak,i){\n\t\t/*\tCreate row for each peak value object in the table\t*/\n\t\tvar tr = document.createElement('tr');\n\t\tid = peak.spec_id+\"peak\"+peak.peak_id;\n\t\tlet l_scan;\n\t\tif((parseInt(peak.peak_id) + 1)%2 == 0)\n\t\t{\n\t\t\tl_class = \"unmatched_peak even\";\n\t\t}\n\t\telse\n\t\t{\n\t\t\tl_class = \"unmatched_peak odd\";\n\t\t}\n\t\tif(peak.hasOwnProperty('matched_ions_num'))\n\t\t{\n\t\t\tid = id + peak.matched_ions.matched_ion.ion_type;\n\t\t\tif((parseInt(peak.peak_id) + 1)%2 == 0)\n\t\t\t{\n\t\t\t\tl_class = \"matched_peak even\";\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tl_class = \"matched_peak odd\";\n\t\t\t}\n\t\t\tl_matched_peak_count++;\n\t\t\t/*\tcreate a name for each row */\n\t\t\ttr.setAttribute(\"name\",peak.matched_ions.matched_ion.ion_position);\n\t\t}\n\t\t/*\tSet \"id\",\"class name\" and \"role\" for each row\t*/\n\t\ttr.setAttribute(\"id\", id);\n\t\ttr.setAttribute(\"class\",l_class);\n\t\ttr.setAttribute(\"role\",\"row\");\n\t\tfor(let i = 0;i<11;i++){\n\t\t\tvar td = document.createElement('td');\n\t\t\ttd.setAttribute(\"align\",\"center\");\n\t\t\tif(i == 0)\n\t\t\t{\n\t\t\t\tif(peak.spec_id == l_specIds[0]) l_scan = l_scans[0];\n\t\t\t\telse l_scan = l_scans[1];\n\n\t\t\t\ttd.innerHTML = l_scan ;\n\t\t\t}\n\t\t\tif(i == 1)\n\t\t\t{\n\t\t\t\ttd.innerHTML = parseInt(peak.peak_id) + 1 ;\n\t\t\t}\n\t\t\tif(i == 2)\n\t\t\t{\n\t\t\t\ttd.innerHTML = peak.monoisotopic_mass;\n\t\t\t}\n\t\t\tif(i == 3)\n\t\t\t{\n\t\t\t\t/*\tprovide link to click on m/z value to view spectrum */\n\t\t\t\tlet a = document.createElement('a');\n\t\t\t\ta.href=\"#!\"\n\t\t\t\ta.className = \"peakRows\"\n\t\t\t\ta.innerHTML = peak.monoisotopic_mz;\n\t\t\t\ttd.appendChild(a);\n\t\t\t}\n\t\t\tif(i == 4)\n\t\t\t{\n\t\t\t\ttd.innerHTML = peak.intensity;\n\t\t\t}\n\t\t\tif(i == 5)\n\t\t\t{\n\t\t\t\ttd.innerHTML = peak.charge;\n\t\t\t}\n\t\t\tif(peak.hasOwnProperty('matched_ions_num'))\n\t\t\t{\n\t\t\t\tif(i == 6)\n\t\t\t\t{\n\t\t\t\t\ttd.innerHTML = peak.matched_ions.matched_ion.theoretical_mass;\n\t\t\t\t}\n\t\t\t\tif(i == 7)\n\t\t\t\t{\n\t\t\t\t\ttd.innerHTML = peak.matched_ions.matched_ion.ion_type+peak.matched_ions.matched_ion.ion_display_position;\n\t\t\t\t}\n\t\t\t\tif(i == 8)\n\t\t\t\t{\n\t\t\t\t\ttd.innerHTML = peak.matched_ions.matched_ion.ion_position;\n\t\t\t\t}\n\t\t\t\tif(i == 9)\n\t\t\t\t{\n\t\t\t\t\ttd.innerHTML = peak.matched_ions.matched_ion.mass_error;\n\t\t\t\t}\n\t\t\t\tif(i == 10)\n\t\t\t\t{\n\t\t\t\t\ttd.innerHTML = peak.matched_ions.matched_ion.ppm;\n\t\t\t\t}\n\t\t\t}\n\t\t\ttr.appendChild(td);\n\t\t}\n\t\ttbdy.appendChild(tr);\n\t}\n\tlet l_All_Peaks = prsm_data.prsm.ms.peaks.peak.length;\n\tlet l_not_matched_peak_count = l_All_Peaks - l_matched_peak_count; \n\tdocument.getElementById(\"all_peak_count\").innerHTML = \"All peaks (\" + l_All_Peaks + \")\" ;\n\tdocument.getElementById(\"matched_peak_count\").innerHTML = \"Matched peaks (\" + l_matched_peak_count + \")\" ;\n\tdocument.getElementById(\"not_matched_peak_count\").innerHTML = \"Not Matched peaks (\" + l_not_matched_peak_count + \")\" ;\n\t\n\ttable.appendChild(tbdy);\n}", "function connSanXML(uptable,lowtable){\n\tvar connStat='';\n\tvar connSanityStat='';\n\tvar devFlag = false;\n\tif(globalInfoType == \"XML\"){\n\t\tfor(var i = 0; i < uptable.length; i++){\n\t\t\tconnStat+=\"<tr>\";\n\t\t\tconnStat+=\"<td>\"+uptable[i].getAttribute('HostName')+\"</td>\";\n\t\t\tconnStat+=\"<td>\"+uptable[i].getAttribute('ManagementIp')+\"</td>\";\n\t\t\tconnStat+=\"<td>\"+uptable[i].getAttribute('ConsoleIp')+\"</td>\";\n\t\t\tconnStat+=\"<td>\"+uptable[i].getAttribute('Manufacturer')+\"</td>\";\n\t\t\tconnStat+=\"<td>\"+uptable[i].getAttribute('Model')+\"</td>\";\n\t\t\tconnStat+=\"<td>\"+uptable[i].getAttribute('PortMapping')+\"</td>\";\n\t\t\tconnStat+=\"</tr>\";\n\t\t\tif(window['variable' + Connectivity[pageCanvas] ].toString() == \"true\" && uptable[i].getAttribute('PortMapping').toLowerCase() != 'fail' && uptable[i].getAttribute('PortMapping').toLowerCase() != 'completed' && uptable[i].getAttribute('PortMapping').toLowerCase() != 'cancelled' && uptable[i].getAttribute('PortMapping').toLowerCase() != 'device not accessible'){\n\t\t\t\tdevFlag = true;\n\t\t\t}\n\t\t}\n\t\tfor(var i = 0; i < lowtable.length; i++){\n//2nd Table of Device Sanity\n\t\t\tconnSanityStat+=\"<tr>\";\t\n\t\t\tconnSanityStat+=\"<td>\"+lowtable[i].getAttribute('TimeStamp')+\"</td>\";\n\t\t\tconnSanityStat+=\"<td>\"+lowtable[i].getAttribute('SrcDevName')+\"</td>\";\n\t\t\tconnSanityStat+=\"<td>\"+lowtable[i].getAttribute('SrcPortName')+\"</td>\";\n\t\t\tconnSanityStat+=\"<td>\"+lowtable[i].getAttribute('SrcSwitchPort')+\"</td>\";\n\t\t\tconnSanityStat+=\"<td>\"+lowtable[i].getAttribute('SrcPortStatus')+\"</td>\";\n\t\t\tconnSanityStat+=\"<td>\"+lowtable[i].getAttribute('DstDevName')+\"</td>\";\n\t\t\tconnSanityStat+=\"<td>\"+lowtable[i].getAttribute('DstPortName')+\"</td>\";\n\t\t\tconnSanityStat+=\"<td>\"+lowtable[i].getAttribute('DstSwitchPort')+\"</td>\";\n\t\t\tconnSanityStat+=\"<td>\"+lowtable[i].getAttribute('DstPortStatus')+\"</td>\";\n\t\t\tconnSanityStat+=\"<td>\"+lowtable[i].getAttribute('SwitchHostName')+\"</td>\";\n\t\t\tconnSanityStat+=\"<td>\"+lowtable[i].getAttribute('ConnectivityType')+\"</td>\";\n\t\t\tconnSanityStat+=\"<td>\"+lowtable[i].getAttribute('Status')+\"</td>\";\n\t\t\tconnSanityStat+=\"</tr>\";\n\n\t\t}\n\t}else{\n\t\tfor(var i = 0; i < uptable.length; i++){\n\t\t\tconnStat+=\"<tr>\";\n\t\t\tconnStat+=\"<td>\"+uptable[i].HostName+\"</td>\";\n\t\t\tconnStat+=\"<td>\"+uptable[i].ManagementIp+\"</td>\";\n\t\t\tconnStat+=\"<td>\"+uptable[i].ConsoleIp+\"</td>\";\n\t\t\tconnStat+=\"<td>\"+uptable[i].Manufacturer+\"</td>\";\n\t\t\tconnStat+=\"<td>\"+uptable[i].Model+\"</td>\";\n\t\t\tconnStat+=\"<td>\"+uptable[i].PortMapping+\"</td>\";\n\t\t\tconnStat+=\"</tr>\";\n\t\t\tif(globalMAINCONFIG[pageCanvas].MAINCONFIG[0].Connectivity.toString() == \"true\" && uptable[i].PortMapping.toLowerCase() != 'fail' && uptable[i].PortMapping.toLowerCase() != 'completed' && uptable[i].PortMapping.toLowerCase() != 'cancelled' && uptable[i].PortMapping.toLowerCase() != 'device not accessible'){\n\t\t\t\tdevFlag = true;\n\t\t\t}\n\t\t}\n\t\tfor(var i = 0; i < lowtable.length; i++){\n//2nd Table of Device Sanity\n\t\t\tconnSanityStat+=\"<tr>\";\t\n\t\t\tconnSanityStat+=\"<td>\"+lowtable[i].TimeStamp+\"</td>\";\n\t\t\tconnSanityStat+=\"<td>\"+lowtable[i].SrcDevName+\"</td>\";\n\t\t\tconnSanityStat+=\"<td>\"+lowtable[i].SrcPortName+\"</td>\";\n\t\t\tconnSanityStat+=\"<td>\"+lowtable[i].SrcSwitchPort+\"</td>\";\n\t\t\tconnSanityStat+=\"<td>\"+lowtable[i].SrcPortStatus+\"</td>\";\n\t\t\tconnSanityStat+=\"<td>\"+lowtable[i].DstDevName+\"</td>\";\n\t\t\tconnSanityStat+=\"<td>\"+lowtable[i].DstPortName+\"</td>\";\n\t\t\tconnSanityStat+=\"<td>\"+lowtable[i].DstSwitchPort+\"</td>\";\n\t\t\tconnSanityStat+=\"<td>\"+lowtable[i].DstPortStatus+\"</td>\";\n\t\t\tconnSanityStat+=\"<td>\"+lowtable[i].SwitchHostName+\"</td>\";\n\t\t\tconnSanityStat+=\"<td>\"+lowtable[i].ConnectivityType+\"</td>\";\n\t\t\tconnSanityStat+=\"<td>\"+lowtable[i].Status+\"</td>\";\n\t\t\tconnSanityStat+=\"</tr>\";\n\t\t}\n\t}\n\t$(\"#connSanityTableStat > tbody\").empty().append(connSanityStat);\n\t$(\"#connSanityTable > tbody\").empty().append(connStat);\n\tif(globalInfoType == \"JSON\"){\n var devices = getDevicesNodeJSON();\n }else{\n var devices =devicesArr;\n }\n\t$('#connTotalNo').empty().append(devices.length);\n\tif(globalDeviceType==\"Mobile\"){\n\t\t$(\"#connSanityTableStat\").table(\"refresh\");\n\t\t$(\"#connSanityTable\").table(\"refresh\");\t\n\t}\n\tTimeOut = setTimeout(function(){\n\t\tconnSanXML2(devFlag);\n\t},2000);\n\treturn;\t\n}", "onTableAdd (name) {\n if (this.tablesRetain.length >= this.tableCount) return // all tables already in the retain list\n if (!name) {\n console.warn('Unable to add table into retain list, table name is empty')\n return\n }\n // add into tables retain list if not in the list already\n let isAdded = false\n if (this.tablesRetain.indexOf(name) < 0) {\n this.tablesRetain.push(name)\n isAdded = true\n }\n\n if (isAdded) {\n this.$q.notify({\n type: 'info',\n message: (this.tablesRetain.length < this.tableCount) ? this.$t('Retain output table') + ': ' + name : this.$t('Retain all output tables')\n })\n this.refreshTableTreeTickle = !this.refreshTableTreeTickle\n }\n }", "function addAttendeeHourToList(attendeeHour) {\n var tr = $('<tr/>', { 'data-id': attendeeHour.id, 'class': 'bg-warning' }); // highlight newly added row\n tr.append($('<td/>', { text: attendeeHour.fullName }));\n tr.append($('<td/>', { text: attendeeHour.certId }));\n tr.append($('<td/>', { text: attendeeHour.pdHours }));\n var removeLink = $('<a/>', {\n href: '#',\n 'class': 'delete',\n 'data-id': attendeeHour.id,\n text: 'Remove'\n });\n var removeTd = $('<td/>').append(removeLink);\n tr.append(removeTd);\n tr.appendTo($('#attendeeContainer > table > tbody'));\n\n // Setup click listener\n removeLink.click(function (e) {\n e.preventDefault();\n deleteAttendeeHour($(this));\n });\n\n // remove highlight after 2 seconds\n setTimeout(function () {\n tr.removeClass('bg-warning'); // ffc107\n }, 2000);\n}", "function addPendingTransactions() {\n blockchain.pendingTransactions.forEach(transaction => {\n const pendingTransactionsTable = document.getElementById(\"newPendingTransactionTable\");\n\n if (!document.getElementById(\"transactionId\") || transaction.transactionId !== document.getElementById(\"transactionId\").innerHTML) {\n let row = pendingTransactionsTable.insertRow();\n let transactionId = row.insertCell(0);\n transactionId.innerHTML = transaction.transactionId;\n transactionId.id = \"transactionId\";\n let txTimestamp = row.insertCell(1);\n txTimestamp.innerHTML = (new Date(transaction.txTimestamp)).toLocaleTimeString();\n let sender = row.insertCell(2);\n sender.innerHTML = transaction.sender;\n let recipient = row.insertCell(3);\n recipient.innerHTML = transaction.recipient;\n let amount = row.insertCell(4);\n amount.innerHTML = transaction.amount;\n } else {\n return;\n };\n });\n }", "function addToWatch(){\n\t\t\t\t\t//\tadds rows within the \"watch\" movies table.\n\t\t\t\t\tconsole.log('Watch Click Worked!');\n\t\t\t\t\t$('#watch-table-row').append($(row));\n\t\t\t\t}", "addConnection(connection) {\n const fromNeuron = this.neurons.get(connection.from.id);\n const toNeuron = this.neurons.get(connection.to.id);\n\n if (fromNeuron === undefined || toNeuron === undefined) {\n throw new Error(\n \"The connection could not be added because the `from` or `to` neurons were undefined\"\n );\n }\n\n fromNeuron.outbound_connections.push(connection);\n toNeuron.inbound_connections.push(connection);\n this.connections.push(connection);\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Save the links into the Document Properties
function persistLinks(e) { var linksInCache = JSON.parse(CacheService.getPrivateCache().get('links')); var documentProperties = PropertiesService.getDocumentProperties(); var linksInDoc = documentProperties.getProperty('LINKS'); if(linksInDoc == null) { documentProperties.setProperty('LINKS', JSON.stringify(linksInCache)); } else { linksInDoc = JSON.parse(documentProperties.getProperty('LINKS')); var newLinks = linksInDoc; var idsToAdd = Object.keys(linksInCache); for (var i = 0; i < idsToAdd.length; i++) { if(newLinks[idsToAdd[i]] == undefined) { newLinks[idsToAdd[i]] = []; } /* To avoid creating a new array in the JSON object */ var nbElem = linksInCache[idsToAdd[i]].length; for (var j = 0; j < nbElem; j++) { newLinks[idsToAdd[i]].push(linksInCache[idsToAdd[i]][j]); } } documentProperties.setProperty('LINKS', JSON.stringify(newLinks)); } DocumentApp.getUi().alert('Links saved'); clearLinksInCache(); }
[ "function showLinkDialog_LinkSave(propert_key, url) {\n\tPropertiesService.getDocumentProperties().setProperty(propert_key, url);\n}", "function saveLinks(id, links, type) {\n links = links.trim().split(\",\") //turn comma separated list into array\n links.forEach(link => {\n if (type == \"doc\") {\n insert_docLink.run(id, link.trim())\n }\n else if (type == \"proj\") {\n insert_projLink.run(id, link)\n }\n })\n}", "function saveStoredThings(){\n localStorage.setItem('fronter_fixes_links', links);\n}", "set link(aValue) {\n this._logService.debug(\"gsDiggEvent.link[set]\");\n this._link = aValue;\n\n var uri;\n try {\n uri = this._ioService.newURI(this._link, null, null);\n } catch (e) {\n uri = this._ioService.newURI(\"http://\" + this._link, null, null);\n }\n this._domain = uri.host;\n }", "set href(aValue) {\n this._logService.debug(\"gsDiggEvent.href[set]\");\n this._href = aValue;\n }", "function showLinks() {\n var app = UiApp.createApplication();\n var mainPanel = app.createVerticalPanel(); \n var scrollPanel = app.createScrollPanel().setPixelSize(500, 300);\n var links = PropertiesService.getDocumentProperties().getProperty('LINKS');\n if(links != null) {\n links = JSON.parse(PropertiesService.getDocumentProperties().getProperty('LINKS')); \n var ids = Object.keys(links);\n var grid = app.createGrid().resize(ids.length+1,2);\n grid.setBorderWidth(1);\n grid.setText(0, 0, 'Source');\n grid.setText(0, 1, 'Target(s)');\n for (var i = 0; i < ids.length; i++) {\n grid.setText(i+1, 0, ids[i]);\n var linksString = \"\";\n for (var j = 0; j < links[ids[i]].length; j++) {\n var target = links[ids[i]][j][\"target\"]\n if(linksString == \"\") {\n linksString = target;\n }\n else {\n linksString += \", \" + target;\n }\n }\n grid.setText(i+1, 1, linksString);\n }\n mainPanel.add(grid); \n scrollPanel.add(mainPanel);\n app.add(scrollPanel);\n }\n else {\n mainPanel.add(app.createLabel(\"No links in this document\"));\n app.add(mainPanel);\n }\n DocumentApp.getUi().showModalDialog(app, 'Links in the document'); \n}", "function updateLink(value) {\n var item = new Array;\n\n //! Update Link\n item.modified = new Date();\n item.id = 1\n item.link = value;\n Storage.updateLink(item);\n strLink = value;\n}", "set href(aValue) {\n this._logger.debug(\"href[set]\");\n this._href = aValue;\n }", "function saveListLinksToCookie() {\n var linkListJson = getShortenLinkListJson();\n if(linkListJson != \"\") {\n setCookie(\"ResultsList\", linkListJson, 30);\n }\n}", "formatUrls(props) {\n this.href = props.href && typeof props.href === 'object' ? format(props.href) : props.href;\n this.as = props.as && typeof props.as === 'object' ? format(props.as) : props.as;\n }", "function updateLinks() {\n var programName=programNameField.value;\n loadLink.href=\"?program=\"+programName;\n runLink.href=loadLink.href+\"&run=\"+window.localStorage.getItem(getProgramAccessTokenKey(programName));\n}", "set link(aValue) {\n this._logger.debug(\"link[set]\");\n this._link = aValue;\n\n let uri;\n\n try {\n uri = this._ioService.newURI(this._link, null, null);\n } catch (e) {\n uri = this._ioService.newURI(\"http://\" + this._link, null, null);\n }\n\n this._domain = uri.host;\n }", "linksAdd(links) {\n for(var i = 0; i < links.length; i++)\n this.linkAdd(links[i]);\n }", "function showLinkDialog(propert_key, title) {\n\tif( typeof title === 'undefined' ) title = 'Save link';\n\t/** Get link form properties\n\t */\n\tvar getLink = function() {\n\t\tvar url = PropertiesService.getDocumentProperties().getProperty(propert_key);\n\t\treturn url ? url : '';\n\t};\n\t\n\tvar save_script = 'google.script.run.showLinkDialog_LinkSave(\\''+propert_key+'\\', document.getElementById(\\'saved-link\\').value);';\n\tvar htmlString = '<link rel=\"stylesheet\" href=\"https://ssl.gstatic.com/docs/script/css/add-ons.css\">'+\n\t\t\t\t\t\t'<style rel=\"stylesheet\">input[type=\"button\"]{margin-right:16px}</style>'+\n\t\t\t\t\t\t'<div>' +\n\t\t\t\t\t\t\t'<input type=\"text\"\tvalue=\"'+getLink()+'\"\tid=\"saved-link\"\tstyle=\"width:100%\" /><br><br>' +\n\t\t\t\t\t\t\t'<input type=\"button\"\tvalue=\"Open\"\tid=\"saved-link-open\"\tonclick=\"'+save_script+'window.open(document.getElementById(\\'saved-link\\').value);google.script.host.close();\"/ class=\"green\">' +\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t'<input type=\"button\"\tvalue=\"Save\"\t\tonclick=\"'+save_script+'google.script.host.close();\" />' +\n\t\t\t\t\t\t\t'<input type=\"button\"\tvalue=\"Remove\"\t\tonclick=\"google.script.run.showLinkDialog_LinkRemove(\\''+propert_key+'\\');google.script.host.close();\" />' +\n\t\t\t\t\t\t'</div>';\n\t\t\t\t \n\tvar htmlOutput = HtmlService.createHtmlOutput(htmlString).setSandboxMode(HtmlService.SandboxMode.IFRAME).setHeight(96);\n\tSpreadsheetApp.getUi().showModalDialog(htmlOutput, title);\n}", "function saveDocToGraphMapping(documentUri, graphUris) {\n const prevGraphUris = privateData.documentToGraph[documentUri];\n if (!prevGraphUris) {\n privateData.documentToGraph[documentUri] = new Set(graphUris);\n } else {\n graphUris.forEach(u => prevGraphUris.add(u));\n }\n }", "function exportGraphicLinks(parentElement,page)\r{\r $.writeln(\"exportGraphicLinks parentElement: \" + parentElement);\r var graphics = page.allGraphics;\r for (var y = 0; y < graphics.length; y++){\r graphic = graphics[y]; \r var graphicTag = parentElement.xmlElements.add(tags.graphicTag);\r var graphicNameTag = graphicTag.xmlElements.add(tags.graphicNameTag);\r if (graphic.itemLink != null) { \r graphicNameTag.contents = graphic.itemLink.name;\r graphicLinkTag = graphicTag.xmlElements.add(tags.graphicLinkTag);\r graphicLinkTag.contents = graphic.itemLink.filePath;\r // add a reference to the image\r imageLinkTag = graphicTag.xmlElements.add(tags.imageLinkTag);\r imageLinkTag.contents = \"images/\" + graphic.itemLink.name + \".png\";\r }\r }\r}", "_isLinkSaveable(aLink) {\n // We don't do the Right Thing for news/snews yet, so turn them off\n // until we do.\n return this.context.linkProtocol && !(\n this.context.linkProtocol == \"mailto\" ||\n this.context.linkProtocol == \"javascript\" ||\n this.context.linkProtocol == \"news\" ||\n this.context.linkProtocol == \"snews\");\n }", "function mark( links ) {\r\n\t\t$( links ).each( function( pos, link ) {\r\n\t\t\tmarkLink( link );\r\n\t\t} );\r\n\t}", "function writeToDoc(hash) {\n hash['url'] = discoverTrueUrl(hash);\n //currentUrl is now the correct URI\n var followedPost = UrlFetchApp.fetch(hash['url'], {'followRedirects': true, 'muteHttpExceptions': true});\n hash['dump'] = followedPost.getContentText();\n //companyName\tLink\trecipient\tsubmitted?\tEffort Level\tLast FollowUp\tjobTitle\tcompanyBlurb\tcompanyCity\tComment\tuseEmailAddress\temailSentDate\tfullListingContent\n var prettyDate = stringifiedCurrentDate();\n Logger.log(hash['url']);\n SpreadsheetApp.getActiveSpreadsheet().getSheets()[0].appendRow([hash['company'], hash['url'], \"\", 1, \"Low\", prettyDate, hash['jobtitle'], \"\", hash['formattedLocation'], \"\", 0, \"\", hash['dump']]);\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
return an array of gap fillers; if they start on 30m interval, should be a 30 then 1hr if they end on 30m interval, should be hours then a 30
function getGapFiller(gap) { const fillers = []; const remainingGap = { start: new Date(gap.prev.end), end: new Date(gap.next.start) }; var gapEnd = null, gapStart = null; // leading 30 if (gap.prev.end.getMinutes() == 30) { gapEnd = new Date(gap.prev.end); gapEnd.setMinutes(0) gapEnd.setHours(gapEnd.getHours() + 1); fillers.push(ev(null, null, new Date(gap.prev.end), gapEnd)); // remove leading 30 from remaining remainingGap.start.setMinutes(0); remainingGap.start.setHours(remainingGap.start.getHours() + 1); } //fillers.push('hello world'); // mid hours const remain = dateDiffMin(remainingGap.start, remainingGap.end); const hourDec = remain / 60; const hours = Math.floor(hourDec); // fill in gaps for number of hours for (var i = 0; i < hours; i++) { fillers.push(ev(null, null, new Date(remainingGap.start))); remainingGap.start.setHours(remainingGap.start.getHours() + 1); } // if next starts on 30, we need to end at next-30, not next // trailing 30 - ... need to start at the 0 hour if (gap.next.start.getMinutes() == 30) { gapStart = new Date(gap.next.start); gapStart.setMinutes(0) gapEnd = new Date(gap.next.start); fillers.push(ev(null, null, gapStart, gapEnd)); } return fillers; }
[ "function gap(time, div, r) {\r\n if (div === 60) {\r\n return (2 * Math.PI * r) * (60 - time / div);\r\n } else {\r\n return (2 * Math.PI * r) * (12 - time / div);\r\n }\r\n}", "function minMaxBPM() {\n var min = Infinity;\n var max = 0;\n for (var i = 0; i < coords.length; i++) {\n var heartrate = parseInt(route_data[i][\"hr\"]);\n if (heartrate < min) {\n min = heartrate;\n }\n if (heartrate > max) {\n max = heartrate;\n }\n }\n return [min, max];\n}", "function createHourArr() {\n for (var i = 0; i < 9; i++) {\n var hour = moment().hour(i + 9).format(\"h a\");\n hourArr.push(hour);\n };\n}", "createTimeGapMapping() {\n let timeGapMapping = {};\n this.patients.forEach(d => {\n let curr = this.sampleStructure[d];\n for (let i = 1; i < curr.length; i++) {\n if (i === 1) {\n timeGapMapping[curr[i - 1]] = undefined\n }\n timeGapMapping[curr[i]] = this.sampleTimelineMap[curr[i]] - this.sampleTimelineMap[curr[i - 1]]\n }\n timeGapMapping[curr[curr.length - 1] + \"_post\"] = undefined;\n });\n this.staticMappers[this.timeDistanceId] = timeGapMapping;\n }", "getIntervalSteps (start, end, asIndex) {\n\t\tlet totalSteps = this.getTotalStepCount();\n\t\tlet ref = this.tzero;\n\t\tstart -= ref;\n\t\tstart /= (60 * 1000);\n\t\tstart = Math.ceil(start / this.getStepInterval());\n\t\tend -= ref;\n\t\tend /= (60 * 1000);\n\t\tend = Math.floor(end / this.getStepInterval());\n\t\tlet ret = [];\n\t\tfor (let i=start; i<=end; i++) {\n\t\t\tif (asIndex) {\n\t\t\t\tlet index = i;\n\t\t\t\twhile (index < 0)\n\t\t\t\t\tindex += totalSteps;\n\t\t\t\tret.push(index % totalSteps);\n\t\t\t}\n\t\t\telse\n\t\t\t\tret.push(i);\n\t\t}\n\t\treturn ret;\n\t}", "function getListOfHours(){\n for(var index = 8; index < 18 ; index++){ //fill in all of the hours\n if (index == 0) { // if index = 0 \n timeBlocksList.push((index + 12) + \"AM\"); // Add hour to timeBlocksList\n }\n else if (index < 12) { // if index < 12 \n timeBlocksList.push(index + \"AM\"); // Add hour to timeBlocksList\n }\n else if (index == 12) { // if index = 12 \n timeBlocksList.push(index + \"PM\"); // Add hour to timeBlocksList\n }\n else if (index > 12) { // if index > 12 \n timeBlocksList.push((index - 12) + \"PM\"); // Add hour to timeBlocksList\n }\n } \n }", "createTimeLabelColumnArray() {\n\n let timeColumn = [];\n\n // We push an empty box first to account for the top left corner.\n timeColumn.push(this.createLabelSlot(\"\"));\n\n // Shows start at 8AM and on the latest days, shows end at 11PM.\n // hence i = 8 until i <= 23\n for (let i = 8; i <= 23; i++) { \n let label = \"\";\n if (i < 11) { // Before 11AM\n label = i + \"AM-\" + (i + 1) + \"AM\";\n } else if (i == 11) { // At 11AM\n label = i + \"AM-\" + (i + 1) + \"PM\";\n } else if (i == 12) { // At Noon\n label = i + \"PM-\" + (i + 1 - 12) + \"PM\";\n } else { // Any time after noon\n label = (i - 12) + \"PM-\" + (i + 1 - 12) + \"PM\";\n }\n timeColumn.push(this.createLabelSlot(label));\n }\n \n return timeColumn;\n }", "function largestGapConsecutiveElements (arr){\n var gap = 0;\n for(var i = 0; i < arr.length; i++){\n var diff = arr[i] - (arr[i+1])\n if (diff > gap){\n gap = diff;\n }\n }\n return gap;\n}", "drawExistingPatterns(startInd, stopInd) {\n\n // find visible patterns\n var startDt = this.priceArray[startInd].Date;\n var stopDt = this.priceArray[stopInd].Date;\n var visPatIndArray = [];\n for (let i = 0; i < this.patternArray.length; i++) {\n if (this.patternArray[i].startDt.isBetween(startDt, stopDt, null, '()') || this.patternArray[i].stopDt.isBetween(startDt, stopDt, null, '()')) { visPatIndArray.push(i); }\n }\n // draw visible patterns\n d3.selectAll(\"rect.bullPattern\").remove();\n d3.selectAll(\"rect.bearPattern\").remove();\n d3.selectAll(\"rect.negPattern\").remove();\n for (let i = 0; i < visPatIndArray.length; i++) {\n let x;\n if (this.xScale(this.patternArray[visPatIndArray[i]].startDt)) {\n x = this.xScale(this.patternArray[visPatIndArray[i]].startDt) - this.xScale.step()*this.xScale.padding()/2;\n } else { x = 0; }\n let width;\n if(this.xScale(this.patternArray[visPatIndArray[i]].stopDt)) {\n width = this.xScale(this.patternArray[visPatIndArray[i]].stopDt) - x + this.xScale.bandwidth() + this.xScale.step()*this.xScale.padding()/2;\n } else { width = this.w; }\n this.chartBody.append(\"rect\").attr(\"class\", this.rectClassDict[this.patternArray[visPatIndArray[i]].dir])\n .attr(\"x\", x)\n .attr(\"y\", 0)\n .attr(\"width\", width)\n .attr(\"height\", this.h);\n }\n }", "splitDateRange(begin, end, step) {\n const beginDate = moment(begin);\n const endDate = moment(end);\n if (!beginDate.isValid() || !endDate.isValid() || beginDate.isAfter(endDate)) {\n throw new Error('invalid date range');\n }\n\n const format = 'YYYY-MM-DD';\n const ranges = [];\n while (!beginDate.isAfter(endDate)) {\n const beginDateString = beginDate.format(format);\n beginDate.add(step - 1, 'days');\n const minDate = moment.min(beginDate, endDate);\n const endDateString = minDate.format(format);\n ranges.push([beginDateString, endDateString]);\n beginDate.add(1, 'days');\n }\n return ranges;\n }", "function genNumArr(inputArr) {\n let strArr = [];\n let hour = inputArr[0];\n let minute = inputArr[1];\n strArr.push([hour, minute]);\n \n incArr.forEach(inc => {\n minute+=inc;\n if(minute>=.60){\n minute=minute%.60;\n hour+=1;\n }\n if(hour>=24){\n hour=hour%24\n }\n strArr.push([hour, minute]);\n })\n \n return strArr;\n}", "getTimesBetween(start, end, day) {\n var times = [];\n // First check if the time is a period\n if (this.data.periods[day].indexOf(start) >= 0) {\n // Check the day given and return the times between those two\n // periods on that given day.\n var periods = Data.gunnSchedule[day];\n for (\n var i = periods.indexOf(start); i <= periods.indexOf(end); i++\n ) {\n times.push(periods[i]);\n }\n } else {\n var timeStrings = this.data.timeStrings;\n // Otherwise, grab every 30 min interval from the start and the end\n // time.\n for (\n var i = timeStrings.indexOf(start); i <= timeStrings.indexOf(end); i += 30\n ) {\n times.push(timeStrings[i]);\n }\n }\n return times;\n }", "fill () {\n for (let i = 0; i < ScheduleList.DAY_HOURS; i++) {\n this.list[i] = []\n }\n }", "calculatePeriods() {\n\n // go through all jobs and generate compound child elements\n let chart = get(this, 'chart'),\n childs = get(this, 'childLines'),\n start = get(this, 'parentLine._start'),\n end = get(this, 'parentLine._end')\n\n // generate period segments\n let periods = dateUtil.mergeTimePeriods(childs, start, end);\n\n // calculate width of segments\n if (periods && periods.length > 0) {\n periods.forEach(period => {\n period.width = chart.dateToOffset(period.dateEnd, period.dateStart, true);\n period.background = this.getBackgroundStyle(period.childs);\n period.style = htmlSafe(`width:${period.width}px;background:${period.background};`);\n });\n }\n\n set(this, 'periods', periods);\n }", "limitArray(arr, limitTimeframeInSeconds){\n if(typeof limitTimeframeInSeconds && !limitTimeframeInSeconds){\n return arr;\n }\n limitTimeframeInSeconds = limitTimeframeInSeconds || 120;\n let timeInMS = limitTimeframeInSeconds * 1000;\n try{\n if(arr && arr.hasOwnProperty('earliestTime')){\n for(var idx = arr.length - 1; idx >= 0; idx--){\n var y = 0;\n var newArr = arr[idx].values;\n var diff = 0;\n \n if(arr.earliestTime){\n diff = (arr.latestTime - arr.earliestTime);\n }\n var earliestUsableTime;\n var timestamp = new Date();\n var lastY = 0;\n if(newArr.length){\n if(newArr[newArr.length - 1].x && newArr[newArr.length - 1].x.getTime){\n var latestTime = newArr[newArr.length - 1].x.getTime();\n for(var x = newArr.length - 1; x >= 0; x--){\n if(newArr[x].x && newArr[x].x.getTime){\n if((newArr[x].x.getTime()) < latestTime - timeInMS){\n lastY = newArr[x].y;\n timestamp = newArr[x].x.getTime();\n newArr.splice(x,1);\n }\n else if(!earliestUsableTime){\n earliestUsableTime = newArr[x].x.getTime();\n }\n else if (newArr[x].x.getTime() < earliestUsableTime){\n earliestUsableTime = newArr[x].x.getTime();\n }\n diff = (arr.latestTime - earliestUsableTime);\n }\n y = newArr[x].y;\n }\n }\n }\n if(earliestUsableTime){\n while(diff < timeInMS){\n if(newArr && newArr.length){\n timestamp = newArr[0].x;\n lastY = newArr[0].y;\n }\n timestamp = new Date(timestamp.getTime() - 1000);\n newArr.unshift({x:timestamp,y:lastY});\n diff += 1000;\n }\n }\n arr[idx].values = newArr;\n }\n }\n }\n catch(e){\n console.error(e);\n }\n return arr;\n }", "fill (options) {\n\n let {\n tonic = 60,\n mode = 'ionian',\n delta = 'degree',\n resolution = beat,\n minNotes = 1,\n duration = beat,\n notes = allNotes,\n onVox = 126, // volume of notes during vocal sections\n pattern = undefined,\n progression = this.progression\n } = options;\n\n const validation = fillOptionsSchema.validate(options);\n\n if (validation.error) {\n throw validation.error;\n }\n \n // random fill\n const chunks = duration / resolution;\n const maxNotes = chunks;\n const numberOfNotes = r(minNotes, maxNotes);\n\n const notesInKey = getNotes(tonic, mode);\n let newGroove = [];\n let delay = 0;\n\n // pattern = 'x(x_x)_x--x'\n // pattern = [{ note: 23, delta: -1 }, {}]\n // pattern = [-2, '_', ['-1, 1, 0], '-', '-']\n // delta: chromatic || degree (default) || chord\n // chromatic - deltas traverse chromatically from root chord, or tonic (if no progression is given)\n // degree - deltas traverse degrees of scale. Ex fill({ pattern: [-1, 0, 1], tonic: 'C4', mode: 'ionian' }) => B4, C4, D4 (degrees) OR B4, C4, C#4 (chromatic)\n // chord - deltas traverse degrees of chord. Ex fill({ pattern: [-1, 0, 1], progression: [{ chord: 'C', duration: 2*beat }] }) => G3, C4, E4\n \n // resolution does not make sense with pattern and duration\n // no pattern and no progression\n // diddle\n // .fill({ duration: 4*beat })\n\n // pattern and no progression \n // -> repeats pattern with random notes until duration is reached\n // -> assumes duration is 1 beat if not given\n\n // pattern and progression\n // -> fill duration of progression step with pattern\n\n // no pattern and progression\n // -> \n\n // no pattern and no progression\n \n // takes a single step of a progression and converts it to notes\n const fill = (step) => {\n const duration = step.duration;\n const p = step.pattern || pattern;\n const res = duration / p.length;\n const chord = step.chord;\n const chordNotes = lib.getChordNotes(chord);\n const chordRoot = chordNotes[0];\n const allChordNotes = lib.getInstancesOf(chordNotes);\n\n for (let i = 0; i < p.length; i++) {\n\n if (Array.isArray(p[i])) {\n const newStep = {\n chord,\n duration: res,\n pattern: p[i]\n } \n \n fill(newStep);\n continue;\n }\n\n // make the previous note longer\n if (p[i] === '_') {\n newGroove[newGroove.length - 1].duration += res;\n continue;\n }\n \n // add to delay of next note\n if (p[i] === '-') {\n delay += res;\n continue;\n }\n\n let note;\n\n if (delta === 'absolute') {\n note = p[i];\n }\n\n if (delta === 'chromatic') {\n note = chordRoot + p[i];\n }\n\n if (delta === 'chord') {\n note = allChordNotes[allChordNotes.indexOf(chordRoot) + p[i]]\n }\n\n if (delta === 'degree') {\n note = notesInKey[notesInKey.indexOf(chordRoot) + p[i]]\n }\n\n newGroove.push({\n note,\n duration: res,\n delay,\n });\n\n delay = 0;\n }\n };\n\n if (progression) {\n for (let i = 0; i < progression.length; i++) {\n fill(progression[i]);\n } \n \n this.notes = newGroove;\n return this; \n }\n\n let randomIntegers = deconstruct(numberOfNotes, chunks);\n\n for (let i = 0; i < numberOfNotes; i++) {\n \n newGroove.push({\n note: notes[r(0, notes.length)],\n duration: randomIntegers.pop() * resolution\n });\n }\n\n this.notes = this.notes.concat(newGroove);\n\n // remove any 0 delay 0 duration notes that may have occurred due to information loss\n this.notes = this.notes.filter((n) => n.duration || n.delay);\n\n this.notes = newGroove;\n return this;\n }", "function getPattern (perWeek, perDay) {\n return _.range(7).map(i => {\n if (i < perWeek) return perDay\n return 0\n })\n}", "function _split(startTime, endTime, durationPerMeasure) {\n const res = [];\n let currStartTime = startTime;\n while (true) {\n const cutoffTime = location.nextMeasureTime(currStartTime, durationPerMeasure);\n const currEndTime = cutoffTime.lessThan(endTime) ? cutoffTime : endTime;\n res.push({\n start: currStartTime,\n end: currEndTime\n });\n if (currEndTime.geq(endTime)) {\n break;\n }\n currStartTime = currEndTime;\n }\n return res;\n}", "function calculateAverageWait(input, previousTime) {\n if (input[0].length < 1) {\n var temp = {};\n temp[0] = previousTime;\n input[0].push(temp);\n }\n for (var i = 1; i < 24; i++) {\n if (input[i].length < 1) {\n var temp = {};\n var hourLastMinute = Object.keys(input[i-1][input[i-1].length-1])[0];\n var hourLastWaitTime = input[i-1][input[i-1].length-1][hourLastMinute];\n temp[0] = hourLastWaitTime;\n input[i].push(temp);\n }\n }\n var result = {};\n for (var i = 0; i < 24; i++) {\n result[i] = null;\n }\n result[0] = Object.keys(input[0][0])[0]*previousTime;\n for (var i = 0; i < input[0].length-1; i++) {\n var currentMinutes = Object.keys(input[0][i])[0];\n var nextMinutes = Object.keys(input[0][i+1])[0];\n var currentWaitTime = input[0][i][currentMinutes];\n result[0] += (nextMinutes - currentMinutes) * currentWaitTime;\n }\n var zeroLastMinute = Object.keys(input[0][input[0].length-1])[0];\n var zeroLastWaitTime = input[0][input[0].length-1][zeroLastMinute];\n result[0] += (60 - zeroLastMinute)*zeroLastWaitTime;\n result[0] /= 60;\n for (var i = 1; i < 24; i++) {\n var lastHour = Object.keys(input[i-1][input[i-1].length-1])[0];\n var lastWaitTime = input[i-1][input[i-1].length-1][lastHour]; \n result[i] = Object.keys(input[i][0])[0]*lastWaitTime;\n for (var j = 0; j < input[i].length-1;j++) {\n var currentMinutes = Object.keys(input[i][j])[0];\n var nextMinutes = Object.keys(input[i][j+1])[0];\n var currentWaitTime = input[i][j][currentMinutes];\n result[i] += (nextMinutes - currentMinutes) * currentWaitTime;\n }\n var hourLastMinute = Object.keys(input[i][input[i].length-1])[0];\n var hourLastWaitTime = input[i][input[i].length-1][hourLastMinute];\n result[i] += (60 - hourLastMinute) * hourLastWaitTime;\n result[i] /= 60;\n }\n return result;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Build the path to the virtualenv
function buildVenvDir() { // Create the venv path const home_dir = process.env["HOME"]; const action_id = process.env["GITHUB_ACTION"]; if (!home_dir) { throw new Error("HOME MISSING"); } return path.join(home_dir, `venv-${action_id}`); }
[ "getProjectPath() {\n let siteName = this.args.getSiteName();\n let projectPath = (0, _path.join)(this.args.output.filename, siteName);\n\n if (!(0, _fs.existsSync)(projectPath)) {\n (0, _fs.mkdirSync)(projectPath);\n }\n\n return projectPath;\n }", "function makeKVSpath() {\n\tvar temp = helper.makeEnrollmentOptions(0);\n\treturn path.join(os.homedir(), '.hfc-key-store/', temp.uuid);\n}", "function buildWebview()\n{\n\tconsole.log(`Building webview bundle for ${chalk.green(\"production envrionment\")}\\n`);\n\tcp.execSync(\"cd views && yarn build:prod\");\n\n\tif (!fs.existsSync(\"./views/dist\"))\n\t{\n\t\tconsole.log(`${chalk.red(\"Need to build webviews first\")}\\n`);\n\t} else\n\t{\n\t\tconsole.log(`${chalk.green(\"Copying webview bundle to current directory\")}\\n`);\n\t\tcp.execSync(\"cp -r ./views/dist ./dist\");\n\t\tcp.execSync(\"cp ./views/package.json ./dist\")\n\n\t\tconsole.log(`Moving img resources to ${chalk.blue(\"./dist/static/css/static\")}\\n`);\n\t\t// then we need to copy the `img` folder to under `css/static`, as now we are using local resources instead of CDN ones\n\t\tif (!fs.existsSync(\"./dist/static/css/static\"))\n\t\t{\n\t\t\tmkdirp(\"./dist/static/css/static\");\n\t\t}\n\t\t// cp.execSync(\"mv ./dist/static/img ./dist/static/css/static/img\");\n\t}\n}", "function GetVirtualPath(){\n\tvar p = window.location.pathname;\n\tif(p.substring(0,1)!=\"/\")\n\t\tp = \"/\"+p;\n\tvar str = p.replace(/^[/]\\w*[/]/,\"\");\t\t\t//将虚拟目录从字符串中清除\n\treturn p.substring(0,p.length - str.length);\t//返回虚拟目录\n}", "function getQbExecutablePath() {\n var path = require( \"path\" );\n var modulePath = path.dirname( module.filename );\n var qbPath = path.resolve( modulePath + \"/../qb/bin/Release/qb.exe\" );\n return qbPath;\n}", "buildVue() {\n return new Promise((resolve, reject) => {\n const args = ['build'];\n if (this.config.vueOptions) {\n const userArgs = this.config.vueOptions.split(' ');\n args = args.push(userArgs);\n }\n const cli = spawn('vue-cli-service', args, { cwd: this.config.vuePath });\n cli.stdout.pipe(process.stdout);\n cli.stderr.pipe(process.stderr);\n cli.on('close', code => {\n // Throw an error if the Vue CLI cannot exit normally.\n if (code) {\n reject(`The Vue CLI exited with code ${code}.`);\n } else {\n // Move the outputs to the Google App Engine project folder.\n rename(`${this.config.vuePath}dist`, `${this.config.gaePath}${this.config.gaeStatic}`, err => {\n if (err) reject(err);\n resolve();\n });\n }\n });\n });\n }", "function setupDistBuild(cb) {\n context.dev = false;\n context.destPath = j('dist', context.assetPath);\n del.sync('dist');\n cb();\n}", "function buildStatic () {\n exec('wintersmith build -X', function (error, stdout, stderr) {\n console.log('stdout: ' + stdout);\n\n if (error !== null) {\n console.log('exec error: ' + error);\n }\n });\n}", "function createFullyQualifiedPath(pathObj) {\n var depPath = pathObj.path.replace(LEADING_SEP_PATT, \"\")\n , projectPath = `${pathObj.project.replace(DOT_PATT, \"/\")}/`\n , mod = pathObj.modifier\n , root = pathObj.root\n , path;\n\n //if this is an absolute path then return it\n if (pathObj.isAbsolute) {\n path = `${mod}${root}${depPath}`\n }\n //if the project path is not in the dependency path, then include it\n else if (depPath.indexOf(projectPath) === -1) {\n path = `${mod}${root}${projectPath}${depPath}`;\n }\n else {\n path = `${mod}${root}${depPath}`;\n }\n\n //standardize the separaters\n path = path.replace(WIN_SEP_PATT, \"/\");\n\n return path;\n }", "installNpmDevDir() {\n let installString = 'npm install';\n let installDir;\n if (this.npmDevDir) {\n installDir = this.npmDevDir;\n }\n else {\n installDir = this.targetDir;\n }\n for (let dependency of this.dependencyArray) {\n installString = installString + ` ${dependency.name}@${dependency.version}`;\n }\n plugins.shelljs.exec(`cd ${installDir} && ${installString}`);\n }", "function Builder(config) {\n this.buildFile = path.join.apply(path, [\n __dirname, \"..\", \"deps\", \"SunSPOT\", \"build.xml\"\n ]);\n\n this.sunspot = config.sunspot;\n this.deploy = config.deploy;\n}", "function url_build () {\n return spawn('python',\n ['./lib/python/change_url.py', 'build'], {stdio: 'inherit'})\n}", "function buildSite (cb, options, environment = 'development') {\n const args = options ? hugoArgsDefault.concat(options) : hugoArgsDefault\n\n process.env.NODE_ENV = environment\n\n return spawn(hugoBin, args, {stdio: 'inherit'}).on('close', (code) => {\n if (code === 0) {\n browserSync.reload()\n cb()\n } else {\n browserSync.notify('Hugo build failed :(')\n cb(new Error('Hugo build failed'))\n }\n })\n}", "loadEnv() {\n let env = dotenvExtended.load({\n silent: false,\n path: path.join(this.getProjectDir(), \".env\"),\n defaults: path.join(this.getProjectDir(), \".env.defaults\")\n });\n\n const options = minimist(process.argv);\n for (let option in options) {\n if (option[0] === \"-\") {\n let value = options[option];\n option = option.slice(1);\n if (option in env) {\n env[option] = value.toString();\n }\n }\n }\n env = dotenvParseVariables(env);\n env = dotenvExpand(env);\n\n this.env = { ...env, project_dir: this.getProjectDir() };\n }", "function getEnvPath() {\n var paths;\n var os = getOsType();\n if (!os) {\n throw new Error('cannot not read system type');\n }\n var p = getEnv('PATH');\n var isMsys = getEnv('OSTYPE') ? true : false;\n if (os.indexOf('WIN') !== -1 && !isMsys) {\n paths = p.split(';');\n } else {\n paths = p.split(':');\n }\n return paths;\n}", "function getVendorPublicPath() {\n return `${baseURL}/vendor/`;\n}", "function preBuild()\n{\n\tconsole.log(`Built bundle will be located at ${chalk.blue(RELEASE_PATH)}\\n`)\n\tif (fs.existsSync(RELEASE_PATH))\n\t{\n\t\tconsole.log(`${chalk.green('Clearing destination folder for built bundle')} 🗑\\n`);\n\t\trimraf.sync(RELEASE_PATH);\n\t}\n\tconsole.log(`${chalk.green('Creating destination folder for built bundle')}\\n`);\n\tmkdirp(RELEASE_PATH);\n\n\n\tconsole.log(`${chalk.yellow('Removing')} ${chalk.bgRed('bld')} folder and ${chalk.bgRed('dist')} folder... 🔥\\n`)\n\t// clean up `bld` folder\n\trimraf.sync(BUILD_PATH);\n\trimraf.sync(DIST_PATH);\n\n\tconsole.log(`Compiling the Electron project\\n`);\n\tcp.execSync('ttsc');\n\tcp.execSync(`cp ${ROOT_PATH}/package.json ${BUILD_PATH}/package.json`)\n}", "function getBinScript(name) {\n // Global install or npm@2 local install, dependencies in local node_modules\n let paths = glob.sync(`../node_modules/.bin/${name}`, {cwd: __dirname})\n if (paths.length > 0) return path.join(__dirname, paths[0])\n // Local npm@3 install, .bin and dependencies are siblings\n paths = glob.sync(`../../.bin/${name}`, {cwd: __dirname})\n if (paths.length > 0) return path.join(__dirname, paths[0])\n throw new Error(`Unable to find .bin script for ${name}`)\n}", "function _resolveClientDirectory() {\n try {\n // Default app dir is\n return process.env.PWD;\n\n } catch (errorSettingAppDir) {\n // Maybe this is being loaded in an IDE or \"node console\"\n return path.dirname(require.main.filename);\n }\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Deserialize a dataframe from a JSON text string.
function fromJSON(jsonTextString) { if (!isString(jsonTextString)) throw new Error("Expected 'jsonTextString' parameter to 'dataForge.fromJSON' to be a string containing data encoded in the JSON format."); return new DataFrame({ values: JSON.parse(jsonTextString) }); }
[ "function fromJSON5(jsonTextString) {\r\n if (!isString(jsonTextString))\r\n throw new Error(\"Expected 'jsonTextString' parameter to 'dataForge.fromJSON5' to be a string containing data encoded in the JSON5 format.\");\r\n return new DataFrame({\r\n values: JSON5.parse(jsonTextString)\r\n });\r\n}", "function fromObject(obj) {\r\n return new DataFrame(Object.keys(obj)\r\n .map(function (fieldName) { return ({\r\n Field: fieldName,\r\n Value: obj[fieldName],\r\n }); }));\r\n}", "function fromCSV(csvTextString, config) {\r\n if (!isString(csvTextString))\r\n throw new Error(\"Expected 'csvTextString' parameter to 'dataForge.fromCSV' to be a string containing data encoded in the CSV format.\");\r\n if (config) {\r\n if (!isObject(config))\r\n throw new Error(\"Expected 'config' parameter to 'dataForge.fromCSV' to be an object with CSV parsing configuration options.\");\r\n if (config.columnNames) {\r\n if (!util_17(config.columnNames[Symbol.iterator])) {\r\n if (!isArray(config.columnNames))\r\n throw new Error(\"Expect 'columnNames' field of 'config' parameter to DataForge.fromCSV to be an array or iterable of strings that specifies column names.\");\r\n }\r\n try {\r\n for (var _a = __values(config.columnNames), _b = _a.next(); !_b.done; _b = _a.next()) {\r\n var columnName = _b.value;\r\n if (!isString(columnName))\r\n throw new Error(\"Expect 'columnNames' field of 'config' parameter to DataForge.fromCSV to be an array of strings that specify column names.\");\r\n }\r\n }\r\n catch (e_1_1) { e_1 = { error: e_1_1 }; }\r\n finally {\r\n try {\r\n if (_b && !_b.done && (_c = _a.return)) _c.call(_a);\r\n }\r\n finally { if (e_1) throw e_1.error; }\r\n }\r\n }\r\n if (config.skipEmptyLines === undefined) {\r\n config = Object.assign({}, config); // Clone the config. Don't want to modify the original.\r\n config.skipEmptyLines = true;\r\n }\r\n }\r\n else {\r\n config = {\r\n skipEmptyLines: true,\r\n };\r\n }\r\n var parsed = PapaParse.parse(csvTextString, config);\r\n var rows = parsed.data;\r\n if (rows.length === 0) {\r\n return new DataFrame();\r\n }\r\n var columnNames;\r\n rows = rows.map(function (row) {\r\n return row.map(function (cell) { return isString(cell) ? cell.trim() : cell; }); // Trim each cell that is still a string.\r\n });\r\n if (config && config.columnNames) {\r\n columnNames = config.columnNames;\r\n }\r\n else {\r\n columnNames = rows.shift();\r\n }\r\n return new DataFrame({\r\n rows: rows,\r\n columnNames: columnNames,\r\n });\r\n var e_1, _c;\r\n}", "parseJsonToObject(str) {\n try {\n const obj = JSON.parse(str);\n return obj;\n } catch (error) {\n return {};\n }\n }", "function parseJSON(string) {\n function dateReviver(key, value) {\n var a;\n if (typeof value === 'string') {\n a = /^(\\d{4})-(\\d{2})-(\\d{2})T(\\d{2}):(\\d{2}):(\\d{2}(?:\\.\\d*)?)Z$/.exec(value);\n if (a) {\n return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4],\n +a[5], +a[6]));\n }\n }\n return value;\n }\n\n return JSON.parse(string, dateReviver);\n }", "function decode (string) {\n\n var body = Buffer.from(string, 'base64').toString('utf8')\n return JSON.parse(body)\n}", "function IsValidJsonString(str) {\n try {\n JSON.parse(str);\n } catch (e) {\n return false;\n }\n return true;\n }", "function parseHeader(dataString) {\n\n // make sure all lines in the header are comma separated\n const commaLines = dataString.split('\\n').reduce((a, b) => {\n const r = b.trim();\n if (r.length !== 0) { // ignore empty lines\n a.push(r.slice(-1) === ',' ? r : `${r},`);\n }\n return a;\n }, []);\n\n // remove comma at end\n const joinedLines = commaLines.join('\\n').slice(0, -1);\n const wrapped = `{${joinedLines}}`;\n let json;\n\n try {\n json = JSON.parse(wrapped);\n } catch (e) {\n throw {\n data: wrapped,\n e,\n message: 'failed to parse the JSON header'\n };\n }\n\n return json;\n}", "static fromJSON(json) {\n if (!Array.isArray(json))\n throw new RangeError('Invalid JSON representation of ChangeSet')\n let sections = [],\n inserted = []\n for (let i = 0; i < json.length; i++) {\n let part = json[i]\n if (typeof part == 'number') {\n sections.push(part, -1)\n } else if (\n !Array.isArray(part) ||\n typeof part[0] != 'number' ||\n part.some((e, i) => i && typeof e != 'string')\n ) {\n throw new RangeError('Invalid JSON representation of ChangeSet')\n } else if (part.length == 1) {\n sections.push(part[0], 0)\n } else {\n while (inserted.length < i) inserted.push(Text.empty)\n inserted[i] = Text.of(part.slice(1))\n sections.push(part[0], inserted[i].length)\n }\n }\n return new ChangeSet(sections, inserted)\n }", "static deserialize(json) {\n let config = json['config'] || {};\n\n let graph = new Graph(config);\n\n json['nodes'].forEach(n => {\n graph.addNode(n.id);\n });\n\n json['links'].forEach(l => {\n if('weight' in l) \n graph.addEdge(l.source, l.target, Number(l.weight));\n else\n graph.addEdge(l.source, l.target);\n });\n\n return graph;\n }", "function parseJson (json) {\n try {\n return JSON.parse(json)\n } catch (_ignored) {\n ignore(_ignored)\n return undefined\n }\n }", "function ParseJson(jsonStr) {\r\n\r\n\t// Create htmlfile COM object\r\n\tvar HFO = CreateOleObject(\"htmlfile\"), jsonObj;\r\n\r\n\t// force htmlfile to load Chakra engine\r\n\tHFO.write(\"<meta http-equiv='x-ua-compatible' content='IE=9' />\");\r\n\r\n\t// Add custom method to objects\r\n\tHFO.write(\"<script type='text/javascript'>Object.prototype.getProp=function(t){return this[t]},Object.prototype.getKeys=function(){return Object.keys(this)};</script>\");\r\n\r\n\t// Parse JSON string\r\n\ttry jsonObj = HFO.parentWindow.JSON.parse(jsonStr);\r\n\texcept jsonObj = \"\"; // JSON parse error\r\n\r\n\t// Unload COM object\r\n\tHFO.close();\r\n\r\n\treturn jsonObj;\r\n}", "static fromJSON(json) {\n if (\n !Array.isArray(json) ||\n json.length % 2 ||\n json.some((a) => typeof a != 'number')\n )\n throw new RangeError('Invalid JSON representation of ChangeDesc')\n return new ChangeDesc(json)\n }", "function parseRecipieContent(recipieText) {\n return parseRecipie(JSON.parse(recipieText));\n}", "function constructDataFrame(times, timesNs, lines, uids, labels, reverse, refId) {\n var dataFrame = {\n refId: refId,\n fields: [{\n name: 'ts',\n type: _grafana_data__WEBPACK_IMPORTED_MODULE_3__[\"FieldType\"].time,\n config: {\n displayName: 'Time'\n },\n values: times\n }, // Time\n {\n name: 'line',\n type: _grafana_data__WEBPACK_IMPORTED_MODULE_3__[\"FieldType\"].string,\n config: {},\n values: lines,\n labels: labels\n }, // Line - needs to be the first field with string type\n {\n name: 'id',\n type: _grafana_data__WEBPACK_IMPORTED_MODULE_3__[\"FieldType\"].string,\n config: {},\n values: uids\n }, {\n name: 'tsNs',\n type: _grafana_data__WEBPACK_IMPORTED_MODULE_3__[\"FieldType\"].time,\n config: {\n displayName: 'Time ns'\n },\n values: timesNs\n } // Time\n ],\n length: times.length\n };\n\n if (reverse) {\n var mutableDataFrame = new _grafana_data__WEBPACK_IMPORTED_MODULE_3__[\"MutableDataFrame\"](dataFrame);\n mutableDataFrame.reverse();\n return mutableDataFrame;\n }\n\n return dataFrame;\n}", "function decode(content, encoding, decoder = \"text\") {\n if (encoding) {\n content = Buffer.from(content, encoding).toString();\n }\n switch (decoder) {\n case \"json\":\n try {\n return JSON.parse(content);\n } catch (e) {\n return undefined;\n }\n default:\n return content;\n }\n}", "function decodeConnectionData (connectionDataString) {\n const buff = new Buffer(connectionDataString, 'base64')\n const text = buff.toString('ascii')\n const connectionData = JSON.parse(text)\n return connectionData\n}", "static fromJSON(json, config = {}) {\n if (!json || typeof json.doc != \"string\")\n throw new RangeError(\"Invalid JSON representation for EditorState\");\n return dist_EditorState.create({\n doc: json.doc,\n selection: EditorSelection.fromJSON(json.selection),\n extensions: config.extensions\n });\n }", "function loadParseObject(objString, objFilename) {\n\tlet obj = {};\n\tif (objString) {\n\t\tlet d = yaml.safeLoad(objString, 'utf8');\n\t\tif (typeof d !== 'object' || !d) throw new Error('Invalid JSON/YAML object');\n\t\tobjtools.merge(obj, d);\n\t}\n\tif (objFilename) {\n\t\tlet str = fs.readFileSync(objFilename);\n\t\tlet d = yaml.safeLoad(str, 'utf8');\n\t\tif (typeof d !== 'object' || !d) throw new Error('Invalid JSON/YAML object');\n\t\tobjtools.merge(obj, d);\n\t}\n\treturn obj;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gymnastics. 5 points. Write a function that prompts the user to enter six scores. From those six scores, the lowest and highest should be discarded. An average score should be computed from the remaining four. Your function should output the discarded scores, as well as the average score. Scores must be real numbers in the range [0.0, 10.0], and users should be continuously reprompted until they comply with this restriction. As always, certain portions of the starter code are critical to the the feedback script. Please do not modify these sections. They are clearly marked. All output should be displayed on the page, not printed to the console.
function gymnastics() { /////////////////// DO NOT MODIFY let total = 0; //// DO NOT MODIFY let scores = []; // DO NOT MODIFY /////////////////// DO NOT MODIFY /* * NOTE: The 'total' variable should be representative of the sum of all * six of the judges' scores. */ /* * NOTE: You need to add each score (valid or not) to the 'scores' variable. * To do this, use the following syntax: * * scores.push(firstScore); // your variable names for your scores * scores.push(secondScore); // will likely be different than mine */ let s1 let s2 let s3 let s4 let s5 let s6 let discard = [] let out = 0 s1 = prompt ("Please enter the first judge's score."); while (s1 < 0 || s1 > 10 ) { s1 = prompt ("Invalid number for the first score. Please enter a interger between 0 to 10 for the first score. "); } s1 = Number(s1); scores.push(s1); s2 = prompt ("Please enter the second judge's score."); while (s2 < 0 || s2 > 10 ) { s2 = prompt ("Invalid number for the second score. Please enter a interger between 0 to 10 for the second score. "); } s2 = Number(s2); scores.push(s2); s3 = prompt ("Please enter the third judge's score."); while (s3 < 0 || s3 > 10) { s3 = prompt ("Invalid number for the third score. Please enter a interger between 0 to 10 for the third score. "); } s3 = Number(s3); scores.push(s3); s4 = prompt ("Please enter the fourth judge's score."); while (s4 < 0 || s4 > 10 ) { s4 = prompt ("Invalid number for the fourth score. Please enter a interger between 0 to 10 for the fourth score. "); } s4 = Number(s4); scores.push(s4); s5 = prompt ("Please enter the fifth judge's score."); s5 = Number(s5); while (s5 < 0 || s5 > 10 ) { s5 = prompt ("Invalid number for the fifth score. Please enter a interger between 0 to 10 for the fifth score. "); } s5 = Number(s5); scores.push(s5); s6 = prompt ("Please enter the sixth judge's score."); while (s6 < 0 || s6 > 10) { s6 = prompt ("Invalid number for the sixth score. Please enter a interger between 0 to 10 for the sixth score. "); } s6 = Number(s6); scores.push(s6); discard.push(Math.min(...scores)); discard.push(Math.max(...scores)); out = discard[0] + discard[1] let scoreFinal = (scores.reduce((a,b) => a + b, 0) - out)/(scores.length-2); var p = document.getElementById("gymnastics-output"); p.innerHTML = "Discarded: " + discard[0] + ", " + discard[1]+ "</br>"; p.innerHTML += "Score: " + scoreFinal.toFixed(2) ; /////////////////////////////// DO NOT MODIFY check('gymnastics', scores); // DO NOT MODIFY /////////////////////////////// DO NOT MODIFY }
[ "function student1(){\n studentId =\"1234\"; \n fname =\"Paul\";\n lname =\"Calais\";\n email =\"paul@yahoo.com\";\n pic ='images/paul.jpg';\n\n// This function is created to assign for student1 grades\n\n p1Num = 95;\n q1Num = 95;\n\n p2Num = 80;\n q2Num = 75;\n\n p3Num = 88;\n q3Num = 75;\n \ngradesAverage = (p1Num + q1Num + p2Num + q2Num + p3Num + q3Num)/6;\n\n console.log ( p1Num);\n console.log ( q1Num);\n console.log ( p2Num);\n console.log ( q2Num);\n console.log ( p3Num);\n console.log ( q3Num);\n console.log ( gradesAverage);\n\nstudentGrades();\n\n}", "function average(x1, x2, x3, x4, x5) {\n var sum = x1 + x2 + x3 + x4 + x5;\n var avg = sum / 5;\n return console.log(avg)\n}", "function highScores() {\n if (\n !qz1Div.classList.contains(\"hidden\") ||\n !qz2Div.classList.contains(\"hidden\") ||\n !qz3Div.classList.contains(\"hidden\") ||\n !qz4Div.classList.contains(\"hidden\") ||\n !qz5Div.classList.contains(\"hidden\") ||\n !qz6Div.classList.contains(\"hidden\") ||\n !qz7Div.classList.contains(\"hidden\") ||\n !qz8Div.classList.contains(\"hidden\") ||\n !qz9Div.classList.contains(\"hidden\") ||\n !qz10Div.classList.contains(\"hidden\")\n ) {\n // if the quiz has started and any question is currently displayed...\n alert(\n \"You are in the middle of a timed quiz. Please complete the quiz before view High Scores.\"\n ); // show user alert that must complete quiz before viewing High Scores\n } else if (!qz11Div.classList.contains(\"hidden\")) {\n // else if score tally div is displayed (and the score hasn't been submitted)...\n alert(\"Please submit your score before viewing High Scores.\"); // show user alert that must submit score before viewing High Scores\n } else {\n // else if the quiz start or the score board is displayed...\n qz0Div.classList.add(\"hidden\"); // ...hide the quiz start div...\n scoresDiv.classList.remove(\"hidden\"); // ...and show the scoreboard div.\n submitScores();\n }\n}", "function five_match_average(array_of_scores){\n five_match_score=array_of_scores.slice(0,5)\n total=0\n for(var x in five_match_score){\n total+=five_match_score[x]\n }\n console.log(total/5)\n}", "function showResAndScore (firstPrompt, secndPrompt) { \n// examFunction returns array [computerPlay, playerPlay]\n// eg [\"Rock\", \"Scissors\"] after asking player for his/her \n// input: \nmyArray = examFunction(firstPrompt, secndPrompt) ;\nplayerSelection = myArray[0] ;\ncomputerSelection = myArray[1] ;\n// Function playRound returns an array containing the (string) contents \n// of either var weWin, var youWin or var draw (eg draw = \"It's a \n// draw! ; We both …\") and the result, ie \"CW\" , \"PW\" or \"NW\" (standing \n// for \"computer wins\" , \"player wins\" and \"nobody wins\"\nroundResult = playRound(playerSelection, computerSelection)\n// Need function here to \n// 1) score the round, after reading roundResult.\n// 2) console.log roundResult and the score (eg\n// \"Computer: 3 Player: 2\")\nscoreRound(roundResult) ;\n } // end showResAndScore", "function getGrade(score) {\n try {\n if (score < 0 || score > 30) {\n throw new RangeError(\"It's not valid range \");\n } else {\n if (score > 0 && score <= 5) {\n console.log(\"F\");\n throw new RangeError(\"Please Improve the Score\");\n } else if (score > 5 && score <= 10) {\n console.log(\"E\");\n throw new RangeError(\"Please Improve the Score\");\n } else if (score > 10 && score <= 15) {\n console.log(\"D\");\n throw new RangeError(\"Please Improve the Score\");\n } else if (score > 15 && score <= 20) {\n console.log(\"C\");\n } else if (score > 20 && score <= 25) {\n console.log(\"B\");\n } else if (score > 25 && score <= 30) {\n console.log(\"A\");\n }\n }\n } catch (error) {\n console.log(error.message);\n }\n}", "function calculatePercentageAndDisplayResult(score) {\n let percentage = ((Number((score/7)*100))).toFixed(2);\n if (percentage=>0 && percentage<=50){\n document.getElementById(\"outputDiv\").innerHTML = `<span class=\"redColor\">Your score is: ${percentage}%</span>` ;\n }\n if(percentage>50 && percentage<80){\n document.getElementById(\"outputDiv\").innerHTML = `<span class=\"orangeColor\">Your score is: ${percentage}%</span>` ;\n }\n if(percentage>=80){\n document.getElementById(\"outputDiv\").innerHTML = `<span class=\"greenColor\">Your score is: ${percentage}%</span>`;\n }\n}", "function score(dice) {\n let score = 0, one = 0,\n two = 0, three = 0,\n four = 0, five = 0,\n six = 0;\n\n for (let i = 0; i < dice.length; i++) {\n switch (dice[i]) {\n case 1: one++;\n break\n case 2: two++;\n break\n case 3: three++;\n break\n case 4: four++;\n break\n case 5: five++;\n break\n case 6: six++;\n break\n }\n }\n if (one > 2) {\n score += 1000\n }\n if (one > 3) {\n score += 100 * (one - 3)\n }\n if (one < 3) {\n score += 100 * one\n }\n if (two > 2) {\n score += 200\n }\n if (three > 2) {\n score += 300\n }\n if (four > 2) {\n score += 400\n }\n if (five > 2) {\n score += 500\n }\n if (five > 3) {\n score += 50 * (five - 3)\n }\n if (five < 3) {\n score += 50 * five\n }\n if (six > 2) {\n score += 600\n }\n return score\n}", "function analyze() {\n var highest = 0,\n lowest = 1000000000,\n averageQA = 0,\n averageAuton = 0,\n averageFouls = 0,\n totalNulls = 0,\n averagePlayoff = 0,\n totalPlayoffs = 0;\n\n for (var matchNum = 0; matchNum < matches.length; matchNum++) {\n\n var currentMatch = matches[matchNum];\n var currentMatchAlliances = currentMatch.alliances;\n var alliance = \"\";\n\n if (currentMatchAlliances.red.teams.indexOf(teamNumber) >= 0) {\n alliance = \"red\";\n } else {\n alliance = \"blue\";\n }\n\n if (currentMatchAlliances[alliance].score >= 0) {\n if (currentMatchAlliances[alliance].score > highest) {\n highest = currentMatchAlliances[alliance].score;\n }\n\n if (currentMatchAlliances[alliance].score < lowest) {\n lowest = currentMatchAlliances[alliance].score;\n }\n\n if (currentMatch.comp_level === 'qm') {\n averageQA += currentMatchAlliances[alliance].score;\n } else {\n averagePlayoff += currentMatchAlliances[alliance].score;\n totalPlayoffs++;\n }\n\n averageAuton += matches[matchNum].score_breakdown[alliance].atuo;\n\n averageFouls += matches[matchNum].score_breakdown[alliance].foul;\n\n } else {\n totalNulls++;\n }\n }\n\n if (totalPlayoffs !== 0) {\n averagePlayoff /= totalPlayoffs;\n }\n\n averageQA /= matches.length - totalNulls - totalPlayoffs;\n averageFouls /= matches.length - totalNulls;\n averageAuton /= matches.length - totalNulls;\n\n console.log('Analytics');\n console.log('Team Name: ' + teamName);\n console.log(\"Highest Number of points: \" + highest);\n console.log(\"Lowest Number of points: \" + lowest);\n console.log(\"Average QA: \" + averageQA);\n console.log(\"Average Playoff Points (If Applicable): \" + averagePlayoff);\n console.log(\"Average Auton points: \" + averageAuton);\n console.log(\"Average Foul points: \" + averageFouls);\n}", "function problem5() {\r\n\tdocument.getElementById(\"problem5\")\r\n\r\n\tvar num1 = Number(prompt(\"Please enter number 1.\"));\r\n\tvar num2 = Number(prompt(\"Please enter number 2.\"));\r\n\tvar num3 = Number(prompt(\"Please enter number 3.\"));\r\n\r\n\t\tif(num1 >= num2 && num2 >= num3) {\r\n\t\t\tdocument.write(num3 + \", \" + num2 + \", \" + num1);\r\n\t\t}\r\n\r\n\t\telse if(num2 >= num3 && num3 >= num1) {\r\n\t\t\tdocument.write(num1 + \", \" + num3 + \", \" + num2);\r\n\t\t}\r\n\r\n\t\telse if(num3 >= num1 && num1 >=num2) {\r\n\t\t\tdocument.write(num2 + \", \" + num1 + \", \" + num3);\r\n\t\t}\r\n\r\n\t\telse if(num1 >= num3 && num3 >= num2) {\r\n\t\t\tdocument.write(num2 + \", \" + num3 + \", \" + num1);\r\n\t\t}\r\n\r\n\t\telse if(num2 >= num1 && num1 >= num3) {\r\n\t\t\tdocument.write(num3 + \", \" + num1 + \", \" + num2);\r\n\t\t}\r\n\r\n\t\telse {\r\n\t\t\tdocument.write(num1 + \", \" + num2 + \", \" + num3);\r\n\t\t}\r\n\t\r\n\trefreshIt();\r\n}", "function game() {\n let score = 0;\n\n for (let i = 0; i < 5; i++) {\n console.log(`Current round: ${i + 1}`);\n let userInput = getUserInput();\n let compInput = genCompInput();\n let result = gameLogic(userInput, compInput);\n console.log(result);\n if (result === 'You won the game.') {\n score += 1;\n console.log(`${userInput} beats ${compInput}`);\n } else if (result === 'You lost the game.') {\n score -= 1;\n console.log(`${compInput} beats ${userInput}`);\n } else {\n console.log(`You and computer both selected ${userInput}.`);\n }\n }\n if (score > 0) {\n console.log('You are the winner.');\n } else if (score < 0) {\n console.log('Computer is the winner');\n } else {\n console.log('Its a tie.');\n }\n}", "function scoringLogic(score){\n\n if (score > 20 && score < 40) {\n dropRate = 30\n wallIncreaseSpeed = 0.3\n dropBallSpeed = 3\n }\n else if (score > 40 && score < 60) {\n dropRate = 20\n wallIncreaseSpeed = 0.5\n dropBallSpeed = 4\n }\n else if (score > 60 && score < 80){\n dropRate = 15\n wallIncreaseSpeed = 0.7\n dropBallSpeed = 5\n }\n else if (score > 80 && score < 100){\n dropRate = 15\n wallIncreaseSpeed = 0.8\n dropBallSpeed = 5\n }\n else if (score > 100){\n dropRate = 10\n wallIncreaseSpeed = 1.2\n dropBallSpeed = 5\n }\n}", "function displayScore()\n{\n\tconsole.log(\"Time taken: \" + Math.floor(timeTaken/60));\n\tconsole.log(\"Stars: \" + inventory[0][4] + \" picked up.\");\n\tconsole.log(\"Bombs: \" + inventory[1][4] + \" picked up, \" + inventory[1][5] + \" used.\");\n\tconsole.log(\"Lives: \" + inventory[3][4] + \" picked up, \" + inventory[3][5] + \" used.\");\n}", "function submitScores() {\n scoresSubmissions = JSON.parse(localStorage.getItem(\"LastScoreBoard\")); // get LastScoreBoard from local storage and parse it\n if (scoresSubmissions == undefined) {\n // if there's nothing in local storage for it\n scoresSubmissions = []; // set it to an empty array\n }\n if (\n scoresDiv.classList.contains(\"hidden\") &&\n !qz11Div.classList.contains(\"hidden\") // make sure the Score Tally div is the one currently displayed\n ) {\n currentInitials = initialsInputField.value.toUpperCase(); // set the currentInitials var to the current initials/score submission and convert to UpperCase\n if (initialsInputField.value !== \"\") {\n let scoresObjectNext = {\n weighted: weightedScore,\n numCorrect: correctCount,\n timeLeft: finalTimeRemaining,\n initials: currentInitials,\n }; // create an object that fills the currect submission's weighted score, # correct, time left, and initials\n scoresSubmissions.push(scoresObjectNext); // push the new object into the scoresSubmissions array\n }\n initialsInputField.value = \"\"; // Reset initials textfield for other quiz submissions\n }\n function compare(a, b) {\n // comparison function to act on the scoresSubmissions sort that follows the function\n const scoreA = a.weighted; // set the weighted key's value of a to scoreA\n const scoreB = b.weighted; // set the weighted key's value of b to scoreB\n let comparison = 0; // set comparison var to 0 for starters, if the values are equal to each other, the sort order stays the same.\n if (scoreA > scoreB) {\n // if a > b, return 1 => the larger value will come after the smaller (order smallest to largest)\n comparison = -1; // typically this is reversed (= 1 usually), but multiplied by neg. 1 here (e.g. * -1) to sort largest to smallest.\n } else if (scoreA < scoreB) {\n // if a < b, return -1 => the larger value will come before the smaller (order largest to smallest)\n comparison = 1; // typically this is reversed (= 1 usually), but multiplied by neg. 1 here (e.g. * -1) to sort largest to smallest.\n }\n return comparison;\n }\n scoresSubmissions.sort(compare); // then sort the array (order of elements in object allows for table to be populated in correct order)\n localStorage.setItem(\"LastScoreBoard\", JSON.stringify(scoresSubmissions)); // set the scoreSubmissions array to local storage\n qz11Div.classList.add(\"hidden\"); // hides the score tally/results div\n scoresDiv.classList.remove(\"hidden\"); // displays the score board\n for (i = 0; i < scoresSubmissions.length; i++) {\n // run a loop for all the scores submissions stored in local storage\n let scoresTableRow = document.createElement(\"tr\"); // create a row element\n scoresTableRow.innerHTML =\n \"<td><strong>\" +\n (i + 1) +\n \"</strong></td><td><strong>\" +\n scoresSubmissions[i].initials +\n \"</strong></td><td><strong>\" +\n scoresSubmissions[i].numCorrect +\n \"</strong></td><td>\" +\n scoresSubmissions[i].timeLeft +\n \"</strong></td><td>\" +\n scoresSubmissions[i].weighted +\n \"</strong></td>\"; // make the row's inner HTML align with the col info and headers\n scoresTableBody.appendChild(scoresTableRow); // add the row to the table\n }\n}", "function scoreChangeHandler(minScore, highScore, step) {\r\n $('input[type=number]').change(function () {\r\n var value = $(this).val();\r\n \r\n // round the value to the closest step multiplication integer\r\n value = (Math.round((Math.round(value)) / step)) * step;\r\n \r\n // make sure the input stays within allowed range\r\n $(this).val(keepInRange(minScore, highScore, value));\r\n\r\n // calculate all scores for this application\r\n calculateScores();\r\n });\r\n}", "function generatePick(ranking = 1) {\n let num = Math.floor(Math.random() * 1000);\n// let ranking = document.querySelector(\"#firstRanking\").value\n\n//if finish with the worst record\n\n if (ranking == 1) {\n if (num >= 0 && num < 141) {\n return \"<strong>1</strong>\";\n }\n if (num > 140 && num < 274) {\n return 2;\n }\n if (num > 273 && num < 401) {\n return 3;\n }\n if (num > 400 && num < 521) {\n return 4;\n }\n if (num > 520 && num < 1000) {\n return 5;\n }\n\n }\n\n//if finish with the 2nd-worst record\n\n if (ranking == 2) {\n if (num >= 0 && num < 141) {\n return \"<strong>1</strong>\";\n }\n if (num > 140 && num < 274) {\n return 2;\n }\n if (num > 273 && num < 401) {\n return 3;\n }\n if (num > 400 && num < 521) {\n return 4;\n }\n if (num > 520 && num < 799) {\n return 5;\n }\n if (num > 798 && num < 1000) {\n return 6;\n }\n\n }\n\n//if finish with the 3rd-worst record\n if (ranking == 3) {\n if (num >= 0 && num < 141) {\n return \"<strong>1</strong>\";\n }\n if (num > 140 && num < 274) {\n return \"<strong>2</strong>\";\n }\n if (num > 273 && num < 401) {\n return 3;\n }\n if (num > 400 && num < 521) {\n return 4;\n }\n if (num > 520 && num < 669) {\n return 5;\n }\n if (num > 668 && num < 929) {\n return 6;\n }\n if (num > 928 && num < 1000) {\n return 7;\n }\n\n }\n\n//4th\n if (ranking == 4) {\n if (num >= 0 && num < 125) {\n return \"<strong>1</strong>\";\n }\n if (num > 124 && num < 247) {\n return \"<strong>2</strong>\";\n }\n if (num > 246 && num < 366) {\n return \"<strong>3</strong>\";\n }\n if (num > 365 && num < 481) {\n return 4;\n }\n if (num > 480 && num < 553) {\n return 5;\n }\n if (num > 552 && num < 810) {\n return 6;\n }\n if (num > 809 && num < 977) {\n return 7;\n }\n if (num > 976 && num < 1000) {\n return 8;\n }\n\n }\n\n\n//5th\n if (ranking == 5) {\n if (num >= 0 && num < 105) {\n return \"<strong>1</strong>\";\n }\n if (num > 104 && num < 210) {\n return \"<strong>2</strong>\";\n }\n if (num > 209 && num < 316) {\n return \"<strong>3</strong>\";\n }\n if (num > 315 && num < 421) {\n return \"<strong>4</strong>\";\n }\n if (num > 420 && num < 443) {\n return 5;\n }\n if (num > 442 && num < 639) {\n return 6;\n }\n if (num > 638 && num < 906) {\n return 7;\n }\n if (num > 905 && num < 993) {\n return 8;\n }\n if (num > 992 && num < 1000) {\n return 9;\n }\n\n }\n\n\n//6th\n if (ranking == 6) {\n if (num >= 0 && num < 90) {\n return \"<strong>1</strong>\";\n }\n if (num > 89 && num < 182) {\n return \"<strong>2</strong>\";\n }\n if (num > 181 && num < 276) {\n return \"<strong>3</strong>\";\n }\n if (num > 275 && num < 372) {\n return \"<strong>4</strong>\";\n }\n if (num > 371 && num < 458) {\n return 6;\n }\n if (num > 457 && num < 756) {\n return 7;\n }\n if (num > 755 && num < 961) {\n return 8;\n }\n if (num > 960 && num < 998) {\n return 9;\n }\n if (num > 997 && num < 1000) {\n return 10;\n }\n\n }\n\n\n\n//7th\n if (ranking == 7) {\n if (num >= 0 && num < 75) {\n return \"<strong>1</strong>\";\n }\n if (num > 74 && num < 153) {\n return \"<strong>2</strong>\";\n }\n if (num > 152 && num < 234) {\n return \"<strong>3</strong>\";\n }\n if (num > 233 && num < 319) {\n return \"<strong>4</strong>\";\n }\n if (num > 318 && num < 516) {\n return 7;\n }\n if (num > 515 && num < 857) {\n return 8;\n }\n if (num > 856 && num < 986) {\n return 9;\n }\n if (num > 985 && num < 1000) {\n return 10;\n }\n\n }\n\n\n\n// 8th\n if (ranking == 8) {\n if (num >= 0 && num < 60) {\n return \"<strong>1</strong>\";\n }\n if (num > 59 && num < 123) {\n return \"<strong>2</strong>\";\n }\n if (num > 122 && num < 190) {\n return \"<strong>3</strong>\";\n }\n if (num > 189 && num < 262) {\n return \"<strong>4</strong>\";\n }\n if (num > 261 && num < 607) {\n return 8;\n }\n if (num > 606 && num < 928) {\n return 9;\n }\n if (num > 927 && num < 995) {\n return 10;\n }\n if (num > 994 && num < 1000) {\n return 11;\n }\n\n }\n\n\n//fix 9th\n if (ranking == 9) {\n if (num >= 0 && num < 45) {\n return \"<strong>1</strong>\";\n }\n if (num > 44 && num < 93) {\n return \"<strong>2</strong>\";\n }\n if (num > 92 && num < 145) {\n return \"<strong>3</strong>\";\n }\n if (num > 144 && num < 202) {\n return \"<strong>4</strong>\";\n }\n if (num > 201 && num < 709) {\n return 9;\n }\n if (num > 708 && num < 968) {\n return 10;\n }\n if (num > 967 && num < 998) {\n return 11;\n }\n if (num > 997 && num < 1000) {\n return 12;\n }\n\n }\n\n\n//fix 10th\n if (ranking == 10) {\n if (num >= 0 && num < 30) {\n return \"<strong>1</strong>\";\n }\n if (num > 29 && num < 63) {\n return \"<strong>2</strong>\";\n }\n if (num > 62 && num < 99) {\n return \"<strong>3</strong>\";\n }\n if (num > 98 && num < 139) {\n return \"<strong>4</strong>\";\n }\n if (num > 138 && num < 798) {\n return 10;\n }\n if (num > 797 && num < 988) {\n return 11;\n }\n if (num > 987 && num < 1000) {\n return 12;\n }\n }\n\n\n//11th\n if (ranking == 11) {\n if (num >= 0 && num < 20) {\n return \"<strong>1</strong>\";\n }\n if (num > 19 && num < 42) {\n return \"<strong>2</strong>\";\n }\n if (num > 41 && num < 66) {\n return \"<strong>3</strong>\";\n }\n if (num > 65 && num < 94) {\n return \"<strong>4</strong>\";\n }\n if (num > 93 && num < 870) {\n return 11;\n }\n if (num > 869 && num < 996) {\n return 12;\n }\n if (num > 995 && num < 1000) {\n return 13;\n }\n }\n\n\n//12th\n if (ranking == 12) {\n if (num >= 0 && num < 15) {\n return \"<strong>1</strong>\";\n }\n if (num > 14 && num < 32) {\n return \"<strong>2</strong>\";\n }\n if (num > 31 && num < 51) {\n return \"<strong>3</strong>\";\n }\n if (num > 50 && num < 72) {\n return \"<strong>4</strong>\";\n }\n if (num > 71 && num < 933) {\n return 12;\n }\n if (num > 932 && num < 999) {\n return 13;\n }\n if (num > 998 && num < 1000) {\n return 14;\n }\n }\n\n\n//13th\n if (ranking == 13) {\n if (num >= 0 && num < 10) {\n return \"<strong>1</strong>\";\n }\n if (num > 9 && num < 21) {\n return \"<strong>2</strong>\";\n }\n if (num > 20 && num < 33) {\n return \"<strong>3</strong>\";\n }\n if (num > 32 && num < 47) {\n return \"<strong>4</strong>\";\n }\n if (num > 46 && num < 976) {\n return 13;\n }\n if (num > 975 && num < 1000) {\n return 14;\n }\n }\n \n\n//14th \nif (ranking == 14) {\n if (num >= 0 && num < 5) {\n return \"<strong>1</strong>\";\n }\n if (num > 4 && num < 11) {\n return \"<strong>2</strong>\";\n }\n if (num > 10 && num < 17) {\n return \"<strong>3</strong>\";\n }\n if (num > 16 && num < 24) {\n return \"<strong>4</strong>\";\n }\n if (num > 23 && num < 1000) {\n return 14;\n }\n }\n}", "function runProgram() {\n let word = initialPrompt();\n let scorer = scorerPrompt();\n\n //calls scoring function on word depending on which score method was selected\n if (scorer === \"0\") {\n console.log(`Score for ${word}: ${scoringAlgorithms[0].scoringFunction(word)}`);\n } else if (scorer === \"1\") {\n console.log(`Score for ${word}: ${scoringAlgorithms[1].scoringFunction(word)}`);\n } else if (scorer === \"2\") {\n console.log(`Score for ${word}: ${scoringAlgorithms[2].scoringFunction(word)}`);\n }\n}", "function getGPA(score) {\n return Math.min(score / 3.0, 4.0);\n}", "function scoreChangeHandlerSprout(minScore, maxScore, step) {\r\n $('input[type=number]').change(function () {\r\n var value = $(this).val();\r\n \r\n // round the value to the closest step multiplication integer\r\n value = (Math.round((Math.round(value)) / step)) * step;\r\n \r\n // make sure the input stays within allowed range\r\n value = keepInRange(minScore, maxScore, value);\r\n $(this).val(value);\r\n\r\n calculateScoresMaps(RATIOS_SPROUT, CATEGORIES_RATIO_SPROUT, CATEGORIES_SPROUT,\"input[name$=_1][type=number]\", 2, \"total_score_1\");\r\n calculateScoresMaps(RATIOS_SPROUT, CATEGORIES_RATIO_SPROUT, CATEGORIES_SPROUT,\"input[name$=_2][type=number]\", 2, \"total_score_2\");\r\n calculateScoresMaps(RATIOS_SPROUT, CATEGORIES_RATIO_SPROUT, CATEGORIES_SPROUT,\"input[name$=_3][type=number]\", 2, \"total_score_3\");\r\n calculateRatingMean(RATIOS_SPROUT);\r\n });\r\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function handling data from SensorEventListener for Motion data, such as Acceleration (with and without gravity included) and Rotation (Gyroscope)
function deviceMotionHandler(eventData) { var info, xyz = "[X, Y, Z]"; // Update the provided HTML file to give visual feedback (optional, nice to have during development) // Grab the acceleration from the results var acceleration = eventData.acceleration; info = xyz.replace("X", acceleration.x && acceleration.x.toFixed(3)); info = info.replace("Y", acceleration.y && acceleration.y.toFixed(3)); info = info.replace("Z", acceleration.z && acceleration.z.toFixed(3)); document.getElementById("moAccel").innerHTML = info; // these variables are set on EVERY new data set arrival, and are used in the bellow motion capture functions z_acceleration = parseFloat(acceleration.z); y_acceleration = parseFloat(acceleration.y); // Grab the acceleration including gravity from the results acceleration = eventData.accelerationIncludingGravity; info = xyz.replace("X", acceleration.x && acceleration.x.toFixed(3)); info = info.replace("Y", acceleration.y && acceleration.y.toFixed(3)); info = info.replace("Z", acceleration.z && acceleration.z.toFixed(3)); document.getElementById("moAccelGrav").innerHTML = info; // Grab the rotation rate from the results var rotation = eventData.rotationRate; info = xyz.replace("X", rotation.alpha && rotation.alpha.toFixed(3)); info = info.replace("Y", rotation.beta && rotation.beta.toFixed(3)); info = info.replace("Z", rotation.gamma && rotation.gamma.toFixed(3)); document.getElementById("moRotation").innerHTML = info; // // Grab the refresh interval from the results info = eventData.interval; document.getElementById("moInterval").innerHTML = info; }
[ "function deviceOrientationHandler (eventData) {\n\tvar info, xyz = \"[X, Y, Z]\";\n\n\t// Update the provided HTML file to give visual feedback (optional, nice to have during development)\n\n\t// Grab the acceleration from the results\n\tinfo = xyz.replace(\"X\", eventData.alpha && eventData.alpha.toFixed(3));\n\tinfo = info.replace(\"Y\", eventData.beta && eventData.beta.toFixed(3));\n\tinfo = info.replace(\"Z\", eventData.gamma && eventData.gamma.toFixed(3));\n\tdocument.getElementById(\"devOrientation\").innerHTML = info;\n\n\t// this variable will be set on every orientation data set arrival and is used in the motion capture functions bellow;\n\t// ATTENTION: Values are not floats, and NEED to be parsed as such for the motion capture functions to work;\n\t// in this example, this parsing is done INSIDE the motion capture functions....\n\t// could've had this the easy way, but did not see my error in time.\n\tdeviceOrientation = [eventData.alpha, eventData.beta, eventData.gamma];\n\n}", "on_sensor_update(sensor){\n // sensor.pitch\n // sensor.roll\n }", "function initGyro() {\n var listYAccelerations = [],\n noise = false,\n lastXA = false;\n\n // set frequency of measurements in milliseconds\n // some more comments\n gyro.frequency = 10;\n\n gyro.startTracking(function(o) {\n var a = o.x.toFixed(3),\n t = new Date(),\n timestep = t - lastT,\n range = 10;\n\n var smoothedA;\n\n // if (parseFloat(a) <= 0.1 && parseFloat(a) >= -0.1) {\n // a = 0;\n // lastVelocity = 0;\n // }\n // some comments\n if (values.length >= range) {\n\n smoothedA = smooth(a, range);\n\n if (parseFloat(smoothedA) <= 0.1 && parseFloat(smoothedA) >= -0.1) {\n smoothedA = 0;\n lastVelocity = 0;\n }\n\n lastT = t;\n lastPosition = position(lastPosition, lastVelocity, smoothedA,\n timestep);\n\n lastVelocity = velocity(lastVelocity, smoothedA, timestep);\n\n xA.innerHTML = smoothedA;\n xV.innerHTML = lastVelocity;\n xP.innerHTML = lastPosition;\n\n }\n values.push(a);\n });\n }", "function GyroPositionSensorVRDevice() {\n // Subscribe to deviceorientation events.\n window.addEventListener('deviceorientation', this.onDeviceOrientationChange.bind(this));\n window.addEventListener('orientationchange', this.onScreenOrientationChange.bind(this));\n this.deviceOrientation = null;\n this.screenOrientation = window.orientation;\n\n // Helper objects for calculating orientation.\n this.finalQuaternion = new THREE.Quaternion();\n this.deviceEuler = new THREE.Euler();\n this.screenTransform = new THREE.Quaternion();\n // -PI/2 around the x-axis.\n this.worldTransform = new THREE.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));\n}", "function hasGyroscope(event) {\n dojo.disconnect(compassTestHandle);\n if (event.webkitCompassHeading !== undefined || event.alpha != null) {\n hasCompass = true;\n } else {\n hasCompass = false;\n }\n orientationChangeHandler();\n }", "formatMotionData(obj){\n var orientationX = {label:'orientationX',values:[]},\n orientationY = {label:'orientationY',values:[]},\n orientationZ = {label:'orientationZ',values:[]},\n accelerationX = {label:'accelerationX',values:[]},\n accelerationY = {label:'accelerationY',values:[]},\n accelerationZ = {label:'accelerationZ',values:[]},\n speed = {label:'speed',values:[]},\n distance = {label:'distance',values:[]}, earliestTime, skipsTime, latestTime;\n\n var totals = {\n s:0, d:0\n };\n var curVals = {};\n try{\n var newObj = obj[0];\n if(newObj){\n var previousTime;\n var avg = 0;\n for(let val in newObj){\n if(!isNaN(val)){\n var curVal = newObj[val];\n if(curVal){\n curVals = curVal;\n curVal.hasOwnProperty('speed') && speed.values.push({\"x\":this.formatTime(parseInt(val,10)), \"y\":curVal['speed']}) && !isNaN(curVal['speed']) && (totals.s += curVal['speed']);\n curVal.hasOwnProperty('ox') && orientationX.values.push({\"x\":this.formatTime(parseInt(val,10)), \"y\":curVal['ox']});\n curVal.hasOwnProperty('oy') && orientationY.values.push({\"x\":this.formatTime(parseInt(val,10)), \"y\":curVal['oy']});\n curVal.hasOwnProperty('oz') && orientationZ.values.push({\"x\":this.formatTime(parseInt(val,10)), \"y\":curVal['oz']});\n curVal.hasOwnProperty('ax') && accelerationX.values.push({\"x\":this.formatTime(parseInt(val,10)), \"y\":curVal['ax']});\n curVal.hasOwnProperty('ay') && accelerationY.values.push({\"x\":this.formatTime(parseInt(val,10)), \"y\":curVal['ay']});\n curVal.hasOwnProperty('az') && accelerationZ.values.push({\"x\":this.formatTime(parseInt(val,10)), \"y\":curVal['az']});\n curVal.hasOwnProperty('distance') && distance.values.push({\"x\":this.formatTime(parseInt(val,10)), \"y\":curVal['distance']}) && !isNaN(curVal['distance']) && (totals.d += curVal['distance']);\n if(parseInt(val,10) < earliestTime || !earliestTime){\n earliestTime = parseInt(val,10);\n }\n if(parseInt(val,10) > latestTime || !latestTime){\n latestTime = parseInt(val,10);\n }\n if(parseInt(val,10) - previousTime > 10000){\n skipsTime = true;\n }\n previousTime = parseInt(val,10);\n }\n }\n }\n }\n }\n catch(e){\n console.error(e);\n }\n var data = {\n skipsTime:skipsTime,\n acceleration:[accelerationX,accelerationY,accelerationZ],\n speed:[speed],\n distance:[distance],\n orientation:[orientationX,orientationY,orientationZ],\n currentValues:curVals\n };\n data['acceleration'].earliestTime = earliestTime;\n data['acceleration'].latestTime = latestTime;\n data['acceleration'].skipsTime = skipsTime;\n data['speed'].earliestTime = earliestTime;\n data['speed'].latestTime = latestTime;\n data['speed'].skipsTime = skipsTime;\n data['speed'].avg = totals.s ? totals.s / speed.values.length : 0;\n data['distance'].earliestTime = earliestTime;\n data['distance'].latestTime = latestTime;\n data['distance'].skipsTime = skipsTime;\n data['distance'].avg = totals.d ? totals.d / speed.values.length : 0;\n data['orientation'].earliestTime = earliestTime;\n data['orientation'].latestTime = latestTime;\n data['orientation'].skipsTime = skipsTime;\n return data;\n }", "gyroCoarseAlign(channel, value) {\n const sign = value & 0x4000 ? -1 : +1;\n const cduPulses = sign * (value & 0x3fff);\n\n if (channel === 124) {\n // 0174\n this.modifyGimbalAngle([cduPulses * CA_ANGLE, 0, 0]);\n } else if (channel === 125) {\n // 0175\n this.modifyGimbalAngle([0, cduPulses * CA_ANGLE, 0]);\n } else if (channel === 126) {\n // 0176\n this.modifyGimbalAngle([0, 0, cduPulses * CA_ANGLE]);\n }\n }", "function registerEventHandlers() {\n // If there is an orientation sensor present on the device, register for notifications\n if (oOrientationSensor != null) {\n oOrientationSensor.addEventListener(\"orientationchanged\", orientationSensor_orientationChanged);\n }\n}", "function handleOrientationChange() {\n console.log('orientationchange')\n window.addEventListener('resize', handleResize, { once: true });\n }", "gyroFineAlign(_channel, value) {\n const gyroSignMinus = value & 0x4000;\n const gyroSelectionA = value & 0x2000;\n const gyroSelectionB = value & 0x1000;\n const sign = gyroSignMinus ? -1 : +1;\n const gyroPulses = sign * (value & 0x07ff);\n\n if (!gyroSelectionA && gyroSelectionB) {\n this.modifyGimbalAngle([gyroPulses * FA_ANGLE, 0, 0]);\n }\n if (gyroSelectionA && !gyroSelectionB) {\n this.modifyGimbalAngle([0, gyroPulses * FA_ANGLE, 0]);\n }\n if (gyroSelectionA && gyroSelectionB) {\n this.modifyGimbalAngle([0, 0, gyroPulses * FA_ANGLE]);\n }\n }", "accelerationBall(){\n this._ball.movement.deltaY -= 1 ;\n if (this._ball.movement.deltaX < 0){\n this._ball.movement.deltaX -=1 ;\n }else{\n this._ball.movement.deltaX += 1;\n }\n }", "modifyGimbalAngle(delta) {\n for (let axis = 0; axis < 3; axis++) {\n if (delta[axis]) {\n // ---- Calculate New Angle ----\n this.imuAngle[axis] = IMU.adjust(\n this.imuAngle[axis] + delta[axis],\n 0,\n 2 * Math.PI\n );\n\n // ---- Calculate Delta between the new Angle and already feeded IMU Angle ----\n const dx = IMU.adjust(\n this.imuAngle[axis] - this.pimu[axis],\n -Math.PI,\n Math.PI\n );\n\n // ---- Feed yaAGC with the new Angular Delta ----\n const sign = dx > 0 ? +1 : -1;\n const n = Math.floor(Math.abs(dx) / ANGLE_INCR);\n this.pimu[axis] = IMU.adjust(\n this.pimu[axis] + sign * ANGLE_INCR * n,\n 0,\n 2 * Math.PI\n );\n\n let cdu = this.peek(26 + axis); // read CDU counter (26 = 0x32 = CDUX)\n cdu = cdu & 0x4000 ? -(cdu ^ 0x7fff) : cdu; // converts from ones-complement to twos-complement\n cdu += sign * n; // adds the number of pulses\n this.poke(26 + axis, cdu < 0 ? -cdu ^ 0x7fff : cdu); // converts back to ones-complement and writes the counter\n }\n }\n }", "function parseSensorPacket(packet) {\n let sensor = {};\n\n let isMinew = (packet.substr(26,4) === 'e1ff');\n let isCodeBlue = (packet.substr(24,6) === 'ff8305');\n\n if(isMinew) {\n let isTemperatureHumidity = (packet.substr(38,4) === 'a101');\n let isVisibleLight = (packet.substr(38,4) === 'a102');\n let isAcceleration = (packet.substr(38,4) === 'a103');\n\n if(isTemperatureHumidity) {\n sensor.temperature = (parseInt(packet.substr(44, 2), 16) +\n parseInt(packet.substr(46, 2), 16) / 256).toFixed(1);\n sensor.humidity = (parseInt(packet.substr(48, 2), 16) +\n parseInt(packet.substr(50, 2), 16) / 256).toFixed(1);\n }\n else if(isVisibleLight) {\n sensor.visibleLight = (packet.substr(44, 2) === '01');\n }\n else if(isAcceleration) {\n sensor.acceleration = [];\n sensor.accelerationMagnitude = 0;\n sensor.acceleration.push(fixedPointToDecimal(packet.substr(44, 4)));\n sensor.acceleration.push(fixedPointToDecimal(packet.substr(48, 4)));\n sensor.acceleration.push(fixedPointToDecimal(packet.substr(52, 4)));\n sensor.acceleration.forEach(function(magnitude, index) {\n sensor.accelerationMagnitude += (magnitude * magnitude);\n sensor.acceleration[index] = magnitude.toFixed(2);\n });\n sensor.accelerationMagnitude = Math.sqrt(sensor.accelerationMagnitude)\n .toFixed(2);\n }\n }\n else if(isCodeBlue) {\n let isPuckyActive = (packet.substr(30,2) === '02');\n\n if(isPuckyActive) {\n sensor.temperature = ((parseInt(packet.substr(38,2), 16) / 2) - 40)\n .toFixed(1);\n sensor.lightPercentage = Math.round((100 / 0xff) * \n parseInt(packet.substr(40,2), 16));\n sensor.capSensePercentage = Math.round((100 / 0xff) * \n parseInt(packet.substr(42,2), 16));\n sensor.magneticField = [];\n sensor.magneticField.push(toMagneticField(packet.substr(44,4)));\n sensor.magneticField.push(toMagneticField(packet.substr(48,4)));\n sensor.magneticField.push(toMagneticField(packet.substr(52,4)));\n }\n }\n\n return sensor;\n}", "loop () {\n if (!this.shouldLoop) {\n return\n }\n\n window.requestAnimationFrame(this.loop.bind(this))\n\n // When not clicking the orientation values can be rounded more, so that\n // less messages are sent.\n const rounding = this.isClicking ? 100 : 25\n const orientation = this.gyroscope.getOrientation(rounding)\n\n this.gyroplane.updateOrientation(orientation)\n\n try {\n const coordinates = this.gyroplane.getScreenCoordinates()\n this.lazy.update(coordinates)\n } catch (e) {\n this.gyroplane.init()\n }\n\n // Get the lazy coordinates.\n const { x, y } = this.lazy.getBrushCoordinates()\n\n // Set the new values to the array.\n this.intArray.set([\n Math.round(x),\n Math.round(y),\n this.isClicking ? 1 : 0,\n Math.round(this.touch.y)\n ], 0)\n\n // Only send the data if it actually has changed.\n if (\n this.prevArray[0] !== this.intArray[0] ||\n this.prevArray[1] !== this.intArray[1] ||\n this.prevArray[2] !== this.intArray[2] ||\n this.prevArray[3] !== this.intArray[3]\n ) {\n this._onDataChange(this.buffer)\n this.prevArray.set(this.intArray, 0)\n }\n }", "accelerate() {\n\t\tthis.velocity.add(this.acceleration)\n\t}", "handleGSArmChanged() {\n const isArmed = this._inputDataStates.gs_arm.state;\n if (isArmed) {\n this.currentVerticalArmedStates = [VerticalNavModeState.GS];\n }\n else if (this.currentVerticalArmedStates.includes(VerticalNavModeState.GS)) {\n this.currentVerticalArmedStates = [];\n }\n }", "function motionEstimation(prevFrame, currentFrame, width, height) {\n // convert frames to grayscale\n const prevPyramidT = convertToGrayScale(prevFrame, width, height);\n const currentPyramidT = convertToGrayScale(currentFrame, width, height);\n\n const prevFeatures = [];\n const currentFeatures = [];\n // detect features for previous frame\n const featuresCount = detectFeatures(prevPyramidT, prevFeatures, width, height);\n\n // klt tracker - tracks features in previous img and maps them to current\n const status = [];\n jsfeat.optical_flow_lk.track(\n prevPyramidT, currentPyramidT, prevFeatures, currentFeatures,\n featuresCount, 15, 30, status, 0.01, 0.0001,\n );\n\n // create homography kernel\n const essentialMatrix = new jsfeat.matrix_t(3, 3, jsfeat.F32_t | jsfeat.C1_t);\n\n // returns 3x3 matrix\n const eMatrix = computeEssential(prevFeatures, currentFeatures);\n\n // convert to matrix_t format\n essentialMatrix.data = eMatrix[0].concat(eMatrix[1].concat(eMatrix[2]));\n\n // return rotation and translation calculated from essentialMatrix\n return recoverPose(essentialMatrix);\n}", "function measurement_handler(event){\n\tpointer_select_handler(event);\n}", "function onStartSensor(sensor){\n\t\tconsole.log(\"Sensor\" + sensor + \"start\");\n\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Given the epoch (in millis) at the last inventory update, update the updatedTimeSpan to show the number of elapsed minutes since it was updated.
function updatedTimeSpan(epochAtLastUpdate) { var e = document.getElementById('updatedTimeSpan'); var nowEpoch = (new Date).getTime(); e.innerHTML = calculateMinutesFromMillis(nowEpoch - epochAtLastUpdate); }
[ "function updateTimeElapsed() {\n var time = formatTime(Math.round(video.currentTime));\n timeElapsed.innerText = formatTimeHumanize(time);\n timeElapsed.setAttribute('datetime', `${time.hours}h ${time.minutes}m ${time.seconds}s`);\n }", "function updateTimer() {\n //get time since last update\n var timeDiff = Date.now() - lastUpdateTime;\n\n //was long enough ago\n if (timeDiff > updateIntervalTime) {\n //update now, will reset timer\n updateList();\n\n //set to start again in 30 seconds\n setTimeout(updateTimer, updateIntervalTime);\n } else {\n //try again in how much time is left until 30 seconds is reached\n setTimeout(updateTimer, updateIntervalTime - timeDiff);\n }\n}", "async getUpdateTime() {\n const [match] = await this.client('lastUpdate').select('*');\n return match\n ? match.time\n : 0;\n }", "function update_timer() {\n seconds = Math.floor(game.time.time / 1000);\n milliseconds = Math.floor(game.time.time);\n elapsed = game.time.time - starting_time;\n}", "function updateDuration() {\n\tconst deltaS = (dateInput(\"dateEnd\") + timeInput(\"timeEnd\") - (dateInput(\"dateStart\") + timeInput(\"timeStart\"))) / 1000;\n\tconst round = 3600 / parseInt(ele(\"timeResolutionsInput\").value);\n\tconst duration = Math.ceil(deltaS / round) * round;\n\tconst hours = Math.floor(duration / 3600);\n\tconst minutes = Math.floor((duration - hours * 3600) / 60);\n\tconst seconds = Math.floor(duration - hours * 3600 - minutes * 60);\n\tele(\"duration\").innerText = `${hours}:${pad(minutes, 2)}:${pad(seconds, 2)}`;\n}", "function UpdateTimer() {\n playSound();\n \n var strTmp = toMinutes(TotalSeconds).split(\":\");\n \n if (strTmp[2])\n var strtime = pad(strTmp[0], 2)+\":\"+pad(strTmp[1], 2)+\":\"+pad(strTmp[2], 2);\n else\n var strtime = pad(strTmp[0], 2)+\":\"+pad(strTmp[1], 2);\n \n Timer.innerHTML = strtime;\n $j('#roundsRemaining').html(pad(cycles, 2));\n \n if (workoutType == 2){ // Advanced\n $j('#repeatsRemaining').html(pad(repeat, 2));\n }\n \n if (totTimeRemaining <= 0){\n var tmpRes = \"00:00\";\n }else{\n var tmpRes = toMinutes(totTimeRemaining).split(\":\"); \n }\n \n if (tmpRes[0] && tmpRes[1]){\n if (tmpRes[2])\n $j('#totTimeRemaining').html(pad(tmpRes[0], 2)+\":\"+pad(tmpRes[1], 2)+\":\"+pad(tmpRes[2], 2)); \n else\n $j('#totTimeRemaining').html(pad(tmpRes[0], 2)+\":\"+pad(tmpRes[1], 2)); \n }\n else\n $j('#totTimeRemaining').html(\"00:00\");\n \n}", "calcRemainingTime() {\n return (Math.round((currentGame.endTime - Date.now()) / 100));\n }", "function onTimeUpdate(e) {\n var newTime = Math.floor(video.currentTime);\n if (newTime != timeInt) {\n timeInt = newTime;\n time_str = toTimeString(timeInt);\n updateTimeBar();\n }\n}", "function stopwatchUpdate(){\n\n rawTime += intervalRate\n stopwatchTime.innerHTML = formatTime(rawTime)\n}", "function timerUpdate() {\n // update display of timer on browser window\n var timeString = timerMilliSeconds / 1000;\n $(\"#timer\").text(timeString + \" seconds until next update\");\n}", "function time_since_last_update()\r\n{\r\n var last_update = localStorage.getItem(\"last_update\"); // Last update time\r\n last_update = last_update ? last_update : 0; // 0 if not yet stored\r\n\r\n return current_time() - last_update;\r\n}", "function displayTimeSinceUpdate(time) {\n time = Math.floor(time/60000);\n if (time<1) {\n return \"< 1 minute ago\";\n } else if (time > 60) {\n return \"> 1 hour ago\";\n } else if (time > 120) {\n return \"> 2 hours ago\";\n } else {\n return time.toString() + \" minutes ago\";\n }\n}", "get_respawn_time ()\n {\n let num_nearby = loot.players_in_cells[this.cell.x][this.cell.y].length;\n const adjacent_cells = loot.cell.GetAdjacentCells(this.cell.x, this.cell.y);\n\n // Get number of players near the lootbox\n for (let i = 0; i < adjacent_cells.length; i++)\n {\n num_nearby += loot.players_in_cells[adjacent_cells[i].x][adjacent_cells[i].y].length;\n }\n\n\n return Math.max(loot.config.respawn_times[this.type] / 2, loot.config.respawn_times[this.type] - (num_nearby * this.type * 0.5));\n }", "update() {\n let frameStart = (performance || Date).now();\n // track wall time for game systems that run when the ECS gametime\n // is frozen.\n let wallDelta = this.lastFrameStart != -1 ?\n frameStart - this.lastFrameStart :\n Constants.DELTA_MS;\n this.lastFrameStart = frameStart;\n // pre: start stats tracking\n this.updateStats.begin();\n // note: implement lag / catchup sometime later. need to measure\n // timing too if we want this.\n this.game.update(wallDelta, Constants.DELTA_MS);\n // post: tell stats done\n this.updateStats.end();\n // Pick when to run update again. Attempt to run every\n // `this.targetUpdate` ms, but if going too slow, just run as soon\n // as possible.\n let elapsed = (performance || Date).now() - frameStart;\n let nextDelay = Math.max(this.targetUpdate - elapsed, 0);\n setTimeout(update, nextDelay);\n }", "updateElapsedTime(){\n\t\tthis.props.updateElapsedTime(this.refs.audioElement.currentTime);\n\t}", "updateSystemTime(event) {\n\t\t// console.log(event);\n\t\tthis.stateSpace.systemTime = event.executionTime;\n\t}", "function updateShotClock () {\n\tvar printShotClockTime = '';\n\tif (CURRENT_SHOT_CLOCK_TIME === 0) {\n\t\tdocument.getElementById('buzzer').play();\n\t\tstopClock();\n\t}\n\tif (CURRENT_SHOT_CLOCK_TIME < SHOT_CLOCK_TIME_CUTOFF) {\n\t\t$('#shotclocktimer').css('color', 'red');\n\t}\n\tvar formattedShotClockTime = msToTime(CURRENT_SHOT_CLOCK_TIME);\n\tif (CURRENT_SHOT_CLOCK_TIME >= TIME_CUTOFF) {\n\t\t// Greater than TIME_CUTOFF\n\t\tprintShotClockTime = formattedShotClockTime[1] + ':' + formattedShotClockTime[2];\n\t} else {\n\t\t// Less than TIME_CUTOFF\n\t\tvar ms = formattedShotClockTime[3];\n\t\tms = ms / 100;\n\t\tprintShotClockTime = parseInt(formattedShotClockTime[2]) + '.' + ms;\n\t}\n\t$('#shotclocktimer').text(printShotClockTime);\n}", "getRemainingSecs() {\n return Math.floor(this.getRemaining() / 1000) + 1;\n }", "function _updateTimer(){\n _timeNow = Date.now();\n var $dt = (_timeNow-_timeThen);\n\n _delta = _delta + $dt; // accumulate delta time between trips, but not more than trip window\n _now = _now+_delta; // accumulate total time since start of timer\n _timeThen = _timeNow;\n\n // record the number of trip windows passed since last reset\n _passedTrips = Math.floor(_delta / _trip);\n\n // determine if timer tripped\n if(_delta > _trip){\n _isTripped = true;\n _timeNow = Date.now();\n // assign current value to the excess amount beyond tripping point,\n // reset the accumulation to whatever is less than the trip window\n _delta = _delta % _trip;\n _timeThen = Date.now();\n }\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Reverse comparator function for comparing timestamps of notes while sorting
function reverseCompareTimestamps(note1, note2) { if(note1.timestamp > note2.timestamp) return -1; if(note1.timestamp < note2.timestamp) return 1; return 0; }
[ "function noteCompareByTime(note1 , note2) {\n\n\tvar first_time = parseInt(note1.note_time);\n\tvar second_time = parseInt(note2.note_time);\n\n\tif (first_time < second_time) {\n\t\treturn -1;\n\t}\n\tif (first_time > second_time) {\n\t\treturn 1;\n\t}\n\treturn 0;\n\n}", "function sortNotes(){\n notesList.sort(function(a,b)\n {\n if(a.date < b.date)\n return 1;\n if(a.date > b.date)\n return -1;\n if(a.date == b.date)\n {\n if(a.id < b.id)\n return 1;\n if(a.id > b.id)\n return -1;\n }\n return 0;\n })\n console.log(\"posortowane\");\n}", "function allNotesSortedByChanged(): Array<TNote> {\n const projectNotes = DataStore.projectNotes.slice()\n const calendarNotes = DataStore.calendarNotes.slice()\n const allNotes = projectNotes.concat(calendarNotes)\n const allNotesSortedByDate = allNotes.sort(\n (first, second) => second.changedDate - first.changedDate,\n ) // most recent first\n return allNotesSortedByDate\n}", "function sortLectures(arr) {\n return arr.sort((a,b) => DateTime.fromFormat(a.date, 'yyyy-MM-dd hh:mm') - DateTime.fromFormat(b.date, 'yyyy-MM-dd hh:mm'));\n}", "sortBookmark() {\n let bookmarks = this.props.bookmarks.slice();\n if (this.state.sortby === 'addTime') {\n bookmarks.sort((a,b) => {\n return compareTime(a.addTime, b.addTime) ? 1 : -1;\n });\n return bookmarks;\n } else {\n bookmarks.sort((a,b) => {\n return ( a.currentChapterOrder > b.currentChapterOrder) ? 1 :\n (((a.currentChapterOrder === b.currentChapterOrder) &&\n ( a.scrollTop / a.scrollHeight > b.scrollTop / b.scrollHeight)) ? 1 :\n (( compareTime(a.addTime, b.addTime)) ? 1 : -1)); \n });\n return bookmarks;\n }\n }", "static pseudo_cmp(a, b) {\n if (a['$reql_type$'] === 'BINARY') {\n if (!('data' in a && 'data' in b)) {\n console.error(\"BINARY ptype doc lacking data field\", a, b);\n throw \"BINARY ptype doc lacking data field\";\n }\n const aData = rethinkdbGlobal.binary_to_string(a['data']);\n const bData = rethinkdbGlobal.binary_to_string(b['data']);\n return aData < bData ? -1 : aData > bData ? 1 : 0;\n }\n if (a['$reql_type$'] === 'TIME') {\n if (!('epoch_time' in a && 'epoch_time' in b)) {\n console.error(\"TIME ptype doc lacking epoch_time field\", a, b);\n throw \"TIME ptype doc lacking epoch_time field\";\n }\n // These are both numbers. And if they aren't, we'll just compare them.\n const aEpoch = a['epoch_time'];\n const bEpoch = b['epoch_time'];\n return aEpoch < bEpoch ? -1 : aEpoch > bEpoch ? 1 : 0;\n }\n console.error(\"pseudo_cmp logic error\", a, b);\n throw \"pseudo_cmp encountered unhandled type\";\n }", "function sortNotesByDate() {\n // red = most important\n // yellow = important\n // green = it can wait\n}", "static compare(first, second) {\n\t\tif(first.time>second.time) return 1;\n\t\telse if(first.time<second.time) return -1;\n\t\telse return 0;\n\t}", "function sortOpeningTimes(a, b){\n\treturn a.open.day - b.open.day;\n}", "sortSequence () {\n this.sequence.sort(function (a, b){\n return a.time.start - b.time.start;\n });\n }", "sortTrip () {\r\n this.recorded_trip.sort(function (x, y) {\r\n if (x.distance < y.distance) {\r\n return 1 // sorts each trip from highest(y) to lowest(x)\r\n }\r\n if (x.distance > y.distance) {\r\n return -1 // sorts each trip from highest(x) to lowest(y)\r\n } // x must equal to y\r\n return 0 // trip order will remain the same\r\n })\r\n }", "function sort_arrangements_by_time( arrangements ) {\n let result = arrangements;\n\n let sort_key_for_row = function(row) {\n let x = parseInt(row[2].split(\"-\")[0].split(\":\")[0]);\n x = x > 9 ? x : x + 12;\n\n return x;\n };\n\n result.sort(\n function (rowA, rowB) {\n return sort_key_for_row(rowA) - sort_key_for_row(rowB);\n }\n );\n\n return result;\n}", "sortTasks() {\n var tempTasks = this.taS.getTasks();\n tempTasks.sort(function(a,b){\n return a.deadline-b.deadline;\n });\n return tempTasks;\n }", "reverse() {\n const compareOriginial = this.compare;\n this.compare = (a, b) => compareOriginial(b, a);\n }", "function sortTweets(tweetList,sortOrder) {\n\tvar result;\n\tvar sortNum;\n\tif (sortOrder.toLowerCase() === 'descending') {\n\t\tsortNum = -1;\n\t} else {\n\t\tsortNum = 1;\n\t}\n\n\ttweetList.sort((tweet1,tweet2) => {\n\t\tvar time1 = moment(tweet1.created_at,'ddd MMM DD HH:mm:ss +SSSS YYYY');\n\t\tvar time2 = moment(tweet2.created_at,'ddd MMM DD HH:mm:ss +SSSS YYYY');\n\t\tif (time1.isAfter(time2)) {\n\t\t\tresult = 1 * sortNum;\n\t\t} else if (time1.isBefore(time2)) {\n\t\t\tresult = -1 * sortNum;\n\t\t}\telse {\n\t\t\tresult = 0;\n\t\t}\n\t\treturn result;\n\t});\n}", "function _ascendingCompare(first, second) {\n return first.position - second.position;\n }", "function sortComments() {\n comment_list.sort(function(x, y){\n return x.timestamp - y.timestamp;\n });\n if(comments_loaded) {\n displayComments();\n }\n}", "reverse() {\n console.debug('sort')\n\n // Sort playlist model\n this.items = this.items.reverse()\n\n // DEBUG\n if (Debug) { this.log() }\n }", "function sortByDuration(a, b) {\n var durA = a.get(\"end\").getTime() - a.get(\"start\").getTime();\n var durB = b.get(\"end\").getTime() - b.get(\"start\").getTime();\n return durA - durB;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Go to the last cell that is run or current if it is running. Note: This requires execution timing to be toggled on or this will have no effect.
function selectLastRunCell(notebook) { let latestTime = null; let latestCellIdx = null; notebook.widgets.forEach((cell, cellIndx) => { if (cell.model.type === 'code') { const execution = cell.model.metadata.get('execution'); if (execution && JSONExt.isObject(execution) && execution['iopub.status.busy'] !== undefined) { // The busy status is used as soon as a request is received: // https://jupyter-client.readthedocs.io/en/stable/messaging.html const timestamp = execution['iopub.status.busy'].toString(); if (timestamp) { const startTime = new Date(timestamp); if (!latestTime || startTime >= latestTime) { latestTime = startTime; latestCellIdx = cellIndx; } } } } }); if (latestCellIdx !== null) { notebook.activeCellIndex = latestCellIdx; } }
[ "changeCellRight() {\n const cells = this.get('cells');\n const hoverIndex = this.get('hoverIndex');\n const lastIndex = cells.length > 0 ? cells.length - 1 : 0;\n const isLoop = this.get('isLoop');\n const noSwitch = this.get('noSwitchRight');\n const inheritPosition = this.get('parentWindow.inheritPosition');\n\n if (hoverIndex === lastIndex) {\n if (isLoop) {\n this.set('hoverIndex', 0);\n this.trigger('cellDidChange', { direction: 'right' });\n } else {\n this.trigger('focusOnLastCell');\n\n if (!noSwitch) {\n this.get('frameService').trigger(\n 'rowFocusRight',\n this.get('parentWindow')\n );\n }\n }\n\n return;\n }\n\n this.incrementProperty('hoverIndex');\n this.trigger('cellDidChange', { direction: 'right' });\n }", "scrollToCell(cell) {\n // use Phosphor to scroll\n ElementExt.scrollIntoViewIfNeeded(this.node, cell.node);\n // change selection and active cell:\n this.deselectAll();\n this.select(cell);\n cell.activate();\n }", "function nextKnCell(e){\n\tvar previousKnCell = keynapse.currentKnCell;\n\tpreviousKnCell.knCellHint.removeClass('kn-cell-hint-current');\n\n\tvar currentKnCell;\n\tif (keynapse.currentKnCellIndex == keynapse.knCells.length - 1 ){\n\t\tkeynapse.currentKnCellIndex = 0;\n\t\tkeynapse.currentKnCell = keynapse.knCells[keynapse.currentKnCellIndex];\n\t\tcurrentKnCell = keynapse.currentKnCell;\n\t} else {\n\t\tkeynapse.currentKnCell = keynapse.knCells[++keynapse.currentKnCellIndex];\n\t\tcurrentKnCell = keynapse.currentKnCell;\n\t}\n\t\n\tcurrentKnCell.knCellHint.addClass('kn-cell-hint-current');\n}", "slideBack() {\n this.slideBy(-this.getSingleStep());\n }", "function setMostRecentGame() {\n\n console.log(\"setting current game...\");\n\n vm.currentGame = vm.games[vm.games.length-1];\n\n\n console.log(\"current game set to: \" + vm.currentGame.rows);\n\n }", "changeCellLeft() {\n const cells = this.get('cells');\n const hoverIndex = this.get('hoverIndex');\n const lastIndex = cells.length > 0 ? cells.length - 1 : 0;\n const isLoop = this.get('isLoop');\n const noSwitch = this.get('noSwitchLeft');\n\n if (hoverIndex === 0) {\n\n if (isLoop) {\n this.set('hoverIndex', lastIndex);\n this.trigger('cellDidChange', { direction: 'left' });\n } else {\n this.trigger('focusOnFirstCell');\n\n if (!noSwitch) {\n this.get('frameService').trigger(\n 'rowFocusLeft',\n this.get('parentWindow')\n );\n }\n }\n\n return;\n }\n\n this.decrementProperty('hoverIndex');\n this.trigger('cellDidChange', { direction: 'left' });\n\n return;\n }", "move() {\n // If the bot has arrived at the end, return\n if (this.maze.is_end_position(this.row, this.col))\n return;\n\n // When the bot isn't aligned with the grid yet, keeping moving in its current direction\n if ( (this.row != floor(this.row)) || (this.col != floor(this.col)) ) {\n this.walk_forward();\n }\n // Otherwise, find direction and then move forward\n else {\n // If global speed has changed, recalculate bot's unit movement\n if (this.speed_update)\n this.calc_unit_movement(speed);\n this.set_trail();\n this.prev_row = this.row;\n this.prev_col = this.col;\n this.find_direction();\n this.walk_forward();\n }\n }", "function currentCell(neighborRow, neighborCol, currRow, currCol) {\n return neighborRow === currRow && neighborCol === currCol\n }", "toGoPosition() {\n console.log('[johnny-five] Proceeding with Go Sequence.');\n\n this.red.on();\n this.yellow.stop().off();\n this.green.stop().off();\n\n setTimeout(() => {\n this.yellow.on();\n }, 2000);\n\n setTimeout(() => {\n this.red.off();\n this.yellow.off();\n this.green.on();\n }, 3500);\n }", "function nextCellAvailable() {\n\t\t\t\tvar cellAvailable = true;\n\t\t\t\tvar newSnakeCellX = newSnakeCell().x;\n\t\t\t\tvar newSnakeCellY = newSnakeCell().y;\n\n\t\t\t\t/* Check if there is no border on X-axis. */\n\t\t\t\tif (Math.floor(newSnakeCellX / ($scope.options.cellWidth + $scope.options.cellMargin)) === $scope.maxAvailabeCells.x || newSnakeCellX < 0) {\n\t\t\t\t\treturn cellAvailable = false;\n\t\t\t\t}\n\n\t\t\t\t/* Check if there is no border on Y-axis. */\n\t\t\t\tif (Math.floor(newSnakeCellY / ($scope.options.cellHeight + $scope.options.cellMargin)) === $scope.maxAvailabeCells.y || newSnakeCellY < 0) {\n\t\t\t\t\treturn cellAvailable = false;\n\t\t\t\t}\n\n\t\t\t\t/* Walking thru all snake's cells. If next cell is busy by existing one it means that snake hits its own tail. */\n\t\t\t\tangular.forEach($scope.snake, function (cell) {\n\t\t\t\t\tif (cell.x === newSnakeCellX && cell.y === newSnakeCellY) {\n\t\t\t\t\t\treturn cellAvailable = false;\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t\treturn cellAvailable;\n\t\t\t}", "jumpToRandom(){\n\t\tthis.coinCount -= 5;\n\t\tthis.updateCoinCount();\n\t\tconst randomTile = Math.floor(Math.random()*40 +1);\n\t\tthis.currentPosition = randomTile;\n\t\tthis.movePiece();\n\t\t$('.resultmessage__container').html(`<p>${this.character} hopped in the vortex and landed on tile [${this.currentPosition}]!</p>`);\n\t\tthis.checkForStar();\n\t\thandleStarFoundMessage();\n\t}", "function handleGotoFirstProblem() {\n run();\n if (_gotoEnabled) {\n $problemsPanel.find(\"tr:not(.inspector-section)\").first().trigger(\"click\");\n }\n }", "function moveDown(notebook) {\n if (!notebook.model || !notebook.activeCell) {\n return;\n }\n const state = Private.getState(notebook);\n const cells = notebook.model.cells;\n const widgets = notebook.widgets;\n cells.beginCompoundOperation();\n for (let i = cells.length - 2; i > -1; i--) {\n if (notebook.isSelectedOrActive(widgets[i])) {\n if (!notebook.isSelectedOrActive(widgets[i + 1])) {\n cells.move(i, i + 1);\n if (notebook.activeCellIndex === i) {\n notebook.activeCellIndex++;\n }\n notebook.select(widgets[i + 1]);\n notebook.deselect(widgets[i]);\n }\n }\n }\n cells.endCompoundOperation();\n Private.handleState(notebook, state, true);\n }", "function changeToNextField(e) {\n $sel = $sel.next(\"td.editable\");\n if($sel.length < 1) {\n $sel = $sel.parent(\"tr.griderRow\").siblings(\"tr:first\").find(\"td.editable:first\");\n }\n setSelectedCell($sel);\n $sel.trigger(\"click\");\n }", "goToPreviousNewComment() {\n if (cd.g.autoScrollInProgress) return;\n\n const commentInViewport = Comment.findInViewport('backward');\n if (!commentInViewport) return;\n\n // This will return invisible comments too in which case an error will be displayed.\n const comment = reorderArray(cd.comments, commentInViewport.id, true)\n .find((comment) => comment.newness && comment.isInViewport(true) !== true);\n if (comment) {\n comment.$elements.cdScrollTo('center', true, () => {\n comment.registerSeen('backward', true);\n this.updateFirstUnseenButton();\n });\n }\n }", "static async switchToLastWindow() {\n const windows = await Browser.driver.getAllWindowHandles();\n await Browser.driver.switchTo().window(windows.pop());\n }", "function navigateCells(e) {\n if($(\"div.griderEditor[style*=block]\").length > 0)\n return false;\n\n var $td = $table.find('.' + defaults.selectedCellClass);\n var col = $td.attr(\"col\");\n switch(e.keyCode) {\n case $.ui.keyCode.DOWN:\n //console.log($td);\n setSelectedCell($td.parent(\"tr:first\").next().find('td[col=' + col + ']') );\n break;\n case $.ui.keyCode.UP:\n setSelectedCell($td.parent(\"tr\").previous().find('td[col=' + col + ']') );\n break;\n case $.ui.keyCode.LEFT:\n //console.log(\"left\");\n break;\n case $.ui.keyCode.RIGHT:\n //console.log(\"right\");\n break;\n }\n }", "function workAni() {\n workAnimation = true;\n t = 1200;\n\n if (scrollUp === true) {\n if (workNumber === 1) {\n endWork(); \n t = 800;\n } \n else {\n nextWorkNumber = workNumber - 1;\n prevWork(); \n } \n } else {\n if (workNumber === finalWorkNumber) {\n endWork(); \n t = 800;\n } \n else {\n nextWorkNumber = workNumber + 1;\n nextWork();\n }\n }\n\n //--- wait till ready for next input\n setTimeout(function(){\n workAnimation = false;\n }, t);\n }", "goToNextBlock () {\n const nextBlockId = this.target.blocks.getNextBlock(this.peekStack());\n this.reuseStackForNextBlock(nextBlockId);\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
CREATE Mob. CALLED IN INITIAL.JS.CREATE() create mobs in a for loop or something..
function createMob(){ mob(); //timer variable keeps track of time elapsed since game started. }
[ "function createMob() {\n var rand = Math.random();\n var tear = 1;\n if (rand < 0.5) {\n tear = 1;\n } else if (rand < 0.8) {\n tear = 2;\n } else if (rand < 0.95) {\n tear = 3;\n } else {\n tear = 4;\n }\n enemy = new Monster(LEVEL, tear);\n updateMob();\n}", "spawn(mob){\r\n\r\n }", "function createPlayer() {\n\n entityManager.generatePlayer({\n cx : 240,\n cy : 266,\n });\n\n}", "create () {\n this.game.switchScene(this.game.postSetupScene);\n }", "creationMeteorProcess(){\r\n this.meteorProcess = window.setInterval(function(){\r\n if(self.gameState.playerLife > 0){\r\n self.gameState.createMeteors(self.gameState.meteors, 1);\r\n }\r\n }, 3000);\r\n }", "createObjects() {\n //this.createCube();\n //this.createSphere();\n //this.createFloor();\n this.createLandscape();\n this.createWater();\n }", "createInitialEnemies() {\n this.enemies = [];\n this.checkEnemyCreation(1000);\n for (let i = 0; i < this.level.numEnemyRows - 1; ++i) this.checkEnemyCreation(2);\n }", "function createMonsters(number) {\n for (let i = 0; i < number; i++) {\n monsterArray.push(new Obstacles(Math.random()*3 + 1))\n }\n //player must die\n setTimeout(() => {\n monsterArray.push(new Obstacles(Math.random()*3 + 1))\n }, 50000);\n}", "function initMonsterGenerator()\r\n{\r\n\tconsole.log('page loaded');\r\n\t$('#mgentabs').tabs();\r\n\r\n\t// Set up events\r\n\t$('#saveicon').click(function()\r\n\t{\r\n\t\tdoSaveMonster(); \r\n\t});\r\n\r\n\t$('#xicon').click(function()\r\n\t{\r\n\t\tdoExitMgen();\r\n\t});\r\n\t$('#newmonster').click(function()\r\n\t{\r\n\t\tdoNewMgen();\r\n\t});\r\n\tdoLoadMonster(bestiary[0]);\r\n\r\n\t$('#m_name').keyup(function()\r\n\t{\r\n\t\t$('#monstertitle').html($('#m_name').val());\r\n\t});\r\n\r\n\thideTabs();\r\n\t\r\n\t// Set up the tabs\r\n\t$('#tab-chat').click(function(){hideTabs(); $('#chat').show(); console.log(\"Showing chat\");});\r\n\t$('#tab-objects').click(function(){hideTabs(); $('#objects').show(); console.log(\"Showing objects\");}); \r\n\t$('#tab-monsters').click(function(){hideTabs(); $('#monsters').show(); console.log(\"Showing monsters\");});\r\n\t$('#tab-social').click(function(){hideTabs(); $('#social').show(); console.log(\"Showing social\");});\r\n\r\n}", "function generateMetalsStones(metalDivID, stoneDivID, numMetals, numStones) {\n setInitialValues();\n generateObjects(metalDivID, stoneDivID, numMetals);\n setGameBoardSettings()\n\n}", "function generateAgents(numHum, propZomb,x,y){\r\n\t//if(gameState){\r\n\t\tfor (var i = 0; i < numHum; i++){\r\n\t\t\tconst human = new Agents('Human',2,traitSelector(),'Blue',initialLocation(x,y));\r\n\t\t\tactiveAgents.push(human);\r\n\t\t}\r\n\t\tfor (var j = 0; j < (numHum*propZomb); j++){\r\n\t\t\tconst zombie = new Agents('Zombie',1,traitSelector(),'Red',initialLocation(x,y));\r\n\t\t\tactiveAgents.push(zombie);\r\n\t\t}\r\n\t//}\r\n}", "function TestEntity1() {\n this.sprite = new Sprite(0,0,20, \"blue\");\n}", "createPlayerManagers() {\n dg(`creating 4 player managers`, 'debug')\n for (let i = 0; i < 4; i++) {\n let player = new PlayerManager(i, this)\n player.init()\n this._playerManagers.push(player)\n this._playerManagers[0].isTurn = true\n }\n dg('player managers created', 'debug')\n }", "function create() {\n var tank = this.add.sprite(200, 200, \"tank\");\n\n fireButton = this.input.keyboard.addKey(\n Phaser.Input.Keyboard.KeyCodes.SPACE\n );\n \n // Fade the camera in for added drama\n this.cameras.main.fadeFrom(2000, 0, 0, 0);\n}", "createPlayer() {\n this.player = new Player(this.level);\n }", "function BoostLife()\n{\n\tif(frameCount%1000 === 0)\t{\n\t\tlifeBoost=createSprite(0,40,10,10);\t\n\t\tlifeBoost.addImage(lifeboostImg);\n\t\tlifeBoost.scale=0.5\n\t\tlifeBoostn.velocityX=2;\t\t\n\t\tlifeBoost.y=random(20,height-20);\n\t\tlifeBoost.lifetime=1000;\t\n\t\tlifeBoostgroup.add(lifeBoost);\n\t\t\n\t}\n\n\n\n\n}", "function createVehicle() {\n var vehicleAssets = [\"tempCar\"];\n var randomAssetNo = Math.floor(Math.random()*vehicleAssets.length);\n var v = [new Sprite(\"/sprites/vehicles/\"+vehicleAssets[randomAssetNo]),\"right\"];\n v[0].pos[0]= (window.innerWidth/2)-(10*tileSize)/2+(0*tileSize);\n v[0].pos[1]= (window.innerHeight/2)-(10*tileSize)/2+(6*tileSize);\n vehicles[vehicles.length] = v;\n}", "function doNewMgen()\r\n{\r\n\t$('#monsteredit').slideDown(); \r\n\tdoLoadMonster(getBlankMonster());\r\n}", "construct_player() {\n this.player = new Player(this);\n this.player.x = 352;\n this.player.y = 256;\n this.nubs = this.add.group();\n this.left_nub = this.physics.add.sprite(this.player.x - 17, this.player.y).setBodySize(3, 3);\n this.nubs.add(this.left_nub);\n this.right_nub = this.physics.add.sprite(this.player.x + 17, this.player.y).setBodySize(3, 3);\n this.nubs.add(this.right_nub);\n this.up_nub = this.physics.add.sprite(this.player.x, this.player.y - 17).setBodySize(3, 3);\n this.nubs.add(this.up_nub);\n this.down_nub = this.physics.add.sprite(this.player.x, this.player.y + 17).setBodySize(3, 3);\n this.nubs.add(this.down_nub);\n\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
_.maxBy(array, [iteratee=_.identity]) This method is like _.max except that it accepts iteratee which is invoked for each element in array to generate the criterion by which the value is ranked. The iteratee is invoked with one argument: (value). Arguments array (Array): The array to iterate over. [iteratee=_.identity] (Function): The iteratee invoked per element. Returns (): Returns the maximum value.
function maxBy(arr, iteratee) { const { length } = arr; if (!length) { return arr; } if (typeof iteratee === `string`) { const str = iteratee; iteratee = (o) => o[str]; } if (length === 1) { return iteratee(arr[0]); } let maxObj = arr[0]; let maxVal = iteratee(arr[0]); for (let i = 1; i < length; i++) { const currValue = iteratee(arr[i]); if (currValue > maxVal) { maxObj = arr[i]; maxVal = currValue; } } return maxObj; }
[ "function max(array, key) {\n let best = null;\n let bestValue = null;\n for (let elt of array) {\n let eltValue = key(elt);\n if (bestValue == null || eltValue > bestValue) {\n bestValue = eltValue;\n best = elt;\n }\n }\n return best;\n}", "function findMaximumValue(array) {\n\n}", "function maxScore(array, elements) {\n var maximumScore = 0;\n for (i = 0; i < BOARD_ELEMENTS; i++) {\n if (array[i] > maximumScore) {\n maximumScore = array[i];\n }\n }\n return maximumScore;\n}", "function findMaxProduct(array) {\n\n}", "function max(object) {\n let valArray = Object.values(object);\n let currMax = valArray[0];\n let error = 0;\n valArray.forEach(function (n) {\n // if array contains a non number return the whole array\n if (typeof (n) != 'number') {\n error = 1;\n }\n else if (n > currMax) {\n currMax = n;\n }\n\n })\n if (error === 1) { return null; }\n else { return currMax; }\n}", "function maxUserAge() {\n return _.maxBy(_.map(users, 'age'));\n}", "function find_largest_array(array)\n{\n\tvar index = 0;\n\tfor (var i = 0; i < array.length; i++)\n\t{\n\t\tif (array[i].length > array[0].length)\n\t\t{\n\t\t\tindex = i;\n\t\t}\n\t}\n\treturn index;\n}", "function largestEvenNum(arr) {\n return arr.filter((x) => x % 2 === 0).reduce((a, b) => (a > b ? a : b));\n}", "function extractMax(table, studentArray, houseName) {\n let currentRank = table.getRank(houseName, studentArray[0]);\n let newRank = 0;\n // the highest rank \"bubbles\" to the end of the array\n for (let i = 0; i < studentArray.length - 1; i++) {\n newRank = table.getRank(houseName, studentArray[i + 1]);\n if (currentRank > newRank) {\n let temp = studentArray[i];\n studentArray[i] = studentArray[i + 1];\n studentArray[i + 1] = temp;\n } else {\n currentRank = newRank;\n }\n }\n let student = studentArray.pop();\n return student;\n}", "highestMarks(marks) {\n let mark = Object.values(marks[0]).map(element => {\n return parseInt(element);\n });\n return Math.max(...mark);\n }", "function getMax(slice, prop) {\n var max = 0;\n slice.each(function () {\n var size = $(this)[prop]();\n if (size > max) max = size;\n });\n return max;\n }", "max() {\n for(let i = this.array.length - 1; i >= 0; i--){\n const bits = this.array[i];\n if (bits) {\n return BitSet.highBit(bits) + i * bitsPerWord;\n }\n }\n return 0;\n }", "function maxIndustryJobs(data) {\n return _.max(industryJobs(data), function (record) {return record.jobs;});\n}", "function maxofThree(a,b,c){\n return max(max(a,b),c);\n \n }", "function testMax() {\n const { parameters } = tests.exercises.find((exercise) => {\n return exercise.name === \"max\";\n });\n\n let tc = 0;\n let pass = 0;\n for (const numbers of parameters[0].values) {\n const functionCall = `max(${format(numbers)})`;\n const expected = staff.max(numbers);\n const actual = student.max(numbers);\n\n if (expected !== actual) {\n console.log(`Test Case ${tc + 1} -- Fail.`);\n console.log(` - call: ${functionCall}`);\n console.log(` - expected: ${expected}`);\n console.log(` - actual: ${actual}\\n`);\n } else {\n pass++;\n }\n\n tc++;\n }\n console.log(`max -- passed ${pass} out of ${tc} test cases.`);\n}", "function findMaxNegProd(arr) {\n if ((arr.filter(item => Array.isArray(item))).length === 0) {\n console.log(\"Invalid argument\");\n return;\n }\n const filterMinus = (arr.map(item => item.filter(item => item < 0)));\n const filterEmptyArr = filterMinus.filter(item => item.length !== 0);\n if (filterEmptyArr.length === 0) {\n console.log(\"No negatives\");\n return;\n }\n const maxMinus = filterEmptyArr.map(item => Math.max.apply(null, item));\n const product = maxMinus.reduce((a,b) => a*b);\n console.log(product);\n}", "function max_subarray(A){\n let max_ending_here = A[0]\n let max_so_far = A[0]\n\n for (let i = 1; i < A.length; i++){\n max_ending_here = Math.max(A[i], max_ending_here + A[i])\n // console.log(max_ending_here)\n max_so_far = Math.max(max_so_far, max_ending_here)\n // console.log(max_so_far)\n } \n\n return max_so_far\n}", "function maxRecurse(...num) {\n const array = num[0];\n const array2 = [...array];\n let max = array2[0];\n\n if (array2.length === 1) {return max}\n array2.shift();\n let newMax = maxRecurse(array2);\n if (max < newMax) {max = newMax}\n \n return max; \n}", "function findMax() {\n var max = dog.data[0].count;\n var winner = dog.data[0];\n for (var i = 0; i < dog.data.length; i++) {\n if (dog.data[i].count > max) {\n max = dog.data[i].count\n winner = dog.data[i]\n }\n }\n return winner;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Removes the given circle from the map.
removeCircle(circle) { return this._circles.get(circle).then(c => { c.setMap(null); this._circles.delete(circle); }); }
[ "function removePoint(){\n \t if(currentPt != null){\n \t\t map.removeLayer(currentPt);\n \t\t currentPt = null;\n \t\t recenterMap();\n \t\t resetCurrentLoc();\n \t }\n }", "removeHitObject() {\n const pos = this.findObj(this.lastUpdated);\n if (pos >= 0) {\n const sprite = this.hitObjectSpriteList.filter(item => item.id === 'CIRCLE_' + this.lastUpdated);\n if (sprite.length > 0) {\n this.hitObjectStage.removeChild(sprite[0]);\n sprite[0].destroy();\n }\n this.hitObjects.splice(pos, 1);\n this.hitObjectSpriteList.splice(pos, 1);\n }\n }", "static deleteCircles() {\n arrCircles.forEach((circle) => {\n circle.div.remove(); // Removes the circle DOM from the body\n });\n }", "function eraseMap() {\n document.body.removeChild(map);\n }", "function removeBox(lat1, lng1, lat2, lng2) {\n var index = makeIndex(lat1, lng1, lat2, lng2)\n boxes[index].setMap(null);\n boxes[index] = null\n}", "function removePolygon() {\n\tif (typeof activePolygon != 'undefined') {\n\t\tactivePolygon.setMap(null);\n\t} else {\n\t\talert(\"Active Polygon is null\");\n\t}\n}", "function removeOutlineMap() {\n\tthis.style.border = \"1px solid #fff\";\n\tif (!this.classList.contains(\"starred\")) {\n\t\tvar star = document.getElementById(\"hoverStar\");\n\t\tthis.removeChild(star);\n\t}\n}", "function removeAddress(){\n\tif(activeCounter >0){\n activeCounter--;\n\t\tif(markers[counter] != null){\n\t\t\tmarkers[counter].setMap(null);\n\t\t\tmarkers[counter] = null;\n if(activeCounter ==0){\n //if no active markers anymore, reinitialize the map\n initialize();\n }else{\n //otherwise, reset the bounds to fit previous list of properties\n setBounds();\n }\n\t\t}\n\t}\n\tdecrement();\n}", "function removeOverlay() {\n imgOverlay.setMap(null);\n}", "function remove_poi() {\n\tif (pois.hasLayer(POI)){\n\t\tpois.removeLayer(POI);\n\t}\n}", "function reset() {\n $(\"#searchInput\").empty();\n circle.setMap(null);\n}", "removeRectangle(rectangle) {\n return this._rectangles.get(rectangle).then(r => {\n r.setMap(null);\n\n this._rectangles.delete(rectangle);\n });\n }", "remove(unit) {\n let x = this.getAxis(unit.xPosition);\n let y = this.getAxis(unit.yPosition);\n\n // remove unit\n let idx = this.getCell(x, y)\n .map(u => u.id).indexOf(unit.id);\n if (idx >= 0) {\n this.grid[x][y].splice(idx, 1);\n }\n }", "removeAllMarkers() {\n if (this.markerGroup) this.markerGroup.clearLayers();\n }", "function unHighlightStationMap(station) {\n\tconsole.log(station);\n\tm = locData.get(station).marker;\n\tm.setMap(null);\n\tm.icon = defaultMapIcon;\n\tm.setMap(map);\n}", "function checkCircleClick() {\n // Check all circles\n for (let i = 0; i < circles.length; i++) {\n let circle = circles[i];\n // Check the distance to the circle from the mouse\n let d = dist(mouseX, mouseY, circle.x, circle.y);\n // If the mouse was clicked inside the circle\n if (d < circle.size / 2) {\n // Remove the circle from the array with splice()\n circles.splice(i, 1);\n // Break out of the for-loop after removing the circle\n break;\n }\n }\n}", "function updateCircleRadius(value) {\r\n\tcircleRadius = parseInt(value) * 1000;\r\n\tif ($(\"#optradio_trueCircle\").prop('checked')) {\r\n\t\tpointCircleLayer.clearLayers().addLayer(L.circle([pointCircleLayerCoords['lat'], pointCircleLayerCoords['lon']], circleRadius, circleOptions));\r\n\t};\r\n}", "function clearMap() {\n for (var i = 0; i < facilityMarkers.length; ++i) {\n facilityMarkers[i].setMap(null);\n }\n facilityMarkers = [];\n}", "function cleanMap() {\n\n\t// Disable position selection by mouse click.\n\tdisablePositionSelect();\n\n\t// Remove existing nearby stations layer.\n\tif (map.getLayersByName(\"Nearby Docking Stations\")[0] != null)\n\t\tmap.removeLayer(map.getLayersByName(\"Nearby Docking Stations\")[0]);\n\t\t\n\t// Reset select controls.\n\tif (selectControl !=null) {\n\t\tselectControl.unselectAll();\n\t\tselectControl.deactivate();\n\t}\n \tif (selIncControl !=null) {\n\t\tselIncControl.unselectAll();\n\t\tselIncControl.deactivate();\n\t}\n \tif (voteControl !=null) {\n\t\tvoteControl.unselectAll();\n\t\tvoteControl.deactivate();\n\t} \n\tif (selectDockControl != null) {\n\t\tselectDockControl.unselectAll();\n\t\tselectDockControl.deactivate();\n\t}\n\n\tif (distr_stats != null)\n\t\tmap.removeLayer(distr_stats);\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
does a page with this slug exist?
function pageExists (slug) { return test('-f', PAGE_DIR+slug+'.md'); }
[ "function pageExists( title )\n{\n if (FILE.file_exists( pagePath( title ) ) || isSpecial( title ) ){\n return true;\n }else{\n return false;\n }\n}", "async isCorrectPageOpened() {\n let currentURL = await PageUtils.getURL()\n return currentURL.indexOf(this.pageUrl)!== -1\n }", "function isPageValid (PageName)\n{\n\tvar cWkgPgObj = generateSEObjects (PageName);\n\treturn (isPageObjValid (cWkgPgObj.pageObjArray[PageName]));\n}", "function isNeptunPage() {\n return document.title.toLowerCase().indexOf(\"neptun.net\") !== -1;\n}", "function urlExists(url) {\n\t\tvar http = new XMLHttpRequest();\n\t\thttp.open('HEAD', url);\n\t\thttp.send();\n\t\tif (http.status !== 404) {\n\t\t\timgsNumber++;\n\t\t\treturn true;\n\t\t} else {\n\t\t\treturn false;\n\t\t}\n\t}", "function isLikedPage(candidate) {\r\n\t//todo search as json instead?\t\r\n\treturn (likes.indexOf(candidate)!=-1);\t\r\n}", "function hasPageTemplate (theme, name) {\n\treturn test('-f', THEME_DIR+theme+'/'+name+'.swig');\n}", "exists() {\n return null !== this._document;\n }", "function contains_hash(){\n var hash = document.location.hash;\n return hash && (section[0].id == hash.substr(1) ||\n section.find(hash.replace(\".\",\"\\\\.\")).length>0);\n }", "function isHomePage() {\n\tvar p = window.location.pathname.toLowerCase();\n\tif (!p || p == '/') return true;\n\tvar m = p.match(/^\\/([^\\.]+)\\.(.*)$/);\n\treturn m && m.length == 3 \n\t\t? \n\t\t\t$.inArray(m[1], ['default', 'index', 'home']) > -1 \n\t\t\t&& $.inArray(m[2], ['htm', 'html', 'shtml', 'php', 'jsp', 'asp', 'aspx', 'cfm']) > -1 \n\t\t: \n\t\t\tfalse;\n\t\n}", "async exists() {\n return $(this.rootElement).isExisting();\n }", "function activeRoute(routeName) {\n return window.location.href.indexOf(routeName) > -1 ? true : false\n }", "function messageOnPage(messageID) {\n return ($j(\"a[name='\" + messageID + \"']\").length > 0);\n }", "function checkOnScreen(myURL){\n HeadingArray = getOnScreenHeadingArray();\n URLArray = getOnScreenURLArray();\n\t\n\tvar i = URLArray.indexOf(myURL);\n if( i != -1 ){\n\t alert(\"Already exists OnScreen with heading: \"+HeadingArray[i]+\" .\");\n\t\treturn true;\n\t}\n}", "has(key) {\n return (this.links.find((ref) => (ref.rel === key)) != null);\n }", "exists() {\n return this.element ? true : false;\n }", "function checkTitleExists(req, res, next) {\n if (!req.body.title) {\n return res.status(400).json({\n error: \"Params TITLE is required\"\n });\n }\n\n return next();\n}", "exists(objectHash) {\n return objectHash !== undefined\n && fs.existsSync(nodePath.join(Files.gitletPath(), 'objects', objectHash));\n }", "function checkSite()\n{\n var path = \"./public\";\n var ok = fs.existsSync(path);\n if(ok) path = \"./public/index.html\";\n if(ok) ok = fs.existsSync(path);\n if(!ok) console.log(\"Can't find\", path);\n return(ok);\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets a given number of items from a given feed URL optionally starting from a given cursor
function fetchFeedItems(url, from, count, callback) { from = from || 0; count = count || 20; var feed = new google.feeds.Feed(FEED_URL); feed.setResultFormat(google.feeds.Feed.JSON_FORMAT); feed.setNumEntries(from + count); feed.includeHistoricalEntries(); log('From ' + from + ' to ' + (from + count) + '\n'); feed.load(function(result) { if (result.error) { ret = false; } else { // Set title header = '<a href="' + result.feed.link + '" rel="external" target="_blank"><h1>' + result.feed.title + '</h1></a>'; header += '<h2><small>' + result.feed.description + '</small></h2>'; header += '<hr class="soften">'; $('body > div.container-fluid > .title-wrapper').html(header); var max = (count > result['feed'].entries.length) ? count : result['feed'].entries.length; items = []; for (var i = from; i < max; i++) { item = result['feed'].entries[i]; item.eid = i; ENTRIES[i] = item; items.push(item); } ret = items; } if (callback && $.isFunction(callback)) { callback(ret); } }); }
[ "function fetchItems() {\n const offset = state.offset - 1;\n state.offset += 10 - 1;\n state.index += 10 - 1;\n return axios\n .get(\n `${apiURL}/api/trade/fetch/${state.itemIds.result.splice(\n state.index,\n offset\n )}?query=${state.itemIds.id}`\n )\n .then((res) => {\n return res.data;\n });\n }", "loadItems(url) {\n this.indexUrl = url;\n this.getFromServer(url, this.serverParams).then(response => {\n this.totalRecords = response.meta.total;\n this.rows = response.data;\n });\n }", "function getFeedsSequentionally(cb) {\n // internal variable storing feed contents\n let contents = [];\n\n // function f is used for calling loadFeed recursively\n // internal state of recursion is controlled with 'i' that is passed to the function as a parameter\n function f(i) {\n contents.push(feed.innerHTML);\n\n // the recursion is stopped when we run out of feeds, and cb is called\n if (i >= allFeeds.length - 1) {\n cb(contents);\n return;\n }\n\n i++;\n\n loadFeed(i, () => f(i));\n }\n\n loadFeed(0, () => f(0)); \n\n }", "getItems(offset, limit) {\n if (this.list.length < offset + limit && !this.lastItem) {\n // All the requested items don't exist and it's not the last page either.\n return null;\n }\n\n if (this.lastItem === 'empty') {\n // empty state\n return [];\n }\n\n const result = [];\n let curr;\n for (let i = offset; i < offset + limit; i++) {\n curr = this.items[this.list[i]];\n if (!curr) {\n // There's a gap in the list of items so the items are not there yet.\n return null;\n }\n result.push(curr);\n\n if (this.lastItem === curr[this.key]) {\n // That should be all items in the collection.\n break;\n }\n }\n\n return result;\n }", "function GADGET_RSS_Auto_Scroll()\n{\t\n\tvar Page = System.Gadget.Settings.read(\"Page\");\n\tGADGET_RSS_Feed_Disp(Page+1);\n}", "function get_loads(req){\r\n var fullUrl = req.protocol + '://' + req.get('host') + req.originalUrl;\r\n //Limit to three boat results per page\r\n var q = datastore.createQuery(LOAD).limit(5);\r\n\r\n var results = {};\r\n\r\n if(Object.keys(req.query).includes(\"cursor\")){\r\n q = q.start(req.query.cursor);\r\n }\r\n\r\n return datastore.runQuery(q).then( (entities) => {\r\n results.loads = entities[0].map(ds.fromDatastore);\r\n for (var object in results.loads)\r\n {\r\n if(results.loads[object].carrier.length === 1)\r\n {\r\n var bid = results.loads[object].carrier[0];\r\n var boatUrl = req.protocol + '://' + req.get('host') + '/boats/' + bid;\r\n results.loads[object].carrier = [];\r\n results.loads[object].carrier = {\"id\": bid, \"self\": boatUrl};\r\n }\r\n \r\n // Make sure self link does not have cursor in it\r\n if(Object.keys(req.query).includes(\"cursor\"))\r\n {\r\n results.loads[object].self = req.protocol + '://' + req.get('host') + results.loads[object].id;\r\n }\r\n else\r\n {\r\n results.loads[object].self = fullUrl +'/' + results.loads[object].id;\r\n }\r\n }\r\n if(entities[1].moreResults !== ds.Datastore.NO_MORE_RESULTS){\r\n results.next = req.protocol + \"://\" + req.get(\"host\") + req.baseUrl + \"?cursor=\" + encodeURIComponent(entities[1].endCursor);\r\n }\r\n }).then(() =>{\r\n return count_loads().then((number) => {\r\n results.total_count = number;\r\n return results; \r\n });\r\n });\r\n}", "function fb_fetch_all_data(url, cb){\n objects = [];\n function iterator(url){\n fb.get(url, function(err, data){\n if (err){\n cb(err, null);\n return;\n }\n if (data.data.length == 0){\n cb(null, objects);\n return;\n }\n for (var i = 0; i < data.data.length; i++){\n objects.push(data.data[i]);\n }\n iterator(data.paging.next);\n });\n }\n iterator(url);\n}", "function fetch() {\n $http.get(resourceUrl + $scope.search + '&maxResults=20&orderBy=newest')\n .success(function(data) {\n $scope.data = data;\n $scope.bookFeed = data.items;\n });\n }", "async loadCards() {\n await JsonPlaceholder.get(\"/posts\", {\n params: {\n _start: this.props.cardList.length + 1,\n },\n })\n .then((res) => {\n this.props.fetchCardsSuccess({\n loadMore: !(res.data.length < 10),\n cardList: res.data,\n });\n })\n .catch((err) => {\n this.props.fetchCardsFailed();\n });\n }", "function get_youtube(args, func){\r\n var request = require(\"request\");\r\n var num = args[0];\r\n var next_page = args[1];\r\n var q = 'https://www.googleapis.com/youtube/v3/playlistItems?key='+youtube_key+\"&part=contentDetails&maxResults=50&playlistId=\"+youtube_id;\r\n if(next_page !== undefined){\r\n q+=\"&pageToken=\"+next_page;\r\n }\r\n console.log(\"Sending request: \"+ q);\r\n request(q,function(error,response,body){\r\n if (error || response.statusCode !== 200) {\r\n console.error(\"youtube: Got error: \" + body);\r\n console.log(error);\r\n }\r\n else {\r\n try{\r\n var response = JSON.parse(body);\r\n var length = response.pageInfo.totalResults;\r\n if (num == undefined){\r\n num = Math.floor(Math.random()*(length)+1)-1;\r\n console.log(\"Found \"+length+\" videos. Getting video #\"+num);\r\n }\r\n if(num<50){\r\n func(\"https://www.youtube.com/watch?v=\"+response.items[num].contentDetails.videoId);\r\n } else {\r\n console.log(\"Continuing to next page...\");\r\n get_youtube([num-50, response.nextPageToken], function(url){\r\n func(url);\r\n });\r\n }\r\n } catch (e){\r\n console.log(e);\r\n func(undefined);\r\n }\r\n }\r\n }.bind(this));\r\n}", "function getTopStoriesId(amount = 50) {\n return fetch(`${baseURL}/topstories.json`)\n .then((data) => data.json())\n .then(data => Array.prototype.slice.call(data, 0, amount))\n}", "async function getStreams(lang, token, nextCursor = \"\") {\n const params = { game_id: \"21779\", after: nextCursor, language: lang }\n url.search = new URLSearchParams(params).toString()\n\n const res = await fetch(url, {\n method: \"GET\",\n headers: {\n Authorization: `Bearer ${token}`,\n \"Client-Id\": clientId,\n },\n })\n const data = await res.json()\n cursor = data.pagination.cursor\n\n return { data, cursor }\n}", "function skipTenAuthors() {\n return new Promise((resolve, reject)=>{\n let skip = 10;\n getBooks();\n function getBooks(books = []) {\n Promise.resolve(books)\n .then((books)=>{\n return Author.find({}).skip(skip).limit(3)\n .then((authors) =>{\n return Promise.all(authors.map((item) => bookByAuthor(item.id)))\n .then((foundBooks)=>{\n foundBooks = foundBooks.filter(item=> item);\n foundBooks.forEach(item=> books.push(item));\n\n if(books.length < 3){\n skip += 3;\n getBooks(books);\n }\n else resolve(books);\n })\n });\n });\n }\n\n });\n}", "async function nextDocumentsFromCursor(cursor, limit) {\n let docsToArchive = [], docIds = [], hasNext = true;\n while (docsToArchive.length < limit) {\n const doc = await cursor.next()\n .then(doc => {\n return doc;\n })\n .catch(err => {\n console.error(`Failed to find documents: ${err}`);\n throw err;\n });\n if (doc) {\n docsToArchive.push(doc);\n docIds.push(doc._id);\n } else {\n hasNext = false;\n break;\n }\n }\n \n return [ docsToArchive, docIds, hasNext ];\n}", "function getItems (site, siteIDs, errorFreeArray, siteItems, siteName, counter) {\n\t\treturn new Promise(function(resolve, reject) {\n\t\t\tif (errorFreeArray[counter.val]) {\n\t\t\t\tconst item = site.items({ collectionId: siteIDs[counter.val]} );\n\t\t\t\titem.then(data => {\n\t\t\t\t\tvar itemObj = JSON.parse(JSON.stringify(data));\n\n\t\t\t\t\tvar totalBatchPromises = new Array();\n\n\t\t\t\t\t/* If total collection size is greater than the maximum\n\t\t\t\t\t * that can be retrieved at one time, iteratively fetch\n\t\t\t\t\t * chunks of the data and merge them into one large array */\n\n\t\t\t\t\tif (itemObj.total > itemObj.count) {\n\t\t\t\t\t\tvar total = itemObj.total;\n\t\t\t\t\t\tvar curr = itemObj.count;\n\t\t\t\t\t\tvar limit = itemObj.limit;\n\t\t\t\t\t\tvar itemsArray = itemObj.items;\n\n\t\t\t\t\t\twhile (curr < total) {\n\t\t\t\t\t\t\tvar thisBatchPromise = new Promise(function(resolve, reject) {\n\t\t\t\t\t\t\t\tvar newItem = site.items({ collectionId: siteIDs[counter.val]},\n\t\t\t\t\t\t\t\t\t{offset: curr});\n\t\t\t\t\t\t\t\tnewItem.then(data => {\n\t\t\t\t\t\t\t\t\titemObj.items = itemObj.items.concat(JSON.parse(JSON.stringify(data)).items);\n\t\t\t\t\t\t\t\t\tconsole.log(\"\\n\\nitemObj.items :\")\n\t\t\t\t\t\t\t\t\tconsole.log(itemObj.items.length);\n\t\t\t\t\t\t\t\t\t// for (var i = 0; i < itemObj.items.length; i++) {\n\t\t\t\t\t\t\t\t\t// \tconsole.log(itemObj.items[i].name);\n\t\t\t\t\t\t\t\t\t// }\n\t\t\t\t\t\t\t\t\tresolve();\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\ttotalBatchPromises.push(thisBatchPromise);\n\t\t\t\t\t\t\tcurr += limit;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tPromise.all(totalBatchPromises).then(function() {\n\t\t\t\t\t\t// Add item to map if site is site A\n\t\t\t\t\t\tif (site == webflowObjects[0]) {\n\t\t\t\t\t\t\ta_SiteItems.set(siteIDs[counter.val], itemObj);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// Slow down program if rate limit is being approached\n\t\t\t\t\t\tif (itemObj._meta.rateLimit.remaining < 10) {\n\t\t\t\t\t\t\tvar waitTime = (itemObj._meta.rateLimit.limit * 500) / itemObj._meta.rateLimit.remaining;\n\t\t\t\t\t\t\tprintWaitTime(siteName, itemObj._meta.rateLimit.remaining);\n\t\t\t\t\t\t\tsetTimeout(() => {\n\t\t\t\t\t\t\t\tsiteItems.push(itemObj);\n\t\t\t\t\t\t\t\tcounter.val++;\n\t\t\t\t\t\t\t\tresolve(itemObj);\n\t\t\t\t\t\t\t}, waitTime);\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tsiteItems.push(itemObj);\n\t\t\t\t\t\t\tcounter.val++;\n\t\t\t\t\t\t\tresolve(itemObj);\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t});\n\t\t\t} else {\n\t\t\t\t// push null element if corresponding collection had errors\n\t\t\t\tsiteItems.push(null);\n\t\t\t\tcounter.val++;\n\t\t\t\tresolve();\n\t\t\t}\n\t\t});\n\t}", "async function load() {\n for (var page = 0; page < 10; page++) {\n let url = `https://www.newegg.com/p/pl?N=100006740%204814&Page=${page}&PageSize=96&order=BESTSELLING`\n makeRequest(url)\n await timer(500)\n\n }\n}", "function GetTopBooks(n, criterion) {\n\n}", "function f(i) {\n contents.push(feed.innerHTML);\n\n // the recursion is stopped when we run out of feeds, and cb is called\n if (i >= allFeeds.length - 1) {\n cb(contents);\n return;\n }\n\n i++;\n\n loadFeed(i, () => f(i));\n }", "function nextPage( callback ){\n // Get tweets from local archive if configured\n if( conf.archive ){\n if( ! archive ){\n archive = fs.readdirSync( conf.archive );\n }\n var filename = archive.pop();\n if( ! filename ){\n console.log('No more tweets in archive, quitting');\n process.exit(0);\n }\n // load these tweets via a GLOBAL hack\n Grailbird = { data: {} };\n require( conf.archive+'/'+filename );\n var key;\n for( key in Grailbird.data ){\n callback( Grailbird.data[key] );\n }\n return;\n }\n // else get page of tweets via API \n var params = { \n count: 200, \n user_id : userId, \n trim_user: true,\n include_rts: false\n };\n if( null != maxId ){\n params.max_id = maxId;\n } \n client.get( 'statuses/user_timeline', params, function( tweets, error, status ){\n if( ! tweets || error ){\n return handleTwitterError( status, error, run );\n }\n if( maxId ){\n var tweet = tweets.shift();\n if( ! tweet || tweet.id_str !== maxId ){\n // console.error('Expecting first tweet to match max_id '+maxId+', got '+(tweet?tweet.id_str:'none') );\n // not sure why this happens, but possibly due to tweeting while running.\n // process.exit( EXIT_TWFAIL );\n tweet && tweets.unshift(tweet);\n }\n }\n if( ! tweets.length ){\n if( ! conf.idleTime ){\n console.log('No more tweets in API, quitting');\n process.exit(0);\n }\n console.log('No more tweets, running again in '+conf.idleTime+' seconds..');\n maxId = null;\n setTimeout( run, conf.idleTime * 1000 );\n return;\n }\n callback( tweets );\n } ); \n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Adds a storage profile to the Kaltura DB.
static add(storageProfile){ let kparams = {}; kparams.storageProfile = storageProfile; return new kaltura.RequestBuilder('storageprofile', 'add', kparams); }
[ "static update(storageProfileId, storageProfile){\n\t\tlet kparams = {};\n\t\tkparams.storageProfileId = storageProfileId;\n\t\tkparams.storageProfile = storageProfile;\n\t\treturn new kaltura.RequestBuilder('storageprofile', 'update', kparams);\n\t}", "function addToStorage(key, skill) {\n skillsDatabase.setItem(key, skill);\n $previousEntriesUl.append(`<li>${skill}</li>`);\n }", "static add(distributionProfile){\n\t\tlet kparams = {};\n\t\tkparams.distributionProfile = distributionProfile;\n\t\treturn new kaltura.RequestBuilder('contentdistribution_distributionprofile', 'add', kparams);\n\t}", "function addProfile(data) {\n let sql = `INSERT INTO \"profile\" (userid, fname, lname) VALUES ('${data.userid}', '${data.fname}','${data.lname}')`;\n return db.query(sql);\n}", "async function addToChromeStorage(key1, value) {\n let key = key1;\n chrome.storage.sync.set({'omswebsites': value}, function() {\n fetchFromChromeStorage('arpit');\n return null;\n }); \n }", "function add(key, value) {\n storeObject.table.push({'key': key, 'value': value});\n writeStore();\n }", "static add(conversionProfile){\n\t\tlet kparams = {};\n\t\tkparams.conversionProfile = conversionProfile;\n\t\treturn new kaltura.RequestBuilder('conversionprofile', 'add', kparams);\n\t}", "static add(metadataProfile, xsdData, viewsData = null){\n\t\tlet kparams = {};\n\t\tkparams.metadataProfile = metadataProfile;\n\t\tkparams.xsdData = xsdData;\n\t\tkparams.viewsData = viewsData;\n\t\treturn new kaltura.RequestBuilder('metadata_metadataprofile', 'add', kparams);\n\t}", "function addMemeToAccount(uid, meme) {\n let topText = meme.topText;\n let bottomText = meme.bottomText;\n let imageURL = meme.backgroundImage;\n let memeUri = meme.memeUri;\n var d = new Date().toString();\n db.ref(\"profile/\" + uid + \"/memes\")\n .push({\n topText: topText,\n bottomText: bottomText,\n backgroundImageURL: imageURL,\n memeUri: memeUri,\n dateCreated: d \n })\n .then(res => {\n console.log(res);\n alert(\"Success\");\n })\n .catch(error => {\n console.log(error.message);\n });\n}", "function store(obj) {\n try {\n localStorage.setItem(storage, JSON.stringify(obj));\n } catch (err) {\n console.error(err);\n }\n}", "static add(accessControlProfile){\n\t\tlet kparams = {};\n\t\tkparams.accessControlProfile = accessControlProfile;\n\t\treturn new kaltura.RequestBuilder('accesscontrolprofile', 'add', kparams);\n\t}", "static addAlbum(album) {\n const albums = Storage.getAlbums();\n\n albums.push(album);\n\n localStorage.setItem('albums', JSON.stringify(albums));\n }", "static add(addResponseProfile){\n\t\tlet kparams = {};\n\t\tkparams.addResponseProfile = addResponseProfile;\n\t\treturn new kaltura.RequestBuilder('responseprofile', 'add', kparams);\n\t}", "function updateStorage() {\n console.log('Updating storage');\n Storage.updateSeenSession(_performers);\n \n _savedState.interactions = Exp.getInteractions();\n _savedState.experience = Exp.getExperience();\n _savedState.level = Exp.getLevel();\n \n Storage.updateStateStorage(_savedState);\n}", "function addLevelDBData(key, value) {\n //console.log(\"Current key value is \" + key)\n db.put(key, JSON.stringify(value), function(err) {\n if (err) return console.log('Block ' + key + ' submission failed', err);\n });\n}", "function setUpStorageClient(err, credentials){\n if (err) return console.log(err);\n\n storageClient = new StorageManagementClient(credentials, subscriptionId);\n //getStorageAccountsLists();\n //getStorageKeyList();\n createStorageAccount();\n //getStorageKeyList();\n}", "function writeUsageToStorage(callback) {\n try {\n \n var stat1 = getStats();\n timerId = setTimeout(function () {\n try {\n clearTimeout(timerId);\n var stat2 = getStats();\n var total1 = 0,\n total2 = 0,\n usage1 = 0,\n usage2 = 0;\n for (var i = 1; i <= 4; i++) {\n total1 += parseInt(stat1[i]);\n total2 += parseInt(stat2[i]);\n if (i != 4) {\n usage1 += parseInt(stat1[i]);\n usage2 += parseInt(stat2[i]);\n }\n }\n \n self.cpuUsage = ((100 * (usage2 - usage1)) / (total2 - total1));\n self.storageOperations.writeTable(self.cpuUsage, self.resourceGroup, function (err, result) {\n if (err) {\n callback(err);\n }\n });\n } catch (e) {\n callback(e);\n }\n }, 5000);\n } catch (e) {\n callback(e);\n }\n }", "createAccount()\n {\n account = this.web3.eth.accounts.create();\n\n vaultData.account_list.push(account)\n\n this.selectAccount( account.address )\n\n this.saveVaultData( vaultData )\n\n }", "static add(scheduledTaskProfile){\n\t\tlet kparams = {};\n\t\tkparams.scheduledTaskProfile = scheduledTaskProfile;\n\t\treturn new kaltura.RequestBuilder('scheduledtask_scheduledtaskprofile', 'add', kparams);\n\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Reset input Playlist Name and Playlist Url
function setResetInputsListener() { $("#reset").on('click', function(event) { event.preventDefault(); $("#Playlist_Name").val(""); $("#Playlist_Url").val(""); $("#thumbnail").attr("src", "https://vignette.wikia.nocookie.net/pandorahearts/images/7/70/No_image.jpg.png/revision/latest?cb=20121025132440&format=original"); }); }
[ "function updatePlaylist(playlist, artistName, songTitle){\n playlist[artistName] = songTitle\n return playlist\n}", "function clearInput() {\n $(\"#url\").val('');\n }", "function updatePlaylist(playlist, artistName, songTitle) {\n playlist[artistName] = songTitle\n\n return playlist\n}", "function clearObjectUrl() {\r\n document.getElementById('objectUrl').value = '';\r\n }", "function updatePlaylist(playlist) {\n _mostRecentPlaylist = playlist;\n $('#playlistqueue').empty();\n Promise.all(retrieveAllVideoTitles()).\n then(function(jsonResponseArray) {\n for (var i = 0; i < playlist.length; i += 1) {\n var title = jsonResponseArray[i].items[0].snippet.title;\n var videoID = playlist[i].video_id;\n var entryID = playlist[i].id;\n updatePlaylistDisplay(videoID, entryID, title);\n }\n });\n}", "function swapSongInfo()\r\n{\r\n\tvar artistInput = document.getElementById(\"lastfm-artist\");\r\n\tvar titleInput = document.getElementById(\"lastfm-title\");\r\n\t\r\n\tvar oldArtist = artistInput.value;\r\n\tvar oldTitle = titleInput.value;\r\n\t\r\n\tartistInput.value = oldTitle;\r\n\ttitleInput.value = oldArtist;\r\n}", "function deletePlaylist(plname){\n //incase plname include any special charactor that cannot use as key name\n var pname = replaceSpecialCharactors(plname);\n $(\"#selectPlaylist option[value='\" + pname + \"']\").remove();\n database.ref(\"users/\" + user + \"/playlists/\" + pname).remove()\n .then(()=>{\n $(\"#playlist\").empty();\n $(\"#playlist option[value='empty']\").attr(\"selected\",\"selected\");\n\n });\n}", "function getPlaylistInput() {\n return $('#playlistinput').val();\n}", "function resetPlayed() {\n for (i = 0; i < videoList.length; i++) {\n videoList[i][1] = false;\n }\n}", "function PlaylistEntry(title) {\n\t// alert(\"create new playlist entry.\");\n\tthis.title = title;\n\tthis.url = \"\";\n}", "function initYouTubeList(){\r\n var tabUrl = window.location.href;\r\n var youTubeListId = getURLParameter(tabUrl, 'list');\r\n if (youTubeListId && youTubeListId != playlistId){\r\n playlistId = youTubeListId;\r\n extractVideosFromYouTubePlaylist(youTubeListId);\r\n }\r\n}", "function fillSongInformation(song) {\r\n\tvar artistInput = document.getElementById(\"lastfm-artist\");\r\n\tvar titleInput = document.getElementById(\"lastfm-title\");\r\n\t\r\n\tif(song.artist != null) {\r\n\t\tartistInput.value = song.artist;\r\n\t}\r\n\tif(song.title != null) {\r\n\t\ttitleInput.value = song.title;\r\n\t}\r\n}", "clearInputs() {\r\n titleBook.value = '';\r\n authorBook.value = '';\r\n isbnBook.value = ''; \r\n}", "function removePlaylist( mixtape, change )\r\n{\r\n if ( change.playlistId > mixtape.playlists.length )\r\n {\r\n console.log( \"Playlist with id '\"+change.playlistId+\"' does not exists\");\r\n return;\r\n }\r\n var numId = parseInt(change.playlistId, 10); \r\n var newlist = mixtape.playlists.filter( el => el.id !== change.playlistId);\r\n mixtape.playlists = newlist;\r\n \r\n \r\n}", "function createPlaylist() {\n\tvar popup = prompt(\"Please enter the name of your playlist\");\n\tif(popup != null) {\n\n\t\t$.post(\"includes/handlers/ajax/createPlaylist.php\", { name: popup, username: userLoggedIn })\n\t\t.done(function(error) {\n\n\t\t\tif(error != \"\") {\n\t\t\t\t\talert(error);\n\t\t\t\t\treturn;\n\t\t\t}\n\t\t\t\topenPage(\"your-music.php\");\n\t\t});\n\t}\n}", "function resetSearch() {\n\t$searchInput.value = \"\";\n\t$navbarSearchInput.value = \"\";\n\tsetInactiveSearch();\n}", "function resetInput() {\n var commentInput = document.getElementById('commentInput');\n commentInput.value = \"\";\n }", "function runPrevKeyDownEvent() {\n /*\n Check to see if the current playlist has been set\n or null and set the previous song.\n */\n if (config.active_playlist == \"\" || config.active_playlist == null) {\n AudioNavigation.setPrevious();\n } else {\n AudioNavigation.setPreviousPlaylist(config.active_playlist);\n }\n }", "function update_playlists(pls) {\n if (playlist_cb) {\n playlist_cb(pls);\n }\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
zooms to bounding box identified by passed osm_id
function zoomTo(osm_id) { try { submitGetRequest( this.url + "?action=getBBOX4OSM_ID&OSM_ID=" + osm_id, handleGetBBOX4OSM_ID, null, false ); } catch(e) { alert( 1 + JSON.stringify( e ) ); } }
[ "function zoomToNode(id) {\n const node = figma.getNodeById(id);\n if (!node) {\n console.error(\"Could not find that node: \" + id);\n return;\n }\n figma.viewport.scrollAndZoomIntoView([node]);\n}", "function startBoxZooming(event, map) {\r\n let x0 = event.clientX;\r\n let x1 = x0;\r\n let y0 = event.clientY;\r\n let y1 = y0;\r\n document.addEventListener('mousemove', drawBox);\r\n document.addEventListener('mouseup', zoomBox);\r\n \r\n /* Click and drag to make a box... */\r\n function drawBox(event) {\r\n x1 = event.clientX;\r\n y1 = event.clientY;\r\n let x, y;\r\n if(x0 < x1) {\r\n x = x0;\r\n } else {\r\n x = x1;\r\n }\r\n if(y0 < y1) {\r\n y = y0;\r\n } else {\r\n y = y1;\r\n }\r\n map.update();\r\n map.context.beginPath();\r\n map.context.setLineDash([5, 5]);\r\n map.context.lineWidth = 2;\r\n map.context.strokeStyle = '#FF0000';\r\n map.context.rect(x, y, Math.abs(x1 - x0), Math.abs(y1 - y0));\r\n map.context.stroke();\r\n }\r\n \r\n /* ...then compute how much to zoom. */\r\n /* FIX: The zoom box method should belong to Map. */\r\n function zoomBox(event) {\r\n \r\n const x = (x0 + x1) / 2;\r\n const y = (y0 + y1) / 2;\r\n map.centeredAt = map.documentToMapCoords(x, y);\r\n \r\n const coords0 = map.documentToCanvasCoords(x0, y0);\r\n const coords1 = map.documentToCanvasCoords(x1, y1);\r\n const w = Math.abs(coords0[0] - coords1[0]);\r\n const h = Math.abs(coords0[1] - coords1[1]);\r\n const aspectAR = map.canvas.width / map.canvas.height;\r\n if(w / h > 1) {\r\n map.zoomFactor /= w / 2;\r\n } else {\r\n map.zoomFactor /= h / 2;\r\n }\r\n document.removeEventListener('mousemove', drawBox);\r\n document.removeEventListener('mouseup', zoomBox);\r\n map.update();\r\n }\r\n}", "function zoomToPolygon(PolygonId)\n{\n jQuery(function ($)\n {\n $(document).ready(function ()\n {\n\n require([\"esri/geometry/Point\", \"esri/map\", 'esri/geometry/webMercatorUtils'],\n function (Point, Map, webMercatorUtils)\n {\n var coordiantesString = document.getElementById(\"reviewMetadata\" + PolygonId.toString()).innerText;\n var pos = coordiantesString.indexOf(\":\");\n\n var lon = coordiantesString.substr(pos + 1, 11) * 1;\n var lat = coordiantesString.substr(pos + 13, 10) * 1;\n\n var point = new Point(lon, lat);\n var map_point = webMercatorUtils.geographicToWebMercator(point);\n\n top.dawgMap.map.centerAt(map_point);\n var newExtent = top.dawgMap.map.extent;\n map_point.x = map_point.x - (newExtent.xmax - newExtent.xmin)/4; \n top.dawgMap.map.centerAt(map_point);\n\n });\n });\n });\n}", "function zoom() {\n airbnbNodeMap.zoom();\n mapLineGraph.wrangleData_borough();\n}", "function zoomToFeature(e) {\n if (event.shiftKey) {\n map.fitBounds(e.target.getBounds());\n } else {\n populateGraphs(e);\n }\n }", "function doOnMouseover(id) {\n // delay between mousing over a list item and zooming over to preview it (ms)\n let delayBeforePreviewZoom = 250\n // delay between starting to zoom to a widget and zooming out for context (ms)\n let delayBeforeShowContextZoom = 600\n // how much to zoom out to show context\n let showContextZoomFactor = .30\n\n function previewZoom() {\n async function showContextZoom() {\n let zoomLevel = await miro.board.viewport.getZoom()\n await miro.board.viewport.setZoom(zoomLevel * showContextZoomFactor)\n }\n miro.board.viewport.zoomToObject(id)\n showContextZoomTimer = window.setTimeout(showContextZoom, delayBeforeShowContextZoom)\n }\n\n previewZoomTimer = window.setTimeout(previewZoom, delayBeforePreviewZoom)\n}", "function boxZoom(box, centroid, paddingPerc)\n {\n minZoom = Math.max(w/w,h/h);\n maxZoom = 20*minZoom;\n minXY = box[0];\n maxXY = box[1];\n // find size of map area defined\n zoomWidth = Math.abs(minXY[0] - maxXY[0]);\n zoomHeight = Math.abs(minXY[1] - maxXY[1]);\n // find midpoint of map area defined\n zoomMidX = centroid[0];\n zoomMidY = centroid[1];\n // increase map area to include padding\n zoomWidth = zoomWidth * (1 + paddingPerc / 100);\n zoomHeight = zoomHeight * (1 + paddingPerc / 100);\n // find scale required for area to fill svg\n maxXscale = w / zoomWidth;\n maxYscale = h/ zoomHeight;\n zoomScale = Math.min(maxXscale, maxYscale);\n // handle some edge cases\n // limit to max zoom (handles tiny countries)\n zoomScale = Math.min(zoomScale, maxZoom);\n // limit to min zoom (handles large countries and countries that span the date line)\n zoomScale = Math.max(zoomScale, minZoom);\n // Find screen pixel equivalent once scaled\n offsetX = zoomScale * zoomMidX;\n offsetY = zoomScale * zoomMidY;\n // Find offset to centre, making sure no gap at left or top of holder\n dleft = Math.min(0, w/ 2 - offsetX);\n dtop = Math.min(0, h / 2 - offsetY);\n // Make sure no gap at bottom or right of holder\n dleft = Math.max(w - w * zoomScale, dleft);\n dtop = Math.max(h - h * zoomScale, dtop);\n // set zoom\n svg\n .transition()\n .duration(500)\n .call(\n zoom.transform,\n d3.zoomIdentity.translate(dleft, dtop).scale(zoomScale)\n );\n }", "function panzoomWithViewBoxCoords(cssDiv, svg, x, y, w, h) {\n x = parseFloat(x);\n y = parseFloat(y);\n w = parseFloat(w);\n h = parseFloat(h);\n\n var viewBox = svg.getAttribute('viewBox');\n var viewX = parseFloat(viewBox.split(/\\s+|,/)[0]); // viewBox is [x, y, w, h], x == [0]\n var viewY = parseFloat(viewBox.split(/\\s+|,/)[1]);\n var viewW = parseFloat(viewBox.split(/\\s+|,/)[2]);\n var viewH = parseFloat(viewBox.split(/\\s+|,/)[3]);\n\n var cssW = $(cssDiv).width();\n var cssH = $(cssDiv).height();\n\n // Step 1, determine the scale\n var scale = Math.min(( viewW / w ), ( viewH / h ));\n\n $(cssDiv).panzoom('zoom', parseFloat(scale));\n\n // Determine bounding box -> CSS coordinate conversion factor\n var bcX = cssW / viewW;\n var bcY = cssH / viewH;\n\n // Step 2, determine the focal\n var bcx = viewX + (viewW / 2); // box center\n var bcy = viewY + (viewH / 2);\n\n var fx = (bcx - (x + (w / 2))) * bcX;\n var fy = (bcy - (y + (h / 2))) * bcY;\n\n // Step 3, apply $.panzoom()\n $(cssDiv).panzoom('pan', fx * scale, fy * scale);\n }", "fitBounds() {\n const { map } = this.context;\n\n if (this.layer.getBounds) {\n map.fitBounds(this.layer.getBounds());\n }\n }", "function resize() {\n\n var mapratio= parseInt(d3.select(tag_id).style('width'));\n\n if (width > 8*height) {\n mapratio = width /5;\n } else if (width > 6*height) {\n mapratio = width /4;\n } else if(width>4*height){\n mapratio = width /3;\n } else if(width> 2*height){\n mapratio = width/2;\n } else if(width >= height){\n mapratio = width;\n }\n\n projection.scale([mapratio]).translate([width/2,height/2]);\n }", "function zoomToPowerLine(powerLineId, powerLineLocationLatitude, powerLineLocationLongitude) {\n\tvar location = new google.maps.LatLng(powerLineLocationLatitude, powerLineLocationLongitude);\n\tvar dataAttributes= {\n\t\t\tpowerLineId : powerLineId,\n\t\t}\n\tvar options= {\n\t\t\tposition:location,\n\t\t\tpowerLineId : powerLineId\n\t}\n\tajaxRequest(\"getPowerLineInfo\", dataAttributes, getPowerLineInfoCallBack, options);\t\t\n\tmap.setCenter(location);\n\tmap.setZoom(18);\n\t\n}", "function zoomToArea() {\r\n // Initialize the geocoder.\r\n var geocoder = new google.maps.Geocoder();\r\n // Get the address or place that the user entered.\r\n var address = document.getElementById('zoom-to-area-text').value;\r\n // Make sure the address isn't blank.\r\n if (address == '') {\r\n window.alert('You must enter an area, or address.');\r\n }\r\n else {\r\n // Geocode the address/area entered to get the center. Then, center the map\r\n // on it and zoom in\r\n geocoder.geocode({\r\n address: address,\r\n componentRestrictions: {\r\n locality: 'Toronto'\r\n }\r\n }, function(results, status) {\r\n if (status == google.maps.GeocoderStatus.OK) {\r\n map.setCenter(results[0].geometry.location);\r\n map.setZoom(15);\r\n }\r\n else {\r\n window.alert(\r\n 'We could not find that location - try entering a more' +\r\n ' specific place.');\r\n }\r\n });\r\n }\r\n}", "function handleZoomToWaypointClick(e) {\n //make sure the waypoint is not empty\n if ($(e.currentTarget).parent().children(\".waypointResult\").children().length > 0) {\n theInterface.emit('ui:zoomToWaypoint', $(e.currentTarget).parent().attr(\"id\"));\n }\n }", "function zoomIn(image) {\n zoomedIn = true;\n createAndAddOverlay();\n fillZoom(image);\n}", "set boundingBoxMode(value) {}", "function onZoom()\r\n{\r\n\tevaluateLayerVisibility();\r\n\t$(\"#zoomlevel\").val(Math.floor(map.getView().getZoom()));\r\n}", "fitBounds() {\n const { map } = this.context\n\n if (this.layer.getBounds) {\n map.fitBounds(this.layer.getBounds(), {\n padding: 40,\n duration: 0,\n bearing: map.getMapGL().getBearing(),\n })\n }\n }", "function fitMapToBoundingBox(self) {\n self.fitToBoundingBox(getBoundingBox(self));\n return self;\n }", "function toggleBoundingBox(obj) {\n\tobj.checked = !obj.checked;\n\tobj.innerHTML = '&nbsp; bounding box';\n\tif (obj.checked) {\n\t\tobj.innerHTML = '&raquo; bounding box';\n\t}\n\tmyimgmap.config.bounding_box = obj.checked;\n\tmyimgmap.relaxAllAreas();\n\tgui_toggleMore();\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
the actual loading screen to be shown when you open the game
function loadingScreen() { textAlign(CENTER); textSize(40); image(player, width/4, width/4, width/2, width/2); text("LOADING. . .", width/2, width/2); }
[ "function displayLoadingScreenForInitialPageLoad() {\n\t\tdocument.getElementById(\"loading_screen\").style.display = \"block\";\n\t\tsetLoadingScreenDimensions();\n\t}", "function DefaultLoadingScreen(_renderingCanvas,_loadingText,_loadingDivBackgroundColor){if(_loadingText===void 0){_loadingText=\"\";}if(_loadingDivBackgroundColor===void 0){_loadingDivBackgroundColor=\"black\";}var _this=this;this._renderingCanvas=_renderingCanvas;this._loadingText=_loadingText;this._loadingDivBackgroundColor=_loadingDivBackgroundColor;// Resize\nthis._resizeLoadingUI=function(){var canvasRect=_this._renderingCanvas.getBoundingClientRect();var canvasPositioning=window.getComputedStyle(_this._renderingCanvas).position;if(!_this._loadingDiv){return;}_this._loadingDiv.style.position=canvasPositioning===\"fixed\"?\"fixed\":\"absolute\";_this._loadingDiv.style.left=canvasRect.left+\"px\";_this._loadingDiv.style.top=canvasRect.top+\"px\";_this._loadingDiv.style.width=canvasRect.width+\"px\";_this._loadingDiv.style.height=canvasRect.height+\"px\";};}", "function showLoadingStatus() {\n console.log(\"[menu_actions.js] Showing loading status\");\n showElementById(\"loading-status\");\n}", "function onScreenLoad(){\n\tstate = parent.newGameState(JSON.parse(localStorage[\"save\"]));\n\tstate.bugs = 9;\n\tscreen1.bugCount = $(\"#bugCount\");\n\tgenerateBreederList(state.breeders);\n\tdisplayTotal();\n\tparent.removeCover();\n}", "function displayGameScreen()\n{\n\t\n\tdisplayResourceElement();\n\t\t\t\n\tdisplayInfoElement();\n\t\n\tdisplayMapElement();\n\t\n\tjoinGame();\n\t\n\tif(player.onTurn == true)\n\t{\n\t\tdisplayEndTurnElement(\"salmon\");\n\t\t\n\t\tdisplayTurnCounterElement(\"lightGreen\");\n\t}\n\telse\n\t{\n\t\tdisplayEndTurnElement(\"lightSlateGrey\");\n\t\n\t\tdisplayTurnCounterElement(\"salmon\");\n\t}\n\t\n\tgameStarted = true;\n\t\n\tstage.update();\n}", "function state_loading() {\n status.loading = true;\n if (status.bar) status.bar.className = 'autopager_loading';\n }", "static waitToLoading() {\n browser.waitForExist(loading, timeToWait, true);\n if (browser.isVisible(introTask)) {\n browser.element(introTaskButton).click();\n }\n browser.waitForExist(introTask, timeToWait, true);\n }", "function GameScreenAssistant() { }", "function displayLoading() {\n\t$('div#loadingDialog').show();\n\tloadingCounter++;\n} // displayLoading()", "function loadContent(){\n pole = game.instantiate(new Pole(Settings.pole.size));\n pole.setColor(Settings.pole.color);\n pole.setPosition(Settings.canvasWidth /2 , Settings.canvasHeight /2);\n\n shield = game.instantiate(new Shield(pole));\n shield.getBody().immovable = true;\n shield.setColor(Settings.shield.color);\n\n player = game.instantiate(new Player(\"\"));\n player.setPole(pole);\n player.setShield(shield);\n pole.setPlayer(player);\n\n //Player labels, name is set once again when the user has filled in his/her name\n scoreLabel = game.instantiate(new ScoreLabel(player, \"Score: 0\"));\n scoreLabel.setPosition(Settings.label.score);\n\n nameLabel = game.instantiate(new Label(\"Unknown Player\"));\n nameLabel.setPosition(Settings.label.name);\n\n highscoreLabel = game.instantiate(new Label(\"Highscore: 0\"));\n highscoreLabel.setPosition(Settings.label.highscore);\n\n createTempImage();\n setTimeout(deleteTempImage, 3000);\n\n //Hide the canvas for the player until a username is filled in and accepted\n var gameElem = document.getElementById(\"gameCanvas\");\n gameElem.style.display=\"none\";\n}", "load() {\n log.debug('Entities - load()', this.game.renderer);\n this.game.app.sendStatus('Lots of monsters ahead...');\n\n if (!this.sprites) {\n log.debug('Entities - load() - no sprites loaded yet', this.game.renderer);\n this.sprites = new Sprites(this.game.renderer);\n\n this.sprites.onLoadedSprites(() => {\n log.debug('Entities - load() - sprites done loading, loading cursors');\n this.game.input.loadCursors();\n this.game.postLoad();\n this.game.start();\n });\n }\n\n this.game.app.sendStatus('Yes, you are also a monster...');\n\n if (!this.grids) {\n log.debug('Entities - load() - no grids loaded yet');\n this.grids = new Grids(this.game.map);\n }\n }", "showLoader () {\n if (this.hideLoader) return\n this.loadingWrapper.style.display = 'flex'\n this.canvas.style.display = 'none'\n }", "function resources_loaded_callback(){\n\n console.log(\"Resources loaded.\");\n\n show_loader_div(false);\n show_setting_div(true);\n show_canvas_div(true);\n\n // init mesh manager that may be contains some object loaded by model loader.\n EntityMeshManager.init();\n\n\n }", "function appAddLoader()\n\t{\n\t\tif (jQuery('#TB_load').size() != 0) return;\n\t\t\n\t\tjQuery('body').append('<div id=\"TB_load\" style=\"display: block;\"><div class=\"loader\"></div></div>');\n\t}", "function loadpage(){\n txt = 'Loading . . .';\n openprocessing();\n}", "displayPauseScreen() {\n\t\tgameState.pauseOverlay = this.add.rectangle(0, 0, 480, 640, 0xFFFFFF);\n\t\tgameState.pauseOverlay.alpha = 0.75;\n\t\tgameState.pauseOverlay.setOrigin(0, 0);\n\n\t\tgameState.pauseText = this.add.text(225, 325, 'PAUSED').setColor('#000000');\n\t\tgameState.resumeText = this.add.text(125, 375, 'Press space to resume game').setColor('#000000');\n\t}", "function DN_System_Load(){\r\nthis.wib = screen.width;\r\nthis.heb = screen.height;\r\nthis.documes = (document.getElementById || document.createElement || document.getElementsByTagName) ? true : false;\r\nthis.objects = window.addEventListener || window.attachEvent ? window : document.addEventListener ? document : null;\r\nthis.types = 'load';\r\n}", "function showGameScene() {\n gameStartScene.visible = false;\n clearDownCurrentBallons();\n gameScene.visible = true;\n\n createNewEquation();\n }", "function state_loaded() {\n status.loading = false;\n if (status.bar) status.bar.className = status.state ? 'autopager_on' : 'autopager_off';\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Reads a LEASE frame from the buffer and returns it.
function deserializeLeaseFrame(buffer, streamId, flags, encoders) { (0, _invariant2.default)( streamId === 0, 'RSocketBinaryFraming: Invalid LEASE frame, expected stream id to be 0.' ); let offset = FRAME_HEADER_SIZE; const ttl = buffer.readUInt32BE(offset); offset += 4; const requestCount = buffer.readUInt32BE(offset); offset += 4; let metadata = null; if (offset < buffer.length) { metadata = encoders.metadata.decode(buffer, offset, buffer.length); } return { flags, metadata, requestCount, streamId, ttl, type: _RSocketFrame.FRAME_TYPES.LEASE, }; }
[ "function getRomFrame(addr){\n\n}", "readKey() {\n const r = this.reader;\n\n let code = r.u8();\n\n if (code === 0x00) return;\n\n let f = null;\n let x = null;\n let y = null;\n let z = null;\n\n if ((code & 0xe0) > 0) {\n // number of frames, byte case\n\n f = code & 0x1f;\n\n if (f === 0x1f) {\n f = 0x20 + r.u8();\n } else {\n f = 1 + f;\n }\n } else {\n // number of frames, half word case\n\n f = code & 0x3;\n\n if (f === 0x3) {\n f = 4 + r.u8();\n } else {\n f = 1 + f;\n }\n\n // half word values\n\n code = code << 3;\n\n const h = r.s16big();\n\n if ((h & 0x4) > 0) {\n x = h >> 3;\n code = code & 0x60;\n\n if ((h & 0x2) > 0) {\n y = r.s16big();\n code = code & 0xa0;\n }\n\n if ((h & 0x1) > 0) {\n z = r.s16big();\n code = code & 0xc0;\n }\n } else if ((h & 0x2) > 0) {\n y = h >> 3;\n code = code & 0xa0;\n\n if ((h & 0x1) > 0) {\n z = r.s16big();\n code = code & 0xc0;\n }\n } else if ((h & 0x1) > 0) {\n z = h >> 3;\n code = code & 0xc0;\n }\n }\n\n // byte values (fallthrough)\n\n if ((code & 0x80) > 0) {\n if (x !== null) {\n throw new Error('Expected undefined x in SEQ animation data');\n }\n\n x = r.s8();\n }\n\n if ((code & 0x40) > 0) {\n if (y !== null) {\n throw new Error('Expected undefined y in SEQ animation data');\n }\n\n y = r.s8();\n }\n\n if ((code & 0x20) > 0) {\n if (z !== null) {\n throw new Error('Expected undefined z in SEQ animation data');\n }\n\n z = r.s8();\n }\n\n return { f, x, y, z };\n }", "function getNextFrame() {\n if (length >= frameByteSize) {\n // copy the frame\n buf.copy(frameBuffer, 0, 0, frameByteSize);\n // move remaining buffer content to the beginning\n buf.copy(buf, 0, frameByteSize, length);\n length -= frameByteSize;\n return frameBuffer;\n }\n return null;\n }", "function LEW(arr, off) {\n return arr[off+3]<<24&0xff000000 | arr[off+2]<<16&0xff0000\n | arr[off+1]<<8&0xff00 | arr[off]&0xFF;\n } // end of LEW", "readWord(address) {\n const lowByte = this.readByte(address);\n const highByte = this.readByte(address + 1);\n return word(highByte, lowByte);\n }", "async readLine() {\n const s = await this.readLineSlice();\n if (s === Deno.EOF)\n return Deno.EOF;\n return str(s);\n }", "restoreBuffer(old) {\n this.buf = old;\n }", "leave(...args) {\n const [handId, leaverAddr] = args;\n // make leave receipt\n // size: 32bytes receipt\n const payload = Buffer.alloc(32);\n // <1 bytes 0x00 space for v>\n payload.writeInt8(0, 0);\n // <7 bytes targetAddr>\n payload.write(this.targetAddr.replace('0x', '').substring(26, 40), 1, 'hex');\n // <4 bytes handId>\n payload.writeUInt32BE(handId, 8);\n // <20 bytes signerAddr>\n payload.write(leaverAddr.replace('0x', ''), 12, 'hex');\n return new Signer(args, [payload], Type.LEAVE);\n }", "async readByte() {\n while (this.r === this.w) {\n if (this.eof)\n return Deno.EOF;\n await this._fill(); // buffer is empty.\n }\n const c = this.buf[this.r];\n this.r++;\n // this.lastByte = c;\n return c;\n }", "matchBefore(expr) {\n let line = this.state.doc.lineAt(this.pos)\n let start = Math.max(line.from, this.pos - 250)\n let str = line.text.slice(start - line.from, this.pos - line.from)\n let found = str.search(ensureAnchor(expr, false))\n return found < 0\n ? null\n : { from: start + found, to: this.pos, text: str.slice(found) }\n }", "async readLine() {\n let line;\n try {\n line = await this.readSlice(LF);\n }\n catch (err) {\n let { partial } = err;\n asserts_ts_1.assert(partial instanceof Uint8Array, \"bufio: caught error from `readSlice()` without `partial` property\");\n // Don't throw if `readSlice()` failed with `BufferFullError`, instead we\n // just return whatever is available and set the `more` flag.\n if (!(err instanceof BufferFullError)) {\n throw err;\n }\n // Handle the case where \"\\r\\n\" straddles the buffer.\n if (!this.eof &&\n partial.byteLength > 0 &&\n partial[partial.byteLength - 1] === CR) {\n // Put the '\\r' back on buf and drop it from line.\n // Let the next call to ReadLine check for \"\\r\\n\".\n asserts_ts_1.assert(this.r > 0, \"bufio: tried to rewind past start of buffer\");\n this.r--;\n partial = partial.subarray(0, partial.byteLength - 1);\n }\n return { line: partial, more: !this.eof };\n }\n if (line === Deno.EOF) {\n return Deno.EOF;\n }\n if (line.byteLength === 0) {\n return { line, more: false };\n }\n if (line[line.byteLength - 1] == LF) {\n let drop = 1;\n if (line.byteLength > 1 && line[line.byteLength - 2] === CR) {\n drop = 2;\n }\n line = line.subarray(0, line.byteLength - drop);\n }\n return { line, more: false };\n }", "function read_encoder(a, b)\n{\n var a;\n var b;\n var new_state = 0;\n var return_state;\n a = bone.digitalRead('P8_13');\n b = bone.digitalRead('P8_15');\n new_state = (a * 4) | (b * 2) | (a ^ b);\n return_state = (new_state - old_state) % 4;\n if (return_state)\n console.log(' a:' + a + ' b: ' + b + ' new_state = ' + new_state + ' return = ' + return_state);\n old_state = new_state;\n return (return_state);\n}", "matchBefore(expr) {\n let line = this.state.doc.lineAt(this.pos);\n let start = Math.max(line.from, this.pos - 250);\n let str = line.slice(start - line.from, this.pos - line.from);\n let found = str.search(ensureAnchor(expr, false));\n return found < 0 ? null : { from: start + found, to: this.pos, text: str.slice(found) };\n }", "function getRomFrame(addr){\n\tvar bf = new bytebuffer(romFrameData);\n\tbf.position(addr);\n\tlet func = bf.get();\n\tif(func == 0x8) {\n\t\t\n\t}else if(func == 0xc) {\t// with 2 sub frames\n\t\tbf.skip();\n\t\taddr = bf.getInt();\n\t\tbf.position(addr + 1);\n\t} else {\n\t\tlabelInfo.innerHTML = 'unsupported';\n\t\treturn;\n\t}\n\tbf.skip(2);\n\t\n\tlet frame = {\n\t\t\tsprites : []\n\t};//debugger\n\tlet cnt = bf.get();\n\tfor(let i = 0;i < cnt;i++) {\n\t\tlet x = bf.getShort();\n\t\tlet y = -bf.getShort();\n\t\tlet nxy = bf.get();\n\t\tlet nx = nxy % 16;\n\t\tlet ny = nxy >> 4;\n\t\tlet palette = bf.get();\n\t\tlet tile = bf.getShort();\n\t\tlet sprite = {\n\t\t\t\tx : x,\n\t\t\t\ty : y,\n\t\t\t\ttile : tile,\n\t\t\t\tnx : nx + 1,\n\t\t\t\tny : ny + 1,\n\t\t\t\tvflip : palette & 0x40,\t// this tile need flip\n\t\t\t\thflip : palette & 0x20,\t// this tile need flip\n\t\t\t\tpal : palette & 0x1F,\n\t\t\t};\n\t\t\n\t\tframe.sprites.push(sprite);\n\t}\n\t\n\treturn frame;\n}", "readKeyboard(addr, clock) {\n addr -= BEGIN_ADDR;\n let b = 0;\n // Dequeue if necessary.\n if (clock > this.keyProcessMinClock) {\n const keyWasPressed = this.processKeyQueue();\n if (keyWasPressed) {\n this.keyProcessMinClock = clock + KEY_DELAY_CLOCK_CYCLES;\n }\n }\n // OR together the various bytes.\n for (let i = 0; i < this.keys.length; i++) {\n let keys = this.keys[i];\n if ((addr & (1 << i)) !== 0) {\n if (i === 7) {\n // Modify keys based on the shift force.\n switch (this.shiftForce) {\n case ShiftState.NEUTRAL:\n // Nothing.\n break;\n case ShiftState.FORCE_UP:\n // On the Model III the first two bits are left and right shift,\n // though we don't handle the right shift anywhere.\n keys &= ~0x03;\n break;\n case ShiftState.FORCE_DOWN:\n keys |= 0x01;\n break;\n }\n }\n b |= keys;\n }\n }\n return b;\n }", "getEncryptedELLData(telegram) {\n let packet = telegram.getPacket();\n let startIndex = 17;\n let length = packet.getBuffer().length - startIndex;\n\n return this.fetchData(packet, {\n BLOCK2_ENCRYPTED_ELL_DATA: {\n start: startIndex,\n length: length\n }\n });\n }", "async onEnterBuffer(details:BufferDetails) : Promise {\n try {\n const { pane, editor } = getPaneAndTextEditorForBuffer(details.bufferNumber);\n pane.activateItem(editor);\n } catch (e) {\n console.warn(e.message);\n }\n }", "function decrypt(buffer, params) {\n var key = extractKey(params);\n var rs = determineRecordSize(params);\n var start = 0;\n var result = new Buffer(0);\n\n for (var i = 0; start < buffer.length; ++i) {\n var end = start + rs + TAG_LENGTH;\n if (end === buffer.length) {\n throw new Error('Truncated payload');\n }\n end = Math.min(end, buffer.length);\n if (end - start <= TAG_LENGTH) {\n throw new Error('Invalid block: too small at ' + i);\n }\n var block = decryptRecord(key, i, buffer.slice(start, end));\n result = Buffer.concat([result, block]);\n start = end;\n }\n return result;\n}", "consumeStateBuffer(gameStates) {\n console.log(new Date() + ' consume');\n\n // Out of states. End of game.\n if (gameStates.length == 0) {\n return;\n }\n\n // Get current state.\n const gameState = gameStates.shift();\n\n // Move elf.\n this.elf = gameState.elf;\n this.gameStatus = gameState.gameStatus;\n this.cookies = gameState.cookies;\n this.arena = gameState.arena;\n this.failureMessage = gameState.failureMessage;\n\n // Success!\n if (this.gameStatus == GAME_STATUS_SUCCESS) {\n this.setChallengePassed(this.selectedDay);\n return;\n }\n\n setTimeout(() => this.play(gameStates), 500);\n }", "next () {\n // Wrap cursor to the beginning of the next non-empty buffer if at the\n // end of the current buffer\n while (this.buffer_i < this.buffers.length &&\n this.offset >= this.buffers[this.buffer_i].length) {\n this.offset = 0;\n this.buffer_i ++;\n }\n\n if (this.buffer_i < this.buffers.length) {\n let byte = this.buffers[this.buffer_i][this.offset];\n\n // Advance cursor\n this.offset++;\n return byte;\n }\n else {\n throw this.END_OF_DATA;\n }\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Save mapping from documentUri to graphUris, e.g. for future deletion operations
function saveDocToGraphMapping(documentUri, graphUris) { const prevGraphUris = privateData.documentToGraph[documentUri]; if (!prevGraphUris) { privateData.documentToGraph[documentUri] = new Set(graphUris); } else { graphUris.forEach(u => prevGraphUris.add(u)); } }
[ "function persistLinks(e) {\n var linksInCache = JSON.parse(CacheService.getPrivateCache().get('links'));\n var documentProperties = PropertiesService.getDocumentProperties();\n var linksInDoc = documentProperties.getProperty('LINKS');\n if(linksInDoc == null) {\n documentProperties.setProperty('LINKS', JSON.stringify(linksInCache));\n }\n else { \n linksInDoc = JSON.parse(documentProperties.getProperty('LINKS'));\n var newLinks = linksInDoc;\n var idsToAdd = Object.keys(linksInCache);\n for (var i = 0; i < idsToAdd.length; i++) {\n if(newLinks[idsToAdd[i]] == undefined) {\n newLinks[idsToAdd[i]] = [];\n }\n /* To avoid creating a new array in the JSON object */\n var nbElem = linksInCache[idsToAdd[i]].length;\n for (var j = 0; j < nbElem; j++) {\n newLinks[idsToAdd[i]].push(linksInCache[idsToAdd[i]][j]);\n }\n }\n documentProperties.setProperty('LINKS', JSON.stringify(newLinks));\n }\n DocumentApp.getUi().alert('Links saved');\n clearLinksInCache(); \n}", "function saveLinks(id, links, type) {\n links = links.trim().split(\",\") //turn comma separated list into array\n links.forEach(link => {\n if (type == \"doc\") {\n insert_docLink.run(id, link.trim())\n }\n else if (type == \"proj\") {\n insert_projLink.run(id, link)\n }\n })\n}", "async writeCurPeerUrls(peerUrls) {\n let data = JSON.stringify(peerUrls);\n return this.db.put(genKey('cur_peer_urls'), data);\n }", "function fixRelatedContentURIs(document) {\n function fixBlock(block) {\n if (block.content) {\n block.content.forEach(item => {\n if (item.mdn_url) {\n item.uri = mapToURI(item);\n delete item.mdn_url;\n }\n fixBlock(item);\n });\n }\n }\n document.related_content.forEach(block => {\n fixBlock(block);\n });\n}", "function asRdfStore(graph) {\n if (graph.rdfstore) return Promise.resolve(graph.rdfstore);\n else return denodeify(rdfstore, 'create', {}).then(function(store){\n return Promise.resolve(graph).then(function(graph){\n if (!graph.graphURI) return denodeify(store, 'insert', graph);\n else return denodeify(store, 'insert', graph, graph.graphURI);\n }).then(_.constant(store));\n });\n}", "function writeGraph(graph, resource, root, serverUri) {\n debug('PATCH -- Writing patched file')\n return new Promise((resolve, reject) => {\n const resourceSym = graph.sym(resource.url)\n const serialized = $rdf.serialize(resourceSym, graph, resource.url, resource.contentType)\n\n // First check if we are above quota\n overQuota(root, serverUri).then((isOverQuota) => {\n if (isOverQuota) {\n return reject(error(413,\n 'User has exceeded their storage quota'))\n }\n\n fs.writeFile(resource.path, serialized, {encoding: 'utf8'}, function (err) {\n if (err) {\n return reject(error(500, `Failed to write file after patch: ${err}`))\n }\n debug('PATCH -- applied successfully')\n resolve('Patch applied successfully.\\n')\n })\n }).catch(() => reject(error(500, 'Error finding user quota')))\n })\n}", "function BrowsingGraph() {\n this.urls = new Set();\n this.adj = new Map(); // id -> [id]\n this.utoi = new Map(); // url -> id\n this.itou = new Map(); // id -> url\n var _d3groups = [0];\n var id = 0;\n\n Array.prototype.copy = function () {\n var copy = new Array();\n this.forEach(function (elem) {\n copy.push(elem); \n });\n return copy;\n }\n\n this.getUrls = function () {\n return Array.from(this.urls).copy();\n }\n\n this.getNodes = function () {\n return Array.from(this.itou.entries()).map(function (kv) {\n return {id: kv[0], url: kv[1], group: 0};\n });\n };\n\n this.getLinks = function () {\n var links = [];\n this.adj.forEach(function (ts, s) {\n ts.forEach(function (t) {\n links.push({source: s, target: t, value: 1});\n });\n });\n return links;\n };\n\n this.getGroups = function () {\n return _d3groups.copy();\n };\n \n this.toJSON = function() {\n return {\n nodes: this.getNodes(), \n links: this.getLinks(),\n groups: this.getGroups()\n };\n };\n\n this.addNode = function(url) {\n if (!this.urls.has(url)) {\n this.urls.add(url);\n this.utoi.set(url,id);\n this.itou.set(id, url);\n id++;\n }\n };\n\n this.addLink = function(url_from, url_to) {\n this.addNode(url_from);\n this.addNode(url_to);\n var src = this.utoi.get(url_from);\n var dest = this.utoi.get(url_to);\n if (!this.adj.has(src)) {\n this.adj.set(src, new Set([dest]))\n } else {\n this.adj.get(src).add(dest);\n }\n };\n\n this.removeNode = function (url) {\n this.adj.delete(this.utoi.get(url));\n this.itou.delete(this.utoi.get(url));\n this.utoi.delete(url);\n this.urls.delete(url);\n };\n\n this.removeLink = function (from, to) {\n var f = this.utoi.get(from);\n var t = this.utoi.get(to);\n var newval = this.adj.get(f).filter(function (i) {\n return i != t;\n });\n this.adj.set(f, newval);\n };\n\n // Produces a json with nodes grouped by their old graphs\n this.mergeJSON = function(graphs) {\n graphs.push(this);\n var new_groups = new Map();\n graphs.forEach(function (g) {\n new_groups.set(g, new Map());\n });\n var g_ids = new Set();\n var new_id = 0;\n var _utoi = new Map();\n \n // Make unique group ids\n graphs.forEach(function (g) {\n var groups = new_groups.get(g);\n g.getGroups().forEach(function (g_id) {\n var key = 0;\n while (g_ids.has(key)) {\n key++;\n }\n g_ids.add(key);\n groups.set(g_id, key);\n });\n });\n\n // Rebuild nodes and ids\n var nodes = [];\n graphs.forEach(function (g) {\n g.getNodes().forEach(function (n) {\n _utoi.set(n.url, new_id);\n var group = new_groups.get(g).get(n.group);\n nodes.push({\n url: n.url, \n id: new_id++, \n group: group\n });\n });\n });\n\n // Rebuild links and ids\n var links = [];\n graphs.forEach(function (g) {\n g.getLinks().forEach(function (l) {\n var s = _utoi.get(g.itou.get(l.source));\n var t = _utoi.get(g.itou.get(l.target));\n links.push({\n source: s,\n target: t,\n value: 1\n });\n });\n });\n\n return {groups: Array.from(g_ids), nodes: nodes, links: links};\n };\n}", "function saveDrawnGraph(){\n topNodes = topData.nodes;\n topEdges = topData.edges;\n\n nodes = addNode(nodes, newNodeID, 'T', 300, 0);\n T = newNodeID;\n N = T + 1;\n E = topEdges.length;\n\n initialiseMatrices();\n\n for(var i = 0; i < topEdges.length; i++){\n var edge = topEdges.get(i);\n var from = edge.from, to = edge.to;\n if(from == -1){\n topEdges.update({id: i, from: T});\n edges[i].from = T;\n from = T;\n }\n if(to == -1) {\n topEdges.update({id: i, to: T});\n edges[i].to = T;\n to = T;\n }\n topAdjMatrix[from][to] = i;\n }\n\n topNodes.remove(-1);\n nodes.splice(1, 1);\n\n assignDataSets(nodes, edges);\n options.manipulation.enabled = false;\n}", "function saveUrlsOnWindowClosing(windowId) {\n chrome.storage.local.set({\"saved-urls\": urls}, null);\n}", "function saveDoc() {\n const currDoc = appData.currDoc();\n if (currDoc.filePath) {\n saveToFile(currDoc.filePath);\n return;\n }\n saveDocAs();\n}", "function saveDocument() {\n if (current.id) {\n console.log(\"saveDocument(old) started\");\n var isUpdateSupported = current.resources.self && $.inArray('PUT', current.resources.self.allowed) != -1;\n if (!isUpdateSupported) {\n alert(\"You are not allowed to update this document\");\n return;\n }\n showMessage(\"Updating existing document ...\");\n current.subject = $(\"#document-subject\").val();\n current.content.text = $(\"#document-text\").val();\n current.update().execute(function(response) {\n console.log(\"Update response = \" + JSON.stringify(response));\n loadDocuments();\n });\n }\n else {\n console.log(\"saveDocument(new) started\");\n showMessage(\"Saving new document ...\");\n current.subject = $(\"#new-document-subject\").val();\n current.html = $(\"#new-document-html\").val();\n user.privateDocuments.create(current).execute(function(response) {\n console.log(\"saveDocument(new) response = \" + JSON.stringify(response));\n loadDocuments();\n });\n }\n}", "function saveSvg(title, storageKey) {\n const svgXml = getSvgXml();\n const svgObject = { Title: title, SvgXml: svgXml };\n const jsonData = JSON.stringify(svgObject);\n localStorage.setItem(storageKey, jsonData);\n hasEdits(false);\n}", "function showLinkDialog_LinkSave(propert_key, url) {\n\tPropertiesService.getDocumentProperties().setProperty(propert_key, url);\n}", "async function saveDocData(name, desc, pathname, mimetype, userid, projid, replaces) {\n //use g_data later to get document related data like Notes, Supersedes, etc...\n\n if (!currentDBYear) { //If currentDBYear isn't set, retrieve it from database\n currentDBYear = get_db_year.get().Year;\n }\n if (currentDBYear != currentDate.getFullYear()) { //if no records exist or most recent is dated with other than current year\n currentDBYear = currentDate.getFullYear() //set currentDBYear to current year\n nextSerial = 0 //reset nextSerial to 0\n }\n\n if (!nextSerial) { //db year matches current but nextSerial not set\n nextSerial = get_last_Serial.get(currentDBYear).Serial; //get most recent Serial for current year\n }\n nextSerial++ //increment to next available ID\n\n //null values to be replaced by Description, Supersedes, and SupersededBy respectively \n docid = insert_doc.run(currentDBYear, nextSerial, name, desc, pathname, mimetype, userid, projid, currentDate.toString(), replaces, null).lastInsertRowid\n return [docid, currentDBYear, nextSerial]\n}", "store() {\n let sitemap = sitemapGenerator.build(this.hostname, this.router);\n console.log(sitemap);\n }", "function saveBuildingDetail(document,callback) {\n\tdocument.save(function(err) {\n\t\tlogger.debug(\"In saveBuilding method\");\n\t\tif(err) {\n\t\t\t\tlogger.error(\" In saveBuilding method >> error >> \" + err);\n\t\t\t\t//callback(err,null);\n\t\t} \n\t\tcallback(null,document);\n\t});\n}", "function saveStoredThings(){\n localStorage.setItem('fronter_fixes_links', links);\n}", "function saveStarred(tabId, info) {\n var url = tabToUrl[tabId.toString()];\n if (info.isWindowClosing && starredTabs[tabId]) {\n if (typeof url != \"undefined\") {\n urls[url] = true;\n chrome.storage.local.set({\"saved-urls\": urls}, null);\n }\t\n }\n else {\n delete urls[url];\n chrome.storage.local.set({\"saved-urls\": urls}, null);\n }\n}", "function guardar(){\n const custom = customFile.files[0];\n const fileName = custom.name;\n const metadata = {\n contentType: custom.type\n };\n const task = firebase.storage().ref('images') \n .child(fileName)\n .put(custom, metadata);\n task.then(snapshot => snapshot.ref.getDownloadURL()) //obtenemos la url de descarga (de la imagen)\n .then(url => {\n console.log(\"URL del archivo > \"+url);\n const titulopublicacion = document.getElementById('titulopublicacion').value;\n document.getElementById('titulopublicacion').value = '';\n const publicacion = document.getElementById('publicacion').value;\n document.getElementById('publicacion').value = '';\n\n db.collection(\"publicacion\").add({ \n title: titulopublicacion,\n text: publicacion,\n img: url,\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 });\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
this loops over all the databases and creates pool cluster objects map in poolClusters
static init() { const oThis = this; // looping over all databases for (let dbName in mysqlConfig['databases']) { let dbClusters = mysqlConfig['databases'][dbName]; // looping over all clusters for the database for (let i = 0; i < dbClusters.length; i++) { let cName = dbClusters[i], cConfig = mysqlConfig['clusters'][cName]; // creating pool cluster object in poolClusters map oThis.generateCluster(cName, dbName, cConfig); } } }
[ "function DBCluster(props) {\n return __assign({ Type: 'AWS::Neptune::DBCluster' }, props);\n }", "function loadClouds() {\n cloud01.create();\n cloud02.create();\n cloud03.create();\n cloud04.create();\n cloud05.create();\n cloud06.create();\n cloud07.create();\n}", "function DBCluster(props) {\n return __assign({ Type: 'AWS::RDS::DBCluster' }, props);\n }", "reload() {\n // start agents for all existing cloud pools\n const agents_to_start = system_store.data.pools.filter(pool =>\n (!_.isUndefined(pool.cloud_pool_info) || !_.isUndefined(pool.mongo_pool_info))\n );\n dbg.log0(`will start agents for these pools: ${util.inspect(agents_to_start)}`);\n return P.map(agents_to_start, pool => this._start_pool_agent(pool));\n }", "function syncWithAll(){\r\n for(var svr of knownMasterServers){\r\n syncWithKnownMasterServer(svr);\r\n }\r\n}", "function applyToAllDB(func){\r\n let db_types = ['bbs', 'es', 'feskills', 'info', 'items', 'ls'];\r\n let servers = ['gl', 'eu', 'jp'];\r\n for (let s = 0; s < servers.length; ++s) {\r\n for (let d = 0; d < db_types.length; ++d) {\r\n func(servers[s],db_types[d]);\r\n }\r\n }\r\n}", "function databaseInitialize() {\n if (!db.getCollection(collections.PLACES)) {\n db.addCollection(collections.PLACES);\n }\n\n if (!db.getCollection(collections.RATINGS)) {\n db.addCollection(collections.RATINGS);\n }\n}", "function listDatabases() {\n mongoDatabase(function (client) {\n const adminDb = client.db().admin();\n\n adminDb.listDatabases({ nameOnly: false }, function (err, results) {\n console.log(results);\n client.close();\n });\n })\n}", "function cluster(dictionary_cols, dictionary_tables) {\n\n // Init\n var cluster_all_entities = [];\n var cluster_all_relations = [];\n cluster_keyword_entities = [];\n\n // For one iteration of clustering\n var cluster_a;\n var cluster_b;\n var cluster_rel;\n var list_keys_pri = [];\n var list_keys_pri_prev = [];\n var tableName;\n\n // 1\n // Transforming dictionary_tables into string of the form:\n // var str = \"col1.col2.[...].tableName\";\n var str;\n for (var t in dictionary_tables) {\n str = \"\";\n for (var col in dictionary_tables[t].cols) {\n if (dictionary_tables[t].cols[col].isKey) {\n str += dictionary_tables[t].cols[col].name + \".\";\n }\n }\n str += t;\n list_keys_pri.push(str);\n }\n\n // 2\n // sort the list of primary keys\n list_keys_pri.sort();\n\n // Until all tables are classified\n while (list_keys_pri.length !== 0) {\n\n // 3\n // Get starting point\n // Starting point 1 \"str_start\" is first key in the list\n // Starting point 2 \"str_start2\" is first key in the list\n // that does not contian \"str_start\"\n var str_start = list_keys_pri[0].split(\".\")[0];\n var str_start2;\n for(var key = 1; key < list_keys_pri.length; key++){\n if (!list_keys_pri[key].includes(str_start)) {\n str_start2 = list_keys_pri[key].split(\".\")[0]; // first token (pri key)\n break;\n }\n }\n\n // Setting up this iteration\n cluster_keyword_entities.push(str_start );\n cluster_keyword_entities.push(str_start2 );\n // prev = curr\n list_keys_pri_prev = list_keys_pri;\n list_keys_pri = [];\n\n // clearing out clusters\n cluster_a = [];\n cluster_b = [];\n cluster_rels = [];\n\n // for all tables\n for(var i = 0; i < list_keys_pri_prev.length; i++){\n\n // get table name from \"col1.col2.[...].tableName\"\n tableName = list_keys_pri_prev[i].split(\".\");\n tableName = tableName[tableName.length - 1];\n\n // evaluate which cluster they belong in\n var isInA = list_keys_pri_prev[i].includes(str_start);\n var isInB = list_keys_pri_prev[i].includes(str_start2);\n\n // Append to appropriate cluster\n if (isInA && isInB) {\n // belongs in abstract relationship\n cluster_rels.push(tableName);\n } else if (isInA && !isInB) {\n // belongs in abstract entity 1\n cluster_a.push(tableName);\n } else if (!isInA && isInB) {\n // belongs in abstract entity 2\n cluster_b.push(tableName);\n } else {\n // belongs elsewhere\n list_keys_pri.push(list_keys_pri_prev[i]);\n }\n }\n\n // Append clusters to main data structure\n cluster_all_entities.push(cluster_a);\n cluster_all_entities.push(cluster_b);\n cluster_all_relations.push(cluster_rels);\n\n }\n\n var data = {};\n data.entities = cluster_all_entities;\n data.relations = cluster_all_relations;\n return data;\n\n}", "pushRefreshedDatas() {\n var tt = this;\n MongoClient.connect(this.uri, function(err, db) {\n if (err) throw err;\n //Looking for a db called test\n var dbo = db.db(\"test\");\n for (var i = 0; i < tt.collections.length; ++i) {\n dbo.collection(\"rss\").insertOne(tt.collections[i],function(err, result) {\n if (err) throw err;\n });\n }\n db.close();\n });\n }", "async function buildDatabaseAndCollections(error, database) {\r\n\t// If we have an error...\r\n\tif (error) {\r\n\t\t// Log it\r\n\t\tconsole.log('database error: ', error);\r\n\t// Otherwise...\r\n\t} else {\r\n\t\t// Setup a database object\r\n\t\tlet databaseObject = database.db(config.database.name);\r\n\t\t// Call our creation events asyncronishly\r\n\t\ttry {\r\n\t\t\tawait createCollection( databaseObject, 'users' );\r\n\t\t\tawait createCollection( databaseObject, 'tasks' );\r\n\t\t\t// await createCollection( databaseObject, 'authentication' ); // Creating a seperate JWT Database so we can log history of user tokens\r\n\t\t} catch (creationError) {\r\n\t\t\tconsole.log(\"Unhandled Error in Collection Creation Run\", creationError);\r\n\t\t}\r\n\t\t// Once they've finished, close the DB.\r\n\t\tdatabase.close();\r\n\t}\r\n}", "function ensureAllDatasetsMapToCancer(){\n\t\t\tdatasets.forEach(function(db){\n\t\t\t\tif (!datasetToCancer[db]){\n\t\t\t\t\tconsole.log(\"Unknown cancer type: \" + db);\n\t\t\t\t\tprocess.exit(1);\n\t\t\t\t}\n\t\t\t});\n\t\t}", "startPool(callback) {\n // Invoke connection pool\n this.poolStorage = this.createPool(this.options.mySQLSettings);\n // Start connection pool monitor\n this.closeIdlePools(\n this.poolStorage,\n this.currentSessionId(),\n this.poolActivity,\n this.options.idlePoolTimeout\n );\n // Start idle connection monitor\n this.closeIdleConnections(\n this.poolStorage,\n this.currentSessionId(),\n this.poolConnectionList\n );\n // Assign event listeners to pool\n this.assignEventListeners();\n // Register connection pool settings\n this.poolSettings[this.currentSessionId()] = this.options.mySQLSettings;\n // Set connection activity to 0\n this.poolActivity[this.currentSessionId()] = 0;\n // Callback if nessesary\n return typeof callback === 'function' ? callback() : void 0;\n }", "static createIDBObjects(){\r\n\r\n\t\treturn idb.open(DBHelper.IDB_DATABASE, 1, upgradeDb => {\r\n\r\n\t\t\tvar restaurantsStore = upgradeDb.createObjectStore('restaurants',{\r\n\t\t\t\tkeyPath: 'id'\r\n\t\t\t});\r\n\r\n\t\t\tvar reviewsStore = upgradeDb.createObjectStore('reviews',{\r\n\t\t\t\tkeyPath: 'id'\r\n\t\t\t});\r\n\t\t\treviewsStore.createIndex(\"restaurant_id\", \"restaurant_id\");\r\n\r\n\t\t\tvar offlineStore = upgradeDb.createObjectStore('offlineRequests',{\r\n\t\t\t\tkeyPath: 'id',\r\n\t\t\t\tautoIncrement: true\r\n\t\t\t});\r\n\r\n\t\t});\r\n\t}", "_closeMongos(){\n this._mongoAliases.forEach(alias => {\n delete this[alias]\n })\n\n this._mongoDbNames.forEach((refName)=>{\n if (this[refName] == null)\n return\n\n this._closePromises.push(this[refName].close().then(()=>{\n self._logger.info(`Mongo/${refName} connection closed`)\n delete this[refName]\n })\n .catch(()=>{\n self._logger.info.log(`Mongo/${refName} connection close error`)\n delete this[refName]\n return Promise.resolve() // resolve anyway\n }))\n })\n }", "static _createStores(connection) {\n store.forEach(store => {\n if (connection.objectStoreNames.contains(store)) { // caso tenha uma store, ela será deletada.\n connection.deleteObjectStore(store);\n }\n \n connection.createObjectStore(store, { // Caso tudo esteja correto, será criado uma nova store.\n autoIncrement: true\n });\n });\n\n }", "async function createArtistDB() {\n for (var i = 0; i < artistLink.length; i++) {\n await timeoutPromise(1000);\n scraper(artistLink[i], ArtistDB);\n }\n await timeoutPromise(5000);\n console.log(ArtistDB);\n enrichingArtistDB(ArtistDB);\n}", "function initDb() {\n\n\t\tif(fs.existsSync(path.join(cloudDir ,dbName))){\n\t\t\t//TODO: catch errors\n\t\t\tfs.createReadStream(path.join(cloudDir ,dbName))\n\t\t\t\t.pipe(fs.createWriteStream(path.join(tempDir, dbName)));\n\t\t\n\t\t}\n\t\n\t}", "function enableClusterers() {\n\n\t\tclusters.moto = {\n\t\t\tgridSize: 50,\n\t\t\tstyles: [\n\t\t\t\t{textColor: 'white', url: '/media/ui/img/map/cluster-blue.png', height: 33, width: 33},\n\t\t\t\t{textColor: 'white', url: '/media/ui/img/map/cluster-blue.png', height: 33, width: 33},\n\t\t\t\t{textColor: 'white', url: '/media/ui/img/map/cluster-blue.png', height: 33, width: 33}\n\t\t\t]\n\t\t}\n\t\tclusters.auto = {\n\t\t\tgridSize: 50,\n\t\t\tstyles: [\n\t\t\t\t{textColor: 'white', url: '/media/ui/img/map/cluster-red.png', height: 33, width: 33},\n\t\t\t\t{textColor: 'white', url: '/media/ui/img/map/cluster-red.png', height: 33, width: 33},\n\t\t\t\t{textColor: 'white', url: '/media/ui/img/map/cluster-red.png', height: 33, width: 33}\n\t\t\t]\n\t\t}\n\t\tclusters.collection = {\n\t\t\tgridSize: 50,\n\t\t\tstyles: [\n\t\t\t\t{textColor: 'white', url: '/media/ui/img/map/cluster-yellow.png', height: 33, width: 33},\n\t\t\t\t{textColor: 'white', url: '/media/ui/img/map/cluster-yellow.png', height: 33, width: 33},\n\t\t\t\t{textColor: 'white', url: '/media/ui/img/map/cluster-yellow.png', height: 33, width: 33}\n\t\t\t]\n\t\t}\n\n\t\tclusters.moto = new MarkerClusterer($kapmap.map, [], clusters.moto);\n\t\tclusters.auto = new MarkerClusterer($kapmap.map, [], clusters.auto);\n\t\tclusters.collection = new MarkerClusterer($kapmap.map, [], clusters.collection);\n\n\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Draw a mark to the given position
__mark(context, Position) { const { x, y, } = this.CoordinateTransform(Position); // Get real position if (Position.x != 1 && Position.y != 1) { // left top this.__line(context, { x: x - 10, y: y - 5 }, { x: x - 5, y: y - 5 }); this.__line(context, { x: x - 5, y: y - 10 }, { x: x - 5, y: y - 5 }); } if (Position.x != 1 && Position.y != 10) { // left bottom this.__line(context, { x: x - 10, y: y + 5 }, { x: x - 5, y: y + 5 }); this.__line(context, { x: x - 5, y: y + 10 }, { x: x - 5, y: y + 5 }); } if (Position.x != 9 && Position.y != 1) { // right top this.__line(context, { x: x + 10, y: y - 5 }, { x: x + 5, y: y - 5 }); this.__line(context, { x: x + 5, y: y - 10 }, { x: x + 5, y: y - 5 }); } if (Position.x != 9 && Position.y != 10) {// right bottom this.__line(context, { x: x + 10, y: y + 5 }, { x: x + 5, y: y + 5 }); this.__line(context, { x: x + 5, y: y + 10 }, { x: x + 5, y: y + 5 }); } }
[ "function moveMarks() {\r\n moveCircleMark();\r\n moveSquareMark();\r\n }", "function markModel(markMode, rectangle) {\n\n\n\n}", "function placeMark(x, y, image) {\n // the particle will be scaled from min to max to add variety\n var scale = Math.random() * (trpm.maxScale - trpm.minScale) + trpm.minScale;\n var w = image.width;\n var h = image.height;\n\n if (clearPathContext) {\n clearPathContext.globalAlpha = Math.random() * (trpm.maxOpacity - trpm.minOpacity) + trpm.minOpacity;\n clearPathContext.globalCompositeOperation = \"destination-out\";\n clearPathContext.drawImage(\n // image\n image,\n // source x\n 0,\n // source y\n 0,\n // source width\n w,\n // source height\n h,\n // target x\n x - w / 2,\n // target y\n y - h / 2,\n // target width\n w * scale,\n // target height\n h * scale);\n // request to update that out of normal rendering loop\n requestFrameRender();\n }\n }", "positionMarkings() {}", "function useMarker(curLocX, curLocY, curColor)\n{\n\t// Draw the marker tool background(rectangle, or circle...)\n\tcontext.drawImage(markerBackgroundImage, 0, 0, canvasWidth, canvasHeight);\n\t\n\t// for the marker give the shape shows\n\tdrawPolyLine(curLocX, curLocY, curColor);\n\n\tif (mBrushShape == 0)\n\t{\n\t\t// 0 represents the circle\n\t\tcontext.drawImage(markerImage, locX, locY, mediumImageRadius);\n\t}\n\telse if (mBrushShape == 1)\n\t{\n\t\t// 1 reprensents the square\n\t\tcontext.drawImage(markerImage, locX, locY, square);\n\t}\n}", "function drawNote(i,j) {\n // Corde à ne pas jouer\n if (j =='x') {\n drawX(i);\n return;\n }\n\n ctx.beginPath();\n ctx.strokeStyle = \"#369\";\n ctx.fillStyle=\"#c00\";\n var center = getCenter(i,j);\n // Corde vide : rond vide\n if (j == '0') {\n ctx.arc(center[0],center[1],4,0,Math.PI*2,false);\n ctx.stroke();\n } else { // Une note à marquer : rond plein\n ctx.arc(center[0],center[1],6,0,Math.PI*2,false);\n ctx.fill();\n }\n ctx.closePath();\n }", "drawNote() {\n push();\n colorMode(HSB, 360, 100, 100);\n stroke(this.color, 100, 100, 100);\n fill(this.color, 100, 100, 100);\n let v = this;\n let v2 = createVector(v.x + 5, v.y - 15);\n circle(v.x, v.y, 7);\n strokeWeight(3);\n line(v.x + 3, v.y, v2.x, v2.y);\n quad(v2.x, v2.y, v2.x + 5, v2.y + 2, v2.x + 6, v2.y, v2.x, v2.y - 2);\n pop();\n }", "function addMarkedSpan(line, span) {\n line.markedSpans = line.markedSpans ? line.markedSpans.concat([span]) : [span];\n span.marker.attachLine(line);\n }", "function drawPoint() {\n push();\n noStroke();\n fill(String(this.color));\n ellipse(this.x, this.y, this.strokeSize, this.strokeSize);\n pop();\n}", "function drawLeaf(str, x, y, d) {\n stroke(100, 255, 100);\n fill(200, 255, 200);\n ellipse(x, y, d, d);\n label(str, x, y, -d/5, d/4);\n}", "function breakMark(cm, marker, chOffset) {\n cm.operation(function () {\n var pos = marker.find().from;\n pos = { line: pos.line, ch: pos.ch + ~~chOffset };\n cm.setCursor(pos);\n cm.focus();\n marker.clear();\n });\n }", "function drawText() {\n push();\n textAlign(CENTER);\n fill(this.color);\n textSize(this.size);\n text(this.txt, this.x, this.y);\n pop();\n}", "set_marks(mark) {\n this.V.forEach(v => {\n v.mark = mark;\n });\n }", "function drawMarkers(plot, ctx) {\n \"use strict\"\n var tmp, maxIndex;\n var xMin = plot.getOptions().xaxis.min;\n var xMax = plot.getOptions().xaxis.max;\n var px = plot.getAxes().xaxis;\n var py = plot.getAxes().yaxis;\n var canvas = $(plot.getCanvas());\n var ctx = canvas[0].getContext('2d'); \n var offset = plot.getPlotOffset();\n var radius = 10;\n var dx, dy; //coordinates of highest point\n var sx, sy; // coordinates of indicator shape\n var max; //maximum value of series at set timeframe\n //indicator dimensions\n var IND_HEIGHT = 24; \n var IND_WIDTH = 30;\n var textOffset_x = 0; //indicator text horizontal offset\n\n //draw indicator for each series \n $.each(plot.getData(), function (i, val) {\n tmp = splitArray(val.datapoints.points, val.datapoints.pointsize, xMax, xMin);\n //acquire the index of the highest value for each series\n maxIndex = tmp.y.indexOf(Math.max.apply(Math, tmp.y)); \n max = tmp.y[maxIndex];\n //transform data point x & y values to canvas coordinates\n dx = px.p2c(tmp.x[maxIndex]) + offset.left;\n dy = py.p2c(tmp.y[maxIndex]) + offset.top - 12;\n sx = dx + 2;\n sy = dy - 22;\n\n //draw indicator\n ctx.beginPath(); \n ctx.moveTo(sx, sy + IND_HEIGHT);\n ctx.lineTo(sx, sy + 30);\n ctx.lineTo(sx + 5, sy + IND_HEIGHT);\n ctx.closePath();\n ctx.fillStyle = val.color; \n\n //set horizontal text offset based on value. \n /*\n TODO:\n Make this more robust - base length adjustment on number of chars instead\n */\n if (max < 10) {\n textOffset_x = 12;\n }\n else if (max >= 10 && max < 100) {\n textOffset_x = 8;\n }\n else if (max >= 100 && max <= 1000) {\n textOffset_x = 4;\n }\n\n ctx.rect(sx,sy, IND_WIDTH, IND_HEIGHT);\n ctx.fillStyle = val.color; \n ctx.fill(); \n\n ctx.fillStyle = '#fff' \n ctx.font = '11pt Calibri';\n ctx.fillText(max, sx + textOffset_x ,sy + 16 ); \n });\n }", "function plotPoint(title, lat, lon){\n\n\n\n\tlat = parseFloat(lat);\n\tlon = parseFloat(lon);\n\n\tvar placemark = ge.createPlacemark('');\n\n\n\tplacemark.setName(title);\n\n\t// Define a custom icon.\n\tvar icon = ge.createIcon('');\n\ticon.setHref('http://maps.google.com/mapfiles/kml/shapes/placemark_circle.png');\n\tvar style = ge.createStyle(''); //create a new style\n\tstyle.getIconStyle().setIcon(icon); //apply the icon to the style\n\tplacemark.setStyleSelector(style); //apply the style to the placemark\n\n\t// Set the placemark's location. \n\tvar point = ge.createPoint('');\n\t//console.log(lat);\n\tpoint.setLatitude(lat);\n\tpoint.setLongitude(lon);\n\tplacemark.setGeometry(point);\n\n\t// Add the placemark to Earth.\n\tplacemarkFolder.getFeatures().appendChild(placemark);\n\tge.getFeatures().appendChild(placemarkFolder);\n\n}", "noteAt(note, glyph, withLineTo = true) {\n if (!note) throw \"NeumeBuilder.noteAt: note must be a valid note\";\n\n if (!glyph) throw \"NeumeBuilder.noteAt: glyph must be a valid glyph code\";\n\n note.setGlyph(this.ctxt, glyph);\n var noteAlignsRight = note.glyphVisualizer.align === \"right\";\n\n var needsLine =\n withLineTo &&\n this.lastNote !== null &&\n (this.lineIsHanging ||\n (this.lastNote.glyphVisualizer &&\n this.lastNote.glyphVisualizer.align === \"right\") ||\n Math.abs(this.lastNote.staffPosition - note.staffPosition) > 1);\n\n if (needsLine) {\n var line = new NeumeLineVisualizer(\n this.ctxt,\n this.lastNote,\n note,\n this.lineIsHanging\n );\n this.neume.addVisualizer(line);\n line.bounds.x = Math.max(this.minX, this.x - line.bounds.width);\n\n if (!noteAlignsRight) this.x = line.bounds.x;\n }\n \n let xOffset = 0;\n if (note.shapeModifiers & NoteShapeModifiers.Linea) {\n var linea = new LineaVisualizer(\n this.ctxt,\n note\n );\n this.neume.addVisualizer(linea);\n note.origin.x += linea.origin.x;\n xOffset = linea.origin.x;\n }\n\n // if this is the first note of a right aligned glyph (probably an initio debilis),\n // then there's nothing to worry about. but if it's not then first, then this\n // subtraction will right align it visually\n if (noteAlignsRight && this.lastNote)\n note.bounds.x = this.x - note.bounds.width;\n else {\n note.bounds.x = this.x + xOffset;\n this.x += note.bounds.width + xOffset;\n }\n\n this.neume.addVisualizer(note);\n\n this.lastNote = note;\n this.lineIsHanging = false;\n\n return this;\n }", "display() {\n //set the color\n stroke(this.element*255) ;\n //draw the point\n point(this.identity.x,this.identity.y)\n }", "function drawPt(x, y, color,isFill,radius) {\n \n\tctx.fillStyle = color;\n ctx.beginPath();\n \n\tctx.arc(x, y, radius, 0, 2*Math.PI);\n ctx.closePath();\n ctx.stroke();\n if(isFill)\n {\n \tctx.fill();\n }\n ctx.fillStyle = \"black\";\n}", "function drawPointerPos() {\n circle(context,pointer.x,pointer.y,pointer.radius/step*50);\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Data maintenance / cleaning helper TODO: validation according to further criteria e.g. re where the list of all currencies and precious metals are available We take it granted for now that each entry in fx.json is of a valid currency type Some currencies are misrepresented in the data set (e.g. MOP), maybe some statistical checks would be in place in real life applications as well.
function cleanFx() { // Remove entries without a currency code present fxData.fx = fxData.fx.filter(fx => fx.currency && (typeof fx.currency === "string") && fx.currency.trim() !== "" && fx.currency.trim() !== "XXX" ); }
[ "function parsetransData(d){\n \n return{\n geoid_2: +d.geoid_2,\n geography: d.geo_display,\n total_population: +d.HC01_EST_VC01,\n age_group: [\n {'16-19': +d.HC01_EST_VC03},\n {'20-24': +d.HC01_EST_VC04},\n {'25-44': +d.HC01_EST_VC05},\n {'45-54': +d.HC01_EST_VC06},\n {'55-59': +d.HC01_EST_VC07},\n {'60+': +d.HC01_EST_VC08} \n ],\n median_age: +d.HC01_EST_VC10,\n earnings_group: [\n {'1-9999': +d.HC01_EST_VC42},\n {'10000-14999': +d.HC01_EST_VC43},\n {'15000-24999': +d.HC01_EST_VC44},\n {'25000-34999': +d.HC01_EST_VC45},\n {'35000-49999': +d.HC01_EST_VC46},\n {'50000-64999': +d.HC01_EST_VC47},\n {'65000-74999': +d.HC01_EST_VC48},\n {'75000+': +d.HC01_EST_VC49}\n ],\n median_earnings: +d.HC01_EST_VC51,\n industries_group: [\n {'argriculture': +d.HC01_EST_VC69},\n {'construction': +d.HC01_EST_VC70},\n {'manufacturing': +d.HC01_EST_VC71},\n {'wholesale trade': +d.HC01_EST_VC72},\n {'retail trade': +d.HC01_EST_VC73},\n {'transportation&warehouse': +d.HC01_EST_VC74},\n {'information&finance': +d.HC01_EST_VC75},\n {'professional&scientific services': +d.HC01_EST_VC76},\n {'healthcare&educational&social assistance': +d.HC01_EST_VC77},\n {'entertainment&recreation': +d.HC01_EST_VC78},\n {'public administration': +d.HC01_EST_VC80},\n {'armed forces': +d.HC01_EST_VC81},\n {'other services': +d.HC01_EST_VC79} \n ],\n time_group: [{'10': +d.HC01_EST_VC103},\n {'10-14': +d.HC01_EST_VC104},\n {'15-19': +d.HC01_EST_VC105},\n {'20-24': +d.HC01_EST_VC106},\n {'25-29': +d.HC01_EST_VC107},\n {'30-34': +d.HC01_EST_VC108},\n {'35-44': +d.HC01_EST_VC109},\n {'45-59': +d.HC01_EST_VC110},\n {'60+': +d.HC01_EST_VC111} \n ],\n mean_time: +d.HC01_EST_VC112\n\n //backup as follows\n // travel_time_work_10: +d.HC01_EST_VC103,\n // travel_time_work_10_14: +d.HC01_EST_VC104,\n // travel_time_work_15_19: +d.HC01_EST_VC105,\n // travel_time_work_20_24: +d.HC01_EST_VC106,\n // travel_time_work_25_29: +d.HC01_EST_VC107,\n // travel_time_work_30_34: +d.HC01_EST_VC108,\n // travel_time_work_35_44: +d.HC01_EST_VC109,\n // travel_time_work_45_59: +d.HC01_EST_VC110,\n // travel_time_work_60: +d.HC01_EST_VC111, \n \n // age_16_19: +d.HC01_EST_VC03,\n // age_20_24: +d.HC01_EST_VC04,\n // age_25_44: +d.HC01_EST_VC05,\n // age_45_54: +d.HC01_EST_VC06,\n // age_55_59: +d.HC01_EST_VC07,\n // age_60: +d.HC01_EST_VC08,\n \n // earnings_1_9999: +d.HC01_EST_VC42,\n // earnings_10000_14999: +d.HC01_EST_VC43,\n // earnings_15000_24999: +d.HC01_EST_VC44,\n // earnings_25000_34999: +d.HC01_EST_VC45,\n // earnings_35000_49999: +d.HC01_EST_VC46,\n // earnings_50000_64999: +d.HC01_EST_VC47,\n // earnings_65000_74999: +d.HC01_EST_VC48,\n // earnings_75000: +d.HC01_EST_VC49,\n\n // agriculture: +d.HC01_EST_VC69,\n // construction: +d.HC01_EST_VC70,\n // manufacturing: +d.HC01_EST_VC71,\n // wholesale_trade: +d.HC01_EST_VC72,\n // retail_trade: +d.HC01_EST_VC73,\n // transportation_warehouse: +d.HC01_EST_VC74,\n // information_finance_realestate: +d.HC01_EST_VC75,\n // professional_scientific_waste_services: +d.HC01_EST_VC76,\n // educational_healthcare_social_assistance: +d.HC01_EST_VC77,\n // arts_entertainment_recreation_accommodation_food_services: +d.HC01_EST_VC78,\n // other_services_no_public_administration: +d.HC01_EST_VC79,\n // public_administration: +d.HC01_EST_VC80,\n // armed_forces: +d.HC01_EST_VC81,\n \n }\n}", "getrenDetFormattedData(renewalsData) {\n\n var renewalTransformedDetails = {\n client: {\n type: renewalsData.market,\n renewalLetter: {\n label: \"Renewal Letter\",\n endpoint: \"\"\n },\n aggregatedPremiums: [\n {\n label: \"Medical\",\n content: {\n current: {\n label: \"Current\",\n content: \"$\"+Math.round(renewalsData.currentMedicalRate * 100) / 100\n },\n renewal: {\n label: \"Renewal\",\n content: \"$\"+Math.round(renewalsData.renewalMedicalRate * 100) / 100\n },\n increase: true\n }\n },\n {\n label: \"Dental\",\n content: {\n current: {\n label: \"Current\",\n content: \"\"\n },\n renewal: {\n label: \"Renewal\",\n content: \"\"\n },\n increase: true\n }\n },\n {\n label: \"Vision\",\n content: {\n current: {\n label: \"Current\",\n content: \"\"\n },\n renewal: {\n label: \"Renewal\",\n content: \"\"\n },\n increase: true\n }\n },\n\n ],\n fields: [\n {\n label: \"Client ID\",\n content: \"\"\n },\n {\n label: \"Renewal Date\",\n content: \"\"\n },\n {\n label: \"Market\",\n content: \"\"\n },\n {\n label: \"State\",\n content: \"\"\n },\n {\n label: \"Products\",\n content: \"\"\n },\n {\n label: \"Exchange\",\n content: renewalsData.exchange\n },\n {\n label: \"Rating Area\",\n content:(renewalsData.medicalFutureRatingArea || renewalsData.medicalCurrentRatingArea || renewalsData.dentalFutureRatingArea || renewalsData.dentalCurrentRatingArea || renewalsData.pdFutureRatingArea || renewalsData.pdCurrentRatingArea)\n },\n {\n label: \"Association\",\n content: \"\"\n },\n {\n label: \"SIC\",\n content: \"\"\n },\n {\n label: \"Group Size\",\n content: renewalsData.size\n }\n ]\n },\n plans: ([]).concat(renewalsData.dentalProducts,\n renewalsData.visionProducts, renewalsData.medicalProducts).filter(function( element ) {\n return element !== undefined;\n })\n .map((val, ind)=>{\n return(\n {\n plan: {\n heading: \"Plan \"+(ind+1),\n columns: [\n {\n label: \"\",\n content: [\"Current\", \"Renewals\"]\n },\n {\n label: \"Plan\",\n content: [val.currentProduct.currentContractPlanName, val.renewalProduct.currentContractPlanName]\n },\n {\n label: \"Contract Code\",\n content: [val.currentProduct.currentContractPlanCode, val.renewalProduct.currentContractPlanCode]\n },\n {\n label: \"Premium\",\n content: [\"$\"+Math.round(val.currentProduct.monthlyPremium * 100) / 100,\n \"$\"+Math.round(val.renewalProduct.monthlyPremium * 100) / 100]\n },\n {\n label: \"Subscribers\",\n content: [val.currentProduct.subscribers, val.renewalProduct.subscribers]\n },\n {\n label: \"Subsidy\",\n content: [\"\",\"\"]\n },\n {\n label: \"Dependants Coverage\",\n content: [\"\",\"\"]\n }\n ]\n },\n employees: {\n heading: \"Employees\",\n columns: [\n {\n label: \"Employee\",\n content: val.employees.map((empVal,empInd)=>{\n return((empVal.name).toLowerCase())\n })\n },\n {\n label: \"Coverage\",\n content: val.employees.map((empVal,empInd)=>{\n return(empVal.coverage)\n })\n },\n {\n label: \"Age\",\n content: val.employees.map((empVal,empInd)=>{\n return(empVal.age)\n })\n },\n {\n label: \"Current Rate\",\n content: val.employees.map((empVal,empInd)=>{\n return(\"$\"+ Math.round(empVal.currentRate * 100) / 100)\n })\n },\n {\n label: \"New Rate\",\n content: val.employees.map((empVal,empInd)=>{\n return(empVal.newRate)\n })\n }\n ]\n }\n }\n\n )\n }),\n\n };\n return renewalTransformedDetails;\n}", "function _sanitize( raw, clean ){\n // error & warning messages\n const messages = { errors: [], warnings: [] };\n\n if (clean.hasOwnProperty('parsed_text') && iso3166.is2(_.toUpper(clean.parsed_text.country))) {\n clean.parsed_text.country = iso3166.to3(_.toUpper(clean.parsed_text.country));\n }\n\n return messages;\n}", "function getGermanValidTaxRateList(taxCategories, taxRateIdToTaxCategoryMap) {\n let germanTaxRateList = taxCategories\n .flatMap(item => item.rates)\n .filter(rate => rate.country ==='DE')\n let validGermanTaxRateList = []\n if (germanTaxRateList.length === 0) {\n let errMsg = 'No valid tax rate from Germany. There is nothing to be done in your project in ' +\n 'respect to VAT.' + '\\n'\n logError(errMsg)\n return validGermanTaxRateList\n }\n let invalidGermanTaxRateList = germanTaxRateList.filter(rate =>\n rate.amount !== vatConstant.TAX_RATE_STANDARD_OLD &&\n rate.amount !== vatConstant.TAX_RATE_REDUCED_OLD)\n validGermanTaxRateList = germanTaxRateList\n .filter(rate => rate.amount===vatConstant.TAX_RATE_STANDARD_OLD ||\n rate.amount === vatConstant.TAX_RATE_REDUCED_OLD)\n\n const standardVATs = validGermanTaxRateList.filter(rate => rate.amount === vatConstant.TAX_RATE_STANDARD_OLD)\n const reducedVATs = validGermanTaxRateList.filter(rate => rate.amount === vatConstant.TAX_RATE_REDUCED_OLD)\n let errMsg = null\n if (invalidGermanTaxRateList.length>0) {\n errMsg = 'We are sorry, we would have to ask you to change the vat manually if applicable. ' +\n 'There seems to be a special case.' + '\\n'\n errMsg += buildTaxRateDraftJson(invalidGermanTaxRateList, taxRateIdToTaxCategoryMap)\n logError(errMsg)\n }\n if (standardVATs.length > 1) {\n printRedundantTaxRateErrorMsg(vatConstant.TAX_RATE_STANDARD_OLD*100, standardVATs,\n taxRateIdToTaxCategoryMap)\n }\n if (reducedVATs.length > 1) {\n printRedundantTaxRateErrorMsg(vatConstant.TAX_RATE_REDUCED_OLD*100, reducedVATs,\n taxRateIdToTaxCategoryMap)\n }\n\n return validGermanTaxRateList\n}", "function splitDefenseData(stringDefenseData) {\n if(DEBUG==true) { console.log(\"sbc-pf1 | Parsing defense data\") };\n \n stringDefenseData = stringDefenseData.replace(/^ | $|^\\n*/,\"\");\n \n // Clean up the Input if there are extra linebreaks (often when copy and pasted from pdfs)\n // Remove linebreaks in parenthesis\n stringDefenseData = stringDefenseData.replace(/(\\([^(.]+?)(?:\\n)([^(.]+?\\))+?/mi, \"$1 $2\");\n \n let splitDefenseData = stringDefenseData.split(/\\n/);\n \n // Get all AC Boni included in Input (everything in parenthesis in splitDefenseData[0]) and split them into separate strings\n let splitACBonusTypes = {};\n if (splitDefenseData[0].search(/\\([\\s\\S]*?\\)/) !== -1) {\n splitACBonusTypes = JSON.stringify(splitDefenseData[0].match(/\\([\\s\\S]*?\\)/)).split(/,/);\n \n // Loop through the found AC Boni and set changes accordingly\n splitACBonusTypes.forEach( function ( item, index) {\n\n // get the bonus type\n let foundBonusType = item.match(/([a-zA-Z]+)/i)[0];\n let foundBonusValue = item.match(/(\\+[\\d]*)|(-[\\d]*)/i)[0].replace(/\\+/,\"\");\n\n formattedInput.ac_bonus_types[foundBonusType] = +foundBonusValue;\n\n });\n formattedInput.acNotes = JSON.parse(splitACBonusTypes)[0];\n }\n\n // Extract AC, Touch AC and Flat-Footed AC\n splitDefenseData[0] = splitDefenseData[0].replace(/\\([\\s\\S]*?\\)/,\"\");\n let splitArmorClasses = splitDefenseData[0].split(/[,;]/g);\n \n splitArmorClasses.forEach( function (item, index) {\n if (this[index].match(/(\\bAC\\b)/gmi)) {\n let splitAC = this[index].replace(/(\\bAC\\b)/gmi,\"\").replace(/^ *| *$|^\\n*/g,\"\");\n formattedInput.ac = splitAC;\n } else if (this[index].match(/(\\bTouch\\b)/gmi)) {\n let splitTouch = this[index].replace(/(\\btouch\\b)/gmi,\"\").replace(/^ *| *$|^\\n*/g,\"\");\n formattedInput.touch = splitTouch;\n } else if (this[index].match(/(\\bflat-footed\\b)/gmi)) {\n let splitFlatFooted = this[index].replace(/(\\bflat-footed\\b)/gmi,\"\").replace(/^ *| *$|^\\n*/g,\"\");\n formattedInput.flat_footed = splitFlatFooted;\n }\n }, splitArmorClasses);\n \n // Extract Number and Size of Hit Dies as well as HP\n // Hit dice\n \n let splitHPTotal = splitDefenseData[1].split(/(?:hp\\s*)([\\d]*)/)[1];\n formattedInput.hp.total = splitHPTotal;\n \n \n let stringHitDice = JSON.parse(JSON.stringify(splitDefenseData[1].match(/\\([\\s\\S]*?\\)/)));\n\n // If available, extract Regeneration\n if (splitDefenseData[1].search(/Regeneration/i) !== -1) {\n let tempRegen = splitDefenseData[1].match(/(?:Regeneration )([\\s\\S]+?)(?:\\n|$|;)/i);\n formattedInput.regeneration = tempRegen[1];\n }\n // If available, extract Fast Healing\n if (splitDefenseData[1].search(/Fast Healing/i) !== -1) {\n let tempFastHealing = splitDefenseData[1].match(/(?:Fast Healing )([\\s\\S]+?)(?:\\n|$|;)/i);\n formattedInput.fast_healing = tempFastHealing[1];\n }\n \n // Calculate HP and HD for Class and Race Items\n\n // Get different DicePools, e.g. XdY combinations, mostly for combinations of racial and class hitDice\n let hitDicePool = JSON.stringify(stringHitDice).match(/(\\d+?d\\d+)/gi);\n \n // Get the total HD\n let totalHD = 0;\n let totalClassHD = 0;\n // Loop over the available XdY Combinations\n hitDicePool.forEach ( function (hitDiceItem, hitDiceIndex) {\n // Increment the totalHD Counter\n totalHD += +hitDiceItem.match(/(\\d+)(?:d\\d+)/i)[1];\n });\n \n // Get the total HD of classHD\n let classKeys = Object.keys(formattedInput.classes);\n classKeys.forEach( function (classKey, classKeyIndex) {\n let numberOfClassLevels = formattedInput.classes[classKey].level;\n totalClassHD += +numberOfClassLevels;\n });\n \n // If there are no classes, all HD are racialHD\n if (totalClassHD === 0) {\n // ONLY RACIALHD \n let hitDicePoolKey = Object.keys(hitDicePool);\n for (let i = 0; i < hitDicePoolKey.length; i++) {\n \n // Set HP for RacialHDItem \n let tempDiceSize = hitDicePool[i].match(/(?:d)(\\d+)/)[1];\n \n // Set HP, HD.Racial and HD.Total\n formattedInput.hp.racial = Math.floor(+totalHD * +getDiceAverage(tempDiceSize));\n formattedInput.hit_dice.hd.racial = +totalHD;\n formattedInput.hit_dice.hd.total = +totalHD;\n }\n \n } else if (totalHD - totalClassHD === 0) {\n // ONLY CLASSHD \n // Loop over the dicePool\n let hitDicePoolKey = Object.keys(hitDicePool);\n for (let i = 0; i < hitDicePoolKey.length; i++) {\n \n let tempNumberOfHD = hitDicePool[i].match(/(\\d+)(?:d\\d+)/)[1];\n let tempHDSize = hitDicePool[i].match(/(?:\\d+d)(\\d+)/)[1];\n \n // Loop over the classes\n let classKeys = Object.keys(formattedInput.classes);\n for (let j = 0; j < classKeys.length; j++) {\n \n let classLevel = formattedInput.classes[classKeys[j]].level;\n \n \n \n // THIS IS NOT WORKING WHEN BOTH DICE POOLS HAVE THE SAME NUMBER OF DICE, e.g. 1d6 + 1d8\n \n \n \n \n if (tempNumberOfHD == classLevel) { \n // Set HP, HD.Racial and HD.Total\n formattedInput.hp.class[j] = Math.floor(+classLevel * +getDiceAverage(tempHDSize));\n formattedInput.hit_dice.hd.class[j] = +tempNumberOfHD;\n formattedInput.hit_dice.hd.total += +tempNumberOfHD;\n \n }\n \n \n }\n \n }\n \n } else if (totalHD - totalClassHD !== 0) {\n // CLASSHD AND RACIALHD\n // Loop for as long as not all ClassHD are matched\n let numberOfClasses = Object.keys(formattedInput.classes).length;\n let numberOfMatchedHD = Object.keys(hitDicePool).length;\n \n \n let counterOfMatchedHD = 0;\n let counterOfMatchedClasses = 0;\n \n while (counterOfMatchedHD < numberOfMatchedHD) {\n\n // Loop over the classKeys\n classKeys.forEach( function (classKey, classKeyIndex) {\n \n // Loop over the hitDicePool searching for matches\n hitDicePool.forEach ( function (hitDiceItem, hitDiceIndex) {\n \n let tempNumberOfHD = +hitDiceItem.match(/(\\d+)(?:d\\d+)/i)[1];\n let tempHDSize = +hitDiceItem.match(/(?:d)(\\d+)/i)[1];\n let tempClassLevel = formattedInput.classes[classKey].level;\n \n if ( (tempNumberOfHD == tempClassLevel) && (+counterOfMatchedHD !== +numberOfMatchedHD) && (counterOfMatchedClasses !== numberOfClasses) ) {\n // IF ITS THE A DIRECT MATCH BETWEEN CLASS LEVEL AND NUMBER OF HITDICE\n \n formattedInput.hp.class[classKey] = Math.floor(+tempClassLevel * +getDiceAverage(tempHDSize));\n formattedInput.hit_dice.hd.class[classKey] = +tempNumberOfHD;\n formattedInput.hit_dice.hd.total += +tempNumberOfHD;\n \n counterOfMatchedHD++;\n counterOfMatchedClasses++;\n \n } else if ( (tempNumberOfHD !== tempClassLevel) && (+counterOfMatchedHD == +(numberOfMatchedHD-1)) && (counterOfMatchedClasses !== numberOfClasses) ) {\n // IF ITS THE LAST HD POSSIBLE AND THERE IS STILL A CLASS LEFT TO MATCH\n \n formattedInput.hp.class[classKey] = Math.floor(+tempClassLevel * +getDiceAverage(tempHDSize));\n formattedInput.hp.racial = Math.floor( (+tempNumberOfHD - +tempClassLevel) * +getDiceAverage(tempHDSize));\n formattedInput.hit_dice.hd.class[classKey] = +tempNumberOfHD;\n formattedInput.hit_dice.hd.racial = +tempNumberOfHD - +tempClassLevel;\n \n formattedInput.hit_dice.hd.total += +tempNumberOfHD;\n \n counterOfMatchedHD++;\n counterOfMatchedClasses++;\n \n } else if ( (counterOfMatchedHD == (numberOfMatchedHD-1)) && (counterOfMatchedClasses == numberOfClasses) ) {\n // IF ITS THE LAST HD POSSIBLE AND THERE IS NO CLASS LEFT \n formattedInput.hp.racial = Math.floor( +tempNumberOfHD * +getDiceAverage(tempHDSize) );\n formattedInput.hit_dice.hd.racial = +tempNumberOfHD;\n formattedInput.hit_dice.hd.total += +tempNumberOfHD;\n \n counterOfMatchedHD++;\n }\n \n \n }); // End of Loop over the classKeys\n \n \n }); // End of Loop over the hitDicePool\n \n \n }\n \n\n }\n \n \n //let hitDiceBonusPool = JSON.stringify(stringHitDice).match(/[^d+\\(](\\d+)/gi);\n let hitDiceBonusPool = stringHitDice[0].replace(/(\\d+d\\d+)/gi,\"\").match(/\\d+/g);\n \n let hitDiceBonus = 0;\n \n // Get the sum of all the additional bonus hp, denoted for example by \"+XX\" and / or \"plus XX\"\n if (hitDiceBonusPool !== null) {\n \n for (let i = 0; i < hitDiceBonusPool.length; i++) {\n hitDiceBonus += +hitDiceBonusPool[i];\n }\n \n }\n \n // Extract Saves \n let splitSaves;\n \n for (var i = 0; i < splitDefenseData.length; i++) {\n if (splitDefenseData[i].search(/Fort/i) !== -1) {\n splitSaves = splitDefenseData[i].split(/,|;/);\n }\n }\n \n //let splitSaves = splitDefenseData[2].split(/,/); \n splitSaves.forEach( function (item, index) {\n \n item = item.replace(/,/g, \"\");\n \n if (this[index].search(/(fort)/i) !== -1) {\n let splitFort = item.match(/(\\+\\d+|\\-\\d+|\\d+)/ig)[0];\n formattedInput.fort_save.total = splitFort.replace(/\\+/,\"\");\n } else if (this[index].search(/(ref)/i) !== -1) {\n let splitRef = item.match(/(\\+\\d+|\\-\\d+|\\d+)/ig)[0];\n formattedInput.ref_save.total = splitRef.replace(/\\+/,\"\");\n } else if (this[index].search(/(will)/i) !== -1) {\n let splitWill = item.match(/(\\+\\d+|\\-\\d+|\\d+)/ig)[0];\n formattedInput.will_save.total = splitWill.replace(/\\+/,\"\");\n } else {\n formattedInput.save_notes = item;\n }\n }, splitSaves);\n \n // Check if there is a forth line\n /// then extract Damage Reduction, Resistances, Immunities, Weaknesses and Spell Resistance \n \n // REWORKED\n let searchableDefenseData = JSON.stringify(stringDefenseData).replace(/\\\\n/g, \";\").replace(/Offense;|Offenses/i, \"\");\n \n // Damage Reduction\n if (searchableDefenseData.search(/\\bDR\\b/) !== -1) {\n let splitDRValue = searchableDefenseData.match(/(?:\\bDR\\b )(\\d+)/)[0].replace(/\\bDR\\b /, \"\");\n let splitDRType = searchableDefenseData.match(/(?:\\bDR\\b \\d+\\/)([\\w\\s]*)/)[1];\n formattedInput.damage_reduction.dr_value = splitDRValue;\n formattedInput.damage_reduction.dr_type = splitDRType;\n }\n \n // Immunities\n if (searchableDefenseData.search(/\\bImmune\\b|\\bImmunities\\b/i) !== -1) {\n let splitImmunities = searchableDefenseData.match(/(?:\\bImmune\\b |\\bImmunities\\b )(.*?)(?:;)/i)[0].replace(/\\bimmune\\b |\\bimmunities\\b /i, \"\");\n formattedInput.immunities = splitImmunities;\n }\n \n // Resistances\n if (searchableDefenseData.search(/\\bResist\\b|\\bResistances\\b/i) !== -1) {\n let splitResistances = searchableDefenseData.match(/(?:\\bResist\\b |\\bResistance\\b )(.*?)(?:;)/i)[0].replace(/\\bResist\\b |\\bResistances\\b /i, \"\");\n formattedInput.resistances = splitResistances;\n }\n \n // Weaknesses\n if (searchableDefenseData.search(/\\bWeakness\\b|\\bWeaknesses\\b/i) !== -1) {\n let splitWeaknesses = searchableDefenseData.match(/(?:\\bWeakness\\b |\\bWeaknesses\\b )(.*?)(?:;)/i)[0].replace(/\\bWeakness\\b |\\bWeaknesses\\b /i, \"\");\n // Remove the phrase \"Vulnerable to\" if thats there\n splitWeaknesses = splitWeaknesses.replace(/vulnerability to |vulnerable to | and /gi, \"\")\n formattedInput.weaknesses = splitWeaknesses;\n }\n \n // Spell Resistance\n if (searchableDefenseData.search(/\\bSR\\b/i) !== -1) {\n let splitSR = searchableDefenseData.match(/(?:\\bSR\\b )(.*?)(?:;)/i)[0].replace(/\\bSR\\b /i, \"\");\n splitSR = splitSR.replace(/;|,| |\\n/g, \"\");\n formattedInput.spell_resistance.total = splitSR.match(/(^\\d+)/)[0];\n if (splitSR.search(/\\(([^)]+)\\)/) !== -1) {\n formattedInput.spell_resistance.context = splitSR.match(/\\(([^)]+)\\)/)[0];\n }\n }\n \n // Defensive Abilities\n // Spell Resistance\n if (searchableDefenseData.search(/\\bDefensive Abilities\\b/i) !== -1) {\n let splitDefensiveAbilities = searchableDefenseData.match(/(?:\\bDefensive Abilities\\b )(.*?)(?:;)/i)[0].replace(/\\bDefensive Abilities\\b /i, \"\");\n splitDefensiveAbilities = splitDefensiveAbilities.replace(/;|,|\\n/g, \",\").replace(/,\\s+$|,$/g, \"\");\n splitDefensiveAbilities = splitDefensiveAbilities.split(/,/g);\n formattedInput.defensive_abilities = splitDefensiveAbilities;\n }\n\n if(DEBUG==true) { console.log(\"sbc-pf1 | DONE parsing defense data\") };\n}", "function FeatureValidator(feature, cityName) {\n\n this.feature = feature;\n this.cityName = cityName;\n this.errors = [];\n this.warnings = [];\n\n this.validate = function() {\n var feature = this.feature;\n if (feature === undefined) {\n this.errors.push(new CustomIssue(\"Feature cannot be undefined.\"));\n } else if (feature === null) {\n this.errors.push(new CustomIssue(\"Feature cannot be null.\"));\n } else if (feature === {}) {\n this.errors.push(new CustomIssue(\"Feature cannot be an empty object.\"));\n } else {\n this.validateGeometry(feature.geometry);\n this.validateProperties(feature.properties);\n this.validateType(feature.type);\n }\n };\n\n this.printErrors = function() {\n if (this.hasErrors()) {\n this.printMarketTitle();\n }\n for (var i = 0, length = this.errors.length; i < length; ++i) {\n var error = this.errors[i];\n console.log(\"Error: %s\", error.toString());\n }\n };\n\n this.printWarnings = function() {\n if (this.hasWarnings()) {\n this.printMarketTitle();\n }\n for (var i = 0, length = this.warnings.length; i < length; ++i) {\n var warning = this.warnings[i];\n console.log(\"Warning: %s\", warning.toString());\n }\n };\n\n this.validateProperties = function(properties) {\n if (properties === undefined) {\n this.errors.push(new UndefinedAttributeIssue(\"properties\"));\n } else if (properties === null) {\n this.errors.push(new NullAttributeIssue(\"properties\"));\n } else if (properties === {}) {\n this.errors.push(new EmptyObjectIssue(\"properties\"));\n } else {\n this.validateTitle(properties.title);\n this.validateLocation(properties.location);\n var openingHours = properties.opening_hours;\n var openingHoursUnclassified = properties.opening_hours_unclassified;\n if (openingHours === null) {\n this.validateOpeningHoursIsNull(openingHours);\n this.validateOpeningHoursUnclassifiedIsNotNull(openingHoursUnclassified);\n } else {\n this.validateOpeningHours(openingHours);\n this.validateOpeningHoursUnclassifiedIsNull(openingHoursUnclassified);\n }\n }\n };\n\n this.validateTitle = function(title) {\n if (title === undefined) {\n this.errors.push(new UndefinedAttributeIssue(\"title\"));\n } else if (title === null) {\n this.errors.push(new NullAttributeIssue(\"title\"));\n } else if (title.length === 0) {\n this.errors.push(new EmptyAttributeIssue(\"title\"));\n }\n };\n\n this.validateLocation = function(location) {\n if (location === undefined) {\n this.errors.push(new UndefinedAttributeIssue(\"location\"));\n } else if (location === null) {\n // Attribute \"location\" is optional.\n } else if (location.length === 0) {\n this.errors.push(new EmptyAttributeIssue(\"location\"));\n }\n };\n\n this.validateOpeningHours = function(openingHours) {\n if (openingHours === undefined) {\n this.errors.push(new UndefinedAttributeIssue(\"opening_hours\"));\n return;\n }\n var oh;\n try {\n var options = {\n \"address\" : {\n \"country_code\" : \"de\"\n }\n };\n oh = new opening_hours(openingHours, options);\n var warnings = oh.getWarnings();\n if (warnings.length > 0) {\n this.errors.push(warnings);\n }\n } catch (error) {\n this.errors.push(error.toString());\n }\n };\n\n this.validateOpeningHoursIsNull = function(openingHours) {\n if (openingHours !== null) {\n this.errors.push(new CustomIssue(\n \"Attribute 'opening_hours' must be null when 'opening_hours_unclassified' is used.\"));\n }\n };\n\n this.validateOpeningHoursUnclassifiedIsNull = function(openingHoursUnclassified) {\n if (openingHoursUnclassified === undefined) {\n // Attribute \"opening_hours_unclassified\" is optional.\n return;\n }\n if (openingHoursUnclassified !== null) {\n this.errors.push(new CustomIssue(\n \"Attribute 'opening_hours_unclassified' must be null when 'opening_hours' is used.\"));\n }\n };\n\n this.validateOpeningHoursUnclassifiedIsNotNull = function(openingHoursUnclassified) {\n if (openingHoursUnclassified === undefined) {\n this.errors.push(new CustomIssue(\n \"Attribute 'opening_hours_unclassified' cannot be undefined when 'opening_hours' is null.\"));\n } else if (openingHoursUnclassified === null) {\n this.errors.push(new CustomIssue(\n \"Attribute 'opening_hours_unclassified' cannot be null when 'opening_hours' is null.\"));\n } else if (openingHoursUnclassified === \"\") {\n this.errors.push(new CustomIssue(\n \"Attribute 'opening_hours_unclassified' cannot be empty when 'opening_hours' is null.\"));\n }\n };\n\n this.validateGeometry = function(geometry) {\n if (geometry === undefined) {\n this.errors.push(new UndefinedAttributeIssue(\"geometry\"));\n } else if (geometry === null) {\n this.errors.push(new NullAttributeIssue(\"geometry\"));\n } else if (geometry === {}) {\n this.errors.push(new EmptyObjectIssue(\"geometry\"));\n } else {\n this.validateCoordinates(geometry.coordinates);\n this.validateGeometryType(geometry.type);\n }\n };\n\n this.validateCoordinates = function(coordinates) {\n if (coordinates === undefined) {\n this.errors.push(new UndefinedAttributeIssue(\"coordinates\"));\n } else if (coordinates === null) {\n this.errors.push(new NullAttributeIssue(\"coordinates\"));\n } else if (coordinates.length !== 2) {\n this.errors.push(new CustomIssue(\n \"Attribute 'coordinates' must contain two values not \" + coordinates.length + \".\"));\n } else {\n var lon = coordinates[0];\n if (!longitudeInValidRange(lon)) {\n this.errors.push(new LongitudeRangeExceedanceIssue(\"coordinates[0]\", lon));\n }\n var lat = coordinates[1];\n if (!latitudeInValidRange(lat)) {\n this.errors.push(new LatitudeRangeExceedanceIssue(\"coordinates[1]\", lat));\n }\n }\n };\n\n this.validateGeometryType = function(type) {\n if (type !== \"Point\") {\n this.errors.push(new CustomIssue(\n \"Attribute 'geometry.type' must be 'Point' not '\" + type + \"'.\"));\n }\n };\n\n this.validateType = function(type) {\n if (type !== \"Feature\") {\n this.errors.push(new CustomIssue(\n \"Attribute 'type' must be 'Feature' not '\" + type + \"'.\"));\n }\n };\n\n this.getErrorsCount = function() {\n return this.errors.length;\n };\n\n this.getWarningsCount = function() {\n return this.warnings.length;\n };\n\n this.hasErrors = function() {\n return this.errors.length > 0;\n };\n\n this.hasWarnings = function() {\n return this.warnings.length > 0;\n };\n\n this.printMarketTitle = function() {\n console.log(\"\\n%s: %s\".market,\n this.cityName.toUpperCase(),\n this.feature.properties.title);\n };\n\n}", "function filterData(filterReq){\n\n if(filterReq){\n\n var filter = JSON.parse(filterReq); \n if(filter.heroName){\n filterObj.heroName = { \"$regex\": filter.heroName, \"$options\": \"i\" } ;\n }\n if(filter.age){\n filterObj.age = filter.age;\n }\n if(filter.relation){\n filterObj.relation = { \"$regex\": filter.relation, \"$options\": \"i\" };\n }\n if(filter.power){\n filterObj.power = { $in: filter.power};\n }\n if(filter.gender){\n filterObj.gender = filter.gender;\n }\n if(filter.faith){\n filterObj.faith = { \"$regex\": filter.faith, \"$options\": \"i\" } ;\n }\n if(filter.nationality){\n filterObj.nationality = { $in: filter.power}; //filter.nationality;\n }\n }\n // return filterObj;\n}", "function dataCleanUp(data,type){\n\t\tif(type == 'places'){\n\t\t\tfor (var i = 0; i < data.features.length; i++) { /*[1]*/\n\t\t\t\tvar feature = data.features[i];\n\t\t\t\tif(feature.properties.tags.constructor !== Array){/*[2]*/\n\t\t\t\t\tvar tagsAarray = feature.properties.tags.split(',');\n\t\t\t\t\tfeature.properties.tags = tagsAarray;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn data;\n\t}", "function data_cleaning_countries_name(suicideData, countriesJson) {\n let all_countries_in_cjson = _.uniqBy(countriesJson.features, 'properties.name');\n for (let c of all_countries_in_cjson) {\n let currentCjsonCountry = c.properties.name;\n let entry = _.filter(suicideData, function(d) {\n\n if (d.country.indexOf(currentCjsonCountry) != -1) {\n d.country = currentCjsonCountry;\n }\n });\n }\n\n let all_countries_in_sjson = _.uniqBy(suicideData, 'country');\n for (let i of all_countries_in_sjson) {\n let currentSjsonCountry = i.country;\n let entry = _.filter(countriesJson.features, function(d) {\n\n if (d.properties.name.indexOf(currentSjsonCountry) != -1) {\n d.properties.name = currentSjsonCountry;\n }\n });\n }\n}", "$checkAndCleanValues(values, operation) {\n if (this.dtypes[0] == \"string\") ErrorThrower.throwStringDtypeOperationError(operation);\n values = utils.removeMissingValuesFromArray(values);\n\n if (this.dtypes[0] == \"boolean\") {\n values = (utils.mapBooleansToIntegers(values, 1));\n }\n return values;\n }", "sanitizeFilters (filters) {\n Object.keys(filters).map((key) => {\n if (filters[key] === null || filters[key] === undefined) {\n delete filters[key];\n }\n });\n return filters;\n }", "function validateFavoriteDataItems() {\n\t//Data elements from favorites\n\tvar issues = [];\n\tfor (var type of [\"charts\", \"mapViews\", \"reportTables\"]) {\n\t\tfor (var i = 0; metaData.hasOwnProperty(type) && i < metaData[type].length; i++) {\n\t\t\tvar item = metaData[type][i];\n\t\t\tfor (var dimItem of item.dataDimensionItems) {\n\n\t\t\t\tif (dimItem.dataDimensionItemType != \"INDICATOR\") {\n\n\n\t\t\t\t\t//Exception: custom objects we list, but don't stop the export\n\t\t\t\t\tvar abort = customObject(type, item.id) ? false : true;\t\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\tvar nameableItem = (type == \"mapViews\") ? mapFromMapView(item.id) : item;\n\t\t\t\t\t\t\n\t\t\t\t\tissues.push({\n\t\t\t\t\t\t\"id\": nameableItem.id,\n\t\t\t\t\t\t\"name\": nameableItem.name,\n\t\t\t\t\t\t\"type\": type,\n\t\t\t\t\t\t\"error\": dimItem.dataDimensionItemType,\n\t\t\t\t\t\t\"abort\": abort\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t\n\tif (issues.length > 0) {\t\n\t\tconsole.log(\"\\nWARNING | Favourites not using indicators only:\");\n\t\t\n\t\tabort = false;\n\n\t\tvar printed = {};\n\t\tfor (var issue of issues) {\n\t\t\tabort = abort || issue.abort;\n\t\t\tif (!printed[issue.id + issue.error]) {\n\t\t\t\tconsole.log(issue.type + \": \" + issue.id + \" - '\" + issue.name + \n\t\t\t\t\t\"': \" + issue.error);\n\t\t\t\tprinted[issue.id + issue.error] = true;\n\t\t\t}\n\t\t\t\n\t\t}\n\t\treturn !abort;\n\t}\n\telse return true;\n}", "validateCarData(car) {\n let requiredetail = 'license model latLong miles make'.split(' ');\n\n for (let field of requiredetail) {\n if (!car[field]) {\n this.errors.push(new DataError(`invalid field in validatin ${field}`, car));\n }\n }\n return car;\n }", "function cleanFireDistrictDataVIC(data, fireDistrict) {\n const { results } = data;\n const merged = mergeItems(results, fireDistrict);\n return { [fireDistrict]: merged };\n}", "function sortFx() {\n function compare(a, b) {\n const currencyA = a.currency.toLowerCase();\n const currencyB = b.currency.toLowerCase();\n\n let comparison = 0;\n if (currencyA > currencyB) {\n comparison = 1;\n } else if (currencyA < currencyB) {\n comparison = -1;\n }\n return comparison;\n }\n\n fxData.fx.sort(compare);\n}", "function filterDataByParameters(cities) {\n // cities[0] is the blackMarket first for loop then starts from 1\n for (var i = 1; i < cities.length; i++) { // Loop through every city\n for (var j = 0; j < cities[i].length; j++) { // Loop through every item\n var item = cities[i][j];\n\n // the reason for 2 item.profit comparisons even though < minProfit would be enough is because\n // some weird entries can show up if you enter a negative value in Min Profit\n if (item.profit < minProfit || item.profit <= 0 || item.highestProfitBM_Age > maxAgeBM || item.city_age > maxAgeCity) {\n cities[i].splice(j, 1);\n j--;\n }\n\n }\n totalApprovedTrades += cities[i].length;\n }\n\n // only true if all the items from all the cities have been spliced\n if (totalApprovedTrades == 0) {\n if (freshTrades == 0) {\n printToConsole(\"Data too old. Pick bigger max age or update the market via the Data Client.\\n\");\n } else if (profitableTrades == 0) {\n printToConsole(\"No profitable trades found. Try decreasing Min Profit.\\n\");\n } else if (profitableTrades != 0 && freshTrades != 0) {\n printToConsole(\"No fresh and profitable items found. Adjust one of the parameters and try again.\\n\")\n }\n } else {\n printToConsole(\"Profitable and fresh items found!\\n\");\n }\n\n return totalApprovedTrades;\n}", "function _fixQuotes(data) {\n var aaIndex=[],msIndex=[];\n var mapping = data.mapping;\n var fields = data.fields;\n var table = data.table;\n var distinguish = function(dataName){\n var indexName=[];\n dataName.forEach(function(ds){\n mapping[ds].forEach(function(dimension){\n fields.forEach(function(field,index){\n if(dimension===field){\n indexName.push(index);\n }\n })\n })\n })\n return indexName;\n };\n //distinguish the aa from the field\n aaIndex = distinguish(_cs.dataTypeName.dimensionName);\n msIndex = distinguish(_cs.dataTypeName.measureName);\n //add quotes\n for(i=0;i<aaIndex.length;i++){\n for(j=0;j<table.length;j++){\n if((typeof table[j][aaIndex[i]])==='number'){\n data.table[j][aaIndex[i]]=table[j][aaIndex[i]]+\"\"; //float2string\n }\n }\n }\n //remove quotes\n for(i=0;i<msIndex.length;i++){\n for(j=0;j<table.length;j++){\n if((typeof Number(table[j][msIndex[i]]))==='number'){\n data.table[j][msIndex[i]]=Number(table[j][msIndex[i]]); //string2float\n }\n }\n }\n return data;\n }", "function normalizeJSON(arr){\n return arr.map(r=> {\n return Object.entries(r).map(kv=> {\n let obj = {};\n let key = kv[0]?.replace(/#/g,'number')?.replace(/%/g,'percent')?.replace(/-/g,'to')?.replace(/\\W+/g,'_')?.replace(/^\\b(?=\\d)/,'_')?.replace(/_$/,'')?.toLowerCase();\n let val = typeof kv[1] == 'string' ? (/^[\\d\\.,]+$|^-[\\d\\.,]+$/.test(kv[1]?.replace(/,/g,'')) ? parseFloat(kv[1]) : /^\\$[\\d,\\.]+$/.test(kv[1]) ? parseFloat(kv[1]?.replace(/\\$|,/g,'')) : /[\\d\\.,]+%$/.test(kv[1]) ? (parseFloat(kv[1]?.replace(/%|,/g,'')) / 100) : kv[1] ) : typeof kv[1] == 'object' && Array.isArray(kv[1]) ? kv[1].map(i=> {\n let is_obj = typeof i == 'object' && !Array.isArray(i);\n let obj = {};\n let sub_key = kv[0]?.replace(/ies$/,'y').replace(/s$/,'');\n if (is_obj) { return i; }\n if (Array.isArray(i)) { obj[sub_key] = JSON.stringify(i); return obj; }\n else { obj[sub_key] = i; return obj; }\n }) : kv[1];\n obj[key] = val;\n return obj;\n }).reduce((a,b)=> { return {...a,...b} })\n }) \n}", "validateWarehouseInfo(warehouse)\n {\n if(warehouse.amount === undefined || !validator.matches(warehouse.amount.toString(),/(^[\\d]{1,4}$)/))\n return \"Invalid warehouse's product amount !\";\n\n return \"pass\";\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
userform_addGroupToUser() flip over the groups in the AvailableGroupList and move any that are selected to the GroupList. at the same time, create the appropriate entries in the userhash.
function userform_addGroupToUser() { var RN = "userform_addGroupToUser"; var su = userform_lookupSelectedUser(); var agl = document.getElementById('AvailableGroupList'); var gl = document.getElementById('GroupList'); if (agl && gl) { unHighLightList("GroupList"); unHighLightList("AccessControlList"); for (var i = agl.options.length-1 ; i > 0 ; i--) { dbg (1, RN + ": move agl/" + i + " to gl"); if (agl.options[i].selected) { var opt = agl.options[i]; if (browserType_IE) agl.options[i] = null; gl.options[gl.options.length] = opt; userhash[su][opt.value] = new Object; } } enableList("AccessControlList"); DBG_objDump(userhash, "userhash"); userform_setAclHash(); sortList("GroupList"); sortList("AvailableGroupList"); } else { dbg (1, RN + ": cant find AvailableGroupList and/or GroupList object"); } return false; }
[ "function setHistoryUserGroupList(offset, size, ordinal, direction) {\n\t 'use strict';\n\t \n\t if (offset === undefined || offset === null || isNaN(offset)) {\n\t\toffset = 0;\n\t }\n\t \n\t if (size === undefined || size === null || isNaN(size)) {\n\t\tsize = 20;\n\t }\n\t \n\t if (ordinal === undefined || ordinal === null || ordinal === '') {\n\t\tordinal = 'default';\n\t }\n\t \n\t if (direction === undefined || direction === null || direction === '') {\n\t\tdirection = 'ascending';\n\t }\n\t \n\t var content = '';\n\t var historyState = {};\n\t historyState.pageUrl = 'user_group.php';\n\t historyState.pageAttributes = 'a=list&offset=' + escape(offset) + '&size=' + escape(size) + '&ordinal=' + escape(ordinal) + '&direction=' + escape(direction);\n\t historyState.pageTitle = butrGlobalConfigurations.company_name + ' | Butr | '+butr_i18n_GroupAdministration+' | '+butr_i18n_ListGroups;\n\t \n\t content = '?page=' + historyState.pageUrl + '&' + historyState.pageAttributes;\n\n\t // Remove trailing ampersand\n\t if (content.charAt(content.length - 1) === '&') {\n\t\t content = content.substring(0, content.length - 1);\n\t }\n\t \n\t document.title = historyState.pageTitle;\n\t $('#title').html(butr_i18n_GroupAdministration + ' - ' + butr_i18n_ListGroups);\n\t document.butr_state_form.content.value = content;\n\t History.pushState(historyState, historyState.pageTitle, content);\n\t}", "function setHistoryUserGroupAdd() {\n 'use strict';\n \n var historyState = {};\n var content = '';\n historyState.pageUrl = 'user_group.php';\n historyState.pageAttributes = 'a=add';\n historyState.pageTitle = butrGlobalConfigurations.company_name + ' | Butr | '+butr_i18n_GroupAdministration+' | '+butr_i18n_AddGroup;\n \n content = '?page=' + historyState.pageUrl + '&' + historyState.pageAttributes;\n\n // Remove trailing ampersand\n if (content.charAt(content.length - 1) === '&') {\n\t content = content.substring(0, content.length - 1);\n }\n \n document.title = historyState.pageTitle;\n $('#title').html(butr_i18n_GroupAdministration+' - '+butr_i18n_AddGroup);\n document.butr_state_form.content.value = content;\n History.pushState(historyState, historyState.pageTitle, content);\n}", "function addGroup(id, name)\n{\n var newplace = window.document.epersongroup.group_ids.options.length;\n\n\tif (newplace > 0 && window.document.epersongroup.group_ids.options[0].value == \"\")\n {\n newplace = 0;\n }\n\n // First we check to see if group is already there\n for (var i = 0; i < window.document.epersongroup.group_ids.options.length; i++)\n {\n // is it in the list already\n if (window.document.epersongroup.group_ids.options[i].value == id)\n {\n newplace = -1;\n }\n\n // are we trying to add the new group to the new group on an Edit Group page (recursive)\n if (window.document.epersongroup.group_id)\n {\n if (window.document.epersongroup.group_id.value == id)\n {\n newplace = -1;\n }\n }\n }\n\n if (newplace > -1)\n {\n window.document.epersongroup.group_ids.options[newplace] = new Option(name + \" (\" + id + \")\", id);\n }\n}", "function groupappend_response(req)\n{\n appending = false;\n if(req.status != 200 ) {\n pnshowajaxerror(req.responseText);\n return;\n }\n var json = pndejsonize(req.responseText);\n\n pnupdateauthids(json.authid);\n $('groupsauthid').value = json.authid;\n\n // copy new group li from permission_1.\n var newgroup = $('group_'+firstgroup).cloneNode(true);\n\n // update the ids. We use the getElementsByTagName function from\n // protoype for this. The 6 tags here cover everything in a single li\n // that has a unique id\n newgroup.id = 'group_' + json.gid;\n $A(newgroup.getElementsByTagName('a')).each(function(node) { node.id = node.id.split('_')[0] + '_' + json.gid; });\n $A(newgroup.getElementsByTagName('div')).each(function(node) { node.id = node.id.split('_')[0] + '_' + json.gid; });\n $A(newgroup.getElementsByTagName('span')).each(function(node) { node.id = node.id.split('_')[0] + '_' + json.gid; });\n $A(newgroup.getElementsByTagName('input')).each(function(node) { node.id = node.id.split('_')[0] + '_' + json.gid; node.value = ''; });\n $A(newgroup.getElementsByTagName('select')).each(function(node) { node.id = node.id.split('_')[0] + '_' + json.gid; });\n $A(newgroup.getElementsByTagName('button')).each(function(node) { node.id = node.id.split('_')[0] + '_' + json.gid; });\n $A(newgroup.getElementsByTagName('textarea')).each(function(node){ node.id = node.id.split('_')[0] + '_' + json.gid; });\n\n // append new group to the group list\n $('grouplist').appendChild(newgroup);\n\n // set initial values in input, hidden and select\n $('name_' + json.gid).value = json.name;\n $('description_' + json.gid).value = json.description;\n $('editgroupnbumax_' + json.gid).value = json.nbumax;\n $('members_' + json.gid).href = json.membersurl;\n\n pnsetselectoption('state_' + json.gid, json.statelbl);\n pnsetselectoption('gtype_' + json.gid, json.gtypelbl);\n\n // hide cancel icon for new groups\n// Element.addClassName('groupeditcancel_' + json.gid, 'z-hide');\n // update delete icon to show cancel icon \n// Element.update('groupeditdelete_' + json.gid, canceliconhtml);\n\n // update some innerHTML\n Element.update('groupnbuser_' + json.gid, json.nbuser);\n Element.update('groupnbumax_' + json.gid, json.nbumax);\n Element.update('groupgid_' + json.gid, json.gid);\n Element.update('groupname_' + json.gid, json.name);\n Element.update('groupgtype_' + json.gid, json.gtypelbl);\n Element.update('groupdescription_' + json.gid, json.description) + '&nbsp;';\n Element.update('groupstate_' + json.gid, json.statelbl);\n //Element.update('members_' + json.gid, json.membersurl);\n\n // add events\n Event.observe('modifyajax_' + json.gid, 'click', function(){groupmodifyinit(json.gid)}, false);\n Event.observe('groupeditsave_' + json.gid, 'click', function(){groupmodify(json.gid)}, false);\n Event.observe('groupeditdelete_' + json.gid, 'click', function(){groupdelete(json.gid)}, false);\n Event.observe('groupeditcancel_' + json.gid, 'click', function(){groupmodifycancel(json.gid)}, false);\n\n // remove class to make edit button visible\n Element.removeClassName('modifyajax_' + json.gid, 'z-hide');\n Event.observe('modifyajax_' + json.gid, 'click', function(){groupmodifyinit(json.gid)}, false);\n\n // turn on edit mode\n enableeditfields(json.gid);\n\n // we are ready now, make it visible\n Element.removeClassName('group_' + json.gid, 'z-hide');\n new Effect.Highlight('group_' + json.gid, { startcolor: '#ffff99', endcolor: '#ffffff' });\n\n\n // set flag: we are adding a new group\n adding[json.gid] = 1;\n}", "addGroup() {\n this._insertItem(FdEditformGroup.create({\n caption: `${this.get('i18n').t('forms.fd-editform-constructor.new-group-caption').toString()} #${this.incrementProperty('_newGroupIndex')}`,\n rows: A(),\n }), this.get('selectedItem') || this.get('controlsTree'));\n }", "function updateGroup(oContext) {\n\t\t\t\tvar oNewGroup = oBinding.getGroup(oContext);\n\t\t\t\tif (oNewGroup.key !== sGroup) {\n\t\t\t\t\tvar oGroupHeader;\n\t\t\t\t\t//If factory is defined use it\n\t\t\t\t\tif (oBindingInfo.groupHeaderFactory) {\n\t\t\t\t\t\toGroupHeader = oBindingInfo.groupHeaderFactory(oNewGroup);\n\t\t\t\t\t}\n\t\t\t\t\tthat[sGroupFunction](oNewGroup, oGroupHeader);\n\t\t\t\t\tsGroup = oNewGroup.key;\n\t\t\t\t}\n\t\t\t}", "function updateGroupInput(input) {\n if(input.checked){\n groupInput.push(input.id);\n }\n else{\n var index = groupInput.indexOf(input.id);\n if(index > -1){\n groupInput.splice(index, 1);\n }\n }\n clearSearch();\n checkLoginAndSetUp();\n fetchOUs();\n return groupInput;\n}", "attachToGroup(group) {\n if (this.groups.find(g => g === group)) {\n return;\n }\n this.groups.push(group);\n }", "addUserToGroup(hub, group, userId, options) {\n const operationOptions = coreHttp.operationOptionsToRequestOptionsBase(options || {});\n return this.client.sendOperationRequest({ hub, group, userId, options: operationOptions }, addUserToGroupOperationSpec);\n }", "createSelectUser() {\n console.log(\"createSelectUser:\")\n let items = [];\n this.state.group_users_list.forEach((T) => {\n items.push(\n <div key={T.user_name + \"user_list\"}>\n <label>\n <input type=\"checkbox\" key={T.user_name} defaultChecked={T.isChecked} name={T.user_name} onChange={this.handleCheckboxListChange}/>\n {T.user_name}\n </label>\n </div>\n );\n })\n return items;\n }", "attachNewGroup() {\n 'use strict'\n let view, builder, groupType, order\n\n view = this\n builder = aljabr.builder\n\n groupType = view.el.select('#group-type-menu')\n .property('value')\n order = parseInt(view.el.select('#group-order-menu')\n .property('value'), 10)\n console.log('groupType: ' + groupType)\n console.log('order: ' + order)\n\n if (groupType === 'empty') {\n aljabr.group = new aljabr.GroupBuilder(aljabr.alphaElements(order))\n }\n else if (groupType === 'cyclic') {\n aljabr.group = aljabr.buildCyclicGroup(order)\n }\n else if (groupType === 'dihedral') {\n aljabr.group = aljabr.buildDihedralGroup(order)\n }\n else if (groupType === 'alternating') {\n aljabr.group = aljabr.buildAlternatingGroup(order)\n }\n else if (groupType === 'symmetry') {\n aljabr.group = aljabr.buildSymmetryGroup(order)\n }\n\n builder.cayleyTableView.attach(aljabr.group)\n builder.cayleyGraphView.attach(aljabr.group)\n\n return\n }", "async function createSubGroup(user, group, name, users) {\n // Make sure the user is the owner of the group\n const role = await getRole(user, group);\n if (role !== 'owner') {\n throw new RequestError('only owners can create sub-groups');\n }\n\n // Create a set of user ID strings to include in the group\n const userSet = new Set();\n userSet.add(user);\n for (const user of users) {\n userSet.add(user.id);\n }\n\n // Create an array of ObjectIds for each user\n const userArray = [];\n for (const user of userSet) {\n userArray.push(ObjectId(user));\n }\n\n // Get the existing info of the group\n const groupInfo = await db.collection(\"Groups\")\n .findOne({ _id: ObjectId(group) }, { projection: { _id: 0, grpUsers: 1, requireApproval: 1 } });\n\n // Filter to only include the specified users\n const grpUsers = groupInfo.grpUsers.filter(u => userSet.has(u.user.toHexString()));\n\n // Create a new group with only the specified users\n const result = await db.collection(\"Groups\").insertOne({\n name,\n grpUsers,\n requireApproval: groupInfo.requireApproval,\n modDate: Date.now(),\n modules: [],\n });\n\n // Get the ID of the new group\n const id = result.insertedId;\n\n // Add the group to all of the users\n await db.collection(\"Users\")\n .updateMany({ _id: { $in: userArray } }, { $push: { groups: id } });\n\n return id.toHexString();\n}", "function AddMemberToGroup(event) {\n\t\t\t\n\t\tvar grp=event.target.name;\n\t\t\n\t\t//alert(\"This is Group id \" + event.target.name + \" : \" + event.target.id);\n\t\t\n\t\t$.ajax({\n\t\t\turl : 'http://localhost:8080/facebook_v01/webapi/groupdetails/addMemberToGroup/'\n\t\t\t\t\t+ event.target.name + '/' + event.target.id,\n\t\t\ttype : 'POST',\n\t\t\tasync:false,\n\t\t\tcomplete : function(request, textStatus, errorThrown){\n\t\t\t\tif(request.status===201){\n\t\t\t\t\t\n\t\t\t\t\t//location.reload();\n\t\t\t\t\n\t\t\t\t\t$('#AddMemberToGrouplist1').empty();\n\t\t\t\t\t$('#AddMemberToGrouplist2').empty();\n\t\t\t\t\taddComponentAddMembersToGroupList(grp);\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\twindow.location.href = 'errorpage.html';\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t}", "function getGroups() {\n\t\n\tthemeIsUpdated = false;\n\t\n\tfor (var themeItem in dataVallydette.checklist.page[currentPage].groups) {\n\t\t\n\t\tif (document.getElementById(themeItem).checked !== dataVallydette.checklist.page[currentPage].groups[themeItem].checked) {\n\t\t\tthemeIsUpdated = true;\n\t\t\tdataVallydette.checklist.page[currentPage].groups[themeItem].checked = document.getElementById(themeItem).checked;\n\t\t\n\t\t}\n\t}\n\t\n\tif (themeIsUpdated) {\n\t\tapplyGroups();\n\t}\n\t\n}", "function userform_showACLforGroup() {\n\tvar RN = \"userform_showACLforGroup\";\n\tvar su = userform_lookupSelectedUser();\n\n\tunHighLightList(\"AccessControlList\");\n\tunHighLightList(\"AvailableGroupList\");\n\tenableList(\"AccessControlList\");\n\n\tvar o = document.getElementById(\"GroupList\");\n\n\tif (o && su && userhash[su][o.value]) {\n\n\t\t// figure out if there are multiple groups selected\n\t\tvar selected = 0;\n\n\t\tif (o.options[0].selected) {\n\t\t\to.options[0].selected = false; //IE\n\t\t\tunHighLightList(\"GroupList\");\n\t\t\treturn;\n\t\t}\n\n\t\tfor (var i = 0 ; i < o.options.length ; i++) {\n\t\t\tif (o.options[i].selected) {\n\t\t\t\tif (i == 0) {\n\t\t\t\t\t// IE doesnt support <option disabled>\n\t\t\t\t\t// deselect if selected\n\t\t\t\t\t//http://msdn.microsoft.com/workshop/author/dhtml/reference/properties/disabled_3.asp\n\t\t\t\t\to.options[0].selected = false;\n\t\t\t\t} else {\n\t\t\t\t\tselected++;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (selected == 0) return;\n\n\t\tif (selected > 1) {\n\t\t\t// clear the ACL and enable the modify all \n\t\t\t// buttons\n\t\t\tunHighLightList(\"AccessControlList\");\n\t\t\tuserform_enableModAll();\n\t\t}\n\t\telse {\n\t\t\tfor(var acl in userhash[su][o.value]) {\n\t\t\t\tuserform_disableModAll();\n\t\t\t\tdbg(1, RN + \": acl/\"+su+\"/\"+o.value+\"=\"+acl);\n\t\t\t\thighLightList(\"AccessControlList\", acl, 1);\n\t\t\t} \n\t\t}\n\t}\n}", "function addGroup(groupName, urls = []) {\n isGroup(groupName, function(isGroup){\n if (isGroup === false) {\n chrome.storage.local.get(\"groups\", function(data) {\n //Push group into groups\n data.groups[groupName] = {};\n data.groups[groupName][\"urls\"] = urls;\n data.groups[groupName][\"priority\"] = 0;\n for (group in data.groups) {\n if (group !== groupName) {\n data.groups[group].priority++;\n }\n }\n data.groups[groupName][\"edit\"] = false;\n chrome.storage.local.set(data, function() {\n console.log(\"Created group: \" + groupName);\n });\n });\n chrome.storage.local.get(\"number\", function(data) {\n data.number++;\n chrome.storage.local.set(data, function() {\n console.log(\"Created group: \" + groupName);\n //Reload the popup so the button will appear again.\n location.reload();\n });\n });\n } else {\n alert(\"There is already a group with name: \" + groupName);\n }\n });\n}", "async addMembers (usersOrIds, attrs = {}, { transacting } = {}) {\n const updatedAttribs = Object.assign(\n {},\n {\n active: true,\n role: GroupMembership.Role.DEFAULT,\n settings: {\n sendEmail: true,\n sendPushNotifications: true,\n showJoinForm: false\n }\n },\n pick(omitBy(attrs, isUndefined), GROUP_ATTR_UPDATE_WHITELIST)\n )\n\n const userIds = usersOrIds.map(x => x instanceof User ? x.id : x)\n const existingMemberships = await this.memberships(true)\n .query(q => q.whereIn('user_id', userIds)).fetch({ transacting })\n const reactivatedUserIds = existingMemberships.filter(m => !m.get('active')).map(m => m.get('user_id'))\n const existingUserIds = existingMemberships.pluck('user_id')\n const newUserIds = difference(userIds, existingUserIds)\n const updatedMemberships = await this.updateMembers(existingUserIds, updatedAttribs, { transacting })\n\n const newMemberships = []\n const defaultTagIds = (await GroupTag.defaults(this.id, transacting)).models.map(t => t.get('tag_id'))\n\n for (const id of newUserIds) {\n const membership = await this.memberships().create(\n Object.assign({}, updatedAttribs, {\n user_id: id,\n created_at: new Date()\n }), { transacting })\n newMemberships.push(membership)\n // Subscribe each user to the default tags in the group\n await User.followTags(id, this.id, defaultTagIds, transacting)\n }\n\n // Increment num_members\n // XXX: num_members is updated every 10 minutes via cron, we are doing this here too for the case that someone joins a group and moderator looks immediately at member count after that\n if (newUserIds.length > 0) {\n await this.save({ num_members: this.get('num_members') + newUserIds.length }, { transacting })\n }\n\n Queue.classMethod('Group', 'afterAddMembers', {\n groupId: this.id,\n newUserIds,\n reactivatedUserIds\n })\n\n return updatedMemberships.concat(newMemberships)\n }", "function addUserToSharePointGroup(groupID, key) {\n\n\n console.log(groupID + ' : ' + key);\n\n \n\n var siteUrl = '/asaalt/hqdag8/quad';\n\n var clientContext = new SP.ClientContext(siteUrl);\n var collGroup = clientContext.get_web().get_siteGroups();\n var oGroup = collGroup.getById(groupID);\n var userCreationInfo = new SP.UserCreationInformation();\n //userCreationInfo.set_email('david.m.lewandowsky.ctr@mail.mil');\n userCreationInfo.set_loginName(key);\n //userCreationInfo.set_title('MAINTENANCE TEST PILOT');\n this.oUser = oGroup.get_users().add(userCreationInfo);\n \n clientContext.load(oUser);\n clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));\n \n\n}", "function addNewGroupButton() {\n var ui = SpreadsheetApp.getUi();\n var response = ui.prompt('Input New Category Group', ui.ButtonSet.OK_CANCEL);\n \n if(response.getSelectedButton() == ui.Button.CANCEL) {\n return;\n }\n \n // Check to see if this group already exists\n var formula2Sheet = SpreadsheetApp.getActive().getSheetByName(\"FORMULAS2\");\n \n // First Get the last row in the groups DB that contains data \n var searchRangeLastRow = formula2Sheet.getLastRow();\n var searchArray = formula2Sheet.getRange(2, 9, searchRangeLastRow).getValues();\n \n for (i = 0; i <= searchArray.length; i++) {\n if(searchArray[i].toString() == \"\") { // searchArray is an array containing multiple arrays, convert each array to a string to expose the empty arrays as emppty strings which can be checked for in the conditional\n var lastRow = i + 2; // Adding 2 to offset for header and the fact that array indexing starts at 0\n \n if(i == 0) { // warn user if DB needs to be initialized\n ui.alert(\"ERROR: Category Groups DB must be initialized with at least one group\");\n return;\n }\n \n break;\n }\n }\n \n var groupDB = formula2Sheet.getRange(2, 9, lastRow-2).getValues();\n \n for (i = 0; i < groupDB.length; i++) {\n if( response.getResponseText() == groupDB[i].toString() ) {\n ui.alert(\"This group already exists\");\n return;\n }\n }\n \n // Now write the user's input to the last row of the DB\n formula2Sheet.getRange(lastRow, 9).setValue(response.getResponseText());\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates a MongoLog Object that takes either a string or an object. If a string is provided it is put on the message property of the MongoLog Object. If an object is provided each key on the object is put on the MongoLog Object.
constructor(db, log, level) { if (typeof log === 'object') { Object.keys(log).forEach(key => { if (key === 'db' || key === 'level') { throw new TypeError(`Invalid key: ${key}`); } this[key] = log[key]; }) } else { this.message = log; } if (typeof db === 'object') { this.db = db; } else { throw new TypeError(`Invalid value for db: ${db}`); } if (typeof level === 'number') { this.level = level; } else { this.level = DEFAULT_LOG_LEVEL; } this.timestamp = new Date(); }
[ "static async createLogDbModelInstanceFromLogDataAndSave(jrContext, type, message, extraData, mergeData) {\n\t\tlet logObj;\n\n\t\tif (message && !(typeof message === \"string\")) {\n\t\t\t// unusual case where the message is an object; for db we should json stringify as message\n\t\t\t// in this way the db log message is a pure stringified json object\n\t\t\tlogObj = {\n\t\t\t\ttype,\n\t\t\t\tmessage: JSON.stringify(message),\n\t\t\t\t...mergeData,\n\t\t\t\textraData,\n\t\t\t};\n\t\t} else {\n\t\t\tif (true && mergeData) {\n\t\t\t\t// ATTN: we want merge data to be part of log properties\n\t\t\t\t// merge mergeData into extraData since log object doesn't have other fields\n\t\t\t\tlogObj = {\n\t\t\t\t\ttype,\n\t\t\t\t\tmessage,\n\t\t\t\t\textraData,\n\t\t\t\t\t...mergeData,\n\t\t\t\t};\n\t\t\t} else {\n\t\t\t\tlogObj = {\n\t\t\t\t\ttype,\n\t\t\t\t\tmessage,\n\t\t\t\t\t...mergeData,\n\t\t\t\t\textraData,\n\t\t\t\t};\n\t\t\t}\n\t\t}\n\n\t\t// create the model\n\t\tconst logModel = LogModel.createModel(logObj);\n\n\t\t// ATTN: Note that it will not return on error to save since an exception will be thrown, since no jrContext is passed to store error\n\t\tconst retv = await logModel.dbSaveThrowException(jrContext);\n\t\treturn retv;\n\t}", "function mongologgerAppender(layout, timezoneOffset, source) {\n return function(loggingEvent) {\n Log.create({\n startTime: loggingEvent.startTime,\n source,\n level: loggingEvent.level.levelStr.toLowerCase(),\n data: loggingEvent.data,\n })\n }\n}", "function asMessage( data, id, type, to ) {\n const message = { time: Date.now(), id: id, data: data }\n if (type) message.type = type\n if (to != undefined) message.to = to\n return message\n }", "async addChatLog(action, user, message) {\n this.calendar.addDate(Date.now());\n return await this.stores.chat.insert({\n type: 'chat',\n created: Date.now(),\n instanceId: await this.getInstanceId(),\n action,\n user,\n ...(message ? {message} : {}),\n });\n }", "function LogItem(l, m, n, t, s) {\n\n this.Level = l;\n this.Message = m;\n this.LoggerName = n;\n this.DateTime = t;\n this.Source = s;\n }", "function createObj(id, textValue, dateValue, timeValue) {\n let noteObjTemp = Object.create(noteObjTemplate);\n noteObjTemp.id = id;\n noteObjTemp.text = textValue;\n noteObjTemp.date = dateValue;\n noteObjTemp.time = timeValue;\n return noteObjTemp;\n }", "function newObject() {\r\n let journalObject = {\r\n // dateObjectProperty: creationDate,\r\n date: creationDate,\r\n // confidenceObjectProperty: confidenceLevel,\r\n confidence: confidenceLevel,\r\n // journalObjectProperty: journalEnt\r\n journal: journalEnt,\r\n // makeObject() {\r\n // return journalObjectArray.push(journalObject);\r\n // }\r\n }\r\n // return journalObjectArray.push(journalObject);\r\n return journalEntries.push(journalObject);\r\n}", "log(_a) {\n var { severity, message } = _a,\n data = __rest(_a, ['severity', 'message']);\n if (!severity) severity = 'INFO';\n this.write(Object.assign({ message }, data), 'INFO');\n }", "async addChat(message){\n //format a chat object\n\n const now = new Date();\n const chat = {\n message : message,\n username:this.username,\n room: this.room,\n created_at : firebase.firestore.Timestamp.fromDate(now)\n }\n\n //save the chat document\n\n const response = await this.chats.add(chat);\n return response;\n }", "function createJobByMsgObj (msg)\n{\n var msgJSON = JSON.parse(msg.toString());\n createJob(msgJSON.jobName, msgJSON.jobName, msgJSON.jobPriority,\n msgJSON.firstRunDelay, msgJSON.runCount, msgJSON.data);\n}", "static create(data) {\n\n //Array?\n if (Array.isArray(data)) {\n return data\n .filter(item => !!item)\n .map(item => this.create(item));\n }\n\n //Already instance of LogAppRequest class?\n if (data instanceof LogAppRequest) {\n return data;\n }\n\n //Create instance\n return new LogAppRequest(data);\n }", "addRecord(record) {\n let _recordType = t.object();\n\n t.param('record', _recordType).assert(record);\n\n const { handlers, processors } = this.getHandlersAndProcessors(record.level);\n\n if (handlers.length === 0) {\n if (record.level > levels.ERROR) {\n // eslint-disable-next-line no-console\n console.log('[nightingale] no logger for > error level.', {\n key: record.key,\n message: record.message\n });\n }\n return;\n }\n\n if (processors) {\n processors.forEach(process => process(record, record.context));\n }\n\n handlers.some(handler => handler.handle(record) === false);\n }", "function populateDocumentWithObject (document, key, value) {\n const keys = Object.keys(value);\n const unprefixedKeys = keys.filter(k => k[0] !== '$');\n\n if (unprefixedKeys.length > 0 || !keys.length) {\n // Literal (possibly empty) object ( or empty object ) \n // Don't allow mixing '$'-prefixed with non-'$'-prefixed fields\n if (keys.length !== unprefixedKeys.length) {\n throw new Error(`unknown operator: ${unprefixedKeys[0]}`);\n }\n validateObject(value, key);\n insertIntoDocument(document, key, value);\n } else {\n Object.keys(value).forEach(function (k) {\n const v = value[k];\n if (k === '$eq') {\n populateDocumentWithKeyValue(document, key, v);\n } else if (k === '$all') {\n // every value for $all should be dealt with as separate $eq-s\n v.forEach(vx => populateDocumentWithKeyValue(document, key, vx));\n }\n });\n }\n}", "constructor(author, message, repliedTo) {\n this._author = author;\n this._message = message;\n this._repliedTo = repliedTo || null;\n this._createdAt = new Date();\n }", "function formatGroupMessage(user_idFrom, text) {\n\treturn {\n\t\tfrom: user_idFrom,\n\t\ttext: text,\n\t\tcreatedAt: moment()\n\t}\n}", "function logSearch(searchTags){\n\tvar date = new Date();\n\tvar newDocument = {\n\t\t'term': searchTags,\n\t\t'when': date\n\t};\n\tmongo.connect(mongoURL , function(error, database){\n\t\tif(error){\n\t\t\tthrow error;\n\t\t} else {\n\t\t\tdatabase.collection('image-searches').insert(newDocument, function(error, data){\n\t\t\t\tif(error){\n\t\t\t\t\tthrow error;\n\t\t\t\t} else {\n\t\t\t\t\tconsole.log(JSON.stringify(newDocument));\n\t\t\t\t\tdatabase.close();\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\t});\n}", "function isValidLog(log_obj){\r\n var expectedFields = [\"data\", \"message\", \"time\", \"subject_type\", \"author_info\"];\r\n for(f in expectedFields){\r\n if(log_obj[expectedFields[f]] != undefined){\r\n // console.log(f + \": \" + log_obj[expectedFields[f]])\r\n if (expectedFields[f] != \"data\" && log_obj[expectedFields[f]].length == 0){\r\n return false;\r\n }\r\n }else{\r\n return false;\r\n }\r\n }\r\n\r\n for(f in log_obj){\r\n if(expectedFields.indexOf(f) == -1){\r\n return false;\r\n }\r\n }\r\n return true;\r\n}", "function stringifyLogObjectFunction(logObject) {\n if (typeof logObject == \"function\") {\n if (logObject instanceof RegExp) {\n return logObject.toString();\n }\n else {\n return logObject();\n }\n }\n return logObject;\n }", "function parseLog(type, data) {\n if (type == 'network') {\n\treturn parseNetworkLog(data);\n } else if (type == 'acs_access') {\n\treturn parseAcsAccessLog(data);\n } else if (type == 'acs_commands') {\n\treturn parseAcsCommandsLog(data);\n } else if (type == 'everything') {\n\treturn parseEverythingLog(data);\n } else if (type == 'firewall') {\n\treturn parseFirewallLog(data);\n } else {\n\treturn { type: type, data: data };\n }\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
util.RegExp.addFlags(regexp, flags) > RegExp regexp (RegExp): Regular expression. flags (String): Flags to add. Adds flags to the given regular expression. util.RegExp.addFlags(/\s/, "g"); // > /\s/g util.RegExp.addFlags(/\s/, "gim"); // > /\s/gim If the given regular expression already has the flags, no action is taken. util.RegExp.addFlags(/\s/g, "g"); // > /\s/g
function addFlags(regexp, flags) { var reg = core.interpretRegExp(regexp); var regFlags = core.arrayUnique( reg.flags.split(""), flags.split("") ).join(""); return new RegExp(reg, regFlags); }
[ "function regexpFrom(string, flags) {\n return new RegExp(core.escapeRegExp(string), flags);\n }", "function getRegExp(pattern, flags) {\n var safeFlags = angular.isString(flags) ? flags : \"\";\n return (angular.isString(pattern) && pattern.length > 0) ? new RegExp(pattern, safeFlags) : null;\n }", "function _globalize($regexp) {\n return new RegExp(String($regexp).slice(1, -1), \"g\");\n }", "function regExBuilder(options){\n var re = options.regex ? options.find : w.escapeRegExp(options.find),\n reOptions = \"g\" + (options.insensitive ? \"i\" : \"\");\n return new RegExp(re, reOptions);\n}", "function regExBuilder (find, regex, insensitive) {\n if (find) {\n var re = regex ? find : s.escapeRegExp(find)\n var reOptions = 'g' + (insensitive ? 'i' : '')\n return new RegExp(re, reOptions)\n }\n}", "match(reg) {\n if (!(reg instanceof RegExp)) {\n console.warn(`Action ${this.name} requires a regex for match()`);\n return this;\n }\n this[match].push(reg);\n return this;\n }", "function TestRE(v, re)\n{\n return new RegExp(re).test(v);\n}", "function regenerateRegExp(){\r\n\t\tpseudoRE = new RegExp('::?(' + Object.keys(pseudos).join('|') + ')(\\\\\\\\[0-9]+)?');\r\n\t}", "function parseQuery(query, ignoreCase, smartCase) {\n // First update the last search register\n var lastSearchRegister = vimGlobalState.registerController.getRegister('/');\n lastSearchRegister.setText(query);\n // Check if the query is already a regex.\n if (query instanceof RegExp) {\n return query;\n }\n // First try to extract regex + flags from the input. If no flags found,\n // extract just the regex. IE does not accept flags directly defined in\n // the regex string in the form /regex/flags\n var slashes = findUnescapedSlashes(query);\n var regexPart;\n var forceIgnoreCase;\n if (!slashes.length) {\n // Query looks like 'regexp'\n regexPart = query;\n } else {\n // Query looks like 'regexp/...'\n regexPart = query.substring(0, slashes[0]);\n var flagsPart = query.substring(slashes[0]);\n forceIgnoreCase = flagsPart.indexOf('i') != -1;\n }\n if (!regexPart) {\n return null;\n }\n if (!getOption('pcre')) {\n regexPart = translateRegex(regexPart);\n }\n if (smartCase) {\n ignoreCase = /^[^A-Z]*$/.test(regexPart);\n }\n var regexp = new RegExp(regexPart, ignoreCase || forceIgnoreCase ? 'i' : undefined);\n return regexp;\n }", "function generateRegExp() {\n\n\tvar str = '';\n\tvar arr = [];\n\tvar tmp = \"@(types)\";\n\t\n\t// Get all the replaceable keywords from corpus, stick them into an array\n\tfor(type in corpus) {\n\t\tarr.push(type);\n\t}\n\t\n\t// Construct regular expression in the form of '@(keyword1,keyword2,keyword3,...)'\n\tvar exp = tmp.replace(\"types\", arr.join('|'));\n\t\n\treturn new RegExp(exp, \"ig\");\n}", "function parseRegExp(node) {\n const evaluated = (0, util_1.getStaticValue)(node, globalScope);\n if (evaluated == null || !(evaluated.value instanceof RegExp)) {\n return null;\n }\n const { source, flags } = evaluated.value;\n const isStartsWith = source.startsWith('^');\n const isEndsWith = source.endsWith('$');\n if (isStartsWith === isEndsWith ||\n flags.includes('i') ||\n flags.includes('m')) {\n return null;\n }\n const text = parseRegExpText(source, flags.includes('u'));\n if (text == null) {\n return null;\n }\n return { isEndsWith, isStartsWith, text };\n }", "function addParamArray(params, flag, paramArray) {\n paramArray.forEach(function(param){\n params.push('--' + flag +'=' + param);\n });\n}", "function generateRegExp() {\n\n\tvar str = '';\n\tvar arr = [];\n\tvar tmp = \"@(types)\";\n\t\n\tfor (type in corpus) {\n\t\tarr.push(type);\n\t}\n\t\n\tvar exp = tmp.replace(\"types\", arr.join('|'));\n\t\n\treturn new RegExp(exp, \"ig\");\n}", "function construct_phrase()\n{\n\tif (!arguments || arguments.length < 1 || !is_regexp)\n\t{\n\t\treturn false;\n\t}\n\n\tvar args = arguments;\n\tvar str = args[0];\n\tvar re;\n\n\tfor (var i = 1; i < args.length; i++)\n\t{\n\t\tre = new RegExp(\"%\" + i + \"\\\\$s\", \"gi\");\n\t\tstr = str.replace(re, args[i]);\n\t}\n\treturn str;\n}", "function AttrRegex(attr) {\r\n return new RegExp(attr + \"=\" + bracketsRegexText);\r\n}", "function parseRegExpText(pattern, uFlag) {\n // Parse it.\n const ast = regexpp.parsePattern(pattern, undefined, undefined, uFlag);\n if (ast.alternatives.length !== 1) {\n return null;\n }\n // Drop `^`/`$` assertion.\n const chars = ast.alternatives[0].elements;\n const first = chars[0];\n if (first.type === 'Assertion' && first.kind === 'start') {\n chars.shift();\n }\n else {\n chars.pop();\n }\n // Check if it can determine a unique string.\n if (!chars.every(c => c.type === 'Character')) {\n return null;\n }\n // To string.\n return String.fromCodePoint(...chars.map(c => c.value));\n }", "function buildNavigationRouteRegexp() {\n // Build the alternation expression for each of the navigation routes.\n let routeAlternation = Object.entries(NavigationConstants)\n .filter(([k]) => k !== \"LOGIN\" && k !== \"LOGOUT\")\n .map(([_, v]) => escapeRegExp(v))\n .join(\"|\");\n\n // Build and compile the full regular expression.\n return new RegExp(`^/(${routeAlternation})`);\n}", "function prepareRe(initials) {\n var myReStr = \"\";\n for (var i = 0; i < initials.length; i++) {\n\tmyReStr += \"\\\\w+\\\\s\";\n };\n myReStr = \"(\" + myReStr + \")\" + \"\\\\(\" + initials + \"\\\\)\";\n var myRe = new RegExp(myReStr, \"g\");\n return myRe;\n}", "function buildRuleRegExp( languageNode, contextNode )\n{\n\tvar sRegExp, ruleNode, regExpExprNode, rootNode;\n\tvar keywordListNode, keywordListNameNode, keywordListRegExpNode,xp;\n\t\n\trootNode = languageNode.selectSingleNode(\"/*\");\n\tsRegExp=\"(\";\n\n\tvar ruleList=contextNode.childNodes;\n\t// building regular expression\t\n\tfor (ruleNode=ruleList.nextNode(); ruleNode != null; ruleNode=ruleList.nextNode() )\n\t{\n\t\tif (ruleNode.nodeName == \"#comment\")\n\t\t\tcontinue;\n\t\t\t\n\t\t// apply rule...\n\t\tif (ruleNode.nodeName == \"detect2chars\")\n\t\t{\n\t\t\tvar char0=ruleNode.attributes.getNamedItem(\"char\").value;\n\t\t\tvar char1=ruleNode.attributes.getNamedItem(\"char1\").value;\n\t\t\tsRegExp= sRegExp + stringToRegExp( char0 + char1 ) + \"|\";\n\t\t}\n\t\telse if (ruleNode.nodeName == \"detectchar\")\n\t\t{\n\t\t\tvar char0=ruleNode.attributes.getNamedItem(\"char\").value;\n\t\t\tsRegExp=sRegExp + stringToRegExp( char0 ) + \"|\";\n\t\t}\n\t\telse if (ruleNode.nodeName == \"linecontinue\")\n\t\t{\n\t\t\tsRegExp=sRegExp + \"\\n|\"\n\t\t}\n\t\telse if (ruleNode.nodeName == \"regexp\" )\n\t\t{\n\t\t\tregExpExprNode = ruleNode.attributes.getNamedItem(\"expression\");\n\t\t\tif ( regExpExprNode == null )\n\t\t\t\tthrow \"Regular expression rule missing expression attribute\";\n\t\t\t\t\n\t\t\tsRegExp=sRegExp + regExpExprNode.nodeTypedValue + \"|\";\n\t\t}\n\t\telse if (ruleNode.nodeName == \"keyword\")\n\t\t{\n\t\t\t// finding keywordlist\n\t\t\tkeywordListNameNode = ruleNode.attributes.getNamedItem(\"family\");\n\t\t\tif (keywordListNameNode == null)\n\t\t\t\tthrow \"Keyword rule missing family\";\n\t\t\txp=\"keywordlists/keywordlist[@id=\\\"\"\n\t\t\t\t\t+ keywordListNameNode.nodeTypedValue \n\t\t\t\t\t+ \"\\\"]\";\n\t\t\tkeywordListNode = rootNode.selectSingleNode(xp);\n\t\t\tif (keywordListNode == null)\n\t\t\t\tthrow \"Could not find keywordlist (xp: \"+ xp + \")\";\n\t\t\t\t\n\t\t\tkeywordListRegExpNode = keywordListNode.attributes.getNamedItem(\"regexp\");\n\t\t\tif (keywordListRegExpNode == null)\n\t\t\t\tthrow \"Could not find keywordlist regular expression\";\n\t\t\t\t\n\t\t\t// adding regexp\n\t\t\tsRegExp=sRegExp+keywordListRegExpNode.nodeTypedValue+\"|\";\n\t\t}\n\t}\n\n\tif (sRegExp.length > 1)\n\t\tsRegExp=sRegExp.substring(0,sRegExp.length-1)+\")\";\n\telse\n\t\tsRegExp=\"\";\n\t\n\treturn sRegExp;\t\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Resets the selected time to client (system) time
resetSelected() { this.setHour(this.time.hour) this.setMinute(this.time.minute) this.setPeriod(this.time.getPeriod()) }
[ "function setCurrentTime() {\n\t\tvar total = player.currentTime;\n\t\tcurrentTimeElement.innerHTML = timeFormat(total);\n\t}", "function refreshMainTimeView() {\n setText(document.querySelector(\"#text-main-hour\"),\n addLeadingZero(Math.floor(setting.timeSet / 3600), 2));\n setText(document.querySelector(\"#text-main-minute\"),\n addLeadingZero(Math.floor(setting.timeSet / 60) % 60, 2));\n setText(document.querySelector(\"#text-main-second\"),\n addLeadingZero(setting.timeSet % 60, 2));\n applyStyleTransition(document.querySelector(\"#box-hand-hour\"),\n ROTATE_DATA_HAND, \"START\", \"END\", (setting.timeSet % 43200) / 43200);\n applyStyleTransition(document.querySelector(\"#box-hand-minute\"),\n ROTATE_DATA_HAND, \"START\", \"END\", (setting.timeSet % 3600) / 3600);\n applyStyleTransition(document.querySelector(\"#box-hand-second\"),\n ROTATE_DATA_HAND, \"START\", \"END\", (setting.timeSet % 60) / 60);\n }", "function setTime() {\n var timerInterval = setInterval(function() {\n var currentTime= moment().format();\n setColor();\n\n if(currentTime === \"11:59:59 pm\") {\n clearInterval(timerInterval);\n localStorage.clear();\n location.reload(); \n }\n\n }, 1800000);\n}", "function resetOwnActionTimer() {\n actionTimer = new Date()\n }", "function changeDefaultTimeOut() {\n let user = db.ref('users/' + userId);\n\n const newDefaultTime = app.getArgument('newDefaultTime');\n\n if (newDefaultTime && (newDefaultTime * 60) > 0) {\n let minutes = parseInt(newDefaultTime) * 60;\n let promise = user.set({userId: userId, defaultCheckOutTime: minutes});\n\n app.tell(`Done. The new default session time out is now set to ${newDefaultTime} hours.`);\n } else {\n app.ask(`Sorry! can you please repeat that.`);\n }\n }", "_clearDate() {\n this.value = undefined;\n this.display = '';\n }", "function clockReset(){\n\n clockOnly.checked = true;\n clockOptions.checked = false;\n toolTip.checked = false;\n\n clockTracker = 1;\n optionsTracker = 0;\n toolTipTracker = 0;\n\n optionsPanel.style.opacity = 0;\n toolTipPanel.style.opacity = 0;\n\n binaryMarker.checked = false;\n binaryMarkerTracker = 0;\n \n binary8.style.opacity = 0;\n binary4.style.opacity = 0;\n binary2.style.opacity = 0;\n binary1.style.opacity = 0;\n binaryDay.style.opacity = 0;\n\n hourMarker.checked = false;\n hourMarkerTracker = 0;\n \n hours.style.opacity = 0;\n minutes.style.opacity = 0;\n seconds.style.opacity = 0;\n nightDay.style.opacity = 0;\n\n hoursMath.style.opacity = 0;\n minutesMath.style.opacity = 0;\n document.getElementById('h3SecondsMath').style.opacity = 0;\n blankNightDay.style.opacity = 0;\n}", "static setTime(from, to) {\n to.setHours(from.getHours());\n to.setMinutes(from.getMinutes());\n to.setSeconds(0);\n to.setMilliseconds(0);\n return to;\n }", "function updateTime() {\n let now = new Date();\n let hour = now.getHours();\n let mins = now.getMinutes();\n let sec = now.getSeconds();\n \n syncAnalogClock(hour, mins, sec);\n syncDigitalClock24Hours(hour, mins, sec);\n syncDigitalClock12Hours(hour, mins, sec);\n}", "reset () {\n this.total = this.seconds * 1000.0;\n this._remaining = this.total;\n this._clearInterval();\n this.tick();\n }", "function setLogOutTime(){\r\n\thour = prompt(output(11), \"23\");\r\n\ttime = new Date();\r\n\ttime.setHours(hour,\"0\", \"0\", \"0\");\r\n\ttimeToLogOut = parseInt(time.getTime());\r\n\tif (timeToLogOut < parseInt(new Date().getTime())){\r\n\t\ttimeToLogOut += 86400000;\r\n\t}\r\n\tGM_setValue(\"logOutTime\", timeToLogOut.toString());\r\n}", "function dateReset() {\n var date = new Date();\n document.write(\"Current date \"+ date);\n var hr = date.getHours();\n date.setHours(hr-1);\n document.write(\"<br> 1 hour ago, it was \"+ date);\n}", "setCurrentTime(newCurrentTime) {\n if (newCurrentTime < 0) {\n return 0;\n }\n this.setState({\n currentTimeState: newCurrentTime\n })\n }", "resetTimer() {\n this.timer = 0;\n this.spawnDelay = GageLib.math.getRandom(\n this.spawnRate.value[0],\n this.spawnRate.value[1]\n );\n }", "setBakingTime() {}", "clearAndResetUpdate(){\n\t\tclearTimeout(timer);\n\t\tthis.getChats();\t\n\t}", "function updateTime() {\n const datetime = tizen.time.getCurrentDateTime();\n const hour = datetime.getHours();\n const minute = datetime.getMinutes();\n const second = datetime.getSeconds();\n\n const separator = second % 2 === 0 ? \":\" : \" \";\n\n $(\"#time-text\").html(padStart(hour.toString()) + separator + padStart(minute.toString()));\n\n // Update the hour/minute/second hands\n rotateElements((hour + (minute / 60) + (second / 3600)) * 30, \"#hands-hr-needle\");\n rotateElements((minute + second / 60) * 6, \"#hands-min-needle\");\n clearInterval(interval);\n if (!isAmbientMode) {\n let anim = 0.1;\n rotateElements(second * 6, \"#hands-sec-needle\");\n interval = setInterval(() => {\n rotateElements((second + anim) * 6, \"#hands-sec-needle\");\n anim += 0.1;\n }, 100);\n }\n }", "reset() {\n\t\tclearInterval(this.timer);\n\t\tthis.setState(this.initialState);\n\t}", "function presetDate() {\n\tvar date = unescape(getURLParam('date'));\n\tvar time = unescape(getURLParam('time'));\n\n\t$('#date').val(date);\n\t$('#date').trigger('change');\n\n\t$('#time').val(time);\n\t$('#time').trigger('change');\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
FUNCTION: extGroup.getSubType DESCRIPTION: get ext data subtype ARGUMENTS: groupName extension data group file name RETURNS: string subType
function extGroup_getSubType(groupName) { return dw.getExtDataValue(groupName, "subType"); }
[ "function extPart_getPartType(groupName, partName)\n{\n var retVal = \"\";\n\n if (groupName)\n {\n retVal = dw.getExtDataValue(groupName, \"groupParticipants\", partName, \"partType\");\n }\n\n return retVal;\n}", "function getItemSubType() {\n return new RegExp(`^${template.bug.headlines[0]}`).test(itemBody)\n ? ItemSubType.bug\n : new RegExp(`^${template.feature.headlines[0]}`).test(itemBody)\n ? ItemSubType.feature\n : new RegExp(`^${template.pr.headlines[0]}`).test(itemBody)\n ? ItemSubType.pr\n : undefined;\n}", "function extGroup_getDataSourceFileName(groupName)\n{\n return dw.getExtDataValue(groupName, \"dataSource\");\n}", "function CallBack_ShowColumSubType(data) {\r\n grid_columnsubtypes.SetDatasource(data);\r\n}", "function extension(type) {\n const match = EXTRACT_TYPE_REGEXP.exec(type);\n if (!match) {\n return;\n }\n const exts = exports.extensions.get(match[1].toLowerCase());\n if (!exts || !exts.length) {\n return;\n }\n return exts[0];\n }", "function getCategory(name)\n{\n let ext=path.extname(name); // get the extension name of the file \n ext=ext.slice(1); // as the extension name will have a dot(.) at the front we need to slice it.\n\n // traverse thorugh all the types and check whether the extension name matches with any subfield in any category or not\n for(let type in types)\n {\n const currentCategory=types[type];\n for(let i=0;i<currentCategory.length;i++)\n {\n // if we've found a match for the extension then return the category\n if(ext==currentCategory[i])\n {\n return type;\n }\n }\n }\n // if the file extension doesn't match with any category then return a default category \"others\"\n return \"others\";\n}", "function extGroup_getFamily(groupName, paramObj)\n{\n var retVal = dw.getExtDataValue(groupName, \"family\");\n\n if (paramObj)\n {\n retVal = extUtils.replaceParamsInStr(retVal, paramObj);\n }\n\n return retVal;\n}", "function extPart_getDeleteType(partName)\n{\n return dw.getExtDataValue(partName, \"delete\", \"deleteType\");\n}", "function has_sub_extension(e) {\n\t//if(process.env.DEBUG_MVC) {\n\t//\tdebug.log('has_sub_extension(', e, ')');\n\t//}\n\tdebug.assert(e).is('string');\n\treturn function has_sub_extension_2(p) {\n\t\tvar name = PATH.basename(p, PATH.extname(p));\n\t\treturn PATH.extname(name) === e;\n\t};\n}", "function extGroup_getVersion(groupName)\n{\n var retrievedVersion = parseFloat(dw.getExtDataValue(groupName, \"version\"));\n if (isNaN(retrievedVersion))\n retrievedVersion = 0;\n return retrievedVersion;\n}", "function dwscripts_getUniqueSBGroupName(paramObj, serverBehaviorName)\n{\n var groupName = \"\";\n var groupNames = dwscripts.getSBGroupNames(serverBehaviorName);\n\n if (groupNames.length)\n {\n if (groupNames.length == 1)\n {\n groupName = groupNames[0];\n }\n else\n {\n //if subType or dataSource given, resolve ties by filtering using them\n if (paramObj)\n {\n var matchGroups = new Array();\n for (var i=0; i<groupNames.length; i++)\n {\n //if no dataSource or it matches, and no subType or it matches, keep groupName\n if (\n (\n (!paramObj.MM_dataSource && !dw.getExtDataValue(groupNames[i],\"dataSource\")) ||\n (paramObj.MM_dataSource && dw.getExtDataValue(groupNames[i],\"dataSource\") == paramObj.MM_dataSource)\n )\n &&\n (\n (!paramObj.MM_subType && !dw.getExtDataValue(groupNames[i],\"subType\")) ||\n (paramObj.MM_subType && dw.getExtDataValue(groupNames[i],\"subType\") == paramObj.MM_subType)\n )\n )\n {\n matchGroups.push(groupNames[i]);\n }\n }\n\n if (!matchGroups.length && paramObj.MM_subType)\n {\n for (var i=0; i<groupNames.length; i++)\n {\n //if no dataSource or it matches, and no subType, keep groupName\n if (\n (\n (!paramObj.MM_dataSource && !dw.getExtDataValue(groupNames[i],\"dataSource\")) ||\n (paramObj.MM_dataSource && dw.getExtDataValue(groupNames[i],\"dataSource\") == paramObj.MM_dataSource)\n )\n && !dw.getExtDataValue(groupNames[i],\"subType\")\n )\n {\n matchGroups.push(groupNames[i]);\n break;\n }\n }\n }\n\n if (!matchGroups.length && paramObj.MM_dataSource)\n {\n //if no dataSource, keep groupName\n for (var i=0; i<groupNames.length; i++)\n {\n if (!dw.getExtDataValue(groupNames[i],\"dataSource\"))\n {\n matchGroups.push(groupNames[i]);\n break;\n }\n }\n }\n\n //if anything left after filtering, use that\n if (matchGroups.length)\n {\n groupName = matchGroups[0];\n }\n }\n }\n }\n\n return groupName;\n}", "function getSub (tag){\n var sub = \"\";\n for(var i = 0; i < tags.length; ++i){\n if(tags[i].name == tag) sub = tags[i].Sub;\n }\n return sub;\n }", "_getSubControlDef(subCtrlName) {\n\t\tfor (let i = 0; i < this.props.control.subControls.length; i++) {\n\t\t\tif (this.props.control.subControls[i].name === subCtrlName) {\n\t\t\t\treturn this.props.control.subControls[i];\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}", "function extGroup_getSelectParticipant(groupName)\n{\n return dw.getExtDataValue(groupName, \"groupParticipants\", \"selectParticipant\");\n}", "function extGroup_find(groupName, title, sbConstructor, participantList)\n{\n var sbList = new Array(); //array of ServerBehaviors\n\n var partList = (participantList) ? participantList : dw.getParticipants(groupName);\n\n if (extGroup.DEBUG) {\n if (partList) {\n for (var i=0; i < partList.length; i++) {\n var msg = new Array();\n msg.push(\"Participant \" + i);\n msg.push(\"\");\n msg.push(\"participantName = \" + partList[i].participantName);\n msg.push(\"\");\n msg.push(\"parameters = \");\n for (var j in partList[i].parameters) {\n msg.push(\" \" + j + \" = \" + partList[i].parameters[j] + \" (typeof \" + typeof partList[i].parameters[j] + \")\");\n }\n msg.push(\"\");\n msg.push(\"participantText = \");\n if (partList[i].participantNode)\n {\n var nodeHTML = dwscripts.getOuterHTML(partList[i].participantNode);\n msg.push(nodeHTML.substring(partList[i].matchRangeMin,partList[i].matchRangeMax));\n }\n else\n {\n msg.push(\"ERROR: null participantNode\");\n }\n\n alert(msg.join(\"\\n\"));\n }\n } else {\n alert(\"no participants found for group: \" + this.name);\n }\n }\n\n // Get group title. If no title is defined in the extension data, use the passed\n // in title. If, in addition, no title is passed in, use the groupName.\n var groupTitle = extGroup.getTitle(groupName);\n if (!groupTitle)\n {\n if (title)\n {\n groupTitle = title;\n }\n else\n {\n groupTitle = groupName;\n }\n }\n\n if (partList)\n {\n //sort participants for correct matching into groups later\n partList.sort( extGroup_participantCompare );\n\n //pull out extra information for each part\n for (var i=0; i < partList.length; i++)\n {\n //set the parts position within the master partList\n partList[i].position = i;\n\n //extract node parameter information\n extPart.extractNodeParam(partList[i].participantName, partList[i].parameters,\n partList[i].participantNode);\n\n }\n\n //now match up the found parts to create a list of part groups\n var partGroupList = extGroup.matchParts(groupName, partList);\n\n //now walk the partGroupList and create ServerBehaviors\n for (var i=0; i < partGroupList.length; i++)\n {\n var partGroup = partGroupList[i];\n\n // create a ServerBehavior\n var serverBehavior = null;\n if (sbConstructor == null)\n {\n serverBehavior = new ServerBehavior(groupName);\n }\n else\n {\n serverBehavior = new sbConstructor(groupName);\n }\n\n //sort the partGroup, so that the insert code finds the participant nodes\n // in the correct document order\n partGroup.sort(new Function(\"a\", \"b\", \"return a.position - b.position\"));\n\n //add the participant information to the ServerBehavior\n for (var j=0; j < partGroup.length; j++)\n {\n if (extPart.getVersion(partGroup[j].participantName) >= 5.0)\n {\n //add the information to the ServerBehavior\n var sbPart = new SBParticipant(partGroup[j].participantName, partGroup[j].participantNode,\n partGroup[j].matchRangeMin, partGroup[j].matchRangeMax,\n partGroup[j].parameters);\n }\n else\n {\n //add the information to the ServerBehavior\n var sbPart = new SBParticipant(partGroup[j].participantName, partGroup[j].participantNode,\n 0, 0,\n partGroup[j].parameters);\n }\n serverBehavior.addParticipant(sbPart);\n\n //set the selected node\n if (partGroup[j].participantName == extGroup.getSelectParticipant(groupName))\n {\n serverBehavior.setSelectedNode(partGroup[j].participantNode);\n }\n }\n\n //set the title\n serverBehavior.setTitle(extUtils.replaceParamsInStr(groupTitle,\n serverBehavior.getParameters(false)));\n\n //set the family\n serverBehavior.setFamily(extGroup.getFamily(groupName, serverBehavior.getParameters(false)));\n\n //check the ServerBehavior for completeness\n var partNames = extGroup.getParticipantNames(groupName);\n for (var j=0; j < partNames.length; j++)\n {\n var isOptional = extPart.getIsOptional(groupName, partNames[j]);\n sbPart = serverBehavior.getNamedSBPart(partNames[j]);\n var partNode = null;\n if (sbPart)\n {\n partNode = sbPart.getNodeSegment().node;\n }\n\n //if this is not an optional participant, check the ServerBehavior for completeness\n if (!isOptional && extPart.getWhereToSearch(partNames[j]) && partNode == null)\n {\n serverBehavior.setIsIncomplete(true);\n\n if (extGroup.DEBUG)\n {\n alert(\"setting record #\" + i + \" to incomplete: missing part: \" + partNames[j]);\n }\n }\n }\n\n // Make the sb object backward compatible with the UD4 sb object.\n serverBehavior.makeUD4Compatible();\n\n //add it to the list of ServerBehaviors\n sbList.push(serverBehavior);\n }\n }\n\n return sbList;\n}", "function recordsetDialog_searchByType(stype) {\r\n\tfor (ii = 0; ii < MM.rsTypes.length;ii++) {\r\n\t\tif (dw.getDocumentDOM().serverModel.getServerName() == MM.rsTypes[ii].serverModel) {\r\n\t\t\tif (MM.rsTypes[ii].type == stype) {\r\n\t\t\t\treturn ii;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\treturn -1;\r\n}", "function longSpecType( )\n{\n var stype = \"Onbekend\";\n\n if(respecConfig.specType != null) \n {\n var stype = respecParams.validSpecTypes[respecConfig.specType].txt;\n }\n console.log(\"\\t\\tLong SpecType is [\" + stype + \"]\");\n return( stype );\n}", "function SBParticipant_getDeleteType()\n{\n return extPart.getDeleteType(this.name);\n}", "visitSubtype_declaration(ctx) {\n\t return this.visitChildren(ctx);\n\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create a new ConsoleLog destination.
function ConsoleLogDestination(filter, formatter) { this.filter = filter || Utils.allowAll; this.formatter = formatter || defaultFormatter; }
[ "function Destination(props) {\n return __assign({ Type: 'AWS::Logs::Destination' }, props);\n }", "function createNewLogFile() {\n var basePath = (global.TYPE.int === global.TYPE_LIST.CLIENT.int ? \"./\" : path.join(__dirname, \"..\")); //Get base path\n if (fs.existsSync(path.join(basePath, \"Timbreuse.10.log\"))) //If log 10 exists, delete\n fs.unlinkSync(path.join(basePath, \"Timbreuse.10.log\"));\n for (var i = 9; i > 0; i--)\n if (fs.existsSync(path.join(basePath, \"Timbreuse.\" + i + \".log\"))) //Then move log n to log n+1\n fs.renameSync(path.join(basePath, \"Timbreuse.\" + i + \".log\"), path.join(basePath, \"Timbreuse.\" + (i + 1) + \".log\"));\n if (fs.existsSync(path.join(basePath, \"Timbreuse.log\"))) //If log exists, move it to log 1\n fs.renameSync(path.join(basePath, \"Timbreuse.log\"), path.join(basePath, \"Timbreuse.1.log\"));\n global.logFile = fs.createWriteStream(path.join(basePath, \"Timbreuse.log\"), { //Then create write stream to log file\n flags: 'w'\n });\n}", "function createDebugLogger(){\r\n $('BODY') \r\n .prepend(\r\n $('<div />')\r\n .append(\r\n $('<h4 />')\r\n .text('Output log event')\r\n .append(\r\n $('<a />')\r\n .attr('href','#')\r\n .on(ao.configuration.tapOrClickEvent,function(e){\r\n e.preventDefault();\r\n \r\n $('#logger .inner')\r\n .empty()\r\n })\r\n .text('(clear)')\r\n )\r\n .append(\r\n $('<a />')\r\n .attr('href','#')\r\n .on(ao.configuration.tapOrClickEvent,function(e){\r\n e.preventDefault();\r\n \r\n $('#logger .inner')\r\n .css('height','100px')\r\n })\r\n .text('(regular size)')\r\n )\r\n .append(\r\n $('<a />')\r\n .attr('href','#')\r\n .on(ao.configuration.tapOrClickEvent,function(e){\r\n e.preventDefault();\r\n \r\n $('#logger .inner')\r\n .css('height','400px')\r\n })\r\n .text('(small expand)')\r\n )\r\n )\r\n .append(\r\n $('<div />')\r\n .attr('class','inner')\r\n )\r\n .attr('id','logger')\r\n )\r\n .addClass('debug');\r\n \r\n $.logEvent('[ao.core.createDebugLogger]');\r\n }", "createProxy() {\n const self = this;\n this._proxy = new Proxy(console, {\n get: (target, property) => {\n if ( typeof target[property] === 'function' ) {\n return function(args) {\n self.send(property, args);\n return target[property](args);\n }\n }\n },\n });\n }", "function _defineConsoleLogMethod(name, level) {\n enhancedConsole[name] = function __expoConsoleLog(...data) {\n const originalMethod = originalConsole[name];\n if (typeof originalMethod === 'function') {\n originalMethod.apply(originalConsole, data);\n }\n _enqueueRemoteLog(level, {}, data);\n };\n }", "setConsoleLogger(consoleLogger) {\n global.G_configLogger = consoleLogger\n }", "function configureConsoleLogging () {\n var isEnabled = ('true' === process.env.LOGGING_CONSOLE_ACTIVE) // mandatory envVar\n , expressJsLog = getExpressJsLog()\n , clientAppLog = getClientAppLog();\n\n // remove default console, and if console logging enabled, add new console with our custom settings\n // headless testing doesn't have console instance attached, try-catch to prevent failure\n try { winston.remove(winston.transports.Console); } catch(err) {}\n try { expressJsLog.remove(winston.transports.Console); } catch(err) {}\n try { clientAppLog.remove(winston.transports.Console); } catch(err) {}\n\n if (isEnabled) {\n winston.add(winston.transports.Console, { level: serverAppLogTreshold, timestamp: true });\n expressJsLog.add(winston.transports.Console, { level: serverAppLogTreshold, timestamp: true });\n clientAppLog.add(winston.transports.Console, { level: clientAppLogTreshold, timestamp: true });\n }\n}", "function Logger(){\n\tthis.log = function(info) {\n\t\tconsole.log(\"The \" + info + \" event has been emitted\");\n\t}\n}", "function setupConsoleLogging() {\n (new goog.debug.Console).setCapturing(true);\n}", "getLogs() {\n this.logs.map((log)=>{\n console[log.type].call(null, log.msg);\n })\n }", "_log() {\n let args = Array.prototype.slice.call(arguments, 0);\n\n if (!args.length) {\n return;\n }\n\n if (args.length > 1)\n this.emit('log', args.join(', '));\n else\n this.emit('log', args[0]);\n }", "function mongologgerAppender(layout, timezoneOffset, source) {\n return function(loggingEvent) {\n Log.create({\n startTime: loggingEvent.startTime,\n source,\n level: loggingEvent.level.levelStr.toLowerCase(),\n data: loggingEvent.data,\n })\n }\n}", "function LogToTTY(max_depth = -1) {\r\n bind.LogToTTY(max_depth);\r\n }", "function configureLog() {\n\t\n\t/**\n\t * create log file path\n\t */\n\tvar logdir = path.join(__dirname, 'logs');\n\n\tif (!fs.existsSync(logdir)){\n\t fs.mkdirSync(logdir);\n\t}else {\n\t\t/**\n\t\t * Delete previous log files\n\t\t */\n\t\ttry {\n\t\t\tfs.unlinkSync(path.join(__dirname, 'logs/webapp.log'));\n\t\t\tfs.unlinkSync(path.join(__dirname, 'logs/webrtc.log'));\n\t\t}catch(err){\n\t\t\tconsole.error(err);\n\t\t}\n\t}\n\n\tlog4js.configure(logger_cfg, { cwd: logging_path });\t\n}", "function consoleOut(msg) {\n console.log(msg);\n console_log += msg + \"\\n\";\n}", "log(_a) {\n var { severity, message } = _a,\n data = __rest(_a, ['severity', 'message']);\n if (!severity) severity = 'INFO';\n this.write(Object.assign({ message }, data), 'INFO');\n }", "function LogStream(props) {\n return __assign({ Type: 'AWS::Logs::LogStream' }, props);\n }", "function createLogger(debug) {\n const { splat, timestamp, colorize, combine } = winston.format;\n const logFilePath = path.join(app.getPath(\"userData\"), \"exilibrium.log\");\n let level = \"info\";\n\n if (fs.pathExistsSync(logFilePath) && fs.statSync(logFilePath).size > 4e6) {\n console.log(`Removing ${logFilePath} before creating logger.`);\n fs.unlinkSync(logFilePath);\n console.log(`Removed file: ${logFilePath}`);\n }\n\n const transports = [\n new winston.transports.File({\n filename: logFilePath,\n maxsize: 4e6, // 4 MB\n maxFiles: 4,\n tailable: true\n //zippedArchive: true // this option doesn't work correctly in this version\n })\n ];\n const format = combine(\n splat(),\n timestamp({ format: \"YYYY-MM-DD HH:mm:ss.SSS\" }),\n customFormatter\n );\n\n if (debug) {\n level = \"debug\";\n transports.push(\n new winston.transports.Console({\n format: combine(\n splat(),\n timestamp({ format: \"YYYY-MM-DD HH:mm:ss.SSS\" }),\n colorize({ message: true }),\n customFormatter\n )\n })\n );\n }\n\n return winston.createLogger({ level, transports, format });\n}", "function LogToClipboard(max_depth = -1) {\r\n bind.LogToClipboard(max_depth);\r\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
createTrain() This function creates the train using a train 3D Object to hold the different parts. The body of the train is created using a boxGeom, and the wheels are created using TorusGeometry.
function createTrain() { var train = new THREE.Object3D(); //create the larger part of the body var geom = new THREE.BoxGeometry(8,4,2); var material = new THREE.MeshPhongMaterial({ambient:"rgb(120,60,30)"}); //dark brown var mesh = new THREE.Mesh(geom,material); mesh.position.set(0,-47,30); train.add(mesh); //create the front part of the train (smaller box) var geom2 = new THREE.BoxGeometry(3,2,1); var material2 = new THREE.MeshPhongMaterial({ambient:"rgb(130,50,20)"}); //sandy brown var mesh2 = new THREE.Mesh(geom2,material2); mesh2.position.set(4,-48,30); train.add(mesh2); //create the spout of the train var spout = new THREE.BoxGeometry(1,2,1); var material3 = new THREE.MeshPhongMaterial({ambient:"rgb(40,40,40)"}); //dark gray var sMesh = new THREE.Mesh(spout,material3); sMesh.position.set(2,-45,30); train.add(sMesh); //create two of the same-side wheels of the train var wheels = new THREE.Object3D(); var wheel = new THREE.TorusGeometry(1,.25,10,10); //create one wheel var wMesh = new THREE.Mesh(wheel,material3); //same material as the spout wMesh.position.set(-2,-49,31.5); wheel2 = wMesh.clone(); //create 2nd wheel wheel2.position.set(2,-49,31.5); wheels.add(wMesh); wheels.add(wheel2); //create other set of wheels (on back side) otherWheels = wheels.clone(); otherWheels.position.set(0,0,-3); //move to the other side train.add(wheels); train.add(otherWheels); return train; //return train object to allow for later positioning and animation }
[ "createModel () {\n var model = new THREE.Object3D()\n var loader = new THREE.TextureLoader();\n var texturaOvo = null;\n\n var texturaEsfera = null;\n \n //var texturaGrua = new THREE.TextureLoader().load(\"imgs/tgrua.jpg\");\n this.robot = new Robot({});\n this.robot.scale.set(3,3,3);\n //model.add (this.robot);\n\n //Crear Objetos voladores\n var comportamiento = null; //Buenos - Malos\n\n for (var i = 0; i < this.maxMeteoritos; ++i) {\n if (i < this.dificultad) {\n comportamiento = false;\n texturaOvo = loader.load (\"imgs/cesped1.jpg\");\n } else {\n comportamiento = true;\n texturaOvo = loader.load (\"imgs/fuego.jpg\");\n }\n this.objetosVoladores[i] = new Ovo(new THREE.MeshPhongMaterial ({map: texturaOvo}), comportamiento);\n //model.add(this.objetosVoladores[i]);\n\n\n this.esfera = new Ovo(new THREE.MeshPhongMaterial ({map: texturaOvo}), comportamiento);\n model.add(this.esfera);\n //model.add(this.createEsfera());\n\n }\n\n\n //var loader = new THREE.TextureLoader();\n var textura = loader.load (\"imgs/suelo1.jpg\");\n this.ground = new Ground (300, 300, new THREE.MeshPhongMaterial ({map: textura}), 4);\n model.add (this.ground);\n\n return model;\n }", "function creaFinestroni(DimX,DimY,PosX,PosY,aperturaFin){\nvar Finestrone1 = new THREE.Object3D();\nvar Finestrone2 = new THREE.Object3D();\nvar Perno = new THREE.Object3D();\n\nvar trave1 = createMeshPortWindow(new THREE.BoxGeometry(DimX/2, 0.1, 0.1), 'PortText.jpg');\ntrave1.position.set(DimX/4,0,0)\nvar trave2 = createMeshPortWindow(new THREE.BoxGeometry(DimX/2, 0.1, 0.1), 'PortText.jpg');\ntrave2.position.set(DimX-(DimX/4),0,0)\nvar trave3 = createMeshPortWindow(new THREE.BoxGeometry(DimX/2, 0.1, 0.1),'PortText.jpg');\ntrave3.position.set(DimX-(DimX/4),DimY,0)\nvar trave4 = createMeshPortWindow(new THREE.BoxGeometry(DimX/2, 0.1, 0.1), 'PortText.jpg');\ntrave4.position.set(DimX/4,DimY,0)\n\nvar trave5 = createMeshPortWindow(new THREE.BoxGeometry(0.1, DimY-0.1, 0.1), 'PortText.jpg');\ntrave5.position.set(0.05,DimY/2,0)\nvar trave6 =createMeshPortWindow(new THREE.BoxGeometry(0.1, DimY-0.1, 0.1), 'PortText.jpg');\ntrave6.position.set(DimX/2,DimY/2,0)\n\nvar trave8 = createMeshPortWindow(new THREE.BoxGeometry(0.1, DimY-0.1, 0.1), 'PortText.jpg');\ntrave8.position.set(DimX/2,DimY/2,0)\n\nvar trave7 = createMeshPortWindow(new THREE.BoxGeometry(0.1, DimY-0.1, 0.1), 'PortText.jpg');\ntrave7.position.set(DimX-0.05,DimY/2,0)\n\nvar specchio1Geometry = new THREE.BoxGeometry((DimX/2)-0.15, DimY-0.1, 0.1);\n var mGlass = new THREE.MeshLambertMaterial( {\n color: 0xccccff,opacity: 0.3, transparent: true} ); \n\nspecchio1 = new THREE.Mesh( specchio1Geometry, mGlass);\nspecchio1.position.set((DimX/4)+0.02,(DimY/2),0)\n\nspecchio2 = new THREE.Mesh( specchio1Geometry, mGlass);\nspecchio2.position.set((DimX-(DimX/4)-0.02),(DimY/2),0)\n\nFinestrone1.add(trave1)\nFinestrone1.add(trave4)\nFinestrone1.add(trave5)\nFinestrone1.add(trave6)\nFinestrone1.add(specchio1)\nFinestrone1.add(Perno)\n\nFinestrone2.add(trave2)\nFinestrone2.add(trave3)\nFinestrone2.add(trave7)\nFinestrone2.add(trave8)\nFinestrone2.add(specchio2)\nPerno.add(Finestrone2)\n\nFinestrone1.position.set(PosX,PosY,0.15);\nFinestrone1.rotation.x=Math.PI/2\nFinestrone1.specchio2=specchio2\n\nFinestrone2.PosX=PosX\nFinestrone2.PosY=PosY\nFinestrone2.DimX=DimX\n\n if(aperturaFin==0){\n specchio2.interact=function(){\n if(Finestrone2.position.x==PosX-((DimX/4)+0.025)){\n finestroneSound.play();\nfinestroneAnimation1(Finestrone2)} \n else {\n finestroneSound.play();\nfinestroneAnimation2(Finestrone2)}}}\n\n if(aperturaFin==1){\n specchio2.interact=function(){\n if(Finestrone2.position.x==PosX-(((DimX/4)+0.025)+(DimX*2))){\n finestroneSound.play();\n finestroneAnimation4(Finestrone2)} \n else {\n finestroneSound.play();\nfinestroneAnimation3(Finestrone2)}}}\n\n if(aperturaFin==2){\n specchio2.interact=function(){\n if(Finestrone2.position.x==PosX-((DimX/2)+0.25)){\n finestroneSound.play();\nfinestroneAnimation5(Finestrone2)} \n else {\n finestroneSound.play();\nfinestroneAnimation6(Finestrone2)}}}\n\n if(aperturaFin==3){\n specchio2.interact=function(){\n if(Finestrone2.position.x==PosX-(DimX+0.15)){\n finestroneSound.play();\nfinestroneAnimation8(Finestrone2)} \n else {\n finestroneSound.play();\nfinestroneAnimation7(Finestrone2)}}}\n return Finestrone1\n }", "function createNozzle(){\n let mtlLoader = new THREE.MTLLoader();\n mtlLoader.setPath('models/');\n mtlLoader.load('nozzle.mtl', mtls => {\n mtls.preload();\n let objLoader = new THREE.OBJLoader();\n objLoader.setMaterials(mtls);\n objLoader.setPath('models/');\n objLoader.load('nozzle.obj', obj => {\n obj.scale.set(20, 20, 20);\n obj.position.set(-0.001, -0.0905, 0);\n self.scene.add(obj);\n render();\n });\n });\n\n }", "createObjects() {\n //this.createCube();\n //this.createSphere();\n //this.createFloor();\n this.createLandscape();\n this.createWater();\n }", "function TorusKnotGeometry(id,scene,/**\n * Defines the radius of the torus knot\n */radius,/**\n * Defines the thickness of the torus knot tube\n */tube,/**\n * Defines the number of radial segments\n */radialSegments,/**\n * Defines the number of tubular segments\n */tubularSegments,/**\n * Defines the first number of windings\n */p,/**\n * Defines the second number of windings\n */q,canBeRegenerated,mesh,/**\n * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)\n */side){if(mesh===void 0){mesh=null;}if(side===void 0){side=BABYLON.Mesh.DEFAULTSIDE;}var _this=_super.call(this,id,scene,canBeRegenerated,mesh)||this;_this.radius=radius;_this.tube=tube;_this.radialSegments=radialSegments;_this.tubularSegments=tubularSegments;_this.p=p;_this.q=q;_this.side=side;return _this;}", "function createMeshes() {\r\n mesh_lantern1 = createLantern ();\r\n scene.add(mesh_lantern1);\r\n\r\n mesh_lantern2 = mesh_lantern1.clone();\r\n mesh_lantern2.translateX(15.0);\r\n scene.add(mesh_lantern2);\r\n\r\n mesh_lantern3 = mesh_lantern1.clone();\r\n mesh_lantern3.translateZ(-20.0);\r\n scene.add(mesh_lantern3);\r\n}", "function fieldGenerator()\r\n {\r\n // Generate the trapezoid base of the field.\r\n trapezoid = new THREE.Geometry();\r\n\r\n trapezoid.vertices.push(\r\n new THREE.Vector3(-178, -30, -313),\r\n new THREE.Vector3(178, -30, -313),\r\n new THREE.Vector3(178, -30, 313),\r\n new THREE.Vector3(-178, -30, 313),\r\n new THREE.Vector3(-198, -50, -333),\r\n new THREE.Vector3(198, -50, -333),\r\n new THREE.Vector3(198, -50, 333),\r\n new THREE.Vector3(-198, -50, 333)\r\n );\r\n\r\n trapezoid.faces.push(new THREE.Face3(0, 1, 2));\r\n trapezoid.faces.push(new THREE.Face3(0, 2, 3));\r\n trapezoid.faces.push(new THREE.Face3(4, 5, 6));\r\n trapezoid.faces.push(new THREE.Face3(4, 6, 7));\r\n trapezoid.faces.push(new THREE.Face3(0, 4, 3));\r\n trapezoid.faces.push(new THREE.Face3(3, 4, 7));\r\n trapezoid.faces.push(new THREE.Face3(3, 7, 2));\r\n trapezoid.faces.push(new THREE.Face3(2, 7, 6));\r\n trapezoid.faces.push(new THREE.Face3(2, 6, 1));\r\n trapezoid.faces.push(new THREE.Face3(1, 6, 5));\r\n trapezoid.faces.push(new THREE.Face3(1, 5, 0));\r\n trapezoid.faces.push(new THREE.Face3(0, 5, 4));\r\n\r\n trapezoid.faceVertexUvs[0] = [];\r\n for(var i = 0; i <= 10; i+=2)\r\n {\r\n trapezoid.faceVertexUvs[0].push([\r\n new THREE.Vector2(0, 1),\r\n new THREE.Vector2(0, 0),\r\n new THREE.Vector2(1, 1)\r\n ]);\r\n trapezoid.faceVertexUvs[0].push([\r\n new THREE.Vector2(1, 1),\r\n new THREE.Vector2(0, 0),\r\n new THREE.Vector2(1, 0)\r\n ]);\r\n }\r\n trapezoid.computeFaceNormals();\r\n \r\n // Add textures to the base.\r\n var soil = new THREE.MeshLambertMaterial({map: THREE.ImageUtils.loadTexture('source/soil.png')});\r\n rect = new THREE.Mesh(trapezoid, soil);\r\n rect.overdraw = true;\r\n \r\n // Add logos to the base.\r\n var espnLogo, ffaLogo, espnMat, ffaMat;\r\n espnLogo = THREE.ImageUtils.loadTexture( \"source/ESPNUK.png\" );\r\n espnLogo.wrapS = THREE.RepeatWrapping; \r\n espnLogo.wrapT = THREE.RepeatWrapping;\r\n \r\n ffaLogo = THREE.ImageUtils.loadTexture( \"source/FFALogo.png\" );\r\n ffaLogo.wrapS = THREE.RepeatWrapping; \r\n ffaLogo.wrapT = THREE.RepeatWrapping;\r\n\r\n espnMat = new THREE.MeshLambertMaterial({ map : espnLogo });\r\n espnMat.transparent = true;\r\n espnPlane = new THREE.Mesh(new THREE.PlaneGeometry(60, 15), espnMat);\r\n espnPlane.material.side = THREE.DoubleSide;\r\n espnPlane.position.x = -108;\r\n espnPlane.position.y = -40;\r\n espnPlane.position.z = 324;\r\n espnPlane.rotation.x = -Math.PI/4;\r\n \r\n ffaMat = new THREE.MeshLambertMaterial({ map : ffaLogo });\r\n ffaMat.transparent = true;\r\n ffaPlane = new THREE.Mesh(new THREE.PlaneGeometry(200, 20), ffaMat);\r\n ffaPlane.material.side = THREE.DoubleSide;\r\n ffaPlane.position.x = 38;\r\n ffaPlane.position.y = -40;\r\n ffaPlane.position.z = 324;\r\n ffaPlane.rotation.x = -Math.PI/4;\r\n\r\n // Load the obj model and its textures for the football field.\r\n var onProgress = function (xhr) {\r\n if ( xhr.lengthComputable ) {\r\n var percentComplete = xhr.loaded / xhr.total * 100;\r\n console.log(Math.round(percentComplete, 2) + '% downloaded');\r\n }\r\n };\r\n var onError = function (xhr) {\r\n };\r\n\r\n THREE.Loader.Handlers.add( /\\.dds$/i, new THREE.DDSLoader() );\r\n\r\n loader = new THREE.OBJMTLLoader();\r\n loader.load('source/field/nfl_football_field2.obj', 'source/field/nfl_football_field2.mtl', function(object) \r\n {\r\n object.rotation.y = Math.PI / 2;\r\n object.position.y = level;\r\n object.scale.set(70, 70, 70);\r\n \r\n object.traverse( function ( child ) {\r\n if ( child instanceof THREE.Mesh ) {\r\n child.receiveShadow = true;\r\n }\r\n } );\r\n \r\n // Add all models to the scene in one time.\r\n scene.add(object);\r\n scene.add(rect);\r\n scene.add(espnPlane);\r\n scene.add(ffaPlane);\r\n }, onProgress, onError);\r\n }", "createTetronimo(position, type) {\n\t\tif (type === TETRONIMO_TYPES.RANDOM) {\n\t\t\ttype = this._randomType();\n\t\t}\n\n\t\tconst origin = new Block(position);\n\t\tconst blocks = this._createOtherBlocksAround(position, type);\n\t\tblocks.push(origin);\n\n\t\treturn new Tetronimo({ origin: origin, blocks: blocks, type: type });\n\t}", "function TorusGeometry(id,scene,/**\n * Defines the diameter of the torus\n */diameter,/**\n * Defines the thickness of the torus (ie. internal diameter)\n */thickness,/**\n * Defines the tesselation factor to apply to the torus\n */tessellation,canBeRegenerated,mesh,/**\n * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)\n */side){if(mesh===void 0){mesh=null;}if(side===void 0){side=BABYLON.Mesh.DEFAULTSIDE;}var _this=_super.call(this,id,scene,canBeRegenerated,mesh)||this;_this.diameter=diameter;_this.thickness=thickness;_this.tessellation=tessellation;_this.side=side;return _this;}", "function loadModels() {\r\n\r\n const loader = new THREE.GLTFLoader();\r\n \r\n \r\n const onLoad = ( gltf, position ) => {\r\n \r\n model_tim = gltf.scene;\r\n model_tim.position.copy( position );\r\n //console.log(position)\r\n \r\n //model_tim_skeleton= new THREE.Skeleton(model_tim_bones);\r\n model_tim_skeleton= new THREE.SkeletonHelper(model_tim);\r\n model_tim_head_bone=model_tim_skeleton.bones[5];\r\n console.log(model_tim_head_bone);\r\n //console.log(model_tim_bones);\r\n animation_walk = gltf.animations[0];\r\n \r\n const mixer = new THREE.AnimationMixer( model_tim );\r\n mixers.push( mixer );\r\n \r\n action_walk = mixer.clipAction( animation_walk );\r\n // Uncomment you need to change the scale or position of the model \r\n //model_tim.scale.set(1,1,1);\r\n //model_tim.rotateY(Math.PI) ;\r\n\r\n scene.add( model_tim );\r\n \r\n //model_tim.geometry.computeBoundingBox();\r\n //var bb = model_tim.boundingBox;\r\n var bb = new THREE.Box3().setFromObject(model_tim);\r\n var object3DWidth = bb.max.x - bb.min.x;\r\n var object3DHeight = bb.max.y - bb.min.y;\r\n var object3DDepth = bb.max.z - bb.min.z;\r\n console.log(object3DWidth);\r\n console.log(object3DHeight);\r\n console.log(object3DDepth);\r\n // Uncomment if you want to change the initial camera position\r\n //camera.position.x = 0;\r\n //camera.position.y = 15;\r\n //camera.position.z = 200;\r\n \r\n \r\n };\r\n \r\n \r\n \r\n // the loader will report the loading progress to this function\r\n const onProgress = () => {console.log('Someone is here');};\r\n \r\n // the loader will send any error messages to this function, and we'll log\r\n // them to to console\r\n const onError = ( errorMessage ) => { console.log( errorMessage ); };\r\n \r\n // load the first model. Each model is loaded asynchronously,\r\n // so don't make any assumption about which one will finish loading first\r\n const tim_Position = new THREE.Vector3( 0,0,0 );\r\n loader.load('Timmy_sc_1_stay_in_place.glb', gltf => onLoad( gltf, tim_Position ), onProgress, onError );\r\n \r\n }", "function creaInfissiFinestra(PortdimX,PortdimY,PortPosX,PortPosY,PortPosZ){\nvar infissi = new THREE.Object3D();\n\nvar infisso1 = createMeshPortWindow(new THREE.BoxGeometry(0.1, 0.02, PortdimY), 'PortText.jpg');\ninfisso1.position.set(-(PortdimX+0.05),-0.05,0);\nvar infisso2 = createMeshPortWindow(new THREE.BoxGeometry(0.1, 0.02, PortdimY), 'PortText.jpg');\ninfisso2.position.set(0.05,-0.05,0);\n\nvar infisso3 = createMeshPortWindow(new THREE.BoxGeometry(0.1, 0.02, PortdimY), 'PortText.jpg');\ninfisso3.position.set(-(PortdimX+0.05),0.05,0);\nvar infisso4 = createMeshPortWindow(new THREE.BoxGeometry(0.1, 0.02, PortdimY), 'PortText.jpg');\ninfisso4.position.set(0.05,0.05,0);\n\nvar infisso5 = createMeshPortWindow(new THREE.BoxGeometry(PortdimX+0.2, 0.02, 0.1), 'PortText.jpg');\ninfisso5.position.set(-(PortdimX/2),0.05,(PortdimY/2)+0.05);\nvar infisso6 = createMeshPortWindow(new THREE.BoxGeometry(PortdimX+0.2, 0.02, 0.1), 'PortText.jpg');\ninfisso6.position.set(-(PortdimX/2),-0.05,(PortdimY/2)+0.05);\n\nvar infisso7 = createMeshPortWindow(new THREE.BoxGeometry(PortdimX+0.2, 0.02, 0.1),'PortText.jpg');\ninfisso7.position.set(-((PortdimX/2)),-0.05,-((PortdimY/2)+0.05));\n\nvar infisso8 = createMeshPortWindow(new THREE.BoxGeometry(PortdimX+0.2, 0.02, 0.1),'PortText.jpg');\ninfisso8.position.set(-((PortdimX/2)),0.05,-((PortdimY/2)+0.05));\n\ninfissi.add(infisso1)\ninfissi.add(infisso2)\ninfissi.add(infisso3)\ninfissi.add(infisso4)\ninfissi.add(infisso5)\ninfissi.add(infisso6)\ninfissi.add(infisso7)\ninfissi.add(infisso8)\n\ninfissi.position.set(PortPosX+(PortdimX/2),PortPosY,(PortdimY/2)+PortPosZ);\nreturn infissi;\n\n\n }", "function ConstructHitBoxes() {\n\t\tfunction CreateHitBox(w, h, d, x, y, z, rotx = 0.0, roty = 0.0, rotz = 0.0, area = \"\") {\n\t\t\tvar geo = new THREE.BoxGeometry(w, h, d);\n\t\t\tvar mat = new THREE.MeshBasicMaterial({ color: 0xFFFFFF });\n\t\t\tmat.transparent = true;\n\t\t\tmat.opacity = 0.0;\n\n\t\t\tvar cube = new THREE.Mesh(geo, mat);\n\t\t\tcube.name = \"hitbox\";\n\t\t\tcube[\"selected\"] = false;\n\t\t\tcube[\"hovering\"] = true;\n\t\t\tcube[\"area\"] = area;\n\t\t\tcube.frustumCulled = false;\n\t\t\tscene.add(cube);\n\n\n\t\t\tcube.rotation.x = rotx;\n\t\t\tcube.rotation.y = roty;\n\t\t\tcube.rotation.z = rotz;\n\n\t\t\tcube.position.x = x;\n\t\t\tcube.position.y = y;\n\t\t\tcube.position.z = z;\n\n\t\t}\n\n\t\tCreateHitBox(3.5, 3.2, 0.1, 0.01, 0.5, 1.2, 0.1, 0, 0.0, \"front\"); // front\n\t\tCreateHitBox(3.4, 2.6, 0.1, 0.2, 0.6, -0.17, 0.2, 0.0, 0.0, \"back\"); // back\n\t\tCreateHitBox(0.5, 2.5, 2.4, -1.90, 0.1, 0.4, 0, 0, 0.21, \"frills\"); // left\n\t\tCreateHitBox(0.5, 2.7, 2.4, 2.095, 0.80, 0.4, 0, 0, 0, \"frills\"); // right\n\t\tCreateHitBox(3.4, 1.0, 2.4, 0.2, -1.0, 0.4, 0.0, 0.0, 0.1, \"frills\"); // bottom\n\t}", "function makeBox(ctx)\n{\n // box\n // v6----- v5\n // /| /|\n // v1------v0|\n // | | | |\n // | |v7---|-|v4\n // |/ |/\n // v2------v3\n //\n // vertex coords array\n var vertices = new Float32Array(\n [ 1, 1, 1, -1, 1, 1, -1,-1, 1, 1,-1, 1, // v0-v1-v2-v3 front\n 1, 1, 1, 1,-1, 1, 1,-1,-1, 1, 1,-1, // v0-v3-v4-v5 right\n 1, 1, 1, 1, 1,-1, -1, 1,-1, -1, 1, 1, // v0-v5-v6-v1 top\n -1, 1, 1, -1, 1,-1, -1,-1,-1, -1,-1, 1, // v1-v6-v7-v2 left\n -1,-1,-1, 1,-1,-1, 1,-1, 1, -1,-1, 1, // v7-v4-v3-v2 bottom\n 1,-1,-1, -1,-1,-1, -1, 1,-1, 1, 1,-1 ] // v4-v7-v6-v5 back\n );\n\n // normal array\n var normals = new Float32Array(\n [ 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, // v0-v1-v2-v3 front\n 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, // v0-v3-v4-v5 right\n 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, // v0-v5-v6-v1 top\n -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, // v1-v6-v7-v2 left\n 0,-1, 0, 0,-1, 0, 0,-1, 0, 0,-1, 0, // v7-v4-v3-v2 bottom\n 0, 0,-1, 0, 0,-1, 0, 0,-1, 0, 0,-1 ] // v4-v7-v6-v5 back\n );\n\n\n // texCoord array\n var texCoords = new Float32Array(\n [ 1, 1, 0, 1, 0, 0, 1, 0, // v0-v1-v2-v3 front\n 0, 1, 0, 0, 1, 0, 1, 1, // v0-v3-v4-v5 right\n 1, 0, 1, 1, 0, 1, 0, 0, // v0-v5-v6-v1 top\n 1, 1, 0, 1, 0, 0, 1, 0, // v1-v6-v7-v2 left\n 0, 0, 1, 0, 1, 1, 0, 1, // v7-v4-v3-v2 bottom\n 0, 0, 1, 0, 1, 1, 0, 1 ] // v4-v7-v6-v5 back\n );\n\n // index array\n var indices = new Uint8Array(\n [ 0, 1, 2, 0, 2, 3, // front\n 4, 5, 6, 4, 6, 7, // right\n 8, 9,10, 8,10,11, // top\n 12,13,14, 12,14,15, // left\n 16,17,18, 16,18,19, // bottom\n 20,21,22, 20,22,23 ] // back\n );\n\n var retval = { };\n\n retval.normalObject = ctx.createBuffer();\n ctx.bindBuffer(ctx.ARRAY_BUFFER, retval.normalObject);\n ctx.bufferData(ctx.ARRAY_BUFFER, normals, ctx.STATIC_DRAW);\n\n retval.texCoordObject = ctx.createBuffer();\n ctx.bindBuffer(ctx.ARRAY_BUFFER, retval.texCoordObject);\n ctx.bufferData(ctx.ARRAY_BUFFER, texCoords, ctx.STATIC_DRAW);\n\n retval.vertexObject = ctx.createBuffer();\n ctx.bindBuffer(ctx.ARRAY_BUFFER, retval.vertexObject);\n ctx.bufferData(ctx.ARRAY_BUFFER, vertices, ctx.STATIC_DRAW);\n\n ctx.bindBuffer(ctx.ARRAY_BUFFER, null);\n\n retval.indexObject = ctx.createBuffer();\n ctx.bindBuffer(ctx.ELEMENT_ARRAY_BUFFER, retval.indexObject);\n ctx.bufferData(ctx.ELEMENT_ARRAY_BUFFER, indices, ctx.STATIC_DRAW);\n ctx.bindBuffer(ctx.ELEMENT_ARRAY_BUFFER, null);\n\n retval.numIndices = indices.length;\n retval.indexType = ctx.UNSIGNED_BYTE;\n return retval;\n}", "function createGroundShape(controlPts, idxPts, zmin, zmax, classId)\n{\n\t// first compute the center\n\tvar anchorPts = [];\n\tvar center = {x: 0, y: 0, z: (zmax+zmin)*0.5}; \n\tfor (var i = 0; i<idxPts; i++) {\n\t\tcenter.x += controlPts.vertices[i].x;\n\t\tcenter.y += controlPts.vertices[i].y;\n\t}\n\n\tcenter.x /= idxPts;\n\tcenter.y /= idxPts;\n\n\t// first offset the center\n\tfor (var i = 0 ;i<idxPts; i++) {\n\t\tanchorPts.push(new THREE.Vector2 (controlPts.vertices[i].x-center.x, controlPts.vertices[i].y-center.y));\n\t}\n\t// get the faces information\n\tvar geometry = new THREE.ShapeGeometry( new THREE.Shape( anchorPts ));\n\n\tvar geometry_top = geometry.clone();\n\tvar geometry_bottom = geometry.clone();\n\n\tvar geometry_total = new THREE.Geometry();\n\tgeometry_total = geometry_top.clone();\n\tgeometry_total.vertices = geometry_top.vertices.concat(geometry_bottom.vertices);\n\tgeometry_total.faces = geometry_top.faces.concat(geometry_bottom.faces);\n\n\n\t//vertices\n\tvar numV = geometry_top.vertices.length;\n\tfor (var i = 0; i < numV; i++) {\n\t\tgeometry_total.vertices[i].y = geometry_total.vertices[i].y;\n\t\tgeometry_total.vertices[i+numV].y = geometry_total.vertices[i+numV].y;\n\t\tgeometry_total.vertices[i].z = zmax-center.z\n\t\tgeometry_total.vertices[i+numV].z = zmin-center.z;\n\t}\n\n\t// faces\n\tvar numF = geometry_top.faces.length;\n\tfor (var i = 0; i < numF; i++) {\n\t\tgeometry_total.faces[i+numF].a += numV;\n\t\tgeometry_total.faces[i+numF].b += numV;\n\t\tgeometry_total.faces[i+numF].c += numV;\n\t}\n\t\n\t// faces bettwen two layers\n\tfor (var i = 0; i < numV-1; i++) {\n\t\tgeometry_total.faces.push(new THREE.Face3( i, i+1, i+numV));\n\t\tgeometry_total.faces.push(new THREE.Face3( i+1, i+1+numV, i+numV));\n\t}\n\tgeometry_total.faces.push(new THREE.Face3( 0, numV-1, numV));\n\tgeometry_total.faces.push(new THREE.Face3( numV-1, numV, 2*numV-1));\n\n\tvar mesh = new THREE.Mesh( geometry_total, new THREE.MeshBasicMaterial( { color: category[classId].colors, side: THREE.DoubleSide, \n\t\tireframe: 0, wireframeLinewidth: 2, transparent: true, opacity: category[classId].opacity}) ); \n\t\n\t// move to the centroid\n\tmesh.position.set(center.x, center.y, center.z);\n\n\treturn {mesh: mesh, center: center};\n}", "createScene() {\n\n this.heightMap = new NoiseMap();\n this.heightMaps = this.heightMap.maps;\n\n this.moistureMap = new NoiseMap();\n this.moistureMaps = this.moistureMap.maps;\n\n this.textureMap = new TextureMap();\n this.textureMaps = this.textureMap.maps;\n\n this.normalMap = new NormalMap();\n this.normalMaps = this.normalMap.maps;\n\n this.roughnessMap = new RoughnessMap();\n this.roughnessMaps = this.roughnessMap.maps;\n\n for (let i=0; i<6; i++) { //Create 6 materials, each with white color\n let material = new THREE.MeshStandardMaterial({\n color: new THREE.Color(0xFFFFFF)\n });\n this.materials[i] = material;\n }\n\n let geo = new THREE.BoxGeometry(1, 1, 1, 64, 64, 64); //Creating a box\n let radius = this.size;\n for (var i in geo.vertices) {\n \t\tvar vertex = geo.vertices[i];\n \t\tvertex.normalize().multiplyScalar(radius);\n \t}\n this.computeGeometry(geo); //Squeezing a box into a sphere\n\n this.ground = new THREE.Mesh(geo, this.materials); //Create ground mesh with squeezed box sphere and 6 materials\n this.view.add(this.ground);\n }", "constructor(params) {\n // times\n this.time = new THREE.Clock(true);\n this.timeNum = 3;\n this.timeScale = 2;\n\n this.scale = params.scale;\n\n // parameters\n this.sketch = params.sketch;\n this.size = params.size;\n this.dist = params.dist;\n this.iIndex = params.indexes.i;\n this.xIndex = params.indexes.x;\n this.yIndex = params.indexes.y;\n this.zIndex = params.indexes.z;\n this.shadow = params.shadow;\n this.geometry = params.geometry;\n this.material = params.material;\n this.others = params.others;\n this.position = new THREE.Vector3(params.position.x, params.position.y, params.position.z);\n\n this.initialize();\n }", "constructor(brain) {\n // All the physics stuff\n this.fx = 0;\n this.vx = 0;\n this.x = random(width);\n this.r = 8;\n this.y = height - this.r * 2;\n\n // This indicates how well it is doing\n this.score = 0;\n\n // How many sensors does each vehicle have?\n // How far can each vehicle see?\n // What's the angle in between sensors\n\n // Create an array of sensors\n this.sensors = [];\n const deltaAngle = PI / TOTALSENSORS;\n for (let angle = PI; angle <= TWO_PI; angle += deltaAngle) {\n this.sensors.push(new Sensor(angle, deltaAngle));\n }\n\n // If a brain is passed via constructor copy it\n if (brain) {\n this.brain = brain.copy();\n this.brain.mutate(0.1);\n // Otherwise make a new brain\n } else {\n // inputs are all the sensors plus position and velocity info\n let inputs = this.sensors.length + 2;\n this.brain = new NeuralNetwork(inputs, inputs, 1);\n }\n }", "function addRobot() {\n loader = new THREE.GLTFLoader();\n loader.load('models/GLTF/RobotExpressive.glb',\n function (gltf) {\n // Import robot and his animations and add them to the scene\n //adds shadow to the robot\n gltf.scene.traverse(function (robot) {\n if (robot instanceof THREE.Mesh) {\n robot.castShadow = true;\n }\n });\n robot = gltf.scene;\n animations = gltf.animations;\n scene.add(robot);\n // Set positions \n robot.position.y = 1.05;\n robot.position.z = 9;\n robot.scale.set(0.3, 0.3, 0.3);\n\n // Rotation\n robot.rotation.y = Math.PI;\n\n // Play Idle animation at first \n mixer = new THREE.AnimationMixer(robot);\n let clip = THREE.AnimationClip.findByName(animations, state.name);\n let action = mixer.clipAction(clip);\n action.play();\n\n })\n }", "function createPolygons() {\n\t// Get 3D coordinates\n\tlet [ground_coord_3D, sky_coord_3D] = computeCoordinates3D();\n\t// Get 2D coordinates for texture calcul\n\tlet [ground_coord_2D, sky_coord_2D] = computeCoordinates2D();\n\n\t// create a simple square shape. We duplicate the top left and bottom right\n\tlet buildingsGeometry = new THREE.BufferGeometry();\n\n\tlet vertices = fillVertices(ground_coord_3D, sky_coord_3D);\n\tlet uv = fillUV(ground_coord_2D, sky_coord_2D);\n\n\n\tbuildingsGeometry.setAttribute('position', new THREE.BufferAttribute(vertices, 3));\n\tbuildingsGeometry.setAttribute('uv', new THREE.BufferAttribute(uv, 2));\n\n\tlet buildingsTextureMaterial = new THREE.MeshBasicMaterial({ transparent: false, color: 0xFFFFFF, map: texture, side: THREE.FrontSide });\n\tlet buildingsColorMaterial = new THREE.MeshBasicMaterial({ transparent: false, color: 0x0, side: THREE.BackSide });\n\n\n\tbuildings = new THREE.Group();\n\tbuildings.add(new THREE.Mesh(buildingsGeometry, buildingsTextureMaterial));\n\tbuildings.add(new THREE.Mesh(buildingsGeometry, buildingsColorMaterial));\n\n\tscene.add(buildings);\n\n\tbuildings.visible = mode3D;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Controller for the MdChips component. Responsible for adding to and removing from the list of chips, marking chips as selected, and binding to the models of various input components.
function MdChipsCtrl ($scope, $mdConstant, $log, $element, $timeout) { /** @type {$timeout} **/ this.$timeout = $timeout; /** @type {Object} */ this.$mdConstant = $mdConstant; /** @type {angular.$scope} */ this.$scope = $scope; /** @type {angular.$scope} */ this.parent = $scope.$parent; /** @type {$log} */ this.$log = $log; /** @type {$element} */ this.$element = $element; /** @type {angular.NgModelController} */ this.ngModelCtrl = null; /** @type {angular.NgModelController} */ this.userInputNgModelCtrl = null; /** @type {Element} */ this.userInputElement = null; /** @type {Array.<Object>} */ this.items = []; /** @type {number} */ this.selectedChip = -1; /** @type {boolean} */ this.hasAutocomplete = false; /** * Hidden hint text for how to delete a chip. Used to give context to screen readers. * @type {string} */ this.deleteHint = 'Press delete to remove this chip.'; /** * Hidden label for the delete button. Used to give context to screen readers. * @type {string} */ this.deleteButtonLabel = 'Remove'; /** * Model used by the input element. * @type {string} */ this.chipBuffer = ''; /** * Whether to use the onAppend expression to transform the chip buffer * before appending it to the list. * @type {boolean} * * * @deprecated Will remove in 1.0. */ this.useOnAppend = false; /** * Whether to use the transformChip expression to transform the chip buffer * before appending it to the list. * @type {boolean} */ this.useTransformChip = false; /** * Whether to use the onAdd expression to notify of chip additions. * @type {boolean} */ this.useOnAdd = false; /** * Whether to use the onRemove expression to notify of chip removals. * @type {boolean} */ this.useOnRemove = false; /** * Whether to use the onSelect expression to notify the component's user * after selecting a chip from the list. * @type {boolean} */ this.useOnSelect = false; }
[ "function setCurrencyList(currency, defval) {\r\n var obj = {}\r\n for (var key in currency) {\r\n obj[currency[key]] = null\r\n }\r\n $('#ddcurrlist').material_chip({\r\n placeholder: \"Enter Currency Pair\",\r\n data: defval,\r\n autocompleteLimit: 5,\r\n autocompleteOptions: {\r\n data: obj,\r\n limit: 7,\r\n minLength: 1\r\n }\r\n });\r\n $('.chips').on('chip.add', function(e, chip) {\r\n socket.emit('subscribecurr', {\r\n \"currency\": chip.tag,\r\n \"user\": username\r\n })\r\n subscribeCurrency(chip.tag);\r\n });\r\n\r\n $('.chips').on('chip.delete', function(deleted, chip) {\r\n var tag = chip.tag.replace(\"/\", \"\");\r\n socket.emit('unsubscribecurr', {\r\n \"currency\": chip.tag,\r\n \"user\": username\r\n })\r\n $(\"#\" + tag + \"block\").remove();\r\n if ($('#ddcurrlist').material_chip(\"data\").length== 0) $(\"#norecord\").show()\r\n else $(\"#norecord\").hide() \r\n });\r\n}", "requestContentUpdate() {\n if (!this.renderer) {\n return;\n }\n\n const model = {\n index: this.index,\n item: this.item,\n focused: this.focused,\n selected: this.selected\n };\n\n this.renderer(this, this._comboBox, model);\n }", "function createChips() {\n chipXCenterOne = -0.5;\n chipYCenterOne = 0.5;\n\n chipXCenterFive = 0.5;\n chipYCenterFive = 0.5;\n\n chipXCenterTen = -0.5;\n chipYCenterTen = -0.5;\n\n chipXCenterTwoFive = 0.5;\n chipYCenterTwoFive = -0.5;\n\n // Generic Circle\n var p = vec2(0.0, 0.0);\n chipVertices = [p];\n var radius = 1;\n var increment = Math.PI / 36;\n\n for (var theta = 0.0; theta < Math.PI * 2 - increment; theta += increment) {\n if (theta == 0.0) {\n chipVertices.push(\n vec2(Math.cos(theta) * radius, Math.sin(theta) * radius)\n );\n }\n chipVertices.push(\n vec2(\n Math.cos(theta + increment) * radius,\n Math.sin(theta + increment) * radius\n )\n );\n }\n\n // Generic Rectangle for chips\n markerVertices = [\n vec2(-1.5, 0.25),\n vec2(-1.5, -0.25),\n vec2(0, 0.25),\n\n vec2(0, 0.25),\n vec2(0, -0.25),\n vec2(-1.5, -0.25),\n ];\n\n chipVertices.push(...markerVertices);\n\n // Make Bet Area from 2 rectangles and 1 part of a circle\n // Wide Area One\n betAreaWideVertices = [\n vec2(-0.15, 0.0),\n vec2(-0.15, 1.4),\n vec2(0.15, 0),\n\n vec2(0.15, 0),\n vec2(0.15, 1.4),\n vec2(-0.15, 1.4),\n ];\n chipVertices.push(...betAreaWideVertices);\n\n // Tall Area One\n betAreaTallVertices = [\n vec2(-0.1, 0.0),\n vec2(-0.1, 1.45),\n vec2(0.1, 0),\n\n vec2(0.1, 0),\n vec2(0.1, 1.45),\n vec2(-0.1, 1.45),\n ];\n\n chipVertices.push(...betAreaTallVertices);\n\n // Corner\n var k = vec2(0.0, 0.0);\n var cornerVerts = [k];\n var radius = 1;\n var increment = Math.PI / 36;\n\n for (var theta = 0.0; theta < Math.PI * 2 - increment; theta += increment) {\n if (theta == 0.0) {\n cornerVerts.push(\n vec2(Math.cos(theta) * radius, Math.sin(theta) * radius)\n );\n }\n cornerVerts.push(\n vec2(\n Math.cos(theta + increment) * radius,\n Math.sin(theta + increment) * radius\n )\n );\n }\n\n chipVertices.push(...cornerVerts);\n\n // Set Colors\n // 1 - white/blue\n chipOnePrimary = vec3(1.0, 1.0, 1.0);\n chipOneSecondary = vec3(20 / 255, 20 / 255, 175 / 255);\n\n // 5 - red/white\n chipFivePrimary = vec3(180 / 255, 10 / 255, 10 / 255);\n chipFiveSecondary = vec3(1.0, 1.0, 1.0);\n\n // 10 - blue/white\n chipTenPrimary = vec3(50 / 255, 50 / 255, 200 / 255);\n chipTenSecondary = vec3(1.0, 1.0, 1.0);\n\n // 25 - black/white\n chipTwoFivePrimary = vec3(0.0, 0.0, 0.0);\n chipTwoFiveSecondary = vec3(1.0, 1.0, 1.0);\n}", "function FieldInputController(typesService) {\n\n var self = this;\n\n /**\n * Init the controller with sane defaults\n */\n self.$onInit = function() {\n self.id = Date.now();\n self.selections = self.createSelections();\n self.value = self.value || self.selection[0];\n self.showMenu = false;\n };\n\n /**\n * Build a map of arrays.\n * The array contain available properties and are mapped by model.\n */\n self.createSelections = function() {\n var selections = {};\n for (var i = 0; i < self.types.length; i++) {\n selections[self.types[i]] = [];\n for (var j = 0; j < typesService.properties[self.types[i]].length; j++) {\n selections[self.types[i]].push({\n type: self.types[i],\n property: typesService.properties[self.types[i]][j]\n });\n }\n }\n return selections;\n };\n\n /**\n * Return whether or not a field is selected.\n */\n self.isSelected = function(field) {\n return (self.value.type == field.type && self.value.property == field.property);\n };\n\n /**\n * Hide the drop down menu.\n */\n self.hide = function() {\n self.showMenu = false;\n };\n\n /**\n * Toggle the drop down menu.\n */\n self.toggle = function() {\n self.showMenu = !self.showMenu;\n };\n\n /**\n * Trigger an onDelete event.\n */\n self.delete = function() {\n self.onDelete({field: self.value});\n };\n\n /**\n * Update selected field and trigger onChange.\n */\n self.change = function(field) {\n self.value = field;\n self.onChange({field: self.value});\n };\n}", "function MapSelectionController($scope, $attrs, $log, SelectionSetService) {\n\n // allow only a single item to be selected at a time\n $scope.singleSelection = true;\n\n /**\n * Clear the selection set. If an Id is provided, remove the specific\n * document by Id. Otherwise, clear all values.\n */\n $scope.clearSelection = function(Id) {\n try {\n SelectionSetService.remove(Id);\n SelectionSetService.clear();\n } catch (err) {\n $log.info(err.message);\n }\n };\n\n /**\n * Initialize the controller.\n */\n $scope.init = function() {\n // apply configured attributes\n for (var key in $attrs) {\n if ($scope.hasOwnProperty(key)) {\n $scope[key] = $attrs[key];\n }\n }\n };\n\n /**\n * Add the selected document to the selection set.\n * @param Id Document identifier\n */\n $scope.select = function(Id) {\n if ($scope.singleSelection) {\n SelectionSetService.clearSilent();\n }\n SelectionSetService.add(Id,null);\n };\n\n // initialize the controller\n $scope.init();\n\n}", "function createSelectController()\r\n{\r\n\t\r\n\t\r\n\treturn new ol.interaction.Select({\r\n\tcondition: ol.events.condition.click,\r\n\t});\t\t\t\r\n}", "function createChip(cell) {\n newCell = document.createElement('div')\n newCell.classList = 'chip'\n cell.setAttribute(\"data-player\", `${currentPlayer}`);\n newCell.style.backgroundColor = chipColour();\n cell.appendChild(newCell);\n cell.setAttribute(\"data-clicked\", true);\n}", "function memberPickerController($scope, dialogService, entityResource, $log, iconHelper, angularHelper){\n\n function trim(str, chr) {\n var rgxtrim = (!chr) ? new RegExp('^\\\\s+|\\\\s+$', 'g') : new RegExp('^' + chr + '+|' + chr + '+$', 'g');\n return str.replace(rgxtrim, '');\n }\n\n $scope.renderModel = [];\n\n var dialogOptions = {\n multiPicker: false,\n entityType: \"Member\",\n section: \"member\",\n treeAlias: \"member\",\n filter: function(i) {\n return i.metaData.isContainer == true;\n },\n filterCssClass: \"not-allowed\",\n callback: function(data) {\n if (angular.isArray(data)) {\n _.each(data, function (item, i) {\n $scope.add(item);\n });\n } else {\n $scope.clear();\n $scope.add(data);\n }\n angularHelper.getCurrentForm($scope).$setDirty();\n }\n };\n\n //since most of the pre-value config's are used in the dialog options (i.e. maxNumber, minNumber, etc...) we'll merge the \n // pre-value config on to the dialog options\n if ($scope.model.config) {\n angular.extend(dialogOptions, $scope.model.config);\n }\n \n $scope.openMemberPicker =function() {\n var d = dialogService.memberPicker(dialogOptions);\n };\n\n\n $scope.remove =function(index){\n $scope.renderModel.splice(index, 1);\n };\n\n $scope.add = function (item) {\n var currIds = _.map($scope.renderModel, function (i) {\n return i.id;\n });\n\n if (currIds.indexOf(item.id) < 0) {\n item.icon = iconHelper.convertFromLegacyIcon(item.icon);\n $scope.renderModel.push({name: item.name, id: item.id, icon: item.icon});\t\t\t\t\n }\t\n };\n\n $scope.clear = function() {\n $scope.renderModel = [];\n };\n\t\n var unsubscribe = $scope.$on(\"formSubmitting\", function (ev, args) {\n var currIds = _.map($scope.renderModel, function (i) {\n return i.id;\n });\n $scope.model.value = trim(currIds.join(), \",\");\n });\n\n //when the scope is destroyed we need to unsubscribe\n $scope.$on('$destroy', function () {\n unsubscribe();\n });\n\n //load member data\n var modelIds = $scope.model.value ? $scope.model.value.split(',') : [];\n entityResource.getByIds(modelIds, \"Member\").then(function (data) {\n _.each(data, function (item, i) {\n item.icon = iconHelper.convertFromLegacyIcon(item.icon);\n $scope.renderModel.push({ name: item.name, id: item.id, icon: item.icon });\n });\n });\n}", "function CharacterAbilityDirectiveController() {}", "function renderWishListSelector() {\n //getWishListSelectorObjects returns array ready to be added to selectWidget\n var selectorObj = cCProductLists.getWishListSelectorObjects();\n\n removeWishListSelector();\n\n wishListSelectorController = Alloy.createController('components/selectWidget', {\n valueField : 'wishListId',\n textField : 'wishListName',\n values : selectorObj,\n messageWhenSelection : '',\n messageWhenNoSelection : _L('Select Wish List'),\n selectListTitleStyle : {\n backgroundColor : Alloy.Styles.color.background.white,\n font : Alloy.Styles.tabFont,\n color : Alloy.Styles.accentColor,\n disabledColor : Alloy.Styles.color.text.light,\n width : Ti.UI.FILL,\n height : Ti.UI.FILL,\n disabledBackgroundColor : Alloy.Styles.color.background.light,\n textAlign : Ti.UI.TEXT_ALIGNMENT_CENTER,\n accessibilityValue : 'wish_list_selector'\n },\n selectListStyle : {\n width : 320,\n left : 20,\n height : 40,\n top : 5,\n bottom : 5,\n font : Alloy.Styles.textFieldFont,\n selectedFont : Alloy.Styles.textFieldFont,\n unselectedFont : Alloy.Styles.textFieldFont,\n color : Alloy.Styles.color.text.darkest,\n selectedOptionColor : Alloy.Styles.color.text.darkest,\n disabledColor : Alloy.Styles.color.text.light,\n backgroundColor : Alloy.Styles.color.background.white,\n selectedOptionBackgroundColor : Alloy.Styles.color.background.light,\n disabledBackgroundColor : Alloy.Styles.color.background.light,\n borderColor : Alloy.Styles.accentColor\n },\n needsCallbackAfterClick : true,\n });\n\n $.listenTo(wishListSelectorController, 'itemSelected', function(event) {\n if (event.item) {\n selectedWishListId = event.item.wishListId;\n loadInitSelectedWishList(selectedWishListId);\n }\n });\n $.listenTo(wishListSelectorController, 'dropdownSelected', function() {\n wishListSelectorController.continueAfterClick();\n });\n\n wishListSelectorController.updateItems(selectorObj);\n wishListSelectorController.setEnabled(true);\n $.wish_list_selector_container.add(wishListSelectorController.getView());\n $.wish_list_selector_container.show();\n //reposition email_wish_list_button if there a select widget\n $.email_wish_list_button.setRight(20);\n}", "function UserSheetController($mdBottomSheet) {\n this.user = selectedUser;\n this.items = [\n { name: 'Phone' , icon: 'phone' , icon_url: 'assets/svg/phone.svg' },\n { name: 'Twitter' , icon: 'twitter' , icon_url: 'assets/svg/twitter.svg' },\n { name: 'Google+' , icon: 'google_plus' , icon_url: 'assets/svg/google_plus.svg'},\n { name: 'Hangout' , icon: 'hangouts' , icon_url: 'assets/svg/hangouts.svg'}\n ];\n\n this.performAction = function(action) {\n $mdBottomSheet.hide();\n }\n }", "function add_and_refresh(sel) {\n return chosen_issues.add_and_refresh(sel);\n}", "sendChatsToList() {\n if (!this._chats)\n return;\n\n this._componenets.chatsList.setChats(this._chats)\n }", "function bindClassCtrl ( itemID ) {\n $('.floor').find('.active').removeClass('active');\n $(itemID).addClass('active');\n }", "handleChipDelete(item) {\n const tags = [...this.state.tags];\n const index = tags.indexOf(item);\n tags.splice(index, 1);\n this.setState({ tags: tags });\n }", "function coveragesController() {\n\n }", "function MakePropertySelectComponent({ luiIcon, showSelectionDialog}) {\r\n return {\r\n template:\r\n `\r\n <div class=\"pp-component\" ng-if=\"visible\">\r\n <div class=\"label\" ng-if=\"label\" ng-class=\"{ \\'disabled\\': readOnly }\">\r\n {{label}}\r\n </div>\r\n <div class=\"lui-input-group\" ng-if=\"!loading\">\r\n <input class=\"lui-input-group__item lui-input-group__input lui-input\" ng-model=\"t.value\" ng-change=\"onDataChange()\"/>\r\n <button class=\"lui-input-group__item lui-input-group__button lui-button\" qva-activate=\"showSelectionDialog()\">\r\n <span class=\"lui-button__icon lui-icon ${luiIcon}\"></span>\r\n </button>\r\n </div>\r\n <div class=\"pp-loading-container\" ng-if=\"loading\">\r\n <div class=\"pp-loader qv-loader\"></div>\r\n </div>\r\n <div ng-if=\"errorMessage\" class=\"pp-invalid error\">{{errorMessage}}</div>\r\n </div>\r\n `,\r\n controller:\r\n [\"$scope\", function(c){\r\n function initOptions() {\r\n c.loading = true;\r\n c.errorMessage = \"\";\r\n c.label = c.definition.label;\r\n c.t = {\r\n value: getRefValue(c.data, c.definition.ref)\r\n }\r\n c.visible = true;\r\n c.loading = false;\r\n }\r\n\r\n c.showSelectionDialog = showSelectionDialog && showSelectionDialog.bind(c);\r\n\r\n c.onDataChange = function(additionalData) {\r\n setRefValue(c.data, c.definition.ref, c.t.value);\r\n \"function\" == typeof c.definition.change && c.definition.change(c.data, c.args.handler, additionalData);\r\n c.$emit(\"saveProperties\");\r\n };\r\n\r\n // c.$on(\"datachanged\", function () {\r\n // initOptions();\r\n // });\r\n\r\n initOptions();\r\n }]\r\n };\r\n}", "forceRenderList() {\n if (this.iconListComp) {\n this.iconListComp.select(this.selected);\n }\n }", "function SingleCoffeeController($stateParams,$state,CoffeeFactory,$http){\n var vm = this\n vm.currentUser = {}\n //move the below to factory or service layer\n //$http.get('/api/coffees/'+$stateParams.id)\n\n CoffeeFactory.show($stateParams.id)\n .success(function(coffee){\n vm.coffee = coffee\n //console.log(vm.coffee);\n vm.selected = true;\n })\n\n vm.destroyCoffee = function(coffee){\n CoffeeFactory.destroy(vm.coffee._id)\n .success(function(data){\n $state.go('coffees')\n })\n }\n\n vm.updateCoffee = function(){\n CoffeeFactory.update(vm.coffee)\n .success(function(data){\n vm.selected = true;\n $state.go('coffee')\n })\n }\n\n vm.addCoffee = function(currentUser) {\n //console.log(\"lets add coffee\");\n //console.log(currentUser);\n if(currentUser){\n $http.post('api/users/' + currentUser._id + '/coffees/' + vm.coffee._id)\n .success(function(data) {\n $state.go('coffees')\n // console.log(data)\n // vm.currentUser.coffees.push(data.coffee)\n })}\n else {alert(\"Please login to buy this product\")}\n\n\n }\n\n // function EditCoffeeController($stateParams,$state,CoffeeFactory, $rootScope) {\n // var vm = this\n // if($rootScope.currentUser.access!=0 || $rootScope.currentUser.access!=1) {\n // $state.go('home')\n // }\n // }\n}", "_updateItems(newItems = []) {\n const oldItems = this._cuttingItems.filter((i) => !newItems.includes(i))\n this._items = newItems\n\n this._eventEmitter.emit(\n 'textae-event.clip-board.change',\n this._cuttingItems,\n oldItems\n )\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
hide the user list frame, and clear some related stuffs
function hideUserFrame(){ cachedName = ""; fullCachedName = ""; listSize = 0; mentioningUser = false; if(isUserFrameShown){ userList.remove(); isUserFrameShown = false; } }
[ "function hideUI() {\n document.getElementById(\"options\").classList.add(\"hidden\");\n document.getElementById(\"fullelement\").classList.add(\"hidden\");\n document.getElementById(\"memorywindow\").classList.add(\"hidden\");\n}", "function hideWatchlistTable() {\n $(\"#watch-table-header\").hide();\n $(\"#watchlist-caption\").hide();\n }", "function clearAndHideForm() {\n clearForm();\n hideForm();\n}", "function participants_view_hide() {\n\tDOM(\"PARTICIPANTS_CLOSE\").style.backgroundColor = \"rgba(0,0,0,.2)\";\n\tsetTimeout(function() {\n\t\tDOM(\"PARTICIPANTS_CLOSE\").style.backgroundColor = \"transparent\";\n\t\tparticipants_view_visible = false;\n\t\tDOM(\"PARTICIPANTS_VIEW\").style.top = \"-100%\";\n\t\tsetTimeout(function() {\n\t\t\tDOM(\"PARTICIPANTS_VIEW\").style.display = \"none\";\n\t\t}, 500);\n\t}, 50);\n}", "function openClose__UserTool() {\n $('.list__Tool-User').toggleClass('display__block');\n}", "function signUp() {\n $('#main-header').text(\"B-Day List\");\n $('#login-container').hide();\n $('#logout-btn').removeClass('hide');\n $('#add-btn').removeClass('hide');\n }", "function removeFrom() {\n form.style.display = 'none';\n }", "function hide() {\n // First things first: we don't show it anymore.\n scope.chatIsOpen = false;\n chat.remove();\n }", "function hide() {\n if (!settings.shown) return;\n win.hide();\n settings.shown = false;\n }", "function showUserPanel() {\n\tlcSendValueAndCallbackHtmlAfterErrorCheckPreserveMessage(\"/user/index\",\n\t\t\t\"#userDiv\", \"#userDiv\", null);\n}", "function closeUpdateUserInfoMenu() {\n console.log(\"Is closing\");\n\n // Remove the update backdrop and update menu from the view\n $(\"div\").remove('#update-user-info-backdrop');\n $(\"div\").remove('#update-user-info-menu');\n}", "function close_edit_profile() {\n $('#profile_edit').hide();\n $('#btn_image_input').hide();\n $('#profile_info').show();\n}", "function toggle_users() {\n $(\"#users\").toggle();\n}", "function hideModule() {\n\t\t// Setting common.naclModule.style.display = \"None\" doesn't work; the\n\t\t// module will no longer be able to receive postMessages.\n\t\tcommon.naclModule.style.height = '0';\n\t}", "function _hideHello() {\n Main.uiGroup.remove_actor(text);\n text = null;\n}", "function showOtherUser(){\n removeFollowList();\n removeSearchArea();\n var userId = this.dataset.user; // get the user of the clicked name or image\n showedUser = userId;\n removeWritenFields();\n removeErrorSuccesFields();\n document.getElementById(\"profileSection\").style.display = \"block\";\n document.getElementById(\"messagesSection\").style.display = \"none\";\n hideAllProfileSection();\n document.getElementById(\"showProfile\").style.display = \"block\";\n\n getOtherProfile(userId);\n}", "hide() {\n\t\tthis.element.style.visibility = 'hidden';\n\t}", "function alterCalculationsScreen(){\n\t$(\"#youHaveNoProjects\").hide();\n\t$(\"#youHaveSomeProjects\").hide();\n\t$(\"#youHaveUntimelyProjects\").show();\n}", "function HideAuth(){\n\t\n\tif ($j(\"#mykmx_login\"))\n\t\t$j(\"#mykmx_login\").toggleClass(\"hide\");\n\t\n\tif ($j(\"#myCarMax_login\"))\n\t\t$j(\"#myCarMax_login\").css(\"display\", \"block\");\n\t\n\tif ($j(\"#myCarMax_close\"))\n\t\t$j(\"#myCarMax_close\").css(\"display\", \"none\");\n\t\n\tif ($j(\"#myCarMax_reg\"))\n\t\t$j(\"#myCarMax_reg\").attr(\"class\", \"last\");\n}", "function hideInviteMemberSection() {\n var element = document.getElementById('inviteMemberSection');\n jQuery(document).ready(function() {\n\tjQuery(element).hide(300);\n });\n setElementBackgroundColor('#inviteMemberTextField', '#ffffff');\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
sets value of optimalCrops array Adds up values inside game.discrete.optimalCrops, which is equal to the maximum possible score
function calculateMaxScore () { for (var i=0; i <= game.maxturn-1; i++) { game.discrete.maxScore += game.discrete.optimalCrops[i] } return game.discrete.maxScore; }
[ "updateExhaustedVotes() {\n const votesSum = this.count[this.round].reduce((a, b) => a + b);\n const exhausted = (this.p * this.numBallots) - votesSum;\n\n this.exhausted[this.round] = exhausted;\n }", "set score(newScore) {\r\n score = newScore;\r\n _scoreChanged();\r\n }", "function assignOptimalCombination(cities, i, j) {\n\n for (var k = 0; k < cities[i][j].optimal_combination.length; k++) {\n var item = cities[i][j - 4 + k];\n\n // if it is equal to itself's quality then it means that the item is not sold (indices start at 0\n // whereas qualities start at 1, look at \"findOptimalCombination()\" function for more info)\n if (cities[i][j].optimal_combination[k] == item.quality) {\n item.highestProfitBM_Quality = NEGATIVE_VALUE_LARGE;\n item.highestProfitBM_Price = NEGATIVE_VALUE_LARGE;\n item.highestProfitBM_Age = POSITIVE_VALUE_LARGE;\n item.profit = NEGATIVE_VALUE_LARGE;\n item.BM_order_difference = NEGATIVE_VALUE_LARGE;\n item.BM_order_difference_age = POSITIVE_VALUE_LARGE;\n item.percentileProfit = NEGATIVE_VALUE_LARGE;\n } else {\n item.highestProfitBM_Quality = cities[i][j].optimal_combination[k] + 1; // indices start at 0 but qualities at 1, so need to add 1\n item.highestProfitBM_Price = cities[i][j - 5 + item.highestProfitBM_Quality].bmPrice; // indices start at 0 but qualities at 1, so need to subtract 1\n item.highestProfitBM_Age = cities[i][j - 5 + item.highestProfitBM_Quality].bm_age;\n item.profit = Math.round(item.profits_array[item.highestProfitBM_Quality - 1]);\n item.BM_order_difference = cities[0][j - 5 + item.highestProfitBM_Quality].sell_price_min - cities[0][j - 5 + item.highestProfitBM_Quality].buy_price_max;\n item.BM_order_difference_age = getAge(cities[0][j - 5 + item.highestProfitBM_Quality].sell_price_min_date);\n item.percentileProfit = Math.round(1000 * (item.profit / item.cityPrice)) / 10;\n }\n\n }\n\n}", "function setScoreLimit(minlimit,maximum)\n{\n\tvar tmp = new Array();\n\ttmp = maximum.split(\",\");\n\tmaxlimit = 0;\n\tfor(var i=0;i<tmp.length;i++)\n\t{\n\t\tif(parseInt(tmp[i]))\n\t\t{\n\t\t\tmaxlimit +=parseInt(tmp[i]);\n\t\t}\n\t}\n\tSetValue( \"cmi.score.min\", minlimit);\n\tSetValue( \"cmi.score.max\", maxlimit);\n}", "function limitValues() {\n var i, j, value, valueInst, valueDescr, skillsets,\n skillKey, skillValue, listResources = Variable.findByName(gm, 'resources');\n //actions\n valueDescr = Variable.findByName(gm, 'actions')\n valueInst = valueDescr.getInstance(self);\n if (valueInst.getValue() > valueDescr.getMaxValue())\n valueInst.setValue(valueDescr.getMaxValue());\n if (valueInst.getValue() < valueDescr.getMinValue())\n valueInst.setValue(valueDescr.getMinValue());\n //teamMotivation\n valueDescr = Variable.findByName(gm, 'teamMotivation')\n valueInst = valueDescr.getInstance(self);\n if (valueInst.getValue() > valueDescr.getMaxValue())\n valueInst.setValue(valueDescr.getMaxValue());\n if (valueInst.getValue() < valueDescr.getMinValue())\n valueInst.setValue(valueDescr.getMinValue());\n //clientsSatisfaction\n valueDescr = Variable.findByName(gm, 'clientsSatisfaction')\n valueInst = valueDescr.getInstance(self);\n if (valueInst.getValue() > valueDescr.getMaxValue())\n valueInst.setValue(valueDescr.getMaxValue());\n if (valueInst.getValue() < valueDescr.getMinValue())\n valueInst.setValue(valueDescr.getMinValue());\n //ressources\n for (i = 0; i < listResources.items.size(); i++) {\n valueDescr = listResources.items.get(i);\n valueInst = valueDescr.getInstance(self);\n //moral\n value = parseInt(valueInst.getMoral());\n if (value > 100)\n valueInst.setMoral(100);\n if (value < 0)\n valueInst.setMoral(0);\n //moral\n value = parseInt(valueInst.getConfidence());\n if (value > 100)\n valueInst.setConfidence(100);\n if (value < 0)\n valueInst.setConfidence(0);\n //frankness\n value = parseInt(valueInst.getProperty('frankness'));\n if (value > 100)\n valueInst.setProperty('frankness', 100);\n if (value < 0)\n valueInst.setProperty('frankness', 0);\n //lastWorkQuality\n value = parseInt(valueInst.getProperty('lastWorkQuality'));\n if (value > 100)\n valueInst.setProperty('lastWorkQuality', 100);\n if (value < 0)\n valueInst.setProperty('lastWorkQuality', 0);\n //skillset\n skillsets = valueInst.getSkillsets();\n for (j = 0; j < skillsets.size(); j++) {\n skillKey = skillsets.keySet().toArray()[j];\n skillValue = parseInt(skillsets.get(skillKey));\n if (skillValue > 100)\n valueInst.setSkillset(skillKey, 100);\n if (skillValue < 0)\n valueInst.setSkillset(skillKey, 0);\n }\n }\n}", "evaluate(){\n let fastest = lifespan;\n for(let i = 0; i < this.popsize; i++){\n this.rockets[i].calcFitness();\n if(this.rockets[i].framesToFinish < fastest){\n fastest = this.rockets[i].framesToFinish\n }\n console.log(fastest)\n fastestRocketGen = fastest;\n if(fastestRocketGen < fastestRocketAll){\n fastestRocketAll = fastestRocketGen\n }\n }\n for(let i = 0; i < this.popsize;i++){\n for(let j = 0; j < this.popsize - 1;j++){\n if(this.rockets[j].fitness > this.rockets[j + 1].fitness){\n let temp = this.rockets[j];\n this.rockets[j] = this.rockets[j + 1];\n this.rockets[j + 1] = temp;\n }\n }\n }\n }", "function greedyStrategy(items, capacity) {\n let changed = false;\n const possibleItems = items;\n let weight = 0;\n const inventory = {\n selectedItems: [],\n totalCost: 0,\n totalValue: 0, \n };\n\n console.log(\"Capacity is: \", capacity);\n\n // sort the array by value/size ratio score\n possibleItems.sort(function(a, b) {\n return parseFloat(b.score) - parseFloat(a.score);\n });\n\n for(let i = 0; weight <= capacity && i < possibleItems.length; i++) {\n weight += possibleItems[i].size;\n if(weight <= capacity){\n inventory.selectedItems.push(possibleItems[i].index);\n inventory.totalCost = weight;\n inventory.totalValue += possibleItems[i].value;\n } else{\n weight -= possibleItems[i].size;\n }\n }\n\n console.log(\"\\nInventory to GREED: \\nItems to select: \", inventory.selectedItems, \"\\nTotal cost: \", inventory.totalCost, \"\\nTotal value: \", inventory.totalValue)\n\n return inventory;\n}", "function applyCropping() {\n\t// Setup options for this rack.\n\tvar options = {\n\t\t'scene-name': nodecg.bundleConfig.obsScenes.gameLayout,\n\t\t'item': cameraCaptureKey[capture],\n\t\t'crop': cropCache[capture]\n\t};\n\n\t// Send settings to OBS.\n\tobs.send('SetSceneItemProperties', options).catch((err) => {\n\t\tnodecg.log.warn(`Cannot change OBS source settings [${options['scene-name']}: ${options.item}]: ${err.error}`);\n\t});\n}", "function updateScore(cardArr) {\n var aces = 0,\n sum = 0;\n \n sum = cardArr.reduce(function(score, card) {\n if (!card.back) score += card.value;\n if (card.value == 11) aces += 1;\n return score;\n }, 0);\n\n for (var i = 0; i < aces; i += 1) {\n if (sum > 21) sum -= 10;\n }\n\n console.log('[ jack ] updated score: ' + sum );\n return sum;\n}", "minimax(newBoard, player) {\n let unvisitedCells = newBoard.unvisitedCells();\n\n if (this.checkWinner(newBoard, this.humanPlayer.identifier)) {\n return { score: -10 };\n } else if (this.checkWinner(newBoard, this.computerPlayer.identifier)) {\n return { score: 10 };\n } else if (unvisitedCells.length === 0) {\n return { score: 0 };\n }\n\n let moves = [];\n for (let i = 0; i < unvisitedCells.length; i++) {\n let move = {};\n move.index = newBoard.board[unvisitedCells[i]];\n newBoard.board[unvisitedCells[i]] = player;\n\n if (player === this.computerPlayer.identifier) {\n let result = this.minimax(newBoard, this.humanPlayer.identifier);\n move.score = result.score;\n } else {\n let result = this.minimax(newBoard, this.computerPlayer.identifier);\n move.score = result.score;\n }\n\n newBoard.board[unvisitedCells[i]] = move.index;\n\n moves.push(move);\n }\n\n let bestMove;\n if (player === this.computerPlayer.identifier) {\n let bestScore = -Infinity;\n for (let i = 0; i < moves.length; i++) {\n if (moves[i].score > bestScore) {\n bestScore = moves[i].score;\n bestMove = i;\n }\n }\n } else {\n let bestScore = Infinity;\n for (let i = 0; i < moves.length; i++) {\n if (moves[i].score < bestScore) {\n bestScore = moves[i].score;\n bestMove = i;\n }\n }\n }\n\n return moves[bestMove];\n }", "setScore() {\n this.#gameScore += this.#rules[this.#gameLevel - 1].score\n document.dispatchEvent(this.#gameScoreEvent)\n }", "set score(rawScore) {\n this._score.raw = rawScore;\n setValue(`cmi.objectives.${this.index}.score.raw`, rawScore);\n }", "function maximumScore(tileHand) {\n\tlet x = 0;\n\t\n\tfor (let i = 0; i < tileHand.length; i++) {\n\t\tx += tileHand[i].score;\n\t}\n\t\n\treturn x;\n}", "function calcHdcpDiff(gross, crsHcp, par) {\r\n\r\n//========================================================================================================\r\n\r\n var whichNine = 0,\r\n i = 0,\r\n j = 0,\r\n maxScore = 0,\r\n scores = {\r\n grossScore: [],\r\n adjGrossScore: []\r\n };\r\n\r\n scores.grossScore = gross;\r\n\r\n for (i = 18; i < 21; i += 1) {\r\n scores.grossScore[i] = 0;\r\n scores.adjGrossScore[i] = 0;\r\n }\r\n\r\n\r\n//========================================================================================================\r\n// Calculate hole max based on cours handicap. Low hcp max will be calculated by hole based on par.\r\n//========================================================================================================\r\n if (crsHcp >= 40) {\r\n maxScore = 10;\r\n } else if (crsHcp >= 30) {\r\n maxScore = 9;\r\n } else if (crsHcp >= 20) {\r\n maxScore = 8;\r\n } else if (crsHcp >= 10) {\r\n maxScore = 7;\r\n }\r\n\r\n\r\n//========================================================================================================\r\n// Calculate values for Front Nine, then for Back Nine.\r\n//========================================================================================================\r\n\r\n for (whichNine = 0; whichNine < 2; whichNine += 1) { /* process each nine in a separate pass */\r\n j = whichNine * 9;\r\n\r\n//========================================================================================================\r\n// Calculate adjusted scores for each hole on the current \"Nine\".\r\n//========================================================================================================\r\n\r\n for (i = 0; i < 9; i += 1) {\r\n if (crsHcp < 10) {\r\n maxScore = par[i] + 2; /* calculate low handicap max score */\r\n }\r\n scores.adjGrossScore[i + j] = Math.min(scores.grossScore[i + j], maxScore);\r\n\r\n//========================================================================================================\r\n// Calculate total gross and adj gross scores for current \"Nine\" [18]/[19] and overall round [20].\r\n//========================================================================================================\r\n\r\n scores.grossScore[18 + whichNine] += scores.grossScore[i + j];\r\n scores.adjGrossScore[18 + whichNine] += scores.adjGrossScore[i + j];\r\n scores.grossScore[20] += scores.grossScore[i + j];\r\n scores.adjGrossScore[20] += scores.adjGrossScore[i + j];\r\n }\r\n }\r\n\r\n return (scores);\r\n }", "process_scores(plane, score, hiscore) {\r\n for (var i = 0; i < this.walls.length; i++) {\r\n var temp_wall = this.walls[i];\r\n if (plane.check_wall_passed(temp_wall) && !temp_wall.scored) {\r\n score.increase();\r\n temp_wall.scored = true; // do not score this wall again!\r\n }\r\n }\r\n \r\n // see if the hiscore was broken\r\n if (score.value > hiscore.value) {\r\n hiscore.value = score.value;\r\n }\r\n }", "function maxMove(game){\n return possMoves.reduce(function(maxSoFar, current){\n return evalMove(game, current) > evalMove(game, maxSoFar) ? current : maxSoFar;\n });\n }", "verifyValueMax() {\n this.discount.value = discountHandler.getFixedValue(this.discount.value, this.discount.type);\n }", "function handleGameProgress(correct) {\n //If answer is correct\n if(correct) {\n //Increse score by 10\n score += 10;\n //Increse item correct by one\n itemCorrect += 1;\n //If the max items for level is reached\n if(itemCorrect == fetchMaxItems()){\n //If level is equal to nuber of levels configured\n if(level == config.numberOfLevels){\n //Take to game win scenario\n gameOver('won');\n //Reset score to 0\n score = 0;\n } else {\n //Level is coompleted scenario\n updateItemsRemaining();\n gameOver('levelUp');\n }\n } else {\n //Next question in same level scenario\n removeCurrentItem();\n resetRightPanel();\n resetLeftPanel();\n updateTeddyDialogueMessage(teddyDialogues.gameCorrectMapping);\n }\n } else {\n //Reduce the score by 5 if score is not zero else game over\n if(score > 0){\n //score reduced by 5\n score -= 5;\n //fetch score element by id and upadte the reduced score\n var score_ele = document.getElementById('score');\n score_ele.innerHTML = \"Score \"+score;\n updateTeddyDialogueMessage(teddyDialogues.gameIncorrectMapping);\n } else {\n //game over as score went below zero\n gameOver('score');\n }\n }\n}", "function player_max(current_board, player, other_player) {\n // Check if the game is over using the \"game_over\" function above.\n // If the current player wins, returns a high score (say 1000).\n // If the current player loses (other player wins), returns a low score (say -1000).\n // If it is a tie return a neutral score (say 0).\n // If the game is on going continue to the remaining part of the function.\n\n // Get all available moves.\n\n // Loop over available moves to find the move with maximum score.\n // 1. For every move, copy the board and apply the move to the copied board.\n // This is because the code here uses the board as a draft. It tried all\n // possible moves before picking the one it likes best. If we dont copy\n // the board before modifying it, then we effectively commit to the move (choose it)\n // before trying the other moves.\n // 2. After applying the move, call player_min with the new copied board and new player. \n // use the returned score and move to find the maximum.\n\n // Return the maximum score and its corresponding move.\n\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
c. metodo para editar un registro en el document tracks
static async edit(id, titulo, descripcion, avatar, color) { // comprobar que ese elemento exista en la BD const trackTemp = await this.findById(id); if (!trackTemp) throw new Error("El track solicitado no existe!"); // crear un DTO> es un objeto de trancicion const modificador = { titulo, descripcion, avatar, color }; // findOneAndUpdate > actualizara en base a un criterio const result = await this.findOneAndUpdate( { _id: id }, { $set: modificador } ); // retornar un resultado return result; }
[ "function editNote(){\n\t\n\tvar moment = require('alloy/moment');\n\t\n\tvar note= myNotes.get(idNote);\n\tnote.set({\n\t\t\"noteTitle\": $.noteTitle.value,\n\t\t\"noteDescription\": $.noteDescription.value,\n\t\t\"date\": moment().format()\n\t}).save();\n\t\n\tvar toast = Ti.UI.createNotification({\n\t\t \t\t\t \tmessage:\"Note has been succesfully saved\",\n\t\t \t\t\tduration: Ti.UI.NOTIFICATION_DURATION_SHORT\n\t\t\t\t\t\t});\n\t\t\t\t\t\t\n\t\t\t\ttoast.show();\n\tAlloy.Collections.note.fetch();\n\t\n $.detailnote.close();\n\t\t\n}", "function editSave() {\n if (!inputValid()) return;\n vm.editObj.id = -3;\n server.addBuoy(vm.editObj).then(function(res) {\n queryBuoys();\n queryBuoyInstances();\n gui.alertSuccess('Buoy added.');\n }, function(res) {\n gui.alertBadResponse(res);\n vm.buoys.splice(vm.buoys.length - 1, 1);\n });\n vm.editId = -1;\n }", "SET_CONTENT(state, editedDoc) {\n // We have to identify the doc to be updated\n // Then replace the content\n let newDoc = state.allDocs.find((doc) => doc.id == editedDoc.id);\n newDoc.content = editedDoc.content;\n newDoc.title = editedDoc.title;\n }", "editTracksInfo () {\n //\n }", "async update ({ params, request, response }) {\n const tarefa = await Tarefa.findOrFail(params.id);\n const dados = request.only([\"descricao\", \"titulo\", \"status\"]);\n \n tarefa.fill({\n id : tarefa.id,\n ...dados\n });\n \n await tarefa.save();\n }", "function updateEsRecord(data) {\n esClient.search({\n index: 'products',\n body: {\n query : {\n term: { \"id\" : data.id }\n }\n }\n }).then(found => {\n \n console.log('Found item: ', found.hits.hits[0]._id);\n\n if(found){\n esClient.update({\n index: 'products',\n id: found.hits.hits[0]._id,\n body: {\n doc: {\n id: data.id,\n title: data.title,\n description: data.description\n }\n }\n })\n .then(response => {\n console.log('Updated successfully.');\n })\n .catch(err => {\n console.log('Update error: ' +err);\n })\n }\n })\n .catch(err => {\n console.log('Not found Error: '+ err);\n });\n}", "function editNotesRecord(recordId,editedTDchange,c) {\n\tconsole.log('In function editNotesRecord. recordId = '+ recordId);\nlet noteId = Number(recordId);\n//let editedDate = dateSelect.value;\nconsole.log('noteId = ' + noteId + '. editedTDchange = ' + editedTDchange);\n//noteId = 3. editedDate = 1\nlet transaction = db.transaction([objectStoreName], 'readwrite');\n\nlet objectStore = transaction.objectStore(objectStoreName);\n\nlet request = objectStore.get(noteId);\n//Date:Jan29 DataError: Failed to execute 'get' on 'IDBObjectStore': The parameter is not a valid key.\n//var request = objectStore.get();noteId = 3 and this was deleted in this dB. Have to parse tableArray[i][c] to get the date\nrequest.onerror = function(event) {\n // Handle errors!\n console.log(\"edit failed\");\n};//end request.o error\nrequest.onsuccess = function(event) {\n\t//original note in data variable\n\tvar data = event.target.result;\n\t//create the tools for doing the edit\n\tconsole.log('Will edit item # ' + data.id + '. data.title = ' + data.title + ' ' + data.created + ' , ' + data.body);\n\t//reference editTitle input this works\n\t//changed data.title = editedTDchange to data.title = noteId + '> ' + editedTDchange NO DON'T HAVE data.title is just the title, not id\nif(c===0) {data.title = editedTDchange}\nconsole.log('data.title now = ' + data.title);\nif (c===1) {data.created = editedTDchange}\nif (c===2) {data.body = editedTDchange}\nif (c===3) {data.xtraField = editedTDchange}\n\n\nvar requestUpdate = objectStore.put(data);\n//};//end request.onsuccess ?might have to move to end of function?\n requestUpdate.onerror = function(event) {\n // Do something with the error\n\t editBanner.textContent = 'Whoops! ERROR! Transaction now inactive!'\n };\n requestUpdate.onsuccess = function(event) {\n // Success - the data is updated!\n\t console.log(\"The record is updated!\");\n\t };\n\t \n };//end request.onsuccess ?might have to move to end of function?\n }//end function editNotesDate(i,c) ", "function User_Update_Type_de_documents_Type_de_documents0(Compo_Maitre)\n{\n var Table=\"typedocument\";\n var CleMaitre = Compo_Maitre.getCleVal();\n var NomCleMaitre = DePrefixerChamp(Compo_Maitre.getCle());\n var to_nom=GetValAt(229);\n if (!ValiderChampsObligatoire(Table,\"to_nom\",TAB_GLOBAL_COMPO[229],to_nom,false))\n \treturn -1;\n if (!ValiderChampsType(Table,\"to_nom\",TAB_GLOBAL_COMPO[229],to_nom))\n \treturn -1;\n var to_description=GetValAt(230);\n if (!ValiderChampsObligatoire(Table,\"to_description\",TAB_GLOBAL_COMPO[230],to_description,false))\n \treturn -1;\n if (!ValiderChampsType(Table,\"to_description\",TAB_GLOBAL_COMPO[230],to_description))\n \treturn -1;\n var note=GetValAt(231);\n if (!ValiderChampsObligatoire(Table,\"note\",TAB_GLOBAL_COMPO[231],note,false))\n \treturn -1;\n if (!ValiderChampsType(Table,\"note\",TAB_GLOBAL_COMPO[231],note))\n \treturn -1;\n var Req=\"update \"+Table+\" set \";\n Req+=\"to_nom=\"+(to_nom==\"\" ? \"null\" : \"'\"+ValiderChaine(to_nom)+\"'\" )+\",to_description=\"+(to_description==\"\" ? \"null\" : \"'\"+ValiderChaine(to_description)+\"'\" )+\",note=\"+(note==\"\" ? \"null\" : \"'\"+ValiderChaine(note)+\"'\" )+\"\";\n Req+=\" where \"+NomCleMaitre+\"=\"+CleMaitre;\n\n if (pgsql_update(Req)==0)\n\talert(\"Echec lors de la mise à jour\");\nreturn CleMaitre;\n\n}", "static editar(portfolio, callback) {\n return db.query(\"update portfolio set nomeProj = ?, descricao = ?, detalhes = ? where id = ?\", [portfolio.nomeProj, portfolio.descricao, portfolio.detalhes, portfolio.id], callback);\n }", "function updateNote(id, updateField) {\n const note = notes.find(note => note.id == id);\n if (!note) {\n return undefined;\n }\n if (typeof updateField.title === 'string') {\n note.title = updateField.title;\n // note.dateModified = moment().valueOf();\n }\n if (typeof updateField.description === 'string') {\n note.description = updateField.description;\n // note.dateModified = moment().valueOf();\n }\n note.dateModified = moment().valueOf();\n saveNotes();\n return note;\n}", "function UpdateTrackById(req, res) {\n// Updates the artist by ID, get ID by req.params.artistId\n}", "function saveDocument() {\n if (current.id) {\n console.log(\"saveDocument(old) started\");\n var isUpdateSupported = current.resources.self && $.inArray('PUT', current.resources.self.allowed) != -1;\n if (!isUpdateSupported) {\n alert(\"You are not allowed to update this document\");\n return;\n }\n showMessage(\"Updating existing document ...\");\n current.subject = $(\"#document-subject\").val();\n current.content.text = $(\"#document-text\").val();\n current.update().execute(function(response) {\n console.log(\"Update response = \" + JSON.stringify(response));\n loadDocuments();\n });\n }\n else {\n console.log(\"saveDocument(new) started\");\n showMessage(\"Saving new document ...\");\n current.subject = $(\"#new-document-subject\").val();\n current.html = $(\"#new-document-html\").val();\n user.privateDocuments.create(current).execute(function(response) {\n console.log(\"saveDocument(new) response = \" + JSON.stringify(response));\n loadDocuments();\n });\n }\n}", "save() {\n var elem = this._view.getNote(),\n data = validate.getSanitizedNote({\n id: this.id,\n content: elem.html(),\n settings: elem.data(\"settings\")\n });\n \n this._model.setData(\n data,\n (d) => {\n console.log(\"saved\");\n }, (e) => {\n console.log(e);\n }\n );\n }", "function updateSyncDoc(service, SyncDoc) {\n service\n .documents(SyncDoc)\n .update({\n data: { temperature: 30,\n humidity: 20 },\n })\n .then(response => {\n console.log(response);\n// console.log(\"== deleteSyncDoc ==\");\n})\n .catch(error => {\n console.log(error);\n });\n}", "function saveChangesInFile() {\n var fileId = $(this).attr(\"data-id\");\n var editedText = $(\"textarea.editFile\").val();\n var fileAndParent = fileSystem.findElementAndParentById(fileId);\n var file = fileAndParent.element;\n file.content = editedText;\n var parent = fileAndParent.parent;\n if (parent != null) {\n showFolderOrFileContentById(parent.id);\n }\n }", "save() {\n let component = this;\n let comment = get(this, 'comment');\n\n comment.save().then((comment) => {\n component.set('isEditing', false);\n this._fetchMentions(comment);\n });\n }", "function editNote() {\n vm.isEditingNote = true;\n }", "updateById(id, data) {\n return this.post('/' + id + '/edit', data);\n }", "function applicaModifiche(oggetto) {\r\n var trans = db.transaction([\"utenti\"],\"readwrite\");\r\n var store = trans.objectStore(\"utenti\");\r\n var operazione = store.put(oggetto); //aggiorna le modifiche\r\n operazione.onsuccess = function(e){}\r\n\r\n\r\n operazione.onerror = function(e) {\r\n alert(\"Errore nel fissaggio dei cambiamenti\");\r\n }\r\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Loads the project id from environment variables.
getProductionProjectId() { return (process.env['GCLOUD_PROJECT'] || process.env['GOOGLE_CLOUD_PROJECT'] || process.env['gcloud_project'] || process.env['google_cloud_project']); }
[ "get githubAppId () {\n return process.env.GITHUB_APP_ID\n }", "loadEnv() {\n let env = dotenvExtended.load({\n silent: false,\n path: path.join(this.getProjectDir(), \".env\"),\n defaults: path.join(this.getProjectDir(), \".env.defaults\")\n });\n\n const options = minimist(process.argv);\n for (let option in options) {\n if (option[0] === \"-\") {\n let value = options[option];\n option = option.slice(1);\n if (option in env) {\n env[option] = value.toString();\n }\n }\n }\n env = dotenvParseVariables(env);\n env = dotenvExpand(env);\n\n this.env = { ...env, project_dir: this.getProjectDir() };\n }", "loadEnvVarsForLocal() {\n const defaultEnvVars = {\n IS_LOCAL: 'true',\n };\n\n _.merge(process.env, defaultEnvVars);\n\n // Turn zero or more --env options into an array\n // ...then split --env NAME=value and put into process.env.\n _.concat(this.options.env || []).forEach(itm => {\n const splitItm = _.split(itm, '=');\n process.env[splitItm[0]] = splitItm[1] || '';\n });\n\n return BbPromise.resolve();\n }", "loadEnvironmentInfo() {\n let infoPath = path.join(this.projectFolder, \"envInfo.json\");\n if (this.utils.fileExists(infoPath)) {\n return this.utils.readJsonFile(infoPath);\n }\n return null;\n }", "function getProjectbyID() {\n vm.showProjectLoading = true;\n projectsSvc.getProjectByOrgID().then(function(response) {\n vm.projectDetailsObj.savedProjects = [];\n vm.projectDetailsObj.savedProjects = response.data;\n // if ($scope.projectId) {\n // var projById = _.filter($scope.projectDetailsObj.savedProjects, function(item) {\n // return item.project_id === $scope.projectId;\n // })[0];\n\n // $scope.projectDetailsObj.selectedProject = projById;\n // }\n vm.showProjectLoading = false;\n }, function(error) {\n console.log(error);\n vm.showProjectLoading = false;\n if (error.data != undefined) {\n errorSvc.displayErrorString(error.data.errorCode, 'error', 15);\n }\n errorSvc.logProcessing(error, 'error');\n });\n }", "function getProjectbyId(project_id){\n\n}", "loadEnvironmentHostnames() {\n let hostNames = path.join(this.projectFolder, \"hostnames.json\");\n return this.utils.readJsonFile(hostNames);\n }", "function getConfigForProject(projectId) {\n var allProjects = allConfig.projects;\n \n for (var i = 0; i < allProjects.length; i++) {\n var project = allProjects[i];\n if (project.id == projectId) {\n return project;\n }\n }\n \n logger.error(\"No project found for id %d\", projectId);\n}", "getProjectUrl(projectId) {\n const url = this.get(HATEOAS_PROJECTS_LIST);\n if (url != null) {\n return url + '/' + projectId;\n } else {\n return null;\n }\n }", "function loadProjects() {\n API.getProjects()\n .then((res) => setProjects(res.data))\n .catch((err) => console.log(err));\n }", "function getProject() {\n return settings.getProject();\n}", "function getEnv() {\n\tvar store = JSON.parse(localStorage.getItem(\"AtmosphereEnv\"));\n\tif ((store !== undefined) && (store !== null)) env = store;\n}", "function getPlatformId(){\n return getURLParameter('platform');\n}", "loadProject(name) {\n this.persistenceController.loadProject(name);\n }", "function getProjectById(id) {\n return db(\"projects\")\n .where({ id })\n .first();\n}", "function getProjectKey(projectOrKey){if(typeof projectOrKey==='string'){return projectOrKey;}else if(!projectOrKey){throw new Error(AJS.I18n.getText('bitbucket.web.error.no.project'));}return projectOrKey.getKey?projectOrKey.getKey():projectOrKey.key;}", "get environment() {\n if (this._enviornment)\n return Promise.resolve(this._enviornment);\n return fs.readFile(this.environmentPath).then((file) => __awaiter(this, void 0, void 0, function* () {\n let localEnvironment = jsonc.parse(file.toString());\n if (!localEnvironment.names || !Array.isArray(localEnvironment.names)) {\n throw new Error('Local environment.json is not properly configured.');\n }\n this._enviornment = localEnvironment;\n return localEnvironment;\n }));\n }", "function getManifestvariable(variableName) {\n return config[variableName]; //dont know if called\n}", "function getEnvSetting(confKey) {\n return CONFIGURATION_VARS[confKey].envValue;\n}", "function loadProject(project){\n\n\t\t\tvar projectDirectory = projectLocation.format(project.id);\n\t\t\tvar projectDataFile = projectDirectory + '/index.html';\n\n\t\t\t// load the file\n\t\t\treturn fsp.readFile(projectDataFile, 'utf8')\n\t\t\t\t.then(createProjectFromFile)\n\t\t\t\t.then(parseFrontMatter)\n\t\t\t\t.catch(error);\n\n\n\t\t\t// split it into front matter and content\n\t\t\tfunction createProjectFromFile(fileString){\n\n\t\t\t\tconsole.log('service: createProjectFromFile (1st)');\n\n\t\t\t\tvar fileParts = fileString.split('---\\n');\n\n\t\t\t\t// fileParts[0] is an empty string\n\t\t\t\tproject.frontMatter = fileParts[1];\n\t\t\t\tproject.content = fileParts[2];\n\n\t\t\t\treturn project;\n\t\t\t}\n\n\n\t\t\t// parse the front matter into an object\n\t\t\tfunction parseFrontMatter(project){\n\n\t\t\t\tconsole.log('service: parseFrontMatter (2nd)');\n\n\t\t\t\tproject.frontMatter = yaml.parse(project.frontMatter);\n\n\t\t\t\treturn project;\n\t\t\t}\n\n\n\t\t\t// catch any error\n\t\t\tfunction error(err) {\n $log.error(err);\n }\n\n\t\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check if a user can affect another user's status based on their roles.
function canAffect(userRole, targetRole) { if (userRole === 'owner') { return true; } if (targetRole === 'owner') { return false; } return userRole === 'moderator' && targetRole === 'user'; }
[ "function can(user, action, target) {\n assert(typeof action === 'string')\n\n switch (action) {\n case 'READ_MESSAGE': // target is message\n assert(target)\n // Anyone can see a message as long as it's not hidden\n if (!target.is_hidden) return true\n // Only admins and mods can read hidden messages\n if (target.is_hidden)\n return ['ADMIN', 'MOD'].includes(user && user.role)\n return false\n case 'UPDATE_USER_*': // target is other user\n return (\n can(user, 'UPDATE_USER_SETTINGS', target) ||\n can(user, 'UPDATE_USER_ROLE', target)\n )\n case 'UPDATE_USER_SETTINGS': // target is other user\n assert(target)\n // Guests never can\n if (!user) return false\n // Banned never can\n if (user.role === 'BANNED') return false\n // Admins always can\n if (user.role === 'ADMIN') return true\n // Mods can only see non-admins\n if (user.role === 'MOD') return target.role !== 'ADMIN'\n // Members can only update their own settings\n if (user.role === 'MEMBER') return target.id === user.id\n return false\n case 'UPDATE_USER_ROLE': // target is other user\n assert(target)\n // Guests never can\n if (!user) return false\n // Admins always can\n if (user.role === 'ADMIN') return true\n return false\n case 'CREATE_MESSAGE': // no target\n // Guests can\n if (!user) return true\n // Any user can unless they are banned\n if (user.role === 'BANNED') return false\n return true\n case 'DELETE_MESSAGE': // target is message\n debug('[DELETE_MESSAGE] user=%j', user)\n assert(target)\n // Guests cannot\n if (!user) return false\n // Banned cannot\n if (user.role === 'BANNED') return false\n // Users can if it's their own message\n if (user.id === target.user_id) return true\n // Admins and mods always can\n if (['ADMIN', 'MOD'].includes(user.role)) return true\n return false\n // Is user authorized for any of the UPDATE_MESSAGE_* actions?\n case 'UPDATE_MESSAGE': // target is message\n assert(target)\n return (\n can(user, 'UPDATE_MESSAGE_STATE', target) ||\n can(user, 'UPDATE_MESSAGE_MARKUP', target)\n )\n // Can user change message.is_hidden?\n case 'UPDATE_MESSAGE_STATE': // target is message\n assert(target)\n // Guests never can\n if (!user) return false\n // Only mods and admins\n if (['ADMIN', 'MOD'].includes(user.role)) return true\n return false\n case 'UPDATE_MESSAGE_MARKUP': // target is message\n assert(target)\n // Guests never can\n if (!user) return false\n // Mods and admins can change any message markup\n if (['ADMIN', 'MOD'].includes(user.role)) return true\n // Members can update their own messages\n if (user.role === 'MEMBER') return user.id === target.user_id\n return false\n default:\n debug('Unsupported cancan action: %j', action)\n return false\n }\n}", "async function permissionCheck(user, group, targetUser, action) {\n const userRole = await getRole(user, group);\n const targetRole = await getRole(targetUser, group);\n\n if (!canAffect(userRole, targetRole)) {\n throw new RequestError(`${userRole} cannot ${action} ${targetRole}`);\n }\n\n return [userRole, targetRole];\n}", "async function isReferee(user_id) {\n const is_referee = await DButils.execQuery(`SELECT * FROM dbo.Roles WHERE userId=${user_id} and roleId=${process.env.refereeRole}`);\n return is_referee.length == 1;\n}", "function checkRoles(roles){\n var possibleRoles = [\"service provider\", \"device owner\", \"infrastructure operator\", \"administrator\", \"system integrator\", \"devOps\", \"user\", \"superUser\"];\n for(var i = 0, l = roles.length; i < l; i++){\n if(possibleRoles.indexOf(roles[i]) === -1){\n return {invalid: true, message: roles[i]};\n }\n }\n return {invalid: false, message: null};\n}", "isPermitted(user_id) {\n if (!user_id) return false;\n for(var permitted in this.permitted) {\n if ( permitted == user_id ) return this.permitted[permitted] != null;\n if ( botStuff.userHasRole(this.server_id, user_id, permitted)) return this.permitted[permitted] != null;\n }\n return false;\n }", "async function checkRole (req, res, next) {\n const { user_id, team_id } = req.params;\n const teamId = req.body.team_id;\n\n if(!teamId){\n next();\n } else if (!team_id){\n const member = await teamMembersDB.getTeamMember(user_id, teamId);\n\n if(!member){\n res.status(401).json({ error: 'You are not a Member of this Team'});\n } else {\n next();\n }\n } else {\n const member = await teamMembersDB.getTeamMember(user_id, team_id);\n\n if(!member){\n res.status(401).json({ error: 'You are not a Member of this Team'});\n } else {\n\n if(member.role !== 'team_owner'){\n res.status(401).json({ error: 'Only Team Owners can do this'});\n } else {\n next();\n }\n }\n }\n}", "function updateRoles(user, level) {\n if (role_rewards.length <= 0) return;\n\n const roleID = getLevelRole(level);\n if (roleID && !user.roles.cache.has(roleID)) {\n // Remove old roles (could be optional)\n for (const reward of role_rewards) {\n if (user.roles.cache.has(reward[1])) {\n user.roles.remove(reward[1]);\n }\n }\n\n user.roles.add(roleID);\n return true;\n }\n}", "canManageTheServer(user_id) {\n return this.userHasPermissions(user_id, P_ADMINISTRATOR) ||\n this.userHasPermissions(user_id, P_MANAGE_GUILD) ||\n this.isServerOwner(user_id);\n }", "function manageRoles(cmd){\n try{\n\t//console.log(cmd.message.channel instanceof Discord.DMChannel);\n\t//if (cmd.message.channel instanceof Discord.DMChannel) { sendMessage(cmd, \"This command currently only works in guild chats\"); return \"failure\"; }\n\tconst openRoles = roleNames.openRoles, voidRoles = roleNames.voidRoles;\n const guild = client.guilds.find(\"name\", \"Terra Battle\");\n\tconst guildRoles = guild.roles; //cmd.message.guild.roles;\n\tvar roles = cmd.details.split(\",\"), guildMember = guild.members.get(cmd.message.author.id);\n \n var feedback = \"\";\n\t//console.log(guildMember);\n\t\n\t//Check to make sure the requested role isn't forbidden\n\t//Find role in guild's role collection\n\t//Assign role (or remove role if already in ownership of)\n\t//Append response of what was done to \"feedback\"\n\troles.forEach(function(entry){\n\t\tentry = entry.trim();\n\t\tlowCaseEntry = entry.toLowerCase();\n\t\t\n\t\t//Ignore any attempts to try to get a moderator, admin, companion, bot, or specialty role.\n\t\t//Ignore: metal minion, wiki editor, content creator, pvp extraordinare\n /*voidRoles.forEach(\n function(currentValue){\n \n }\n );*/ //TODO: Manage Void Role rejection more elegantly\n\t\tif (!(voidRoles.some( x => lowCaseEntry.includes(x) )) ){\n\t\t\t\n\t\t\t//run requested role name through the roleName DB\n\t\t\tvar roleCheck = openRoles.get(lowCaseEntry); //TODO: Make a DB that allows for server-specific role name checks\n\t\t\tvar role;\n\t\t\t\n\t\t\ttry{ role = guildRoles.find(\"name\", roleCheck); }\n\t\t\tcatch (err) { \n\t\t\t\t//Role didn't exist\n\t\t\t\tconsole.log(err.message);\n console.log(\"User: \" + cmd.message.author.name);\n\t\t\t}\n\t\t\t\n\t\t\tif( typeof role === 'undefined' || role == null ){ feedback += \"So... role '\" + entry + \"' does not exist\\n\"; }\n\t\t\telse if( guildMember.roles.has(role.id) ) {\n\t\t\t\tguildMember.removeRole(role);\n\t\t\t\tfeedback += \"I removed the role: \" + role.name + \"\\n\"; }\n\t\t\telse {\n\t\t\t\tguildMember.addRole(role);\n\t\t\t\tfeedback += \"I assigned the role: \" + role.name + \"\\n\"; }\n\t\t} else { feedback += \"FYI, I cannot assign '\" + entry + \"' roles\"; }\n\t\t//guildMember = cmd.message.member;\n\t});\n\t//return feedback responses\n\t( feedback.length > 0 ? cmd.message.channel.send(feedback) : \"\" );\n } catch (err) {\n console.log(err.message);\n console.log(\"User: \" + cmd.message.author.name);\n }\n}", "isMember(state) {\n return state.oauth.user !== null && ['board', 'member'].indexOf(state.oauth.user.level) !== -1;\n }", "function isModerator(user){\r\n return user.mod;\r\n}", "function getUserRole(name, role){\n switch (role) {\n case \"admin\":\n return `${name} is admin with all access`\n break; //this is not neccesary\n\n case \"subadmin\":\n return `${name} is sub-admin acess to delete and create courses`\n break;\n\n case \"testprep\":\n return `${name} is test-prep access with to delete and create tests `\n break;\n case \"user\":\n return `${name} is a user to consume content`\n break;\n \n default:\n return `${name} is admin access with to delete and create tests `\n break;\n }\n}", "function checkRole (role, allowed, options) {\n // Check if the value type passed to view is create or edit \n var temp = allowed.split(',');\n if (temp[role]) { \n return options.fn(this);\n } else {\n return;\n } \n}", "function ChangeUserRole(id, role) {\n\tvar confirmed = confirm(\"Change the user's role to: \" + role);\n\t\n\tif (confirmed) {\n\t\t// Again, this could be done through AJAX.\n\t\twindow.location = '/?action=changerole&userid=' + id + '&role=' + role;\n\t}\n}", "function _checkUserAdmin() {\r\n\t\t\t// if user is authenticated and not defined yet, check if they're an admin\r\n\t\t\tif ($auth.isAuthenticated() && header.adminUser === undefined) {\r\n\t\t\t\tuserData.getUser()\r\n\t\t\t\t\t.then(function(data) {\r\n\t\t\t\t\t\theader.adminUser = data.isAdmin;\r\n\t\t\t\t\t});\r\n\t\t\t}\r\n\t\t}", "function checkLogedInUser() {\n\n}", "'addUserRole'(userid, role)\n {\n Roles.addUsersToRoles(userid,role);\n\n\n }", "function seperateRole(){\n\n}", "async function checkModerator(user, group) {\n const role = await getRole(user, group);\n if (!canAffect(role, 'user')) {\n throw new RequestError('user is not a moderator');\n }\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Push boolean onto the stack.
pushBoolean(b) { this.pushObject(Lua.valueOfBoolean(b)); }
[ "push(val) {\n this._stack.push(val);\n }", "_add_boolean_expression_subtree_to_ast(boolean_expression_node, parent_var_type) {\n this.verbose[this.verbose.length - 1].push(new NightingaleCompiler.OutputConsoleMessage(SEMANTIC_ANALYSIS, INFO, `Adding ${boolean_expression_node.name} subtree to abstract syntax tree.`) // OutputConsoleMessage\n ); // this.verbose[this.verbose.length - 1].push\n let open_parenthesis_or_boolean_value_node = boolean_expression_node.children_nodes[0];\n // Enforce type matching in boolean expressions\n let valid_type = false;\n // If, no parent type was given to enforce type matching...\n if (parent_var_type === UNDEFINED) {\n // Enforce type matching using the current type from now on.\n parent_var_type = BOOLEAN;\n } // if\n // Else, there is a parent type to enforce type matching with.\n else {\n valid_type = !this.check_type(parent_var_type, open_parenthesis_or_boolean_value_node, BOOLEAN);\n } // else\n // Boolean expression ::== ( Expr BoolOp Expr )\n if (boolean_expression_node.children_nodes.length > 1) {\n // Ignore Symbol Open Argument [(] and Symbol Close Argument [)]\n // let open_parenthisis_node = boolean_expression_node.children_nodes[0];\n // let open_parenthisis_node = boolean_expression_node.children_nodes[4];\n let boolean_operator_value_node = boolean_expression_node.children_nodes[2].children_nodes[0];\n let left_expression_node = boolean_expression_node.children_nodes[1];\n let right_expression_node = boolean_expression_node.children_nodes[3];\n // FIRST Add the Boolean Operator\n this._current_ast.add_node(boolean_operator_value_node.name, NODE_TYPE_BRANCH, valid_type, false, boolean_operator_value_node.getToken()); // this._current_ast.add_node\n // Start by recursively evaluating the left side...\n // Note the type as it will be used to enforce type matching with the right side.\n let left_expression_type = this._add_expression_subtree(left_expression_node, UNDEFINED);\n // If it was an integer expression climb back up to the parent boolean expression node\n if (left_expression_node.children_nodes[0].name === NODE_NAME_INT_EXPRESSION) {\n while ((this._current_ast.current_node !== undefined || this._current_ast.current_node !== null)\n && this._current_ast.current_node.name !== AST_NODE_NAME_BOOLEAN_EQUALS\n && this._current_ast.current_node.name !== AST_NODE_NAME_BOOLEAN_NOT_EQUALS) {\n if (this._current_ast.current_node.name !== AST_NODE_NAME_BOOLEAN_EQUALS\n || this._current_ast.current_node.name !== AST_NODE_NAME_BOOLEAN_NOT_EQUALS) {\n this._current_ast.climb_one_level();\n } // if\n } // while\n } // if\n // Ensures the correct order of nested operators in the ast.\n //\n // Look ahead in the tree on the left side of the \n // boolean expression and climb if it's an expression and not some value.\n if (left_expression_node.children_nodes[0].children_nodes[0].name == \"(\") {\n this._climb_ast_one_level();\n } // if\n // Then recursively deal with the right side...\n // To enforce type matching, use the left sides type as the parent type.\n let right_expression_type = this._add_expression_subtree(right_expression_node, left_expression_type);\n // If it was an integer expression climb back up to the parent boolean expression node\n if (right_expression_node.children_nodes[0].name === NODE_NAME_INT_EXPRESSION) {\n while ((this._current_ast.current_node !== undefined || this._current_ast.current_node !== null)\n && this._current_ast.current_node.name !== AST_NODE_NAME_BOOLEAN_EQUALS\n && this._current_ast.current_node.name !== AST_NODE_NAME_BOOLEAN_NOT_EQUALS) {\n if (this._current_ast.current_node.name !== AST_NODE_NAME_BOOLEAN_EQUALS\n || this._current_ast.current_node.name !== AST_NODE_NAME_BOOLEAN_NOT_EQUALS) {\n this._current_ast.climb_one_level();\n } // if\n } // while\n } // if\n // Ensures the correct order of nested operators in the ast.\n //\n // Look ahead in the tree on the right side of the \n // boolean expression and climb if it's an expression and not some value.\n if (right_expression_node.children_nodes[0].children_nodes[0].name == \"(\") {\n this._climb_ast_one_level();\n } // if\n } // if\n // Boolean expression is: boolval\n else if (boolean_expression_node.children_nodes.length === 1) {\n this._current_ast.add_node(open_parenthesis_or_boolean_value_node.children_nodes[0].name, NODE_TYPE_LEAF, valid_type, false);\n } // else if\n // Boolean expression is neither: ( Expr BoolOp Expr ) NOR boolval...\n else {\n // Given a valid parse tree, this should never happen...\n throw Error(\"You messed up Parse: Boolean expression has no children, or negative children.\");\n } // else \n }", "addBoolean(title, properties) {\n return this.add(title, 8, properties);\n }", "function parse_BooleanExpr(){\n\t\n\tdocument.getElementById(\"tree\").value += \"PARSER: parse_BooleanExpr()\" + '\\n';\n\t\n\n\t\n\tvar tempDesc = tokenstreamCOPY[parseCounter][0]; //check desc of token\n\tvar tempType = tokenstreamCOPY[parseCounter][1]; //check type of token\n\tif (tempDesc == '('){\n\t\tmatchSpecChars('(',parseCounter);\n\t\t\n\t\tCSTREE.addNode('BooleanExpr', 'branch');\n\t\t\n\t\tparseCounter = parseCounter + 1;\n\t\t\n\t\t\n\t\tparse_Expr();\n\t\n\t\t\n\t\tparse_boolop();\n\t\n\t\t\n\t\tparse_Expr();\n\t\n\t\tmatchSpecChars(')',parseCounter);\n\t\tparseCounter = parseCounter + 1;\n\t\t\n\t}\n\telse{\n\t\tparse_boolval();\n\t\n\t}\n\n\t\n}", "push(element) {\r\n //this.stack.push(element);\r\n this.stack.unshift(element);\r\n }", "static bool(v) { return new Typed(_gaurd, \"bool\", !!v); }", "stackPush(byte) {\n this.writeRam({ address: 0x0100 + this.cpu.sp, value: byte });\n this.decrementRegister('sp');\n }", "pushState(state, start) {\n this.stack.push(this.state, start, this.bufferBase + this.buffer.length)\n this.state = state\n }", "writeBoolean(value) {\n this.writeUint8(value ? 0xff : 0x00);\n return this;\n }", "plus() {\n this._lastX = this.pop();\n this._stack.push(this.pop() + this._lastX);\n }", "function addItem(item){\n basket.push(item);\n return true;\n}", "pushToken(token) {\n this.stack.push(token);\n }", "pushNode(node) {\n this.stack.push(new Frame(node));\n }", "function Stack() {\n\tthis.layers = [];\n\tthis.layers.push({});\n\t\n\tthis.addLayer = function() {\n\t\tthis.layers.push({});\n\t}\n\tthis.removeLayer = function() {\n\t\tthis.layers.pop();\n\t}\n\tthis.addVar = function(name, value) {\n\t\tname = name.toLowerCase();\n\t\tthis.layers[this.layers.length-1][name] = value;\n\t}\n\tthis.existVar = function(name) {\n\t\tname = name.toLowerCase();\n\t\tvar result = false;\n\t\tfor(var i=this.layers.length-1; i>=0; i--) {\n\t\t\tif(this.layers[i].hasOwnProperty(name)) {\n\t\t\t\tresult = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\treturn result;\n\t}\n\tthis.existNow = function(name) {\n\t\tname = name.toLowerCase();\n\t\tvar result = false;\n\t\tif(this.layers[this.layers.length-1].hasOwnProperty(name)) {\n\t\t\tresult = true;\n\t\t}\n\t\treturn result;\n\t}\n\tthis.setVar = function(name, value) {\n\t\tname = name.toLowerCase();\n\t\tfor(var i=this.layers.length-1; i>=0; i--) {\n\t\t\tif(this.layers[i].hasOwnProperty(name)) {\n\t\t\t\tthis.layers[i][name] = value;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\tthis.getVar = function(name) {\n\t\tname = name.toLowerCase();\n\t\tfor(var i=this.layers.length-1; i>=0; i--) {\n\t\t\tif(this.layers[i].hasOwnProperty(name)) {\n\t\t\t\treturn this.layers[i][name];\n\t\t\t}\n\t\t}\n\t}\n}", "function push(tile) {\n \tvar id = tile.value == 1? tile.id1 : tile.id2;\n \tvar newState = { 'parent': currentState, tile: tile };\n \t// add the new state on top of the current\n \tcurrentState[id] = newState;\n \t// for this specific tile, count how many values have been tried\n \tif (currentState[tile.id])\n \t\tcurrentState[tile.id]++\n \telse\n \t\tcurrentState[tile.id] = 1;\n \tcurrentState = newState;\n }", "pushByte(value) {\n this.write(\">\" + \"+\".repeat(value));\n this.stack.push(StackEntry(DataType.Byte, 1));\n }", "emitIf(signal, boolean_expression) {\n if (boolean_expression) {\n return this.emit(signal);\n }\n return false;\n }", "function push() {\n var lastState = newState(),\n i;\n copyModelState(lastState);\n list[listState.index + 1] = lastState; // Drop the oldest state if we went over the max list size\n\n if (list.length > listState.maxSize) {\n list.splice(0, 1);\n listState.startCounter++;\n } else {\n listState.index++;\n }\n\n listState.counter = listState.index + listState.startCounter; // Send push request to external objects defining TickHistoryCompatible Interface.\n\n for (i = 0; i < externalObjects.length; i++) {\n externalObjects[i].push();\n }\n\n invalidateFollowingState();\n listState.length = list.length;\n }", "function conditionalPush(list, item) {\n\t//If you're wondering why I chose j here, blame dynamic scope.\n\t//If I had used i instead, getUsers() and conditionalPush would be sharing the same value for i, despite being in separate functions.\n\tfor (j = 0; j < list.length; j++) {\n\t\tif (list[j] == item){\n\t\t\treturn false;\n\t\t}\n\t}\n\tlist.push(item);\n\treturn true\n}", "push(msg) {\r\n this._msgStack.push(msg)\r\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Clone and move infoboxes into the right rail.
function doInfoboxen() { // <div id="section_SpokenWikipedia" class="infobox sisterproject plainlinks haudio"> // Move the infobox into the right rail. var $ibClone = $('.infobox').clone(true, true); if ($ibClone.length) { // Remove the old one. $('.infobox').remove(); $('#wsidebar').append($ibClone); } }
[ "function doNavboxen() {\n\t\t\t// Move vertical-navbox into the right rail.\n\t\t\tvar $nbClone = $('.vertical-navbox').clone(true, true);\n\t\t\tif ($nbClone.length) {\n\t\t\t\t// Remove the old one.\n\t\t\t\t$('.vertical-navbox').remove();\n\t\t\t\t$('#wsidebar').append($nbClone);\n\t\t\t}\n\t\t}", "function doMboxen() {\n\t\t\tvar $mbClone = $('.mbox-small').clone(true, true);\n\t\t\tif ($mbClone.length) {\n\t\t\t\t// Remove the old one.\n\t\t\t\t$('.mbox-small').remove();\n\t\t\t\t$('#wsidebar').append($mbClone);\n\t\t\t}\n\t\t}", "function changeBuildingPosition() {\n\n // clean DOM\n var $addCaptors = $(\"#add-captors\").empty();\n\n // append building name\n $addCaptors.append(\"<div><h2>\" + position.name + \"</h2></div>\");\n\n //We append a link to every room / place we can access from position\n for (var i = 0; i < buildings.length; i++) {\n $addCaptors.append(\n \"<div class=\\\"row\\\"><a class=\\\"node\\\" style=\\\"cursor : pointer;\\\" id=\\\"\" + i + \"\\\">\"\n + buildings[i].name + \"</a> - <span class=\\\"badge\\\" style=\\\"background:#4781ff;\\\">\"\n + buildings[i].amountOfSensors+\"</span></div>\"\n );\n }\n\n $addCaptors.append( \"<hr><div id='directSensors\"+position.name.replace(/ /g,\"_\")+\"' class='text-left'></div>\");\n var $directSensorsPosition = $(\"#directSensors\"+position.name.replace(/ /g,\"_\"));\n\n //Then, in position we check if there is any sensor\n if (position.directSensor != null && typeof(position.directSensor) !== 'undefined' && position.directSensor != [null]) {\n for (var i = 0; i < position.directSensor.length; i++) {\n\n if (position.directSensor[i] != null) {\n $directSensorsPosition.append(\n '<div class=\"draggableSensor\" id=\"' + position.directSensor[i].name + '\" style=\"cursor: -webkit-grab; cursor:-moz-grab;\">'\n + '<img class=\"sensorIcon\" src=\"/assets/images/sensorIcons/' + position.directSensor[i].kind + '.png\">'\n + position.directSensor[i].displayName\n + '</img> </div>'\n );\n }\n\n }\n }\n else {\n $directSensorsPosition.append(\"<div>There isn't any compatible sensor here. </div>\");\n }\n\n // make sensors draggable\n $(\".draggableSensor\").draggable({\n helper: function (event) {\n return $(\"<div style='cursor:-webkit-grabbing; cursor:-moz-grabbing;' id='\" + event.currentTarget.id + \"'>\" + event.currentTarget.innerHTML + \"</div>\");\n },\n revert: \"invalid\",\n cursorAt: { bottom: 10, left: 60 }\n });\n\n updateBuildingPath();\n}", "function moveComponents(updwn)\r\n{\r\n\tvar directn = parseInt(updwn);\r\n\thideAllDialogs();\r\n var stateDisplay = document.getElementById('stateDisplay');\r\n stateDisplay.value = globalBreadBoard.toString();\r\n\r\n okToClear = true;\r\n clearBreadBoard( ! okToClear);\r\n\r\n var circuitCode = stateDisplay.value;\r\n var lines = circuitCode.split(\"\\n\");\r\n\r\n for(var i = 0; i < lines.length; ++ i)\r\n {\r\n if(lines[i].length > 10 && lines[i].indexOf(\"BREADBOARDSTYLE\") == -1 && lines[i].indexOf(\"SHOWTHETOPAREA\") == -1)\r\n {\r\n var parts = lines[i].split(\"|\");\r\n\r\n\t\t\tif(directn == 1) // downwards\r\n\t\t\t{\r\n\t\t\t\tparts[3] = parseInt(parts[3]) + 295\t\t\r\n\t\t\t}\r\n\t\t\telse if(directn == 2) // up and drop/delete any in top area\r\n\t\t\t{\t\r\n\t\t\t\tif ( parts[3] < 295)\r\n\t\t\t\t{\r\n\t\t\t\t\tcontinue;\r\n\t\t\t\t}\r\n\t\t\t\telse\r\n\t\t\t\t{\r\n\t\t\t\t\tparts[3] = parseInt(parts[3]) - 295;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\telse if(directn == 3) // up and gather\r\n\t\t\t{\t\r\n\t\t\t\tif( parts[3] < 295)\r\n\t\t\t\t{\r\n\t\t\t\t\tparts[3] = 0; \r\n\t\t\t\t}\r\n\t\t\t\telse\r\n\t\t\t\t{\r\n\t\t\t\t\tparts[3] = parseInt(parts[3]) - 295;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\telse if(directn == 4) // up and left for backward compatability\r\n\t\t\t{\r\n\t\t\t\tparts[2] = parseInt(parts[2]) - 160\t// adjust the x coordinate value\t\r\n\t\t\t\tparts[3] = parseInt(parts[3]) - 60\t// adjust the y coordinate value\t\r\n\t\t\t}\r\n\t\t\r\n var newComp = new BBComponent(parts[0], parts[1], parts[2], parts[3], parts[4], parts[5],\r\n parts[6], parts[7], parts[8], parts[9], parts[10], parts[11], parts[12]);\r\n createComponent(newComp);\r\n }\r\n }\r\n}", "function moveToViewsContainer(p_item) {\n p_item.fadeOut(function() {\n p_item\n .resizable('destroy')\n .attr({\n style: ''\n })\n .clone(true)\n .appendTo('#menu')\n .fadeIn(function() {\n p_item.remove();\n })\n .find(\".portlet-header .port-icon-switch\")\n .unbind('click')\n .click(function() {\n moveToCenterContainer(jQuery(this).parents('.portlet'));\n jQuery(this)\n .toggleClass(\"ui-icon-arrowthick-1-e\")\n .toggleClass(\"ui-icon-arrowthick-1-w\");\n });\n });\n }", "function estimateBtnClone() {\n btnMenu.on('click',function(){\n var btn = $('.h-estimate').clone();\n if($(this).hasClass('active')){\n btn.prependTo('.menu > ul');\n }\n else{\n btn = '';\n $('.menu ul .h-estimate').remove();\n }\n });\n }", "changeBoard(fromSpace, toSpace){\n let fromIndex; let toIndex\n if (this.direction === 1){\n fromIndex = this.getId(fromSpace); toIndex = this.getId(toSpace)\n } else {\n fromIndex = this.getId(toSpace); toIndex = this.getId(fromSpace)\n }\n let orig_copy = $(\"#\"+fromIndex).children()\n let temp = orig_copy.clone()\n temp.appendTo('body')\n temp.css(\"display\", \"inline-block\")\n if (!$(\"#\"+toIndex).children().is('span')){\n let img_src = $(\"#\"+toIndex).children().prop('src')\n img_src = \".\"+img_src.slice(img_src.length - 11, img_src.length)\n this.takenPieces.push([img_src, this.current, this.direction])\n }\n $(\"#\"+toIndex).empty()\n let new_copy = orig_copy.clone().appendTo(\"#\"+toIndex)\n new_copy.css(\"display\", \"inline-block\")\n let oldOffset = orig_copy.offset()\n $(\"#\"+fromIndex).empty().append(\"<span id='piece'></span>\")\n let newOffset = new_copy.offset()\n for (let i = 0; i < this.takenPieces.length; i++){\n if (this.takenPieces[i][1] === this.current && this.takenPieces[i][2] !== this.direction){\n $(\"#\"+fromIndex).empty().append(`<img id=\"piece\" src=${this.takenPieces[i][0]}></img>`)\n $(\"#\"+fromIndex).css(\"display\", \"inline-block\")\n }\n }\n for (let i = 0; i < this.highlights.length; i++){\n if (this.highlights[i]){\n this.highlights[i].attr(\"class\").includes(\"dark\") ? this.highlights[i].css(\"border\", \"solid medium darkgrey\") : this.highlights[i].css(\"border\", \"solid medium lightgrey\")\n }\n }\n this.highlights[1] = $(\"#\"+fromIndex); this.highlights[2] = $(\"#\"+toIndex)\n $(\"#\"+fromIndex).css(\"border\", \"medium solid green\")\n $(\"#\"+toIndex).css(\"border\", \"medium solid green\")\n if (this.moves[this.current][\"special_square\"]){\n let special_square = [this.moves[this.current][\"special_square\"][\"row\"], this.moves[this.current][\"special_square\"][\"col\"]]\n $(\"#\"+this.getId(special_square)).css(\"border\", \"medium solid red\")\n this.highlights[0] = $(\"#\"+this.getId(special_square))\n }\n temp\n .css('position', 'absolute')\n .css('left', oldOffset.left)\n .css('top', oldOffset.top)\n .css('zIndex', 1000)\n .css(\"display\", \"inline\")\n .css(\"width\", \"25px\")\n .css(\"height\", \"25px\")\n new_copy.css(\"display\", \"none\")\n temp.animate({'top': newOffset.top, 'left':newOffset.left}, this.delay, function(){\n new_copy.css(\"display\", \"inline-block\")\n temp.remove()\n })\n }", "repositionDetails() {\n if (this.details && this.ibScapeDetails) {\n // Position the details based on its size.\n let ibScapeDetailsDiv = this.ibScapeDetails.node();\n let detailsRect = ibScapeDetailsDiv.getBoundingClientRect();\n ibScapeDetailsDiv.style.position = \"absolute\";\n\n\n // Relative to top left corner of the graph, move up and left half\n // of the details height/width.\n ibScapeDetailsDiv.style.left = (this.rect.left + this.center.x - (detailsRect.width / 2)) + \"px\";\n\n // Special handling for the top, because virtual keyboards on mobile\n // devices take up real estate and it's not worth it to check for\n // keyboard manually. Just have the top of the details higher than center.\n let topOffset = this.getIsPortrait() ? this.rect.height / 5 : 20;\n ibScapeDetailsDiv.style.top = (this.rect.top + topOffset) + \"px\";\n }\n }", "function moveNodeForNew(node) {\n // when create new box dom, move pass to 150 right\n var first_sub_node_x = getFirstSubNodePosition(node).x;\n // move each node position\n // add paret node, then sub node change position\n // add sub node, then parent node do not change position\n $('g[data-object-id=\"'+node.parent_id+'\"]>use').each(function(index_g, element_g){\n var x = first_sub_node_x + index_g * 150;\n $(element_g).attr(\"x\", x);\n });\n $('g[data-object-id=\"'+node.parent_id+'\"]>text').each(function(index_g, element_g){\n var x = first_sub_node_x + index_g * 150;\n $(element_g).attr(\"x\", x+30);\n });\n $('g[data-object-id=\"'+node.parent_id+'\"]>line').each(function(index_g, element_g){\n var x = first_sub_node_x + index_g * 150;\n $(element_g).attr(\"x2\", x+50);\n });\n // moving px\n var px = 0;\n $('use[data-object-id=\"'+node.object_id+'\"]').parent().find('g').children('use').each(function(index_g, element_g){\n var x = parseInt($(element_g).attr(\"x\"));\n px = x - parseInt($(element_g).attr(\"x\"));\n $(element_g).attr(\"x\", x-75);\n });\n $('use[data-object-id=\"'+node.object_id+'\"]').parent().find('g').children('text').each(function(index_g, element_g){\n var x = parseInt($(element_g).attr(\"x\"));\n $(element_g).attr(\"x\", x-75);\n });\n $('use[data-object-id=\"'+node.object_id+'\"]').parent().find('g').children('line').each(function(index_g, element_g){\n var x1 = parseInt($(element_g).attr(\"x1\"));\n var x2 = parseInt($(element_g).attr(\"x2\"));\n $(element_g).attr(\"x1\", x1-75);\n $(element_g).attr(\"x2\", x2-75);\n });\n }", "function updateBoxes(newFrame) {\n\t\tconsole.log(newFrame);\n\t\tclearCustomBoxes();\n\t\tframe = newFrame;\n\n\t\tupdateStandardBoxes(newFrame);\n\t\tvar boxesData = boxes.custom[frame];\n\t\tif (boxesData != null) {\t\t\t//creates custom boxes\n\t\t\tfor (var i = 0; i < boxesData.length; i++) {\n\t\t\t\tmakeCustomBox(boxesData[i]);\n\t\t\t}\n\t\t}\n\t}", "function updatePosition() {\n\t \n\t\tbox.css({\n\t\t\t'width': ($(element).width() - 2) + 'px',\n\t\t\t'top': ($(element).position().top + $(element).height()) + 'px',\n\t\t\t'left': $(element).position().left +'px'\n\t\t});\n\t}", "function tb_add_clipping_to_workspace(){\n $(\"#TB_window input.link\").link_button();\n\t$(\"#project_name\").clear_search();\n $(\"form.new_clipping\").select_project_to_add();\n}", "function addLinesAcrossLeftRight() {\n\n\tconst corners = [\n\t\t{\n\t\t\tx: 0, \n\t\t\ty: 0\n\t\t},\n\t\t{\n\t\t\tx: editorSize, \n\t\t\ty: 0\n\t\t},\n\t\t{\n\t\t\tx: editorSize, \n\t\t\ty: editorSize\n\t\t},\n\t\t{\n\t\t\tx: 0, \n\t\t\ty: editorSize\n\t\t},\n\t];\n\n\tcorners.forEach(linesAcrossLRForCorner);\n}", "function recreateMapClones() {\n\t\tjQuery('#mapgyver_holder').removeClass(\"mapisready\");\n\t\t\tvar mhod = jQuery('#mapgyver_holder .originalmap .originalmap-inner');\n\t\t\tmhod.find('.gmnoprint, .gmnoscreen, .gmn, .gm-style, .gm-style-mtc').each(function() {\n\t\t\t\tTweenLite.set(jQuery(this),{transformPerspective:7000,rotationY:0,rotationZ:0});\n\t\t\t})\n\t\t\tfor (var i=0;i<5;i++) {\n\t\t\t\tvar im = jQuery('#overlaymap'+i+' .mapgyver-innermap');\n\t\t\t\tim.html(\"\").css({width:im.closest('#mapgyver_holder').width()});\n\t\t\t\tmhod.clone().appendTo(im);\n\t\t\t}\n}", "function displaceRight() {\n\tvar currentRight = $(pictureArray[rightPic]).offset().left;\n\t$(pictureArray[rightPic]).offset({left: currentRight - slideshowWidth});\n\t\n\tleftPic = (leftPic + pictureArray.length - 1) % pictureArray.length;\n\t\n\trightPic = (rightPic + pictureArray.length - 1) % pictureArray.length;\n}", "addNewCardAddressForm(_el){\n let _el2 = _el.parents('.drop').find('.address-drop-area');\n _el2 = _el2[_el2.length - 1]; //find last address\n $(`<section class=\"drop-area address-drop-area\">\n <div class=\"drop-area-row address-title-row\"><span><i class=\"fas fa-map-marker-alt\" aria-hidden=\"true\"></i> Address:</span> <button class=\"btn search-address\"><i class=\"fa fa-check\" aria-hidden=\"true\"></i> Search</button> <button class=\"btn clear-address\"><i class=\"fa fa-times\" aria-hidden=\"true\"></i> Clear</button></div>\n <div class=\"selected-address\">\n </div>\n <div class=\"drop-area-row address-row\">\n <input type=\"number\" placeholder=\"#\" class=\"add-num\">\n <input type=\"text\" placeholder=\"Street St.\" class=\"add-street\">\n <input type=\"number\" placeholder=\"Parcel #\" class=\"par-num\" min=\"0\">\n </div>\n <div class=\"drop-area-row address-results-row\"></div>\n <div class=\"owner-array\"></div>\n <div class=\"code-enforcement\"></div>\n </section>`).insertAfter($(_el2)); //add form to end\n _el.hide(); \n }", "function leftWindowToRightLocation() {\n moveForward(15);\n turnRight(90);\n moveForward(50);\n turnRight(90);\n moveForward(7);\n turnRight(90);\n}", "handleRightShiftUpdate($row){\n const node = $row.children(':last')\n node.detach();\n $row.prepend(node); \n }", "function rollUpInfoBox() {\n d3.select('#infobox-top')\n .transition()\n .ease(d3.easePoly)\n .duration(300)\n .style('height', '60px');\n d3.select('#infobox')\n .transition()\n .ease(d3.easePoly)\n .duration(150)\n .style('height', '60px');\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
8 This function returns a string containing the keys (prperty names) of of all the properties on the flower object.
function listKeys() { let keyString = ""; for (let key in flower) { keyString += key + ", "; } return keyString; }
[ "getPropertyKeys() {\n let properties = this.getProperties();\n let propertyKeys = [];\n if (properties) {\n for (var key in properties) {\n if (Object.prototype.hasOwnProperty.call(properties, key)) {\n propertyKeys.push(key);\n }\n }\n }\n propertyKeys = propertyKeys.sort();\n return propertyKeys;\n }", "getProps(){\n let properties = new ValueMap();\n let propWalker = this;\n\n while(propWalker.__type<0x10){\n for(let [k,v] of propWalker.__props){\n properties.set(k,v);\n }\n propWalker = propWalker.getProp(\"__proto__\");\n };\n return properties;\n }", "function toString ()\n{\n let baleString = \"\";\n let fieldNames = Object.keys(PROPERTIES);\n\n // Loop through the fieldNames and build the string \n for (let name of fieldNames)\n {\n baleString += name + \":\" + this[name] +\";\";\n }\n\n return baleString;\n}", "function listAllProperties(o){ \n\tvar objectToInspect; \n\tvar result = [];\n\t\n\tfor(objectToInspect = o; objectToInspect !== null; objectToInspect = Object.getPrototypeOf(objectToInspect)){ \n\t\tresult = result.concat(Object.getOwnPropertyNames(objectToInspect)); \n\t}\n\t\n\treturn result; \n}", "function showProperties(obj) {\n for(let key in obj) {\n if(typeof obj[key] === 'string') {\n console.log(key, obj[key]);\n }\n }\n}", "listFlyweights() {\n const count = Object.keys(flyweights).length;\n console.log(`\\nFlyweightFactory: have ${count} flyweights:`);\n const keys = Object.keys(flyweights);\n keys.forEach((key) => {\n console.log(key);\n });\n }", "function getKeys() {\n for (let data of Object.values(person)) {\n console.log(`${data}`);\n }\n}", "function propertyDescriptors() {\r\n console.log('--------------------- Property Descriptors ---------------------');\r\n\r\n var enber = {\r\n name: {christian: 'Christian', family: 'Bale'},\r\n age: 50\r\n };\r\n\r\n Object.defineProperty(enber, 'fullName', {\r\n get: function getFullName() {\r\n return this.name.family + '; ' + this.name.christian;\r\n },\r\n set: function setFullName(fullName) {\r\n var object = this;\r\n\r\n var names = fullName.split(' '); // ['John', 'Martin', 'Doe'] <<<< 'John Martin Doe'\r\n this.name.family = names.splice(names.length - 1, 1); // 'Doe' <-- ['John', 'Martin', ]\r\n\r\n this.name.christian = names.splice(0, 1);\r\n names.map(function (name) {\r\n object.name.christian = object.name.christian + ' ' + name;\r\n });\r\n }\r\n });\r\n\r\n console.log('enber object\\'s keys:', Object.keys(enber));\r\n console.log('enber object\\'s own property names:', Object.getOwnPropertyNames(enber));\r\n\r\n console.log('full name:', enber.fullName);\r\n console.log('set name...');\r\n enber.fullName = 'Johanns Chrisostomus Wolfgangus Amadeus Mozart';\r\n console.log('full name:', enber.fullName);\r\n }", "function objectKeys(object) { Object.keys(object) }", "function stringifyProperties(properties) {\n var result = [];\n var _loop_1 = function (name, value) {\n if (value != null) {\n if (Array.isArray(value)) {\n value.forEach(function (value) {\n value && result.push(styleToString(name, value));\n });\n }\n else {\n result.push(styleToString(name, value));\n }\n }\n };\n for (var _i = 0, properties_1 = properties; _i < properties_1.length; _i++) {\n var _a = properties_1[_i], name = _a[0], value = _a[1];\n _loop_1(name, value);\n }\n return result.join(';');\n}", "function fruitProperties(fruitName) {\r\n if (typeof fruitName !== 'object' || fruitName === undefined) {\r\n console.error('Your fruit has not been declared');\r\n } else if (fruitName.hasOwnProperty('color') &&\r\n fruitName.hasOwnProperty('shape') &&\r\n fruitName.hasOwnProperty('price')) {\r\n console.log('color: ' + fruitName.color);\r\n console.log('shape: ' + fruitName.shape);\r\n console.log('price: ' + fruitName.price);\r\n } else {\r\n console.log('Your fruit does not have all properties');\r\n }\r\n}", "function getProjectNames(theObj){\n\n\t\t\tvar theProjNamesArray = []; // empty array to hold projects\n\n\t\t\tfor (var proj in theObj){ // loop through object props\n\t\t\t\tif (theObj.hasOwnProperty(proj)){\n\t\t\t\t\ttheProjNamesArray.push(String(proj)); // add props to array\n\t\t\t\t}\n\t\t\t} // end loop through object props\n\n\t\t\treturn theProjNamesArray; // return array\n\n\t\t} // ----- End getProjectNames -----", "function keys(obj) {\n //return Object.keys(obj);\n var output = [];\n each(obj, function(elem, key) {\n output.push(key);\n });\n return output;\n}", "function propiedades(){\r\n\tres = \"\";\r\n\tfor (prop in document)\r\n\t\tres += prop +' ';\r\n\talert(res);\r\n\t}", "getTourNames(){\n return this.tourMap.keys();\n }", "function keysToString(object) {\n // create empty array to collect data \n let keyArray = [];\n for( let key in object){\n// using for in loop push the keys onto the empty array \n keyArray.push(key);\n }\n// use the .join method to convert the array to a string and use ' ' to indicate spaces between words \n return keyArray.join(' '); \n}", "function defineObjectKeys(){\n Object.keys = (function() {\n 'use strict';\n var hasOwnProperty = Object.prototype.hasOwnProperty,\n hasDontEnumBug = !({ toString: null }).propertyIsEnumerable('toString'),\n dontEnums = [\n 'toString',\n 'toLocaleString',\n 'valueOf',\n 'hasOwnProperty',\n 'isPrototypeOf',\n 'propertyIsEnumerable',\n 'constructor'\n ],\n dontEnumsLength = dontEnums.length;\n\n return function(obj) {\n if (typeof obj !== 'object' && (typeof obj !== 'function' || obj === null)) {\n throw new TypeError('Object.keys called on non-object');\n }\n\n var result = [], prop, i;\n\n for (prop in obj) {\n if (hasOwnProperty.call(obj, prop)) {\n result.push(prop);\n }\n }\n\n if (hasDontEnumBug) {\n for (i = 0; i < dontEnumsLength; i++) {\n if (hasOwnProperty.call(obj, dontEnums[i])) {\n result.push(dontEnums[i]);\n }\n }\n }\n return result;\n };\n }());\n}", "visitObject_properties(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "function getPropertyCount(obj) {\n\t\tvar count = 0,\n\t\t\tkey;\n\n\t\tfor (key in obj) {\n\t\t\tif (obj.hasOwnProperty(key)) {\n\t\t\t\tcount++;\n\t\t\t\tconsole.log(obj[key]);\n\t\t\t}\n\t\t}\n\t\treturn count;\n\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
function replace(string,text,by) Thay the ky tu trong mot chuoi
function replace(pString, pText, by) { try { var strLength = pString.length, txtLength = pText.length; if ((strLength == 0) || (txtLength == 0)) return pString; var vIndex = pString.indexOf(pText); while (vIndex >= 0) { pString = pString.replace(pText, by); vIndex = pString.indexOf(pText); } //End While } catch (e) {} return pString; }
[ "function replace(string,text,by) {\n // Replaces text with by in string\n\t var i = string.indexOf(text);\n\t var newstr = '';\n\t if ((!i) || (i == -1)) return string;\n\t newstr += string.substring(0,i) + by;\n\n\t if (i+text.length < string.length)\n\t\t newstr += replace(string.substring(i+text.length,string.length),text,by);\n\t \n\t return newstr;\n }", "function replaceThe(str) {\n\tconst a = [];\n\tfor (let i = 0; i < str.split(\" \").length; i++) {\n\t\tif (str.split(\" \")[i] === \"the\" && /[aeiou]/.test(str.split(\" \")[i+1][0])) {\n\t\t\ta.push(\"an\");\n\t\t} else if (str.split(\" \")[i] === \"the\" && /([b-df-hj-np-tv-z])/.test(str.split(\" \")[i+1][0])) {\n\t\t\ta.push(\"a\");\n\t\t} else a.push(str.split(\" \")[i])\n\t}\n\treturn a.join(\" \");\n}", "function owofied(sentence) {\n\tconst a = sentence.replace(/i/g, \"wi\");\n\tconst b = a.replace(/e/g, \"we\");\n\treturn b + \" owo\";\n}", "function replaceApici(text,charToSubst)\n{\n\t/*if (!charToSubst) return text;\n\t// Trasforma \" in ''\n\tif (charToSubst==\"\\\"\")\n\t\treturn strReplace(text,\"\\\"\",\"''\");\n\t// Trasforma ' in \"\n\telse\n\t\treturn strReplace(text,\"'\",\"\\\"\");*/\n\t\t\n\tif (!charToSubst) return text;\n\t// Trasforma \" in ''\n\tif (charToSubst==\"\\\"\")\n\t\treturn strReplace(text,\"\\\"\",\"''\");\n\t// Trasforma ' in \"\n\telse\n\t\treturn strReplace(text,\"'\",\"''\");\n\t\n\n\t\t\n\t\t\n}", "function strReplace(text,toBeReplaced,toReplace,substituteFirst)\n{\n\tvar newToBeReplaced=\"\";\n\t\n\tfor(var i=0;i<toBeReplaced.length;i++)\n\t{\n\t\t// Elabora caratteri riservati dell'oggetto RegExp\n\t\tswitch (toBeReplaced.substr(i,1))\n\t\t{\n\t\t\tcase \"^\":\n\t\t\tcase \"$\":\n\t\t\tcase \"*\":\n\t\t\tcase \"+\":\n\t\t\tcase \"?\":\n\t\t\tcase \"[\":\n\t\t\tcase \"]\":\n\t\t\tcase \"(\":\n\t\t\tcase \")\":\n\t\t\tcase \"|\": \n\t\t\t\tnewToBeReplaced+=\"\\\\\"+toBeReplaced.substr(i,1);\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\texcape=/\\\\/g;\n\t\t\t\tnewToBeReplaced=toBeReplaced.replace(excape,\"\\\\\\\\\");\t\n\t\t}\t\n\t}\n\t\n\tif (newToBeReplaced==\"\")\n\t\tnewToBeReplaced=toBeReplaced;\n\t\n\tif (substituteFirst)\n\t\trg=new RegExp(newToBeReplaced)\n\telse\n\t\trg=new RegExp(newToBeReplaced,\"g\");\n\t\n\treturn text.replace(rg,toReplace);\n}", "function str_replace(haystack, needle, replacement) {var temp = haystack.split(needle);return temp.join(replacement);}", "function replaceAll(str, term, replacement) {\n return str.replace(new RegExp(escapeRegExp(term), 'g'), replacement);\n }", "function replaceString(str, findTok, replaceTok, isOne) {\n\n pos = str.indexOf(findTok);\n valueRet = \"\";\n if (pos == -1) {\n return str;\n }\n valueRet += str.substring(0,pos) + replaceTok;\n if (!isOne && ( pos + findTok.length < str.length)) {\n valueRet += replaceString(str.substring(pos + findTok.length, str.length), findTok, replaceTok);\n } else {\n\t\tvalueRet += str.substring(pos + findTok.length, str.length)\n\t}\n\n return valueRet;\n}", "function replaceS() {\n strings[string.indexOf(\"words\")] = \"string\";\n}", "function jsReplace(inString, find, replace) {\n\n var outString = \"\";\n\n if (!inString) {\n return \"\";\n }\n\n // REPLACE ALL INSTANCES OF find WITH replace\n if (inString.indexOf(find) != -1) {\n // SEPARATE THE STRING INTO AN ARRAY OF STRINGS USING THE VALUE IN find\n t = inString.split(find);\n\n // JOIN ALL ELEMENTS OF THE ARRAY, SEPARATED BY THE VALUE IN replace\n\t\t\n return (t.join(replace));\n }\n else {\n return inString;\n }\n}", "function SearchAndReplace(arr,oldWord,newWord) {\n var t = '';\n var text = arr.split(' ');\n for (let i = 0; i < text.length; i++) {\n if (text[i] == oldWord) {\n t = text[i].charAt(0);\n if (t == text[i].charAt(0).toUpperCase()) {\n t = newWord.charAt(0).toUpperCase()\n t += newWord.slice(1)\n }else{\n t = newWord.charAt(0).toLowerCase()\n t += newWord.slice(1)\n }\n text[i] = t\n }\n }\n return text.join(' ')\n}", "function leetspeak(text) {\n regularText = text;\n\n //The global modifier is used to change more than just the first occurence\n regularText = regularText.toUpperCase();\n regularText = regularText.replace(/A/g, '4');\n regularText = regularText.replace(/E/g, '3');\n regularText = regularText.replace(/G/g, '6');\n regularText = regularText.replace(/I/g, '1');\n regularText = regularText.replace(/O/g, '0');\n regularText = regularText.replace(/S/g, '5');\n regularText = regularText.replace(/T/g, '7');\n\n console.log(regularText);\n\n}", "function replaceAt(str, ind, charac) {\n return str.substr(0, ind) + charac + str.substr(ind + charac.length);\n }", "function SUBSTITUTE(text, old_text, new_text, occurrence) {\n if (!text || !old_text || !new_text) {\n return text;\n } else if (occurrence === undefined) {\n return text.replace(new RegExp(old_text, 'g'), new_text);\n } else {\n var index = 0;\n var i = 0;\n while (text.indexOf(old_text, index) > 0) {\n index = text.indexOf(old_text, index + 1);\n i++;\n if (i === occurrence) {\n return text.substring(0, index) + new_text + text.substring(index + old_text.length);\n }\n }\n }\n}", "function replaceInString(data, search, replace) {\n if (Array.isArray(search)) {\n for (var i=0; i<search.length; i++) {\n data = data.replaceAll(search[i], replace[i]);\n }\n return data;\n } else {\n return data.replaceAll(search, replace);\n }\n}", "function REPLACE(text, position, length, new_text) {\n\n if (ISERROR(position) || ISERROR(length) || typeof text !== 'string' || typeof new_text !== 'string') {\n return error$2.value;\n }\n return text.substr(0, position - 1) + new_text + text.substr(position - 1 + length);\n}", "function replaceAll(Source,stringToFind,stringToReplace){\n var temp = Source;\n var index = temp.indexOf(stringToFind);\n while(index != -1){\n temp = temp.replace(stringToFind,stringToReplace);\n index = temp.indexOf(stringToFind);\n }\n return temp;\n}", "function replaceWord(word, thisChar){\r\n\tthisChar.dialogue[thisChar.diaCounter]=thisChar.dialogue[thisChar.diaCounter].replace(\"[\"+word+\"]\", eval(\"player.\"+word));\r\n}", "function insert_a(text, script) {\r\n const a = (script == Script.CYRL) ? '\\u0430' : 'a'; // roman a or cyrl a\r\n text = text.replace(new RegExp(`([ක-ෆ])([^\\u0DCF-\\u0DDF\\u0DCA${a}])`, 'g'), `$1${a}$2`);\r\n text = text.replace(new RegExp(`([ක-ෆ])([^\\u0DCF-\\u0DDF\\u0DCA${a}])`, 'g'), `$1${a}$2`);\r\n return text.replace(/([ක-ෆ])$/g, `$1${a}`); // conso at the end of string not matched by regex above\r\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Register controllers so they can be accessed in the property 'controllers' a literal object with all userdefined controllers. (key = name of controller, value = user defined controller class)
register(...controllers) { for (let controller of controllers) { if (controller.name === 'DEFAULT') { throw new Error('"DEFAULT" is a reserved controller name, use a different name.'); } this.controllers[controller.name] = new controller(this); } this.controllers['DEFAULT'] = new DefaultController_1.DefaultController(this); }
[ "function initControllers() {\n CONTROLLERS.forEach(loadController)\n }", "function initializeControllers() {\n let instances = [];\n controllers.forEach(x => {\n instances.push(new x.Controller());\n });\n return instances;\n}", "function registerRouter(controllers, router) {\n if (!controllers)\n controllers = initializeControllers();\n if (!router)\n router = getMiddleware();\n controllers.forEach(x => x.registerRouter(router));\n return controllers;\n}", "function Run_CtrlRegistration( config ) {\n\tif (Registration_Controller)\n\t\tRegistration_Controller( config );\n}", "getConnectedControllers() {\n\n var _thisSvc = this;\n\n var controllerList = [];\n\n for(var controllerId in _thisSvc.controllerInfoCollection) {\n\n var controllerInfo =\n _thisSvc.controllerInfoCollection[controllerId];\n\n controllerList.push({\n controllerId: controllerInfo.controllerId,\n name: controllerInfo.name\n });\n }\n\n return controllerList;\n }", "function initializeControllers(world) {\n // Tracking controller state changes.\n function onSelectStart() {\n this.userData.isSelecting = true;\n }\n\n function onSelectEnd() {\n this.userData.isSelecting = false;\n }\n\n function onConnect(event) {\n this.add(buildController(event.data));\n }\n\n // Added this function to ensure we don't leak memory when repeatedly adding\n // and removing controllers, piling up unused geometry/materials for the selection pointer child.\n function onRemove() {\n let child = this.children[0];\n if (child) {\n this.remove(child);\n child.geometry.dispose();\n child.material.dispose();\n }\n }\n\n // Wire up left and reight controllers, and add them to the user's local coordinate space\n // so they follow as we teleport around the scene.\n controller1 = world.renderer.xr.getController(0);\n controller1.addEventListener('selectstart', onSelectStart);\n controller1.addEventListener('selectend', onSelectEnd);\n controller1.addEventListener('connected', onConnect); \n controller1.addEventListener('disconnected', onRemove);\n world.clientSpace.add(controller1);\n\n controller2 = world.renderer.xr.getController(1);\n controller2.addEventListener('selectstart', onSelectStart);\n controller2.addEventListener('selectend', onSelectEnd);\n controller2.addEventListener('connected', onConnect);\n controller2.addEventListener('disconnected', onRemove);\n world.clientSpace.add(controller2);\n\n // The XRControllerModelFactory will automatically fetch controller models\n // that match what the user is holding as closely as possible. The models\n // should be attached to the object returned from getControllerGrip in\n // order to match the orientation of the held device.\n const controllerModelFactory = new XRControllerModelFactory();\n\n // Load appropriate display model into the \"grip\" group for each controller,\n // and add them to the user's local coordinate space so they follow as we teleport.\n controllerGrip1 = world.renderer.xr.getControllerGrip(0);\n controllerGrip1.add(\n controllerModelFactory.createControllerModel(controllerGrip1)\n );\n world.clientSpace.add(controllerGrip1);\n\n controllerGrip2 = world.renderer.xr.getControllerGrip(1);\n controllerGrip2.add(\n controllerModelFactory.createControllerModel(controllerGrip2)\n );\n world.clientSpace.add(controllerGrip2);\n}", "function Run_CtrlAddAction( config ) {\n\tif (AddAction_Controller)\n\t\tAddAction_Controller( config );\n}", "function controller_by_user(){\n\t\ttry {\n\t\t\t\n\t\t\t\n\t\t} catch(e){\n\t\t\tconsole.log(\"error: page jokes_singles => custom controller\");\n\t\t\tconsole.log(e);\n\t\t}\n\t}", "function registerForDeviceActions() {\r\n /**\r\n * This creates an object of the Actions class defined in the toolkit \r\n * for the specific protocol\r\n */\r\n let driverActionsObject = toolkit.object.actions(lit.PROTOCOL);\r\n // Register action create with a custom validator and completor function\r\n /**\r\n * While registering for a create action, the assumption here for a generic \r\n * framework is to assume that the driver already knows about the device \r\n * type. To know how to use custom driver specific types refer to \r\n * Chapter 12: Device Types from IAP/MQ spec\r\n */\r\n driverActionsObject.register(\r\n toolkit.spec.ACTION_CREATE,\r\n createAction.createActionValidator,\r\n null,\r\n createAction.createActionCompletor\r\n );\r\n\r\n driverActionsObject.register(\r\n toolkit.spec.ACTION_UPDATE,\r\n null,\r\n null,\r\n updateAction.updateActionCompletor\r\n );\r\n\r\n /**\r\n * Register action provision with a custom validator, executor and \r\n * completor functions\r\n */\r\n driverActionsObject.register(\r\n toolkit.spec.ACTION_PROVISION,\r\n provisionAction.provisionActionValidator,\r\n provisionAction.provisionActionExecutor,\r\n provisionAction.provisionActionCompletor\r\n );\r\n\r\n driverActionsObject.register(\r\n toolkit.spec.ACTION_DEPROVISION,\r\n deprovisionAction.deprovisionActionValidator,\r\n deprovisionAction.deprovisionActionExecutor,\r\n deprovisionAction.deprovisionActionCompletor\r\n );\r\n\r\n driverActionsObject.register(\r\n toolkit.spec.ACTION_TEST,\r\n testAction.testActionValidator,\r\n testAction.testActionExecutor,\r\n testAction.testActionCompletor\r\n );\r\n\r\n // Register action delete with a custom validator and completor function\r\n driverActionsObject.register(\r\n toolkit.spec.ACTION_DELETE,\r\n deleteAction.deleteActionValidator,\r\n null,\r\n deleteAction.deleteActionCompletor\r\n );\r\n\r\n driverActionsObject.register(\r\n toolkit.spec.ACTION_REPLACE,\r\n replaceAction.replaceActionValidator,\r\n replaceAction.replaceActionExecutor,\r\n replaceAction.replaceActionCompletor\r\n );\r\n\r\n driverActionsObject.register(\r\n toolkit.spec.ACTION_LOAD,\r\n loadAction.loadActionValidator,\r\n loadAction.loadActionExecutor,\r\n loadAction.loadActionCompletor\r\n );\r\n\r\n /**\r\n * Register all actions and provide the default config object and \r\n * status object template with constraints to mandate properties in \r\n * both the objects.\r\n */\r\n let error = toolkit.object.register(\r\n toolkit.spec.OBJECT_TYPE_DEVICE,\r\n driverActionsObject,\r\n toolkit.spec.Device_Config_Template,\r\n toolkit.spec.Device_Config_Constraints,\r\n toolkit.spec.Device_Status_Template,\r\n toolkit.spec.DEVICE_STATES,\r\n false\r\n );\r\n\r\n return error;\r\n}", "function controller_by_user(){\n\t\ttry {\n\t\t\t\n\t\t\t\n\t\t} catch(e){\n\t\t\tconsole.log(\"error: page dashboard => custom controller\");\n\t\t\tconsole.log(e);\n\t\t}\n\t}", "constructor({ controllerMessenger, name, allowedActions, allowedEvents, }) {\n this.controllerMessenger = controllerMessenger;\n this.controllerName = name;\n this.allowedActions = allowedActions || null;\n this.allowedEvents = allowedEvents || null;\n }", "register() {\n this._container.instance('expressApp', require('express')())\n\n //TODO: add Socket.io here @url https://trello.com/c/KFCXzYom/71-socketio-adapter\n\n this._container.register('httpServing', require(FRAMEWORK_PATH + '/lib/HTTPServing'))\n .dependencies('config', 'expressApp')\n .singleton()\n\n this._container.instance('expressRouterFactory', () => {\n return require('express').Router()\n })\n\n this._container.register('RoutesResolver', require(FRAMEWORK_PATH + '/lib/RoutesResolver'))\n .dependencies('logger', 'app', 'expressRouterFactory')\n\n this._container.register('httpErrorHandler', require(FRAMEWORK_PATH + '/lib/HTTPErrorHandler'))\n .dependencies('logger')\n .singleton()\n\n //TODO: add WS the serving @url https://trello.com/c/KFCXzYom/71-socketio-adapter\n }", "registerActions() {\n this.registerAction(\"read\", new read_action_1.default());\n this.registerAction(\"write\", new write_action_1.default());\n }", "function controller_by_user() {\n try {\n\n\n } catch (e) {\n }\n }", "setupController(controller, model) {\n this._super(controller, model);\n\n //Cannot rely on the native `init` callback of the controller because the model is not available before controller initialization\n this.controller.activate();\n }", "function WindowController () {\n\tthis.init();\n}", "function controller_by_user(){\n\t\ttry {\n\t\t\t\n//debug: all data\nconsole.log(data_jokess);\n\t\t\t\n\t\t} catch(e){\n\t\t\tconsole.log(\"error: page jokes => custom controller\");\n\t\t\tconsole.log(e);\n\t\t}\n\t}", "function GenericController(vrGamepad){return _super.call(this,vrGamepad)||this;}", "get isStrictControllers() {\n return this[kStrictControllers];\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
generate a tick at every multiple of divisor, stop at max width
function generate_ticks(multiple, divisor, suffix) { var result = []; var t = 0; while (true) { result.push([Math.round(availableSpace * t / totalDuration), t, t / divisor + suffix]); if (t > totalDuration) { break; } t += multiple * divisor; } return result; }
[ "static Repeat(value, length) {\n return value - Math.floor(value / length) * length;\n }", "function generate(min, max, capacity, options) {\n\t\tvar timeOpts = options.time;\n\t\tvar minor = timeOpts.unit || determineUnitForAutoTicks(timeOpts.minUnit, min, max, capacity);\n\t\tvar major = determineMajorUnit(minor);\n\t\tvar stepSize = helpers.valueOrDefault(timeOpts.stepSize, timeOpts.unitStepSize);\n\t\tvar weekday = minor === 'week' ? timeOpts.isoWeekday : false;\n\t\tvar majorTicksEnabled = options.ticks.major.enabled;\n\t\tvar interval = INTERVALS[minor];\n\t\tvar first = moment(min);\n\t\tvar last = moment(max);\n\t\tvar ticks = [];\n\t\tvar time;\n\n\t\tif (!stepSize) {\n\t\t\tstepSize = determineStepSize(min, max, minor, capacity);\n\t\t}\n\n\t\t// For 'week' unit, handle the first day of week option\n\t\tif (weekday) {\n\t\t\tfirst = first.isoWeekday(weekday);\n\t\t\tlast = last.isoWeekday(weekday);\n\t\t}\n\n\t\t// Align first/last ticks on unit\n\t\tfirst = first.startOf(weekday ? 'day' : minor);\n\t\tlast = last.startOf(weekday ? 'day' : minor);\n\n\t\t// Make sure that the last tick include max\n\t\tif (last < max) {\n\t\t\tlast.add(1, minor);\n\t\t}\n\n\t\ttime = moment(first);\n\n\t\tif (majorTicksEnabled && major && !weekday && !timeOpts.round) {\n\t\t\t// Align the first tick on the previous `minor` unit aligned on the `major` unit:\n\t\t\t// we first aligned time on the previous `major` unit then add the number of full\n\t\t\t// stepSize there is between first and the previous major time.\n\t\t\ttime.startOf(major);\n\t\t\ttime.add(~~((first - time) / (interval.size * stepSize)) * stepSize, minor);\n\t\t}\n\n\t\tfor (; time < last; time.add(stepSize, minor)) {\n\t\t\tticks.push(+time);\n\t\t}\n\n\t\tticks.push(+time);\n\n\t\treturn ticks;\n\t}", "function maxTickLength() {\n\treturn(0.1) // Default is 1 hour which is just arbitrarily large\n}", "get stepWidth() {\n return Math.floor(this.width / this.step) + 1;\n }", "generateSticks() {\n let numberOfSticks = Math.ceil(this.steps);\n for(let i = 0; i <= numberOfSticks; i++)\n new Stick();\n }", "function tickCount() {\n\t\t\tif (svgWidth <= 500) { \n\t\t\t\tbottomAxis.ticks(5);\n\t\t\t\tleftAxis.ticks(5);\n\t\t\t\t}\n\t\t\telse {\n\t\t\t\tbottomAxis.ticks(10);\n\t\t\t\tleftAxis.ticks(10);\n\t\t\t}\n\t\t}", "timeProcess(itself=(cov_50nz68pmo.b[1][0]++,this)){cov_50nz68pmo.f[3]++;cov_50nz68pmo.s[7]++;// define begin cooldown\ninitTime=new Date().getTime();// function to send clockBar instant to setInterval\nfunction sendTosetInterval(){cov_50nz68pmo.f[4]++;cov_50nz68pmo.s[8]++;return itself;}// define time cooldown\nvar process=(cov_50nz68pmo.s[9]++,setInterval(function(){cov_50nz68pmo.f[5]++;// get clockBar instant\nlet itself=(cov_50nz68pmo.s[10]++,sendTosetInterval());// get current time\nvar now=(cov_50nz68pmo.s[11]++,new Date().getTime());// find the distance between now and the init time\nvar distance=(cov_50nz68pmo.s[12]++,now-initTime);cov_50nz68pmo.s[13]++;if(distance>limited){cov_50nz68pmo.b[2][0]++;cov_50nz68pmo.s[14]++;drawFluid('0%');cov_50nz68pmo.s[15]++;clearInterval(process);cov_50nz68pmo.s[16]++;itself.setTimeout('true');}else{cov_50nz68pmo.b[2][1]++;}// set percentage of time cooldown\ncov_50nz68pmo.s[17]++;fracTime=Math.round(100-distance/limited*100);// draw percentage to page\ncov_50nz68pmo.s[18]++;drawFluid(fracTime+'%');},timeUpdate));}", "function everyinterval(n) {\n if ((myGameArea.frameNo / n) % 1 === 0) {\n return true;\n }\n return false;\n}", "function howManyStickers(n) {\n\treturn 6 * n * n;\n}", "function boxSeq(step) {\n\tlet x = 0;\n\tlet counter = step;\n\t\n\tfor (let i = 1; i <= step; i++) {\n\t\t\tif (step <= 0) {\n\t\t\tx = 0;\n\t\t} else if (counter % 2 === 1) {\n\t\t\tx += 3;\n\t\t\tcounter--;\n\t\t} else if (counter % 2 === 0) {\n\t\t\tx -= 1;\n\t\t\tcounter--;\n\t\t}\n\t}\n\treturn x;\n}", "function rawMultiplier(componentCount){\r\n if(this.componentCount >= 6){\r\n return .3;\r\n }\r\n else{ \r\n return 0.225;\r\n }\r\n \r\n}", "function ssx(n){\n\treturn n % spriteSheetSizeX;\n}", "function blockTicks (d) {\n const k = (d.end - d.start) / d.len\n return range(0, d.len, conf.ticks.spacing).map((v, i) => {\n return {\n angle: v * k + d.start,\n label: displayLabel(v, i)\n }\n })\n }", "hormonic(n) {\n var value = 0;\n\n while (n > 0) {\n value = value + (1 / n);\n n--\n }\n console.log(' this is the final hormonic value ' + value)\n }", "function _drawSequenceScale(paper, x, l, w, c, scaleColors)\n{\n var sequenceScaleY = c + 20;\n var i = 0; // loop variable\n\n paper.path(\"M\" + x + \" \" + (sequenceScaleY + 6) +\n \"L\" + x + \" \" + sequenceScaleY +\n \"L\" + (x + scaleHoriz(l, w, l)) + \" \" + sequenceScaleY +\n \"L\" + (x + scaleHoriz(l, w, l)) + \" \" + (sequenceScaleY + 6))\n .attr({\"stroke\": scaleColors[0], \"stroke-width\": 1});\n\n // sequence scale minor ticks\n for (i = 50; i < l; i += 100) {\n paper.path(\"M\" + (x + scaleHoriz(i, w, l)) + \" \" + sequenceScaleY +\n \"L\" + (x + scaleHoriz(i, w, l)) + \" \" + (sequenceScaleY + 2))\n .attr({\"stroke\": scaleColors[0], \"stroke-width\": 1});\n }\n\n // sequence scale major ticks\n for (i = 0; i < l; i += 100) {\n paper.path(\"M\" + (x + scaleHoriz(i, w, l)) + \" \" + sequenceScaleY +\n \"L\" + (x + scaleHoriz(i, w, l)) + \" \" + (sequenceScaleY + 4))\n .attr({\"stroke\": scaleColors[0], \"stroke-width\": 1});\n }\n\n // sequence scale labels\n for (i = 0; i < l; i += 100) {\n if ((l < 1000) || ((i % 500) == 0)) {\n if (scaleHoriz(l - i, w, l) > 30) {\n paper.text(x + scaleHoriz(i, w, l), sequenceScaleY + 16, i)\n .attr({\"text-anchor\": \"middle\", \"fill\": scaleColors[1], \"font-size\": \"11px\", \"font-family\": \"sans-serif\"});\n }\n }\n }\n\n paper.text(x + scaleHoriz(l, w, l), sequenceScaleY + 16, l + \" aa\")\n .attr({\"text-anchor\": \"middle\", \"fill\": scaleColors[1], \"font-size\": \"11px\", \"font-family\": \"sans-serif\"});\n\n}", "function multiplesOfSix() {\n let count = 6\n while (count <= 60000) {\n if (count % 6 == 0) {\n console.log(count)\n }\n count++\n }\n}", "function scaleGDP(x) {\nreturn x/1000000000;\n}", "function fiveMultiples(arr,start)\r\n{\r\n \r\n if((start*5)<=100) // creating multiples of 5 till '100'\r\n {\r\n \r\n arr.push(start*5);\r\n \r\n return fiveMultiples(arr,start+1); //recursive loop to keep creating multiples of 5 \r\n }\r\n\r\n else\r\n {\r\n return arr;\r\n }\r\n \r\n}", "function threshTicks() {\n d3.select(\"#thresh-slider\").selectAll(\"text\").remove();\n // Starting coordinates for tick marks\n var startTransX = 22;\n var startTransY = 70;\n // Tick mark increment amount\n var incr = 2;\n for (var i = minVal; i <= maxVal; i += incr) {\n thresh.append(\"text\")\n .attr(\"class\", \"label\")\n .text((Math.round(i) * 2).toString())\n .attr(\"font-size\", \"11px\")\n .attr(\"transform\", \"translate(\" + startTransX + \",\" + startTransY + \")\")\n startTransX += (x.range()[1] / ((maxVal - minVal) / 2));\n }\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
REQUETES UTILSATEUR : Onglet : Application de profil TAPEZ ICI LE CODE DE LA REQUETE D'INSERTION
function User_Insert_Application_de_profil_Lot_s__5(Compo_Maitre) { /* ***** INFOS ****** Nbr d'esclaves = 2 Id dans le tab: 15; simple Nbr Jointure: 1; Joint n° 0 = article,lo_article,ar_numero Id dans le tab: 16; simple Nbr Jointure: PAS DE JOINTURE; ****************** */ var Table="lot"; var CleMaitre = TAB_COMPO_PPTES[12].NewCle; var NomCleMaitre = DePrefixerChamp(Compo_Maitre.getCle()); /* COMPOSANT LISTE AVEC JOINTURE SIMPLE */ var lo_article=GetValAt(15); if (lo_article=="-1") lo_article="null"; if (!ValiderChampsObligatoire(Table,"lo_article",TAB_GLOBAL_COMPO[15],lo_article,true)) return -1; var lo_lot=GetValAt(16); if (!ValiderChampsObligatoire(Table,"lo_lot",TAB_GLOBAL_COMPO[16],lo_lot,false)) return -1; if (!ValiderChampsType(Table,"lo_lot",TAB_GLOBAL_COMPO[16],lo_lot)) return -1; var Req="insert into "+Table+" "; var TabInsertionEnPlus=new Array(); Req+="("+NomCleMaitre+",lo_applique,lo_article,lo_lot"+(TabInsertionEnPlus.length!=0?","+TabInsertionEnPlus[0]:"")+")"; Req+=" values ("+CleMaitre+","+TAB_COMPO_PPTES[3].NewCle+","+lo_article+","+(lo_lot=="" ? "null" : "'"+ValiderChaine(lo_lot)+"'" )+""+(TabInsertionEnPlus.length!=0?","+TabInsertionEnPlus[1]:"")+")"; if (pgsql_update(Req)==0) alert("Echec lors de l'insertion"); return CleMaitre; }
[ "function User_Insert_Codes_postaux_Codes_postaux0(Compo_Maitre)\n{\n\n/*\n***** INFOS ******\n\nNbr d'esclaves = 3\n\nId dans le tab: 203;\nsimple\nNbr Jointure: PAS DE JOINTURE;\n\nId dans le tab: 204;\nsimple\nNbr Jointure: PAS DE JOINTURE;\n\nId dans le tab: 208;\ncomplexe\nNbr Jointure: 2;\n Joint n° 0 = communecp,cp_numero,mc_codepostal\n Joint n° 1 = commune,mc_commune,co_numero\n\n******************\n*/\n\n var Table=\"codepostal\";\n var CleMaitre = TAB_COMPO_PPTES[200].NewCle;\n var NomCleMaitre = DePrefixerChamp(Compo_Maitre.getCle());\n var cp_code=GetValAt(203);\n if (!ValiderChampsObligatoire(Table,\"cp_code\",TAB_GLOBAL_COMPO[203],cp_code,false))\n \treturn -1;\n if (!ValiderChampsType(Table,\"cp_code\",TAB_GLOBAL_COMPO[203],cp_code))\n \treturn -1;\n var cp_bureau=GetValAt(204);\n if (!ValiderChampsObligatoire(Table,\"cp_bureau\",TAB_GLOBAL_COMPO[204],cp_bureau,false))\n \treturn -1;\n if (!ValiderChampsType(Table,\"cp_bureau\",TAB_GLOBAL_COMPO[204],cp_bureau))\n \treturn -1;\n var Req=\"insert into \"+Table+\" \";\nvar TabInsertionEnPlus=new Array();\n Req+=\"(\"+NomCleMaitre+\",cp_code,cp_bureau\"+(TabInsertionEnPlus.length!=0?\",\"+TabInsertionEnPlus[0]:\"\")+\")\";\n Req+=\" values (\"+CleMaitre+\",\"+(cp_code==\"\" ? \"null\" : \"'\"+ValiderChaine(cp_code)+\"'\" )+\",\"+(cp_bureau==\"\" ? \"null\" : \"'\"+ValiderChaine(cp_bureau)+\"'\" )+\"\"+(TabInsertionEnPlus.length!=0?\",\"+TabInsertionEnPlus[1]:\"\")+\")\";\n\n if (pgsql_update(Req)==0)\n\talert(\"Echec lors de l'insertion\");\n\n/* table commune*/\nLstDouble_Exec_Req(GetSQLCompoAt(208),CleMaitre);\nreturn CleMaitre;\n\n}", "function User_Insert_Famille_de_profil_Famille_de_profil0(Compo_Maitre)\n{\n\n/*\n***** INFOS ******\n\nNbr d'esclaves = 3\n\nId dans le tab: 42;\nsimple\nNbr Jointure: PAS DE JOINTURE;\n\nId dans le tab: 43;\nsimple\nNbr Jointure: PAS DE JOINTURE;\n\nId dans le tab: 44;\nsimple\nNbr Jointure: PAS DE JOINTURE;\n\n******************\n*/\n\n var Table=\"typeprofil\";\n var CleMaitre = TAB_COMPO_PPTES[40].NewCle;\n var NomCleMaitre = DePrefixerChamp(Compo_Maitre.getCle());\n var tp_nom=GetValAt(42);\n if (!ValiderChampsObligatoire(Table,\"tp_nom\",TAB_GLOBAL_COMPO[42],tp_nom,false))\n \treturn -1;\n if (!ValiderChampsType(Table,\"tp_nom\",TAB_GLOBAL_COMPO[42],tp_nom))\n \treturn -1;\n var note=GetValAt(43);\n if (!ValiderChampsObligatoire(Table,\"note\",TAB_GLOBAL_COMPO[43],note,false))\n \treturn -1;\n if (!ValiderChampsType(Table,\"note\",TAB_GLOBAL_COMPO[43],note))\n \treturn -1;\n var couleur=GetValAt(44);\n if (!ValiderChampsObligatoire(Table,\"couleur\",TAB_GLOBAL_COMPO[44],couleur,false))\n \treturn -1;\n if (!ValiderChampsType(Table,\"couleur\",TAB_GLOBAL_COMPO[44],couleur))\n \treturn -1;\n var Req=\"insert into \"+Table+\" \";\nvar TabInsertionEnPlus=new Array();\n Req+=\"(\"+NomCleMaitre+\",tp_nom,note,couleur\"+(TabInsertionEnPlus.length!=0?\",\"+TabInsertionEnPlus[0]:\"\")+\")\";\n Req+=\" values (\"+CleMaitre+\",\"+(tp_nom==\"\" ? \"null\" : \"'\"+ValiderChaine(tp_nom)+\"'\" )+\",\"+(note==\"\" ? \"null\" : \"'\"+ValiderChaine(note)+\"'\" )+\",\"+(couleur==null ? \"null\" : \"'\"+ValiderChaine(couleur)+\"'\" )+\"\"+(TabInsertionEnPlus.length!=0?\",\"+TabInsertionEnPlus[1]:\"\")+\")\";\n\n if (pgsql_update(Req)==0)\n\talert(\"Echec lors de l'insertion\");\nreturn CleMaitre;\n\n}", "function User_Insert_Type_de_documents_Type_de_documents0(Compo_Maitre)\n{\n\n/*\n***** INFOS ******\n\nNbr d'esclaves = 3\n\nId dans le tab: 229;\nsimple\nNbr Jointure: PAS DE JOINTURE;\n\nId dans le tab: 230;\nsimple\nNbr Jointure: PAS DE JOINTURE;\n\nId dans le tab: 231;\nsimple\nNbr Jointure: PAS DE JOINTURE;\n\n******************\n*/\n\n var Table=\"typedocument\";\n var CleMaitre = TAB_COMPO_PPTES[227].NewCle;\n var NomCleMaitre = DePrefixerChamp(Compo_Maitre.getCle());\n var to_nom=GetValAt(229);\n if (!ValiderChampsObligatoire(Table,\"to_nom\",TAB_GLOBAL_COMPO[229],to_nom,false))\n \treturn -1;\n if (!ValiderChampsType(Table,\"to_nom\",TAB_GLOBAL_COMPO[229],to_nom))\n \treturn -1;\n var to_description=GetValAt(230);\n if (!ValiderChampsObligatoire(Table,\"to_description\",TAB_GLOBAL_COMPO[230],to_description,false))\n \treturn -1;\n if (!ValiderChampsType(Table,\"to_description\",TAB_GLOBAL_COMPO[230],to_description))\n \treturn -1;\n var note=GetValAt(231);\n if (!ValiderChampsObligatoire(Table,\"note\",TAB_GLOBAL_COMPO[231],note,false))\n \treturn -1;\n if (!ValiderChampsType(Table,\"note\",TAB_GLOBAL_COMPO[231],note))\n \treturn -1;\n var Req=\"insert into \"+Table+\" \";\nvar TabInsertionEnPlus=new Array();\n Req+=\"(\"+NomCleMaitre+\",to_nom,to_description,note\"+(TabInsertionEnPlus.length!=0?\",\"+TabInsertionEnPlus[0]:\"\")+\")\";\n Req+=\" values (\"+CleMaitre+\",\"+(to_nom==\"\" ? \"null\" : \"'\"+ValiderChaine(to_nom)+\"'\" )+\",\"+(to_description==\"\" ? \"null\" : \"'\"+ValiderChaine(to_description)+\"'\" )+\",\"+(note==\"\" ? \"null\" : \"'\"+ValiderChaine(note)+\"'\" )+\"\"+(TabInsertionEnPlus.length!=0?\",\"+TabInsertionEnPlus[1]:\"\")+\")\";\n\n if (pgsql_update(Req)==0)\n\talert(\"Echec lors de l'insertion\");\nreturn CleMaitre;\n\n}", "function User_Insert_Type_de_couche_Type_de_couches0(Compo_Maitre)\n{\n\n/*\n***** INFOS ******\n\nNbr d'esclaves = 4\n\nId dans le tab: 96;\nsimple\nNbr Jointure: PAS DE JOINTURE;\n\nId dans le tab: 97;\nsimple\nNbr Jointure: PAS DE JOINTURE;\n\nId dans le tab: 98;\nsimple\nNbr Jointure: PAS DE JOINTURE;\n\nId dans le tab: 99;\nsimple\nNbr Jointure: PAS DE JOINTURE;\n\n******************\n*/\n\n var Table=\"typecouche\";\n var CleMaitre = TAB_COMPO_PPTES[93].NewCle;\n var NomCleMaitre = DePrefixerChamp(Compo_Maitre.getCle());\n var tc_nom=GetValAt(96);\n if (!ValiderChampsObligatoire(Table,\"tc_nom\",TAB_GLOBAL_COMPO[96],tc_nom,false))\n \treturn -1;\n if (!ValiderChampsType(Table,\"tc_nom\",TAB_GLOBAL_COMPO[96],tc_nom))\n \treturn -1;\n var note=GetValAt(97);\n if (!ValiderChampsObligatoire(Table,\"note\",TAB_GLOBAL_COMPO[97],note,false))\n \treturn -1;\n if (!ValiderChampsType(Table,\"note\",TAB_GLOBAL_COMPO[97],note))\n \treturn -1;\n var couleur=GetValAt(98);\n if (!ValiderChampsObligatoire(Table,\"couleur\",TAB_GLOBAL_COMPO[98],couleur,false))\n \treturn -1;\n if (!ValiderChampsType(Table,\"couleur\",TAB_GLOBAL_COMPO[98],couleur))\n \treturn -1;\n var tc_sansilots=GetValAt(99);\n if (!ValiderChampsObligatoire(Table,\"tc_sansilots\",TAB_GLOBAL_COMPO[99],tc_sansilots,false))\n \treturn -1;\n if (!ValiderChampsType(Table,\"tc_sansilots\",TAB_GLOBAL_COMPO[99],tc_sansilots))\n \treturn -1;\n var Req=\"insert into \"+Table+\" \";\nvar TabInsertionEnPlus=new Array();\n Req+=\"(\"+NomCleMaitre+\",tc_nom,note,couleur,tc_sansilots\"+(TabInsertionEnPlus.length!=0?\",\"+TabInsertionEnPlus[0]:\"\")+\")\";\n Req+=\" values (\"+CleMaitre+\",\"+(tc_nom==\"\" ? \"null\" : \"'\"+ValiderChaine(tc_nom)+\"'\" )+\",\"+(note==\"\" ? \"null\" : \"'\"+ValiderChaine(note)+\"'\" )+\",\"+(couleur==null ? \"null\" : \"'\"+ValiderChaine(couleur)+\"'\" )+\",\"+(tc_sansilots==\"\" ? \"null\" : \"'\"+ValiderChaine(tc_sansilots)+\"'\" )+\"\"+(TabInsertionEnPlus.length!=0?\",\"+TabInsertionEnPlus[1]:\"\")+\")\";\n\n if (pgsql_update(Req)==0)\n\talert(\"Echec lors de l'insertion\");\nreturn CleMaitre;\n\n}", "function User_Insert_Composition_Compositions0(Compo_Maitre)\n{\n\n/*\n***** INFOS ******\n\nNbr d'esclaves = 3\n\nId dans le tab: 121;\nsimple\nNbr Jointure: PAS DE JOINTURE;\n\nId dans le tab: 122;\nsimple\nNbr Jointure: PAS DE JOINTURE;\n\nId dans le tab: 123;\ncomplexe\nNbr Jointure: 1;\n Joint n° 0 = compose,cs_numero,ce_composition\n\n******************\n*/\n\n var Table=\"composition\";\n var CleMaitre = TAB_COMPO_PPTES[119].NewCle;\n var NomCleMaitre = DePrefixerChamp(Compo_Maitre.getCle());\n var cs_nom=GetValAt(121);\n if (!ValiderChampsObligatoire(Table,\"cs_nom\",TAB_GLOBAL_COMPO[121],cs_nom,false))\n \treturn -1;\n if (!ValiderChampsType(Table,\"cs_nom\",TAB_GLOBAL_COMPO[121],cs_nom))\n \treturn -1;\n var note=GetValAt(122);\n if (!ValiderChampsObligatoire(Table,\"note\",TAB_GLOBAL_COMPO[122],note,false))\n \treturn -1;\n if (!ValiderChampsType(Table,\"note\",TAB_GLOBAL_COMPO[122],note))\n \treturn -1;\n var Req=\"insert into \"+Table+\" \";\nvar TabInsertionEnPlus=new Array();\n Req+=\"(\"+NomCleMaitre+\",cs_nom,note\"+(TabInsertionEnPlus.length!=0?\",\"+TabInsertionEnPlus[0]:\"\")+\")\";\n Req+=\" values (\"+CleMaitre+\",\"+(cs_nom==\"\" ? \"null\" : \"'\"+ValiderChaine(cs_nom)+\"'\" )+\",\"+(note==\"\" ? \"null\" : \"'\"+ValiderChaine(note)+\"'\" )+\"\"+(TabInsertionEnPlus.length!=0?\",\"+TabInsertionEnPlus[1]:\"\")+\")\";\n\n if (pgsql_update(Req)==0)\n\talert(\"Echec lors de l'insertion\");\nreturn CleMaitre;\n\n}", "function applicaModifiche(oggetto) {\r\n var trans = db.transaction([\"utenti\"],\"readwrite\");\r\n var store = trans.objectStore(\"utenti\");\r\n var operazione = store.put(oggetto); //aggiorna le modifiche\r\n operazione.onsuccess = function(e){}\r\n\r\n\r\n operazione.onerror = function(e) {\r\n alert(\"Errore nel fissaggio dei cambiamenti\");\r\n }\r\n}", "async criar() {\n this.validar(true);\n const resultado = await TabelaProduto.inserir({\n titulo : this.titulo,\n preco: this.preco,\n estoque : this.estoque,\n fornecedor : this.fornecedor\n });\n this.id = resultado.id;\n this.dataCriacao = resultado.dataCriacao;\n this.dataAtualizacao = resultado.dataAtualizacao;\n this.versao = resultado.versao\n }", "function tratarRetornoEmulacionLocal(retornoEjecucion) {\n\tdocument.forms[0].SRVPRESENTACION_CONTEXTO_SALIDA.value = retornoEjecucion;\n\twindow.document.forms[0].evento.value='0x0E003270';\n\twindow.document.forms[0].submit();\n}", "function asignarProdutoSucursal(keyProducto){\n\t\t/*key sucursal es llamada del valor de un hidden que esta en area.php*/\t\n\t\tvar keySucursal= document.getElementById(\"lb1\").value;\n\t\n\t\tvar requestData = {};\n\t\t\n\t\trequestData.websafeSucursalKey=keySucursal;\n\t\trequestData.websafeProductoKey=keyProducto;\n\t\t\n\t\tgapi.client.doomiClientes.apiClientes.addProductoForSucursal(requestData).execute(\n\t\t\t\n\t\t\tfunction(resp) {\n\n\t\t\t\tif (!resp.code) {\n\t\t\t\t\t//se envia al metodo obtenerProductosXsucursal() para que actualize los productos \n\t\t\t\t\t\n\t\t\t\t\tdocument.getElementById('formrp').reset();\n\t\t\t\t\tobtenerProductosXsucursal();\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\talert(\"Ha ocurrido un error en Tu registro, intentalo de nuevo \");\n\t\t\t\t\t//window.location.href=\"registroCliente.html\";\n\t\t\t\t\t\n\t\t\t\t\t}\n\t\t\t});\n\t\n\t\t\n\t\t}", "function addItemsAscensorValoresProteccion(k_codusuario,k_codinspeccion,k_coditem,v_sele_inspector,v_sele_empresa,o_observacion) {\n db.transaction(function (tx) {\n var query = \"INSERT INTO ascensor_valores_proteccion (k_codusuario,k_codinspeccion,k_coditem,v_sele_inspector,v_sele_empresa,o_observacion) VALUES (?,?,?,?,?,?)\";\n tx.executeSql(query, [k_codusuario,k_codinspeccion,k_coditem,v_sele_inspector,v_sele_empresa,o_observacion], function(tx, res) {\n console.log(\"insertId: \" + res.insertId + \" -- probably 1\");\n console.log(\"rowsAffected: \" + res.rowsAffected + \" -- should be 1\");\n $('#texto_carga').text(\"Añadiendo datos de protección...Espere\");\n },\n function(tx, error) {\n console.log('INSERT error: ' + error.message);\n });\n }, function(error) {\n console.log('transaction error: ' + error.message);\n }, function() {\n console.log('transaction ok');\n });\n}", "function User_Insert_Classement_Classements0(Compo_Maitre)\n{\n\n/*\n***** INFOS ******\n\nNbr d'esclaves = 3\n\nId dans le tab: 148;\nsimple\nNbr Jointure: PAS DE JOINTURE;\n\nId dans le tab: 149;\nsimple\nNbr Jointure: PAS DE JOINTURE;\n\nId dans le tab: 150;\nsimple\nNbr Jointure: PAS DE JOINTURE;\n\n******************\n*/\n\n var Table=\"classement\";\n var CleMaitre = TAB_COMPO_PPTES[146].NewCle;\n var NomCleMaitre = DePrefixerChamp(Compo_Maitre.getCle());\n var cl_nom=GetValAt(148);\n if (!ValiderChampsObligatoire(Table,\"cl_nom\",TAB_GLOBAL_COMPO[148],cl_nom,false))\n \treturn -1;\n if (!ValiderChampsType(Table,\"cl_nom\",TAB_GLOBAL_COMPO[148],cl_nom))\n \treturn -1;\n var cl_symbole=GetValAt(149);\n if (!ValiderChampsObligatoire(Table,\"cl_symbole\",TAB_GLOBAL_COMPO[149],cl_symbole,false))\n \treturn -1;\n if (!ValiderChampsType(Table,\"cl_symbole\",TAB_GLOBAL_COMPO[149],cl_symbole))\n \treturn -1;\n var cl_description=GetValAt(150);\n if (!ValiderChampsObligatoire(Table,\"cl_description\",TAB_GLOBAL_COMPO[150],cl_description,false))\n \treturn -1;\n if (!ValiderChampsType(Table,\"cl_description\",TAB_GLOBAL_COMPO[150],cl_description))\n \treturn -1;\n var Req=\"insert into \"+Table+\" \";\nvar TabInsertionEnPlus=new Array();\n Req+=\"(\"+NomCleMaitre+\",cl_nom,cl_symbole,cl_description\"+(TabInsertionEnPlus.length!=0?\",\"+TabInsertionEnPlus[0]:\"\")+\")\";\n Req+=\" values (\"+CleMaitre+\",\"+(cl_nom==\"\" ? \"null\" : \"'\"+ValiderChaine(cl_nom)+\"'\" )+\",\"+(cl_symbole==\"\" ? \"null\" : \"'\"+ValiderChaine(cl_symbole)+\"'\" )+\",\"+(cl_description==\"\" ? \"null\" : \"'\"+ValiderChaine(cl_description)+\"'\" )+\"\"+(TabInsertionEnPlus.length!=0?\",\"+TabInsertionEnPlus[1]:\"\")+\")\";\n\n if (pgsql_update(Req)==0)\n\talert(\"Echec lors de l'insertion\");\nreturn CleMaitre;\n\n}", "function insertarCarrito(curso)\n{\n const row = document.createElement('tr');\n\n row.innerHTML = `\n <td>\n <img src=\"${curso.imagen}\"width=\"100%\">\n </td>\n <td>\n ${curso.titulo} \n </td>\n <td>\n <p>${curso.precio}</p>\n </td>\n <td>\n <a href=\"#\" class=\"borrar-curso\" data-id=\"${curso.id}\">X</a> \n </td>\n \n `;\n\n\n listaCursos.appendChild(row);\n alertify.set('notifier','position', 'bottom-left');\n alertify.success('Curso Agregado al carrito');\n\n //guardar curso en el local Storage\n GuardarLocalStorage(curso);\n}", "function User_Insert_Personnes_Adresse_5(Compo_Maitre)\n{\n\n/*\n***** INFOS ******\n\nNbr d'esclaves = 5\n\nId dans le tab: 182;\nsimple\nNbr Jointure: PAS DE JOINTURE;\n\nId dans le tab: 183;\nsimple\nNbr Jointure: PAS DE JOINTURE;\n\nId dans le tab: 184;\nsimple\nNbr Jointure: PAS DE JOINTURE;\n\nId dans le tab: 185;\nsimple\nNbr Jointure: 1;\n Joint n° 0 = commune,ad_commune,co_numero\n\nId dans le tab: 186;\nsimple\nNbr Jointure: 1;\n Joint n° 0 = codepostal,ad_codepostal,cp_numero\n\n******************\n*/\n\n var Table=\"adresse\";\n var CleMaitre = TAB_COMPO_PPTES[176].NewCle;\n var NomCleMaitre = DePrefixerChamp(Compo_Maitre.getCle());\n var ad_addr1=GetValAt(182);\n if (!ValiderChampsObligatoire(Table,\"ad_addr1\",TAB_GLOBAL_COMPO[182],ad_addr1,false))\n \treturn -1;\n if (!ValiderChampsType(Table,\"ad_addr1\",TAB_GLOBAL_COMPO[182],ad_addr1))\n \treturn -1;\n var ad_addr2=GetValAt(183);\n if (!ValiderChampsObligatoire(Table,\"ad_addr2\",TAB_GLOBAL_COMPO[183],ad_addr2,false))\n \treturn -1;\n if (!ValiderChampsType(Table,\"ad_addr2\",TAB_GLOBAL_COMPO[183],ad_addr2))\n \treturn -1;\n var ad_addr3=GetValAt(184);\n if (!ValiderChampsObligatoire(Table,\"ad_addr3\",TAB_GLOBAL_COMPO[184],ad_addr3,false))\n \treturn -1;\n if (!ValiderChampsType(Table,\"ad_addr3\",TAB_GLOBAL_COMPO[184],ad_addr3))\n \treturn -1;\n var ad_commune=GetValAt(185);\n if (ad_commune==\"-1\")\n ad_commune=\"null\";\n if (!ValiderChampsObligatoire(Table,\"ad_commune\",TAB_GLOBAL_COMPO[185],ad_commune,true))\n \treturn -1;\n var ad_codepostal=GetValAt(186);\n if (ad_codepostal==\"-1\")\n ad_codepostal=\"null\";\n if (!ValiderChampsObligatoire(Table,\"ad_codepostal\",TAB_GLOBAL_COMPO[186],ad_codepostal,true))\n \treturn -1;\n var Req=\"insert into \"+Table+\" \";\nvar TabInsertionEnPlus=new Array();\n Req+=\"(\"+NomCleMaitre+\",ad_addr1,ad_addr2,ad_addr3,ad_commune,ad_codepostal\"+(TabInsertionEnPlus.length!=0?\",\"+TabInsertionEnPlus[0]:\"\")+\")\";\n Req+=\" values (\"+CleMaitre+\",\"+(ad_addr1==\"\" ? \"null\" : \"'\"+ValiderChaine(ad_addr1)+\"'\" )+\",\"+(ad_addr2==\"\" ? \"null\" : \"'\"+ValiderChaine(ad_addr2)+\"'\" )+\",\"+(ad_addr3==\"\" ? \"null\" : \"'\"+ValiderChaine(ad_addr3)+\"'\" )+\",\"+ad_commune+\",\"+ad_codepostal+\"\"+(TabInsertionEnPlus.length!=0?\",\"+TabInsertionEnPlus[1]:\"\")+\")\";\n\n if (pgsql_update(Req)==0)\n\talert(\"Echec lors de l'insertion\");\nreturn CleMaitre;\n\n}", "function inserisci(data){\n id.value = data[0]._id\n name.value = data[0].regione_sociale\n indirizzo.value = data[0].indirizzo\n cap.value = data[0].cap\n località.value = data[0].località\n provincia.value = data[0].provincia\n nazionalità.value = data[0].nazionalità\n cod_fiscale.value = data[0].cod_fiscale\n data_nascita.value = data[0].data_nascita\n tel.value = data[0].tel\n email.value = data[0].email\n importo.value = data[0].importo\n note.value = data[0].note\n\n}", "function addItemsAscensorValoresCabina(k_codusuario,k_codinspeccion,k_coditem,n_calificacion,v_calificacion,o_observacion) {\n db.transaction(function (tx) {\n var query = \"INSERT INTO ascensor_valores_cabina (k_codusuario,k_codinspeccion,k_coditem,n_calificacion,v_calificacion,o_observacion) VALUES (?,?,?,?,?,?)\";\n tx.executeSql(query, [k_codusuario,k_codinspeccion,k_coditem,n_calificacion,v_calificacion,o_observacion], function(tx, res) {\n console.log(\"insertId: \" + res.insertId + \" -- probably 1\");\n console.log(\"rowsAffected: \" + res.rowsAffected + \" -- should be 1\");\n $('#texto_carga').text(\"Añadiendo datos de cabina...Espere\");\n },\n function(tx, error) {\n console.log('INSERT error: ' + error.message);\n });\n }, function(error) {\n console.log('transaction error: ' + error.message);\n }, function() {\n console.log('transaction ok');\n });\n}", "function addItemsAscensorValoresPreliminar(k_codusuario,k_codinspeccion,k_coditem_preli,v_calificacion,o_observacion) {\n db.transaction(function (tx) {\n var query = \"INSERT INTO ascensor_valores_preliminar (k_codusuario,k_codinspeccion,k_coditem_preli,v_calificacion,o_observacion) VALUES (?,?,?,?,?)\";\n tx.executeSql(query, [k_codusuario,k_codinspeccion,k_coditem_preli,v_calificacion,o_observacion], function(tx, res) {\n console.log(\"insertId: \" + res.insertId + \" -- probably 1\");\n console.log(\"rowsAffected: \" + res.rowsAffected + \" -- should be 1\");\n $('#texto_carga').text(\"Añadiendo datos preliminares...Espere\");\n },\n function(tx, error) {\n console.log('INSERT error: ' + error.message);\n });\n }, function(error) {\n console.log('transaction error: ' + error.message);\n }, function() {\n console.log('transaction ok');\n });\n}", "function silencios_insert()\n{\n var silencio_nota = document.getElementById('silencio_notas');\n silencio_nota = silencio_nota.value;\n var textarea = document.getElementById('textarea');\n var text = textarea.value;\n var cursor = getCaret(textarea); \n switch (silencio_nota) { \n case \"redonda\":\n text = text.substring(0,cursor)+'_z8'+text.substring(cursor,text.length);\n textarea.value = text;\n break;\n case \"blanca\":\n text = text.substring(0,cursor)+'_z4'+text.substring(cursor,text.length);\n textarea.value = text; \n break;\n case \"negra\":\n text = text.substring(0,cursor)+'_z2'+text.substring(cursor,text.length);\n textarea.value = text;\n break;\n case \"corchea\":\n text = text.substring(0,cursor)+'_z1'+text.substring(cursor,text.length);\n textarea.value = text;\n break;\n case \"semicorchea\":\n text = text.substring(0,cursor)+'_z1/2'+text.substring(cursor,text.length);\n textarea.value = text;\n break;\n case \"fusa\":\n text = text.substring(0,cursor)+'_z1/4'+text.substring(cursor,text.length);\n textarea.value = text;\n break;\n case \"semifusa\":\n text = text.substring(0,cursor)+'_z1/8'+text.substring(cursor,text.length);\n textarea.value = text;\n break;\n default:\n alert(\"error\");\n break;\n }\n}", "function saveProgram() {\n var programName=programNameField.value;\n if (programName==\"\") {\n\talert(\"Enter a program name first\");\n\treturn;\n }\n window.localStorage.setItem(getProgramHTMLKey(programName),htmlSrc.value);\n window.localStorage.setItem(getProgramJSKey(programName),jsSrc.value);\n if (window.localStorage.getItem(getProgramAccessTokenKey(programName))==null) {\n\t// Generate an access token if there isn't one yet\n\tvar tokenValuesArray=new Uint32Array(4);\n\twindow.crypto.getRandomValues(tokenValuesArray);\n\tvar accessToken=\"\"+tokenValuesArray[0];\n\tfor (i=1;i<4;i++) {\n\t accessToken=accessToken+\",\"+tokenValuesArray[i];\n\t}\n\twindow.localStorage.setItem(getProgramAccessTokenKey(programName),accessToken);\n }\n setModified(false);\n generateProgramList(programName);\n updateLinks();\n}", "function executar() {\n if (desenhoDaArvoreFinalizado) {\n desenhaResultado();\n execucaoDoAlgoritmoFinalizada = true;\n }\n\n if (finalizado && !desenhoDaArvoreFinalizado) {\n desenhar();\n desenhoDaArvoreFinalizado = true;\n }\n\n /**\n * Cria a tabela inicial.\n */\n if (!finalizado) {\n if (ciclos == 0) {\n let texto = document.getElementById(\"textoACodificar\").value; // string da textfield\n analisaFrequenciasDoAlfabeto(texto);\n primeriaOrdenacao();\n desenhaTabelas();\n } else {\n /**\n * Cria as demais tabelas.\n */\n codificacaoDeHufmann();\n ordenarDicionario();\n desenhaTabelas();\n }\n }\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Finds the next safe (unique) slug to use
getNextSafeSlug(originalSlug, isDryRun) { let slug = originalSlug; let occurenceAccumulator = 0; if (this.seen.hasOwnProperty(slug)) { occurenceAccumulator = this.seen[originalSlug]; do { occurenceAccumulator++; slug = originalSlug + '-' + occurenceAccumulator; } while (this.seen.hasOwnProperty(slug)); } if (!isDryRun) { this.seen[originalSlug] = occurenceAccumulator; this.seen[slug] = 0; } return slug; }
[ "function getSlug() {\n\n // if we're on the home page, there won't be a slug\n if (window.location.pathname == '/') {\n return 'home';\n // otherwise, get the slug\n } else {\n // get the full path and split it into components\n var pathComponents = window.location.pathname.match(/([^\\/]+)/g);\n // return the last bit (AKA, the slug)\n return pathComponents[pathComponents.length - 1];\n // debugging\n // console.log('getSlug() fired; the slug is: ' + slug);\n }\n}", "fallbackItemSlug() {\n if (this.manifest && this.activeItem) {\n if (\n this.activeManifestIndex > 0 &&\n this.manifest.items[this.activeManifestIndex - 1]\n ) {\n return this.manifest.items[this.activeManifestIndex - 1].slug;\n } else if (\n this.activeManifestIndex < this.manifest.items.length - 1 &&\n this.manifest.items[this.activeManifestIndex + 1]\n ) {\n return this.manifest.items[this.activeManifestIndex + 1].slug;\n }\n }\n return null;\n }", "function uniqueLinkGen(){\n if(linkGenStore.findOne({'shortURL':short_url})===true){//check if short url is present\n short_url = linkGen.genURL();\n uniqueLinkGen();\n }\n else{\n return short_url;\n }\n }", "function slug (): string {\n return sample(foodhubSlugs);\n}", "function slugifyUrl(url) {\n\t\t\treturn Util.parseUrl(url).path\n\t\t\t\t.replace(/^[^\\w]+|[^\\w]+$/g, '')\n\t\t\t\t.replace(/[^\\w]+/g, '-')\n\t\t\t\t.toLocaleLowerCase();\n\t\t}", "function giveFriendlyUrl(url){\n\t\tvar splitElements = url.split(\"../index.html\");\n\t\treturn splitElements[splitElements.length-2];\n\t}", "function Slugify(obj, prop) {\n\n obj.prototype.bookSlug = function(ns, slug) {\n if(!this.model.slugBooker[ns]) {\n this.model.slugBooker[ns] = []\n }\n this.model.slugBooker[ns].push(slug)\n }\n\n obj.prototype.freeSlug = function(ns, slug) {\n if(this.model.slugBooker[ns] && this.model.slugBooker[ns][slug]) {\n delete this.model.slugBooker[ns][slug]\n if(this.model.slugBooker[ns].length == 0) {\n delete this.model.slugBooker[ns]\n }\n }\n }\n\n obj.prototype.isBookSlug = function(ns, slug) {\n return this.model.slugBooker[ns] && this.model.slugBooker[ns].indexOf(slug) >= 0\n }\n\n obj.prototype.slugging = function(ns, cb) {\n var self = this\n , slug = encodeURIComponent(this[prop].substring(0, 10))\n , base_slug = slug\n , acc = 0\n , find_it = function() {\n if(self.isBookSlug(ns, slug)) {\n slug = base_slug + '-' + (++acc)\n find_it()\n } else {\n self.bookSlug(ns, slug)\n self.get(slug, function(err, res) {\n if(res) {\n self.freeSlug(ns, slug)\n slug = base_slug + '-' + (++acc)\n find_it()\n } else {\n self.slug = slug\n cb(err)\n }\n })\n }\n }\n find_it()\n }\n}", "function termSlug( term, prefix ){\n var slug = term.replace(/[^a-zA-Z ]/g, \"\");\n return prefix ? prefix+slug : slug;\n}", "function shortenUrl(longUrl) {\n var newUrl = Url({\n long_url: longUrl\n });\n // save the new link in the db\n newUrl.save(function(err) {\n if (err){\n console.log(err);\n }\n });\n // the short url will just be the id of the saved url in the db. Todo : optimize this. \n var shortUrl = config.url + \"/\" + newUrl._id ;\n return shortUrl ;\n}", "function getShortURL(canonicalKey) {\n var shortKey = _.token(KEY_LENGTH);\n\n return _.dynamo.put('short-urls', {\n key: {S: shortKey},\n pathname: {S: canonicalKey},\n created: {N: Date.now().toString()},\n })\n .then(function() {\n return 'https://peppermint.com/' + shortKey;\n });\n}", "function uniqueURI(container, callback) {\n\t\tvar candidate = addPath(container, 'res' + Date.now())\n\t\tdb.reserveURI(candidate, function(err) {\n\t\t\tcallback(err, candidate)\n\t\t});\n\t}", "function getProductId(url){\n let id = url.match(/p-[0-9]+/g)\n let lastIndex = id.length -1\n return id[lastIndex].slice(2)\n}", "async reserveUrl() {\n let result = null;\n\n try {\n result = await models.urls.create();\n } catch (e) {\n log.error('reserveUrl: Unable to reserve index for new URL hash.');\n log.error(e);\n throw e;\n }\n\n return result.id;\n }", "updateHash(slug) {\n window.location.hash = slug;\n }", "function find_next_autogen_key(resourceName,offset) {\n var nextId = 'id_'+(Object.keys(DATA[resourceName]).length + offset);\n if (DATA[resourceName][nextId]) {\n nextId = find_next_autogen_key(resourceName,offset + 1);\n }\n return nextId;\n }", "function nextURL(crawler) {\n if(crawler.queue.length === 0) {\n return null;\n }\n var urlString = crawler.queue.shift();\n delete crawler.alreadyQueued[urlString];\n return urlString;\n}", "function build_unique_id(options) {\n\t\t\toptions._iter = options._iter ? ++options._iter : 1;\n\t\t\tif (options._iter >= 1000) {\t\t\t\t\t\t\t\t\t\t\t\t// monitor loop count, all stop after excessive loops\n\t\t\t\tlogger.warn('[component lib] yikes, recursive loop exceeded trying to build unique id:', options.id_str, options._iter);\n\t\t\t\treturn null;\n\t\t\t}\n\n\t\t\tif (Array.isArray(options.taken_ids) && options.taken_ids.includes(options.id_str)) {\t\t// is this id taken?\n\t\t\t\tconst regex_last_numb = RegExp(/(\\d*)$/);\t\t\t\t\t\t\t\t// find the last number in a string\n\t\t\t\tconst matches = options.id_str.match(regex_last_numb);\n\t\t\t\tconst last_number = (matches && matches[1]) ? Number(matches[1]) : null;\n\n\t\t\t\tif (last_number === null) {\t\t\t\t\t\t\t\t\t\t\t\t// no suffix delim... but we found a number, increment last pos by 1\n\t\t\t\t\toptions.id_str += '_0';\n\t\t\t\t\tlogger.warn('[component lib] id is already taken, appending id suffix', options.id_str);\n\t\t\t\t} else {\n\t\t\t\t\toptions.id_str = options.id_str.replace(regex_last_numb, Number(last_number) + 1);\n\t\t\t\t\tlogger.warn('[component lib] id is already taken, incrementing id suffix', options.id_str);\n\t\t\t\t}\n\t\t\t\treturn build_unique_id(options);\t\t\t\t\t\t\t\t\t\t// repeat, check if its still taken...\n\t\t\t}\n\n\t\t\treturn options.id_str;\n\t\t}", "function generateCampaignName() {\n var splitURL = window.location.href.split('/');\n return splitURL[3];\n}", "function makeId(base, input) {\n // check if not falsy\n if(input) {\n // check for full id\n if(input.indexOf('http://') === 0 || input.indexOf('https://') === 0) {\n return input;\n }\n // else a short id\n else {\n return base + '/' + input;\n }\n }\n\n return base;\n}", "function shortenID(mid) {\n var id1 = parseInt(mid.substr(0,9), 16).toString(36)\n if (isNaN(id1)) { // conversion failed\n return mid; // return unchanged\n }\n\n // add padding if < 7 chars long\n while (id1.length < 7) id1 = '-' + id1\n\n var id2 = parseInt(mid.substr(9,9), 16).toString(36)\n if (isNaN(id2)) { // conversion failed\n return mid; // return unchanged\n }\n while (id2.length < 7) id2 = '-' + id2\n \n // add 'Z' which is the short link denoter\n return 'Z' + id1 + id2\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Copyright 20052014 The Kuali Foundation Licensed under the Educational Community License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Show growl with message, title and theme passed in
function showGrowl(message, title, theme) { var context = getContext(); if (theme) { context.jGrowl(message, { header:title, theme:theme}); } else { context.jGrowl(message, { header:title}); } }
[ "function showInfoFallr(msg) {\n\tjQuery.fallr('show', {\n\t\tcontent : '<p>'+ msg +'</p>',\n\t\ticon : 'info'\n\t});\n}", "renderWelcomeMessage(language) {\n switch(language) {\n case 'en':\n this.setState({welcomeMessage: 'Welcome message from STORMRIDER'});\n break;\n case 'is':\n this.setState({welcomeMessage: 'Bulbulbul asfgwthyt sadasd STORMRIDER'});\n break;\n default:\n break;\n }\n }", "function showWelcome() {\n\n\tconst welcomeHeader = `\n\n=================================================================\n|| ||\n| Employee Summary Generator |\n|| ||\n=================================================================\n\n`\n\n\tconst welcomeMessage = `\n\nWelcome to the Employee Summary Generator!\nThis application will generate a roster of employee details based on information you provide.\n\n`\n\n\tconsole.clear();\n\n\tconsole.log(colors.brightCyan(welcomeHeader));\n\tconsole.log(colors.brightCyan(welcomeMessage));\n\n}", "showWelcomeMessage(welcomeMessageMode) {\n Instabug.showWelcomeMessageWithMode(welcomeMessageMode);\n }", "function popupText(data) {\n\t\tvar text = '<p class=\"alertHeader\">'+data.header+'</p>' +\n\t\t\t\t\t'<p class=\"alertBody1\">'+data.body1+'</p>' +\n\t\t\t\t\t'<p class=\"alertBody2\">'+data.body2+'</p>';\n\t\treturn text;\n\t}", "function showAlert(type, message, callback) {\n // Set alert colors\n setAlertStyle(type);\n // Determine type of alert to show\n var hitboxElement;\n if ($('#welcome-blue-hitbox').length) {\n // Check to see if we are on the welcome page\n hitboxElement = $('#welcome-blue-hitbox');\n } else {\n hitboxElement = $('#blue-hitbox-add-pane');\n }\n if (isElementInViewport(hitboxElement)) {\n // Hitbox is in view, show alert there\n return showHitboxAlert(hitboxElement, message, callback);\n } else {\n // Hitbox is not in view, show a fixed alert\n return showFixedAlert(hitboxElement, message, callback);\n }\n}", "function mensaje(titulo, mensaje){\n swal(titulo, mensaje); \n }", "function showErrorFallr(msg) {\n\tjQuery.fallr('show', {\n\t\tcontent : '<p>'+ msg +'</p>',\n\t\ticon : 'error'\n\t});\n}", "function showStatusMsg(msg) {\n\tExt.get('status-msg').update(msg);\n\t//Ext.get('status-msg').slideIn();\n}", "function displayText(message) {\n push();\n fill(255);\n textSize(32);\n textAlign(CENTER, CENTER);\n text(message, width / 2, height / 2);\n pop();\n}", "function milestoneMessage() {\n // Make the message disappear when a game over happens\n if (state === \"GAMEOVER\") {\n return;\n }\n push();\n // Setting the text aesthetics\n textFont(neoFont);\n textSize(64);\n textAlign(CENTER, CENTER);\n fill(255);\n // The message displays nothing at 0 prey eaten\n if (thief.preyEaten === 0) {\n message = \"\";\n }\n // The first message\n if (thief.preyEaten === 4) { // The message will display when 5 prey are eaten\n // Setting the text to be displayed\n message = \"Good start!\";\n milestoneY = 700;\n }\n // The second message\n if (thief.preyEaten === 11) { // The message will display when 12 prey are eaten\n message = \"Doing great!\";\n milestoneY = 700;\n }\n // The third message\n if (thief.preyEaten === 20) { // The message will display when 21 prey are eaten\n message = \"Almost there!\";\n milestoneY = 700;\n }\n // Handling the universal settings for the message display\n // The messages activate as soon as the number of prey eaten reaches 5\n if (thief.preyEaten >= 5) {\n text(message, width / 2, milestoneY);\n milestoneY = milestoneY - 3;\n }\n pop();\n}", "showMessage(type,title,message){\n\t\tsetTimeout(function() {\n\t\t\tvar html = message;\n\t\t\t\t\t\tif(type == \"error\"){\n\t\t\t\t\t\t\tvar html = '<span style=\"color:#ef5350;\">'+message+'</span>'\n\t\t\t\t\t\t}\n\t\t\t\t\t\tM.toast({html: html})\n }, 1000);\n\t}", "function ShowDemoWindow(parent, init)\n{\n var window = two.ui.window(parent, 'ImGui Demo', two.WindowState.Default | two.WindowState.Menu);\n\n var body = two.ui.scrollable(window.body);\n //var scrollsheet = two.ui.scroll_sheet(window.body);\n //var body = scrollsheet.body;\n\n if(window.menu)\n {\n menubar = window.menu;\n\n var menu = two.ui.menu(menubar, 'Menu').body\n if(menu)\n {\n //ShowExampleMenuFile();\n }\n\n theme_menu(menubar);\n\n var menu = two.ui.menu(menubar, 'Examples').body\n if(menu)\n {\n //two.ui.menu_option(menu, 'Main menu bar', '', show_app_main_menu_bar);\n //two.ui.menu_option(menu, 'Console', '', show_app_console);\n //two.ui.menu_option(menu, 'Log', '', show_app_log);\n //two.ui.menu_option(menu, 'Simple layout', '', show_app_layout);\n //two.ui.menu_option(menu, 'Property editor', '', show_app_property_editor);\n //two.ui.menu_option(menu, 'Long text display', '', show_app_long_text);\n //two.ui.menu_option(menu, 'Auto-resizing window', '', show_app_auto_resize);\n //two.ui.menu_option(menu, 'Constrained-resizing window', '', show_app_constrained_resize);\n //two.ui.menu_option(menu, 'Simple overlay', '', show_app_simple_overlay);\n //two.ui.menu_option(menu, 'Manipulating window titles', '', show_app_window_titles);\n //two.ui.menu_option(menu, 'Custom rendering', '', show_app_custorendering);\n //two.ui.menu_option(menu, 'Documents', '', show_app_documents);\n }\n\n var help = two.ui.menu(menubar, 'Help').body\n if(help)\n {\n //two.ui.menu_option(help, 'Metrics', '', show_app_metrics);\n //two.ui.menu_option(help, 'Style Editor', '', show_app_style_editor);\n //two.ui.menu_option(help, 'About Dear ImGui', '', show_app_about);\n }\n }\n\n //two.ui.labelf(body, 'dear imgui says hello. (%s)', '1.0'); //IMGUI_VERSION);\n //two.ui.Spacing();\n\n var help = two.ui.expandbox(body, 'Help').body\n if(help)\n {\n two.ui.label(help, 'PROGRAMMER GUIDE:');\n two.ui.bullet(help, 'Please see the ShowDemoWindow() code in imgui_demo.cpp. <- you are here!');\n two.ui.bullet(help, 'Please see the comments in imgui.cpp.');\n two.ui.bullet(help, 'Please see the examples/ in application.');\n two.ui.bullet(help, 'Enable io.ConfigFlags |= NavEnableKeyboard for keyboard controls.');\n two.ui.bullet(help, 'Enable io.ConfigFlags |= NavEnableGamepad for gamepad controls.');\n two.ui.separator(help);\n\n two.ui.label(help, 'USER GUIDE:');\n ShowUserGuide(help);\n }\n\n var config = two.ui.expandbox(body, 'Configuration').body\n if(config)\n {\n }\n\n if(init)\n {\n this.no_titlebar = false;\n this.no_scrollbar = false;\n this.no_menu = false;\n this.no_move = false;\n this.no_resize = false;\n this.no_collapse = false;\n this.no_close = false;\n this.no_nav = false;\n this.no_background = false;\n this.no_bring_to_front = false;\n }\n \n var opts = two.ui.expandbox(body, 'Window options').body\n if(opts)\n {\n row0 = two.ui.row(opts);\n two.ui.field_bool(row0, 'No titlebar', this.no_titlebar, true);\n two.ui.field_bool(row0, 'No scrollbar', this.no_scrollbar, true);\n two.ui.field_bool(row0, 'No menu', this.no_menu, true);\n\n row1 = two.ui.row(opts);\n two.ui.field_bool(row1, 'No move', this.no_move, true);\n two.ui.field_bool(row1, 'No resize', this.no_resize, true);\n two.ui.field_bool(row1, 'No collapse', this.no_collapse, true);\n\n row2 = two.ui.row(opts);\n two.ui.field_bool(row2, 'No close', this.no_close, true);\n two.ui.field_bool(row2, 'No nav', this.no_nav, true);\n two.ui.field_bool(row2, 'No background', this.no_background, true);\n\n row3 = two.ui.row(opts);\n two.ui.field_bool(row3, 'No bring to front', this.no_bring_to_front, true);\n }\n\n}", "function notiflixConfirm() {\n let amstedOrGreenbrier = Array.from(document.querySelector(\"body\").classList).includes(\"theme-am\") ? \"#0C134F\" : \"#32c682\";\n Notiflix.Confirm.init({\n titleColor: amstedOrGreenbrier,\n okButtonColor: '#f8f8f8',\n okButtonBackground: amstedOrGreenbrier,\n });\n}", "function callMessageDialog(title, messageContent){\n\t\t$(\"#messageDialog\").find(\"#messageContent\").text(messageContent);\n\t\t$(\"#messageDialog\").dialog({\n\t\t\tshow:{\n\t\t\t\teffect:\"slide\",\n\t\t\t\tduration: 300\n\t\t\t},\n\t\t\ttitle: title,\n\t\t\theight: 200,\n\t\t\twidth: 350,\n\t\t\thide: {\n\t\t\t\teffect: \"slide\",\n\t\t\t\tduration: 300\n\t\t\t},\n\t\t\tbuttons:{\n\t\t\t\t\"OK\": function(){\n\t\t\t\t\t$(this).dialog(\"close\");\n\t\t\t\t\tloadData();\n\t\t\t\t\tloadFactoryData();\n\t\t\t\t}\n\t\t\t}\n\t\t}).prev(\".ui-widget-header\").css(\"color\",\"#333\");\n\t}", "function getBubblePopupThemePath() {\n return getConfigParam(kradVariables.APPLICATION_URL) + kradVariables.BUBBLEPOPUP_THEME_PATH;\n}", "function displayHelpMsg(msg) {\n\tExt.getCmp('helpIframe').el.update(msg);\n}", "function setGreeting() {\n var greetingTranslation = i18nHelper.t('Hello world.');\n greetingElement.innerHTML = greetingTranslation;\n}", "function createLaunchPopOver (options){\n \n if (typeof options === 'undefined' ||\n options === null){\n return;\n }\n \n var message = options['message'],\n trace = options['trace'],\n isConfirm = options['confirm-mode'] || false,\n okLabel = options['ok-label'] || 'Ok',\n okCallBack = options['ok-callback'],\n closeLabel = options['close-label'] || 'Close',\n closeCallBack = options['close-callback'],\n header = options['header'] || 'Results Analytics';\n \n var raSplash = document.querySelector('.sim-ui-advise-splash-background') || null;\n \n document.querySelector('.sim-ui-errpop-header').textContent = header;\n \n if(isConfirm)\n document.querySelector('#sim-ui-errpop-ok').classList.remove('sim-ui-errpop-noshow');\n else\n document.querySelector('#sim-ui-errpop-ok').classList.add('sim-ui-errpop-noshow');\n if (okLabel.length > 0)\n $simjq('#sim-ui-errpop-ok').text(okLabel);\n if (okLabel.length > 0)\n $simjq('#sim-ui-errpop-close').text(closeLabel);\n if (typeof message !== 'undefined' &&\n message !== null &&\n message.length > 0){\n $simjq('#sim-ui-errpop-msgcard').html(message);\n }\n else {\n if(typeof closeCallBack === 'function')\n closeCallBack();\n return;\n }\n if (typeof trace !== 'undefined' &&\n trace !== null &&\n trace.length > 0){\n $simjq('#sim-ui-errpop-tracecard').text(trace);\n }\n \n $simjq('#sim-ui-errpop-close,#sim-ui-errpop-ok').bind('click',\n function(){\n var id = $simjq(this).attr('id');\n if(id === 'sim-ui-errpop-ok'){\n if(typeof okCallBack === 'function')\n okCallBack();\n }\n if(id === 'sim-ui-errpop-close'){\n if(typeof closeCallBack === 'function')\n closeCallBack();\n }\n document.querySelector('.sim-ui-errpop-veil').classList.add('sim-ui-errpop-noshow');\n if(raSplash)\n raSplash.classList.remove('sim-ui-errpop-noshow');\n return;\n });\n\n if(raSplash)\n raSplash.classList.add('sim-ui-errpop-noshow');\n document.querySelector('.sim-ui-errpop-veil').classList.remove('sim-ui-errpop-noshow');\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
QueryAssetsByOwner queries for assets based on a passed in owner. This is an example of a parameterized query where the query logic is baked into the TDrive, and accepting a single query parameter (owner). Only available on state databases that support rich query (e.g. CouchDB) Example: Parameterized rich query
async QueryAssetsByOwner(ctx, owner) { let queryString = {}; queryString.selector = {}; queryString.selector.docType = 'asset'; queryString.selector.owner = owner; return await this.GetQueryResultForQueryString(ctx, JSON.stringify(queryString)); //shim.success(queryResults); }
[ "async function searchOrdersOfOwner(login, atState, containerId){\n\tconst uri = '/transdev/shop/v1/secured/api/command/searchOrdersOfOwner/?login=' + login + '&containerId=' + containerId;\n\tconst url = `${API_ROOT}` + uri;\n return _doGet(url);\n}", "listTournamentRecordsAroundOwner(bearerToken, tournamentId, ownerId, limit, expiry, options = {}) {\n if (tournamentId === null || tournamentId === void 0) {\n throw new Error(\"'tournamentId' is a required parameter but is null or undefined.\");\n }\n if (ownerId === null || ownerId === void 0) {\n throw new Error(\"'ownerId' is a required parameter but is null or undefined.\");\n }\n const urlPath = \"/v2/tournament/{tournamentId}/owner/{ownerId}\".replace(\"{tournamentId}\", encodeURIComponent(String(tournamentId))).replace(\"{ownerId}\", encodeURIComponent(String(ownerId)));\n const queryParams = /* @__PURE__ */ new Map();\n queryParams.set(\"limit\", limit);\n queryParams.set(\"expiry\", expiry);\n let bodyJson = \"\";\n const fullUrl = this.buildFullUrl(this.basePath, urlPath, queryParams);\n const fetchOptions = buildFetchOptions(\"GET\", options, bodyJson);\n if (bearerToken) {\n fetchOptions.headers[\"Authorization\"] = \"Bearer \" + bearerToken;\n }\n return Promise.race([\n fetch(fullUrl, fetchOptions).then((response) => {\n if (response.status == 204) {\n return response;\n } else if (response.status >= 200 && response.status < 300) {\n return response.json();\n } else {\n throw response;\n }\n }),\n new Promise(\n (_, reject) => setTimeout(reject, this.timeoutMs, \"Request timed out.\")\n )\n ]);\n }", "async function getObjectList(connection, owner, type, name, status, query) {\n // Get the list of object types\n query = sql.statement[query];\n const filtered_name = name.toString().toUpperCase().replace('*', '%').replace('_', '\\\\_');\n const filtered_type = type.toString().replace('*', '%');\n let filtered_status = status.toString().toUpperCase();\n if (filtered_status !== 'VALID' &&\n filtered_status !== 'INVALID') {\n filtered_status = '%';\n }\n query.params.owner.val = owner;\n query.params.object_type.val = filtered_type;\n query.params.object_name.val = filtered_name;\n query.params.status.val = filtered_status;\n\n const result = await dbService.query(connection, query.sql, query.params);\n return result;\n}", "getAssetsOwnedByAddress(address) {\n return rxjs_1.of(\"mosaic/owned?address=\" + address.plain())\n .pipe(operators_1.flatMap((url) => requestPromise.get(this.nextNode() + url, { json: true })), operators_1.retryWhen(this.replyWhenRequestError), operators_1.map((mosaicsData) => {\n return mosaicsData.data.map((mosaicDTO) => {\n return Asset_1.Asset.createFromMosaicDTO(mosaicDTO);\n });\n }));\n }", "async function getArtistsByOwnerId(id) {\n const [ results ] = await mysqlPool.query(\n 'SELECT * FROM artist WHERE ownerid = ?',\n [ id ]\n );\n return results;\n}", "function queryByAssetId(assetId, privateIdInventory) {\n var reqSpec = {\n method: 'POST',\n headers: {\n 'accept': 'application/json',\n 'Content-Type': 'application/json',\n 'Authorization': \"ID \" + privateIdInventory\n },\n body: \"{\\\"queryTql\\\": \\\"SELECT * FROM Medications WHERE asset_id = '\" + assetId + \"'\\\"}\"\n };\n fetch('https://testnet.burstiq.com/api/burstchain/mines_summer/Medications/assets/query', reqSpec)\n .then(function (resp) { return resp.json(); })\n .then(function (data) {\n updateMedicationStatus(data, privateIdInventory);\n console.log(data);\n });\n}", "isOwner(user) {\n return this.json_.owner._account_id === user._account_id;\n }", "static listAction(filter = null, pager = null){\n\t\tlet kparams = {};\n\t\tkparams.filter = filter;\n\t\tkparams.pager = pager;\n\t\treturn new kaltura.RequestBuilder('flavorasset', 'list', kparams);\n\t}", "static listAction(filter, pager = null){\n\t\tlet kparams = {};\n\t\tkparams.filter = filter;\n\t\tkparams.pager = pager;\n\t\treturn new kaltura.RequestBuilder('fileasset', 'list', kparams);\n\t}", "static search(entryFilter = null, captionAssetItemFilter = null, captionAssetItemPager = null){\n\t\tlet kparams = {};\n\t\tkparams.entryFilter = entryFilter;\n\t\tkparams.captionAssetItemFilter = captionAssetItemFilter;\n\t\tkparams.captionAssetItemPager = captionAssetItemPager;\n\t\treturn new kaltura.RequestBuilder('captionsearch_captionassetitem', 'search', kparams);\n\t}", "static queryByUser(req, res) {\r\n const { userId } = req.params\r\n if (req.query.tags) {\r\n var tags = JSON.parse(req.query.tags)\r\n } else {\r\n var tags = null\r\n }\r\n\r\n // If tag not given, return all the songs\r\n var filterBy = {};\r\n if (tags) {\r\n filterBy = { name: tags, userId: userId }\r\n } else { filterBy = { userId: userId } }\r\n\r\n return Song\r\n //Find all song ids by the user and the tag\r\n .findAll({\r\n attributes: ['id'],\r\n include: [{\r\n model: Tag,\r\n where: filterBy,\r\n attributes: []\r\n }],\r\n raw: true\r\n // Convert the song ids to a list of ids\r\n }).then(songs => {\r\n return songs.map(song => song.id)\r\n })\r\n .then(ids => {\r\n // Find all songs with the ids, this is done to retain all the other \r\n // tags that the song might have\r\n // If no ids\r\n if (ids == []) {\r\n res.status(200).send({\r\n message: `User does not have any songs with tag ${tags}`\r\n })\r\n }\r\n return Song.findAll({\r\n // Find all songs with those IDs\r\n where: { id: { [Sequelize.Op.or]: [ids] } },\r\n include: [{\r\n model: Tag,\r\n // Only get the name of the tag\r\n attributes: ['name'],\r\n // To ignore the join table\r\n through: { attributes: [] }\r\n }]\r\n })\r\n })\r\n .then(songs => {\r\n if (songs.length != 0) {\r\n res.status(200).send(songs)\r\n } else {\r\n // If the list of songs is empty\r\n if (tags) {\r\n var message = `User does not have any songs with tag ${tags}`\r\n } else {\r\n var message = `User does not have any songs`\r\n }\r\n res.status(200).send({ message: message })\r\n }\r\n });\r\n }", "static listAction(filter = null, pager = null){\n\t\tlet kparams = {};\n\t\tkparams.filter = filter;\n\t\tkparams.pager = pager;\n\t\treturn new kaltura.RequestBuilder('attachment_attachmentasset', 'list', kparams);\n\t}", "static getFlavorAssetsWithParams(entryId){\n\t\tlet kparams = {};\n\t\tkparams.entryId = entryId;\n\t\treturn new kaltura.RequestBuilder('flavorasset', 'getFlavorAssetsWithParams', kparams);\n\t}", "function getCarerOfAnimal(con, aid, callback){\n var sql = \"SELECT owner_id FROM animals WHERE aid=\" + aid;\n con.query(sql, function(err, result){\n if (err) throw err;\n if (result.length == 0){\n callback(null);\n }\n else {\n var carer_id = JSON.parse(JSON.stringify(result[0])).owner_id;\n callback(carer_id);\n }\n });\n}", "static listAction(filter = null, pager = null){\n\t\tlet kparams = {};\n\t\tkparams.filter = filter;\n\t\tkparams.pager = pager;\n\t\treturn new kaltura.RequestBuilder('thumbasset', 'list', kparams);\n\t}", "async function findObjects(argv) {\n let body = {};\n const url = new URL(argv.url);\n url.pathname = '/api/saved_objects/_find';\n url.search = '?per_page=1000';\n for (const type of argv.types) url.search += `&type=${type}`;\n url.search;\n url.search += argv.search ? `&search=${argv.search}` : '';\n\n logger.verbose('url.search: ' + url.search);\n\n const options = {\n method: 'GET',\n headers: {\n 'kbn-xsrf': true,\n },\n };\n\n try {\n const res = await fetch(url, { ...options });\n body = await res.json();\n if (res.status === 200) {\n logger.info(\n `${res.status} ${res.statusText} Found: ${body.saved_objects.length} objects`\n );\n } else {\n logger.error(`${res.status} ${res.statusText} Error: ${body}`);\n }\n } catch (FetchError) {\n logger.error(`${FetchError.message}`);\n }\n return body.saved_objects;\n}", "function getConfigPricingFromResourceQuery(ownerid, elements, callback) {\n var configJson = {};\n\n // Identify configurable vs\n if((elements.uri).match('vs/') && (elements.uri).match('/configurable')){\n configJson.volumeStorageUri = elements.uri;\n if(elements.parameters && elements.parameters.sizeInGBytes){\n configJson.size = elements.parameters.sizeInGBytes;\n }\n }else if((elements.uri).match('saas/') && (elements.uri).match('/configurable')){\n configJson.uri = elements.uri;\n if(elements.parameters && elements.parameters.sizeInGBytes){\n configJson.size = elements.parameters.sizeInGBytes;\n }\n }else {\n if(elements.uri){\n configJson.instanceTypeUri = elements.uri;\n }\n if(elements.parameters && elements.parameters.imageUri){\n configJson.imageUri = elements.parameters.imageUri;\n }\n if(elements.parameters && elements.parameters.ram){\n configJson.ram = elements.parameters.ram;\n }\n if(elements.parameters && elements.parameters.cpuCount){\n configJson.cpuCount = elements.parameters.cpuCount;\n }\n if(elements.parameters && elements.parameters.localStorage){\n configJson.localStorage = elements.parameters.localStorage;\n }\n trace.info(configJson);\n }\n\n jsonObject = JSON.stringify(configJson);\n\n // prepare the header\n //TODO Implement new Auth Model\n var postheaders = {\n 'Content-Type' : 'application/json',\n 'Content-Length' : Buffer.byteLength(jsonObject, 'utf8')\n //\"Authorization\": \"Basic \" + new Buffer(ownerid + \":\" + ownerid).toString(\"base64\")\n };\n\n postheaders[authConfig.bypassHeaderName] = 'billing'+':'+authConfig.billing;\n postheaders['ownerId'] = ownerid;\n\n // the post options\n var optionspost = {\n host : config.resourceServiceHost,\n port : config.resourceServicePort,\n path : '/apiv1.0/resourceQuery/validate',\n method : 'POST',\n headers : postheaders\n };\n\n // do the POST call to resource service\n restservices.postCall(optionspost,jsonObject).then(function (resourceServiceresult) {\n return callback(resourceServiceresult);\n\n }).catch(function onReject(err) {\n trace.error('Rejected', err);\n if(err.stack)\n trace.debug('Error Occurred in : '+ err.stack);\n return callback(null);\n\n }).catch(function(error){\n trace.error('Catch Error:', error);\n if(error.stack)\n trace.debug('Error Occurred in : '+ error.stack);\n return callback(null);\n });\n}", "function get_objects_from_repository (type, resource_params) {\r\n var rest_params = \"\";\r\n var query_params = \"?callback=1\";\r\n var base_url = DataRepositoryDefault.url;\r\n var authentication = \"\";\r\n if (DataRepositoryDefault.authentication) {\r\n authentication = \"&\" + DataRepositoryDefault.authentication;\r\n }\r\n\r\n if (resource_params) {\r\n if (resource_params.data_repository && DataRepositories[resource_params.data_repository]) {\r\n base_url = DataRepositories[resource_params.data_repository].url;\r\n if (DataRepositories[resource_params.data_repository].authentication) {\r\n\tauthentication = \"&\" + DataRepositories[resource_params.data_repository].authentication;\r\n } else {\r\n\tauthentication = \"\";\r\n }\r\n }\r\n if (resource_params.rest) {\r\n rest_params += resource_params.rest.join(\"/\");\r\n }\r\n if (resource_params && resource_params.query) {\r\n for (var i=0; i<resource_params.query.length - 1; i++) {\r\n\tquery_params += \"&\" + resource_params.query[i] + \"=\" + resource_params.query[i+1];\r\n }\r\n }\r\n }\r\n\r\n base_url += type + \"/\" + rest_params + query_params + authentication;\r\n\r\n var script = document.createElement('script');\r\n script.setAttribute('type', 'text/javascript');\r\n script.setAttribute('src', base_url);\r\n script.setAttribute('id', 'callback_script_'+type)\r\n document.getElementsByTagName('head')[0].appendChild(script);\r\n}", "function getAthletes() {\n // get athletes owned by logged in user\n console.log(\"In getAthletes, OwnerId:\", OwnerId);\n $.get(\"/api/athletes/team/\"+OwnerId, function(data) {\n initializeRows(data);\n });\n // get unowned athletes\n $.get(\"/api/athletes/team/1\", function(data) {\n initializeRosterRows(data);\n });\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the metatable for a Lua value.
setMetatable(o, mt) { if (Lua.isNil(mt)) { mt = null; } else { this.apiCheck(mt instanceof LuaTable_1.LuaTable); } var mtt = mt; if (o instanceof LuaTable_1.LuaTable) { var t = o; t.setMetatable(mtt); } else if (o instanceof LuaUserdata_1.LuaUserdata) { var u = o; u.metatable = mtt; } else { this._metatable[Lua.____type(o)] = mtt; } }
[ "set type(aValue) {\n this._logger.debug(\"type[set]\");\n this._type = aValue;\n }", "function set_value(vals, val, is_variable) {\n set_head(head(vals), val);\n set_tail(head(vals), is_variable);\n }", "function doSetValue(identifier,value,objectname,callbackname,randomnumber)\n{\n // JP TODO - temp hack to get rid of the value for strings and associated language data model elements\n var dotBindingName = identifier.replace(\".Value\", \"\");\n var api = getAPIHandle();\n var result = \"false\";\n\n if (api == null)\n {\n message(\"Unable to locate the LMS's API Implementation.\\nSetValue was not successful.\");\n }\n else if (!initialized && !doInitialize())\n {\n var error = ErrorHandler();\n message(\"SetValue failed - Could not initialize communication with the LMS - error code: \" + error.code);\n }\n else\n {\n \n // switch set method based on SCORM version\n if (versionIsSCORM2004)\n {\n result = api.SetValue(dotBindingName, value);\n }\n else\n {\n result = api.LMSSetValue(dotBindingName, value);\n }\n \n //DebugPrint(dotBindingName + \":\" + value + \":\" + result);\n \n if (result.toString() != \"true\")\n {\n var err = ErrorHandler();\n message(\"SetValue(\"+dotBindingName+\", \"+value+\") failed. \\n\"+ err.code + \": \" + err.string);\n GetUnity().SendMessage(objectname, callbackname, result.toString() + \"|\" + err.code + \"|\" + err.string + \"|\" + randomnumber);\n }else\n {\n GetUnity().SendMessage(objectname, callbackname, result.toString() + \"|\" + \"|\" + \"|\" + randomnumber);\n }\n }\n}", "function setattr( obj, name, value )\n { obj[name] = value; }", "set metallic(value) {}", "async setValue(cap, value) {\n if (value == null) return;\n if (typeof value === 'number') {\n value = formatValue(value);\n }\n if (this.getCapabilityValue(cap) !== value) {\n await this.setCapabilityValue(cap, value).catch(e => {\n this.log(`Unable to set capability '${ cap }': ${ e.message }`);\n });\n }\n }", "set(target, property, value, receiver) {\n const updateWasSuccessful = trap.set(target, property, value, receiver);\n return updateWasSuccessful;\n }", "set (...args) {\n let arity = args.length;\n let mutators = this.mutators();\n let defaults = [v=>v];\n\n let assign = (value, attr) => {\n let [set] = mutators[attr] || defaults;\n this.attrs[attr] = set(value);\n };\n\n if (arity < 1) {\n throw new Error('expected at least one argument');\n }\n if (arity > 2) {\n throw new Error('expected no more than two arguments');\n }\n\n if (arity === 1) {\n each(args[0], assign);\n return;\n }\n\n let [attr, value] = args;\n assign(value, attr);\n }", "function set( key, value, ttl ) {\n var expires = ttl && new Date( +new Date() + ttl * 1000 ),\n obj = {\n expires: +expires,\n value: value\n };\n \n if ( use_localStorage ) {\n try {\n localStorage[ key ] = JSON.stringify( obj );\n } catch(e) {\n return e;\n }\n } else {\n cache[ key ] = obj;\n }\n }", "setValue(attributeName, value) {\n const arg = this.args[attributeName];\n const newIdx = arg ? arg.values.indexOf(value) : 0;\n\n if (arg && newIdx !== -1 && newIdx !== arg.idx) {\n arg.idx = newIdx;\n this.emit('state.change.value', {\n value: arg.values[arg.idx],\n idx: arg.idx,\n name: attributeName,\n instance: this,\n });\n return true;\n }\n\n if (arg === undefined && this.externalArgs[attributeName] !== value) {\n this.externalArgs[attributeName] = value;\n this.emit('state.change.value', {\n value,\n name: attributeName,\n external: true,\n instance: this,\n });\n return true;\n }\n\n return false;\n }", "setUserData (user = {}) {\n this.memory.set(this.getName(\"userData\"), user);\n }", "static from(type, value) {\n return new Typed(_gaurd, type, value);\n }", "set value(_) {\n throw \"Cannot set computed property\";\n }", "set(x, y, value) {\n this.content[y * this.width + x] = value;\n }", "_setDataToUI() {\n const data = this._data;\n if (data === undefined) return;\n console.log('View#_setDataToUI', this);\n\n if (data instanceof Object) {\n eachEntry(data, ([name, val]) => this._setFieldValue(name, val));\n } else {\n this._setVal(this.el, data);\n }\n }", "function setMetaDescription(description) {\r\n\t\t\tif (typeof description === 'string') {\r\n\t\t\t\tmetaDescription = description;\r\n\t\t\t} else {\r\n\t\t\t\tmetaDescription = '';\r\n\t\t\t}\r\n\t\t}", "set(key, value){\n //1. get hash\n const hash = this.hash(key) //creating a hash\n\n //2. make value entry\n const entry = {[key]: value};\n\n //3. set the entry to the hash value in the map\n //3.1 check to see if there is hash there, if not put a LL in\n if(!this.map[hash]){\n this.map[hash] = new LinkedList();\n }\n\n //add the entry\n this.map[hash].add(entry); //add makes add(entry) node the new head\n }", "set(key, value = null) {\n // If only argument is an Object, merge Object with internal data\n if (key instanceof Object && value == null) {\n const updateObj = key;\n Object.assign(this.__data, updateObj);\n this.__fullUpdate = true;\n return;\n }\n\n // Add change to internal updates set\n this.__updates.add(key);\n\n // Set internal value selected by dot-prop key\n DotProp.set(this.__data, key, value);\n }", "set contentType(aValue) {\n this._logService.debug(\"gsDiggThumbnailDTO.contentType[set]\");\n this._contentType = aValue;\n }", "set user(aValue) {\n this._logger.debug(\"user[set]\");\n this._user = aValue;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Time: O(2n) > n Where n is the amount of even nodes in the LinkedList Space: O(1)
removeEvenValues() { let current = this.head; while (this.head.value % 2 === 0) { if (this.head.next) { current = this.head.next; this.head.next = null; this.head = current; } else { this.head.value = null; } } while (current.next) { if (current.next.value % 2 === 0) { if (current.next.next) { const helper = current.next.next; current.next.next = null; current.next = helper; } else { current.next = null; } } else { current = current.next; } } }
[ "function findHalf(head, stack) {\n var runner1, runner2;\n runner1 = runner2 = head;\n\n while (runner2) {\n stack.push(runner1.value);\n runner1 = runner1.next;\n runner2 = runner2.next;\n runner2 = runner2.next;\n if (!runner2 || !runner2.next) break;\n }\n\n while (runner2 && runner2.next) {\n runner1 = runner1.next;\n runner2 = runner2.next.next;\n }\n\n\n // when LL is even\n if (!runner2) {\n return runner1;\n } else {\n return runner1.next;\n }\n}", "setupLoop(n) {\n const loopTo = this.kToLast2(n);\n if(loopTo === null){\n return loopTo;\n }\n let current = loopTo;\n while(current && current.next){\n current = current.next;\n }\n if(current === loopTo){\n return null;\n }\n current.next = loopTo;\n return this;\n\n }", "function kthToLastIterative(head, k) {\n let p1 = head,\n p2 = head\n\n for (let i = 0; i < k; i++) {\n if (!p2) return null //k > size of linked list\n p2 = p2.next\n }\n\n while (p2) {\n p1 = p1.next\n p2 = p2.next\n }\n\n return p1\n}", "function removeNthFromEnd(head, n) {\n let current = head;\n let previous = head;\n let ahead = head;\n let count = 0;\n while (count < n && ahead) {\n ahead = ahead.next;\n count++;\n }\n while (ahead) {\n ahead = ahead.next;\n previous = current;\n current = current.next\n }\n if (previous == current) {\n return head.next\n } else if (!head) {\n return null;\n } else {\n previous.next = current.next;\n return head;\n }\n\n return head;\n}", "_getNode(idx) {\n let currentNode = this.head;\n let count = 0;\n\n while (currentNode !== null && count !== idx) {\n currentNode = currentNode.next;\n count++;\n }\n return currentNode;\n }", "function detectCycle(head) {\n\tlet p1 = head;\n\tlet p2 = head;\n\twhile (p2) {\n\t\tif (!p2.next) {\n\t\t\treturn null;\n\t\t}\n\t\tp1 = p1.next;\n\t\tp2 = p2.next.next;\n\t\tif (p1 === p2) {\n\t\t\tp1 = head;\n\t\t\twhile (true) {\n\t\t\t\tif (p1 === p2) {\n\t\t\t\t\treturn p1;\n\t\t\t\t}\n\t\t\t\tp1 = p1.next;\n\t\t\t\tp2 = p2.next;\n\t\t\t\t\n\t\t\t}\n\t\t} \n\t} \n\treturn null;\t\n}", "traverseToIndex(index) {\n let counter = 1;\n let currentNode = this.head;\n\n while (counter !== index) {\n currentNode = currentNode.next;\n counter++;\n }\n\n return currentNode;\n }", "function FibonacciSumEven (n) {\n let start = [1, 2];\n let sumOfEven = 2;\n\n for (let i = start.length-1; i < n-2; i++) {\n let nextNumb = start[i] + start[i-1];\n start.push(nextNumb);\n if (nextNumb % 2 === 0) {\n sumOfEven += nextNumb;\n }\n }\n\n return sumOfEven;\n}", "function removeKthNodeFromEnd(head, k) {\n let firstPointer = head;\n let secondPointer = head;\n while (k >= 1) {\n secondPointer = secondPointer.next;\n k--;\n }\n if (secondPointer === null) {\n head.value = head.next.value;\n head.next = head.next.next;\n //Below is the alternate solution if you wanted to return the head of the\n //Linked List that removed the kth node.\n // let solution = head.next\n // return solution\n }\n while (secondPointer.next !== null) {\n firstPointer = firstPointer.next;\n secondPointer = secondPointer.next;\n }\n firstPointer.next = firstPointer.next.next;\n //Return head if you need it\n //return head\n}", "function forwardDifference (n, xs) {\n // Good luck!\n}", "function DoubleLL() {\n this.head = null;\n this.tail = null; \n}", "function isPalindrome(theList) {\r\n\tif(theList == null) return false;\r\n\t\r\n\t//set up the nodes; counter counts the number nodes in the list - I'm assuming that info isn't given to us \r\n\tvar listStart = theList, listEnd = theList, counter = 0; \r\n\twhile(listEnd.next != null) {\r\n\t\tlistEnd = listEnd.next;\r\n\t\tcounter++;\r\n\t} \r\n\tcounter++;\r\n\t\r\n\t//I use counter just so we can know if the list has an even or odd number of items; this determines how we'll end the loop\r\n\tif(counter % 2 != 0) {\r\n\t\t//an odd number of nodes means that the ends will converge into one middle node \r\n\t\twhile(listStart != listEnd) {\r\n\t\t\t//stop immediately if we are ever not equal\r\n\t\t\tif(listStart.value != listEnd.value) {\r\n\t\t\t\treturn false;\r\n\t\t\t}\r\n\t\t\t//move nodes closer to each other\r\n\t\t\tlistStart = listStart.next;\r\n\t\t\tlistEnd = listEnd.prev;\r\n\t\t}\r\n\t} else if(counter % 2 == 0) {\r\n\t\t//an even number of nodes means that we will have two center nodes \r\n\t\twhile(listStart.next != listEnd) {\r\n\t\t\t//stop immediately if we are ever not equal\r\n\t\t\tif(listStart.value != listEnd.value) {\r\n\t\t\t\treturn false;\r\n\t\t\t}\r\n\t\t\t//move nodes closer to each other\r\n\t\t\tlistStart = listStart.next;\r\n\t\t\tlistEnd = listEnd.prev;\r\n\t\t}\r\n\t\t//this loop stops before checking the final two nodes in the middle, so we do the check again \r\n\t\tif(listStart.value != listEnd.value) {\r\n\t\t\treturn false;\r\n\t\t}\r\n\t}\r\n\r\n\treturn true;\r\n}", "function partition(sll, partition){\n\n if(!sll.head){\n return undefined;\n }\n\n var lower = new SLL();\n var higher = new SLL();\n var current = sll.head;\n\n // Traverse sll\n while(current){\n\n // if the current node's value is lower than the partition value, place that value in the lower sll\n if(current.val < partition){\n if(!lower.head){\n lower.head = new node(current.val);\n var lower_pointer = lower.head;\n }else{\n lower_pointer.next = new node(current.val);\n lower_pointer = lower_pointer.next;\n }\n }\n\n // if the current node's value is higher than the partition value, place that value in the higher sll\n else if(current.val > partition){\n if(!higher.head){\n higher.head = new node(current.val);\n var higher_pointer = higher.head;\n }else{\n higher_pointer.next = new node(current.val);\n higher_pointer = higher_pointer.next;\n }\n }\n\n // if the current node's value is the same as the partition add as a head in the higher sll and connect it to the old list\n else if(current.val == partition){\n if(!higher.head){\n higher.head = new node(current.val);\n var higher_pointer = higher.head;\n }else{\n var old = higher.head;\n higher.head = new node(current.val);\n higher.head.next = old;\n higher_pointer = higher_pointer.next;\n }\n }\n current = current.next;\n }\n lower_pointer.next = higher.head;\n return lower.head;\n}", "function firstEvenNumbersSum(n) {\n if (n === 1) return 2;\n let nthEven = 2 * n;\n return nthEven + firstEvenNumbersSum(n - 1);\n}", "function printOdds(n) { \n if(n%2 != 0)\n console.log(n)\n if(n == 0) return;\n\n printOdds(n-1)\n}", "function evenOddTransform(arr, n) {\n\tfor (let i = 0; i < n; i++) {\n\t\tfor (let j = 0; j < arr.length; j++) {\n\t\t\tif (arr[j] % 2 !== 0) {\n\t\t\t\tarr[j] += 2;\n\t\t\t} else if (arr[j] % 2 === 0) {\n\t\t\t\tarr[j] -= 2;\n\t\t\t}\n\t\t}\n\t}\n\treturn arr;\n}", "addToHead(val) {\n // console.log('something')\n\n const node = new Node(val)\n if(this.head === null){\n this.head = node;\n this.tail = node;\n\n } else {\n const temp = this.head;\n this.head = node;\n this.head.next = temp;\n\n }\n\n this.length++\n return this\n }", "function getTailAndSize(ll) {\n\tlet currentNode = ll.head;\n\tlet counter = 1;\n\n\twhile(currentNode.next) {\n\t\tcurrentNode = currentNode.next;\n\t\tcounter++;\n\t}\n\n\treturn { tail: currentNode, size: counter };\n}", "function doStuff4(N) {\n let myNum = 2;\n myNum = myNum * myNum * myNum;\n\n doStuff3(N); // O(N+4) + 2\n\n for (let i = 0; i < N; i++) {\n // O(N)\n }\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Initialize the Elastic Search Server connection
async initialize() { const nodes = this._config.get(CONFIG_KEY.ES_NODE); const maxRetries = this._config.get(CONFIG_KEY.ES_MAXRETRIES); const requestTimeout = this._config.get(CONFIG_KEY.ES_REQUEST_TIMEOUT); const sniffOnStart = this._config.get(CONFIG_KEY.ES_SNIFF_ON_START); Assert.isNonEmptyArray(nodes, 'esHostname'); this.client = new Client({ nodes, maxRetries, requestTimeout, sniffOnStart }); this._logger.info(`Trying to establish connection to Elastic Search with host ${nodes}`); // Create an index/mapping if it doesn't exist await this.createIndexIfNotExists(); // Test connection if (!this.client) { this._logger.error('Can not connect to Elastic Search database'); throw new Error('Could not connect to Elastic Search database'); } }
[ "function createElasticConnection () {\n\n if (testing) {\n function genPromise() {\n return new Promise(function(resolve, reject) { reject(\"No els\"); });\n }\n\n els = {\n search: function() { return genPromise(); },\n index: function() { return genPromise(); },\n delete: function() { return genPromise(); }\n };\n\n return;\n }\n\n console.log(\"Attempting connection\")\n els = new elasticsearch.Client({\n host: 'elk:9200',\n requestTimeout: Infinity,\n keepAlive: true\n });\n\n els.ping({\n requestTimeout: 2500,\n }, (error) => {\n console.log(\"Attempting connection to elastic search failed, retrying\")\n if (error)\n setTimeout(createElasticConnection, 2500)\n });\n\n }", "startEMR() {\n this.express = express();\n this.middleware();\n this.routes();\n this.setNodeConfiguartionFromDockerCommand();\n }", "configure() {\n mongoose.connect(nconf.get('DATABASE'), this.opts);\n }", "static init() {\n\t\tconst oThis = this;\n\t\t// looping over all databases\n\t\tfor (let dbName in mysqlConfig['databases']) {\n\t\t\tlet dbClusters = mysqlConfig['databases'][dbName];\n\t\t\t// looping over all clusters for the database\n\t\t\tfor (let i = 0; i < dbClusters.length; i++) {\n\t\t\t\tlet cName = dbClusters[i],\n\t\t\t\t\tcConfig = mysqlConfig['clusters'][cName];\n\n\t\t\t\t// creating pool cluster object in poolClusters map\n\t\t\t\toThis.generateCluster(cName, dbName, cConfig);\n\t\t\t}\n\t\t}\n\t}", "function initializeConnection() {\n //Add my libs\n var handlers = require( './handlers.js' );\n\n //Initialize the ssh connection\n connection = new Connection(),\n handler = domain.create();\n //Handling \"error\" event inside domain handler.\n handler.add(connection);\n //Add global connection handlers\n handlers.setGlobalConnectionHandlers();\n //Start connection\n connection.connect(OptionsForSFTP);\n}", "constructor() { \n \n ComDayCqReplicationImplAgentManagerImplInfo.initialize(this);\n }", "constructor() {\n\n V1DaskReplica.initialize(this);\n }", "function initLunr() {\n if (!endsWith(fsdocs_search_baseurl,\"/\")){\n fsdocs_search_baseurl = fsdocs_search_baseurl+'/'\n };\n\n // First retrieve the index file\n $.getJSON(fsdocs_search_baseurl +\"index.json\")\n .done(function(index) {\n pagesIndex = index;\n // Set up lunrjs by declaring the fields we use\n // Also provide their boost level for the ranking\n lunrIndex = lunr(function() {\n this.ref(\"uri\");\n this.field('title', {\n\t\t boost: 15\n });\n this.field('tags', {\n\t\t boost: 10\n });\n this.field(\"content\", {\n\t\t boost: 5\n });\n\t\t\t\t\n this.pipeline.remove(lunr.stemmer);\n this.searchPipeline.remove(lunr.stemmer);\n\t\t\t\t\n // Feed lunr with each file and let lunr actually index them\n pagesIndex.forEach(function(page) {\n\t\t this.add(page);\n }, this);\n })\n })\n .fail(function(jqxhr, textStatus, error) {\n var err = textStatus + \", \" + error;\n console.error(\"Error getting Hugo index file:\", err);\n });\n}", "constructor() { \n \n OrgApacheJackrabbitOakSegmentSegmentNodeStoreFactoryProperties.initialize(this);\n }", "initializeIndex() {\n if (NylasEnv.config.get('threadSearchIndexVersion') !== INDEX_VERSION) {\n return this.clearIndex()\n .then(() => this.buildIndex(this.accountIds))\n }\n\n return this.buildIndex(this.accountIds);\n }", "function initApolloServer() {\n const server = new ApolloServer({ typeDefs, resolvers });\n server.listen().then(({ url }) => {\n console.log(`🚀 Server ready at ${url}`);\n });\n}", "function initServer() {\n var options = {\n dataAdapter: new DataAdapter(config.api),\n errorHandler: mw.errorHandler(),\n appData: config.rendrApp\n };\n server = rendr.createServer(app, options);\n}", "async initialize() {\n this.loadEnv();\n this.loadConfiguration();\n }", "function initializeServer(){\n // these are the credentials to use to connect to the Hyperledger Fabric\n let participantId = config.get('participantId');\n let participantPwd = config.get('participantPwd');\n // physial connection details (eg port numbers) are held in a profile\n let connectionProfile = config.get('connectionProfile');\n // the logical business newtork has an indentifier\n let businessNetworkIdentifier = config.get('businessNetworkIdentifier');\n\n businessNetworkConnection.connect(connectionProfile, businessNetworkIdentifier, participantId, participantPwd).then(function(result){\n businessNetworkDefinition = result;\n console.log('Connected: BusinessNetworkDefinition obtained=' + businessNetworkDefinition.getIdentifier());\n });\n\n console.log('%s listening at %s', server.name, server.url);\n}", "function OSSAdapter() {\r\n var options = optionsFromArguments(arguments);\r\n this._region = options.region;\r\n this._internal = options.internal;\r\n this._bucket = options.bucket;\r\n this._bucketPrefix = options.bucketPrefix;\r\n this._directAccess = options.directAccess;\r\n this._baseUrl = options.baseUrl;\r\n this._baseUrlDirect = options.baseUrlDirect;\r\n\r\n let ossOptions = {\r\n accessKeyId: options.accessKey,\r\n accessKeySecret: options.secretKey,\r\n bucket: this._bucket,\r\n region: this._region,\r\n internal: this._internal\r\n };\r\n this._ossClient = new OSS(ossOptions);\r\n this._ossClient.listBuckets().then((val)=> {\r\n var bucket = val.buckets.filter((bucket)=> {\r\n return bucket.name == this._bucket\r\n }).pop();\r\n\r\n this._hasBucket = !!bucket;\r\n });\r\n}", "init(bot) {\n Log.info(`Loading server config...`);\n serverConfig.find({}).then(configs => {\n configs.forEach(row => {\n this.set(row.guildId, new ServerConfigItem(this, row._doc));\n });\n for (const guild of bot.guilds) {\n if (!guild) return false;\n if (!this.has(guild[1].id)) {\n this.AddGuild(guild[1]).catch(Log.error);\n }\n }\n }).catch(Log.error);\n\n this._bot = bot;\n }", "constructor() { \n \n S3StorageConfig.initialize(this);\n }", "_initSwaggerClient() {\n LOG.debug('Initializing Client with Swagger URL: ', this._swaggerUrl);\n\n const CLIENT = new SwaggerClient({\n url: this._swaggerUrl,\n usePromise: true,\n });\n\n CLIENT.then((client) => {\n this.client = client;\n this._clientReady();\n LOG.debug('SwaggerClient successfully initialized.');\n });\n\n CLIENT.catch((error) => {\n LOG.error('Error initializing SwaggerClient: ', error);\n });\n }", "startDiscovery() {}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
When the user moves the mouse between the main menu button and the submenu there might be a mouseout() event that will dismiss the submenu. To avoid this UI problem the dismissal is delayed by a little bit and the submenu gets a window in which to cancel its own dismissal.
function dismiss() { while( subMenu = subMenusUp.pop() ) { if( ! subMenu.cancelDismiss ) { subMenu.getElementsByTagName("ul")[0].style.display = "none"; } } }
[ "function close()\n{\n\tif(menuitem) menuitem.style.visibility = 'hidden'; // hide the sub menu\n} // end function", "static onMenuItemClicked(event) {\n let menuHideOnClick = $(event.target).parents(\".popup-menu\").data(\"hide-on-click\");\n let itemHideOnClick = $(event.target).parents(\"li\").data(\"hide-on-click\");\n let hideOnClick = itemHideOnClick !== undefined ? itemHideOnClick : menuHideOnClick;\n\n if (hideOnClick) {\n let tippy = $(event.target).parents(\"[data-tippy-root]\").get(0)?._tippy;\n tippy?.hide();\n }\n }", "function closeMobileMenu() {\n navMenuMobile.style.maxHeight = null;\n navMenuMobile.style.pointerEvents = 'none';\n bodyOverlay.style.opacity = 0;\n document.querySelector('body').style.overflow = 'unset';\n bodyOverlay.style.pointerEvents = 'none';\n navTriangle.style.display = 'none';\n}", "async closeMenu() {\n const closeMenuLocator = await this.components.menuCloseButton()\n await closeMenuLocator.click()\n }", "closeMenuSoon_() {\n const menu = /** @type {!CrActionMenuElement} */ (this.$.menu.get());\n setTimeout(function() {\n if (menu.open) {\n menu.close();\n }\n }, settings.kMenuCloseDelay);\n }", "function w3int_menu_close(evt)\n{\n //event_dump(evt, 'MENU-CLOSE');\n if ((evt.type == 'keyup' && evt.key == 'Escape') ||\n (evt.type == 'click' && evt.button != 2 )) {\n //console.log('w3int_menu_close '+ evt.type +' button='+ evt.button);\n w3int_menu_onclick(null, w3int_menu_close_cur_id);\n }\n}", "function buttonMenu(event) {\n let menu = new Windows.UI.Popups.PopupMenu();\n\n let button = this;\n\n menu.commands.append(new Windows.UI.Popups.UICommand(\"Remove\", function () { onRemove(button); }));\n menu.commands.append(new Windows.UI.Popups.UICommand(\"Log out\", function () { onLogOut(button); }));\n\n // Crashed here too! :c\n menu.showAsync(pageToWinRT(event.pageX, event.pageY)).done(function (invokedCommand) {\n if (invokedCommand === null) {\n // The command is null if no command was invoked.\n WinJS.log && WinJS.log(\"Context menu dismissed\", \"sample\", \"status\");\n }\n });\n\n }", "function handleOutsideClick(e) {\n if (topMenuRef.current && !topMenuRef.current.contains(e.target)) {\n // dispatch({ type: \"RESET\", where: \"top\" });\n }\n }", "function onMouseDown(e) {\n dismissTooltipOfParent(e.currentTarget, false);\n }", "onPopupMouseLeave() {\n this.delaySetPopupVisible(false, this.props.delayHide);\n }", "function closeUpdateUserInfoMenu() {\n console.log(\"Is closing\");\n\n // Remove the update backdrop and update menu from the view\n $(\"div\").remove('#update-user-info-backdrop');\n $(\"div\").remove('#update-user-info-menu');\n}", "function onMouseOut(e) {\n // Only take action if the relatedTarget is not the currentTarget or a child of the currentTarget\n if (e.relatedTarget && (e.currentTarget !== e.relatedTarget) && !hasChild(e.currentTarget, e.relatedTarget)) {\n dismissTooltipOfParent(e.currentTarget);\n }\n }", "mouseOut() {\n this.setState({\n markingMenu: { ...this.state.markingMenu, mouseOver: false }\n });\n }", "function closeAsideMenu_() {\n\n if ( asideBtn.classList.contains('presentation__aside-open--opened') )\n asideBtn.classList.remove('presentation__aside-open--opened');\n\n }", "function menuClosed() {\n mainNav.classList.remove('main-nav-reveal');\n html.classList.remove('html-nav-opened');\n mainNav.style.overflowY = 'unset';\n}", "function closeBurgerMenu() {\n $menuBurgerOverlay.removeClass('open');\n $body.removeClass('overflow');\n }", "onElementMouseOut(event) {\n super.onElementMouseOut(event);\n\n const me = this;\n\n // We must be over the event bar\n if (event.target.closest(me.eventInnerSelector) && me.resolveTimeSpanRecord(event.target) && me.hoveredEventNode) {\n // out to child shouldn't count...\n if (event.relatedTarget && DomHelper.isDescendant(event.target.closest(me.eventInnerSelector), event.relatedTarget)) return;\n\n me.unhover(event);\n }\n }", "function hideTutorialsMenu()\n{\n\ttutorialsTimeoutId = window.setTimeout(\"turnOffMenu('\" + tutorialsMenu + \"')\", 60 * 3);\n}", "function hideResourcesMenu()\n{\n\tresourcesTimeoutId = window.setTimeout(\"turnOffMenu('\" + resourcesMenu + \"')\", 60 * 3);\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Devuelve la instancia de la clase AlmacenesRoute
static get instanceAlmacenRoute() { return this.almacenesRouteInstance || (this.almacenesRouteInstance = new this()); }
[ "_generateRoute( answers ) {\n\n // monta a rota\n let obj = {\n route : `/${answers.path}`,\n controller : `${answers.controller}Controller`,\n function : `${answers.method}`,\n method : answers.action,\n is_public : ( answers.is_public === 'yes' || answers.is_public === 'y' ) \n };\n\n // escreva a rota\n this._writeRoute( obj );\n }", "function Route() {\n _classCallCheck(this, Route);\n\n Route.initialize(this);\n }", "createRouteTable() {\n this.routeTable = new Map();\n for (const [controllerMethod, annotations] of this.annotations) {\n const accepts = [];\n let method = null;\n for (const annotation of annotations) {\n switch (annotation.name) {\n case 'method':\n method = annotation.args[0];\n break;\n case 'accept':\n accepts.push(annotation.args[0]);\n break;\n }\n }\n if (method === null) {\n throw new Error('Controller method ' + controllerMethod + ' was annotated, but it needs a @method annotation to actually do anything');\n }\n if (!this.routeTable.has(method)) {\n this.routeTable.set(method, {\n accepts: new Map(),\n default: null\n });\n }\n const route = this.routeTable.get(method);\n if (accepts.length === 0) {\n route.default = controllerMethod;\n }\n else {\n for (const mime of accepts) {\n if (mime === '*') {\n route.default = controllerMethod;\n }\n else {\n route.accepts.set(mime, controllerMethod);\n }\n }\n }\n }\n }", "createRouter() {\n this.router = new Router(this);\n }", "function Route(title,name,htmlName,builder){\n this.title= title;\n this.name = name;\n this.htmlName = htmlName;\n this.builder = builder;\n}", "get routes() {\n return JSON.parse(JSON.stringify(this._routes));\n }", "function Route(props) {\n return __assign({ Type: 'AWS::EC2::Route' }, props);\n }", "function route_all(){\n\n /*\n Routing all\n */\n\n main_init()\n other_routes()\n\n}", "function addRoute() {\n routes.addRoute(vm.formInfo, user.getUser().username)\n .then(function() {\n // clear form data\n vm.formInfo.methodKeys.length = 0;\n vm.formInfo.methods = {};\n vm.formInfo.route = '';\n vm.formInfo.persistence = false;\n });\n }", "loadRoutes() {\n this._routes = this.loadConfigFile('routes') || function() {};\n }", "static get baseRoute () {\n throw new Error('Not implemented')\n }", "$registerRouter() {\n this.$container.singleton('Adonis/Core/Route', () => {\n return this.$container.use('Adonis/Core/Server').router;\n });\n }", "mountRoutes() {}", "refresh() {\n const temp = this.routeName;\n\n this.routeName = this.fullRouteName;\n this._super(...arguments);\n this.routeName = temp;\n }", "get routePath() {\n return this._routePath;\n }", "methodsAction(req, res) {\n const routes = [];\n const scenes = Object.keys(config.tradfri.scenes);\n\n for(let route = 0; route < scenes.length; route++) {\n routes.push(`/api/scene/${scenes[route]}`);\n }\n\n routes.push('/api/disco');\n\n this.jsonResponse(res, 200, { 'routes': routes });\n }", "route() {\n return (request, response) => {\n Promise.all([bodyParser(request)]) \n .then(() => {\n logger.log(logger.INFO, `Router rec'd: ${request.method} ${request.url.pathname}`);\n // the line below retrieves the ROUTE callback using the request method and pathname\n // as route (this) object keys.\n const requestResponseCallback = this.routes[request.method][request.url.pathname];\n const isFunction = typeof requestResponseCallback === 'function';\n if (isFunction) return requestResponseCallback(request, response);\n \n customResponse.sendError(response, 404, `API path ${request.url.pathname} not found.`);\n return undefined;\n })\n .catch((err) => {\n logger.log(logger.INFO, JSON.stringify(err));\n customResponse.sendError(response, 400, 'Bad request received.');\n return undefined;\n });\n };\n }", "_initialize() {\n if ( this._initialized ) {\n return;\n }\n\n this._log(2, `Initializing Routes...`);\n\n //Add routing information to crossroads\n // todo: handle internal only routes\n // An internal only route can be used to keep track of UI state\n // But it will never update the URL\n // You can't use .go() to get to an internal route\n // You can only get it via directly calling dispatch(route, params)\n //\n let routes = this.routes;\n\n for (let route of routes) {\n this._log(3, `Initializing >> ${route.name}`);\n\n // Set basename\n route.set_basename(this._basename);\n // Set crossroads_route\n route._crossroads = this.crossroads.addRoute(route.path, this._make_crossroads_shim(route));\n }\n\n this._log(3, `Initialized ${routes.length} routes`);\n this._initialized = true;\n }", "merge(router) {\n for (var route of router.routes) {\n this.routes.push(route);\n }\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Handle received done message. Records done received. Next run stop detects and performs wrapup.
handleDone () { const priv = privs.get(this) switch (priv.state) { case State.Done: case State.Errored: return case State.Running: case State.Stopped: case State.Stopping: priv.state = State.Done } }
[ "handleRunStopped () {\n const priv = privs.get(this)\n if (priv.state === State.Done) privm.wrapup.call(this)\n }", "function done() {\n putstr(padding_left(\" DONE\", seperator, sndWidth));\n putstr(\"\\n\");\n }", "function completedProcess(self) {\n\t//console.log('completedProcess called');\n\tself.emit('completedProcess', self.file, self.fileObjectList.getAll());\n\tconsole.log(\"FeedFileProcessor : Finished processing \", self.file);\n\t//console.log(\"Contents are \", self.fileObjectList.getAll());\n\n}", "function dispatchingFilesFinished() {\n // NOTE: ignoring possible error because processOneFile never passes error to async\n if (this.errors.length > 0) {\n callback(this.errors);\n } else {\n callback(null, this.stats);\n }\n }", "finish() {\n if (!this.disabled) {\n this._sendBatch();\n this.clearEvents();\n }\n }", "function handleEnd(dataChunked) {\n\t\t\t\ttry {\n\t\t\t\t\tcontent = JSON.parse(dataChunked);\n\t\t\t\t\tcallback(content);\n\t\t\t\t} catch(ex) {\n\t\t\t\t\tthrow new Error(ex);\n\t\t\t\t}\n\t\t\t}", "function video_done(e) {\n\tthis.currentTime = 0;\n}", "onScanCompleted_() {\n if (this.scanCancelled_) {\n return;\n }\n\n this.processNewEntriesQueue_.run(callback => {\n // Call callback first, so isScanning() returns false in the event\n // handlers.\n callback();\n dispatchSimpleEvent(this, 'scan-completed');\n });\n }", "function toggle_done() {\n if (active_timer_idx >= 0 && active_timer_idx != selected_timer_idx) {\n return; // Special case of discussion toggled on. Don't set to done in this case.\n }\n\n var next_timer_idx = -1;\n if (active_timer_idx < 0) {\n timer_object = timers[selected_timer_idx];\n } else {\n timer_object = timers[active_timer_idx];\n if (typeof timers[active_timer_idx + 1] != 'undefined') {\n next_timer_idx = active_timer_idx + 1;\n }\n }\n if (timer_object != null) {\n if (active_timer_idx >= 0) {\n timer_object.circleProgress('timer_done', 1);\n start_stop_timer(active_timer_idx, 0);\n if (next_timer_idx >= 0) {\n change_selected_to(next_timer_idx);\n start_stop_timer(next_timer_idx, 1);\n active_timer_idx = next_timer_idx;\n } else {\n active_timer_idx = -1;\n }\n\n } else {\n timer_object.circleProgress('timer_done', -1);\n }\n }\n}", "async processQueue() {\n let message;\n while (this.queue.length) {\n if (!message || this.needsTaskBoundaryBetween(this.queue[0], message)) {\n await async_1.timeout(0);\n }\n message = this.queue.shift();\n if (!message) {\n return; // may have been disposed of\n }\n switch (message.type) {\n case 'event':\n if (this.eventCallback) {\n this.eventCallback(message);\n }\n break;\n case 'request':\n if (this.requestCallback) {\n this.requestCallback(message);\n }\n break;\n case 'response':\n const response = message;\n const clb = this.pendingRequests.get(response.request_seq);\n if (clb) {\n this.pendingRequests.delete(response.request_seq);\n clb(response);\n }\n break;\n }\n }\n }", "_handleNextDataEvent() {\n this._processingData = false;\n let next = this._dataEventsQueue.shift();\n if (next) {\n this._onData(next);\n }\n }", "afterGrpcCallFinish() {\n this.tracer.scoped(() => {\n this.tracer.setId(this.traceId);\n this.tracer.recordAnnotation(new Annotation.ClientRecv());\n });\n }", "function onTakePlayComplete (detail) {\n _log('Did receive \\'playcomplete\\' with detail: ' + JSON.stringify(detail));\n\n if (opts.takes) {\n opts.takes.find(opts.selectedTakesSelector).removeClass('playing')\n }\n if (opts.playPause) {\n opts.playPause.removeClass('disabled');\n }\n if (opts.record) {\n opts.record.removeClass(opts.recordDisableClass);\n }\n\n if (didHaveSlowEnabled) {\n logAndSend('slow', {value: true});\n if (opts.slow) {\n createSelfCancellingActiveChecker(opts.slow);\n }\n }\n\n if (didHaveRepeatEnabled) {\n logAndSend('repeat', {value: true});\n if (opts.loop) {\n createSelfCancellingActiveChecker(opts.loop);\n }\n }\n\n didHaveRepeatEnabled = false;\n didHaveSlowEnabled = false;\n\n window.removeNativeEventListener('playcomplete', onTakePlayComplete);\n }", "handleBreakClipEnded(event) {\n let data = {};\n data.id = this.breakClipId;\n this.breakClipStarted = false;\n this.breakClipLength = null;\n this.breakClipId = null;\n this.qt1 = null;\n this.qt2 = null;\n this.qt3 = null;\n\n data.action = event.endedReason;\n this.sendData(data);\n }", "tripAllDone(){\r\n\t\tthis.recorded_trip.forEach(function(trip){\r\n\t\t\ttrip.done = true\r\n\t\t})\r\n\t}", "function handleDoneList(e) {\n const li = e.target.parentNode.parentNode;\n finishNoList.style.display = \"none\";\n handleCreateFinished(li.innerText);\n\n handleDelToDos(e);\n}", "function onExit(done) {\n done();\n}", "function onRecordComplete (detail) {\n _log('onRecordComplete: ' + JSON.stringify(detail));\n\n console.log('isRecording: false from within `onRecordComplete`');\n window.MusicStudio.isRecording(false);\n\n stopTrackPlaybackProgress();\n\n // KK, 2017-05-09, This conditional was for the headphone merging\n // if (!hasHeadphones) {\n hideLoading();\n console.log('recordTakeFinished form onRecordComplete');\n recordTakeFinished(detail.index);\n // }\n\n // window.removeNativeEventListener('recordcomplete', onRecordComplete);\n // window.removeNativeEventListener('audiostop', onRecordAudioStopped);\n }", "function completeContinuePhase () {\n\t/* show the player removing an article of clothing */\n\tprepareToStripPlayer(recentLoser);\n updateAllGameVisuals();\n\t\n\t$mainButton.html(\"Strip\");\n if (players[HUMAN_PLAYER].out && AUTO_FORFEIT) {\n setTimeout(advanceGame,FORFEIT_DELAY);\n }\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns true if the given result is from failed transaction or transaction list.
static isFailedTx(result) { if (!result) { return true; } if (CommonUtil.isDict(result.result_list)) { for (const subResult of Object.values(result.result_list)) { if (CommonUtil.isFailedTxResultCode(subResult.code)) { return true; } if (subResult.func_results) { if (CommonUtil.isFailedFuncTrigger(subResult.func_results)) { return true; } } } return false; } if (CommonUtil.isFailedTxResultCode(result.code)) { return true; } if (result.func_results) { if (CommonUtil.isFailedFuncTrigger(result.func_results)) { return true; } } return false; }
[ "static txPrecheckFailed(result) {\n const precheckFailureCode = [21, 22, 3, 15, 33, 16, 17, 34, 35];\n return precheckFailureCode.includes(result.code);\n }", "static isFailedFuncTrigger(result) {\n if (CommonUtil.isDict(result)) {\n for (const fid in result) {\n const funcResult = result[fid];\n if (CommonUtil.isFailedFuncResultCode(funcResult.code)) {\n return true;\n }\n if (!CommonUtil.isEmpty(funcResult.op_results)) {\n for (const opResult of Object.values(funcResult.op_results)) {\n if (CommonUtil.isFailedTx(opResult.result)) {\n return true;\n }\n }\n }\n }\n }\n return false;\n }", "hasValidTransactions() {\n for (const tx of this.transactions) {\n if (!tx.isValid()) {\n return false;\n }\n }\n return true;\n }", "function isResult(x) {\n return x instanceof Result || className(x) === \"Result\" /* Tag.RESULT */;\n}", "_validateMultiResults (results, callback) {\n const errors = results.map(result => result[0])\n\n if (errors.some(error => !!error)) {\n callback(new Error(`${compact(errors)}`))\n } else {\n callback()\n }\n }", "Exists() {\n return this.transaction != null;\n }", "get numberOfResultsIsValid() {\n return this._isPositiveNumber(this.state.numberOfResults);\n }", "function isSuccessful(json) {\n\t\treturn json.STATUS_DATA.STATUS.toUpperCase() === \"S\" ? true : false;\n\t}", "function checkErrors(data) {\n\tif (data['error'] !== false) {\n\t\tconsole.log(data['error']);\n\t\treturn true;\n\t} else {\n\t\treturn false;\n\t}\n}", "isDebit(account) {\n return __awaiter(this, void 0, void 0, function* () {\n return (yield this.getDebitAccount()) != null && account != null && (yield this.getDebitAccount()).getNormalizedName() == account.getNormalizedName();\n });\n }", "function ePayTransactionStatus(spTrn){\n\tvar request = MFP.Server.getClientRequest();\n\tvar isAuthorizedResponse = this._isAuthorized(request);\n\tif(isAuthorizedResponse.authRequired == false) {\n\t\tvar spCode = MFP.Server.getPropertyValue(\"epay.DSGOptions.SPCODE\");\n\t\tvar servCode = \"MApp\";\n\t\t\n\t\tvar invocationData = {\n\t\t\tadapter : 'ePayAdapter',\n\t\t\tprocedure : 'getTransactionStatusWithoutRecording',\n\t\t\tparameters : [ spCode,servCode,spTrn ]\n\t\t};\n\t\n\t\tvar result = MFP.Server.invokeProcedure(invocationData);\n\t\tif(result && result.result) {\n\t\t\t_updateEPayStatus(result.result, spTrn);\n\t\t}\n\t\t\n\t\treturn result;\n\t}\n\t\n\treturn isAuthorizedResponse;\n}", "failTransaction(transaction, reason) {\n transaction.fail = true;\n\n this.ensureTransactionErrors(transaction);\n if (reason) {\n transaction.errors.push({ severity: 'error', message: reason });\n }\n\n if (!transaction.test) {\n transaction.test = this.createTest(transaction);\n }\n transaction.test.status = 'fail';\n if (reason) {\n transaction.test.message = reason;\n }\n\n this.ensureTestStructure(transaction);\n }", "loadXMLData(XMLData) {\n let transactionsDetails;\n try {\n transactionsDetails = xmlParser.parseStringSync(XMLData).TransactionList.SupportTransaction;\n } catch(err) {\n logger.warn('Invalid syntax.');\n this.lastDataLoadErrorCount++;\n return false;\n }\n\n for(let i = 0; i < transactionsDetails.length; i++) {\n let objectNumber = i + 1;\n let transactionDetails = transactionsDetails[i];\n\n if(!this.addTransaction(moment.fromOADate(transactionDetails.$.Date), transactionDetails.Parties[0].From[0], transactionDetails.Parties[0].To[0], transactionDetails.Description, transactionDetails.Value)) {\n logger.warn('Could not process transaction number ' + objectNumber + ': ' + this.lastAddTransactionError);\n this.lastDataLoadErrorCount++;\n }\n }\n\n return true;\n }", "function checkIfResult() {\n if (isFinalResult) {\n isFinalResult = false;\n displayContent = \"\";\n }\n}", "function passedFailed(expectation, message1, message2) {\n\treturn result(expectation.isNot, message1, message2);\n}", "function results_contains(results,username) {\n\tvar i;\n\tfor (i = 0; i < results.length; i++) {\n\t\tif (results[i].USERNAME == username)\n\t\t\treturn true;\n\t}\n\treturn false;\n}", "function addResult( $result ) {\n\t\tif ( Util.elementCount( $result ) === 0 ) { return };\n\t\t$results = $results.add( $result );\n\t}", "function firstOk(results) {\r\n return results.find(isOk) || error(null);\r\n}", "validateActivityStatus() {\r\n let res = this.state.selectedData.every((livestock) => {\r\n return !(livestock.ActivitySystemCode == livestockActivityStatusCodes.Deceased ||\r\n livestock.ActivitySystemCode == livestockActivityStatusCodes.Killed ||\r\n livestock.ActivitySystemCode == livestockActivityStatusCodes.Lost);\r\n });\r\n if (!res) this.notifyToaster(NOTIFY_WARNING, { message: this.strings.INVALID_RECORD_LOST_STATUS });\r\n return res;\r\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
gathers all selected cells into a commaseparated list to send as POST parameter
function concatCellIds() { var cellIds = ""; var key; var first = true; for (key in selectedCells) { if (selectedCells[key] != null && Ext.isPrimitive(selectedCells[key])) { if (!first) cellIds += ","; first = false; cellIds += key; } } var selectedCellsInput = document.getElementById("selectedCells"); selectedCellsInput.value = cellIds; return cellIds; }
[ "function updateSelectedRows() {\n var selectedList = [];\n if (grid.api) {\n var selectedRows = grid.api.selection.getSelectedRows();\n _.each(selectedRows, function (row) {\n selectedList.push(row[component.constants.ROW_IDENTIFIER]);\n });\n }\n component.onSelectRows(selectedList);\n }", "function values(){\n\t\treturn selection;\n\t}", "action() {\n if (this.selectedRows().length > 0) {\n dispatch.action(this.element, this.selectedRows());\n }\n }", "createRangeBySelectedCells() {\n const sq = this.wwe.getEditor();\n const range = sq.getSelection().cloneRange();\n const selectedCells = this.getSelectedCells();\n const [firstSelectedCell] = selectedCells;\n const lastSelectedCell = selectedCells[selectedCells.length - 1];\n\n if (selectedCells.length && this.wwe.isInTable(range)) {\n range.setStart(firstSelectedCell, 0);\n range.setEnd(lastSelectedCell, lastSelectedCell.childNodes.length);\n sq.setSelection(range);\n }\n }", "function buildMultiSelectCell(control, columnIndex) {\n var $cell = buildControlCell(control, columnIndex);\n // multiple selection - selected is an array\n if (control.selected && control.selected.indexOf(columnIndex) !== -1) {\n $cell.addClass(SELECTED_CLASS);\n }\n setSelectedText($cell, control, columnIndex);\n\n // only add the handler to non-disabled controls\n if (!$cell.hasClass(DISABLED_CLASS)) {\n $cell.click(function multiselectClick(ev) {\n var $cell = $(this);\n // can be more than one selected - toggle selected on this cell\n $cell.toggleClass(SELECTED_CLASS);\n setSelectedText($cell, control, columnIndex);\n var selectedColumnIndeces = $cell\n .parent()\n .find(`.${SELECTED_CLASS}`)\n .map((i, e) => $(e).data(COLUMN_INDEX_DATA_KEY));\n\n // fire the event from the table itself, passing the id and index of selected\n var eventData = {};\n\n var key = $cell.parent().attr(\"id\");\n eventData[key] = $.makeArray(selectedColumnIndeces);\n $cell.parents(\".peek\").trigger(CHANGE_EVENT, eventData);\n });\n }\n return $cell;\n}", "_handleRequestGetSelectedWorkflowJobs()\n {\n var workflowJobs = [];\n for (var itemIndex in this._selectedItems)\n {\n workflowJobs.push(this._selectedItems[itemIndex].getModel());\n }\n return workflowJobs;\n }", "function tableToGrid(selector, options) {\r\njQuery(selector).each(function() {\r\n\tif(this.grid) {return;} //Adedd from Tony Tomov\r\n\t// This is a small \"hack\" to make the width of the jqGrid 100%\r\n\tjQuery(this).width(\"99%\");\r\n\tvar w = jQuery(this).width();\r\n\r\n\t// Text whether we have single or multi select\r\n\tvar inputCheckbox = jQuery('tr td:first-child input[type=checkbox]:first', jQuery(this));\r\n\tvar inputRadio = jQuery('tr td:first-child input[type=radio]:first', jQuery(this));\r\n\tvar selectMultiple = inputCheckbox.length > 0;\r\n\tvar selectSingle = !selectMultiple && inputRadio.length > 0;\r\n\tvar selectable = selectMultiple || selectSingle;\r\n\t//var inputName = inputCheckbox.attr(\"name\") || inputRadio.attr(\"name\");\r\n\r\n\t// Build up the columnModel and the data\r\n\tvar colModel = [];\r\n\tvar colNames = [];\r\n\tjQuery('th', jQuery(this)).each(function() {\r\n\t\tif (colModel.length === 0 && selectable) {\r\n\t\t\tcolModel.push({\r\n\t\t\t\tname: '__selection__',\r\n\t\t\t\tindex: '__selection__',\r\n\t\t\t\twidth: 0,\r\n\t\t\t\thidden: true\r\n\t\t\t});\r\n\t\t\tcolNames.push('__selection__');\r\n\t\t} else {\r\n\t\t\tcolModel.push({\r\n\t\t\t\tname: jQuery(this).attr(\"id\") || jQuery.trim(jQuery.jgrid.stripHtml(jQuery(this).html())).split(' ').join('_'),\r\n\t\t\t\tindex: jQuery(this).attr(\"id\") || jQuery.trim(jQuery.jgrid.stripHtml(jQuery(this).html())).split(' ').join('_'),\r\n\t\t\t\twidth: jQuery(this).width() || 150\r\n\t\t\t});\r\n\t\t\tcolNames.push(jQuery(this).html());\r\n\t\t}\r\n\t});\r\n\tvar data = [];\r\n\tvar rowIds = [];\r\n\tvar rowChecked = [];\r\n\tjQuery('tbody > tr', jQuery(this)).each(function() {\r\n\t\tvar row = {};\r\n\t\tvar rowPos = 0;\r\n\t\tjQuery('td', jQuery(this)).each(function() {\r\n\t\t\tif (rowPos === 0 && selectable) {\r\n\t\t\t\tvar input = jQuery('input', jQuery(this));\r\n\t\t\t\tvar rowId = input.attr(\"value\");\r\n\t\t\t\trowIds.push(rowId || data.length);\r\n\t\t\t\tif (input.is(\":checked\")) {\r\n\t\t\t\t\trowChecked.push(rowId);\r\n\t\t\t\t}\r\n\t\t\t\trow[colModel[rowPos].name] = input.attr(\"value\");\r\n\t\t\t} else {\r\n\t\t\t\trow[colModel[rowPos].name] = jQuery(this).html();\r\n\t\t\t}\r\n\t\t\trowPos++;\r\n\t\t});\r\n\t\tif(rowPos >0) { data.push(row); }\r\n\t});\r\n\r\n\t// Clear the original HTML table\r\n\tjQuery(this).empty();\r\n\r\n\t// Mark it as jqGrid\r\n\tjQuery(this).addClass(\"scroll\");\r\n\r\n\tjQuery(this).jqGrid(jQuery.extend({\r\n\t\tdatatype: \"local\",\r\n\t\twidth: w,\r\n\t\tcolNames: colNames,\r\n\t\tcolModel: colModel,\r\n\t\tmultiselect: selectMultiple\r\n\t\t//inputName: inputName,\r\n\t\t//inputValueCol: imputName != null ? \"__selection__\" : null\r\n\t}, options || {}));\r\n\r\n\t// Add data\r\n\tvar a;\r\n\tfor (a = 0; a < data.length; a++) {\r\n\t\tvar id = null;\r\n\t\tif (rowIds.length > 0) {\r\n\t\t\tid = rowIds[a];\r\n\t\t\tif (id && id.replace) {\r\n\t\t\t\t// We have to do this since the value of a checkbox\r\n\t\t\t\t// or radio button can be anything\r\n\t\t\t\tid = encodeURIComponent(id).replace(/[.\\-%]/g, \"_\");\r\n\t\t\t}\r\n\t\t}\r\n\t\tif (id === null) {\r\n\t\t\tid = a + 1;\r\n\t\t}\r\n\t\tjQuery(this).jqGrid(\"addRowData\",id, data[a]);\r\n\t}\r\n\r\n\t// Set the selection\r\n\tfor (a = 0; a < rowChecked.length; a++) {\r\n\t\tjQuery(this).jqGrid(\"setSelection\",rowChecked[a]);\r\n\t}\r\n});\r\n}", "function TKR_HandleBulkEdit() {\n var selectedIssueRefs = GetSelectedIssuesRefs();\n var selectedLocalIDs = [];\n for(var i = 0; i < selectedIssueRefs.length; i++) {\n selectedLocalIDs.push(selectedIssueRefs[i]['id']);\n }\n if (selectedLocalIDs.length > 0) {\n var selectedLocalIDString = selectedLocalIDs.join(',');\n var url = 'bulkedit?ids=' + selectedLocalIDString;\n TKR_go(url + _ctxArgs);\n } else {\n alert('Please select some issues to edit');\n }\n}", "function retrieveValues(target){\n\t\tvar opts = $.data(target, 'combogrid').options;\n\t\tvar grid = $.data(target, 'combogrid').grid;\n\t\tvar rows = grid.datagrid('getSelections');\n\t\tvar vv = [],ss = [];\n\t\tfor(var i=0; i<rows.length; i++){\n\t\t\tvv.push(rows[i][opts.idField]);\n\t\t\tss.push(rows[i][opts.textField]);\n\t\t}\n\t\t$(target).combo('setValues', vv).combo('setText', ss.join(opts.separator));\n\t}", "function retrieveValues(target){ \n\t\tvar opts = $.data(target, 'combogrid').options; \n\t\tvar grid = $.data(target, 'combogrid').grid; \n\t\tvar rows = grid.datagrid('getSelections'); \n\t\tvar vv = [],ss = []; \n\t\tfor(var i=0; i<rows.length; i++){ \n\t\t\tvv.push(rows[i][opts.idField]); \n\t\t\tss.push(rows[i][opts.textField]); \n\t\t} \n\t\t$(target).combo('setValues', vv).combo('setText', ss.join(opts.separator)); \n\t}", "function IAjaxBatchRequest() {}", "function csvImportierenSelectColumns(editor, csv, header) {\n var selectEditor = new $.fn.dataTable.Editor();\n var fields = editor.order();\n\n for (var i = 0; i < fields.length; i++) {\n var field = editor.field(fields[i]);\n\n selectEditor.add({\n label: field.label(),\n name: field.name(),\n type: 'select',\n options: header,\n def: header[i]\n });\n }\n\n selectEditor.create({\n title: 'CSV-Spalten zuordnen',\n buttons: csv.length + ' Datensätze importieren',\n message: 'Wähle bitte die CSV-Spalten und das jeweils zugehörige Datenbank-Feld aus.'\n });\n\n selectEditor.on('submitComplete', function (e, json, data, action) {\n // Use the host Editor instance to show a multi-row create form allowing the user to submit the data.\n editor.create(csv.length, {\n title: 'Import bestätigen',\n buttons: 'Bestätigen',\n message: 'Klicke auf <i>Bestätigen</i> um ' + csv.length + ' Zeilen zu importieren. Du kannst den Wert für ein Feld überschreiben indem du hier etwas änderst:'\n });\n\n for (var i = 0; i < fields.length; i++) {\n var field = editor.field(fields[i]);\n var mapped = data[field.name()];\n\n for (var j = 0; j < csv.length; j++) {\n field.multiSet(j, csv[j][mapped]);\n }\n }\n });\n}", "function GenerateSeletedQCEquipmentList() {\n var promiseArray1 = [];\n promiseArray1.push(\n $http.post(config.baseUrlApi + 'HMLVTS/GenerateSeletedQCEquipmentList', {\n \"WOID\": $scope.selectedWOIDData['woid'],\n \"ProcOpSeq\": $scope.ProcOpSeq,\n 'OpSeq': $scope.OpSeq,\n 'RouteID': $scope.RouteID,\n 'WorkCenter':$scope.WorkCenter\n }\n )\n );\n //GenerateSeletedQCEquipmentList\n //\"Select McID \"\n // + \"from TS_QC_Equipment \"\n // + \"where WOID ='\" + selectedWO + \"' \"\n // + \"and WorkCenter ='\" + WorkCenter + \"' \"\n // + \"and RouteID = \" + int.Parse(RouteID)\n // + \"and OpSeq = \" + int.Parse(OpSeq)\n // + \"and ProcOpSeq = \" + int.Parse(ProcOpSeq)\n // + \" Order by McID Asc\"\n\n $q.all(promiseArray1).then(function (response) {\n console.log(\"GenerateSeletedQCEquipmentList\", response);\n\n if (response.length != 0 && response[0].data.success ) {\n //makeequipment table\n $scope.equipmentList = response[0].data.result;\n makeTableEquipment(response[0].data.result);\n }\n\n });\n }", "function exportSelectedMacros() {\r\n\r\n var checkboxes = $('#ID-macroTable .cb_export:checked');\r\n prepareExport('macros', checkboxes.length);\r\n\r\n checkboxes.each(function(index, element) {\r\n $.ajax({\r\n type : 'POST',\r\n async : checkboxes.length < PARALLEL_AJAX_REQUESTS,\r\n url : \"/tagmanager/web/getPage?_.versionId=0&TagManagementPage.mode=EDIT_MACRO&TagManagementPage.macroId=\" + $(element).data('tid') + \"&id=TagManagement&ds=\" + CONTAINER_ID,\r\n dataType : 'json'\r\n })\r\n .done(function(data) {\r\n\r\n var component = data.components[0];\r\n\r\n var new_obj = {\r\n macroType : component.macroData.type,\r\n macroName : component.macroData.name\r\n }\r\n\r\n if (new_obj.macroType == 'CUSTOM_VAR') {\r\n new_obj.customVarName = component.macroData.customVarMacro.name.string;\r\n }\r\n else if (new_obj.macroType == 'COOKIE') {\r\n new_obj.cookieName = component.macroData.cookieMacro.name.string;\r\n }\r\n else if (new_obj.macroType == 'CONSTANT') {\r\n new_obj.macroValue = component.macroData.constantMacro.value.string;\r\n }\r\n else if (new_obj.macroType == 'EVENT') {\r\n //no additional data needed\r\n }\r\n else if (new_obj.macroType == 'REFERRER') {\r\n //no additional data needed\r\n }\r\n else if (new_obj.macroType == 'ARBITRARY_JAVASCRIPT') {\r\n new_obj.javascript = component.macroData.arbitraryJavascriptMacro.javascript.string;\r\n }\r\n else if (new_obj.macroType == 'AUTO_EVENT_VAR') {\r\n new_obj.varType = component.macroData.autoEventVarMacro.varType;\r\n if (typeof component.macroData.autoEventVarMacro.defaultValue != 'undefined') {\r\n new_obj.defaultValue = component.macroData.autoEventVarMacro.defaultValue.string;\r\n }\r\n }\r\n else if (new_obj.macroType == 'DOM_ELEMENT') {\r\n new_obj.elementId = component.macroData.domElementMacro.elementId.string;\r\n if (typeof component.macroData.domElementMacro.attributeName != 'undefined') {\r\n new_obj.attributeName = component.macroData.domElementMacro.attributeName.string;\r\n }\r\n }\r\n else if (new_obj.macroType == 'URL') {\r\n new_obj.urlComponentType = component.macroData.urlMacro.component;\r\n if (typeof component.macroData.urlMacro.queryKey != 'undefined') {\r\n new_obj.queryKey = component.macroData.urlMacro.queryKey.string;\r\n }\r\n if (typeof component.macroData.urlMacro.stripWww != 'undefined') {\r\n new_obj.stripWww = component.macroData.urlMacro.stripWww.boolean;\r\n }\r\n if (typeof component.macroData.urlMacro.defaultPages != 'undefined') {\r\n new_obj.defaultPages = '';\r\n for (var i = 0; i < component.macroData.urlMacro.defaultPages.listItem.length; i++) {\r\n new_obj.defaultPages+= component.macroData.urlMacro.defaultPages.listItem[i].string + \"\\n\";\r\n }\r\n }\r\n\r\n }\r\n else {\r\n logMessage(new_obj.macroName + ': skipping. Unsupported type: ' + new_obj.macroType);\r\n return;\r\n }\r\n\r\n pushToExport(new_obj, 'macroName');\r\n });\r\n });\r\n\r\n\r\n }", "handle_index_table_form(){\n let $form = $(\"#custom-table-parameters\"),\n $form_submit_button = $form.find(\".button-primary\");\n\n $form.on(\"submit\",(e) => {\n e.preventDefault();\n //Disable button\n $form_submit_button.attr(\"disabled\",true);\n //Collect data\n let table_params = {},\n $dataTypes_input = $(\"[data-datatype]\").filter(\":checked\");\n if($dataTypes_input.length > 0){\n $.each($dataTypes_input, function (index,input) {\n let $input = $(input);\n if(typeof table_params[\"\"+$input.data(\"datatype\")+\"\"] === \"undefined\"){\n table_params[\"\"+$input.data(\"datatype\")+\"\"] = [];\n }\n table_params[$input.data(\"datatype\")].push($input.val());\n });\n/* for(let input of $dataTypes_input){\n let $input = $(input);\n if(typeof table_params[\"\"+$input.data(\"datatype\")+\"\"] === \"undefined\"){\n table_params[\"\"+$input.data(\"datatype\")+\"\"] = [];\n }\n table_params[$input.data(\"datatype\")].push($input.val());\n }*/\n }\n //Send ajax requests\n this.handle_index_table_creation(table_params);\n });\n }", "function renderParams() {\n \"use strict\";\n const table = document.getElementById(\"tableParams\");\n\n /* Clear the table */\n while (table.rows.length > 1) {\n table.deleteRow(-1);\n }\n\n params.forEach(function (value, key, map) {\n tableAppendRow(table, [key, value]);\n });\n}", "function process_form_submit_header_edit( event ) {\n\t\tfor ( var i = 0; i <= 1; i++ ) {\n\t\t\tif ( i == 0 ) {\n\t\t\t\tedit_col = 'left';\n\t\t\t} else {\n\t\t\t\tedit_col = 'right';\n\t\t\t}\n\n\t\t\tsaved_values = [];\n\n\t\t\t$processing_fields = $( '#cacap-profile-edit-column-' + edit_col + ' > ul > li' );\n\t\t\tif ( $processing_fields.length ) {\n\t\t\t\t$processing_fields.each( function( k, v ) {\n\t\t\t\t\tsaved_values.push( $( v ).data( 'field-id' ) );\n\t\t\t\t} );\n\t\t\t}\n\n\t\t\t// Convert to json and send along with the payload\n\t\t\t$( event.target ).append( '<input type=\"hidden\" name=\"cacap-saved-values-header-edit-' + edit_col + '\" id=\"cacap-saved-values-' + edit_col + '\" value=\"\" />' );\n\t\t\t$( '#cacap-saved-values-' + edit_col ).val( JSON.stringify( saved_values ) );\n\t\t}\n\t}", "function descargaExcel(e){\n e.preventDefault();\n\n var filtros = \"\";\n \n //Orden de datos\n var Orden = (obtenerOrden() > 0) ? obtenerOrden() : 0;\n\n // Temporada de operacion\n var Temporada = document.getElementById(\"selectTemporada\").value;\n\n // Especie\n var Especie = document.getElementById(\"SelEspecies\").value;\n\n // Pestaña activa\n var active = document.getElementsByClassName(\"nav-link active\")[0].id;\n switch(active){\n case \"resumen-tab\":\n activa = 1;\n filtros = document.getElementsByName(\"FRes\");\n break;\n case \"sowing-tab\":\n activa = 2;\n filtros = document.getElementsByName(\"FLib\");\n break;\n case \"flowering-tab\":\n activa = 3;\n filtros = document.getElementsByName(\"FLib\");\n break;\n case \"harvest-tab\":\n activa = 4;\n filtros = document.getElementsByName(\"FLib\");\n break;\n case \"all-tab\":\n activa = 5;\n filtros = document.getElementsByName(\"FLib\");\n break;\n\n }\n\n var campos = \"?Temporada=\"+Temporada+\"&Orden=\"+Orden+\"&Especie=\"+Especie+\"&Libro=\"+activa;\n\n for(let i = 0; i < filtros.length; i++){\n if(filtros[i].value != \"\" && filtros[i].value != null && filtros[i].value != undefined && filtros[i].value.length > 0){\n console.log(filtros[i]);\n campos += \"&Campo\"+i+\"=\"+filtros[i].value;\n\n }\n\n }\n\n let form = document.getElementById('formExport');\n form.action = \"docs/excel/libro.php\"+campos;\n form.submit();\n\n }", "function exportSelectedRules() {\r\n\r\n var checkboxes = $('#ID-conditionTable .cb_export:checked');\r\n prepareExport('rules', checkboxes.length);\r\n\r\n\r\n checkboxes.each(function(index, element) {\r\n $.ajax({\r\n type : 'POST',\r\n async : checkboxes.length < PARALLEL_AJAX_REQUESTS,\r\n url : \"/tagmanager/web/getPage?TagManagementPage.mode=EDIT_CONDITION&TagManagementPage.conditionId=\" + $(element).data('tid') + \"&id=TagManagement&ds=\" + CONTAINER_ID,\r\n dataType : 'json'\r\n })\r\n .done(function(data) {\r\n var component = data.components[0];\r\n var new_obj = {\r\n conditionName : component.conditionName,\r\n //watch out: import expects predicateS (plural), but export provides predicate (singular)\r\n predicates : JSON.stringify(component.predicate)\r\n };\r\n\r\n pushToExport(new_obj, 'conditionName');\r\n });\r\n });\r\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Initializes a new instance of the ActiveConnectionService class.
function ActiveConnectionService(connectionService, cimService, powerShellService, fileTransferService) { return _super.call(this, connectionService, cimService, powerShellService, fileTransferService) || this; }
[ "constructor() { \n \n VpcPeeringConnection.initialize(this);\n }", "function ContactService(){\r\n\t\tthis.contacts = [];\r\n\t\tthis.contactsIndex = {};\r\n\t\tthis.uuid = 0;\r\n\t}", "constructor() { \n \n ComputeInfoProtocol.initialize(this);\n }", "initConnectionToService(name, port, callback) {\n // Ensure the address is qualified\n const { address } = this.settings;\n const host = getHostByAddress(address);\n const resolvedAddress = host !== null ? `${host}:${port}` : port;\n // Initiate micro service connection\n return this.initiateMicroServerConnection(port, (socket) => {\n // Show status\n if (Object.prototype.hasOwnProperty.call(socket, 'error')) {\n this.log(`Unable to connect to service - ${name}. Retrying...`, 'log');\n // Set status\n this.serviceData[name].status = false;\n // Retry\n return setTimeout(\n () => this.initConnectionToService(name, port, callback),\n this.settings.connectionTimeout\n );\n }\n this.log(\n `Service core has successfully connected to micro service: ${resolvedAddress}`\n );\n // Set status\n this.serviceData[name].status = true;\n // Store Socket Object\n this.serviceData[name].socketList[\n this.getProcessIndex(name, port)\n ] = socket;\n // Callback\n return callback(true, socket);\n });\n }", "function initializeOpcuaClient(){\n client = new OPCUAClient({keepSessionAlive:true});\n client.connect(\"opc.tcp://\" + os.hostname() + \":\" + port, onClientConnected);\n}", "initServices () {\n this.services.db = new DBService({\n app: this,\n db: this.options.dbBackend\n })\n this.services.rpcServer = new RPCServerService({\n app: this,\n port: this.options.rpcPort\n })\n this.services.jsonrpc = new JSONRPCService({\n app: this\n })\n }", "function initializeConnection() {\n //Add my libs\n var handlers = require( './handlers.js' );\n\n //Initialize the ssh connection\n connection = new Connection(),\n handler = domain.create();\n //Handling \"error\" event inside domain handler.\n handler.add(connection);\n //Add global connection handlers\n handlers.setGlobalConnectionHandlers();\n //Start connection\n connection.connect(OptionsForSFTP);\n}", "constructor(hostname, stage, origin, apikey)\n {\n if (!hostname && !(\"INOMIAL_HOSTNAME\" in process.env))\n throw new Error(\"No hostname given (INOMIAL_HOSTNAME is unset)\");\n\n hostname = hostname || process.env.INOMIAL_HOSTNAME;\n stage = stage || process.env.INOMIAL_STAGE || \"live\";\n apikey = apikey || process.env.INOMIAL_APIKEY;\n\n this.clientConfig = websocketClientConfig;\n\n // If the connection is down, queries are added to this queue.\n // When the connection comes back up, the queries are executed.\n this.requestQueue = [];\n\n // Set of outstanding queries, indexed by request ID.\n this.responseQueue = {};\n\n // Request ID generator.\n this.nextRequestId = 1000000;\n\n // URL We'll be connecting to.\n this.url = \"wss://\" + hostname + \"/\" + stage + \"/api/events\";\n\n // WSS Origin header, for non-browser clients.\n this.origin = origin;\n\n // API key, for non-browser clients. Browser clients will inherit the\n // HTTP session credentials.\n this.apikey = apikey;\n\n // The connection will be set once we connect.\n this.connection = null;\n\n // USN caches for accounts and subscriptions\n this.accountUuidCache = {};\n this.subscriptionUuidCache = {};\n\n this.reconnectPolicy = false;\n }", "constructor() { \n \n ScheduledInstanceAvailability.initialize(this);\n }", "constructor() { \n \n Operation.initialize(this);\n }", "constructor(peripheral) {\n this._peripheral = peripheral;\n this._peripheral_handler = new PeripheralHandler(peripheral);\n\n this._chars = null;\n\n this._SERV_UUID_PRIMARY = '6e400001b5a3f393e0a9e50e24dcca9e';\n this._CHAR_UUID_COMMAND = '6e400002b5a3f393e0a9e50e24dcca9e';\n this._CHAR_UUID_NOTIFY = '6e400003b5a3f393e0a9e50e24dcca9e';\n this._CHAR_UUID_DEVICE = '2a00';\n\n\n this._COMMAND_TIMEOUT_MSEC = 3000;\n\n this._CONNECT_TRIAL_NUM_MAX = 3;\n\n // Save the device information\n let ad = bleadBlAdvertising.parse(peripheral);\n this._id = ad.id;\n this._address = ad.address;\n this._battery = ad.battery;\n\n this._was_connected_explicitly = false;\n\n this._onconnect = () => { };\n this._ondisconnect = () => { };\n this._ondisconnect_internal = () => { };\n this._onnotify_internal = () => { };\n }", "constructor() {\n //const LATTICE_NUM = globalThis.latticeNum;\n const LATTICE_PORT = 31415;\n const LATTICE_URL = `https://sustain.cs.colostate.edu:${LATTICE_PORT}`;\n this.service = new SustainClient(LATTICE_URL, \"sustainServer\");\n this.modelService = new JsonProxyClient(LATTICE_URL, \"sustainServer\");\n return this;\n }", "function ControlService() {\n var id = null;\n this.getId = function () {return id;};\n\n if (1 == arguments.length && arguments[0][rhoUtil.rhoIdParam()]) {\n if (moduleNS != arguments[0][rhoUtil.rhoClassParam()]) {\n throw \"Wrong class instantiation!\";\n }\n id = arguments[0][rhoUtil.rhoIdParam()];\n } else {\n id = rhoUtil.nextId();\n // constructor methods are following:\n \n }\n }", "async initialize() {\n const nodes = this._config.get(CONFIG_KEY.ES_NODE);\n const maxRetries = this._config.get(CONFIG_KEY.ES_MAXRETRIES);\n const requestTimeout = this._config.get(CONFIG_KEY.ES_REQUEST_TIMEOUT);\n const sniffOnStart = this._config.get(CONFIG_KEY.ES_SNIFF_ON_START);\n\n Assert.isNonEmptyArray(nodes, 'esHostname');\n\n this.client = new Client({\n nodes,\n maxRetries,\n requestTimeout,\n sniffOnStart\n });\n\n this._logger.info(`Trying to establish connection to Elastic Search with host ${nodes}`);\n // Create an index/mapping if it doesn't exist\n await this.createIndexIfNotExists();\n\n // Test connection\n if (!this.client) {\n this._logger.error('Can not connect to Elastic Search database');\n throw new Error('Could not connect to Elastic Search database');\n }\n }", "function initialize(callback){\n\n\tsoap.createClient(apiInfo.wsdl, { endpoint: apiInfo.endpoint }, function(err,client){ \n\t\tif(err){ console.log(err); callback(err); }\n\t\telse {\n\t\t\tclient.setSecurity(new soap.BasicAuthSecurity(apiInfo.httpUsername, apiInfo.httpPassword));\n\t\t\tsoapClient = client;\n\t\t\tcallback(null);\n\t\t}\n\t});\n\n}", "constructor() { \n \n ComDayCqReplicationImplAgentManagerImplInfo.initialize(this);\n }", "constructor() {\n\n V1DaskReplica.initialize(this);\n }", "_connect () {\n if (this._reconnectionInterval) {\n this._reconnectionInterval = clearInterval(this._reconnectionInterval)\n }\n\n if (this._connection && this.isConnected) {\n return\n }\n\n this._connection = new WebSocket(\n this._host + this._createQueryString()\n )\n\n this._connectionAttemps++\n this._listen()\n }", "function init(input_params) {\n\tvar input_args = input_params.toString().match(/\\S+/g);\n\t//console.log('input_args: ' + input_args);\n\tvar params = ['',''].concat(input_args);\n\t//console.log('client disconnected');\n\tvar d = domain.create();\n\td.on('error', function(err) {\n\t\tconsole.error(\"EXCEPTION IN USER SERVICE APPLICATION:\");\n\t\tconsole.error(\"Error Object:\");\n\t\tutil.inspect(err,{showHidden: true, depth: 1}).split(/\\r?\\n/)\n\t\t .forEach(function(s) {console.error(s)});\n\t\tconsole.error(\"Stack trace:\");\n\t\terr.stack.toString().split(/\\r?\\n/)\n\t\t .forEach(function(s) {console.error(s)});\n\t\t// Unload user service application module if possible.\n\t\tif (err.domain && err.domain.service_dir) {\n\t\t\tvar mainModuleFile = require.resolve(err.domain.service_dir);\n\t\t\tunified_service.unrequire(mainModuleFile);\n\t\t}\n\t});\n\td.run(function() {\n\t\tbootstrap.parse(loadAndStart, params);\n\t});\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get and set de raiz
get raiz() { return this._raiz; }
[ "function saveValues () {\n ff1 = f1; ff2 = f2; ff3 = f3; // Kraftbeträge\n xxL = xL; yyL = yL; xxR = xR; yyR = yR; // Positionen der Rollen\n }", "get nombre(){\n return this._nombreMascota\n }", "setNiveau(niveau) {\n this.niveau = niveau;\n }", "usuarioRecibido() {\n\t\t\tvar usuarioR = this.usuario;\n\t\t\tif (!this.usuario) {\n\t\t\t\t//si el usuario es null o undefined\n\t\t\t\tusuarioR = { nombre: \"Visitante\", rol: \"Estudiante\" };\n\t\t\t}\n\t\t\treturn usuarioR;\n\t\t}", "get z() {return this._z;}", "function muokkaaRastia() {\n let lat = document.getElementById('latMuokkaa');\n let lon = document.getElementById('lonMuokkaa');\n let koodi = document.getElementById('koodiMuokkaa');\n let aika = document.getElementById('aikaMuokkaa');\n\n let paikka = document.getElementById('selectRasti');\n let numero = document.getElementById('selectRasti').selectedIndex;\n let lapset = paikka.children;\n\n // hae täällä id:llä oikea rasti ja muokkaa.\n let muokattava = kaikkiRastit.get(lapset[numero].id.toString());\n muokattava.koodi = koodi.value;\n muokattava.lat = lat.value;\n muokattava.lon = lon.value;\n muokattava.aika = aika.value;\n // etsitään datasta joukkue, ja vaihdetaan muokattava sen tilalle.\n for (let kilpailu of data) {\n for (let sarja of kilpailu.sarjat) {\n if (sarja.nimi === muokattavaJoukkue.sarja) {\n for (let joukkue of sarja.joukkueet) {\n if (joukkue.id === muokattavaJoukkue.id) {\n for (let rasti of joukkue.rastit) {\n if (rasti.rasti.toString() === lapset[numero].id.toString()) {\n rasti.aika = aika.value;\n }\n\n }\n }\n }\n }\n }\n } \n tulostaRastit(data);\n luoTulosTaulukkoTaso3(data);\n luoFormTaso3();\n muokkaaRasti = false;\n muokkaa = false;\n }", "function get_trabajoActual() {\n fct_MyLearn_API_Client.get({ type: 'Proyectos', extension1: 'Curso', extension2: $routeParams.IdTrabajo.trim() }).$promise.then(function (data) {\n $scope.trabajoActual = data;\n });\n }", "getDocumento() {\n\n return this.binario;\n\n }", "function Rectangulo() {\n this.ancho=0;\n this.alto=0;\n \n this.setAncho=function(ancho) {\n this.ancho=ancho;\n }\n \n this.setAlto=function(alto) {\n this.alto=alto;\n } \n \n this.getArea=function() {\n return this.ancho * this.alto;\n }\n}", "set attitude(val){\n this._loyal = val;\n }", "function haeRastiKoodit(joukkue) {\n let rastit = joukkue.rastit.slice();\n for (let i = 0; i < rastit.length; i++) {\n for (let j = 0; j < data.rastit.length; j++) {\n if (rastit[i].rasti == data.rastit[j].id + \"\") {\n rastit[i].koodi = data.rastit[j].koodi;\n }\n }\n if (rastit[i].koodi == undefined) {\n rastit[i].koodi = \"0\";\n }\n }\n joukkue.rastit = rastit;\n return joukkue;\n}", "function obtenerMediana(){\n $.get(\"\"+baseurl+\"/obtenermediana\", \n { semana: $(\"#semana\").find(':selected').val(), marcador: $(\"#marcador\").find(':selected').val(), unidad: $(\"#id_unidad\").find(':selected').val()}, \n function(data){\n var campo = $('#mediana');\n var valor = 0;\n $.each(data, function(index,element) {\n valor = element.mediana_marcador;\n });\n campo.val(valor);\n });\n }", "function set_remix (value)\n {\n remix = value;\n modify();\n }", "get read_item(){\n\t\treturn this.Item.read\n\t}", "set(propObj, value) {\n propObj[this.id] = value;\n return propObj;\n }", "set(id, data) {\n let oldData = this.raw();\n oldData[id] = data;\n this._write(oldData);\n }", "getCapacidad() {\n return this.capacidad;\n }", "function sukeistiMasyvo2Elementus(x, y) {\n var z = prekiautojai[x];\n prekiautojai[x] = prekiautojai[y];\n prekiautojai[y] = z;\n\n}", "function jkn_rdr_read_get() {\n var $option = jkn_rdr_url_param(JKNRendererSwitch.get_key);\n if ($option) {\n $select = $('#' + JKNRendererSwitch.id_select);\n\n // Only change if we have such an option\n if ($select.has('[value=\"' + $option + '\"]').length > 0) {\n $select.val($option);\n $select.change();\n }\n }\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Alias of getQTIAncestor for assessmentItem.
function getQTIAssessmentItem(elem) { return getQTIAncestor(elem, "assessmentItem"); }
[ "getItemAncestors(item) {\n return this.composer.getItemAncestors(item);\n }", "getItemParent(item) {\n return this.composer.getItemParent(item);\n }", "get parentItem()\n\t{\n\t\t//dump(\"get parentItem: title:\"+this.title);\n\t\tif ((!this._parentItem) && (!this._newParentItem)) {\n\t\t\tthis._parenItem = this;\n\t\t\tthis._calEvent.parentItem = this;\n\t\t}\n\t\treturn this._calEvent.parentItem;\n\t}", "function selectAncestor(elem, type) {\n type = type.toLowerCase();\n if (elem.parentNode === null) {\n console.log('No more parents');\n return undefined;\n }\n var tagName = elem.parentNode.tagName;\n\n if (tagName !== undefined && tagName.toLowerCase() === type) {\n return elem.parentNode;\n } else {\n return selectAncestor(elem.parentNode, type);\n }\n }", "get parent() {\n return tag.configure(ContentType(this, \"parent\"), \"ct.parent\");\n }", "isItemParent(item) {\n return this.composer.isItemParent(item);\n }", "get ancestorTitle() {\n if (this.manifest && this.activeItem) {\n let tmpItem = this.manifest.items.find(\n (d) => this.activeItem.parent === d.id\n );\n // walk back up to the root\n while (tmpItem && tmpItem.parent != null) {\n // take the parent object of this current item\n tmpItem = this.manifest.items.find((i) => i.id == tmpItem.parent);\n }\n if (tmpItem) {\n return tmpItem.title;\n }\n }\n return \"\";\n }", "parent() {\n var selection = this.selected.anchorNode;\n // prevent '#text' node as element\n if (selection && selection.nodeType == 3) selection = selection.parentElement;\n\n return selection ? selection : null;\n }", "isAncestor(value) {\n return isPlainObject(value) && Node$1.isNodeList(value.children);\n }", "get parent() {\n return ContentType(this, \"parent\");\n }", "function closest_ancestor_of_class(elt, a_class){\n if (elt == null) { return null }\n else if(elt.classList && elt.classList.contains(a_class)) { return elt }\n else if (elt.parentNode) { return closest_ancestor_of_class(elt.parentNode, a_class) }\n else return null\n}", "getParentProduct() {\n return this.parent;\n }", "async getChildLocationAncestor(ID) {\r\n // Determine the ID if not present\r\n const isNewID = ID != undefined;\r\n if (ID == undefined)\r\n ID = this.getData().ID;\r\n // Obtain this module's path, and child's path\r\n const path = this.getData().path || [];\r\n const childPath = isNewID ? [...path, ID] : path;\r\n // Request the location\r\n const locationAncestor = (await this.request({\r\n type: locationAncestor_type_1.LocationAncestorType,\r\n use: providers => {\r\n // Get the index of this module class\r\n const nextIndex = childPath.length;\r\n // Get the module with the next (lower priority) index\r\n const provider = providers[nextIndex].provider;\r\n return [provider];\r\n },\r\n data: {\r\n ID: ID,\r\n path: childPath,\r\n },\r\n }))[0];\r\n // Make sure to initialise the correct state\r\n if (this.state.inEditMode)\r\n locationAncestor.setEditMode(true);\r\n if (this.state.inDropMode)\r\n locationAncestor.setDropMode(true);\r\n // Return the ancestor\r\n return locationAncestor;\r\n }", "function hasNodeAsAncestor(self, candidate) {\n\t\t\t\twhile ((self.parent != null) && (self.parent != candidate)) {\n\t\t\t\t\tself = self.parent;\n\t\t\t\t}\n\t\t\t\treturn ((self.parent == candidate) && (candidate != null));\n\t\t\t}", "function furthestAncestor(node) {\n var root = node;\n while (root.parentNode != null) {\n root = root.parentNode;\n }\n return root;\n}", "parent() {\n\t const parents = [];\n\t this.each(el => {\n\t if (!parents.includes(el.parentNode)) {\n\t parents.push(el.parentNode);\n\t }\n\t });\n\t return new DOMNodeCollection(parents);\n\t }", "get parentId() {\n return this.getStringAttribute('parent_id');\n }", "function getParentOfRange(editor) {\r\n\tvar r = getRange(editor);\r\n\tif ($.browser.msie) return r.parentElement()\r\n\treturn r.commonAncestorContainer\r\n }", "parentEditable() {\n var parent = this.parent();\n var editable = false;\n\n while (parent) {\n if (parent.getAttribute('contenteditable') == 'true' &&\n parent.getAttribute(this.config.attribute.plugin) == this.config.attribute.plugin) {\n editable = parent;\n break;\n }\n\n parent = parent.parentElement;\n }\n\n return editable;\n }", "function is_ancestor(node, target)\r\n{\r\n while (target.parentNode) {\r\n target = target.parentNode;\r\n if (node == target)\r\n return true;\r\n }\r\n return false;\r\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Renders the AWS CloudFormation properties of an `AWS::AppMesh::Route.HttpPathMatch` resource
function cfnRouteHttpPathMatchPropertyToCloudFormation(properties) { if (!cdk.canInspect(properties)) { return properties; } CfnRoute_HttpPathMatchPropertyValidator(properties).assertSuccess(); return { Exact: cdk.stringToCloudFormation(properties.exact), Regex: cdk.stringToCloudFormation(properties.regex), }; }
[ "function cfnGatewayRouteHttpPathMatchPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnGatewayRoute_HttpPathMatchPropertyValidator(properties).assertSuccess();\n return {\n Exact: cdk.stringToCloudFormation(properties.exact),\n Regex: cdk.stringToCloudFormation(properties.regex),\n };\n}", "function cfnGatewayRouteHttpGatewayRoutePathRewritePropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnGatewayRoute_HttpGatewayRoutePathRewritePropertyValidator(properties).assertSuccess();\n return {\n Exact: cdk.stringToCloudFormation(properties.exact),\n };\n}", "function cfnRouteHttpRoutePropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnRoute_HttpRoutePropertyValidator(properties).assertSuccess();\n return {\n Action: cfnRouteHttpRouteActionPropertyToCloudFormation(properties.action),\n Match: cfnRouteHttpRouteMatchPropertyToCloudFormation(properties.match),\n RetryPolicy: cfnRouteHttpRetryPolicyPropertyToCloudFormation(properties.retryPolicy),\n Timeout: cfnRouteHttpTimeoutPropertyToCloudFormation(properties.timeout),\n };\n}", "function cfnGatewayRouteHttpGatewayRoutePropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnGatewayRoute_HttpGatewayRoutePropertyValidator(properties).assertSuccess();\n return {\n Action: cfnGatewayRouteHttpGatewayRouteActionPropertyToCloudFormation(properties.action),\n Match: cfnGatewayRouteHttpGatewayRouteMatchPropertyToCloudFormation(properties.match),\n };\n}", "function cfnGatewayRouteHttpGatewayRouteMatchPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnGatewayRoute_HttpGatewayRouteMatchPropertyValidator(properties).assertSuccess();\n return {\n Headers: cdk.listMapper(cfnGatewayRouteHttpGatewayRouteHeaderPropertyToCloudFormation)(properties.headers),\n Hostname: cfnGatewayRouteGatewayRouteHostnameMatchPropertyToCloudFormation(properties.hostname),\n Method: cdk.stringToCloudFormation(properties.method),\n Path: cfnGatewayRouteHttpPathMatchPropertyToCloudFormation(properties.path),\n Port: cdk.numberToCloudFormation(properties.port),\n Prefix: cdk.stringToCloudFormation(properties.prefix),\n QueryParameters: cdk.listMapper(cfnGatewayRouteQueryParameterPropertyToCloudFormation)(properties.queryParameters),\n };\n}", "function cfnGatewayRouteHttpGatewayRouteActionPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnGatewayRoute_HttpGatewayRouteActionPropertyValidator(properties).assertSuccess();\n return {\n Rewrite: cfnGatewayRouteHttpGatewayRouteRewritePropertyToCloudFormation(properties.rewrite),\n Target: cfnGatewayRouteGatewayRouteTargetPropertyToCloudFormation(properties.target),\n };\n}", "function cfnRouteHttpRouteActionPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnRoute_HttpRouteActionPropertyValidator(properties).assertSuccess();\n return {\n WeightedTargets: cdk.listMapper(cfnRouteWeightedTargetPropertyToCloudFormation)(properties.weightedTargets),\n };\n}", "function cfnRouteGrpcRouteMatchPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnRoute_GrpcRouteMatchPropertyValidator(properties).assertSuccess();\n return {\n Metadata: cdk.listMapper(cfnRouteGrpcRouteMetadataPropertyToCloudFormation)(properties.metadata),\n MethodName: cdk.stringToCloudFormation(properties.methodName),\n Port: cdk.numberToCloudFormation(properties.port),\n ServiceName: cdk.stringToCloudFormation(properties.serviceName),\n };\n}", "function cfnRouteHttpRouteHeaderPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnRoute_HttpRouteHeaderPropertyValidator(properties).assertSuccess();\n return {\n Invert: cdk.booleanToCloudFormation(properties.invert),\n Match: cfnRouteHeaderMatchMethodPropertyToCloudFormation(properties.match),\n Name: cdk.stringToCloudFormation(properties.name),\n };\n}", "function CfnRoute_HttpPathMatchPropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n if (typeof properties !== 'object') {\n errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.stringify(properties)));\n }\n errors.collect(cdk.propertyValidator('exact', cdk.validateString)(properties.exact));\n errors.collect(cdk.propertyValidator('regex', cdk.validateString)(properties.regex));\n return errors.wrap('supplied properties not correct for \"HttpPathMatchProperty\"');\n}", "function CfnGatewayRoute_HttpPathMatchPropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n if (typeof properties !== 'object') {\n errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.stringify(properties)));\n }\n errors.collect(cdk.propertyValidator('exact', cdk.validateString)(properties.exact));\n errors.collect(cdk.propertyValidator('regex', cdk.validateString)(properties.regex));\n return errors.wrap('supplied properties not correct for \"HttpPathMatchProperty\"');\n}", "function cfnRouteHttpQueryParameterMatchPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnRoute_HttpQueryParameterMatchPropertyValidator(properties).assertSuccess();\n return {\n Exact: cdk.stringToCloudFormation(properties.exact),\n };\n}", "function cfnGatewayRouteGrpcGatewayRouteMatchPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnGatewayRoute_GrpcGatewayRouteMatchPropertyValidator(properties).assertSuccess();\n return {\n Hostname: cfnGatewayRouteGatewayRouteHostnameMatchPropertyToCloudFormation(properties.hostname),\n Metadata: cdk.listMapper(cfnGatewayRouteGrpcGatewayRouteMetadataPropertyToCloudFormation)(properties.metadata),\n Port: cdk.numberToCloudFormation(properties.port),\n ServiceName: cdk.stringToCloudFormation(properties.serviceName),\n };\n}", "function cfnGatewayRouteHttpQueryParameterMatchPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnGatewayRoute_HttpQueryParameterMatchPropertyValidator(properties).assertSuccess();\n return {\n Exact: cdk.stringToCloudFormation(properties.exact),\n };\n}", "function cfnGatewayRouteGrpcGatewayRoutePropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnGatewayRoute_GrpcGatewayRoutePropertyValidator(properties).assertSuccess();\n return {\n Action: cfnGatewayRouteGrpcGatewayRouteActionPropertyToCloudFormation(properties.action),\n Match: cfnGatewayRouteGrpcGatewayRouteMatchPropertyToCloudFormation(properties.match),\n };\n}", "function cfnGatewayRouteHttpGatewayRouteRewritePropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnGatewayRoute_HttpGatewayRouteRewritePropertyValidator(properties).assertSuccess();\n return {\n Hostname: cfnGatewayRouteGatewayRouteHostnameRewritePropertyToCloudFormation(properties.hostname),\n Path: cfnGatewayRouteHttpGatewayRoutePathRewritePropertyToCloudFormation(properties.path),\n Prefix: cfnGatewayRouteHttpGatewayRoutePrefixRewritePropertyToCloudFormation(properties.prefix),\n };\n}", "function cfnRouteRouteSpecPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnRoute_RouteSpecPropertyValidator(properties).assertSuccess();\n return {\n GrpcRoute: cfnRouteGrpcRoutePropertyToCloudFormation(properties.grpcRoute),\n Http2Route: cfnRouteHttpRoutePropertyToCloudFormation(properties.http2Route),\n HttpRoute: cfnRouteHttpRoutePropertyToCloudFormation(properties.httpRoute),\n Priority: cdk.numberToCloudFormation(properties.priority),\n TcpRoute: cfnRouteTcpRoutePropertyToCloudFormation(properties.tcpRoute),\n };\n}", "get routePath() {\n return this._routePath;\n }", "function cfnGatewayRouteHttpGatewayRouteHeaderPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnGatewayRoute_HttpGatewayRouteHeaderPropertyValidator(properties).assertSuccess();\n return {\n Invert: cdk.booleanToCloudFormation(properties.invert),\n Match: cfnGatewayRouteHttpGatewayRouteHeaderMatchPropertyToCloudFormation(properties.match),\n Name: cdk.stringToCloudFormation(properties.name),\n };\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Serializes the body to an encoded string, where keyvalue pairs (separated by `=`) are separated by `&`s.
toString() { this.init(); return this.keys() .map(key => { const eKey = this.encoder.encodeKey(key); // `a: ['1']` produces `'a=1'` // `b: []` produces `''` // `c: ['1', '2']` produces `'c=1&c=2'` return this.map.get(key).map(value => eKey + '=' + this.encoder.encodeValue(value)) .join('&'); }) // filter out empty values because `b: []` produces `''` // which results in `a=1&&c=1&c=2` instead of `a=1&c=1&c=2` if we don't .filter(param => param !== '') .join('&'); }
[ "encodeParams(params) {\n return Object.entries(params).map(([k, v]) => `${k}=${encodeURI(v)}`).join('&')\n }", "function urlEncodePair(key, value, str) {\n if (value instanceof Array) {\n value.forEach(function (item) {\n str.push(encodeURIComponent(key) + '[]=' + encodeURIComponent(item));\n });\n }\n else {\n str.push(encodeURIComponent(key) + '=' + encodeURIComponent(value));\n }\n }", "function queryStringToJsonString(str){\n var pairs = str.split('&');\n var result = {};\n pairs.forEach(function (pair) {\n pair = pair.split('=');\n var name = pair[0]\n var value = pair[1]\n if (name.length)\n if (result[name] !== undefined) {\n if (!result[name].push) {\n result[name] = [result[name]];\n }\n result[name].push(value || '');\n } else {\n result[name] = value || '';\n }\n });\n return (JSON.stringify(result));\n}", "buildQuerry (query){\n var ecodedQuery = encodeURIComponent(query);\n return ecodedQuery;\n }", "function uriSerialize(obj, prefix) {\n\t\tvar str = [];\n\t\tfor(var p in obj) {\n\t\t\tvar k = prefix ? prefix + \"[\" + p + \"]\" : p, v = obj[p];\n\t\t\tstr.push(typeof v == \"object\" ?\n\t\t\t\turiSerialize(v, k) :\n\t \t\tencodeURIComponent(k) + \"=\" + encodeURIComponent(v));\n\t\t}\n\t\treturn str.join(\"&\");\n\t}", "_encodeQuad({\n subject,\n predicate,\n object,\n graph\n }) {\n return `<<${this._encodeSubject(subject)} ${this._encodePredicate(predicate)} ${this._encodeObject(object)}${(0, _N3Util.isDefaultGraph)(graph) ? '' : ` ${this._encodeIriOrBlank(graph)}`}>>`;\n }", "function encode(text)\n{\n return encodeURIComponent(text);\n}", "function createEncodedParam (key,value) {\n return {\n key: percentEncode(key),\n value: percentEncode(value)\n }\n}", "function genQueryString (options) {\n\n if ( !options.queryParams ) {\n return \"\";\n }\n\n log(options.verbose,\"Now generating query string value ...\");\n\n var queryStringParams = [];\n\n Object.keys(options.queryParams).forEach(function (key) {\n queryStringParams.push(createEncodedParam(key,options.queryParams[key]));\n });\n\n var queryString = \"?\";\n\n log(options.verbose,\"Query string key/value pairs are:\");\n\n for ( var i=0; i<queryStringParams.length; i++ ) {\n log(options.verbose,\" \"+queryStringParams[i].key+\"=\"+queryStringParams[i].value);\n queryString += queryStringParams[i].key+\"=\"+queryStringParams[i].value;\n if ( queryStringParams[i+1] ) {\n queryString += \"&\";\n }\n }\n\n log(options.verbose,\"Query string value is: \"+queryString);\n\n return queryString;\n}", "function data_enc( string ) {\n\n //ZIH - works, seems to be the fastest, and doesn't bloat too bad\n return 'utf8,' + string\n .replace( /%/g, '%25' )\n .replace( /&/g, '%26' )\n .replace( /#/g, '%23' )\n //.replace( /\"/g, '%22' )\n .replace( /'/g, '%27' );\n\n //ZIH - works, but it's bloaty\n //return 'utf8,' + encodeURIComponent( string );\n\n //ZIH - works, but it's laggy\n //return 'base64,' + window.btoa( string );\n}", "function bodyToParams(body) {\n var params = {};\n\n body = body.trim();\n body.split('\\n').forEach(function(line) {\n var match = line.trim().match(/^(\\w+)=(.*)$/);\n if (match) {\n params[match[1]] = match[2];\n }\n });\n return params;\n}", "toBase64() {\n return this._byteString.toBase64();\n }", "function encodeUriPath(pathParam) { \n /*if (uriPath.indexOf(\"/\") === -1) {\n return encodeUriPathComponent(uriPath);\n }\n var slashSplitPath = uriPath.split('/');\n for (var pathCptInd in slashSplitPath) {\n slashSplitPath[pathCptInd] = encodeUriPathComponent(slashSplitPath[pathCptInd]); // encoding ! NOT encodeURIComponent\n }\n return slashSplitPath.join('/');\n //return encodeURI(idValue); // encoding !\n // (rather than encodeURIComponent which would not accept unencoded slashes)*/\n var encParts, part, parts, _i, _len;\n if (pathParam.indexOf(\"/\") === -1) {\n return encodeUriPathComponent(pathParam);\n } else if (pathParam.indexOf(\"//\") !== -1) { // else '//' (in path param that is ex. itself an URI)\n // would be equivalent to '/' in URI semantics, so to avoid that encode also '/' instead\n return encodeURIComponent(pathParam);\n } else {\n parts = pathParam.split(\"/\");\n encParts = [];\n for (_i = 0, _len = parts.length; _i < _len; _i++) {\n part = parts[_i];\n ///encParts.push(encodeURIComponent(part));\n encParts.push(encodeUriPathComponent(part));\n }\n return encParts.join(\"/\");\n }\n }", "_getPatchBody(value) {\n let body = {};\n const patch = this.config.patch;\n value = typeof value !== 'undefined' ? value : this.config.control.value;\n if (IsObject(value)) {\n const val = value;\n body = Object.assign(Object.assign({}, body), val);\n }\n else if (IsArray(value)) {\n body[this.config.patch.field] = value;\n }\n else {\n body[this.config.patch.field] = value;\n if (this.config.empty && !body[this.config.patch.field]) {\n body[this.config.patch.field] = PopTransform(String(value), this.config.empty);\n }\n }\n if (this.config.patch.json)\n body[this.config.patch.field] = JSON.stringify(body[this.config.patch.field]);\n if (patch && patch.metadata) {\n for (const i in patch.metadata) {\n if (!patch.metadata.hasOwnProperty(i))\n continue;\n body[i] = patch.metadata[i];\n }\n }\n return body;\n }", "_encodeObject(object) {\n switch (object.termType) {\n case 'Quad':\n return this._encodeQuad(object);\n\n case 'Literal':\n return this._encodeLiteral(object);\n\n default:\n return this._encodeIriOrBlank(object);\n }\n }", "function buildRequestBody (req) {\n if ((~ (req.headers['content-type'] || '').indexOf('x-www-form-urlencoded')) ||\n (~ (req.headers['content-type'] || '').indexOf('form-data'))) {\n return new Buffer(qs.stringify(req.body), 'utf8');\n } else if (req.body instanceof Buffer) {\n return req.body\n } else if (typeof req.body === 'string') {\n return new Buffer(req.body, 'utf8');\n } else {\n return new Buffer(JSON.stringify(req.body, null, 2), 'utf8');\n }\n}", "function formatQueryParamsHiking(params) {\n const queryItems = Object.keys(params)\n .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`)\n return queryItems.join('&');\n}", "encodedFilters() {\n const encoded = pick(\n this.$route.query,\n this.filters.map(f => f.name)\n )\n return Object.keys(encoded).length ? encoded : null\n }", "function encodeFormData (data, boundary) {\n var parts, name, value;\n // **NOTE**:\n // use the decoding of `%0D%0A` to break line in HTTP message body\n var lineBreaker = decodeURIComponent('%0D%0A');\n // ensure `data` contains key/value pairs\n // due to form data is always key/value pairs,\n // but always return a string\n if (Object.prototype.toString.call(data) !== '[object Object]') return '';\n\n parts = [];\n\n // Encode according to http://www.w3.org/TR/html401/interact/forms.html#didx-applicationx-www-form-urlencoded,\n // but space charactor is not replaced by '+'\n if (!boundary) {\n for (name in data) {\n value = data[name];\n if (!data.hasOwnProperty(name) || typeof value === 'functoin') continue;\n name = encodeURIComponent(name);\n // name = encodeURIComponent(name.replace(/\\s{1}/g, '+'));\n value = encodeURIComponent(value.toString());\n // value = encodeURIComponent(value.toString().replace(/\\s{1}/g, '+'));\n parts.push(name + '=' + value);\n }\n return parts.join('&');\n }\n // Encode according to http://www.w3.org/TR/html401/interact/forms.html#didx-applicationx-www-form-urlencoded#didx-multipartform-data,\n // but not support file currently\n else {\n boundary = '--' + boundary + lineBreaker;\n\n for (name in data) {\n value = data[name];\n if (!data.hasOwnProperty(name) || typeof value === 'function') continue;\n value = value.toString();\n parts.push('Content-Disposition: form-data; name=\"' + name + '\"' + lineBreaker + lineBreaker + value + lineBreaker);\n }\n\n if (parts.length === 0) {\n return '';\n }\n else {\n parts = parts.join(boundary);\n parts = boundary + parts;\n parts += boundary.slice(0, lineBreaker.length * -1) + '--';\n return parts;\n }\n }\n}", "function genApplicationJson() {\n return encodeURIComponent(\"application/json\");\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
void round_hill (int cx, int cz, unsigned r, float h, float hmax, char allowcanyons)
function round_hill(cx, cz, r, h, hmax, allowcanyons) { // Una collina rotonda, o una montagna molto erosa (se la si fa grossa). // hmax entra in gioco se il flag "allowcanyons" Š a zero: // quando l'altezza puntuale supera "hmax", per allowcanyons=0 // la funzione costruisce un altopiano sulla sommit… della collina, // mentre allowcanyons=1 fa ignorare il parametro "hmax" e, quando // l'altezza supera il limite massimo globale (127), scava un canyon // al centro della collina. WEIRDDOSHILLS = true; if (WEIRDDOSHILLS) { var x, z; //int var dx, dz, d; //float var y, v = r / M_PI_2; for (x = cx - r; x < cx + r; x++) { for (z = cz - r; z < cz + r; z++) { if (x > -1 && z > -1 && x < 200 && z < 200) { dx = x - cx; dz = z - cz; d = Math.sqrt(dx * dx + dz * dz); y = cos(d / v) * h; if (y >= 0) { y += p_surfacemap[200 * z + x]; if (allowcanyons == 1) { //regular pit in the middle if (y > 127) y = 254 - y; } if (allowcanyons == 2) { //volcano! if (y > 127) { y = 254 - (y - y / 1.3) - 127 / 1.3; if (y < 123) ruinschart[200 * z + x] = AF6; } } if (allowcanyons == 0) { //no pit in middle. normal round hill. if (y > hmax) y = hmax; } p_surfacemap[200 * z + x] = y; } } } } } else { // Dword dr = (Dword)r; // Dword x, z; // float d; // Dword dx, dz; // float y, v = ((float)r) / M_PI_2; // Dword minx = cx - dr; // Dword maxx = cx + dr; // Dword minz = cz - dr; // Dword maxz = cz + dr; // if (minx<0) minx=0; // if (minz<0) minz=0; // if (minx>199) minx=199; // if (minz>199) minz=199; // if (maxx<0) maxx=0; // if (maxz<0) maxz=0; // if (maxx>199) maxx=199; // if (maxz>199) maxz=199; // //DebugPrintf(0, "x range=[%li,%li] z range=[%li,%li]", minx, maxx, minz, maxz); // for (x = minx; x < maxx; x++) { // for (z = minz; z < maxz; z++) { // //if (x>-1&&z>-1&&x<200&&z<200) { // dx = x - cx; // dz = z - cz; // d = SQRT (dx*dx + dz*dz); // y = cos (d / v) * h; // //DebugPrintf(0, "[%li,%li] y=%f", x, z, y); // if (y>=0) { // y += p_surfacemap[200*z+x]; // if (allowcanyons) { // if (y>127) // y = 254 - y; // } // else { // if (y>hmax) // y = hmax; // } // p_surfacemap[200*z+x] = (Uchar) y; // } // //} // } // } } }
[ "function std_crater(map, cx, cz, r, lim_h, h_factor, h_raiser, align) {\n // Un cratere. A crater.\n var x, z; //int\n\n var dx, dz, d, y, h, fr; //float\n\n h = parseFloat(r) * h_factor;\n r = Math.abs(r);\n fr = r;\n\n for (x = cx - r; x < cx + r; x++)\n for (z = cz - r; z < cz + r; z++) {\n if (x > -1 && z > -1 && x < align && z < align) {\n dx = x - cx;\n dz = z - cz;\n d = Math.sqrt(dx * dx + dz * dz);\n if (d <= fr) {\n y = Math.sin(Math.PI * (d / fr)) * h;\n y = Math.pow(y, h_raiser);\n y += map[align * z + x]; //In C: y += map[align*(long)z+x]; // This may cause a bug\n if (y < 0) y = 0;\n if (y > lim_h) y = lim_h;\n map[align * z + x] = y; //In C: map[align*(long)z+x] = (Uchar) y; //This may cause a bug\n }\n }\n }\n}", "function smoothterrain(rounding) {\n // Smussa il profilo del terreno.\n var n;\n while (rounding) {\n for (ptr = 0; ptr < 39798; ptr++) {\n n = p_surfacemap[ptr];\n n += p_surfacemap[ptr + 1];\n n += p_surfacemap[ptr + 200];\n n += p_surfacemap[ptr + 201];\n p_surfacemap[ptr] = n >> 2;\n }\n rounding--;\n }\n}", "function findBestCorner() {\n\t\t\n\t}", "function clipSutherland() { \r\n\r\n clip1x = x1;\r\n clip1y = y1;\r\n clip2x = x2;\r\n clip2y = y2;\r\n\r\n var x = 0;\r\n var y = 0;\r\n var m = (clip2y - clip1y) / (clip2x - clip1x);\r\n\r\n var code1 = getCode(clip1x, clip1y);\r\n var code2 = getCode(clip2x, clip2y);\r\n\r\n while (code1 != INSIDE || code2 != INSIDE) {\r\n\r\n var clipCode;\r\n\r\n if ((code1 & code2) != INSIDE) {\r\n return false;\r\n }\r\n if (code1 == INSIDE) {\r\n clipCode = code2;\r\n }\r\n else { \r\n clipCode = code1\r\n }\r\n if ((clipCode & LEFT) != INSIDE) {\r\n x = xMin;\r\n y = (x - clip1x) * m + clip1y;\r\n }\r\n else if ((clipCode & RIGHT) != INSIDE) {\r\n x = xMax;\r\n y = (x - clip1x) * m + clip1y;\r\n }\r\n else if ((clipCode & BOTTOM) != INSIDE) {\r\n y = yMin;\r\n x = (y - clip1y) / m + clip1x;\r\n }\r\n else if ((clipCode & TOP) != INSIDE) {\r\n y = yMax;\r\n x = (y - clip1y) / m + clip1x;\r\n }\r\n if (clipCode == code1) {\r\n clip1x = x;\r\n clip1y = y;\r\n code1 = getCode(clip1x, clip1y);\r\n }\r\n else {\r\n clip2x = x;\r\n clip2y = y;\r\n code2 = getCode(clip2x, clip2y);\r\n }\r\n }\r\n return true;\r\n}", "function colorHarmonizer(referenceAngle) {\n var result,\n // Analogous: Choose second and third ranges 0.\n // Complementary: Choose rangeAngle2 = 0, offsetAngle1 = 180.\n // Split Complementary: Choose offset angles 180 +/- a small angle. The second and third ranges must be smaller than the difference between the two offset angles.\n // Triad: Choose offset angles 120 and 240.\n offsetAngle1 = 120, \n offsetAngle2 = 240,\n rangeAngle0 = 15, \n rangeAngle1 = 30, \n rangeAngle2 = 60,\n rangeAngleSum = rangeAngle0 + rangeAngle1 + rangeAngle2,\n saturation = p.random(60, 100), \n luminance = p.random(50, 70),\n randomAngle;\n p.colorMode(p.HSL, 360, 100, 100);\n randomAngle = p.random(0, rangeAngleSum);\n if (randomAngle > rangeAngle0) {\n if (randomAngle < rangeAngle0 + rangeAngle1) {\n randomAngle += offsetAngle1;\n } else { randomAngle += offsetAngle2; }\n }\n return p.color( (referenceAngle + randomAngle) % 360, saturation, luminance);\n }", "function makeNoFaceMouth(){\n var halfSmile = makeNoFaceMask(0x000000);\n halfSmile.scale.set(0.2,0.045,0.075);\n return halfSmile;\n}", "function rhomb(gen, bX, bY, tX, tY) {\n // make center and missing corners\n const cX = 0.5 * (bX + tX);\n const cY = 0.5 * (bY + tY);\n // 0.378937382=tan(Math.PI/12)*sqrt(2);\n const upX = 0.378937382 * (cX - bX);\n const upY = 0.378937382 * (cY - bY);\n const rightX = upY;\n const rightY = -upX;\n const rX = cX + 0.7071 * rightX;\n const rY = cY + 0.7071 * rightY;\n const lX = cX - 0.7071 * rightX;\n const lY = cY - 0.7071 * rightY;\n if (output.isInCanvas(bX, bY, rX, rY, tX, tY, lX, lY)) {\n if (gen >= tiling.maxGen) {\n rhombAreas.add(bX, bY, rX, rY, tX, tY, lX, lY);\n tiles.rhomb30(false, tiling.rhombUpperImage, bX, bY, rX, rY, tX, tY, lX, lY);\n } else {\n gen += 1;\n const bcX = cX - 0.7071 * upX;\n const bcY = cY - 0.7071 * upY;\n const tcX = cX + 0.7071 * upX;\n const tcY = cY + 0.7071 * upY;\n rhomb(gen, bX, bY, bcX, bcY);\n rhomb(gen, tX, tY, tcX, tcY);\n square(gen, cX, cY, lX, lY);\n square(gen, cX, cY, rX, rY);\n square(gen, cX, cY, bcX, bcY);\n square(gen, cX, cY, tcX, tcY);\n // sqrt(0.5)-sqrt(3)/2*cos(75)=0.48296\n // sqrt(3)/2*sin(75)=0.83652\n let x = cX + 0.48296 * rightX + 0.83652 * upX;\n let y = cY + 0.48296 * rightY + 0.83652 * upY;\n // sqrt(0.5)-sqrt(3)*cos(75)=0.25881\n // sqrt(3)*sin(75)=1.67303\n triangleA(gen, x, y, tcX, tcY, rX, rY);\n triangleC(gen, x, y, tcX, tcY, cX + 0.25881 * rightX + 1.67303 * upX, cY + 0.25881 * rightY + 1.67303 * upY);\n x = cX - 0.48296 * rightX + 0.83652 * upX;\n y = cY - 0.48296 * rightY + 0.83652 * upY;\n triangleA(gen, x, y, tcX, tcY, lX, lY);\n triangleC(gen, x, y, tcX, tcY, cX - 0.25881 * rightX + 1.67303 * upX, cY - 0.25881 * rightY + 1.67303 * upY);\n x = cX + 0.48296 * rightX - 0.83652 * upX;\n y = cY + 0.48296 * rightY - 0.83652 * upY;\n triangleA(gen, x, y, bcX, bcY, rX, rY);\n triangleC(gen, x, y, bcX, bcY, cX + 0.25881 * rightX - 1.67303 * upX, cY + 0.25881 * rightY - 1.67303 * upY);\n x = cX - 0.48296 * rightX - 0.83652 * upX;\n y = cY - 0.48296 * rightY - 0.83652 * upY;\n triangleA(gen, x, y, bcX, bcY, lX, lY);\n triangleC(gen, x, y, bcX, bcY, cX - 0.25881 * rightX - 1.67303 * upX, cY - 0.25881 * rightY - 1.67303 * upY);\n }\n }\n}", "function rockyground(roughness, rounding, level) {\n // Produce una superficie pi— o meno accidentata.\n for (ptr = 0; ptr < 40000; ptr++) p_surfacemap[ptr] = RANDOM(roughness);\n smoothterrain(rounding);\n for (ptr = 0; ptr < 40000; ptr++) {\n if (p_surfacemap[ptr] >= Math.abs(level)) {\n p_surfacemap[ptr] += level;\n if (p_surfacemap[ptr] > 127) p_surfacemap[ptr] = 127;\n } else p_surfacemap[ptr] = 0;\n }\n}", "function drawSquareSideHouse() {\n moveForward(50);\n turnRight(90);\n}", "function MorceauSnake(x, y, width, height, dx, dy, historique, color) {\n this.x = x;\n this.y = y;\n this.width = width;\n this.height = height;\n this.dx = dx;\n this.dy = dy;\n this.historique = historique;\n this.color = color;\n}", "function interpolate(x, xl, xh, yl, yh) {\n var r = 0;\n if ( x >= xh ) {\n r = yh;\n } else if ( x <= xl ) {\n r = yl;\n } else if ( (xh - xl) < 1.0E-8 ) {\n r = yl+(yh-yl)*((x-xl)/1.0E-8);\n } else {\n r = yl+(yh-yl)*((x-xl)/(xh-xl));\n }\n return r;\n }", "removeSandwich(x,y){\r\n if(this.hasSandwichNorth(x,y)){\r\n this.delete(x,y-1);\r\n this.delete(x,y-2);\r\n if(this.getColor(x,y) === 1){\r\n this.blackCapture += 1;\r\n }\r\n else{\r\n this.whiteCapture += 1;\r\n }\r\n }\r\n if(this.hasSandwichNorthEast(x,y)){\r\n this.delete(x+1,y-1);\r\n this.delete(x+2,y-2);\r\n if(this.getColor(x,y) === 1){\r\n this.blackCapture += 1;\r\n }\r\n else{\r\n this.whiteCapture += 1;\r\n }\r\n }\r\n if(this.hasSandwichEast(x,y)){\r\n this.delete(x+1,y);\r\n this.delete(x+2,y);\r\n if(this.getColor(x,y) === 1){\r\n this.blackCapture += 1;\r\n }\r\n else{\r\n this.whiteCapture += 1;\r\n }\r\n }\r\n if(this.hasSandwichSouthEast(x,y)){\r\n this.delete(x+1,y+1);\r\n this.delete(x+2,y+2);\r\n if(this.getColor(x,y) === 1){\r\n this.blackCapture += 1;\r\n }\r\n else{\r\n this.whiteCapture += 1;\r\n }\r\n }\r\n if(this.hasSandwichSouth(x,y)){\r\n this.delete(x,y+1);\r\n this.delete(x,y+2);\r\n if(this.getColor(x,y) === 1){\r\n this.blackCapture += 1;\r\n }\r\n else{\r\n this.whiteCapture += 1;\r\n }\r\n }\r\n if(this.hasSandwichSouthWest(x,y)){\r\n this.delete(x-1,y+1);\r\n this.delete(x-1,y+2);\r\n if(this.getColor(x,y) === 1){\r\n this.blackCapture += 1;\r\n }\r\n else{\r\n this.whiteCapture += 1;\r\n }\r\n }\r\n if(this.hasSandwichWest(x,y)){\r\n this.delete(x-1,y);\r\n this.delete(x-2,y);\r\n if(this.getColor(x,y) === 1){\r\n this.blackCapture += 1;\r\n }\r\n else{\r\n this.whiteCapture += 1;\r\n }\r\n }\r\n if(this.hasSandwichNorthWest(x,y)){\r\n this.delete(x-1,y-1);\r\n this.delete(x-2,y-2);\r\n if(this.getColor(x,y) === 1){\r\n this.blackCapture += 1;\r\n }\r\n else{\r\n this.whiteCapture += 1;\r\n }\r\n }\r\n }", "function rgbToSix(r) {\n return r / 51;\n}", "function getGearLightShade(x,y,s){\n\tvar result=\"M\"+(x+Math.cos(Math.PI/12)*s/2)+\" \"+(y-Math.sin(Math.PI/12)*s/2)+\",L\"+(x+Math.cos(Math.PI/12)*s/2)+\" \"+(y-Math.sin(Math.PI/12)*s/2+s/12)+\",L\"+(x+Math.cos(Math.PI/12)*s/3)+\" \"+(y-Math.sin(Math.PI/12)*s/3+s/12)+\",L\"+(x+Math.cos(Math.PI/12)*s/3)+\" \"+(y-Math.sin(Math.PI/12)*s/3)+\"Z,\";\n\t\n\tresult=result+\"M\"+(x+Math.cos(-Math.PI/12)*s/2)+\" \"+(y-Math.sin(-Math.PI/12)*s/2)+\",L\"+(x+Math.cos(-Math.PI/12)*s/2)+\" \"+(y-Math.sin(-Math.PI/12)*s/2+s/12)+\",L\"+(x+Math.cos(-Math.PI/4)*s/2)+\" \"+(y-Math.sin(-Math.PI/4)*s/2+s/12)+\",L\"+(x+Math.cos(-Math.PI/4)*s/2)+\" \"+(y-Math.sin(-Math.PI/4)*s/2)+\"Z,\";\n\t\n\tresult=result+\"M\"+(x+Math.cos(-Math.PI*5/12)*s/3)+\" \"+(y-Math.sin(-Math.PI*5/12)*s/3)+\",L\"+(x+Math.cos(-Math.PI*5/12)*s/3)+\" \"+(y-Math.sin(-Math.PI*5/12)*s/3+s/12)+\",S\"+(x+Math.cos(-Math.PI/3)*s/3)+\" \"+(y-Math.sin(-Math.PI/3)*s/3+s/12)+\" \"+(x+Math.cos(-Math.PI/4)*s/3)+\" \"+(y-Math.sin(-Math.PI/4)*s/3+s/12)+\",L\"+(x+Math.cos(-Math.PI/4)*s/3)+\" \"+(y-Math.sin(-Math.PI/4)*s/3)+\"Z,\";\n\t\n\tresult=result+\"M\"+(x+Math.cos(-Math.PI*5/12)*s/2)+\" \"+(y-Math.sin(-Math.PI*5/12)*s/2)+\",L\"+(x+Math.cos(-Math.PI*5/12)*s/2)+\" \"+(y-Math.sin(-Math.PI*5/12)*s/2+s/12)+\",L\"+(x+Math.cos(-Math.PI*7/12)*s/2)+\" \"+(y-Math.sin(-Math.PI*7/12)*s/2+s/12)+\",L\"+(x+Math.cos(-Math.PI*7/12)*s/2)+\" \"+(y-Math.sin(-Math.PI*7/12)*s/2)+\"Z,\";\n\t\n\tresult=result+\"M\"+(x+Math.cos(-Math.PI*3/4)*s/3)+\" \"+(y-Math.sin(-Math.PI*3/4)*s/3)+\",L\"+(x+Math.cos(-Math.PI*3/4)*s/2)+\" \"+(y-Math.sin(-Math.PI*3/4)*s/2)+\",L\"+(x+Math.cos(-Math.PI*3/4)*s/2)+\" \"+(y-Math.sin(-Math.PI*3/4)*s/2+s/12)+\",L\"+(x+Math.cos(-Math.PI*3/4)*s/3)+\" \"+(y-Math.sin(-Math.PI*3/4)*s/3+s/12)+\"Z,\";\n\t\n\tresult=result+\"M\"+(x+s/6)+\" \"+y+\",S\"+x+\" \"+(y-s/6)+\" \"+(x-s/6)+\" \"+y+\",A\"+(s/6)+\" \"+(s/6)+\" 1 1 1 \"+(x+s/6)+\" \"+y;\n\t\n\treturn result;\n}", "function drawHighway(numLanesPerDirection) {\r\n //drawLane(0, 50, 800, 70, \"northBound\",'grey');\r\n var yPosition = 0;\r\n //Drawing 3 lanes going east\r\n for (lanenum = 0; lanenum < numLanesPerDirection; lanenum++) {\r\n drawLane(0, lanenum * 73, 800, 70, \"east\", \"grey\");\r\n }\r\n //Drawing 3 lanes going west\r\n for (lanenum = 0; lanenum < numLanesPerDirection; lanenum++) {\r\n drawLane(0, lanenum * 73 + 230, 800, 70, \"west\", \"grey\");\r\n }\r\n //Draw guard rails\r\n fill(\"black\");\r\n rect(0, 210, 800, 8);\r\n rect(0, 225, 800, 8);\r\n rect(0, 440, 800, 8);\r\n rect(0, 0, 800, 8);\r\n}", "function grow_cylinder(it, params) {\n var p,\n sublevels = [],\n err_r,\n total_err = 0,\n\t\t\tr_close = params.r/12;\n\n // Find the valid sublevels based on how well the radius agrees\n // TODO: Use some probablity thing, maybe\n\n for (var a of it){\n p = a[1];\n err_r = abs(sqrt(pow(p[0] - params.xc, 2) + pow(p[2] - params.zc, 2)) - params.r);\n if (err_r < r_close) {\n sublevels.push(p);\n total_err += err_r;\n }\n }\n\n // Get the connected region that includes the clicked point\n var goodlevels = sublevels.sort(function(first, second){\n if (first[1] === second[1]){return 0;} else if (first[1] < second[1]){return -1;} else{return 1;}\n });\n var y0_is_seen = false,\n i_lower = 0, i_upper = goodlevels.length,\n p_lower = goodlevels[i_lower], p_upper = goodlevels[i_upper - 1],\n p_last;\n // TODO: Get statistics, now, so we know some noise ideas?\n for(var si = 1, sl = goodlevels.length; si < sl; si += 1) {\n p = goodlevels[si];\n p_last = goodlevels[si - 1];\n if (abs(p[1] - params.yc) < 10) { y0_is_seen = true; }\n // 1cm discepancy is a break\n if (p[1] - p_last[1] > 5) {\n if(y0_is_seen){\n i_upper = si;\n p_upper = p_last;\n } else {\n i_lower = si;\n p_lower = p;\n }\n }\n }\n\n // Filter to only the points we want\n var valid_cyl_points = goodlevels.filter(function(value, index){\n return index>=i_lower && index<i_upper;\n });\n\n // Update the parameters from these points\n params = estimate_cylinder(valid_cyl_points.entries(), params.root);\n params.h = p_upper[1] - p_lower[1];\n params.yc = (p_upper[1] + p_lower[1]) / 2;\n\n params.error = total_err;\n params.points = valid_cyl_points;\n\n return params;\n }", "function makeHexagons(){\r\n var hexX = 0;\r\n var hexY = 0;\r\n for(var i = 0; i < 91; i++){\r\n hexagons[i][1][0] = hexX;\r\n hexagons[i][1][1] = hexY;\r\n hexY += 1;\r\n if(hexX == 9 && hexY == 7){\r\n hexX += 1;\r\n hexY = 5;\r\n }\r\n if(hexX == 8 && hexY == 8){\r\n hexX += 1;\r\n hexY = 4;\r\n }\r\n if(hexX == 7 && hexY == 9){\r\n hexX += 1;\r\n hexY = 3;\r\n }\r\n if(hexX == 6 && hexY == 10){\r\n hexX += 1;\r\n hexY = 2;\r\n }\r\n if(hexX == 5 && hexY == 11){\r\n hexX += 1;\r\n hexY = 1;\r\n }\r\n if(hexY == 11){\r\n hexY = 0;\r\n hexX += 1;\r\n }\r\n }\r\n for(var i = 0; i < 91; i++){\r\n hexagons[i][0][1] = hexagons[i][1][1] - 5;\r\n hexagons[i][0][0] = (hexagons[i][0][1]) / importantNumber;\r\n hexagons[i][0][0] = Math.abs(hexagons[i][0][0]);\r\n hexagons[i][0][0] += hexagons[i][1][0];\r\n hexagons[i][0][1] += 5;\r\n hexagons[i][0][0] *= s/13;\r\n hexagons[i][0][1] *= s/14;\r\n hexagons[i][0][0] += s/13 * 1.5;\r\n hexagons[i][0][1] += s/13 * 1.5;\r\n }\r\n for(var i = 0; i < 91; i++){\r\n if(hexagons[i][1][1] == 5) for(var j = 0; j < 91; j++){\r\n if((hexagons[i][1][0] == hexagons[j][1][0] + 1) && (hexagons[i][1][1] == hexagons[j][1][1])){\r\n hexagons[i][3][0] = j;\r\n }\r\n if((hexagons[i][1][0] == hexagons[j][1][0] + 1) && (hexagons[i][1][1] == hexagons[j][1][1] - 1)){\r\n hexagons[i][3][1] = j;\r\n }\r\n if((hexagons[i][1][0] == hexagons[j][1][0]) && (hexagons[i][1][1] == hexagons[j][1][1] - 1)){\r\n hexagons[i][3][2] = j;\r\n }\r\n if((hexagons[i][1][0] == hexagons[j][1][0] - 1) && (hexagons[i][1][1] == hexagons[j][1][1])){\r\n hexagons[i][3][3] = j;\r\n }\r\n if((hexagons[i][1][0] == hexagons[j][1][0] + 1) && (hexagons[i][1][1] == hexagons[j][1][1] + 1)){\r\n hexagons[i][3][4] = j;\r\n }\r\n if((hexagons[i][1][0] == hexagons[j][1][0]) && (hexagons[i][1][1] == hexagons[j][1][1] + 1)){\r\n hexagons[i][3][5] = j;\r\n }\r\n }\r\n if(hexagons[i][1][1] < 5) for(var j = 0; j < 91; j++){\r\n if((hexagons[i][1][0] == hexagons[j][1][0] + 1) && (hexagons[i][1][1] == hexagons[j][1][1])){\r\n hexagons[i][3][0] = j;\r\n }\r\n if((hexagons[i][1][0] == hexagons[j][1][0] - 1) && (hexagons[i][1][1] == hexagons[j][1][1] - 1)){\r\n hexagons[i][3][1] = j;\r\n }\r\n if((hexagons[i][1][0] == hexagons[j][1][0]) && (hexagons[i][1][1] == hexagons[j][1][1] - 1)){\r\n hexagons[i][3][2] = j;\r\n }\r\n if((hexagons[i][1][0] == hexagons[j][1][0] - 1) && (hexagons[i][1][1] == hexagons[j][1][1])){\r\n hexagons[i][3][3] = j;\r\n }\r\n if((hexagons[i][1][0] == hexagons[j][1][0] + 1) && (hexagons[i][1][1] == hexagons[j][1][1] + 1)){\r\n hexagons[i][3][4] = j;\r\n }\r\n if((hexagons[i][1][0] == hexagons[j][1][0]) && (hexagons[i][1][1] == hexagons[j][1][1] + 1)){\r\n hexagons[i][3][5] = j;\r\n }\r\n }\r\n if(hexagons[i][1][1] > 5) for(var j = 0; j < 91; j++){\r\n if((hexagons[i][1][0] == hexagons[j][1][0] + 1) && (hexagons[i][1][1] == hexagons[j][1][1])){\r\n hexagons[i][3][0] = j;\r\n }\r\n if((hexagons[i][1][0] == hexagons[j][1][0] - 1) && (hexagons[i][1][1] == hexagons[j][1][1] + 1)){\r\n hexagons[i][3][1] = j;\r\n }\r\n if((hexagons[i][1][0] == hexagons[j][1][0]) && (hexagons[i][1][1] == hexagons[j][1][1] - 1)){\r\n hexagons[i][3][2] = j;\r\n }\r\n if((hexagons[i][1][0] == hexagons[j][1][0] - 1) && (hexagons[i][1][1] == hexagons[j][1][1])){\r\n hexagons[i][3][3] = j;\r\n }\r\n if((hexagons[i][1][0] == hexagons[j][1][0] + 1) && (hexagons[i][1][1] == hexagons[j][1][1] - 1)){\r\n hexagons[i][3][4] = j;\r\n }\r\n if((hexagons[i][1][0] == hexagons[j][1][0]) && (hexagons[i][1][1] == hexagons[j][1][1] + 1)){\r\n hexagons[i][3][5] = j;\r\n }\r\n }\r\n }\r\n}", "function theta_oh(o,h) {\n console.log((Math.asin(o/h))*180/Math.PI)\n}", "function roundToGrid(numb) {\n\treturn Math.round(numb/10) * 10;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Update the current scale of the viewport
function updateScale(increment) { var ctx = document.getElementById("canvas").getContext("2d"); ctx.clearRect(0, 0, canvas.width, canvas.height); //var viewportScale = document.getElementById("scale").value; axes.scale += increment; draw(); }
[ "function setCurrentScale() {\n\t\tFloorPlanService.currentScale = $(FloorPlanService.panzoomSelector).panzoom(\"getMatrix\")[0];\n\t}", "updateViewport() {\n const { width, height } = this.renderer.getSize();\n const rw = width / this.frameWidth;\n const rh = height / this.frameHeight;\n const ratio = Math.max(rw, rh);\n const rtw = this.frameWidth * ratio;\n const rth = this.frameHeight * ratio;\n\n let x = 0;\n let y = 0;\n\n if (rw < rh) {\n x = -(rtw - width) / 2;\n } else if (rw > rh) {\n y = -(rth - height) / 2;\n }\n\n this.renderer.setViewport(x, y, rtw, rth);\n }", "set scale(newscale)\n\t{\n\t\tthis.myscale.x = newscale;\n\t\tthis.myscale.y = newscale;\n\n\t\tthis.container.style.transform = \"scale(\" + newscale + \",\" + newscale + \")\";\n \n\t\t//get width and height metrics\n\t\tthis.size.x = this.container.getBoundingClientRect().width;\n this.size.y = this.container.getBoundingClientRect().height;\n\n\t\t//adjust z order based on scale\n\t\tthis.container.style.zIndex = (100 * newscale).toString();\n\t}", "function gScale(sx,sy,sz) {\r\n modelViewMatrix = mult(modelViewMatrix,scale(sx,sy,sz)) ;\r\n}", "onTransformScaling() {\n const scale = this.getClosestScaleToFitExtentFeature();\n this.setScale(scale);\n }", "function scale_changed() {\n\n var s = document.getElementById(\"scale_input\");\n //alert(\"slider value \" + s.value);\n\n var range = s.value / 100; // .25 - 2\n\n g_config.scale_factor = range;\n\n if (g_enableInstrumentation) {\n alert(\"scale_factor \" + g_config.scale_factor);\n }\n\n updateScaleCSS(g_config.scale_factor);\n\n refreshMode();\n}", "function updateCanvasScale() {\n cellSize = (window.innerWidth / 100) * gridCellSizePercent;\n cellsPerWidth = parseInt(window.innerWidth / cellSize);\n cellsPerHeight = parseInt((cellsPerWidth * 9) / 21);\n\n canvasWidth = window.innerWidth;\n canvasHeight = cellSize * cellsPerHeight;\n resizeCanvas(canvasWidth, canvasHeight);\n\n if (smallScreen != canvasWidth < minCanvasWidth) {\n smallScreen = canvasWidth < minCanvasWidth;\n if (!smallScreen) {\n ui.showUIByState();\n }\n }\n\n ui.hiscores.resize(false);\n}", "function scaleStage() {\n var win = {\n width : $(window).width()-20,\n height: $(window).height()-20\n },\n stage = {\n width : 323,\n height: 574\n },\n scaling = Math.min(\n win.height/stage.height,\n win.width/stage.width\n );\n\n // Scale and FadeIn entire stage for better UX\n\n new TimelineLite()\n .set('#stage', {scale:scaling, transformOrigin:\"0 0 0\" })\n .to(\"#stage\", 0.5, {opacity:1});\n\n }", "setZoomScale(scale_zoom){\n this.scale_zoom = scale_zoom;\n }", "doResize() {\n console.log('doREsize called');\n var scale;\n\n var wrapperWidth = document.documentElement.clientWidth;\n var wrapperHeight = document.documentElement.clientHeight;\n\n // Use Math.min if you want to scale so that the width fills the screen.\n // Math.max fills the height\n\n scale = wrapperHeight / this.$refs.scalingContainer.clientHeight;\n this.$parent.mobile = false;\n \n // scale = Math.max(\n // wrapperWidth / this.$el.clientWidth,\n // wrapperHeight / this.$el.clientHeight\n // );\n console.log('scale:' + scale, 'elWidth', this.$refs.scalingContainer.clientWidth, '$wrapper.width()' + wrapperWidth);\n this.scalingObject = {\n //Keeps container centered\n transform: 'translateX(' + (-(scale * this.$refs.scalingContainer.clientWidth) / 2 + (wrapperWidth / 2)) + 'px) ' + 'scale(' + scale + ')'\n };\n\n this.scaledViewportWidth = wrapperWidth / scale;\n this.scaledViewportHeight = wrapperHeight / scale;\n\n }", "get scale() { return (this.myscale.x + this.myscale.y)/2;}", "setPanScale(scale_pan){\n this.scale_pan = scale_pan;\n }", "function resetScaleTransform() {\n Data.Edit.Transform.Scale = 1;\n updateTransform();\n}", "function _scaling ( /*[Object] event*/ e ) {\n\t\tvar activeObject = cnv.getActiveObject(),\n\t\tscale = activeObject.get('scaleY') * 100;\n\t\tif ( scale > 500 ) {\n\t\t\tactiveObject.scale(5);\n\t\t\tactiveObject.left = activeObject.lastGoodLeft;\n \tactiveObject.top = activeObject.lastGoodTop;\n\t\t}\n\t\tactiveObject.lastGoodTop = activeObject.top;\n \tactiveObject.lastGoodLeft = activeObject.left;\n\t\tif ( is_text(activeObject) ) {\n\t\t\teditTextScale.set( scale );\n\t\t\twindow.tmpTextProps && window.tmpTextProps.setNEW( 'scale', scale );\n\t\t\twindow.tmpTextProps && window.tmpTextProps.setNEW( 'top', activeObject.top );\n\t\t\twindow.tmpTextProps && window.tmpTextProps.setNEW( 'left', activeObject.left );\n\t\t}\n\t\telse {\n\t\t\teditImageScale.set(scale);\n\t\t}\n\t}", "function UpdateWindowSize()\n{\n var WindowSize = GetWindowSize();\n\n // Only update the sizes if they are larget than zero\n if(WindowSize.X != 0 && WindowSize.Y != 0)\n {\n // Update the canvas size\n Canvas.width = WindowSize.X;\n Canvas.height = WindowSize.Y;\n\n // Update the Vieport to match the size of the canvas\n gl.viewportWidth = Canvas.width;\n gl.viewportHeight = Canvas.height;\n }\n}", "function resize(){\n const width = window.innerWidth - 100;\n const topHeight = d3.select(\".top\").node().clientHeight\n const height = window.innerHeight - topHeight - 50\n console.log(width, height)\n \n self.camera.aspect = width / height;\n self.camera.updateProjectionMatrix();\n self.renderer.setSize(width, height);\n render()\n\n }", "setWheelScale(wheelScale) {\n this.scale_zoomwheel = wheelScale;\n }", "get scale() {\n\t\treturn {\n\t\t\tx: this.dimens.x/this.width,\n\t\t\ty: this.dimens.y/this.height,\n\t\t};\n\t}", "calculatePinchZoom() {\n let distance_1 = Math.sqrt(Math.pow(this.finger_1.start.x - this.finger_2.start.x, 2) + Math.pow(this.finger_1.start.y - this.finger_2.start.y, 2));\n\t\tlet distance_2 = Math.sqrt(Math.pow(this.finger_1.end.x - this.finger_2.end.x, 2) + Math.pow(this.finger_1.end.y - this.finger_2.end.y, 2));\n\t\tif (distance_1 && distance_2) {\n \t\t\tthis.ratio = (distance_2 / distance_1);\n \n \t\t\t\n \t\t\tlet new_scale = this.scale * this.ratio;\n\t\t \n\t\t if ((new_scale > this.scale && new_scale < this.settings.maxZoom) || (new_scale < this.scale && new_scale > this.settings.minZoom)) { \n \t\t\t\n\t \t\t\tlet focal_point = {\n\t \t\t\t\tx: (this.finger_1.start.x + this.finger_2.start.x) / 2, \n\t \t\t\t\ty: (this.finger_1.start.y + this.finger_2.start.y) / 2 \n\t \t\t\t};\n\t \t\t\t\n\t \t\t\tthis.translate(this.originX, this.originY)\n\t \t\t\t\n\t \t\t\tlet originx = focal_point.x/(new_scale) - focal_point.x/this.scale;\n\t \t\t\tlet originy = focal_point.y/(new_scale) - focal_point.y/this.scale;\n\t \t\t\t\n\t \t\t\tthis.originX -= originx;\n\t \t\t \tthis.originY -= originy;\n\t \t\t\tthis.context.scale(this.ratio, this.ratio);\n\t \t\t\t\n\t \t\t\tthis.translate(-this.originX, -this.originY)\n\t \t\t\t\n\t \t\t\tthis.scale = new_scale; // redraw the empty rectangle at proper scaled size to avoid multiple instances of the image on the canvas\n \t\t\t\n\t\t }\n\t\t}\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Performs (if needed) a swap in the shirt numbers on the pitch table
function performPitchTableChangeOnShirtNumbers(textElementIdentifier, draggableAttributeType, draggableAttributeIndex, droppableAttributeType, droppableAttributeIndex) { var droppablePlayerNumber = $('#' + droppableAttributeType + 'number' + droppableAttributeIndex).text(); var draggablePlayerNumber = $('#' + draggableAttributeType + 'number' + draggableAttributeIndex).text(); if (new String(draggableAttributeType).valueOf() == new String("fsqp_").valueOf() && new String(droppableAttributeType).valueOf() == new String("fsqp_").valueOf()) { // Add fade out animation, swap the text and fade in the droppable player number $('#' + textElementIdentifier + $.trim(droppablePlayerNumber)).fadeOut(10); $('#' + textElementIdentifier + $.trim(droppablePlayerNumber)).text($.trim(draggablePlayerNumber)); $('#' + textElementIdentifier + $.trim(droppablePlayerNumber)).fadeIn(700); // Add fade out animation, swap the text and fade in the draggable player number $('#' + textElementIdentifier + $.trim(draggablePlayerNumber)).fadeOut(10); $('#' + textElementIdentifier + $.trim(draggablePlayerNumber)).text($.trim(droppablePlayerNumber)); $('#' + textElementIdentifier + $.trim(draggablePlayerNumber)).fadeIn(700); // Swap the elements' identifiers. To perform a change, set the ids of the elements // to a temporary ids, to address them uniquely and make a successful swap. var id1 = 'changer1'; var id2 = 'changer2'; $('#' + textElementIdentifier + $.trim(droppablePlayerNumber)).attr('id', id1); $('#' + textElementIdentifier + $.trim(draggablePlayerNumber)).attr('id', id2); // swap. $('#' + id1).attr('id', textElementIdentifier + $.trim(draggablePlayerNumber)); $('#' + id2).attr('id', textElementIdentifier + $.trim(droppablePlayerNumber)); } else if (new String(draggableAttributeType).valueOf() == new String("fsqp_").valueOf()) { // Draggable is first squad player, but droppable not. Therefore droppable becomes the fsqp now // Fade out animation $('#' + textElementIdentifier + $.trim(droppablePlayerNumber)).fadeOut(10); // Swap the text $('#' + textElementIdentifier + $.trim(droppablePlayerNumber)).text($.trim(draggablePlayerNumber)); // Fade in animation $('#' + textElementIdentifier + $.trim(droppablePlayerNumber)).fadeIn(700); // Swap the elements' identifiers $('#' + textElementIdentifier + $.trim(droppablePlayerNumber)).attr('id', textElementIdentifier + $.trim(draggablePlayerNumber)); } else if (new String(droppableAttributeType).valueOf() == new String("fsqp_").valueOf()) { // Droppable is first squad player. Therefore draggable becomes the fsqp. // Fade out animation $('#' + textElementIdentifier + $.trim(draggablePlayerNumber)).fadeOut(10); // Swap the text $('#' + textElementIdentifier + $.trim(draggablePlayerNumber)).text($.trim(droppablePlayerNumber)); // Fade in animation $('#' + textElementIdentifier + $.trim(draggablePlayerNumber)).fadeIn(700); // Swap the elements' identifiers $('#' + textElementIdentifier + $.trim(draggablePlayerNumber)).attr('id', textElementIdentifier + $.trim(droppablePlayerNumber)); } // Otherwise no change needed on the pitch table }
[ "function swapPieces(face, times) {\n\tfor (var i = 0; i < 6 * times; i++) {\n\t\tvar piece1 = getPieceBy(face, i / 2, i % 2),\n\t\t\t\tpiece2 = getPieceBy(face, i / 2 + 1, i % 2);\n\t\tfor (var j = 0; j < 5; j++) {\n\t\t\tvar sticker1 = piece1.children[j < 4 ? mx(face, j) : face].firstChild,\n\t\t\t\t\tsticker2 = piece2.children[j < 4 ? mx(face, j + 1) : face].firstChild,\n\t\t\t\t\tclassName = sticker1 ? sticker1.className : '';\n\t\t\tif (className)\n\t\t\t\tsticker1.className = sticker2.className,\n\t\t\t\tsticker2.className = className;\n\t\t}\n\t}\n}", "function swap (a, b) {\n var c = rep_data.data [a];\n rep_data.data [a] = rep_data.data [b];\n rep_data.data [b] = c;\n}", "function swap (mapping, rank1, rank2, qualifier) {\n const temp = {...mapping[rank2], qualifier};\n mapping[rank2] = mapping[rank1];\n mapping[rank1] = temp;\n}", "swap(first, second)\n\t{\n\n\t\tthis.first = first;\n\t\tthis.second = second;\n\n\t\tvar temp = this.bars[first];\n\t\tthis.bars[first] = this.bars[second];\n\t\tthis.bars[second] = temp;\n\n\t\tvar temp2 = this.bars[first].index;\n\t\tthis.bars[first].index = this.bars[second].index;\n\t\tthis.bars[second].index = temp2;\n\n\t\ttemp2 = this.bars[first].compairednumberXPos;\n\t\tthis.bars[first].compairednumberXPos = this.bars[second].compairednumberXPos;\n\t\tthis.bars[second].compairednumberXPos= temp2;\n\n\t\tthis.bars[first].targetX = this.bars[second].xPos;\n\t\tthis.bars[second].targetX = this.bars[first].xPos;\n\n\t\tthis.numOfSwaps++;\n\n\t\t/* Redundant\n\t\tthis.bar1 = this.bars[j];\n\t\tthis.bar2 = this.bars[j + 1];*/\n\t}", "function swap(heights, i, j) {\n let temp = heights[i];\n heights[i] = heights[j];\n heights[j] = temp;\n}", "function swap(event){\n\tvar str = event.target.id;\n\tvar currentCell = parseInt(str.substring(4, str.length)) - 1;\n\tvar temp = shuffledArray[currentCell];\n\t\n\tif(isNeighbour(currentCell)){\t//checking if neighbor\n\t\tshuffledArray[currentCell] = shuffledArray[emptyCell];\n\t\tshuffledArray[emptyCell] = temp;\n\t\temptyCell = currentCell;\n\t\tmovesCounter++; //moves is incremented\n\t\tloadMatrix(shuffledArray); //the array is loaded to the table \n\t\tif(checkMatrix(shuffledArray)){ //checked if puzzle is solved\n\t\t\tif(confirm(\"Congratulations!! You solved the puzzle in \"+movesCounter+\" moves! Do you want to Play Again?\")){\n\t\t\t\tshuffledArray = shuffle(); //new shuffled array for new game\n\t\t\t\tloadMatrix(shuffledArray); //new array loaded to table\n\t\t\t\tmovesCounter = 0; //moves is reset\n\t\t\t}\n\t\t\telse{\n\t\t\t\t$(\"rules\").style.display = 'none';\n\t\t\t\t$(\"game\").style.display = 'none';\n\t\t\t\t$(\"endgame\").style.display = 'block';\n\t\t\t}\n\t\t}\n\t}\n}", "async function swap(arr, a, b){\n await sleep(playbackSpeed)\n\n let temp = arr[a];\n arr[a] = arr[b];\n arr[b] = temp;\n\n swaps++;\n}", "function swap(triangle, i , j) {\n var temp = triangle[i];\n triangle[i] = triangle[j];\n triangle[j] = temp;\n return triangle;\n}", "animatePlayerSwap(p1, p2) {\n var done = false;\n if (p1 != undefined) {\n swapping[0] = p1;\n swapping[1] = p2;\n\n for (var p of swapping) {\n if ((p.pos.x < 400) && (p.pos.y < 200)) {\n for (var yval = 110 ; yval <= 300 ; yval += 10) {\n p.addStep(new Point(75, yval));\n }\n } else if ((p.pos.x < 400) && (200 < p.pos.y)) {\n for (var yval = 290 ; 100 <= yval ; yval -= 10) {\n p.addStep(new Point(75, yval));\n }\n } else if ((400 < p.pos.x) && (p.pos.y < 200)) {\n for (var yval = 110 ; yval <= 300 ; yval += 10) {\n p.addStep(new Point(805, yval));\n }\n } else if ((400 < p.pos.x) && (200 < p.pos.y)) {\n for (var yval = 290 ; 100 <= yval ; yval -= 10) {\n p.addStep(new Point(805, yval));\n }\n }\n }\n\n swapInterval = setInterval( function() {\n court.animatePlayerSwap();\n }, 20 );\n } else {\n this.draw();\n\n var moved = 0;\n for (var p of swapping) {\n moved += p.takeStep();\n }\n\n if (moved <= 0) {\n clearInterval(swapInterval);\n }\n }\n }", "function swapGun()\n{\n let tmp = gun;\n selectGun(prevGun);\n prevGun = tmp;\n}", "swapRows() {\n Performance.start('swapRows');\n if (this.rows.length > 998) {\n let temp = this.rows[1];\n this.rows[1] = this.rows[998];\n this.rows[998] = temp;\n }\n Performance.stop();\n }", "function vectorSwap(){\n\tchanges = 0;\n\tnoiseLevel = 0;\n\tvar eta = 1;\n\t\n\tvar lchanges = changes;\n\tvar a = fixedSpots[0][2];\n\tvar b = fixedSpots[1][2];\n\tvar c = fixedSpots[2][2];\n\tvar d = fixedSpots[3][2];\n\t\n\tfor (var i=0;i<gridSize2;i++){\n\t\tvar i1 = iToY(i,gridSize);\n\t\tvar j1 = iToX(i,gridSize);\n\t\tlchanges = changes;\n\t\t\ttestCellNeighborsOverGrid(i1,j1);\n\t}\n\t// Annealing - random cell swaps....\n\tvar gSM1 = gridSize-1;\n\tfor (var i = 0; i<gridSize; i++){\n\t\tvar i1 = randGS(gridSize); // i,j +/- foreceRange....\n\t\tvar j1 = randGS(gridSize);\n\t\tvar force1At1 = forceAtGridPoint(i1,j1);\n\t\tvar i2 = Math.min(gSM1,Math.max(0,i1 + randPMFr()));\n\t\tvar j2 = Math.min(gSM1,Math.max(0,j1 + randPMFr()));\n\t\tvar force2At2 = forceAtGridPoint(i2,j2);\n\t\ttrade(i1,j1,i2,j2);\n\t\tvar force1At2 = forceAtGridPoint(i2,j2);\n\t\tvar force2At1 = forceAtGridPoint(i1,j1);\n\t\tvar resetTrade = force1At1 + force2At2 + eta - force1At2 - force2At1;\n\t\tif(resetTrade < 0){\n\t\t\ttrade(i1,j1,i2,j2); // reset if no gain in trades...\n\t\t} else {\n\t\t\tlchanges = changes;\n\t\t\tchanges++;\n\t\t\tnoiseLevel += resetTrade;\n\t\t}\n\t}\n\tlchanges = changes;\n\ttotalChanges += changes;\n}", "function pairwiseSwap(num){\n const even = 0xAAAAAAAA;\n const odd = 0x55555555;\n\n return ((num & even) >> 1) | ((num & odd) << 1);\n}", "_cycle(s1, s2, s3, s4) {\n const temp = this.stickers[s1];\n this.stickers[s1] = this.stickers[s4];\n this.stickers[s4] = this.stickers[s3];\n this.stickers[s3] = this.stickers[s2];\n this.stickers[s2] = temp;\n }", "swapPosition(player1, player2, team) {\n this.animatePlayerSwap(player1, player2);\n [player1.pos, player2.pos] = [player2.pos, player1.pos];\n if (team == nameWest) {\n [this.nw, this.sw] = [this.sw, this.nw];\n } else {\n [this.ne, this.se] = [this.se, this.ne];\n }\n }", "swap() {\n const { top, stack } = this;\n const tmp = stack[top - 2];\n\n stack[top] = stack[this.top];\n stack[this.top] = tmp;\n }", "function FlexTable_stacks_in_5677_page22_SetRotHeader() {\n\n\tif (0 != 1) { return; }\n\n\tvar table = document.getElementById('FlexTable_stacks_in_5677_page22');\n\tvar rtable = document.getElementById('FlexTableRot_stacks_in_5677_page22');\n\tif (!table || !rtable) { return; }\n\n\tfor (i=0; i<table.rows[0].cells.length; i++) {\n\t\trtable.rows[i].cells[0].innerHTML = table.rows[0].cells[i].innerHTML;\n\t\t}\n\t}", "function swap(x1, y1, x2, y2, callback) {\n var tmp, swap1, swap2, //modified on p.246\n events = []; //modified on p.246\n\n //p.246\n swap1 = {\n \ttype : \"move\",\n \tdata : [{\n \t\ttype: getJewel(x1, y1),\n \t\tfromX : x1, fromY : y1, toX : x2, toY : y2 \n \t}, {\n \t\ttype: getJewel(x2, y2),\n \t\tfromX: x2, fromY: y2, toX: x1, toY: y1 \n \t}]\n };//end of swap1\n\n swap2 = {\n \ttype: \"move\",\n \tdata: [{\n \t\ttype: getJewel(x2,y2),\n \t\tfromX: x1, fromY:y1, toX: x2, toY: y2\n \t}, {\n \t\ttype: getJewel(x1,y1),\n \t\tfromX: x2, fromY: y2, toX: x1, toY: y1 \n \t}]\n };\n\n if (isAdjacent(x1, y1, x2, y2)) {\n \tevents.push(swap1);\n\n \tif (canSwap(x1, y1, x2, y2)) {\n\n // swap the jewels\n tmp = getJewel(x1, y1);\n jewels[x1][y1] = getJewel(x2, y2);\n jewels[x2][y2] = tmp;\n\n events = events.concat(check());\n } else {\n \tevents.push(swap2, {type: \"badswap\"});\n }\n /*\n // check the board and get list of events\n events = check();\n\t\t*/\n callback(events);\n /*} else {\n callback(false);\n */\n }\n }", "function handleTranspose(mode) {\r\n console.log(\"Transpose: \"+mode)\r\n let modeOption\r\n if (mode=='up') {\r\n modeOption = 1\r\n }\r\n else if(mode=='down'){\r\n modeOption = -1\r\n }\r\n //walk through words and checking type chord\r\n for (let i = 0; i < words.length; i++) {\r\n let sharpFlatNote = 1\r\n \r\n if (words[i].type===\"chord\"){\r\n \r\n //console.log(\"Before: \" + words[i].word)\r\n if(words[i].word.includes(\"#\") || words[i].word.includes(\"b\")){\r\n sharpFlatNote = 2\r\n }\r\n\r\n if(words[i].word.includes(\"/\")){\r\n for(let j =0;j<semitones.length;j++){\r\n\r\n if (words[i].word.substring(words[i].word.indexOf(\"/\")+1,words[i].word.length)==semitones[j].chord) {\r\n words[i].word = words[i].word.replace(semitones[j].chord,semitones[((j+modeOption)+12)%12].chord)\r\n break\r\n }\r\n }\r\n }\r\n\r\n for (let k =0; k<semitones.length;k++) {\r\n //console.log(words[i].word)\r\n if (words[i].word.substring(0,sharpFlatNote)==semitones[k].chord) {\r\n words[i].word = words[i].word.replace(semitones[k].chord, semitones[((k+modeOption)+12)%12].chord)\r\n break\r\n }\r\n else if (words[i].word.substring(0,sharpFlatNote)==semitones[k].flat) {\r\n words[i].word = words[i].word.replace(semitones[k].flat,semitones[((k+modeOption)+12)%12].chord)\r\n break\r\n }\r\n //console.log(\"after replace: \"+words[i].word)\r\n }\r\n } \r\n }\r\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
method to animate said sword slashing
slashSwordAnimation() { // console.log('slashSwordAnimation: ', this.attackAnimationSwitch, this.direction); if (this.attackAnimationSwitch) { this.direction ? this.animations.play('RightAttackHtoL') : this.animations.play('LeftAttackHtoL'); this.attackAnimationSwitch = false; } else { this.direction ? this.animations.play('RightAttackLtoH') : this.animations.play('LeftAttackLtoH'); this.attackAnimationSwitch = true; } }
[ "function moveTurtle() {\n $('.turtle').animate({\n left: \"+=80vw\"\n }, 100);\n }", "function textWiggle() {\n var timelineWiggle = new TimelineMax({repeat:-1, yoyo:true}); \n for(var j=0; j < 10; j++) {\n timelineWiggle.staggerTo(chars, 0.1, {\n cycle: {\n x: function() { return Math.random()*4 - 2; },\n y: function() { return Math.random()*4 - 2; },\n rotation: function() { return Math.random()*10 - 5; }\n },\n ease: Linear.easeNone\n }, 0);\n }\n }", "function knightsRunAway1(skew,callback) {//move left and skew\n $('.arthur').css('transform',skew).animate({\n left: '-=10px'\n },50,'linear',callback);\n}", "haduken() {\n\t\tthis.updateState(KEN_SPRITE_POSITION.haduken, KEN_IDLE_ANIMATION_TIME, false);\n\t}", "function bgSway() {\n var bg = $('#bg');\n TweenMax.to(bg, 12, {x:64, ease:Sine.easeInOut});\n TweenMax.to(bg, 12, {x:-64, ease:Sine.easeInOut, delay: 12, onComplete:bgSway});\n}", "sailAway() {\n // making the boat sail to the right \n this.x ++\n // if the boat sails off the screen\n // bring it back from the left\n if (this.x > 400) {\n this.x = - this.w;\n }\n }", "function showStars() {background(\n\t0, 0, 40, sparkle_trail);\n\n\t////moon///\n\tif (started) {\n\t\tfill(255);\n\t\tellipse(100, 100, 150, 150);\n\t\tfill(0, 0, 40);\n\t\tellipse(130, 90, 130, 130);\n\t}////moon///\n\n\tif (!showingStars) {showingStars = true;\n\t\tfor (let i = 0; i < 300; i++) {stars[i] = new Star;}\n\t}\n\tfor (let i = 0; i < stars.length; i++) {\n\t\tstars[i].show();\n\t}\n}////////MAKE 300 STARS AND SHOW THEM////////", "function create_rainbow() {\r\n player_pos(player_current_pos_x, player_current_pos_y).classList.remove('path')\r\n player_pos(player_current_pos_x, player_current_pos_y).classList.remove('start')\r\n player_pos(player_current_pos_x, player_current_pos_y).classList.add('path_rainbow')\r\n}", "function animate() {\r\n requestAnimationFrame(animate);\r\n spirit_3.rotation -= 20;\r\n spirit_1.rotation += 100;\r\n renderer.render(stage);\r\n}", "function animateGrenade() {\n let l = 'left';\n let r = 'right';\n let i;\n for(i=0;i<4;i++){\n callAnimationGrenade('3%','1%',l);\n }\n for(i=0;i<7;i++){\n callAnimationGrenade('1.875%','1%',l);\n }\n for(i=0;i<10;i++) {\n callAnimationGrenade('1%','1%',l);\n }\n for(i=0;i<10;i++) {\n callAnimationGrenade('.615%','1%',l);\n }\n for(i=0;i<5;i++) {\n callAnimationGrenade('.321%','1%',l);\n }\n for(i=0;i<5;i++) {\n callAnimationGrenade('.321%','1%',r);\n }\n for(i=0;i<10;i++) {\n callAnimationGrenade('.615%','1%',r);\n }\n for(i=0;i<10;i++) {\n callAnimationGrenade('1%','1%',r);\n }\n for(i=0;i<7;i++){\n callAnimationGrenade('1.875%','1%',r);\n }\n for(i=0;i<4;i++){\n callAnimationGrenade('3%','1%',r);\n }\n setTimeout(function(){\n $('#handGrenade').addClass('toggle'); \n },2600);\n setTimeout(explosion, 2600);\n setTimeout(function() {\n audio1.setAttribute('src',staticSoundBits[1]);\n audioPromise();\n },3000);\n}", "animate () {\n if (this.multiStep) this.animateSteps()\n this.animateDraws()\n }", "function rollSmileyOut () {\r\n\tbtn1.style.animationDuration = \"0.4s\";\r\n\tbtn2.style.animationName = \"none\";\r\n\tbtn1.style.animationName = \"rollSmileyOut\";\r\n\tbtn1.style.animationIterationCount = \"1\";\r\n}", "dash(){\n\n this.dashing=true;\n this.lrMaxSpeed=9;\n this.animate(1);\n setTimeout(function(tar){ tar.lrMaxSpeed=4; tar.animate(0); }, 3000, this );\n setTimeout(function(tar){ tar.dashing=false; }, 3500, this );\n }", "function animatePaths(){\n // Creating a shallow copy of the gamePath and move it forward by two.\n const tempPath = gamePath.slice(2);\n ctx.clearRect(0, 0, canvas.width, canvas.height);\n drawBoard();\n decorateBoard();\n\n // Differentiate player and gamePath by using different coloration.\n drawPath(path, \"blue\");\n drawPath(tempPath, \"pink\");\n frameCount++;\n}", "function animateSymbol(s) {\n // create a white outline and explode it\n var c = map.paper.circle().attr(s.path.attrs);\n c.insertBefore(s.path);\n c.attr({ fill: false });\n c.animate({ r: c.attrs.r * 3, 'stroke-width': 7, opacity: 0 }, 2500,\n 'linear', function () { c.remove(); });\n // ..and pop the bubble itself\n var col = s.path.attrs.fill,\n rad = s.path.attrs.r;\n s.path.show();\n s.path.attr({ fill: symbolAnimateFill, r: 0.1, opacity: 1 });\n s.path.animate({ fill: col, r: rad }, 700, 'bounce');\n\n }", "function spawnPainting() {\n if (!animating) {\n scalar = 1;\n\n generateMondrian();\n\n animating = true;\n t = 0;\n // loop();\n }\n }", "function animateGame(){\n var i = 0;\n var intervalId = setInterval(function() {\n if(i >= sequenceArray.length) {\n clearInterval(intervalId);\n }\n animate(i);\n i++;\n }, 800);\n }", "function turbulentAnimate()\n\t{\n\t\t\n\t\tid=requestAnimationFrame(turbulentAnimate);\n\t\tc.clearRect(xLeftWater,yLeftWater,227,2);\n\t\tif(yLeftWater<345)\n\t\t{\n\t\t\tyLeftWater+=0.5;\n\t\t}\n\t\tc.beginPath();\n\t\tc.strokeStyle=\"black\";\n\t\tc.lineWidth=\"1\";\n\t\tc.moveTo(465,240);\n\t\tc.lineTo(465,324);\n\t\tc.lineTo(490,349);\n\t\tc.lineTo(490,394);\n\t\tc.lineTo(580,394);\n\t\tc.lineTo(599,387);\n\t\tc.lineTo(580,380);\n\t\tc.lineTo(510,380);\n\t\tc.lineTo(510,349);\n\t\tc.lineTo(535,324);\n\t\tc.lineTo(535,270);\n\t\tc.lineTo(465,270);\n\t\tc.fillStyle=\"#333333\";\n\t\tc.fill();\n\t\tc.lineTo(535,270);\n\t\tc.lineTo(535,240);\n\t\tc.stroke();\n\t\tc.fillStyle=\"#0099FF\";\n\t\tc.fillRect(x,360,11,44);\n\t\tc.stroke();\n\t\tif(flag===60)\n\t\t{ \n\t\t\t\tc.beginPath();\n\t\t\t\tc.strokeStyle=\"white\";\n\t\t\t\tc.lineWidth=\"2\";\n\t\t\t\tc.moveTo(xCounter,373);\n\t\t\t\tc.lineTo(xCounter+10,373);\n\t\t\t\tc.stroke();\n\t\t\t\tc.beginPath();\n\t\t\t\tc.strokeStyle=\"white\";\n\t\t\t\tc.lineWidth=\"2\";\n\t\t\t\tc.moveTo(xCounter,388);\n\t\t\t\tc.lineTo(xCounter+10,388);\n\t\t\t\tc.stroke();\n\t\t\t\tc.closePath();\n\t\t\t\tc.closePath();\n\t\t\t\txCounter+=20;\n\t\t\t\tflag=10;\n\t\t}\n\t\tif(x<974)\n\t\t{\n\t\t\tx=x+0.5;\n\t\t\tflag++;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tend=1;\n\t\t}\n\t\t\t\tc.beginPath();\n\t\t\t\tc.strokeStyle=\"white\";\n\t\t\t\tc.lineWidth=\"2\";\n\t\t\t\tc.moveTo(xCounter,373);\n\t\t\t\tc.lineTo(xCounter+10,373);\n\t\t\t\tc.stroke();\n\t\t\t\tc.closePath();\n\t\t\t\tc.beginPath();\n\t\t\t\tc.strokeStyle=\"white\";\n\t\t\t\tc.lineWidth=\"2\";\n\t\t\t\tc.moveTo(xCounter,388);\n\t\t\t\tc.lineTo(xCounter+10,388);\n\t\t\t\tc.stroke();\n\t\t\t\tc.closePath();\n\t\t\t\t\n\t\tif(end)\n\t\t{\n\t\t\tcancelAnimationFrame(id);\n\t\t\tx=900;\n\t\t}\n\t\t\n\t}", "animate() {\n\t\t// increase the entropy value by one for use in animations\n\t\t// require more entropy in visual than in audio\n\t\tlet animateEntropy = this.state.entropy + 1;\n\n\t\t// kick off anime targeting unanimated note pieces\n\t\t// use random translate/transform values using entropy value in equation\n\t\tAnime({\n\t\t\ttargets: '[data-note-piece]:not(.animated)',\n\t\t\ttranslateX: () => {\n\t\t\t\tlet num = 3 * animateEntropy;\n\t\t\t\treturn Anime.random(num * -1, num) + 'rem';\n\t\t\t},\n\t\t\ttranslateY: () => {\n\t\t\t\tlet num = 3 * animateEntropy;\n\t\t\t\treturn Anime.random(num * -1, num) * animateEntropy + 'rem';\n\t\t\t},\n\t\t\tscale: () => {\n\t\t\t\treturn Anime.random(5, 30) * animateEntropy / 10;\n\t\t\t},\n\t\t\trotate: () => {\n\t\t\t\treturn Anime.random(-900, 900) * animateEntropy;\n\t\t\t},\n\t\t\tdelay: () => {\n\t\t\t\treturn Anime.random(0, 100);\n\t\t\t},\n\t\t\tduration: () => {\n\t\t\t\treturn Anime.random(500, 750);\n\t\t\t},\n\t\t\topacity: .7,\n\t\t\tdirection: 'alternate',\n\t\t});\n\n\t\t// once animation kicked off set all note pieces as 'animated'\n\t\t[].forEach.call(document.querySelectorAll('[data-note-piece]'), (piece) => {\n\t\t\tpiece.classList.add('animated');\n\t\t});\n\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Validates that radius is a positive number
get radiusIsValid() { return this._isPositiveNumber(this.state.radius); }
[ "function checkSqrtArg(arg) {\n var isValid = true;\n if (arg < 0) {\n isValid = false;\n }\n return isValid;\n}", "validate(value) {\n if (value < 0) throw new Error('Valor negativo para preço');\n }", "isCircleTooClose(x1,y1,x2,y2){\n // if(Math.abs(x1-x2)<50 && Math.abs(y1-y2)<50)\n // return true;\n // return false; \n\n var distance = Math.sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2));\n if(distance<90)\n return true;\n return false;\n \n }", "function isPositive(input) {\n return input > 0;\n}", "function validateInput() {\n\tvar valid = false;\n\tvar maxPins = 0;\n\tif (!((pins==0)||(pins==\"1\")||(pins==2)||(pins==3)||(pins==4)||(pins==5)||(pins==6)||(pins==7)||(pins==8)||(pins==9)||(pins==10))) {\n\t\talert('The number of pins must be between 0 and 10.');\n\t\t$scope.pins = '';\n\t} else if ((ball == 1) && (frame != 9) && (pins > (10 - parseInt(line[frame][0])))) {\n\t\tmaxPins = (10 - parseInt(line[frame][0]));\n\t\talert('Number of pins must be in the range of 0 to ' + maxPins + '.');\n\t\t$scope.pins = '';\n\n\t} else if ((ball == 1) && (frame == 9) && (parseInt(line[frame][0]) != 10) && (pins > (10 - parseInt(line[frame][0])))) {\n\t\tmaxPins = (10 - parseInt(line[frame][0]));\n\t\talert('Number of pins must be in the range of 0 to ' + maxPins + '.');\n\t\t$scope.pins = '';\n\n\n\t} else {\n\t\tvalid = true;\n\t\tconsole.log('valid input');\n\t}\n\treturn valid;\n}", "function lhopitalValida(numerador, denominador){\n return (parseInt(numerador) === 0 && parseInt(denominador) === 0);\n}", "function volumeOfCircle(inputs) {\n const { radius } = inputs;\n if (!isNaN(Number(radius)) && Number(radius) > 0) {\n const volume = (4/3 * Math.PI * Math.pow(radius, 3)).toFixed(8);\n return `\n <p class=\"output\">Input the radius of the circle: ${radius}.</p>\n <p class=\"output\">The volume of the sphere is: ${volume}. </p>\n `;\n }\n throw new Error(\"Please enter a valid number\");\n}", "function isUserNumberValid(v) {\n return v <= 100 && v >= 1 && v != NaN && v % 1 == 0;\n}", "validateInputs() {\n\t\tif(isNaN(this.billAmount) || this.billAmount <= 0 || this.totalPerson == 0) return false;\n\t\treturn true;\n\t}", "function lessThanOrEqualToZero(num) {\r\n if(num <= 0){\r\n return true;\r\n } else{\r\n return false;\r\n }\r\n}", "function validQuantity(input) {\n return parseInt(input) > 0 && input.toString().indexOf(\".\") === -1;\n }", "function validateZoom(e, searchRadius) {\n var bounds = map.getBounds(); \n var sw = bounds.getSouthWest(); \n var ne = bounds.getNorthEast(); \n var swPoint = turf.point([sw.lng, sw.lat]);\n var nePoint = turf.point([ne.lng, ne.lat]);\n var bboxDiagonal = turf.distance(swPoint, nePoint);\n\n // Mapbox's functions are less accurate here, returning a smaller radius \n if (Math.abs(e.lngLat.lat) > 70) {\n showErrorMessage(\"There isn't any data in this section of the map.\");\n return;\n }\n\n if (bboxDiagonal * 2 < searchRadius) {\n showErrorMessage(\"Your search radius is larger than your current view. Try zooming out!\");\n }\n\n const MIN_SAFE_DIAG = 3000;\n if (bboxDiagonal < MIN_SAFE_DIAG) {\n return \n }\n if (searchRadius * 4 < bboxDiagonal) {\n showErrorMessage(\"Your search radius is smaller than your current view. Try zooming in!\");\n }\n}", "function isValidStat(stat) {\n return (stat >= 0 && stat <= 5);\n}", "function isValid(position) {\n\n return !isNaN(position) && parseInt(grid[position]) && (position >= 0 && position <= 8);\n}", "function hasValidPoint(data) {\n return (typeof data.latitude != \"undefined\" && data.longitude != \"undefined\" && data.latitude != null && data.longitude != null && !isNaN(data.latitude) && !isNaN(data.longitude));\n }", "function posNeg(x,y, z) {\n\t(((x < 0)&&(y > 0)) || ((x > 0) && (y < 0)) || ((x < 0)&&(y<0) && (z === true))) ? console.log(\"true\") : console.log(\"false\");\n}", "function validNumber(n) {\n if(topBottom === \"top\") {\n n = (Math.round((n - topStart) / incrementTop) * incrementTop) + topStart;\n if(!isInRange(n, topStart, topEnd)) {\n if(!topInverted) {\n n = n < topStart ? topStart : topEnd;\n } else {\n n = n < topStart ? topEnd : topStart;\n }\n }\n } else {\n n = (Math.round((n - bottomStart) / incrementBottom) * incrementBottom) + bottomStart;\n if(!isInRange(n, bottomStart, bottomEnd)) {\n if(!bottomInverted) {\n n = n < bottomStart ? bottomStart : bottomEnd;\n } else {\n n = n < bottomStart ? bottomEnd : bottomStart;\n }\n }\n }\n return n;\n }", "function isWithinRadius(centerLat, centerLon, radius, lat, lon) {\n\tlet dist = distance(centerLat, centerLon, lat, lon);\n\treturn (dist <= radius);\n}", "function positiveDistance() \n\t{\t\n\t\ttry\n\t\t{\n\t\t\tvar messageText = \"\";\n\t\t\t\n\t\t\tif (milesInput.value < 0)\n\t\t\t{\n\t\t\t\tthrow \"Please enter distance greater than zero.\";\n\t\t\t}\n\t\t}\n\t\t\n\t\n\t\tcatch(mileError)\n\t\t{\n\t\t\tmessageText = mileError;\n\t\t\t\n\t\t}\n\t\n\t\tfinally\n\t\t{\n\t\t\tmessageElement.innerHTML = messageText;\n\t\t}\n\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Some mouse events can be translated directly into Responses.
function handleMouseResponseEvents(modelHelper, sortedInputEvents) { var protoExpectations = []; forEventTypesIn( sortedInputEvents, MOUSE_RESPONSE_TYPE_NAMES, function(event) { var pe = new ProtoExpectation( ProtoExpectation.RESPONSE_TYPE, MOUSE_IR_NAME); pe.pushEvent(event); protoExpectations.push(pe); }); return protoExpectations; }
[ "function sendMouse() {\n document.addEventListener(\"mousemove\", sendSomeData);\n document.addEventListener(\"click\", sendClick);\n document.addEventListener(\"keypress\", sendKey);\n}", "function updateMouse(e) {\n mouseX = e.pageX;\n mouseY = e.pageY;\n}", "function sendEvent(button, pos) {\n var term = ace.session.term;\n // term.emit('mouse', {\n // x: pos.x - 32,\n // y: pos.x - 32,\n // button: button\n // });\n\n if (term.vt300Mouse) {\n // NOTE: Unstable.\n // http://www.vt100.net/docs/vt3xx-gp/chapter15.html\n button &= 3;\n pos.x -= 32;\n pos.y -= 32;\n var data = '\\x1b[24';\n if (button === 0) data += '1';\n else if (button === 1) data += '3';\n else if (button === 2) data += '5';\n else if (button === 3) return;\n else data += '0';\n data += '~[' + pos.x + ',' + pos.y + ']\\r';\n term.send(data);\n return;\n }\n\n if (term.decLocator) {\n // NOTE: Unstable.\n button &= 3;\n pos.x -= 32;\n pos.y -= 32;\n if (button === 0) button = 2;\n else if (button === 1) button = 4;\n else if (button === 2) button = 6;\n else if (button === 3) button = 3;\n term.send('\\x1b[' + button + ';' + (button === 3 ? 4 : 0) + ';' + pos.y + ';' + pos.x + ';' + (pos.page || 0) + '&w');\n return;\n }\n\n if (term.urxvtMouse) {\n pos.x -= 32;\n pos.y -= 32;\n pos.x++;\n pos.y++;\n term.send('\\x1b[' + button + ';' + pos.x + ';' + pos.y + 'M');\n return;\n }\n\n if (term.sgrMouse) {\n pos.x -= 32;\n pos.y -= 32;\n term.send('\\x1b[<' + ((button & 3) === 3 ? button & ~3 : button) + ';' + pos.x + ';' + pos.y + ((button & 3) === 3 ? 'm' : 'M'));\n return;\n }\n\n var data = [];\n\n encode(data, button);\n encode(data, pos.x);\n encode(data, pos.y);\n\n term.send('\\x1b[M' + String.fromCharCode.apply(String, data));\n }", "implementMouseInteractions() {\t\t\n\t\t// mouse click interactions\n\t\tthis.ctx.canvas.addEventListener(\"click\", this.towerStoreClick, false);\n\t\t\n\t\t// mouse move interactions\n\t\tthis.ctx.canvas.addEventListener(\"mousemove\", this.towerStoreMove, false);\t\n\t}", "function addEvents() {\n\t\taddEvent(chart.container, MOUSEDOWN, function(e) {\n\t\t\te = chart.tracker.normalizeMouseEvent(e);\n\t\t\tvar chartX = e.chartX,\n\t\t\t\tchartY = e.chartY,\n\t\t\t\thandleSensitivity = hasTouch ? 10 : 7,\n\t\t\t\tleft,\n\t\t\t\tisOnNavigator;\n\n\t\t\tif (chartY > top && chartY < top + height + scrollbarHeight) { // we're vertically inside the navigator\n\t\t\t\tisOnNavigator = !scrollbarEnabled || chartY < top + height;\n\n\t\t\t\t// grab the left handle\n\t\t\t\tif (isOnNavigator && math.abs(chartX - zoomedMin - navigatorLeft) < handleSensitivity) {\n\t\t\t\t\tgrabbedLeft = true;\n\t\t\t\t\totherHandlePos = zoomedMax;\n\t\t\t\t}\n\n\t\t\t\t// grab the right handle\n\t\t\t\telse if (isOnNavigator && math.abs(chartX - zoomedMax - navigatorLeft) < handleSensitivity) {\n\t\t\t\t\tgrabbedRight = true;\n\t\t\t\t\totherHandlePos = zoomedMin;\n\t\t\t\t}\n\n\t\t\t\t// grab the zoomed range\n\t\t\t\telse if (chartX > navigatorLeft + zoomedMin && chartX < navigatorLeft + zoomedMax) {\n\t\t\t\t\tgrabbedCenter = chartX;\n\t\t\t\t\tdefaultBodyCursor = bodyStyle.cursor;\n\t\t\t\t\tbodyStyle.cursor = 'ew-resize';\n\n\t\t\t\t\tdragOffset = chartX - zoomedMin;\n\t\t\t\t}\n\n\t\t\t\t// click on the shaded areas\n\t\t\t\telse if (chartX > plotLeft && chartX < plotLeft + plotWidth) {\n\n\t\t\t\t\tif (isOnNavigator) { // center around the clicked point\n\t\t\t\t\t\tleft = chartX - navigatorLeft - range / 2;\n\t\t\t\t\t} else { // click on scrollbar\n\t\t\t\t\t\tif (chartX < navigatorLeft) { // click left scrollbar button\n\t\t\t\t\t\t\tleft = zoomedMin - mathMin(10, range);\n\t\t\t\t\t\t} else if (chartX > plotLeft + plotWidth - scrollbarHeight) {\n\t\t\t\t\t\t\tleft = zoomedMin + mathMin(10, range);\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t// shift the scrollbar by one range\n\t\t\t\t\t\t\tleft = chartX < navigatorLeft + zoomedMin ? // on the left\n\t\t\t\t\t\t\t\tzoomedMin - range :\n\t\t\t\t\t\t\t\tzoomedMax;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif (left < 0) {\n\t\t\t\t\t\tleft = 0;\n\t\t\t\t\t} else if (left + range > plotWidth - 2 * scrollbarHeight) {\n\t\t\t\t\t\tleft = plotWidth - range - 2 * scrollbarHeight;\n\t\t\t\t\t}\n\t\t\t\t\tchart.xAxis[0].setExtremes(\n\t\t\t\t\t\txAxis.translate(left, true),\n\t\t\t\t\t\txAxis.translate(left + range, true),\n\t\t\t\t\t\ttrue,\n\t\t\t\t\t\tfalse\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (e.preventDefault) { // tries to drag object when clicking on the shades\n\t\t\t\te.preventDefault();\n\t\t\t}\n\t\t});\n\n\t\taddEvent(chart.container, MOUSEMOVE, function(e) {\n\t\t\te = chart.tracker.normalizeMouseEvent(e);\n\t\t\tvar chartX = e.chartX;\n\n\t\t\t// validation for handle dragging\n\t\t\tif (chartX < navigatorLeft) {\n\t\t\t\tchartX = navigatorLeft;\n\t\t\t} else if (chartX > plotLeft + plotWidth - scrollbarHeight) {\n\t\t\t\tchartX = plotLeft + plotWidth - scrollbarHeight;\n\t\t\t}\n\n\t\t\t// drag left handle\n\t\t\tif (grabbedLeft) {\n\t\t\t\thasDragged = true;\n\t\t\t\trender(0, 0, chartX - navigatorLeft, otherHandlePos);\n\n\t\t\t// drag right handle\n\t\t\t} else if (grabbedRight) {\n\t\t\t\thasDragged = true;\n\t\t\t\trender(0, 0, otherHandlePos, chartX - navigatorLeft);\n\n\t\t\t// drag scrollbar or open area in navigator\n\t\t\t} else if (grabbedCenter) {\n\t\t\t\thasDragged = true;\n\t\t\t\tif (chartX < dragOffset) { // outside left\n\t\t\t\t\tchartX = dragOffset;\n\t\t\t\t} else if (chartX > plotWidth + dragOffset - range - 2 * scrollbarHeight) { // outside right\n\t\t\t\t\tchartX = plotWidth + dragOffset - range - 2 * scrollbarHeight;\n\t\t\t\t}\n\n\t\t\t\trender(0, 0, chartX - dragOffset, chartX - dragOffset + range);\n\t\t\t}\n\t\t});\n\n\t\taddEvent(document, MOUSEUP, function() {\n\t\t\tif (hasDragged) {\n\t\t\t\tchart.xAxis[0].setExtremes(\n\t\t\t\t\txAxis.translate(zoomedMin, true),\n\t\t\t\t\txAxis.translate(zoomedMax, true),\n\t\t\t\t\ttrue,\n\t\t\t\t\tfalse\n\t\t\t\t);\n\t\t\t}\n\t\t\tgrabbedLeft = grabbedRight = grabbedCenter = hasDragged = dragOffset = null;\n\t\t\tbodyStyle.cursor = defaultBodyCursor;\n\t\t});\n\t}", "function __Mouse() {\r\n\tthis.x = 0;\r\n\tthis.y = 0;\r\n\tthis.xWin\t = 0;\r\n\tthis.yWin\t = 0;\r\n\tthis.button = __config.nullString;\r\n\tthis.target = __config.nullString;\r\n\tthis.evnt = __config.nullString; \r\n\r\n\t// this function set the status of the mouse on each event\r\n\tthis.fire = function(e) {\r\n\t// e -> event\r\n\t\t__printDebug(e);\r\n\t\tif (e.type = \"mousemove\") {\r\n\t\t\tthis.x = e.screenX;\r\n\t\t\tthis.y = e.screenY;\r\n\t\t\tthis.xWin = e.clientX + window.pageXOffset;\r\n\t\t\tthis.yWin = e.clientY + window.pageYOffset;\r\n\t\t}\r\n\r\n\t\tif (e.type === \"click\" || e.type === \"dblclick\") {\r\n\t\t\tthis.target = \"[nodeName] = \" + e.target.nodeName + \r\n\t\t\t \" :: [Value] = \" + e.target.value + \r\n\t\t\t \" :: [HREF] = \" + (e.target.href ? \"NO\" : e.target.href) + \r\n\t\t\t\t\t \" :: [TEXTCONTENT] = \" + e.target.textContent.htmlEncode().substring(0,1024);\r\n\t\t\tswitch(e.button) {\r\n\t\t\tcase 0: \r\n\t\t\t\tthis.button = __config.LeftMouseDef;\r\n\t\t\t\tbreak;\r\n\t\t\tcase 1:\r\n\t\t\t\tthis.button = __config.CenterMouseDef;\r\n\t\t\t\tbreak;\r\n\t\t\tcase 2:\r\n\t\t\t\tthis.button = __config.RightMouseDef;\r\n\t\t\t\tbreak;\r\n\t\t\tdefault:\r\n\t\t\t\tthis.button = __config.OtherMouseDef;\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t} else {\r\n\t\t\tthis.button = __config.nullString;\r\n\t\t\tthis.target = __config.nullString;\r\n\t\t}\r\n\r\n\t\tswitch(e.type) {\r\n\t\t\tcase \"click\": \r\n\t\t\t\tthis.evnt = __config.clickDef;\r\n\t\t\t\tbreak;\r\n\t\t\tcase \"dblclick\":\r\n\t\t\t\tthis.evnt = __config.dblclickDef;\r\n\t\t\t\tbreak;\r\n\t\t\tcase \"mousemove\":\r\n\t\t\t\tthis.evnt = __config.mousemoveDef;\r\n\t\t\t\tbreak;\r\n\t\t\tcase \"onmousedown\":\r\n\t\t\t\tthis.evnt = __config.clickDef;\r\n\t\t\t\tbreak;\r\n\t\t\tdefault:\r\n\t\t\t\tthis.evnt = __config.nullString;\r\n\t\t}\r\n\t}\r\n\r\n\t// This functions returns the mouse object actual status\r\n\t/*\r\n\t{\r\n\t\tx: x position of the mouse with respect to screen \r\n\t\ty: y position of the mouse with respect to screen \r\n\t\tevnt: event that was triggered\r\n\t\tbutton: eventually clicked button\r\n\t}\r\n\t*/\r\n\tthis.get = function() {\r\n\t\treturn {\r\n\t\t\tx: this.x,\r\n\t\t\ty: this.y,\r\n\t\t\txWin: this.xWin,\r\n\t\t\tyWin: this.yWin,\r\n\t\t\tevnt: this.evnt,\r\n\t\t\tbutton: this.button,\r\n\t\t\ttarget: this.target\r\n\t\t}\r\n\t}\r\n}", "function saveMouse(e) {\n var mouseData = [];\n var pos = getMousePos(e);\n mouseData[0] = pos.x;\n mouseData[1] = pos.y;\n registerClick(mouseData[0], mouseData[1]);\n}", "function get_relative_mouse_coordinates(event)\n{\n\tvar mouse_x, mouse_y;\n\n\tif(event.offsetX)\n\t{\n\t\tmouse_x = event.offsetX;\n\t\tmouse_y = event.offsetY;\n\t}\n\telse if(event.layerX)\n\t{\n\t\tmouse_x = event.layerX;\n\t\tmouse_y = event.layerY;\n\t}\n\n\treturn { x: mouse_x, y: mouse_y };\n}", "function getEvents(){\nreturn events;\n}", "function handleResponse(event) {\n let elementClicked = event.target; // returns the list element \"<li>3</li>\" that was clicked on\n \n // Record user selection.\n let questionObject;\n\n // Find the questionObject that corresponds to the question the user responded to.\n for (i = 0; i < questionObjects.length; i++) {\n if (document.getElementsByTagName(\"p\")[0].innerText == questionObjects[i].question) {\n questionObjects[i].userResponse = Array.from(elementClicked.parentNode.children).indexOf(elementClicked);\n break;\n }\n }\n // Ask next question if questions are left to be asked. Otherwise, get results.\n if (questionsAlreadyAsked.length == questionObjects.length) {\n document.getElementsByTagName(\"ul\")[0].removeEventListener(\"click\", handleResponse);\n getResults();\n } else {\n askNextQuestion();\n }\n}", "function getRawCoords(e){\n \tvar mousePos = canvas.getBoundingClientRect();\n \tvar coords = {\n \t\tx : e.clientX - mousePos.left,\n \t\ty : e.clientY - mousePos.top\n \t}\n\n \treturn coords;\n }", "function convertResponse(events) {\n const items = [];\n\n // iterate through each issue and extract id, title, etc. into a new array\n for (let i = 0; i < events.length; i++) {\n const raw = events[i];\n const item = {\n id: raw.id,\n title: raw.summary,\n description: raw.description,\n date: raw.start.dateTime,\n link: raw.htmlLink,\n raw: raw\n };\n\n items.push(item);\n }\n\n return { items };\n}", "function mousemove(e) {\n var ifrPos = eventXY(e) // mouse from iframe origin\n var xyOI = iframeXY(iframe) // iframe from window origin\n var xySW = scrollXY(window) // window scroll\n var xySI = scrollXY(iwin) // iframe scroll\n // mouse in iframe viewport\n var xyMouse = xy.subtract(ifrPos, xySI)\n // mouse in window viewport\n var winPos = xy.subtract(xy.add(xyMouse, xyOI), xySW)\n lastMousePos = xyMouse\n coords.show(xy.str(ifrPos), xy.add(winPos, deltaXY))\n }", "$registerRequestResponse() {\n this.$container.bind('Adonis/Core/Request', () => Request_1.Request);\n this.$container.bind('Adonis/Core/Response', () => Response_1.Response);\n }", "function mousePos(p_e)\n{\n\tposx = 0;\n\tposy = 0;\n\n\tif (!p_e)\n\t\tvar e = window.event;\n\telse\n\t\tvar e = p_e;\n\n\tif (e.pageX || e.pageY)\n\t{\n\t\tposx = e.pageX;\n\t\tposy = e.pageY;\n\t}\n\telse if (e.clientX || e.clientY)\n\t{\n\t\tposx = e.clientX + document.body.scrollLeft;\n\t\tposy = e.clientY + document.body.scrollTop;\n\t}\n\n\treturnObj = new Object();\n\treturnObj.x = posx;\n\treturnObj.y = posy;\n\treturn returnObj;\n}", "function catchMouse() {\n $remoteDesktopView = $('#view-port');\n\n $remoteDesktopView.mousedown(function (e) {\n handleEvent(e);\n });\n \n\n $remoteDesktopView.mouseup(function (e) {\n handleEvent(e);\n });\n\n $remoteDesktopView.mousemove(function (e) {\n if (($mouseX != e.pageX) || ($mouseY != e.pageY)) {\n $mouseX = e.pageX;\n $mouseY = e.pageY;\n $mouseMoved = true\n }\n });\n\n $remoteDesktopView.click(function (e) {\n handleEvent(e);\n });\n}", "function responseReceived(e){\n document.getElementById('response').innerHTML = e.target.responseText;\n}", "function onMouseDownEventHandler(e) {\r\n\thandleGraphicsObjAndEventObj(g, e);\r\n\tswitch (drawMode) {\r\n\tcase \"FreeStyle\":\r\n\t\toldX = e.offsetX;\r\n\t\toldY = e.offsetY;\r\n\t\tbreak;\r\n\tcase \"LineStyle\":\r\n\t\tswitch (lineMode.getClickCount()){\r\n\t\tcase lineMode.ZERO_CLICK():\r\n\t\t\tlineMode.setLineModeStartX(e.offsetX);\r\n\t\t\tlineMode.setLineModeStartY(e.offsetY);\r\n\t\t\tlineMode.setClickCount(lineMode.FIRST_CLICK());\r\n\t\t\tbreak;\r\n\t\tcase lineMode.FIRST_CLICK():\r\n\t\t\tlineMode.setClickCount(lineMode.SECOND_CLICK());\r\n\t\t\tbreak;\r\n\t\tcase lineMode.SECOND_CLICK():\r\n\t\t\tbreak;\r\n\t\t}\r\n\t\tbreak;\r\n\tcase \"SprayStyle\":\r\n\t\tdrawingOn = true;\r\n\t\tbreak;\r\n\t}\r\n\r\n}", "function normalizeOnEventArgs(args) {\n if (typeof args[0] === 'object') {\n return args;\n }\n \n var selector = null;\n var eventMap = {};\n var callback = args[args.length - 1];\n var events = args[0].split(\" \");\n \n for (var i = 0; i < events.length; i++) {\n eventMap[events[i]] = callback;\n }\n \n // Selector is the optional second argument, callback is always last.\n if (args.length === 3) {\n selector = args[1];\n }\n \n return [ eventMap, selector ];\n }", "function playbackEvents () {\n\n\t\tvar play = document.getElementById('play');\n\t\tvar overlayPlay = document.getElementById('overlay-play');\n\t\tvar pause = document.getElementById('pause');\n\t\tvar overlayPause = document.getElementById('overlay-pause');\n\t\tvar previous = document.getElementById('previous');\n\t\tvar next = document.getElementById('next');\n\n\t\tplay.addEventListener('click', emitEvent('play'));\n\t\toverlayPlay.addEventListener('click', emitEvent('play'));\n\t\tpause.addEventListener('click', emitEvent('pause'));\n\t\toverlayPause.addEventListener('click', emitEvent('pause'));\n\t\tprevious.addEventListener('click', emitEvent('previous'));\n\t\tnext.addEventListener('click', emitEvent('next'));\n\n\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
checkLegal Tests whether the move is legal Params: player the player placing a token x the xcoordinate where the player is trying to place a token y the ycoordinate Returns: True if the move is legal False otherwise
checkLegal (player, x, y) { //Is the space occupied? if (this.board.get(x, y) !== 0) { return false; } return this.__evaluationTest(player, x, y); }
[ "placeToken (player, x, y) {\n if(!this.__gameOver){\n var captured;\n\n if (this.checkLegal(player, x, y)) {\n \t\tthis.__lastMove = {\"x\":x, \"y\":y, \"c\":player, \"pass\":false};\n this.board = this.board.clone();\n this.board.evaluateMove(player, x, y);\n this.__addCapturedArmies(player);\n \t\t\tthis.history.push(this.board);\n\n // this.board.print();\n return true;\n }\n return false;\n }else{\n return true;\n }\n }", "function isValidPlayerMove(data)\n\t{\n\t\treturn ((data.unit != null) && ((data.type == 'move') || (data.type == 'skill')));\n\t}", "function checkMoveValid()\n\t{\n\t\t// Converted the position of the empty space variables\n\t\t// to integers to be able to easily manipulate them later\n\t\tvar tempX = parseInt(blankX);\n\t\tvar tempY = parseInt(blankY);\n\n\t\t// Resets the array and clears the previous valid moves\n\t\tvalidMoves = new Array();\n\n\t\t// Check Up\n\t\t// Check if there's a piece above the empty space\n\t\tif (tempY != 0)\n\t\t{\n\t\t\tvalidMoves.push([tempX, tempY - 100]);\n\t\t}\n\n\t\t// Check Right\n\t\t// Check if there's a piece to the right of the empty space\n\t\tif (tempX != 300)\n\t\t{\n\t\t\tvalidMoves.push([tempX + 100, tempY]);\n\t\t}\n\n\t\t// Check Down \n\t\t// Checks if there's a piece below the empty space\n\t\tif (tempY != 300)\n\t\t{\n\t\t\tvalidMoves.push([tempX, tempY + 100]);\n\t\t}\n\n\t\t// Check Left\n\t\t// Checks if there's a piece to the left of the empty space\n\t\tif (tempX != 0)\n\t\t{\n\t\t\tvalidMoves.push([tempX - 100, tempY]);\n\t\t}\n\t}", "function checkPos(roverNum, d) {\n const rover = roversArray[roverNum];\n futurePosX = rover.x;\n futurePosY = rover.y;\n\n if (d === 'f') {\n switch (rover.direction) {\n case 'N':\n futurePosY = rover.y - 1;\n break;\n case 'S':\n futurePosY = rover.y + 1;\n break;\n case 'E':\n futurePosX = rover.x + 1;\n break;\n case 'W':\n futurePosX = rover.x - 1;\n break;\n default:\n break;\n }\n }\n if (d === 'b') {\n switch (rover.direction) {\n case 'N':\n futurePosY = rover.y + 1;\n break;\n case 'S':\n futurePosY = rover.y - 1;\n break;\n case 'E':\n futurePosX = rover.x - 1;\n break;\n case 'W':\n futurePosX = rover.x + 1;\n break;\n default:\n break;\n }\n }\n futurePos = `${futurePosY},${futurePosX}`;\n // checks if future position will be out of the board\n if (futurePosY >= 0 && futurePosY < 10 && futurePosX >= 0 && futurePosX < 10) {\n message = '';\n } else {\n message = `Rover ${roverNum} says: Ouch! There's a wall!`;\n }\n // checks if there's an obstacle in future position\n if (obstaclesArray.includes(futurePos)) {\n message = `Rover ${roverNum} says: Hey! There's an obstacle here!`;\n }\n // checks if there's another rover in future position\n addCurrentRoversPos();\n if (allCurrentRoversPos.includes(futurePos)) {\n message = `Rover ${roverNum} says: Hey! There's another rover here!`;\n }\n // resets allCurrentRoversPos for next iteration\n allCurrentRoversPos = [];\n}", "function isValidMovePawn(fromRow, fromCol, toRow, toCol, tmpDir)\r\n\t{\r\n\t\tif (((toRow - fromRow)/Math.abs(toRow - fromRow)) != tmpDir)\r\n\t\t{\r\n\t\t\t//errMsg = \"Pawns cannot move backwards, only forward.\";\r\n\t\t\terrMsg = document.getElementById('#alert_err_move_pawn_id').innerHTML;\r\n\t\t\t\r\n\t\t\treturn false;\r\n\t\t}\r\n\r\n\t\t/* standard move */\r\n\t\tif ((tmpDir * (toRow - fromRow) == 1) && (toCol == fromCol) && (board[toRow][toCol] == 0))\r\n\t\t\treturn true;\r\n\t\t/* first move double jump - white */\r\n\t\tif ((tmpDir == 1) && (fromRow == 1) && (toRow == 3) && (toCol == fromCol) && (board[2][toCol] == 0) && (board[3][toCol] == 0))\r\n\t\t\treturn true;\r\n\t\t/* first move double jump - black */\r\n\t\tif ((tmpDir == -1) && (fromRow == 6) && (toRow == 4) && (toCol == fromCol) && (board[5][toCol] == 0) && (board[4][toCol] == 0))\r\n\t\t\treturn true;\r\n\t\t/* standard eating */\r\n\t\telse if ((tmpDir * (toRow - fromRow) == 1) && (Math.abs(toCol - fromCol) == 1) && (board[toRow][toCol] != 0))\r\n\t\t\treturn true;\r\n\t\t/* en passant - white */\r\n\t\telse if ((tmpDir == 1) && (fromRow == 4) && (toRow == 5) && (board[4][toCol] == (PAWN | BLACK)))\r\n\t\t{\r\n\t\t\t/* can only move en passant if last move is the one where the white pawn moved up two */\r\n\t\t\tif ((chessHistory[numMoves][TOROW] == 4) && (chessHistory[numMoves][FROMROW] == 6) && (chessHistory[numMoves][TOCOL] == toCol))\r\n\t\t\t\treturn true;\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\t//errMsg = \"Pawns can only move en passant immediately after an opponent played his pawn.\";\r\n\t\t\t\terrMsg = document.getElementById('#alert_err_move_passant_id').innerHTML;\r\n\t\t\t\t\r\n\t\t\t\treturn false;\r\n\t\t\t}\r\n\t\t}\r\n\t\t/* en passant - black */\r\n\t\telse if ((tmpDir == -1) && (fromRow == 3) && (toRow == 2) && (board[3][toCol] == PAWN))\r\n\t\t{\r\n\t\t\t/* can only move en passant if last move is the one where the black pawn moved up two */\r\n\t\t\tif ((chessHistory[numMoves][TOROW] == 3) && (chessHistory[numMoves][FROMROW] == 1) && (chessHistory[numMoves][TOCOL] == toCol))\r\n\t\t\t\treturn true;\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\t//errMsg = \"Pawns can only move en passant immediately after an opponent played his pawn.\";\r\n\t\t\t\terrMsg = document.getElementById('#alert_err_move_passant_id').innerHTML;\r\n\t\t\t\t\r\n\t\t\t\treturn false;\r\n\t\t\t}\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\t//errMsg = \"Pawns cannot move like that.\";\r\n\t\t\terrMsg = document.getElementById('#alert_err_move_pawn_id').innerHTML;\r\n\t\t\t\r\n\t\t\treturn false;\r\n\t\t}\r\n\t}", "checkAvailableMoves() {\n this.prolog.checkAvailableMoves(this.gameboard.toString(), this.currentPlayer)\n }", "function isOpenPos(x, y) {\n\tif (x < 0 && x >= canvasWidth / pieceSize) {\n\t\treturn false;\n\t}\n\tif (y < 0 && y >= canvasHeight / pieceSize) {\n\t\treturn false;\n\t}\n\n\tswitch(board[y][x]) {\n\t\tcase 3: // Wall\n\t\t\treturn false;\n\t\tcase 2: // Monster\n\t\t\treturn false;\n\t\tcase 1: // Player\n\t\t\treturn false;\n\t\tcase 0: // Empty\n\t\t\treturn true;\n\t}\n}", "canMove(tile) {\r\n if (abs(tile.mapX - this.mapX) <= this.info.movement &&\r\n abs(tile.mapY - this.mapY) <= this.info.movement) {\r\n if (tile.unit) {\r\n return false;\r\n }\r\n return true;\r\n }\r\n return false;\r\n }", "function check_if_can_move(location, direction){\n if(direction == \"secret\"){\n if (location[0] % 4 == 0 && location[1] % 4 == 0){\n return true;\n }\n return false;\n }\n \n switch(direction) {\n case \"left\": \n if ((location[0] - 1) < 0)\n return false;\n break;\n case \"up\":\n if ((location[1] + 1) > 4)\n return false;\n break;\n case \"right\":\n if((location[0] + 1) > 4)\n return false;\n break;\n case \"down\":\n if((location[1] - 1) < 0)\n return false;\n break;\n }\n return true;\n}", "function valid_move(who,dr,dc,r,c,board){\n var other;\n if(who === 'd'){\n other = 'l';\n }\n else if(who === 'l'){\n other = 'd';\n }\n else{\n log('Houston, we have a color problem: '+who);\n return false;\n }\n if( (r+dr < 0) || (r+dr > 7) ){\n return false;\n }\n if( (c+dc < 0) || (c+dc > 7) ){\n return false;\n }\n if(board[r+dr][c+dc] != other){\n return false;\n }\n if( (r+dr+dr < 0) || (r+dr+dr > 7) ){\n return false;\n }\n if( (c+dc+dc < 0) || (c+dc+dc > 7) ){\n return false;\n }\n return check_line_match(who, dr, dc, r+dr+dr, c+dc+dc, board);\n}", "validDirections() {\r\n let row;\r\n let col;\r\n\r\n if (game.color == 'b') {\r\n row = game.blackPositions[game.piece - 1][0];\r\n col = game.blackPositions[game.piece - 1][1];\r\n }\r\n\r\n if (game.color == 'w') {\r\n row = game.whitePositions[game.piece - 1][0];\r\n col = game.whitePositions[game.piece - 1][1];\r\n }\r\n\r\n this.getPrologRequest(\"valid_moves(\" + game.board + \",\" + row + \",\" + col + \")\", this.validMovesReply);\r\n }", "verifyMove(playerColor, selectedPiece, stoneColor, gnomeColor, startSpace, endSpace) {\n\n //checks if player can move selectedPiece from startSpace to endSpace validly\n //if valid, returns true\n //check if playerColor is same as the selectedPieceColor\n //find out what kind of piece selectedPiece is;\n //if selectedPiece is stone can only move to empty place, no gnomes can be occupying that startSpace with it\n //if selectedPiece is gnome, it can move to any empty adjacent stone or land\n //check if selectedEnd is bLand, wLand, wEmptyLand, bEmptyLand\n\n\n if (playerColor === selectedPieceColor) {\n return\n }\n\n\n && (turnCount >= 6) && (endSpace.empty === true) {\n endSpace = selectedPiece)\n }\n }", "checkPosition (y, x) {\n\t\t// Checks position of coordinates\n\t\treturn this.grid[y][x] === 0;\n\t}", "function isSafe(testRow, testCol, testColor)\r\n\t{\r\n\t\t/* NOTE: if a piece occupates the square itself,\r\n\t\t\tthat piece does not participate in determining the safety of the square */\r\n\r\n\t\t/* IMPORTANT: note that if we're checking to see if the square is safe for a pawn\r\n\t\t\twe're moving, we need to verify the safety for En-passant */\r\n\r\n\t\t/* OPTIMIZE: cache results (if client-side game only, invalidate cache after each move) */\r\n\r\n\t\t/* AI NOTE: just because a square isn't entirely safe doesn't mean we don't want to\r\n\t\t\tmove there; for instance, we may be protected by another piece */\r\n\r\n\t\t/* DESIGN NOTE: this function is mostly designed with CHECK checking in mind and\r\n\t\t\tmay not be suitable for other purposes */\r\n\r\n\t\tvar ennemyColor = 0;\r\n\t\t\r\n\t\tif (testColor == 'white')\r\n\t\t\tennemyColor = 128; /* 1000 0000 */\r\n\r\n\t\t/* check for knights first */\r\n\t\tfor (var i = 0; i < 8; i++) {\t// Check all eight possible knight moves\r\n\t\t\tvar fromRow = testRow + knightMove[i][0];\r\n\t\t\tvar fromCol = testCol + knightMove[i][1];\r\n\t\t\tif (isInBoard(fromRow, fromCol))\r\n\t\t\t\tif (board[fromRow][fromCol] == (KNIGHT | ennemyColor))\t// Enemy knight found\r\n\t\t\t\t\t\treturn false;\r\n\t\t}\r\n\r\n\t\t/* tactic: start at test pos and check all 8 directions for an attacking piece */\r\n\t\t/* directions:\r\n\t\t\t0 1 2\r\n\t\t\t7 * 3\r\n\t\t\t6 5 4\r\n\t\t*/\r\n\t\tvar pieceFound = new Array();\r\n\t\tfor (i = 0; i < 8; i++)\r\n\t\t\tpieceFound[i] = new GamePiece();\r\n\r\n\t\tfor (i = 1; i < 8; i++)\r\n\t\t{\r\n\t\t\tif (((testRow - i) >= 0) && ((testCol - i) >= 0))\r\n\t\t\t\tif ((pieceFound[0].piece == 0) && (board[testRow - i][testCol - i] != 0))\r\n\t\t\t\t{\r\n\t\t\t\t\tpieceFound[0].piece = board[testRow - i][testCol - i];\r\n\t\t\t\t\tpieceFound[0].dist = i;\r\n\t\t\t\t}\r\n\r\n\t\t\tif ((testRow - i) >= 0)\r\n\t\t\t\tif ((pieceFound[1].piece == 0) && (board[testRow - i][testCol] != 0))\r\n\t\t\t\t{\r\n\t\t\t\t\tpieceFound[1].piece = board[testRow - i][testCol];\r\n\t\t\t\t\tpieceFound[1].dist = i;\r\n\t\t\t\t}\r\n\r\n\t\t\tif (((testRow - i) >= 0) && ((testCol + i) < 8))\r\n\t\t\t\tif ((pieceFound[2].piece == 0) && (board[testRow - i][testCol + i] != 0))\r\n\t\t\t\t{\r\n\t\t\t\t\tpieceFound[2].piece = board[testRow - i][testCol + i];\r\n\t\t\t\t\tpieceFound[2].dist = i;\r\n\t\t\t\t}\r\n\r\n\t\t\tif ((testCol + i) < 8)\r\n\t\t\t\tif ((pieceFound[3].piece == 0) && (board[testRow][testCol + i] != 0))\r\n\t\t\t\t{\r\n\t\t\t\t\tpieceFound[3].piece = board[testRow][testCol + i];\r\n\t\t\t\t\tpieceFound[3].dist = i;\r\n\t\t\t\t}\r\n\r\n\t\t\tif (((testRow + i) < 8) && ((testCol + i) < 8))\r\n\t\t\t\tif ((pieceFound[4].piece == 0) && (board[testRow + i][testCol + i] != 0))\r\n\t\t\t\t{\r\n\t\t\t\t\tpieceFound[4].piece = board[testRow + i][testCol + i];\r\n\t\t\t\t\tpieceFound[4].dist = i;\r\n\t\t\t\t}\r\n\r\n\t\t\tif ((testRow + i) < 8)\r\n\t\t\t\tif ((pieceFound[5].piece == 0) && (board[testRow + i][testCol] != 0))\r\n\t\t\t\t{\r\n\t\t\t\t\tpieceFound[5].piece = board[testRow + i][testCol];\r\n\t\t\t\t\tpieceFound[5].dist = i;\r\n\t\t\t\t}\r\n\r\n\t\t\tif (((testRow + i) < 8) && ((testCol - i) >= 0))\r\n\t\t\t\tif ((pieceFound[6].piece == 0) && (board[testRow + i][testCol - i] != 0))\r\n\t\t\t\t{\r\n\t\t\t\t\tpieceFound[6].piece = board[testRow + i][testCol - i];\r\n\t\t\t\t\tpieceFound[6].dist = i;\r\n\t\t\t\t}\r\n\r\n\t\t\tif ((testCol - i) >= 0)\r\n\t\t\t\tif ((pieceFound[7].piece == 0) && (board[testRow][testCol - i] != 0))\r\n\t\t\t\t{\r\n\t\t\t\t\tpieceFound[7].piece = board[testRow][testCol - i];\r\n\t\t\t\t\tpieceFound[7].dist = i;\r\n\t\t\t\t}\r\n\t\t}\r\n\r\n\t\t/* check pieces found for possible threats */\r\n\t\tfor (var i = 0; i < 8; i++)\r\n\t\t\tif ((pieceFound[i].piece != 0) && ((pieceFound[i].piece & BLACK) == ennemyColor))\r\n\t\t\t\tswitch(i)\r\n\t\t\t\t{\r\n\t\t\t\t\t/* diagonally: queen, bishop, pawn, king */\r\n\t\t\t\t\tcase 0:\r\n\t\t\t\t\tcase 2:\r\n\t\t\t\t\tcase 4:\r\n\t\t\t\t\tcase 6:\r\n\t\t\t\t\t\tif (((pieceFound[i].piece & COLOR_MASK) == QUEEN)\r\n\t\t\t\t\t\t\t\t|| ((pieceFound[i].piece & COLOR_MASK) == BISHOP))\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\treturn false;\r\n\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\tif ((pieceFound[i].dist == 1)\r\n\t\t\t\t\t\t\t\t&& ((pieceFound[i].piece & COLOR_MASK) == PAWN))\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\tif ((ennemyColor == WHITE) && ((i == 0) || (i == 2)))\r\n\t\t\t\t\t\t\t\treturn false;\r\n\t\t\t\t\t\t\telse if ((ennemyColor == BLACK) && ((i == 4) || (i == 6)))\r\n\t\t\t\t\t\t\t\treturn false;\r\n\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\tif ((pieceFound[i].dist == 1)\r\n\t\t\t\t\t\t\t\t&& ((pieceFound[i].piece & COLOR_MASK) == KING))\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t/* Are the kings next to each other? */\r\n\t\t\t\t\t\t\tif ((board[testRow][testCol] & COLOR_MASK) == KING)\r\n\t\t\t\t\t\t\t\treturn false;\r\n\r\n\t\t\t\t\t\t\t/* save current board destination */\r\n\t\t\t\t\t\t\tvar tmpPiece = board[testRow][testCol];\r\n\r\n\t\t\t\t\t\t\t/* update board with move (client-side) */\r\n\t\t\t\t\t\t\tboard[testRow][testCol] = pieceFound[i].piece;\r\n\r\n\t\t\t\t\t\t\tvar kingRow = 0;\r\n\t\t\t\t\t\t\tvar kingCol = 0;\r\n\t\t\t\t\t\t\tswitch(i)\r\n\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\tcase 0: kingRow = testRow - 1; kingCol = testCol - 1;\r\n\t\t\t\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t\t\t\tcase 1: kingRow = testRow - 1; kingCol = testCol;\r\n\t\t\t\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t\t\t\tcase 2: kingRow = testRow - 1; kingCol = testCol + 1;\r\n\t\t\t\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t\t\t\tcase 3: kingRow = testRow; kingCol = testCol + 1;\r\n\t\t\t\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t\t\t\tcase 4: kingRow = testRow + 1; kingCol = testCol + 1;\r\n\t\t\t\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t\t\t\tcase 5: kingRow = testRow + 1; kingCol = testCol;\r\n\t\t\t\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t\t\t\tcase 6: kingRow = testRow + 1; kingCol = testCol - 1;\r\n\t\t\t\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t\t\t\tcase 7: kingRow = testRow; kingCol = testCol - 1;\r\n\t\t\t\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\t\tboard[kingRow][kingCol] = 0;\r\n\r\n\t\t\t\t\t\t\t/* if king needs to move into check to capture piece, isSafe() is true */\r\n\t\t\t\t\t\t\tvar tmpIsSafe = isInCheck(getOtherColor(testColor));\r\n\r\n\t\t\t\t\t\t\t/* restore board to previous state */\r\n\t\t\t\t\t\t\tboard[kingRow][kingCol] = pieceFound[i].piece;\r\n\t\t\t\t\t\t\tboard[testRow][testCol] = tmpPiece;\r\n\r\n\t\t\t\t\t\t\t/* if king CAN eat target without moving into check, return false */\r\n\t\t\t\t\t\t\t/* otherwise, continue checking other piecesFound */\r\n\t\t\t\t\t\t\tif (!tmpIsSafe)\r\n\t\t\t\t\t\t\t\treturn false;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\tbreak;\r\n\r\n\t\t\t\t\t/* horizontally/vertically: queen, rook, king */\r\n\t\t\t\t\tcase 1:\r\n\t\t\t\t\tcase 3:\r\n\t\t\t\t\tcase 5:\r\n\t\t\t\t\tcase 7:\r\n\t\t\t\t\t\tif (((pieceFound[i].piece & COLOR_MASK) == QUEEN)\r\n\t\t\t\t\t\t\t\t|| ((pieceFound[i].piece & COLOR_MASK) == ROOK))\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\treturn false;\r\n\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\tif ((pieceFound[i].dist == 1)\r\n\t\t\t\t\t\t\t\t&& ((pieceFound[i].piece & COLOR_MASK) == KING))\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t/* Are the kings next to each other? */\r\n\t\t\t\t\t\t\tif ((board[testRow][testCol] & COLOR_MASK) == KING)\r\n\t\t\t\t\t\t\t\treturn false;\r\n\r\n\t\t\t\t\t\t\t/* save current board destination */\r\n\t\t\t\t\t\t\tvar tmpPiece = board[testRow][testCol];\r\n\r\n\t\t\t\t\t\t\t/* update board with move (client-side) */\r\n\t\t\t\t\t\t\tboard[testRow][testCol] = pieceFound[i].piece;\r\n\r\n\t\t\t\t\t\t\tvar kingRow = 0;\r\n\t\t\t\t\t\t\tvar KingCol = 0;\r\n\t\t\t\t\t\t\tswitch(i)\r\n\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\tcase 0: kingRow = testRow - 1; kingCol = testCol - 1;\r\n\t\t\t\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t\t\t\tcase 1: kingRow = testRow - 1; kingCol = testCol;\r\n\t\t\t\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t\t\t\tcase 2: kingRow = testRow - 1; kingCol = testCol + 1;\r\n\t\t\t\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t\t\t\tcase 3: kingRow = testRow; kingCol = testCol + 1;\r\n\t\t\t\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t\t\t\tcase 4: kingRow = testRow + 1; kingCol = testCol + 1;\r\n\t\t\t\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t\t\t\tcase 5: kingRow = testRow + 1; kingCol = testCol;\r\n\t\t\t\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t\t\t\tcase 6: kingRow = testRow + 1; kingCol = testCol - 1;\r\n\t\t\t\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t\t\t\tcase 7: kingRow = testRow; kingCol = testCol - 1;\r\n\t\t\t\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\t\tboard[kingRow][kingCol] = 0;\r\n\r\n\t\t\t\t\t\t\t/* if king needs to move into check to capture piece, isSafe() is true */\r\n\t\t\t\t\t\t\tvar tmpIsSafe = isInCheck(getOtherColor(testColor));\r\n\r\n\t\t\t\t\t\t\t/* restore board to previous state */\r\n\t\t\t\t\t\t\tboard[kingRow][kingCol] = pieceFound[i].piece;\r\n\t\t\t\t\t\t\tboard[testRow][testCol] = tmpPiece;\r\n\r\n\t\t\t\t\t\t\t/* if king CAN eat target without moving into check, return false */\r\n\t\t\t\t\t\t\t/* otherwise, continue checking other piecesFound */\r\n\t\t\t\t\t\t\tif (!tmpIsSafe)\r\n\t\t\t\t\t\t\t\treturn false;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t}\r\n\t\treturn true;\r\n\t}", "function invalidMove(){\n\n }", "function winDetection(player) {\n if (player.y >= 0 && player.y <= 20 ) {\n gameReset();\n return true;\n }\n}", "function safeCoordinate(x, y) {\r\n if (x < 0 || x >= row) return false;\r\n if (y < 0 || y >= col) return false;\r\n if (grid[x][y].state == 'block') return false;\r\n\r\n return true;\r\n}", "isValidMoveNew(row, column) {\n if (!isInBoundaries(row, column)) {\n return false;\n }\n if (!this.tileSet.hasTileAt(row, column)) {\n return false;\n }\n var dx = [1, 0, -1, 0];\n var dy = [0, 1, 0, -1];\n let thisTile = this.tileSet.getTileAt(row, column);\n for (var i = 0; i < 4; ++i) {\n // if the given cell's i'th neighbour has the same color as this\n // cell, then this move is valid\n var neighbourTile = this.tileSet.getTileAt(row + dx[i], column + dy[i]);\n if (thisTile.equalTo(neighbourTile)) {\n return true;\n }\n }\n // if we have not found any neighbours with the same color, then the\n // move is not valid\n return false;\n }", "function canPass(xTile, yTile) {\n\tif (xTile < 0 || yTile < 0 || xTile >= gridWidth || yTile >= gridHeight) return false;\n\treturn !grid[xTile + yTile * gridWidth].blocks;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calculate the output of the cascade of biquad filters for an inputBuffer.
process(inputBuffer, outputBuffer) { var x; var y = []; var b1, b2, a1, a2; var xi1, xi2, yi1, yi2, y1i1, y1i2; for (var i = 0; i < inputBuffer.length; i++) { x = inputBuffer[i]; // Save coefficients in local variables b1 = this.coefficients[0].b1; b2 = this.coefficients[0].b2; a1 = this.coefficients[0].a1; a2 = this.coefficients[0].a2; // Save memories in local variables xi1 = this.memories[0].xi1; xi2 = this.memories[0].xi2; yi1 = this.memories[0].yi1; yi2 = this.memories[0].yi2; // Formula: y[n] = x[n] + b1*x[n-1] + b2*x[n-2] - a1*y[n-1] - a2*y[n-2] // First biquad y[0] = x + b1 * xi1 + b2 * xi2 - a1 * yi1 - a2 * yi2; for (var e = 1; e < this.numberOfCascade; e++) { // Save coefficients in local variables b1 = this.coefficients[e].b1; b2 = this.coefficients[e].b2; a1 = this.coefficients[e].a1; a2 = this.coefficients[e].a2; // Save memories in local variables y1i1 = this.memories[e - 1].yi1; y1i2 = this.memories[e - 1].yi2; yi1 = this.memories[e].yi1; yi2 = this.memories[e].yi2; y[e] = y[e - 1] + b1 * y1i1 + b2 * y1i2 - a1 * yi1 - a2 * yi2; } // Write the output outputBuffer[i] = y[this.numberOfCascade - 1] * this.coefficients.g; // Update the memories this.memories[0].xi2 = this.memories[0].xi1; this.memories[0].xi1 = x; for (var p = 0; p < this.numberOfCascade; p++) { this.memories[p].yi2 = this.memories[p].yi1; this.memories[p].yi1 = y[p]; } } }
[ "stream(value) {\n let out = 0;\n this.filter.pop();\n this.filter.unshift(value);\n\n for (let i = 0, end = this.coefficients.length; i < end; ++i) {\n out += this.coefficients[i] * this.filter[i];\n }\n\n this.filter.shift();\n this.filter.unshift(out);\n return out;\n }", "_bufferTransform() {\n if (this.mode === 'buffer') {\n const scale = this.bufferValue / 100;\n return { transform: `scaleX(${scale})` };\n }\n return null;\n }", "function displayBuffer(buff /* is an AudioBuffer */) {\n\n let container = document.getElementById(\"waveformContainer\");\n seekPositionBar.style.height = (buff.numberOfChannels * 100) + 'px';\n seekPositionBar.style.bottom = -(135 + buff.numberOfChannels * 100) + 'px';\n seekPositionBar.style.display = \"block\";\n for (let channel = 0; channel < buff.numberOfChannels; channel++) {\n let canvas = document.createElement('canvas');\n canvas.id = \"waveform\" + channel;\n canvas.width = canvasWidth;\n canvas.height = canvasHeight;\n container.appendChild(canvas);\n\n let channelData = buff.getChannelData(channel);\n createChannelWaveform(canvas, channelData);\n }\n}", "function ConvolutionPostProcess(name,/** Array of 9 values corrisponding to the 3x3 kernel to be applied */kernel,options,camera,samplingMode,engine,reusable,textureType){if(textureType===void 0){textureType=BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;}var _this=_super.call(this,name,\"convolution\",[\"kernel\",\"screenSize\"],null,options,camera,samplingMode,engine,reusable,null,textureType)||this;_this.kernel=kernel;_this.onApply=function(effect){effect.setFloat2(\"screenSize\",_this.width,_this.height);effect.setArray(\"kernel\",_this.kernel);};return _this;}// Statics", "function AugmentBroadband ( Inb, Ibb, F, exposBB, exposNB, fwBB, fwNB, outname ) {\n // setup CONSTANTS\n let k1 = exposNB/exposBB;\n let k3 = k1*fwNB/fwBB;\n\n // equations that mix narrowband into the broadband channel\n let BkgnEQ = \"Bkgn=(\"+k1+\"*\"+Ibb.id+\"-\"+Inb.id+\")/(\"+k1+\"-\"+k3+\"); \";\n let LineEQ = \"Line=max(\"+Ibb.id+\"-Bkgn, 0); \";\n let MixEQ = F+\"*Line+Bkgn; \";\n let EQ = BkgnEQ + LineEQ + MixEQ; // order dependent!!!\n\n // implement above equations in PixelMath\n var P = new PixelMath;\n P.expression = EQ;\n P.symbols = \"Inb, Ibb, F, Line, Bkgn, Mix, outname\";\n P.expression1 = \"\";\n P.expression2 = \"\";\n P.useSingleExpression = true;\n P.generateOutput = true;\n P.singleThreaded = false;\n P.optimization = true;\n P.use64BitWorkingImage = true;\n P.rescale = true;\n P.rescaleLower = 0;\n P.rescaleUpper = 1;\n P.truncate = true;\n P.truncateLower = 0;\n P.truncateUpper = 1;\n P.createNewImage = true;\n P.showNewImage = true;\n P.newImageId = outname;\n P.newImageWidth = 0;\n P.newImageHeight = 0;\n P.newImageAlpha = false;\n P.newImageColorSpace = PixelMath.prototype.Gray;\n P.newImageSampleFormat = PixelMath.prototype.SameAsTarget;\n P.executeOn(Ibb);\n\t\tvar view = View.viewById(outname);\n \treturn view;\n}", "function buffer1(geometry) {\n return geometry.buffer(5000);\n}", "function getInputActivations({ imageWidth, imageHeight, imagesBuffer }, sampleId) {\n // size of input\n const sizeOfInput = imageWidth * imageHeight;\n // our result array\n const inputActivations = new Float32Array(sizeOfInput);\n // for each pixel in the image\n for (let r = 0; r < imageHeight; ++r) {\n for (let c = 0; c < imageWidth; ++c) {\n inputActivations[r * imageWidth + c] =\n imagesBuffer.getUint8(sampleId * sizeOfInput + r * imageWidth + c) / 256.0;\n }\n }\n return inputActivations;\n }", "getNumberOfCascadeFilters(coef) {\n return (coef.length - 1) / 4;\n }", "_trackGPUResultBuffers(results, weights) {\n const {\n resources\n } = this.state;\n\n for (const id in results) {\n if (results[id]) {\n for (const bufferName of BUFFER_NAMES) {\n if (results[id][bufferName] && weights[id][bufferName] !== results[id][bufferName]) {\n // No result buffer is provided in weights object, `readPixelsToBuffer` has created a new Buffer object\n // collect the new buffer for garabge collection\n const name = `gpu-result-${id}-${bufferName}`;\n\n if (resources[name]) {\n resources[name].delete();\n }\n\n resources[name] = results[id][bufferName];\n }\n }\n }\n }\n }", "function normalizedSquareDifference(float32AudioBuffer) {\n var acf;\n var divisorM;\n squaredBufferSum[0] = float32AudioBuffer[0] * float32AudioBuffer[0];\n for (var i = 1; i < float32AudioBuffer.length; i += 1) {\n squaredBufferSum[i] =\n float32AudioBuffer[i] * float32AudioBuffer[i] + squaredBufferSum[i - 1];\n }\n for (var tau = 0; tau < float32AudioBuffer.length; tau++) {\n acf = 0;\n divisorM =\n squaredBufferSum[float32AudioBuffer.length - 1 - tau] +\n squaredBufferSum[float32AudioBuffer.length - 1] -\n squaredBufferSum[tau];\n for (var i = 0; i < float32AudioBuffer.length - tau; i++) {\n acf += float32AudioBuffer[i] * float32AudioBuffer[i + tau];\n }\n nsdf[tau] = (2 * acf) / divisorM;\n }\n }", "function mix (bufferA, bufferB, weight, offset) {\r\n validate(bufferA);\r\n validate(bufferB);\r\n\r\n if (weight == null) weight = 0.5;\r\n var fn = weight instanceof Function ? weight : function (a, b) {\r\n return a * (1 - weight) + b * weight;\r\n };\r\n\r\n if (offset == null) offset = 0;\r\n else if (offset < 0) offset += bufferA.length;\r\n\r\n for (var channel = 0; channel < bufferA.numberOfChannels; channel++) {\r\n var aData = bufferA.getChannelData(channel);\r\n var bData = bufferB.getChannelData(channel);\r\n\r\n for (var i = offset, j = 0; i < bufferA.length && j < bufferB.length; i++, j++) {\r\n aData[i] = fn.call(bufferA, aData[i], bData[j], j, channel);\r\n }\r\n }\r\n\r\n return bufferA;\r\n}", "function BlurPostProcess(name,/** The direction in which to blur the image. */direction,kernel,options,camera,samplingMode,engine,reusable,textureType,defines,blockCompilation){if(samplingMode===void 0){samplingMode=BABYLON.Texture.BILINEAR_SAMPLINGMODE;}if(textureType===void 0){textureType=BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;}if(defines===void 0){defines=\"\";}if(blockCompilation===void 0){blockCompilation=false;}var _this=_super.call(this,name,\"kernelBlur\",[\"delta\",\"direction\",\"cameraMinMaxZ\"],[\"circleOfConfusionSampler\"],options,camera,samplingMode,engine,reusable,null,textureType,\"kernelBlur\",{varyingCount:0,depCount:0},true)||this;_this.direction=direction;_this.blockCompilation=blockCompilation;_this._packedFloat=false;_this._staticDefines=\"\";_this._staticDefines=defines;_this.onApplyObservable.add(function(effect){if(_this._outputTexture){effect.setFloat2('delta',1/_this._outputTexture.width*_this.direction.x,1/_this._outputTexture.height*_this.direction.y);}else{effect.setFloat2('delta',1/_this.width*_this.direction.x,1/_this.height*_this.direction.y);}});_this.kernel=kernel;return _this;}", "output(inputArr) {\n\n let inputs = (this.hiddensOutputs.singleColumnMatrix(inputArr)); //turn the vision array into a 1xN Matrix\n let Biased = inputs.Bias(); //Applies a level of bias to the array to encourage acting\n\n let WeightedHiddenInputs = this.hiddensInputs.dot(inputs); //Runs the biased input matrix through the first matrix\n\n let WeightedHiddenOutputs = WeightedHiddenInputs.activate(); //Runs the 1 generation matrix through the sigmoid function (which represents learning curves)\n\n let WeightedHiddenOutputsBias = WeightedHiddenOutputs.Bias(); //Adds a level of bias to the 1 generation matrix to encourage acting\n\n let HI2 = this.hiddenshiddens.dot(WeightedHiddenOutputsBias); //Runs the 1 generation matrix through the second matrix \n\n let HO2 = HI2.activate(); //Runs the 2 generation matrix through the sigmoid function learning curve\n let HOB2 = HO2.Bias(); //Adds a level of bias to the 2 generation matrix to encourage acting\n\n let OutIn = this.hiddensOutputs.dot(HOB2); // runs the 2 generation matrix through the third matrix\n\n let Out = OutIn.activate(); //runs the 3 generation matrix through the sigmoid learning curve\n\n return Out.toArray(); //outputs the 3 generation learning matrix to an array to be returned to the ship.\n }", "function compute_LF_filtering(ibu) {\n var LF_filtering = 0.0;\n\n LF_filtering = 1.0;\n if (!isNaN(ibu.filtering.value)) {\n if (ibu.filtering.value >= 0 && ibu.filtering.value < 3.83) {\n // formula based on Fix & Fix page 129 Table 5.5\n LF_filtering = (0.017 * ibu.filtering.value) + 0.934\n }\n }\n if (SMPH.verbose > 5) {\n console.log(\"LF filtering : \" + LF_filtering.toFixed(4));\n }\n return LF_filtering;\n}", "function combinedWF(channel,wfarray,index,differ6581) { //on 6581 most combined waveforms are essentially halved 8580-like waves\n if(differ6581 && SID_model==6581.0) index&=0x7FF; combiwf = (wfarray[index]+prevwavdata[channel])/2; prevwavdata[channel]=wfarray[index]; return combiwf; \n }", "calculateCoefficients () {\n\n const modifiedInputs = this._applyCallbackToInputs();\n const transposedInputs = math.transpose(modifiedInputs);\n \n let result = math.multiply(transposedInputs, modifiedInputs);\n result = math.inv(result);\n result = math.multiply(result, transposedInputs);\n result = math.multiply(result, this._outputs);\n\n this._coefficients = \n this._getCoefficientsArrayByMatrix(result);\n\n return this._coefficients;\n }", "measure(q, b) {\n if (q >= this.numQubits) {\n throw 'Index for qubit out of range.';\n }\n if (b >= this.numClbits) {\n throw 'Index for output bit out of range.';\n }\n this.data.push('m', q, b);\n return this;\n}", "function guesstimatorInputToCdf({\n guesstimatorInput,\n simulationSampleCount,\n outputSampleCount,\n smoothingWidth,\n min,\n max\n}) {\n let toSamples = inputToSamples({\n input: guesstimatorInput,\n simulationSampleCount: simulationSampleCount\n });\n var samp = new cdfLib.Samples(toSamples.values);\n return samp.toCdf({\n size: outputSampleCount,\n width: smoothingWidth,\n min: min,\n max: max\n });\n}", "SolveBend_PBD_Triangle() {\n const stiffness = this.m_tuning.bendStiffness;\n for (let i = 0; i < this.m_bendCount; ++i) {\n const c = this.m_bendConstraints[i];\n const b0 = this.m_ps[c.i1].Clone();\n const v = this.m_ps[c.i2].Clone();\n const b1 = this.m_ps[c.i3].Clone();\n const wb0 = c.invMass1;\n const wv = c.invMass2;\n const wb1 = c.invMass3;\n const W = wb0 + wb1 + 2.0 * wv;\n const invW = stiffness / W;\n const d = new b2_math_js_1.b2Vec2();\n d.x = v.x - (1.0 / 3.0) * (b0.x + v.x + b1.x);\n d.y = v.y - (1.0 / 3.0) * (b0.y + v.y + b1.y);\n const db0 = new b2_math_js_1.b2Vec2();\n db0.x = 2.0 * wb0 * invW * d.x;\n db0.y = 2.0 * wb0 * invW * d.y;\n const dv = new b2_math_js_1.b2Vec2();\n dv.x = -4.0 * wv * invW * d.x;\n dv.y = -4.0 * wv * invW * d.y;\n const db1 = new b2_math_js_1.b2Vec2();\n db1.x = 2.0 * wb1 * invW * d.x;\n db1.y = 2.0 * wb1 * invW * d.y;\n b0.SelfAdd(db0);\n v.SelfAdd(dv);\n b1.SelfAdd(db1);\n this.m_ps[c.i1].Copy(b0);\n this.m_ps[c.i2].Copy(v);\n this.m_ps[c.i3].Copy(b1);\n }\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Visit a parse tree produced by PlSqlParserset_transaction_command.
visitSet_transaction_command(ctx) { return this.visitChildren(ctx); }
[ "visitTransaction_control_statements(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "function parse_StatementList(){\n\t\n\n\t\n\n\tvar tempDesc = tokenstreamCOPY[parseCounter][0]; //check desc of token\n\tvar tempType = tokenstreamCOPY[parseCounter][1]; //check type of token\n\n\tif (tempDesc == ' print' || tempType == 'identifier' || tempType == 'type' || tempDesc == ' while' || tempDesc == ' if' || tempDesc == '{' ){ //if next token is a statment\n\t\tdocument.getElementById(\"tree\").value += \"PARSER: parse_StatementList()\" + '\\n';\n\t\tCSTREE.addNode('StatementList', 'branch');\n\t\t\n\t\t\n\t\tparse_Statement(); \n\t\n\t\tparse_StatementList();\n\t\t\n\t\tCSTREE.endChildren();\n\t\n\t\t\n\t\t\n\t}\n\telse{\n\t\t\n\t\t\n\t\t//e production\n\t}\n\n\n\n\n\t\n\t\n}", "visitCommit_statement(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "visitData_manipulation_language_statements(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "visitUnit_statement(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "visitSeq_of_statements(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "commit(transaction) {\n return this._transmit(\"COMMIT\", {\n transaction: transaction\n });\n }", "function generateStatementList(node)\n\t{\n\t\tfor(var i = 0; i < node.children.length; i++)\n\t\t{\n\t\t\tgenerateStatement(node.children[i]);\n\t\t}\n\t}", "visitInsert_statement(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "visitCursor_manipulation_statements(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "function tcbProcessNodes(nodes, tcb, scope) {\n nodes.forEach(function (node) {\n // Process elements, templates, and bindings.\n if (node instanceof compiler_1.TmplAstElement) {\n tcbProcessElement(node, tcb, scope);\n }\n else if (node instanceof compiler_1.TmplAstTemplate) {\n tcbProcessTemplateDeclaration(node, tcb, scope);\n }\n else if (node instanceof compiler_1.TmplAstBoundText) {\n var expr = tcbExpression(node.value, tcb, scope);\n scope.addStatement(ts.createStatement(expr));\n }\n });\n }", "visitGrant_statement(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "parse_statement() {\n let values = this.find_some(this.parse_base_expr, tk.COMMA, tk.BAR); \n return Ex(pr.Statement, values);\n }", "function STLangVisitor() {\n STLangParserVisitor.call(this);\n this.result = {\n \"valid\": true,\n \"error\": null,\n \"tree\": {\n \"text\": \"\",\n \"children\": null\n }\n };\n\treturn this;\n}", "function txHandler (state, tx, context) {\n if (tx.headers) {\n // headers tx, add headers to chain\n headersTx(state, tx, context)\n } else if (tx.transactions) {\n // deposit tx, verify tx and collect UTXO(s)\n depositTx(state, tx, context)\n } else if (tx.signatoryKey) {\n // signatory key tx, add validator's pubkey to signatory set\n signatoryKeyTx(state, tx, context)\n } else {\n throw Error('Unknown transaction type')\n }\n }", "visitSql_operation(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "visitOpen_statement(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "function parse_PrintStatement(){\n\tdocument.getElementById(\"tree\").value += \"PARSER: parse_PrintStatement()\" + '\\n';\n\tCSTREE.addNode('PrintStatment', 'branch');\n\n\t\n\tmatchSpecChars(' print',parseCounter);\n\t\n\tparseCounter = parseCounter + 1;\n\t\n\t\n\tmatchSpecChars('(',parseCounter);\n\t\n\tparseCounter = parseCounter + 1;\n\t\n\t\n\tparse_Expr(); \n\t\n\t\n\t\n\tmatchSpecChars (')',parseCounter);\n\t\n\tCSTREE.endChildren();\n\n\tparseCounter = parseCounter + 1;\n\t\n\t\n}", "visitSql_plus_command(ctx) {\n\t return this.visitChildren(ctx);\n\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Expand/Collapse all bug's comments. commentSize total comment size. stateInit = set 1 for Expand init or else 2 for Collapse init.
function allCommentAction(commentSize, stateInit, expandId, imgId, prefixId, imgIdx) { var state1 = "Expand All"; var state2 = "Collapse All"; var expandObj = document.getElementById(expandId == null ? 'comments_expand' : expandId); imgId = (imgId == null ? "img_comment_" : imgId); prefixId = (prefixId == null ? "comment_" : prefixId); if (stateInit != null) { if (stateInit == 1) { Tikal.Bugzilla.Util.setInnerHTML(expandObj, state1); } else if (stateInit == 2){ Tikal.Bugzilla.Util.setInnerHTML(expandObj, state2); } } if (expandObj.innerHTML == state1) { Tikal.Bugzilla.Util.setInnerHTML(expandObj, state2); minimizeAction(commentSize, 'down', imgId, prefixId, imgIdx) } else { Tikal.Bugzilla.Util.setInnerHTML(expandObj, state1); minimizeAction(commentSize, 'up', imgId, prefixId, imgIdx) } }
[ "function collapseComments() {\n $('.commentarea .comment .child').hide();\n $('.tagline').append('<span class=\"expand-children\">[+]</span>');\n $('.tagline .expand-children')\n .css('cursor', 'pointer')\n .click(function() {\n toggleExpandButton(this);\n $(this).closest('.comment').find('.child').toggle();\n });\n loadImage();\n\n /**\n * Toggle expand button from + to -.\n *\n * @param {Element} el\n */\n\n function toggleExpandButton(el) {\n if (~$(el).text().indexOf('+'))\n $(el).text('[-]');\n else\n $(el).text('[+]');\n }\n}", "function toggleCommentCollapse(elem) {\n var str = elem.childNodes[elem.childNodes.length-1].innerHTML;\n if (elem.getAttribute(\"data-collapsed\") == \"true\") {\n elem.setAttribute(\"data-collapsed\", \"false\");\n elem.style.height = (parseInt(elem.getAttribute(\"data-origheight\"))+40)+\"px\";\n elem.childNodes[elem.childNodes.length-1].innerHTML = str.replace(\"Show full comment\", \"Collapse comment\");\n } else {\n elem.setAttribute(\"data-collapsed\", \"true\");\n elem.style.height = '100px';\n elem.childNodes[elem.childNodes.length-1].innerHTML = str.replace(\"Collapse comment\", \"Show full comment\");\n }\n}", "function initComments() {\n const $comments = $('.comment-item');\n $comments.each((ind, comment) => {\n const $comment = $(comment);\n initComment($comment);\n });\n }", "function formExpand() {\n $leaveComment\n .attr('rows', '2')\n .closest('.create-comment')\n .addClass('focused');\n }", "function expandup( node ) {\n\tvar classlist = $( node ).attr( \"class\" );\n\tvar i;\n\tvar j;\n\tvar pnode;\n\n\tif( node == \"#commentbox\" ) {\n\t\treturn;\n\t}\n\ti = classlist.indexOf( \"descendent-of-\" );\n\tif( i >= 0 ) {\n\t\tpnode = classlist.substr( i );\n\t\tj = pnode.indexOf ( \" \" );\n\t\tif( j > 0 ) {\n\t\t\tpnode = pnode.substr( 0, j );\n\t\t}\n\t\tpnode = \"#\" + pnode;\n\t\tpnode = pnode.replace( \"descendent-of-\", \"\" );\n\t\texpandup( pnode );\n\t}\n\t$( node ).expand();\n}", "function promoteWithComments(stateName, comments) {\r\n\tif (comments === null) {\r\n\t\ttoolbar.getActiveToolbar().getItem('promote').setEnabled(true);\r\n\t\treturn false;\r\n\t}\r\n\r\n\tvar res = aras\r\n\t\t.getMostTopWindowWithAras(window)\r\n\t\t.aras.promoteEx(item, stateName, comments);\r\n\twhenPromoteFinish(res);\r\n}", "function commentsMobile (ev) {\n var v = require('./comments_events_vars')\n if ($(ev.target).attr('class').indexOf('disagree') !== -1) {\n if (disagreeOpened === false || disagreeOpened === undefined) {\n $(v.commentsMobile[3]).css('display', 'flex')\n $(v.commentsMobile[4]).css('display', 'block')\n $(v.commentsMobile[5]).css('display', 'flex')\n disagreeOpened = true\n } else {\n $(v.commentsMobile[3]).css('display', 'none')\n $(v.commentsMobile[4]).css('display', 'none')\n $(v.commentsMobile[5]).css('display', 'none')\n disagreeOpened = false\n }\n } else {\n if (agreeOpened === false || agreeOpened === undefined) {\n $(v.commentsMobile[0]).css('display', 'flex')\n $(v.commentsMobile[1]).css('display', 'block')\n $(v.commentsMobile[2]).css('display', 'flex')\n agreeOpened = true\n } else {\n $(v.commentsMobile[0]).css('display', 'none')\n $(v.commentsMobile[1]).css('display', 'none')\n $(v.commentsMobile[2]).css('display', 'none')\n agreeOpened = false\n }\n }\n}", "function unfoldComment (comment, scrollTarget) {\n //If we've already loaded\n if (comment.comments) {\n comment.element.parentElement.insertBefore(createCommentTextbox(comment.id), comment.element.nextSibling)\n for (var i = comment.comments.length-1; i >= 0; i--) {\n comment.element.parentElement.insertBefore(displayComment(comment.comments[i]), comment.element.nextSibling);\n }\n comment.unfolded = true;\n var el = comment.element.getElementsByClassName(\"show-hide-comments\")[0];\n el.innerText = el.innerText.replace(/^Show/, \"Hide\");\n }else {\n var req = new XMLHttpRequest();\n req.open(\"GET\", \"/api/program/\" + programData.id + \"/comment/\" + comment.id + \"/comments\");\n req.addEventListener(\"load\", function () {\n var data = JSON.parse(this.response);\n if (data && data.success) {\n comment.comments = data.comments;\n comment.replyCount = data.comments.length; //Reset local value to the correct number\n var el = comment.element.getElementsByClassName(\"show-hide-comments\")[0];\n el.innerText = el.innerText.replace(/\\(\\d+\\)/, \"(\" + comment.replyCount + \")\")\n\n unfoldComment(comment);\n\n if (scrollTarget) {\n var scrollComment = document.getElementById(scrollTarget);\n jumpToComment(scrollComment);\n }\n }\n });\n req.send();\n }\n}", "function resetCommentForm(commentForm)\n{\n commentForm.addClass('collapsed');\n var commentField = commentForm.find('textarea');\n commentField.val(commentField.attr('title'));\n}", "function ShowAccordion() {\n // Hide other commands\n if (dojo.coords(\"divAppContainer\").h > 0) {\n dojo.replaceClass(\"divAppContainer\", \"hideContainerHeight\", \"showContainerHeight\");\n dojo.byId('divAppContainer').style.height = '0px';\n }\n if (dojo.coords(\"divLayerContainer\").h > 0) {\n dojo.replaceClass(\"divLayerContainer\", \"hideContainerHeight\", \"showContainerHeight\");\n dojo.byId('divLayerContainer').style.height = '0px';\n dojo.byId('txtAddress').blur();\n }\n if (dojo.coords(\"divAddressContent\").h > 0) {\n dojo.replaceClass(\"divAddressContent\", \"hideContainerHeight\", \"showContainerHeight\");\n dojo.byId('divAddressContent').style.height = '0px';\n }\n\n // Toggle express\n if(dojo.hasClass(\"divExpress\", \"showContainerHeight\")) {\n // Visible now, so switch to hidden class\n dojo.replaceClass(\"divExpress\", \"hideContainerHeight\", \"showContainerHeight\");\n } else if(dojo.hasClass(\"divExpress\", \"hideContainerHeight\")) {\n // Hidden now, so switch to visible class\n dojo.replaceClass(\"divExpress\", \"showContainerHeight\", \"hideContainerHeight\");\n }\n\n // Toggle accordion\n if(dojo.hasClass(\"divAccordion\", \"showContainerHeight\")) {\n // Visible now, so switch to hidden class\n dojo.replaceClass(\"divAccordion\", \"hideContainerHeight\", \"showContainerHeight\");\n } else if(dojo.hasClass(\"divAccordion\", \"hideContainerHeight\")) {\n // Hidden now, so switch to visible class\n dojo.replaceClass(\"divAccordion\", \"showContainerHeight\", \"hideContainerHeight\");\n }\n}", "function comments (state={},action){\n switch(action.type) {\n case GET_COMMENTS :\n return {\n ...state,\n commentsId:action.comments,\n }\n case FILTER_COMMENTS:\n return {\n ...state,\n filter:action.filter,\n }\n case EDIT_COMMENTS:\n return {\n ...state,\n commentId:action.comment,\n edit:true\n }\n case UPDATE_COMMENTS:\n return {\n ...state,\n edit:false\n }\n default:\n return state\n }\n}", "function GenerateComment(i, j) {\n var Width = GetLayerWidth(Semtree_TreeDivId);\n var Height = GetLayerHeight(Semtree_TreeDivId);\n var x = Width / 2;\n var y = Height / 2;\n var Scale = (Width + Height) / 4;\n var X;\n var Y;\n var Html = \"\";\n var SemTree = SemTree_SemTreeData;\n Html += '<a href=\"javascript:GenerateComment(-1,-1)\"><div align=right class=\"SemTree_CommentWindow_Close\">[X]&nbsp;Close</div></a>';\n if ((i < 0) && (j < 0)) {\n Html += \"Click on any word in the graph.\"\n document.getElementById(Semtree_CommentDivId).style.display = \"None\";\n }\n else if ((i >= 0) && (j < 0)) {\n X = (SemTree[i].x - XOffset) * Zoom * Scale + x;\n Y = Height - ((SemTree[i].y - YOffset) * Zoom * Scale + y);\n var k;\n var List = \"\";\n Html += '<h2 class=\"SemTree_CommentWindow_Title\">You clicked on the word \"<b>' + SemTree[i].label + '</b>\".</h2>';\n Html += '<ul>';\n Html += '<li>This is one of the keyword that defines the content of your website<br>(other examples of those important words are: ';\n for (k = 0; k < SemtreeLength(SemTree); k++) {\n if (k != i) {\n if (List != '') {\n List += ', ';\n }\n List += SemTree[k].label;\n }\n }\n Html += '\"' + List + '\").<br>';\n Html += 'This word is likely one that you\\'d like to be SEO optimised.<br>';\n Html += 'If this is the case, here is a link explaining <a href=\"javascript:alert(\\'Not yet !\\')\">how to optimise \"' + SemTree[i].label + '\" on your website</a>.';\n Html += '<li>Sentences containing \"' + SemTree[i].label + '\" also often contain the following words:<br>';\n Html += '<small><ul>';\n for (k = 0; k < SemsubtreeLength(SemTree, i); k++) {\n Html += '<li>' + SemTree[i].subnodes[k].label;\n }\n Html += '</ul></small>';\n Html += 'Combinations such as \"' + SemTree[i].label + ' ' + SemTree[i].subnodes[0].label + '\", ';\n Html += '\"' + SemTree[i].label + ' ' + SemTree[i].subnodes[1].label + '\", ';\n Html += '\"' + SemTree[i].label + ' ' + SemTree[i].subnodes[2].label + '\",... ';\n Html += 'are also good candidates for SEO.';\n Html += '<li>Here are the pages where \"' + SemTree[i].label + '\" appears most:';\n Html += '<small><ul>';\n for (k = 0; k < SemTree[i].urls.length; k++) {\n Html += '<li>Appears ' + SemTree[i].urls[k].count + ' times on <a href=\"' + SemTree[i].urls[k].url + '\" target=_blank>' + SemTree[i].urls[k].url + '</a>';\n }\n Html += '</ul></small>';\n Html += '<li>If \"' + SemTree[i].label + '\" seems odd as representative of your content, you may have ';\n Html += 'an issue with the way your content is written and how it appears to others.<br>';\n Html += 'This link will <a href=\"javascript:alert(\\'Not yet !\\')\">give you advices on how to write content on your site</a>.';\n document.getElementById(Semtree_CommentDivId).style.display = \"\";\n }\n else {\n X = (SemTree[i].subnodes[j].x - XOffset) * Zoom * Scale + x;\n Y = Height - ((SemTree[i].subnodes[j].y - YOffset) * Zoom * Scale + y);\n Html += '<h2 class=\"SemTree_CommentWindow_Title\">You clicked on the word \"<b>' + SemTree[i].subnodes[j].label + '</b>\".</h2>';\n Html += '<ul>';\n Html += '<li>This word is often found in the neighborhood of \"' + SemTree[i].label + '\".';\n List = \"\";\n for (k = 0; k < SemtreeLength(SemTree); k++) {\n if (k != i) {\n var kk;\n for (kk = 0; kk < SemsubtreeLength(SemTree, k); kk++) {\n if (SemTree[i].subnodes[j].label == SemTree[k].subnodes[kk].label) {\n if (List != \"\") {\n List += \", \";\n }\n List += '\"' + SemTree[k].label + '\"';\n }\n }\n }\n }\n if (List != \"\") {\n Html += \"<li>It is also found in the neighborhood of \" + List + \".\";\n }\n Html += '<ul>';\n document.getElementById(Semtree_CommentDivId).style.display = \"\";\n }\n document.getElementById(Semtree_CommentDivId).innerHTML = Html;\n document.getElementById(Semtree_CommentDivId).style.left = X + \"px\";\n document.getElementById(Semtree_CommentDivId).style.top = Y + \"px\";\n}", "function layerList_ExpandAll(expand) {\n //alert(layerListWidget.operationalItems.items[0].children.items[10].visible);\n var ctSpans = document.getElementsByClassName(\"esri-layer-list__child-toggle\");\n if (ctSpans.length > 0) {\n for (var i = 0; i < ctSpans.length; i++)\n if (ctSpans[i].hasOwnProperty(\"data-item\")) {\n if (ctSpans[i][\"data-item\"].open) // If root node already expanded, assume the rest is also expanded, and exit function\n return;\n ctSpans[i][\"data-item\"].open = expand;\n }\n }\n }", "function setUpCommentTextBoxControls() {\n\n //Updates the current length of the comment on the max length label. Horizontal area.\n $('#horizontal-comment-expanded-container').on('keyup', 'textarea', function () {\n var textLabel = $('#horizontal-comment-expanded-container label');\n var textBox = $('#horizontal-comment-expanded-container textarea');\n textLabel.text(textBox.val().length + '/ 320');\n if (textBox.val().length > 320) {\n textLabel.css('color', 'red');\n }\n else {\n textLabel.css('color', 'white');\n }\n });\n\n //Updates the current length of the comment on the max length label. Vertical area.\n $('#vertical-comment-expanded-container').on('keyup', 'textarea', function () {\n var textLabel = $('#vertical-comment-expanded-container label');\n var textBox = $('#vertical-comment-expanded-container textarea');\n textLabel.text(textBox.val().length + '/ 320');\n if (textBox.val().length > 320) {\n textLabel.css('color', 'red');\n }\n else {\n textLabel.css('color', 'white');\n }\n });\n\n //Expands the horizontal expandable controls when you click inside the Photo comments textbox.\n $('#horizontal-comment-expandable-control').click(function () {\n if (isAuthed) {\n $('#horizontal-comment-expanded-container label').text('0/320');\n $('#horizontal-comment-expandable-container').hide();\n $('#horizontal-comment-expanded-container').css('display', 'flex');\n $('#horizontal-comment-expanded-container textarea').addClass('horizontal-textarea-expanded');\n window.setTimeout(function () {\n $('#horizontal-comment-expanded-container textarea').focus();\n }, 200);\n\n window.setTimeout(function () {\n $(document).on('click', retractHorizontalCommentsControls);\n }, 200);\n }\n //Warns the user that you need to be authenticated in order to place a comment.\n else {\n var paginator = $('#horizontal-details-error-text');\n paginator.text('You need to be logged in to be able to post comments.');\n paginator.showV();\n }\n });\n\n //Expands the vertical expandable controls when you click inside the Photo comments textbox.\n $('#vertical-comment-expandable-control').click(function () {\n if (isAuthed) {\n $('#vertical-comment-expanded-container label').text('0/320');\n $('#vertical-comment-expandable-container').hide();\n $('#vertical-comment-expanded-container').css('display', 'flex');\n setTimeout(function () {\n $('#vertical-comment-expanded-container textarea').addClass('vertical-textarea-expanded');\n $('#vertical-comment-expanded-container textarea').focus();\n }, 200);\n setTimeout(function () {\n $(document).on('click', retractVerticalCommentsControls);\n }, 200);\n }\n //Warns the user that you need to be authenticated in order to place a comment.\n else {\n var paginator = $('#vertical-details-error-text');\n paginator.text('You need to be logged in to be able to post comments.');\n paginator.showV();\n }\n });\n}", "static RemoveExceedComment()\r\n {\r\n const Max = Settings.MaxDisplayComment;\r\n if( Max > 0 )\r\n {\r\n while( $('#CommentArea #Body .Row').length > Max )\r\n {\r\n $('#ViewCommentArea #Body .Row:first-child').remove(); \r\n }\r\n }\r\n }", "init() {\n set(this, 'isEditing', false);\n this._prefetchMentions(get(this, 'comment'));\n return this._super(...arguments);\n }", "async function renderComments(postId) {\n const comments = await get(`http://5c332abce0948000147a7749.mockapi.io/api/v1/posts/${postId}/comments`);\n if (comments.length) {\n sortByDate(comments);\n\n let n = comments.length - 1;\n // if more than 4 comments, adds expand button\n if (comments.length > 4) {\n const commentsHtml = $(`#p${postId} .comments`);\n commentsHtml.append('<div class=\"more-comments\">Load more comments</div>');\n n = 3;\n }\n\n for (let i = n; i >= 0; i--)\n appendComment(postId, comments[i].username, comments[i].text);\n }\n}", "function updateComments(){\n var html = \"\";\n var comments = photoData[currentPhotoID]['comments'];\n for(var i = 0; i < comments.length; i++){\n var line = \"<p><strong>\" + comments[i][0] + \"</strong>: \" + comments[i][1] + \"</p>\\n\";\n html += line;\n }\n $(galleryCommentsID).html(html);\n}", "function updateComments(id){\n\n // Show comments box\n $('#msgb-comments').show();\n\n // only load comments if a topic is picked\n if($.qs[\"mbt\"] !== undefined){\n p = {\"method\":\"updateComments\",\"params\":{\"topic_id\":$.qs[\"mbt\"],\"comment_id\":id}};\n $.post('api.php',p,function(v){ fillComments(v) }); // ajax and call fill\n }\n\n // Insert comments from API into DOM\n function fillComments(o){\n console.log(\"Filling comments:\");\n _.each(o,function(o,i){\n console.log(o);\n $T = $('#msgb-comment-template').clone().removeAttr(\"id\").attr(\"data-id\", o.id);\n $T.find('.msgb-comment-body').html(o.content);\n $T.find('.msgb-comment-header').html(\"Bryan Potts,<time \");\n $('#msgb-comments').append($T);\n });\n $('.msgb-delete-comment').on(\"click\", function(){ deleteComment($(this).parent().parent(\".msgb-comment\")) });\n }\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Clears the memory property
clearMem() { this.memory = undefined; }
[ "_clearMemory() {\n for (let i = 0; i < this._memory.length; i++) {\n this._memory[i] = 0;\n }\n }", "function clearMemory(){ memory = [] }", "clear(){\n this.buffer.length = 0;\n this.count = 0;\n }", "function clear() {\n resetStore();\n }", "function propertyNull() {\n\t delete this[name];\n\t }", "clear() {\n this._storage.clear();\n this._allDependenciesChanged();\n this._updateLength();\n }", "clear() {\n if (this.props.vars) {\n clearCustomVars(this, this.props.vars);\n }\n this.props.vars = {};\n }", "clearVariables()\n {\n this._variables.clear();\n }", "clearAllObject() {\r\n this.m_drawToolList.length = 0;\r\n this.clearTechToolMousePos();\r\n }", "detach() {\n this.surface = null;\n this.dom = null;\n }", "function clear() {\n clearCalculation();\n clearEntry();\n resetVariables();\n operation = null;\n }", "Clear()\n {\n this._loadedObjects = {};\n }", "reset() {\n this.#length = 0;\n }", "function clearScreen(){ displayVal.textContent = null}", "free() {\n for (let name in Memory.creeps) {\n if (Game.creeps[name] === undefined) {\n delete Memory.creeps[name];\n }\n }\n }", "reset(){\n this._input = null;\n this._output = null;\n }", "clear()\n {\n this.clearVariables();\n this.clearTerminals();\n this.clearRules();\n this._startVariable = null;\n this._errors.length = 0;\n }", "function clear() {\n\t\tgenerations = [];\n\t\tfittest = [];\n\t}", "purge(){\n this.airports = [];\n this.airportsMap.clear();\n }", "function clearAddress() {\n address = [];\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
draws in the images
function drawImages(){ image(handSanatizer, handSanatizerX, handSanatizerY, imageSizes, imageSizes); image(mask, maskX, maskY, imageSizes, imageSizes); image(broom, broomX, broomY, imageSizes, imageSizes); image(washingHands, washingHandsX, washingHandsY, imageSizes ,imageSizes); }
[ "function draw() {\n\n for (var i = 0; i < document.images.length; i++) {\n if (document.images[i].getAttribute('id') != 'frame') {\n canvas = document.createElement('canvas');\n canvas.className = \"canvas-room-basic\"\n canvas.setAttribute('width', 400);\n canvas.setAttribute('height', 300);\n\n document.images[i].parentNode.insertBefore(canvas,document.images[i]);\n\n ctx = canvas.getContext('2d');\n\n ctx.drawImage(document.images[i], 35, 37, 325, 225);\n ctx.drawImage(document.getElementById('frame'), 0, 0, 400, 300);\n }\n }\n}", "display()\r\n {\r\n image(this.image,this.x, this.y, this.w,this.h);\r\n }", "function _drawImages(image,nbLignes,nbColonnes) {\n \n $(\"canvas\").each( function() {\n \n /* extraire l'id du canvas */\n var id = $(this).attr(\"id\"); \n \n var position = extractPositionFromId(id,\"canvas\");\n var i = position[\"i\"];\n var j = position[\"j\"];\n var context = $(this)[0].getContext(\"2d\")\n \n /* si ce n'est pas la dernière case en bas en à droite, alors dessiner les sous-images dans les canvas */\n if( i != nbLignes-1 || j != nbColonnes-1) \n \n _draw(context,i,j,image);\n\n else {\n \n context.fillStyle = \"gray\";\n context.fillRect(0,0,this.width,this.height);\n }\n \n \n });\n}", "draw() {\n push();\n translate(GSIZE / 2, GSIZE / 2);\n // Ordered drawing allows for the disks to appear to fall behind the grid borders\n this.el_list.forEach(cell => cell.drawDisk());\n this.el_list.forEach(cell => cell.drawBorder());\n this.el_list.filter(cell => cell.highlight)\n .forEach(cell => cell.drawHighlight());\n pop();\n }", "function draw() {\n // clear the canvas\n canvas.width = canvas.width;\n drawBlocks();\n drawGrid();\n }", "display() {\n let coin = c.getContext(\"2d\");\n var img = document.createElement(\"IMG\");\n img.src = \"images/Coin20.png\";\n coin.drawImage(img, this.x, this.y, this.width, this.width);\n }", "function drawShapes() {\n\tfor (var i = 0; i < shapes.length; i++) {\n\t\tvar points = shapes[i];\n\t\tdrawFinishedShape(points);\n\t}\n}", "draw() {\n for (const waveform of this.waveforms) {\n this.drawInCanvas(waveform.canvas, waveform.samples);\n }\n }", "function render() {\n\t//clear all canvases for a fresh render\n\tclearScreen();\n\t\n\t//draw objects centered in order\n\tfor (let i = 0; i < objects.length; ++i) {\n\t\tdrawCentered(objects[i].imgName,ctx, objects[i].x, objects[i].y,objects[i].dir);\n\t}\n\t\n\t//finally draw the HUD\n\tdrawHUD();\n}", "function drawShapes()\r\n{\r\n\tvar viewLayers = map.getLayers();\r\n\t\r\n\tif( viewLayers != undefined )\r\n\t{\r\n\t\tviewLayers = viewLayers.getArray();\r\n\t\r\n\t\tvar viewLayer;\r\n\t\tvar mapLayer;\r\n\t\tvar mapShapes;\r\n\t\tvar layerSource;\r\n\t\tvar mapShape;\r\n\t\t\r\n\t\tfor( var i = 0; i < viewLayers.length; i++ )\r\n\t\t{\r\n\t\t\tviewLayer = viewLayers[i];\r\n\t\t\tlayerSource = viewLayer.getSource();\r\n\t\t\tmapLayer = getLayerById( imageMap, viewLayer.id ); \r\n\t\t\t\r\n\t\t\tif( mapLayer != undefined )\r\n\t\t\t{\r\n\t\t\t\tmapShapes = mapLayer.shapes;\r\n\t\t\t\t\r\n\t\t\t\tfor( var j = 0; j < mapShapes.length; j++ )\r\n\t\t\t\t{\r\n\t\t\t\t\tmapShape = mapShapes[j];\r\n\t\t\t\t\tdrawShape( layerSource, mapShape.points, mapShape.id );\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\t\r\n\t}\r\n}", "draw() {\n this.ghosts.forEach((ghost) => ghost.draw());\n }", "draw() {\n\t\tthis.components.forEach( component => component.draw() );\n\t}", "draw() {\n if (this.paused) return;\n \n clear();\n this.quadtree.clear();\n \n // add each blob to quadtree\n this.blobs.forEach(blob => {\n this.quadtree.insert(blob);\n });\n \n // move and draw each blob\n this.blobs.forEach(blob => {\n // what the blob sees\n let saw = blob.see(this.quadtree);\n \n // TODO: turn saw into inputs\n let input = [];\n let output = blob.network.compute(input);\n blob.move(output[0] * TWO_PI, output[1]);\n \n let collidedWith = blob.checkCollision(this.quadtree);\n if (collidedWith) {\n if (collidedWith.size > blob.size) {\n // blob dies\n \n } else {\n // collidedWith dies\n \n }\n }\n \n if (this.dead.length == this.population) {\n this.allDead();\n return;\n }\n \n blob.draw();\n });\n }", "function renderImages() {\n\t\t$('.landing-page').addClass('hidden');\n\t\t$('.img-round').removeClass('hidden');\n\t\tupdateSrcs();\n\t\tcurrentOffset+=100;\n\t}", "function render() {\n\t\t// Clear canvas\n\t\tctx.clearRect(0, 0, canvas.width, canvas.height);\n\n\t\tctx.imageSmoothingEnabled = false;\n\n\t\tctx.fillStyle = \"rgba(255,255,255,1)\";\n\t\tctx.fillRect(offset.x, offset.y, width * pixelSize, height * pixelSize);\n\t\tif (showTransparencyBackground) {\n\t\t\tctx.globalCompositeOperation = 'source-in';\n\t\t\t// Now we can scale our image and display the drawing canvas\n\t\t\tctx.drawImage(transparencyCanvas, 0, 0, canvas.width, canvas.height);\n\t\t\tctx.globalCompositeOperation = 'source-over';\n\n\t\t}\n\n\t\t// Now we can scale our image and display the drawing canvas\n\t\tctx.drawImage(drawCanvas, offset.x, offset.y, width * pixelSize, height * pixelSize);\n\n\t\tif (showGrid && pixelSize > 4) {\n\t\t\tctx.globalCompositeOperation = 'source-atop';\n\t\t\t// Now we can scale our image and display the drawing canvas\n\t\t\tctx.drawImage(gridCanvas, offset.x % pixelSize, offset.y % pixelSize, canvas.width + 2 * pixelSize, canvas.height + 2 * pixelSize);\n\t\t\tctx.globalCompositeOperation = 'source-over';\n\t\t}\n\n\t\t// Draw the scrollbars\n\t\tctx.fillStyle = \"rgba(150,150,150,1)\";\n\t\tvar horizontal = horizontalScrollbarPos();\n\t\tvar vertical = verticalScrollbarPos();\n\t\tctx.fillRect(horizontal[0], horizontal[1], scrollBarWidth, scrollBarHeight); // Horizontal\n\t\tctx.fillRect(vertical[0], vertical[1], scrollBarHeight, scrollBarWidth); // Veritcal\n\n\t\t// Request next animation frame\n\t\twindow.requestAnimationFrame(render);\n\t}", "draw() {\r\n this._ctx.clearRect(0, 0, this._ctx.canvas.width, this._ctx.canvas.height);\r\n this._ctx.save();\r\n for (let i = 0; i < this._entities.length; i++) {\r\n this._entities[i].draw(this._ctx);\r\n }\r\n this._ctx.restore();\r\n }", "function displayEnding() {\n image(endingImages[endingIndex], 0, 0, windowWidth, windowHeight);\n}", "draw(){\n\n for(let i=0; i<this.belt.length;i++){\n this.belt[i].draw();\n }\n }", "function horseImageDraw(horse, image){\n\timage.onload = horse.addHorse(image);\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
`_encodeLiteral` represents a literal
_encodeLiteral(literal) { // Escape special characters let value = literal.value; if (escape.test(value)) value = value.replace(escapeAll, characterReplacer); // Write a language-tagged literal if (literal.language) return `"${value}"@${literal.language}`; // Write dedicated literals per data type if (this._lineMode) { // Only abbreviate strings in N-Triples or N-Quads if (literal.datatype.value === xsd.string) return `"${value}"`; } else { // Use common datatype abbreviations in Turtle or TriG switch (literal.datatype.value) { case xsd.string: return `"${value}"`; case xsd.boolean: if (value === 'true' || value === 'false') return value; break; case xsd.integer: if (/^[+-]?\d+$/.test(value)) return value; break; case xsd.decimal: if (/^[+-]?\d*\.\d+$/.test(value)) return value; break; case xsd.double: if (/^[+-]?(?:\d+\.\d*|\.?\d+)[eE][+-]?\d+$/.test(value)) return value; break; } } // Write a regular datatyped literal return `"${value}"^^${this._encodeIriOrBlank(literal.datatype)}`; }
[ "_encodeLiteral(literal) {\n // Escape special characters\n let value = literal.value;\n if (escape.test(value)) value = value.replace(escapeAll, characterReplacer); // Write a language-tagged literal\n\n if (literal.language) return `\"${value}\"@${literal.language}`; // Write dedicated literals per data type\n\n if (this._lineMode) {\n // Only abbreviate strings in N-Triples or N-Quads\n if (literal.datatype.value === xsd.string) return `\"${value}\"`;\n } else {\n // Use common datatype abbreviations in Turtle or TriG\n switch (literal.datatype.value) {\n case xsd.string:\n return `\"${value}\"`;\n\n case xsd.boolean:\n if (value === 'true' || value === 'false') return value;\n break;\n\n case xsd.integer:\n if (/^[+-]?\\d+$/.test(value)) return value;\n break;\n\n case xsd.decimal:\n if (/^[+-]?\\d*\\.\\d+$/.test(value)) return value;\n break;\n\n case xsd.double:\n if (/^[+-]?(?:\\d+\\.\\d*|\\.?\\d+)[eE][+-]?\\d+$/.test(value)) return value;\n break;\n }\n } // Write a regular datatyped literal\n\n\n return `\"${value}\"^^${this._encodeIriOrBlank(literal.datatype)}`;\n }", "Literal() {\n switch (this._lookahead.type) {\n case \"NUMBER\":\n return this.NumericLiteral();\n case \"STRING\":\n return this.StringLiteral();\n case \"true\":\n case \"false\":\n return this.BooleanLiteral(this._lookahead.type);\n case \"null\":\n return this.NullLiteral();\n }\n throw new SyntaxError(`Literal: unexpected literal production`);\n }", "function isLiteral(node) {\n return node && node.type === typescript_estree_1.AST_NODE_TYPES.TSTypeLiteral;\n }", "_isLiteral(tokenType) {\n return (\n tokenType === \"NUMBER\" ||\n tokenType === \"STRING\" ||\n tokenType === \"true\" ||\n tokenType === \"false\" ||\n tokenType === \"null\"\n );\n }", "function validLiteral(node) {\n if (node && node.type === 'Literal' && typeof node.value === 'string') {\n return true;\n }\n return false;\n}", "encodeSpecials() {\n const value = this.value;\n const regex = /(\\'|\"|\\\\x00|\\\\\\\\(?![\\\\\\\\NGETHLnlr]))/g;\n return value.replace(regex, '\\\\\\\\$0');\n }", "_completeLiteral(token) {\n // Create a simple string literal by default\n let literal = this._literal(this._literalValue);\n\n switch (token.type) {\n // Create a datatyped literal\n case 'type':\n case 'typeIRI':\n const datatype = this._readEntity(token);\n\n if (datatype === undefined) return; // No datatype means an error occurred\n\n literal = this._literal(this._literalValue, datatype);\n token = null;\n break;\n // Create a language-tagged string\n\n case 'langcode':\n literal = this._literal(this._literalValue, token.value);\n token = null;\n break;\n }\n\n return {\n token,\n literal\n };\n }", "_encodeObject(object) {\n switch (object.termType) {\n case 'Quad':\n return this._encodeQuad(object);\n\n case 'Literal':\n return this._encodeLiteral(object);\n\n default:\n return this._encodeIriOrBlank(object);\n }\n }", "function makeLiteralFromSymbol(sym){\n var loc = sym.location, result, kid;\n if([\"true\", \"false\", \"#t\", \"#f\"].indexOf(sym.val) > -1){\n kid = (sym.val===\"true\" || sym.val===\"#t\")?\n {name:\"TRUE\", value:\"true\", key:\"'TRUE:true\", pos: loc}\n : {name:\"FALSE\", value:\"false\", key:\"'FALSE\", pos: loc};\n result = {name:\"bool-expr\", kids:[kid], pos: loc};\n } else {\n kid = {name:\"STRING\", value:'\"'+sym.val+'\"', key:\"'STRING:\\\"\"+sym.val+\"\\\"\", pos:loc};\n result = {name:\"string-expr\", kids:[kid], pos: loc};\n }\n return {name:\"expr\", kids:[{name:\"prim-expr\", kids:[result], pos: loc}], pos: loc};\n }", "enterLiteralConstant(ctx) {\n\t}", "function unicodeLiteral(str)\n{\n var i;\n var result = \"\";\n for( i = 0; i < str.length; ++i) {\n if(str.charCodeAt(i) < 32) {\n result += \"\\\\u\" + fixedHex(str.charCodeAt(i),4);\n } else {\n result += str[i];\n }\n }\n return result;\n}", "function literalToValue(literal) {\n return literal.value;\n}", "enterFunctionLiteral(ctx) {\n\t}", "function encode(text)\n{\n return encodeURIComponent(text);\n}", "function stringFromAnyLiteral(node) {\n if (node.type === 'ObjectProperty') {\n return stringFromAnyLiteral(node.value);\n }\n if (['TemplateLiteral', 'StringLiteral', 'Literal'].includes(get(node, 'type'))) {\n return node.type === 'TemplateLiteral'\n ? get(node, 'quasis[0].value.raw')\n : get(node, 'value', null);\n } else {\n logging.error(\n 'Tried to get string value from a node that is not a Literal, TemplateLiteral or a StringLiteral',\n '\\n\\n',\n get(node, 'init.properties[0].key.name', '')\n );\n }\n}", "function convertValueToEscapedSqlLiteral (value) {\n if (_.isNumber(value)) {\n return value;\n } else if (value === null) {\n return \"NULL\";\n } else if (_.isBoolean(value)) {\n return value ? \"TRUE\" : \"FALSE\";\n } else if (isDateTimeString(value)) {\n return dateTimeStringToSqlValue(value);\n } else {\n return \"'\" + sanitizeSqlString(value).replace(\"'\", \"''\") + \"'\";\n }\n}", "function setLiteral(source, key, rules) {\n const item = (source[key] || { type: 'literal' });\n item.rules = rules;\n source[key] = item;\n return item;\n}", "BooleanLiteral(type) {\n const token = this._eat(type);\n return {\n type: \"BooleanLiteral\",\n value: token.value === \"true\" ? true : false,\n };\n }", "writeStringLiteralType(enumeration, options) {\n if (!enumeration)\n return this;\n if (!options)\n options = {};\n this.writeJsDocDescription(enumeration.ownedComments);\n this.writeIndent();\n if (options.export) {\n this.write(`export `);\n }\n if (options.declare) {\n this.write('declare ');\n }\n this.write(`type ${enumeration.name} = `);\n this.joinWrite(enumeration.ownedLiterals, ' | ', lit => `'${lit.name}'`);\n this.writeEndOfLine(';');\n return this;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create a new unique buoy callback url.
createCallbackUrl() { return `${this.serviceAddress}/${uuid_1.v4()}`; }
[ "function createUrl(username, projectName) {\n return `http://www.github.com/${username}/${projectName}`\n}", "static get rocketWebhookUrl() {\n\t\tlet rocketUrl = RocketChat.settings.get('Site_Url');\n\t\trocketUrl = rocketUrl ? rocketUrl.replace(/\\/?$/, '/') : rocketUrl;\n\t\treturn `${ rocketUrl }api/v1/smarti.result/${ RocketChat.settings.get('Assistify_AI_RocketChat_Webhook_Token') }`;\n\t}", "function createWeatherURL() {\n weatherURL = \"https://api.openweathermap.org/data/2.5/weather?q=\" + city + \",\" + region + \",\" + country + \"&units=imperial&appid=\" + APIKey\n}", "function makeUrl(){\r\n var url = location.origin + location.pathname +\r\n '?cid=' + collectedData.currentComment;\r\n return url;\r\n}", "createURL(baseURL, parameters) { return createURL(baseURL, parameters); }", "function generateURL(id) {\n return `https://picsum.photos/id/${id}/400`;\n }", "function init_url( url ) {\n\treturn api_url + url;\n}", "function OAuth(client_id, cb) {\n Linking.addEventListener('url', handleUrl);\n function handleUrl(event) {\n Linking.removeEventListener('url', handleUrl);\n const [, query_string] = event.url.match(/\\#(.*)/);\n const query = qs.parse(query_string);\n cb(query.access_token);\n}\n \nconst oauthurl = `https://www.fitbit.com/oauth2/authorize?${qs.stringify({\n client_id,\n response_type: 'token',\n scope: 'heartrate activity activity profile sleep',\n redirect_uri:'fitbitTest1://fit', // it should be same as mentioned while registration at Fitbit.\n expires_in: '604800',\n})}`;\nconsole.log(oauthurl);\nLinking.openURL(oauthurl).catch(err => console.error('Error processing linking', err));\n}", "function _buildAuthUrl(){\n return 'https://github.com/login/oauth/authorize?client_id=' \n + github_config.client_id \n + '&scope=repo&redirect_uri=' \n + github_config.callback_url\n }", "function handleGenInstanceURLEvent(err, result) {\n if (err) return displayError(err)\n\n // if the URL was generated successfully, create and append a new element to the HTML containing it.\n let url = getAnchorWithLink(result, \"instance link\");\n\n let textcenter = document.createElement('div');\n textcenter.className = \"text-center\";\n textcenter.id = \"instance_permalink\";\n textcenter.appendChild(url);\n\n $(\"#url-instance-permalink\").empty()\n document.getElementById('url-instance-permalink').appendChild(textcenter);\n $(\"#genInstanceUrl > button\").prop('disabled', true);\n zeroclipboard();\n}", "function uniqueLinkGen(){\n if(linkGenStore.findOne({'shortURL':short_url})===true){//check if short url is present\n short_url = linkGen.genURL();\n uniqueLinkGen();\n }\n else{\n return short_url;\n }\n }", "static async UrlShortener() {\n\n }", "function uniqueIdCallback(id){\n sys.puts('Generated new unique id : ' + id + ' for url ' + req.body.url );\n var options = {\n uri : URL_DB_URL+id,\n method : 'PUT',\n headers : {\n 'content-type' : 'application/json', \n //'Authorization' : 'Basic YWRtaW46cGFzcw==',\n //'Authorization' : b,\n 'Referer' : URL_DB_URL + id, \n },\n body : that.couchdb.toJSON(req.body),\n };\n \n request(options, function(error, response, body){ \n if (error){\n sys.puts(sys.inspect(error));\n res.send(sys.inspect(error));\n }else{\n sys.puts('New doc added : id:' + id + ' url' + req.body.url);\n req.query.urlDoc = body;\n if (!callback) res.send(body); else callback(body);\n }\n }); \n }", "function create_uri(address) {\n var uri = new bitcore.URI({\n address: address,\n // message: get_user_memo(),\n // amount: 10000\n });\n var uriString = uri.toString();\n // var img = jQuery('#logo')[0];\n // jQuery('#qrcode').qrcode(uriString);\n jQuery('#uri_string').html(address.toString());\n jQuery('#qr_wrapper').html('<a id=\"qr_link\" href=\"' + uriString + '\"></a>');\n // jQuery('#qr_wrapper').html('<div class=\"pop-left\" data-container=\"body\" data-toggle=\"popover\" data-placement=\"left\" data-content=\"<a id=' + \"'qr_link' href=\" + uriString + '\"></a></div>');\n jQuery('#qr_link').qrcode({\n 'size': 150,\n 'ecLevel': 'H',\n 'radius': 0,\n 'top': 0,\n 'minVersion': 8,\n // 'fill': '#000',\n // 'color': '#FAF',\n 'text': uriString,\n //'background': '#FFF',\n // 'mode': 4,\n // 'mSize': 0.05,\n // 'image': img\n });\n\n\n $('.uri-popover').popover({\n trigger:'hover',\n placement:'right',\n container:'body',\n html:true,\n title: 'URI Code:',\n content:function(){\n return '<a href=\"'+address.toString()+'\">'+address.toString()+'</a>';\n }\n });\n}", "function fancyConfirmURL(url, title, message, buttonName, width) {\n\n function redirect() {\n window.location.href = url;\n }\n\n fancyConfirmCallback(redirect, title, message, buttonName, width);\n return false;\n}", "function url_build () {\n return spawn('python',\n ['./lib/python/change_url.py', 'build'], {stdio: 'inherit'})\n}", "static buildApiUrl(opts) {\n if (!opts.apiKey) {\n return null;\n }\n const urlBase = 'https://maps.googleapis.com/maps/api/js';\n const params = {\n key: opts.apiKey,\n callback: opts.callback,\n libraries: (opts.libraries || ['places']).join(','),\n client: opts.client,\n v: opts.version || '3.27',\n channel: null,\n language: null,\n region: null,\n };\n const urlParams = _.reduce(params, (result, value, key) => {\n if (value) result.push(`${key}=${value}`);\n return result;\n }, []).join('&');\n\n return `${urlBase}?${urlParams}`;\n }", "function createItem(url, name = \"\", note = \"\", price = 0, callback = () => {}) {\n chrome.storage.sync.get(['firebase-auth-uid'], function(result){\n var uid = result['firebase-auth-uid'];\n var wishlistRef = database.ref(\"users/\" + uid + \"/wishlist\");\n var itemsRef = database.ref(\"items/\");\n var newItemRef = itemsRef.push({\n gifter : false,\n name : name,\n note : note,\n price : price,\n requester : uid,\n url : url,\n });\n wishlistRef.child(newItemRef.key).set(true).then(function() {\n callback();\n });\n });\n}", "function createRenderUrl(uuid, script) {\n let url = new URL(`${FLEDGE_BASE_URL}resources/fenced-frame.sub.py`);\n if (script)\n url.searchParams.append('script', script);\n url.searchParams.append('uuid', uuid);\n return url.toString();\n}", "function genGmailLink(numYears) {\n\tvar today,\n\t\tyearAgo,\n\t\tyearAgoOneDay,\n\t\tgmailUrl = 'https://mail.google.com/mail/u/0/#apps/',\n\t\tencodedBeforAfter,\n\t\tbeforeAfter;\n\n\n\t// yearAgo = Date.parse(\"t - 1 y\").toString('yyyy/mm/dd');\n\tyearAgo = Date.today().add(-numYears).years().toString('yyyy/MM/dd');\n\tyearAgoOneDay = Date.today().add( {days: -numYears, years: -numYears}).toString('yyyy/MM/dd');\n\tbeforeAfter = \"after:\" + yearAgoOneDay + \" before:\" + yearAgo;\n\tencodedBeforAfter =\tencodeURIComponent(beforeAfter);\n\treturn gmailUrl + encodedBeforAfter;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
START STATE This is the intro for the game
function displayStart() { introSFX.play(); push(); createCanvas(500, 500); background(0); textAlign(CENTER); textSize(20); textFont(myFont); fill(250); text("to infinity and beyond!", width / 2, 80); text("press X to start your adventure", width / 2, 450); imageMode(CENTER); translate(width / 2, height / 2); translate(p5.Vector.fromAngle(millis() / 1000, 40)); image(playerImage, 5, 5); pop(); // information for the stars in the background push(); translate(width / 2, height / 2); for (var i = 0; i < stars.length; i++) { stars[i].update(); stars[i].display(); } pop(); // To start the game, we only have to press the space bar to access the level one of the game if (keyIsPressed && key === 'x') { state = "INSTRUCTION"; } }
[ "function startGame() {\n removeWelcome();\n questionIndex = 0;\n startTimer();\n generateQuestions();\n}", "startGame() {\r\n this.generateInitialBoard();\r\n this.printBoard();\r\n this.getMoveInput();\r\n }", "function startGame() {\n removeWelcomePage();\n createGamePage();\n createCards();\n}", "function startIntro(){\n\tvar intro = introJs();\n\t\tintro.setOptions({\n\t\t\tsteps: [\n\t\t\t\t{\n\t\t\t\t\tintro: \"Welcome! This webpage will help you explore unemployment data in different areas of Münster.\"\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\telement: '#settingsBox',\n\t\t\t\t\tintro: \"Use this sidebar to customize the data that is displayed on the map.\",\n\t\t\t\t\tposition: 'right'\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\telement: '#yearSection',\n\t\t\t\t\tintro: \"You can move this slider to get data from 2010 to 2014.\",\n\t\t\t\t\tposition: 'right'\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\telement: '#criteriaSection',\n\t\t\t\t\tintro: \"Choose a criterion to select a specific group of unemployed.\",\n\t\t\t\t\tposition: 'right'\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\telement: '#boundarySection',\n\t\t\t\t\tintro: \"You can also switch to districts to get finer granularity.\",\n\t\t\t\t\tposition: 'right'\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\telement: '#legendBox',\n\t\t\t\t\tintro: \"This legend will tell how many unemployed are represented by each color.\",\n\t\t\t\t\tposition: 'right'\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\telement: '#map',\n\t\t\t\t\tintro: \"Check the map to view your selected data! You can also click on all boundaries. A popup will show you a timeline to compare data of recent years and links to additional information.\",\n\t\t\t\t\tposition: 'left'\n\t\t\t\t}\n\t\t\t]\n\t\t});\n\n\t\tintro.start();\n}", "function giveInstructions()\n{\n startScene.visible = false;\n instructionScene.visible = true;\n gameScene.visible = false;\n pauseMenu.visible = false;\n gameOverScene.visible = false;\n screenButtonSound.play();\n}", "function startNewGame(){\n\ttoggleNewGameSettings();\n\tnewGame();\n}", "function StartUp(){\n dispHelp();\n hangmanGame.newGameWord();\n askForPlayer();\n}", "function startIntro(){\n var intro = introJs();\n intro.setOptions({\n steps: [\n { \n intro: \"Hello world!\"\n },\n {\n element: document.querySelector('.cont'),\n intro: \"This is a tooltip.\"\n },\n // {\n // element: document.querySelectorAll('#step2')[0],\n // intro: \"Ok, wasn't that fun?\",\n // position: 'right'\n // },\n {\n element: '.cont2',\n intro: 'More features, more fun.',\n position: 'left'\n },\n // {\n // element: '#step4',\n // intro: \"Another step.\",\n // position: 'bottom'\n // }\n ]\n });\n intro.start();\n }", "function startTutorial() {\n\t// May or may not be necessary\n\tgameType = 'tutorial';\n\tstartGame();\n\ttutorialInstructionIndex = -1;\n\tcallbackAfterMessage = nextTutorialMessage;\n\tnextTutorialMessage();\n}", "function gameStart() {\n let random = Math.random();\n if (random > 0.5) {\n playerTurn = true;\n playerMessage.text('Your Turn');\n } else {\n playerTurn = false;\n loader.show();\n computerAction();\n }\n}", "start() {\n \n //Start the game loop\n this.gameLoop();\n }", "function intro() {\n background(0,0,50);\n\n textFont('Helvetica');\n textSize(18);\n textAlign(CENTER, CENTER);\n fill(255);\n noStroke();\n text('[ click anywhere to start animation ]', width/2,height/2);\n}", "function startGame() {\n getDifficulty();\n startTimer();\n addCards();\n $(\"refresh\").addEventListener(\"click\", addCards);\n toggleGame();\n currSetCount = 0;\n $(\"set-count\").innerHTML = currSetCount;\n deselectAll();\n }", "function drawIntro(){\n\t\n}", "function tourButtonClick() {\n\tstartButtonClick();\n\tstartIntro();\n}", "function playLevel1() {\n ga('send', 'event', 'Jeu', 'Niveau 1', 'Début');\n //console.log('Jeu - Niveau 1 - Début');\n\n /**\n * Prepare information if the board is resolved.\n */\n informationBoardIsResolved = {\n category: \"Jeu\",\n action: \"Niveau 1\",\n timeLabel: \"playMinSceneActiveTime\",\n }\n\n // Activate the timer.\n $(document).trigger('startTime', currentGame.scenes.play_min_scene.scene);\n\n $(\"body\").closeAllDialogs(function() {\n\n // Active input for play_min_scene\n currentGame.iaPlay = true;\n currentGame.scenes.play_min_scene.scene.setPaused(false);\n currentGame.playMinSceneActive = true;\n });\n }", "function setStartScreen() {\n score = 0;\n showScreen('start-screen');\n document.getElementById('start-btns').addEventListener('click', function (event) {\n if (!event.target.className.includes('btn')) return; //makes sure event is only fired if a button is clicked\n let button = event.target; //sets button to the element that fired the event\n let gameType = button.getAttribute('data-type');\n setGameScreen(gameType);\n });\n }", "function runIntro(frame){\n if (paused) {return;}\n console.log(introCount);\n //Display the cards\n document.getElementById('expression').innerHTML = '<span class=\"intro\">' + introTexts[introCount] + '</span>';\n stop = Date.now();\n checkHands(frame);\n\n // If we are on the last page of the slide\n if (introCount == (introTexts.length - 1)){\n if ((confidence > .8) && (extendedFingers < 6) && (extendedFingers > 0) && ((stop-start) > 2000)){\n difficulty = extendedFingers;\n console.log('woooo!!!!');\n inIntro = false;\n return;\n }\n inIntro = true;\n } else\n\n // If the user wants to skip to the end;\n if ((confidence > .6) && (extendedFingers == 10)){\n introCount = (introTexts.length - 1);\n expression = introTexts[introCount];\n cardChange(expression, 0, true);\n inIntro = true;\n } else\n\n // If the user wants to move to the next page\n if ((confidence > .6) && (extendedFingers == (introCount+1))){\n introCount++;\n expression = introTexts[introCount];\n cardChange(expression, 0, true);\n if (introCount == 3){\n start = Date.now();\n }\n inIntro = true;\n } else {\n inIntro = true;\n }\n }", "startGame() {\n let self = this\n this.props.changeSetupConfigClass(\"setupconfig__holder setupconfig__holder__deactive\")\n setTimeout(()=>{\n self.props.changeResetCoords(true)\n self.props.changeMarkerCoords([0,0])\n self.props.changeResetCoords(false)\n self.props.changeActiveHandler(this.props.game.id, false, true)\n self.props.changeActiveState(this.props.game.id, true)\n }, 1600)\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
['red', 'green', 'yellow', 'black'] Issue: Arguments cannot be passed to the supertype. / Constructor Stealing To solve prototype inheritance call the supertype constructor within the subtype constructor. Arguments can now be passed to supertype.
function SuperType(name) { this.colors = ['red', 'green']; this.name = name; }
[ "function inheritPrototype(subType, superType) {\n var prototype = object(superType.prototype); //this is a function defined eariler in this document\n //or use the following:\n //var prototype = Object.create(superType.prototype); //ECMAScript 5\n \n prototype.constructor = subType;\n subType.prototype = prototype;\n}", "constructor(animals=[], plants=[], randomObjects=[]) {\n this.animals = animals;\n this.plants = plants;\n this.randomObjects = randomObjects;\n }", "constructor(name, weight, eyeColor){\n//Assigns it to this instance\n// this is the object that is instantiated (created) \nthis.name = name //assigns value to this specific instance of a gorilla\nthis.weight = weight\nthis.isAlive = true // a default can also be set\nthis.eyeColor = eyeColor\nthis.bananasEaten = 0\nconsole.log(('you built a gorilla'));\n\n}", "function task2 () {\n function Animal() {}\n\n function Rabbit() {}\n Rabbit.prototype = Object.create(Animal.prototype);\n\n var rabbit = new Rabbit();\n\n console.log( rabbit instanceof Rabbit ); //true\n console.log( rabbit instanceof Animal ); //true\n console.log( rabbit instanceof Object ); //true\n}", "constructor (size) {\n /* Constructor function to create new instance of Square through Rectangle attributes and methods */\n super(size, size);\n }", "constructor(height: number, width: number) {\r\n super(height, width);\r\n // now we can use \"this\"\r\n }", "function ColorType()\n{\t\t\t\t\n}", "constructor(pairs) {\n super(pairs, \"Plugboard\");\n }", "function Dog(name, color) {\n this.name = name;\n this.color = color;\n this.numLegs = 4; \n}", "constructor({origin, size} /*: $Shape<UI$Rect> */ ) {\n this.origin = new Point({...origin});\n this.size = new Size({...size});\n }", "function ClassB(primerNombre, asunto){\r\n // LLamamos al constructor de la superclase\r\n ClassA.call(this, primerNombre);\r\n // Inicializamos las propiedades específicas de la subclase\r\n this.asunto=asunto;\r\n}", "createClothes(options = {}) {\n // for(var prop in superProps) {\n // if (!options.hasOwnProperty(prop)) {\n // options[prop] = superProps[prop];\n // }\n // } \n options.clothesType = options.clothesType.toLowerCase()\n switch (options.clothesType) {\n case 'shoe':\n this.clothesClass = Shoe;\n break;\n case 'jacket':\n this.clothesClass = Jacket;\n break;\n case 'hat':\n this.clothesClass = Hat;\n break;\n default:\n }\n\n return new this.clothesClass(options);\n }", "function inheritFrom(parentConstructor, prototypeProps, constructorProps) {\n // Get or create a child constructor\n var childConstructor\n if (prototypeProps && object.hasOwn(prototypeProps, 'constructor')) {\n childConstructor = prototypeProps.constructor\n }\n else {\n childConstructor = function() {\n parentConstructor.apply(this, arguments)\n }\n }\n\n // Base constructors should only have the properties they're defined with\n if (parentConstructor !== Concur) {\n // Inherit the parent's prototype\n object.inherits(childConstructor, parentConstructor)\n childConstructor.__super__ = parentConstructor.prototype\n }\n\n // Add prototype properties, if given\n if (prototypeProps) {\n object.extend(childConstructor.prototype, prototypeProps)\n }\n\n // Add constructor properties, if given\n if (constructorProps) {\n object.extend(childConstructor, constructorProps)\n }\n\n return childConstructor\n}", "legalArguments(args, params) {\n doCheck(\n args.length === params.length,\n `Expected ${params.length} args in call, got ${args.length}`\n );\n args.forEach((arg, i) => this.isAssignableTo(arg, params[i].type));\n }", "constructor(actual /*: mixed*/, expect /*: mixed*/) {\n super()\n this.actual = actual\n this.expect = expect\n }", "function Sprite_Damage() {\n this.initialize.apply(this, arguments);\n}", "function getNewCreature() {\n let newCreature = null;\n\n let randNum = int(random(0, 6));\n if (randNum < 2) {\n\n //shades of blue color array\n let colors = [\"darkCyan\", \"darkSlateBlue\", \"lightSteelBlue\", \"midnightBlue\", \"royalBlue\", \"steelBlue\"];\n let index = floor(random(colors.length));\n let color = colors[index];\n\n newCreature = new Spike(color); //instance of Triangle class\n }\n else if (randNum < 3) {\n //offwhite colors\n let colors = [\"aliceBlue\", \"azure\", \"cornsilk\", \"floralWhite\", \"honeyDew\", \"ivory\"];\n let index = floor(random(colors.length));\n let color = colors[index];\n newCreature = new Butterfly(color); //instance of Butterfly class\n }\n else if (randNum < 5) {\n //shades of pink/purple\n let colors = [\"paleVioletRed\", \"pink\", \"plum\", \"rosyBrown\", \"salmon\", \"thistle\"];\n let index = floor(random(colors.length));\n let color = colors[index];\n newCreature = new Orb(color); //instance of Orb class\n }\n else {\n //shades of green color array\n let colors = [\"forestGreen\", \"green\", \"greenYellow\", \"lawnGreen\", \"lightGreen\", \"lime\"];\n let index = floor(random(colors.length));\n let color = colors[index];\n\n newCreature = new Creature(color); //instance of Creature class\n }\n return newCreature;\n}", "function Price(color, make, model, price){\n // this is how I can inherit the properties of Car\n Car.call(this,color, make, model)\n\n this.price = price\n // return `car color ${this.color}, model ${this.model}, maker ${this.make} and price is $${price}`\n}", "custom (mode, speed, ...colors) {\n let ary = [0x99]\n for (var idx = 0; idx < 16; idx++) {\n if (idx < colors.length) {\n ary = ary.concat(colors[idx])\n } else {\n ary = ary.concat([1, 2, 3])\n }\n }\n ary = ary.concat(speed)\n ary = ary.concat(mode + 0x39)\n ary = ary.concat([0xff, 0x66])\n console.log(ary)\n this._sendMessage(ary)\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create the cursor keys
function createKeys() { cursors = this.input.keyboard.createCursorKeys(); }
[ "function createCursors(players) {\n\t\tfor (var key in players) {\n\t\t\tcreateCursor(players[key]);\n\t\t}\n\t}", "generateKeys(octaves, startOctave = 1) {\n\t\tlet tmpKeyboard = ``;\n\t\tfor (let octave = 0 ; octave < octaves; octave++) {\n\t\t\tlet tmpKeys = ``;\n\n\t\t\tthis.constructor.notes.forEach((note, index) => {\n\t\t\t\tlet keyClass = this.constructor.whiteKeyIndexes.includes(index) ? 'white' : 'black';\n\t\t\t\ttmpKeys += `<div class=\"key ${keyClass}\" data-octave=\"${octave + startOctave}\" data-note=\"${this.constructor.notes[index]}\"></div>`;\n\t\t\t});\n\n\t\t\ttmpKeyboard += `<div class=\"octave\" data-octave=\"${octave + startOctave}\">${tmpKeys}</div>`\n\t\t}\n\n\t\treturn tmpKeyboard;\n\t}", "function Keymap(){\r\n this.map = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q',\r\n 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'backspace', 'enter', 'shift', 'delete'];\r\n }", "_setDefault(){\n this.defaultCursor = \"default\";\n // this.hOverCursor = \"pointer\";\n }", "addShortcut(keys, callback) {\n Mousetrap.bind(keys, callback)\n }", "setKeyStateOrder() {\n this.keyStates = [this.KEY_LEFT, this.KEY_UP, this.KEY_RIGHT, this.KEY_DOWN]\n }", "static bulkCtrlKey(selectors) {\n return bulkOfClicks(Action.ctrlClick, selectors);\n }", "createCursor() {\n var cursor = document.createElement( 'div' );\n cursor.classList.add( 'cursor' );\n cursor.style.height = this.lineHeight + 'px';\n this.overlay.appendChild( cursor );\n\n return cursor;\n }", "function generateKey() {\n if (!isOwnKey) {\n let $field = $('#space-title');\n let key = \"\";\n if ($field.val().includes(\" \")) {\n let parts = $field.val().split(\" \");\n parts.forEach(function (entry) {\n if (entry.length > 0 && entry[0].match(/[A-Za-z0-9äöüÄÖÜ]/)) key += entry[0].toUpperCase()\n })\n } else {\n for (let i = 0; i < $field.val().length; i++)\n if ($field.val()[i].match(/[A-Za-z0-9äöüÄÖÜ]/)) key += $field.val()[i].toUpperCase()\n };\n $('#space-key').val(key.replace(\"Ä\", \"A\").replace(\"Ö\", \"O\").replace(\"Ü\", \"U\"))\n }\n }", "function iglooKeys () {\n\tthis.mode = 'default';\n\tthis.keys = ['default', 'search', 'settings'];\n\tthis.cbs = {\n\t\t'default': {},\n\t\t'search': {\n\t\t\tnoDefault: true\n\t\t},\n\t\t'settings': {}\n\t};\n\n\t//This registers a new keybinding for use in igloo\n\t//And then executes the function under the right circumstances\n\tthis.register = function (combo, mode, func) {\n\t\tvar me = this;\n\t\tif ($.inArray(mode, this.keys) !== -1 && iglooUserSettings.useKeys === true) {\n\t\t\tthis.cbs[mode][combo] = func;\n\n\t\t\tMousetrap.bind(combo, function(e, input) {\n\t\t\t\tif (!me.cbs[igloo.piano.mode].noDefault || input === 'f5') {\n\t\t\t\t\tif (e.preventDefault) {\n\t\t\t\t\t\te.preventDefault();\n\t\t\t\t\t} else {\n\t\t\t\t\t\t// internet explorer\n\t\t\t\t\t\te.returnValue = false;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tme.cbs[igloo.piano.mode][input]();\n\t\t\t});\n\t\t\treturn true;\n\t\t} else {\n\t\t\treturn false;\n\t\t}\n\t};\n}", "function emitKeySequence(keys) {\r\n var i;\r\n for (i = 0; i < keys.length; i++)\r\n emitKey(keys[i], 1);\r\n for (i = keys.length - 1; i >= 0; i--)\r\n emitKey(keys[i], 0);\r\n}", "function crosshairCursor(options = {}) {\n let [code, getter] = keys[options.key || 'Alt']\n let plugin = dist_ViewPlugin.fromClass(\n class {\n constructor(view) {\n this.view = view\n this.isDown = false\n }\n set(isDown) {\n if (this.isDown != isDown) {\n this.isDown = isDown\n this.view.update([])\n }\n }\n },\n {\n eventHandlers: {\n keydown(e) {\n this.set(e.keyCode == code || getter(e))\n },\n keyup(e) {\n if (e.keyCode == code || !getter(e)) this.set(false)\n },\n mousemove(e) {\n this.set(getter(e))\n }\n }\n }\n )\n return [\n plugin,\n EditorView.contentAttributes.of((view) => {\n var _a\n return (\n (_a = view.plugin(plugin)) === null || _a === void 0\n ? void 0\n : _a.isDown\n )\n ? showCrosshair\n : null\n })\n ]\n }", "function Keymap(keys, options) {\n\t this.options = options || {}\n\t this.bindings = Object.create(null)\n\t if (keys) this.addBindings(keys)\n\t }", "buildCursor(props) {\n let cursorCameraControls = `movement-controls=\"controls: checkpoint\"`;\n let cursor = ``;\n\n if (props.cursorCamera === true) {\n // Add camera cursor\n // cursorCameraControls = `look-controls movement-controls=\"controls: checkpoint\"`;\n cursorCameraControls = `look-controls`;\n cursor = `<a-entity\n cursor=\"fuse: true\"\n material=\"color: black; shader: flat\"\n position=\"0 0 -3\"\n raycaster=\"objects: ${props.cursorTargetClass};\"\n geometry=\"primitive: ring; radiusInner: 0.08; radiusOuter: 0.1;\"\n >\n </a-entity>`;\n }\n return {\n cursorCameraControls: cursorCameraControls,\n cursor: cursor\n }\n }", "addSlotKeys() {\n\t\t\tthis.$slots.default.forEach((item, index) => {\n\t\t\t\titem.key = item.key!=null?item.key:index;\n\t\t\t});\n\t\t}", "generateKeyboard(elementId, pianoType=Piano2.PIANO_TYPE_NEW, includeLabels=false) {\r\n \r\n this.out(\"Generating Keyboard_\" + pianoType + \" in \" + elementId);\r\n var wrap = document.getElementById(elementId);\r\n if (null == wrap)\r\n throw new Error(\"ERROR: Invalid Element '\"+elementId+\"' in generateKeyboard()\");\r\n var wrap2 = document.createElement(\"div\");\r\n wrap2.classList.add(\"piano\");\r\n \r\n var divs = [];\r\n var xOffset = -0.5; //For X-axis offset in display (as CSS var(--xOffset))\r\n for (var i = 0; i < Piano2.MAX_KEYS; ++i) {\r\n var randomId = Math.floor(Math.random() * 9999999); //Give it 1 of 10M unique IDs\r\n randomId = \"__p2__key_\" + randomId;\r\n xOffset += 0.5; //Move over 1-half key each time\r\n var note1 = Piano2.HALF_STEPS[0][i % Piano2.NUM_HALF_STEPS]; //Note Name for Classic Piano\r\n var note2 = Piano2.HALF_STEPS[1][i % Piano2.NUM_HALF_STEPS]; //Note Name for Piano 2.0\r\n\r\n //Create a Div Representing a Piano Key\r\n divs.push(document.createElement(\"div\"));\r\n divs[i].id = randomId;\r\n divs[i].classList.add(\"key\", \"white\", \"freq\" + i); //\"black\" may replace \"white\"\r\n divs[i].dataset.freq = i;\r\n \r\n var label = document.createElement(\"div\");\r\n label.classList.add(\"keyLabel\");\r\n label.innerHTML = note1;\r\n divs[i].appendChild(label);\r\n\r\n //Black Key Handling\r\n if (pianoType == Piano2.PIANO_TYPE_NEW) { //for Piano 2.0\r\n label.innerHTML = note2;\r\n divs[i].title = note2 + \" (Classically \" + note1 + \")\";\r\n if (i % 2 == 1) { //Odd keys are always Black in 2.0\r\n divs[i].classList.replace(\"white\", \"black\");\r\n if (i in Piano2.BLACK_KEYS_CENTERED)\r\n divs[i].classList.add(\"blackCenter\");\r\n else if (i in Piano2.BLACK_KEYS_LONG)\r\n divs[i].classList.add(\"blackBig\");\r\n else\r\n divs[i].classList.add(\"blackLighter\");\r\n }\r\n } else { //For Classic style piano (1.0)\r\n if (i in Piano2.BLACK_KEYS_CLASSIC) {\r\n divs[i].classList.replace(\"white\", \"black\");\r\n divs[i].title = note1;\r\n }\r\n }\r\n\r\n //Handle 2 whites in a row (more xOffset needed)\r\n if (i > 0 && divs[i].classList.contains(\"white\") && divs[i - 1].classList.contains(\"white\"))\r\n xOffset += 0.5; //Extra half position\r\n divs[i].style.setProperty(\"--xOffset\", xOffset);\r\n \r\n //Make Clickable Note (with Kludge to keep \"this\" context in p2)\r\n var p2 = this;\r\n divs[i].onclick = function() { p2.handleKeyClick(event, p2); };\r\n wrap2.appendChild(divs[i]);\r\n }\r\n\r\n wrap.appendChild(wrap2);\r\n }", "loadKeysToActions() {\n // Clear beforehand in case we're reloading.\n this.keysToActions.clear();\n this.actions.forEach((action) => {\n const keys = action.getKeys();\n // TODO: For local co-op/split screen, set player-specific bindings.\n keys.forEach((key, inputType) => {\n // Get if this key is for a specific player, denoted by a \"-[0-9]\".\n if (SPLIT_SCREEN_REG.test(inputType)) {\n // This is a split-screen binding, add the player number to the key.\n const playerNumber = inputType.split('-').pop();\n key = `${key}-${playerNumber}`;\n }\n if (!this.keysToActions.has(key)) {\n this.keysToActions.set(key, new Array());\n }\n this.keysToActions.get(key).push(action);\n });\n });\n }", "static keyField() {\n return new lt([\"__name__\"]);\n }", "static getKeys() {\n return [\n this.USD_N,\n //this.EUR_N,\n //this.BTC_N,\n ];\n }", "renderAlphabetKey() {\n this.alphabetKey = document.createElement('div')\n this.alphabetKey.id = 'alphabet-key'\n \n this.alphabetTable = document.createElement('table')\n this.letterArray = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.split('')\n this.letterRow = document.createElement('tr')\n this.formRow = document.createElement('tr')\n this.letterArray.forEach(char => {\n this.letterCell = document.createElement('td')\n this.charLabel = this.createCharLabel(char)\n \n this.letterCell.append(this.charLabel)\n this.letterRow.append(this.letterCell)\n \n this.formCell = document.createElement('td')\n this.charInput = this.createCharInput(char)\n this.charInput.className = 'key-char-input'\n \n this.charInput.addEventListener('input', this.handleInputToAll)\n \n this.formCell.append(this.charInput)\n this.formRow.append(this.formCell)\n })\n \n this.alphabetTable.append(this.letterRow, this.formRow)\n this.alphabetKey.append(this.alphabetTable)\n return this.alphabetKey\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Functions Starts the time counter, preloads available texts, and activates the play/stop button
function start() { generalTime = new Date(); createTextArray(); document.getElementById("playButton").addEventListener('click', buttonControl, false); }//end function start
[ "processStartButton() {\n\t\tclearTimeout(this.timer);\n\t\tthis.timer = null;\n\t\tthis.game.switchScreens('play');\n\t}", "function start() {\n // Disables the text area (place where the user provides input)\n $(\"txtarea_input\").disabled = true;\n \n // Enables the Stop button & disables the Start button\n disableBtn($(\"stop\"), false);\n disableBtn($(\"start\"), true);\n \n // Processes user input\n wordsList = processInput($(\"txtarea_input\").value);\n \n // Sets the timer (frame speed)\n var speed = changeSpeed(); // let the timer tick once\n timer = setInterval(readWordFramePerFrame, speed);\n }", "function countdown() {\n nIntervId = setInterval(changeText, 1000);\n}", "function timer() {\n number--\n $(\"#show-number\").html(\"<h2>\" + number + \"</h2>\");\n if (number === 0) {\n stop();\n }\n }", "function play(){\n removeClassName('no-display');\n addClassName('img', 'no-display');\n addClassName('play-btn', 'no-display')\n showDisplay('player-score');\n showDisplay('computer-score');\n showDisplay('results');\n }", "function tourButtonClick() {\n\tstartButtonClick();\n\tstartIntro();\n}", "function pauseCounter(e) {\n if (e.target.innerText == 'pause') {\n clearInterval(start);\n e.target.innerText = 'resume';\n allButtonsArray.forEach(function(button) {\n button.disabled = true\n });\n }else{\n start = window.setInterval(increase, 1000);\n e.target.innerText = 'pause';\n allButtonsArray.forEach(function(button) {\n button.disabled = false\n });\n }\n }", "function startCounter() {\n timer = window.setInterval(updateCounter, 1*1000);\n }", "function timer() {\n var timeleft = 29;\n var downloadTimer = setInterval(function() {\n if (timeleft <= 0) {\n clearInterval(downloadTimer);\n playEnd();\n document.getElementById(\"time\").innerHTML = \"The End!\";\n document.getElementById(\"go-home\").innerHTML = `\n <a href=\"index.html\">\n <button class=\"btn-options\">Home</button>\n </a> `;\n document.getElementById(\"play-again\").innerHTML = `\n <button class=\"btn-options\" >Play Again</button> `;\n\n } else {\n document.getElementById(\"time\").innerHTML = timeleft + \" s\";\n }\n timeleft -= 1;\n }, 1000);\n}", "function tm_start() {\n\n tm_startTime = Date.now();\n tm_intervalId = setInterval(tm_calculate, tm_intervalTime); // avg key presses per minute get updated on every keystroke or every 2.5 seconds\n}", "function readingTime(time) {\r\n var timer = null;\r\n timer = setInterval(function () {\r\n if (time != 0) {\r\n time--;\r\n $('.ruleBtn').text(time + 's').css(\"color\", \"#ffffff\");\r\n } else {\r\n clearInterval(timer);\r\n $('.ruleBtn').attr('disabled', false);\r\n execI18n();\r\n }\r\n }, 1000);\r\n }", "function startGame() {\n getDifficulty();\n startTimer();\n addCards();\n $(\"refresh\").addEventListener(\"click\", addCards);\n toggleGame();\n currSetCount = 0;\n $(\"set-count\").innerHTML = currSetCount;\n deselectAll();\n }", "function audioPlayerUpdate(event) {\n\tvar time=event.jPlayer.status.currentTime;\n\t// This if ensures that the update event doesn't fire right after the learner presses the replay button, and so the first item isn't displayed right away again because it thinks it is later than it is.\n\tif (!(shell.caption.currPosition == 0 && time > 0.5)) {\n\t\t//console.log('shell.caption.currPosition: ' + shell.caption.currPosition + \" time: \" + time);\n\t\tshell.audio.currentTime = time;\n\t\tif (shell.caption.isTimedCC && shell.caption.data[shell.currPageId]) {\n\t\t\tvar ccObjArray = shell.caption.data[shell.currPageId].mainPage;\n\t\t\tif (shell.caption.onSubPage) {\n\t\t\t\tif (shell.caption.onSubSubPage) {\n\t\t\t\t\tccObjArray = shell.caption.data[shell.currPageId].subPages[shell.caption.subPageNum].subPages[shell.caption.subSubPageNum];\n\t\t\t\t} else {\n\t\t\t\t\tif(shell.caption.data[shell.currPageId].subPages) {\n\t\t\t\t\t\t//console.log(\"subpages: \" +shell.caption.data[shell.currPageId].subPages);\n\t\t\t\t\t\tccObjArray = shell.caption.data[shell.currPageId].subPages[shell.caption.subPageNum].mainPage;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\t//console.log(ccObjArray);\n\t\t\tif (shell.caption.currPosition < ccObjArray.length) {\n\t\t\t\tvar pageInfo = ccObjArray[shell.caption.currPosition];\t\t\t\t\t\t\n\t\t\t\t//console.log('pageInfo: ' + pageInfo);\n\t\t\t\tif (time >= pageInfo.time) {\n\t\t\t\t\tloadCCText(pageInfo.html);\n\t\t\t\t\tshell.caption.currPosition++;\n\t\t\t\t}\n\t\t\t} \n\t\t}\n\t\t// Set up timed content display\n\t\tif (shell.timedContent.data[shell.currPageId]) {\n\t\t\tif (!shell.timedContent.onSubPage && !shell.timedContent.onSubSubPage) {\n\t\t\t\tif (shell.timedContent.currPosition < shell.timedContent.data[shell.currPageId].mainPage.length) {\n\t\t\t\t\t//console.log('shell.timedContent.currPosition: ' + shell.timedContent.currPosition + ' and shell.timedContent.data[shell.currPageId].mainPage.length: ' + shell.timedContent.data[shell.currPageId].mainPage.length);\n\t\t\t\t\tvar timeInfo = shell.timedContent.data[shell.currPageId].mainPage[shell.timedContent.currPosition];\t\t\t\t\t\t\n\t\t\t\t\tif (time >= timeInfo.time) {\n\t\t\t\t\t\t//console.log(timeInfo.displayType + \" \" + timeInfo.contentId);\n\t\t\t\t\t\tdisplayTimedItem(timeInfo);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else if (shell.timedContent.onSubPage) {\n\t\t\t\t//console.log(\"I'm on a sub page\");\n\t\t\t\t//If ths subpage has timed content (outside of CC text)\n\t\t\t\tif (shell.timedContent.data[shell.currPageId].subPages) {\n\t\t\t\t\t//console.log(\"shell.timedContent.currPosition: \"+ shell.timedContent.currPosition);\n\t\t\t\t\tif (shell.timedContent.currPosition < shell.timedContent.data[shell.currPageId].subPages[shell.caption.subPageNum].length) {\n\t\t\t\t\t\t//console.log('shell.timedContent.currPosition: ' + shell.timedContent.currPosition + ' and shell.timedContent.data[shell.currPageId].mainPage.length: ' + shell.timedContent.data[shell.currPageId].mainPage.length);\n\t\t\t\t\t\tvar timeInfo = shell.timedContent.data[shell.currPageId].subPages[shell.caption.subPageNum][shell.timedContent.currPosition];\t\t\t\t\t\t\n\t\t\t\t\t\t//console.log(\"time: \"+ time);\n\t\t\t\t\t\tif (time >= timeInfo.time) {\n\t\t\t\t\t\t\t//console.log(timeInfo.displayType + \" \" + timeInfo.contentId);\n\t\t\t\t\t\t\tdisplayTimedItem(timeInfo);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\t\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n//console.log('time is being updated: ' + event.jPlayer.status.currentTime);\t\t\n}", "function timerControl( pAction ) {\n console.log( \"Entered timer control, action = '\" + pAction + \"'\" );\n\tif ( pAction === \"start\" ) {\n\t\tptrTimer.innerHTML = secondsPerQuestion;\n\t\tsecondsRemaining = secondsPerQuestion;\n\t\twindow.clearInterval( timer ); // Ensure that the timer has stopped\n\t\ttimer = window.setInterval( updateTimer, 1000 );\n\t\tpauseTimer = false;\n\t} else if ( pAction === \"stop\" ) {\n\t\twindow.clearInterval( timer );\n\t} else if ( pAction === \"pause\" ) {\n\t\tconsole.log( \"Pausing timer: \" + pauseTimer );\n\t\tpauseTimer = ! pauseTimer;\n if ( pauseTimer ) {\n ptrPause.innerHTML = \"Resume Game\"\n } else {\n ptrPause.innerHTML = \"Pause Game\" \n }\n\t}\n}", "function ready() {\n\tsetTimeout(countdownThree, 1000);\n\tdocument.getElementById(\"timer\").innerHTML = \"READY..\";\n\tconsole.log(\"ready.....\");\n}", "function beginCountDown() {\n\n myCountDown = setInterval(countDown, 1000)\n }", "function startBattleTimer() {\n // Swap button\n document.getElementById('startButton').remove();\n document.getElementById('attackButton').classList.remove('d-none');\n document.getElementById('retreatButton').classList.remove('d-none');\n \n // Add battle log entry\n document.getElementById(\"battleLog\").append(\"Battle Commenced!\");\n \n // Start Battle\n engageBattle();\n}", "function loadCounters() {\n \n // set up timer for reading the script\n game.time.events.repeat(1000, 30, (() => {\n scriptIterator.readNextScript();\n }), this);\n\n createTimer(0, 1000, true);\n createLiveTimer();\n}", "function OnTimeSliderClick()\n{\n\t\n\tnDomain = DVD.CurrentDomain;\n\tif (nDomain == 2 || nDomain == 3) \n\t\treturn;\n\n\tlTitle = DVD.CurrentTitle;\n\ttimeStr = GetTimeSliderBstr();\n\n\tDVD.PlayAtTimeInTitle(lTitle, timeStr);\n\tDVD.PlayForwards(DVDOpt.PlaySpeed);\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Retrieves the object that is being designated.
getObject() { return this.object; }
[ "function GetObject(name)\n{\n\tvar o=null;\n\tif(document.getElementById)\n\t\to=document.getElementById(name);\n\telse if(document.all)\n\t\to=document.all.item(name);\n\telse if(document.layers)\n\t\to=document.layers[name];\n\tif (o==null && document.getElementsByName)\n\t{\n\t\tvar e=document.getElementsByName(name);\n\t\tif (e.length==1) o=e[0];\n\t}\n\treturn o;\n}", "function getLocator(obj) {\n return obj.locator;\n }", "function getCurrentInstance() {\n return currentInstance && { proxy: currentInstance };\n }", "function getTableauObj() {\n try {\n return window.parent.tableau;\n } catch (errorMsg) {\n console.log('Can not retrieve window.parent.tableau');\n return null;\n }\n}", "getFabricObject(ag_objectID) {\n let canvas_objects = this._room_canvas.getObjects();\n let fab_buffer;\n canvas_objects.forEach(function (item, i) {\n if (item.isObject && item.AGObjectID == ag_objectID) {\n fab_buffer = item;\n }\n });\n return fab_buffer;\n }", "get ownerUserProfile() {\n return spPost(this.getParent(ProfileLoaderFactory, \"_api/sp.userprofiles.profileloader.getowneruserprofile\"));\n }", "function findObject(index) {\n return repository[index];\n }", "function getDeviceObject(){\n\tif(globalInfoType == \"JSON\"){\n var devices = getDevicesNodeJSON();\n }else{\n var devices =devicesArr;\n }\n\tfor(var a=0; a<devices.length; a++){\n\t\tif (devices[a].ObjectPath == glblDevMenImg){\n\t\t\treturn devices[a];\n\t\t}\n\t}\n}", "getOwner() {\n this.logger.debug(GuildService.name, this.getOwner.name, \"Executing\");\n this.logger.debug(GuildService.name, this.getOwner.name, \"Getting owner and exiting.\");\n return this.guild.owner.user;\n }", "findObject(id) {\n\t\tfor (var i in this.gameobjects) {\n\t\t\tif (this.gameobjects[i].id == id) {\n\t\t\t\treturn this.gameobjects[i];\n\t\t\t}\n\t\t}\n\n\t\treturn null;\n\t}", "static get screenName() {\n return this.__proto__.constructor.name;\n }", "getCurrentItem() {\n\t\t\tlet itemID = currentAdventure.rooms[currentRoom].item_id;\n\t\t\t\n\t\t\tif (!itemID)\n\t\t\t\treturn null;\n\n\t\t\tlet items = currentAdventure.items;\n\t\t\tlet itemObj = {};\n\n\t\t\tfor (let i=0; i < items.length; i++){\n\t\t\t\tif (items[i].id === itemID)\n\t\t\t\t\titemObj = items[i];\n\t\t\t}\n\n\t\t\treturn itemObj;\n\t\t}", "getDestinationEntity () {\n\t\tconst definition = this.definition;\n\t\tconst entity = this.getEntity();\n\t\tconst objectGraph = entity.getObjectGraph();\n\n\t\treturn objectGraph.getEntitiesByName()[definition.entityName];\n\t}", "get element() {\n if (Screen.cache_.element === undefined) {\n Screen.cache_.element = document.getElementById(\"screen\");\n }\n return Screen.cache_.element;\n }", "function getMember() {\n var matchMin = getMin();\n var getMember;\n for (var y = 0; y < store.length; y++) {\n if (store[y].actProjects == matchMin) {\n getMember = store[y].member;\n }\n }\n if (DEBUG) {\n wom.log(DEBUG_PREFIX + \"Got member... \" + getMember.lastName);\n }\n return getMember;\n }", "get user() {\n this._logger.debug(\"user[get]\");\n return this._user;\n }", "function pullEnemyObj(y) {\n let eindex = findInArray(enemylist, y);\n let enemy = enemylist[eindex];\n return enemy;\n }", "constructor() {\r\n ObjectManager.instance = this;\r\n\r\n }", "get webpart() {\n return SPInstance(this, \"webpart\");\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
draw n enemies into enemies array
function drawEnemies(){ for (var _ = 0; _<4; _++){ var x = Math.random()*(innerWidth-enemy_width); var y = -enemy_height; var width = enemy_width; var height = enemy_height; var speed = Math.random()*4.5; var __enemy = new Enemy(x, y, width, height, speed); _enemies.push(__enemy); } }
[ "generateEnemies() {\n // Run the spawn timer\n this.timer++;\n if (this.enemies.length == 0) {\n this.timer += 2;\n } else if (this.enemies.length == 1) {\n this.timer += 1;\n }\n\n if (\n this.timer >= this.spawnDelay &&\n this.enemies.length < MAX_ENEMIES.value\n ) {\n this.createEnemy(this.x, this.y);\n this.resetTimer();\n }\n }", "function addMoreEnemies(){\n let enemyPosition = Math.random() * 184 + 50;\n enemyLocation.push(enemyPosition);\n enemy = new Enemy(0, enemyPosition, Math.random() * 256);\n allEnemies.push(enemy);\n}", "setupEnemies() {\n if (!this.enemies) {\n this.enemies = [];\n }\n while (this.enemies.filter(e => !!e).length < MAX_ENEMIES) {\n this.addEnemy();\n }\n }", "createInitialEnemies() {\n this.enemies = [];\n this.checkEnemyCreation(1000);\n for (let i = 0; i < this.level.numEnemyRows - 1; ++i) this.checkEnemyCreation(2);\n }", "function createArrayOfEnemies() {\n let arrayOfEnemies = [];\n const SPACING = 4; // the spacing between each enemy in each row\n // Iterate through each stone row\n for (let i=1; i<4; i++) {\n // Determine a random speed for the enemies in each row based on\n // the current level (player index being played)\n const LOWER_SPEED_LIMIT = 50 + currentPlayerIndex*25;\n const UPPER_SPEED_LIMIT = 75 + currentPlayerIndex*25;\n const SPEED = getRandomInteger(LOWER_SPEED_LIMIT, UPPER_SPEED_LIMIT);\n // Alternate direction for each row\n const DIRECTION = i%2;\n // Create 8 enemies within each row.\n for (let j=-3; j<4; j++) {\n // Determine the column in which the enemy will initialize.\n // This is determined according to index of the enemy in the\n // current row, the set spacing provided for the row, and\n // a random increment in spacing so that the enemies don't\n // march with a uniform spacing. Some enemies will initialize\n // before the visibile portion of the row begins, within the\n // visible portion of the row, and after the visible portion\n // of the row ends.\n const START_X_COL = j*SPACING + getRandomInteger(0, 2);\n // Create and add an enemy to the arrayOfEnemies\n arrayOfEnemies.push(new Enemy(i, DIRECTION, START_X_COL, SPEED));\n }\n }\n return arrayOfEnemies;\n}", "function MoveEnemies () {\n if (ENEMIES.length || ENEMIES_WAITING.length) {\n ENEMIES.map(function (enemy) { \n if (enemy.y < CANVAS_HEIGHT-enemy.height) {\n DrawEnemy(enemy); \n enemy.y++;\n } \n else {\n ENEMIES.shift();\n }\n });\n }\n else {\n console.log('No enemies left!');\n }\n }", "function createMonsters(number) {\n for (let i = 0; i < number; i++) {\n monsterArray.push(new Obstacles(Math.random()*3 + 1))\n }\n //player must die\n setTimeout(() => {\n monsterArray.push(new Obstacles(Math.random()*3 + 1))\n }, 50000);\n}", "function drawEnemyPlanes()\r\n{\r\n for(var i = 0; i < enemyPlanes.length; i++)\r\n {\r\n ctx.drawImage(enemyPlane, enemyPlanes[i][0], enemyPlanes[i][1]);\r\n }\r\n}", "spawnOne(i){\n\n // pick which enemy to spawn:\n // shooting enemies appear starting at difficulty level 2,\n // and are more likely to appear at difficulty level 3\n\n let choice='fighter'\n if(levelData.difficulty>1){\n if(levelData.difficulty>2&&Math.random()>0.3) choice='shooter';\n else if(Math.random()>0.6) choice='shooter';\n }\n\n if(i==undefined) i=0;\n enemies.push(new Enemy(\n this.x - 50 + randInt(50) + i*50,\n this.y-80,\n choice\n ));\n }", "function renderEnemyMissle(){\r\n\t\tif(enemyMissles.length > 0){\r\n\t\t\tfor(var i = 0; i < enemyMissles.length; i++){\r\n\t\t\t\tcontext.save();\r\n\t\t\t\tcontext.fillStyle=\"red\";\r\n\t\t\t context.fillStroke=\"red\";\r\n\t\t\t context.translate(enemyMissles[i].x, enemyMissles[i].y);\r\n\t\t\t context.rotate(enemyMissles[i].rotation);\r\n\t\t\t context.translate(-enemyMissles[i].x, -enemyMissles[i].y);\r\n\t\t\t\tcontext.fillRect(enemyMissles[i].x, enemyMissles[i].y, 10, 5);\r\n\t \tcontext.restore();\r\n\t\t\t}\r\n\t\t}\t\r\n\t}", "function newEnemy() {\n if (allEnemies.length < maxEnemy) {\n var enemy = new Enemy(randomCol(), enemyY, randomSpeed(), enemyWidth, enemyHeight, getChar());\n allEnemies.push(enemy);\n }\n}", "function drawenemy() {\n var canvas = document.getElementById('myCanvas');\n var context = canvas.getContext('2d');\n context.fillStyle=\"green\";\n context.textAlign = 'center';\n context.font = \"20px monospace\";\n \n for(var i = 0; i < enemy.length; i++) {\n // context.fillText(enemy[i][6]-enemy[i][7],enemy[i][0],enemy[i][1]-enemysize*5);\n context.lineWidth = 1;\n context.save();\n // enemyx= enemyx+1;\n enemy[i][0]=enemy[i][0]+enemy[i][3];\n if( enemy[i][0]>canvas.width){\n enemy[i][0]=1;\n }\n enemy[i][7]=enemy[i][7]+1;\n // context.translate(enemyx,enemyy);\n if(enemy[i][7]>enemy[i][6]){\n enemy[i][7]=0;\n enemy[i][5]=\"red\";\n rndx = (Math.round(Math.random() * canvas.width));\n randangle = (Math.round(Math.random() * 5)+1);\n superenemyspeed = (Math.round(Math.random() * 8)+1);\n superenemies.push([enemy[i][0], enemy[i][1], randangle, superenemyspeed, superenemyspeed, \"red\", minePoints*2]);\n }\n if(enemy[i][7]>0 && enemy[i][7]<enemy[i][6]) {\n enemy[i][5]=\"green\";\n }\n context.strokeStyle = enemy[i][5];\n context.translate(enemy[i][0],enemy[i][1]);\n context.beginPath();\n context.strokeRect(-enemysize, -enemysize, enemysize*2, enemysize*2); \n context.arc(0, 0, enemysize*3, 0, Math.PI * 2, true);\n context.closePath();\n context.stroke();\n context.rotate(enemyrotatedeg * Math.PI / 180);\n// context.translate(0, 0);\n for (var b = 0; b < 2; b++) {\n // context.translate(0, 0);\n context.rotate(45*Math.PI/180)\n context.strokeRect(-enemysize*2.5, -enemysize*2.5, enemysize*5, enemysize*5);\n \n }\n context.restore();\n }\n}", "function weaponHit(e, m, ei, mi) {\n\n if(m.x <= (e.x + e.w) && (m.x + m.w) >= e.x && m.y <= (e.y + e.h) && (m.y + m.h) >= e.y) {\n enemyArray.splice(ei,1)\n weaponArray.splice(mi,1)\n new enemyExplosion(\"./sfx/enemyExplosion.wav\")\n score += 100\n\n for(let d=0; d < 15; d++) {\n let size = Math.floor(Math.random() * 3) + 1\n let dx = (Math.random() - 0.5) * 20;\n let dy = (Math.random() - 0.5) * 20;\n let color = colorArray[Math.floor(Math.random()*colorArray.length)]\n debrisArray.push(new enemyDestroyed(e.x, e.y , size, dx, dy, color))\n }\n \n for(let d=0; d < 15; d++) {\n let size = Math.floor(Math.random() * 1) + 1\n let dx = (Math.random() - 0.5) * 30;\n let dy = (Math.random() - 0.5) * 30;\n let color = colorArray2[Math.floor(Math.random()*colorArray.length)]\n debrisArray.push(new enemyDestroyed(e.x, e.y , size, dx, dy, color))\n }\n }\n}", "checkEnemyCreation(dt) {\n if (Math.random() < dt * this.level.enemyFrequency * this.level.stoneRows) {\n // only create enemies in stone rows\n const row = Math.floor(Math.random() * this.level.stoneRows + this.level.waterRows);\n const speed = Math.floor(Math.random() * (this.level.enemyMaxSpeed - this.level.enemyMinSpeed) + this.level.enemyMinSpeed);\n // place enemies at either the left or right edge of screen\n // and set their movement to travel to the other side\n if (Math.random() < 0.5) {\n this.enemies.push(new Enemy({x: -this.level.tileWidth, y: row * this.level.tileHeight}, {x: speed, y: 0}));\n } else {\n this.enemies.push(new Enemy({x: this.level.widthPixels() + this.level.tileWidth, y: row * this.level.tileHeight},\n {x: -speed, y: 0}));\n }\n }\n }", "spawnMore(){\n this.hitPoints =0;\n for(let i=0; i<levelData.sections+1; i++)\n this.spawnOne(i);\n }", "totalEnemies()\n {\n this.numberOfEnemies++;\n }", "function removeEnemiesOutOfFrame() {\n // Iterate Through Enemies\n for (var x = 0; x < allEnemies.length; x++) {\n var en = allEnemies[x];\n // If Grid X Position is > 7\n // Remove From Stack\n if (en.x > 7) {\n // Remove The Enemy\n allEnemies.splice(x, 1);\n // Break The Loop and Recursively\n // Repeat the Process Untill All\n // Useless Enemies Are Gone\n removeEnemiesOutOfFrame();\n break;\n }\n }\n}", "function checkEnemiesOutOfBounds()\r\n{\r\n\tlivingEnemies.length=0;\r\n\r\n enemies.forEachAlive(function(bad){\r\n\r\n \r\n livingEnemies.push(bad);\r\n });\r\n\t\r\n\tfor(var i = 0; i < livingEnemies.length; i++)\r\n\t{\r\n\t\tif(livingEnemies[i].body.y > game.world.height)\r\n\t\t{\r\n\t\t\tlivingEnemies[i].kill();\r\n\t\t\tkillPlayer();\r\n\t\t}\r\n\t\t\r\n\t}\r\n}", "function renderEntities() {\n /* Loop through all of the objects within the allEnemies array and call\n * the render function you have defined.\n */\n allEnemies.forEach(function(enemy) {\n enemy.render();\n });\n\n player.render();\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Student TP Number Validation
function tpNumberValidation(sData, tpNumber){ var studentTpNumber studentTpNumber = sData.filter(obj => { return obj.tpNumber === tpNumber }) return studentTpNumber.length }
[ "function checkInsert() {\n var insert_student_name = document.getElementById('insert_student_name').value;\n var insert_student_score = document.getElementById('insert_student_score').value;\n if (insert_student_name==null || insert_student_name=='') {\n alert('student name cannot be empty.')\n return false;\n }\n if (insert_student_score==null || insert_student_score=='') {\n alert('student score cannot be empty.')\n return false;\n }\n if (isNaN(parseFloat(insert_student_score))) {\n alert('invalid score.')\n return false;\n }\n return true;\n}", "function check_input_fields() {\n var name = $('#student_name').val().replace(/\\s+/g, '');\n var course = $('#course_name').val().replace(/\\s+/g, '');\n var grade = parseFloat($('#student_grade').val());\n if (name == '' || course == '' || grade < 0 || grade > 100 || grade == '' || isNaN(grade) == true) {\n var message = 'All input fields must contain at least one non-space character. Grade must be a number between 0 and 100.';\n display(message);\n return true;\n }\n}", "function validateAmortization(errorMsg) {\n var tempAmortization = document.mortgage.amortization.value;\n tempAmortization = tempAmortization.trim();\n var tempAmortizationLength = tempAmortization.length;\n var tempAmortizationMsg = \"Please enter Amortization!\";\n\n if (tempAmortizationLength == 0) {\n errorMsg += \"<p><mark>No. of years field: </mark>Field is empty <br />\" + tempAmortizationMsg + \"</p>\";\n } else {\n if (isNaN(tempAmortization) == true) {\n errorMsg += \"<p><mark>No. of years field: </mark>Must be numeric <br />\" + tempAmortizationMsg + \"</p>\";\n } else {\n if (tempAmortization < 5 || tempAmortization > 20) {\n errorMsg += \"<p><mark>No. of years field: </mark>Must be values: 5 thru 20 inclusive <br />\" + tempAmortizationMsg + \"</p>\";\n }\n }\n }\n return errorMsg;\n}", "function isGraduateStudent(data) {\r\n\t\tswitch (data) {\r\n\t\t\tcase \"M.A.\":\r\n\t\t\t\tresult = true;\r\n\t\t\t\tbreak;\r\n\t\t\tcase \"M.B.A.\":\r\n\t\t\t\tresult = true;\r\n\t\t\t\tbreak;\r\n\t\t\tcase \"M.ED.\":\r\n\t\t\t\tresult = true;\r\n\t\t\t\tbreak;\r\n\t\t\tcase \"M.J.A.\":\r\n\t\t\t\tresult = true;\r\n\t\t\t\tbreak;\r\n\t\t\tcase \"M.S.\":\r\n\t\t\t\tresult = true;\r\n\t\t\t\tbreak;\r\n\t\t\tcase \"M.S.M.\":\r\n\t\t\t\tresult = true;\r\n\t\t\t\tbreak;\r\n\t\t\tcase \"PHD\":\r\n\t\t\t\tresult = true;\r\n\t\t\t\tbreak;\r\n\t\t\tcase \"J.D.\":\r\n\t\t\t\tresult = true;\r\n\t\t\t\tbreak;\r\n\t\t\tdefault:\r\n\t\t\t\tresult = false;\r\n\t\t\t\tbreak;\r\n\t\t}\r\n\t\treturn result;\r\n\r\n\r\n\t}", "function VerificationPrenom() {\n const prenom = document.getElementById(\"prenom\");\n const LMINI = 2, // DP LMINI = longueur minimale du prenom\n LMAXI = 50; //DP LMAXI = longueur maximale du prenom\n\n //DP si le prenom comporte moins de 2 lettres ou plus de 50 lettres alors erreur\n if ((prenom.value.length < LMINI) || (prenom.value.length > LMAXI)) {\n console.log(\"longueur prenom NOK\", prenom.value.length);\n return false;\n } else {\n console.log(\"longueur prenom OK\", prenom.value.length);\n return true;\n }\n}", "function validateIntRate(errorMsg) {\n var tempIntRate = document.mortgage.intRate.value;\n tempIntRate = tempIntRate.trim();\n var tempIntRateLength = tempIntRate.length;\n var tempIntRateMsg = \"Please enter Interest Rate!\";\n\n if (tempIntRateLength == 0) {\n errorMsg += \"<p><mark>Interest rate field: </mark>Field is empty <br />\" + tempIntRateMsg + \"</p>\";\n } else {\n if (isNaN(tempIntRate) == true) {\n errorMsg += \"<p><mark>Interest rate field: </mark>Must be numeric <br />\" + tempIntRateMsg + \"</p>\";\n } else {\n if (parseFloat(tempIntRate) < 2.000 || parseFloat(tempIntRate) > 11.000) {\n errorMsg += \"<p><mark>Interest rate field: </mark>Must be values: 2.000 thru 11.000 inclusive <br />\" + tempIntRateMsg + \"</p>\";\n } \n }\n }\n return errorMsg;\n}", "function isPassing(grade){\n return grade >= 10;\n}", "function _validUPS(number) {\n number = number.trim();\n if (number.length != 18) { return false; }\n var check = number.substr(17, 1);\n\n // First Two Digits Must Be 1Z\n if (number.substr(0, 2) !== \"1Z\") { return false; }\n\n // Remaining Characters To Check\n number = number.substr(2, 15);\n console.log(number);\n\n var iRunningTotal = 0;\n var ValidChars = \"0123456789\"; // used to validate a number\n for (var i = 0; i < number.length; i++) {\n var c = number.charAt(i);\n if (((i + 1) % 2) == 0) { // even index value\n if (ValidChars.indexOf(c) != -1) // indicates numeric value\n iRunningTotal += 2 * Number(c);\n else\n iRunningTotal += (number.charCodeAt(i) - 63) % 10;\n\n }\n else { // character is at an odd position\n if (ValidChars.indexOf(c) != -1) // indicates numeric value\n iRunningTotal += Number(c);\n else {\n var n = (number.charCodeAt(i) - 63) % 10;\n iRunningTotal += (2 * n) - (9 * Math.floor(n / 5));\n }\n }\n }\n\n var digit = iRunningTotal % 10;\n if (digit != check && digit > 0)\n digit = 10 - digit;\n else\n return true;\n\n return digit == check\n }", "function isUserNumberValid(v) {\n return v <= 100 && v >= 1 && v != NaN && v % 1 == 0;\n}", "function validaSumaAnticipo(modoEdicionPartida){\r\n\t\tvar tipoComprobacion = $(\"#tipoComprobacion\").val();\r\n\t\tvar validacion = true;\r\n\t\tvar sumaAnticipo = 0;\r\n\t\tvar tablaLength = obtenTablaLength(\"comprobacion_table\");\r\n\t\t\r\n\t\tvar anticipo = limpiaCantidad($(\"#div_anticipo\").text());\r\n\t\tvar totalPartida = limpiaCantidad($(\"#totalPartida\").val());\r\n\t\t\r\n\t\tfor(var i = 1; i <= tablaLength; i++){\r\n\t\t\tif($(\"#div_row_tipoComprobacion\"+i).val() == \"Anticipo\")\r\n\t\t\t\tsumaAnticipo+= (modoEdicionPartida == i) ? 0 : limpiaCantidad($(\"#row_totalPartida\"+i).val());\r\n\t\t}\r\n\t\tsumaAnticipo+= totalPartida;\r\n\t\t\r\n\t\tif( tipoComprobacion == \"Anticipo\" && (totalPartida > anticipo || sumaAnticipo > anticipo) ){\r\n\t\t\talert(\"El valor que se esta ingresando supera el anticipo asignado\");\r\n\t\t\tvalidacion = false;\r\n\t\t}\t\t\r\n\t\treturn validacion;\r\n\t}", "function checkNatYear()\n{\n let re = /^(\\[?[0-9]{4}\\]?|nat?|\\[blank\\]?|\\[Blank\\]?|\\?|)$/;\n let year = this.value;\n setErrorFlag(this, re.test(year));\n}", "gradeSubmission(student){\n //only python files are allowed\n if (this.file.slice(-2) !== 'py'){\n this.grade = 0;\n student.calculateStudentAverage()\n this.comment = \"Only py files are allowed!\"\n return\n }\n //submission is before the deadline\n if (this.submissionTime > this.deadline){\n this.grade = 0;\n student.calculateStudentAverage()\n this.comment = \"Submission after deadline!\"\n return\n }\n //if formal requirements are met, the submission is evaluated by the judge\n //instance of Student and Weektask are updated\n this.grade = getRandomInt(6);\n student.calculateStudentAverage()\n this.weektask.getWeektaskAverage()\n this.comment = \"Submitted and graded\"\n\n }", "function errorTime(){\n\tvar timet1 = document.getElementById('TRV_t1_id').value\n var timet2 = document.getElementById('TRV_t2_id').value\n\tvar timet3 = document.getElementById('TRV_t3_id').value\n\ttimet1 = parseFloat(timet1)\n\ttimet2 = parseFloat(timet2)\n\tif (timet1 > timet2){\n\t\treturn true\n\t}\n\tif (timet3!=0 && (timet1!=0 || timet2 != 0)){\n\t\treturn true\n\t} \n\telse {\n\t\treturn false\n\t}\n}", "function isValidScore(value) {\n\tvar result = false;\n\tif (value != '' && typeof value != \"undefined\") {\n\t\tif (IsNumeric(value)) {\n\t\t\tvalue = parseFloat(value);\n\t\t\tif (value >= 0 && value <= 5) {\n\t\t\t\tresult = true;\n\t\t\t} else {\n\t\t\t\tresult = false;\n\t\t\t}\n\t\t} else {\n\t\t\tresult = false;\n\t\t}\n\t} else {\n\t\tresult = true;\n\t}\n\treturn result;\n}", "function validatePounds() {\n\tvar ptr = $(\"numItemWeightLb\"); \t\t//Pointer to pounds input field\n\tvar err = $(\"errItemWeightLb\");\t\t//Pointer to error marker for pounds\n\tvar input;\t\t\t\t\t\t\t\t\t//Contents of the pounds text box\n\t\n\terr.style.visibility = \"hidden\";\n\tif(ptr.value == \"\") {\n\t\terr.style.visibility = \"visible\";\n\t\terr.title = \"You must enter the number of pounds.\";\n\t} else {\n\t\tinput = FormatNumber(ptr.value, \"G\"); //Unformat it (remove commas\n\t\tinput = parseInt(input);\n\t\tif(input<0) { \n\t\t\terr.style.visibility = \"visible\";\n\t\t\terr.title = \"Pounds must be at least 0\";\n\t\t} else {\n\t\t\tptr.value = FormatNumber(input, \"N0\");\n\t\t} //end if\n\t}//end if\n\n\treturn err.style.visibility == \"hidden\";\n\n}", "function onVerifyOTPClicked (event) {\n let isValid = true;\n let { userType } = event.target.dataset;\n if (!userType) {\n userType = 'student'\n }\n\n const phoneNumber = window.sentOTPtoPhoneNumber;\n const otp = $('.otp-input').toArray().map((input) => input.value).join('');\n if (otp.length !== 6) {\n $(getClassName(userType, 'otpCodeError')).text('Please provide valid OTP');\n isValid = false;\n }\n if (isValid) {\n verifyOtpAPI(userType, phoneNumber, otp);\n }\n}", "function validar_RUC_2(ruc) {\n //Valida dimension\n if (ruc.length != 13) {\n return 0;\n } else {\n let dos_primeros_digitos = parseInt(ruc.slice(0, 2));\n //Valida dos primeros digitos\n if (dos_primeros_digitos < 1 && dos_primeros_digitos > 22) {\n return 0;\n }\n let tercer_digito = parseInt(ruc[2]);\n //Valida tercer digito (Condicion creada con logica matematica y leyes de De Morgan)\n if (\n tercer_digito != 9 &&\n tercer_digito != 6 &&\n (tercer_digito < 0 || tercer_digito >= 6)\n ) {\n return 0;\n }\n //Realizamos la validacion del caso 2\n else {\n let ultimos_cuatro_digitos = parseInt(ruc.slice(9, 13));\n if (ultimos_cuatro_digitos <= 0) {\n return 0;\n }\n let total = 0;\n let ocho_primeros_digitos = ruc.slice(0, 8);\n let coeficientes = \"32765432\";\n let num;\n let coef;\n let valor;\n for (i = 0; i <= coeficientes.length - 1; i++) {\n num = parseInt(ocho_primeros_digitos[i]);\n coef = parseInt(coeficientes[i]);\n valor = num * coef;\n total = total + valor;\n }\n //Calculamos el residuo y el verificador\n let residuo = total % 11;\n let verificador;\n if (residuo == 0) {\n verificador = 0;\n } else {\n verificador = 11 - residuo;\n }\n if (verificador == parseInt(ruc[8])) {\n return 1;\n } else {\n return 0;\n }\n }\n }\n}", "function validRating(rating){\n try {\n let numRate = parseInt(rating)\n if(numRate < 1 || numRate > 5){\n return false;\n } else {\n return true;\n }\n } catch (e){\n return false;\n }\n}", "function isPandigital(num){\n\n\n\n// split the number into an array\nlet numArr = `${num}`.split(\"\")\n// get length of array\nlet len = parseInt(`${num}`.length)\n\nlet sum1 = 0;\nlet sum2 = 0;\n\n// loop over length\nfor(let i = 1; i<len+1; i++){\n sum1 += i;\n}\n// loop over each number in array\nfor(let i = 0; i<numArr.length; i++){\n sum2 += parseInt(numArr[i])\n}\nif (sum1 == sum2 && sum1 > 0){\n\treturn true \n\n}\nelse{\n\treturn false\n}\n}", "function guessValidation () {\n if (+($(\"#userGuess\").val()) > 100 || +($(\"#userGuess\").val()) < 1) {\n alert(\"Please enter a number between 1 - 100\");\n }\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Exports html to docx format and downloads automatically
function exportHTML(html){ var header = "<html xmlns:o='urn:schemas-microsoft-com:office:office' "+ "xmlns:w='urn:schemas-microsoft-com:office:word' "+ "xmlns='http://www.w3.org/TR/REC-html40'>"+ "<head><meta charset='utf-8'><title>Export HTML to Word Document with JavaScript</title></head><body>"; var footer = "</body></html>"; var sourceHTML = header+html+footer; var source = 'data:application/vnd.ms-word;charset=utf-8,' + encodeURIComponent(sourceHTML); var fileDownload = document.createElement("a"); document.body.appendChild(fileDownload); fileDownload.href = source; fileDownload.download = 'myResume.doc'; fileDownload.click(); document.body.removeChild(fileDownload); }
[ "function Export2Doc(element, filename = ''){\r\n var preHtml = \"<html><head><meta charset='utf-8'><title>Export HTML To Doc</title><link rel='stylesheet' href='/static/css/style.css'></head><body>\";\r\n var postHtml = \"</body></html>\";\r\n var iframe=document.getElementById(\"awindow\");\r\n var report_template=iframe.contentDocument.getElementsByClassName(element);\r\n var reporting =iframe.contentDocument.getElementById(\"reporting-period\");\r\n var html = preHtml+report_template[0].innerHTML+postHtml;\r\n\r\n var blob = new Blob(['\\ufeff',html], {\r\n type: 'application/msword'\r\n });\r\n\r\n // Specify link url\r\n var url = 'data:application/vnd.ms-word;charset=utf-8,' + encodeURIComponent(html);\r\n\r\n // Specify file name\r\n filename=\"Weekly_progress_report_\"+reporting.innerText\r\n filename = filename.split('-').join('').replace(' To ','_')\r\n filename = filename?filename+'.doc':'document.doc';\r\n\r\n // Create download link element\r\n var downloadLink = document.createElement(\"a\");\r\n\r\n document.body.appendChild(downloadLink);\r\n\r\n if(navigator.msSaveOrOpenBlob ){\r\n navigator.msSaveOrOpenBlob(blob, filename);\r\n }else{\r\n // Create a link to the file\r\n downloadLink.href = url;\r\n\r\n // Setting the file name\r\n downloadLink.download = filename;\r\n\r\n //triggering the function\r\n downloadLink.click();\r\n }\r\n\r\n document.body.removeChild(downloadLink);\r\n}", "function export1Gdoc2Html(fileId, fileName, cb) {\r\n\t\tgdriveAPI.files.export({\r\n\t\t auth : auth,\r\n\t\t fileId: fileId,\r\n mimeType : 'text/html',\r\n\t\t alt: 'media'\r\n\t }, function(err, res) {\r\n\t\t fs.writeFileSync('private/gdocs/' + fileName + '.html', res, 'utf8')\r\n\r\n cb()\r\n\t })\r\n\t}", "function convert_docx_to_html(file) {\n let output = 'html.html'\n execSync(`pandoc ${file} -o ${output} --extract-media=.`)\n console.info(\"Converted docx file to HTML\")\n return output\n}", "function exportProcessedDocumentsToFiles(action, context, callback) {\n if (action.debug)\n debugger;\n for (var filePath in context.HTMLOutputs) {\n var $_1 = context.HTMLOutputs[filePath];\n context.fileManager.writeTextFileSync(filePath.replace('.html', '.temp.html'), $_1.html());\n }\n ca.endAction(action, callback);\n }", "function download(year) {\n wiki()\n .page(year)\n .then(page => page.html() )\n .then(response => {\n fs.writeFileSync(`${outputDir}/${year}.html`, response)\n });\n}", "createDocument(html, documentId) {\n documentId = documentId || uuid()\n let documentPath = path.join(this.userLibraryDir, documentId)\n let storageArchivePath = path.join(documentPath, 'storage')\n let buffer = new FileSystemBuffer(documentPath)\n let mainFileName = 'index.html'\n let storer = new FileSystemStorer(storageArchivePath, mainFileName)\n let converter = this._getConverter(mainFileName)\n\n return storer.writeFile('index.html', 'text/html', html).then(() => {\n return converter.importDocument(\n storer,\n buffer\n ).then((manifest) => {\n return this._setLibraryRecord(documentId, manifest)\n }).then(() => {\n return documentId\n })\n })\n }", "function saveHtmlResults(html){\n let templateDir = path.join(path.resolve(__dirname,'reports','html_template'));\n\n App.Utils.Log.msg(['Saving html report to ', htmlReportingDirectory],true);\n fs.copySync(templateDir,htmlReportingDirectory);\n fs.outputFileSync(path.join(htmlReportingDirectory,'index.html'),html);\n App.Utils.Log.msg([' - COMPLETED']);\n}", "function saveDoc() {\n const currDoc = appData.currDoc();\n if (currDoc.filePath) {\n saveToFile(currDoc.filePath);\n return;\n }\n saveDocAs();\n}", "function generateDocument(inputTemplateFilename, payload) {\n const outputFileName = inputTemplateFilename+\"_\"+(Math.floor(Math.random() * 9000) + 1000)+\"_\"+Date.now();\n //Load the docx file as a binary \n var content = fs.readFileSync(path.resolve(__dirname, 'App/MortgageTemplates/'+inputTemplateFilename+'.docx'),\"binary\");\n // var content = fs.readFileSync(path.resolve(__dirname, 'App/MortgageTemplates/'+inputTemplateFilename),\"binary\");\n var zip = new PizZip(content);\n var doc;\n try {\n doc = new Docxtemplater(zip);\n } catch (error) {\n // Catch compilation errors (errors caused by the compilation of the template : misplaced tags)\n errorHandler(error);\n }\n doc.setData(payload);\n try {\n // render the document (replace all occurences of {label} )\n doc.render();\n } catch (error) {\n // Catch rendering errors (errors relating to the rendering of the template : angularParser throws an error)\n errorHandler(error);\n }\n var buf = doc.getZip().generate({ type: \"nodebuffer\" }); \n // buf is a nodejs buffer, you can either write it to a file or do anything else with it.\n fs.writeFileSync(path.resolve(__dirname, `App/morgreports/${outputFileName}.docx`),buf); \n return outputFileName;\n}", "function myExportAllStories(myExportFormat, myFolder){\n\tfor(myCounter = 0; myCounter < app.activeDocument.stories.length; myCounter++){\n fullName = app.activeDocument.fullName + \"\";\n\t\tmyStory = app.activeDocument.stories.item(myCounter);\n\t\tmyID = myStory.id;\n\t\tswitch(myExportFormat){\n\t\t\tcase 0:\n\t\t\t\tmyFormat = ExportFormat.textType;\n\t\t\t\tmyExtension = \".txt\"\n\t\t\t\tbreak;\n\t\t\tcase 1:\n\t\t\t\tmyFormat = ExportFormat.RTF;\n\t\t\t\tmyExtension = \".rtf\"\n\t\t\t\tbreak;\n\t\t\tcase 2:\n\t\t\t\tmyFormat = ExportFormat.taggedText;\n\t\t\t\tmyExtension = \".txt\"\n\t\t\t\tbreak;\n\t\t}\n\t\tmyFileName = fullName + \"_\" + myID + myExtension;\n\t\tmyFilePath = myFolder + \"/\" + myFileName;\n\t\tmyFile = new File(myFilePath); \n\t\t//myStory.exportFile(myFormat, myFile);\n //myStory.exportFile(myFormat, /c/temp/myFileName.replace('~/desk);\n alert(myFileName.toLowerCase().replace(\"~/desktop/\",\"\"));\n\t}\n}", "generate() {\n if (!fs.existsSync(this.outputPath)) {\n fs.mkdirSync(this.outputPath);\n }\n\n fs.writeFile(`${ this.outputPath }/index.html`, this.report, (err) => {\n if (err) {\n return logger.error(err);\n }\n });\n }", "function fn_downloaddoc()\n{\n\tvar filename=$('#activityfilename').val();\n\twindow.open('library/activities/library-activities-download.php?&filename='+filename,'_self');\n\treturn false;\n}", "function saveFile( docRef, fileNameBody, exportInfo) {\n switch (exportInfo.fileType) {\n case jpegIndex:\n\t docRef.bitsPerChannel = BitsPerChannelType.EIGHT;\n var saveFile = new File(exportInfo.destination + \"/\" + fileNameBody + \".jpg\");\n jpgSaveOptions = new JPEGSaveOptions();\n jpgSaveOptions.embedColorProfile = exportInfo.icc;\n jpgSaveOptions.quality = exportInfo.jpegQuality;\n docRef.saveAs(saveFile, jpgSaveOptions, true, Extension.LOWERCASE);\n break;\n case psdIndex:\n var saveFile = new File(exportInfo.destination + \"/\" + fileNameBody + \".psd\");\n psdSaveOptions = new PhotoshopSaveOptions();\n psdSaveOptions.embedColorProfile = exportInfo.icc;\n psdSaveOptions.maximizeCompatibility = exportInfo.psdMaxComp;\n docRef.saveAs(saveFile, psdSaveOptions, true, Extension.LOWERCASE);\n break;\n case tiffIndex:\n var saveFile = new File(exportInfo.destination + \"/\" + fileNameBody + \".tif\");\n tiffSaveOptions = new TiffSaveOptions();\n tiffSaveOptions.embedColorProfile = exportInfo.icc;\n tiffSaveOptions.imageCompression = exportInfo.tiffCompression;\n if (TIFFEncoding.JPEG == exportInfo.tiffCompression) {\n\t\t\t\ttiffSaveOptions.jpegQuality = exportInfo.tiffJpegQuality;\n\t\t\t}\n docRef.saveAs(saveFile, tiffSaveOptions, true, Extension.LOWERCASE);\n break;\n case pdfIndex:\n\t \tif (docRef.bitsPerChannel == BitsPerChannelType.THIRTYTWO)\n\t\t\t\tdocRef.bitsPerChannel = BitsPerChannelType.SIXTEEN;\n var saveFile = new File(exportInfo.destination + \"/\" + fileNameBody + \".pdf\");\n pdfSaveOptions = new PDFSaveOptions();\n pdfSaveOptions.embedColorProfile = exportInfo.icc;\n pdfSaveOptions.encoding = exportInfo.pdfEncoding;\n if (PDFEncoding.JPEG == exportInfo.pdfEncoding) {\n\t\t\t\tpdfSaveOptions.jpegQuality = exportInfo.pdfJpegQuality;\n\t\t\t}\n docRef.saveAs(saveFile, pdfSaveOptions, true, Extension.LOWERCASE);\n break;\n case targaIndex:\n\t \tdocRef.bitsPerChannel = BitsPerChannelType.EIGHT;\n var saveFile = new File(exportInfo.destination + \"/\" + fileNameBody + \".tga\");\n targaSaveOptions = new TargaSaveOptions();\n targaSaveOptions.resolution = exportInfo.targaDepth;\n docRef.saveAs(saveFile, targaSaveOptions, true, Extension.LOWERCASE);\n break;\n case bmpIndex:\n\t \tdocRef.bitsPerChannel = BitsPerChannelType.EIGHT;\n var saveFile = new File(exportInfo.destination + \"/\" + fileNameBody + \".bmp\");\n bmpSaveOptions = new BMPSaveOptions();\n bmpSaveOptions.depth = exportInfo.bmpDepth;\n docRef.saveAs(saveFile, bmpSaveOptions, true, Extension.LOWERCASE);\n break;\n case png8Index:\n\t\t\tsaveFile(docRef, fileNameBody, exportInfo, exportInfo.interlaced, exportInfo.transparency);\n \tfunction saveFile( docRef, fileNameBody, exportInfo, interlacedValue, transparencyValue) {\n\t\t\t\tvar id5 = charIDToTypeID( \"Expr\" );\n\t\t\t\tvar desc3 = new ActionDescriptor();\n\t\t\t\tvar id6 = charIDToTypeID( \"Usng\" );\n\t\t\t\tvar desc4 = new ActionDescriptor();\n\t\t\t\tvar id7 = charIDToTypeID( \"Op \" );\n\t\t\t\tvar id8 = charIDToTypeID( \"SWOp\" );\n\t\t\t\tvar id9 = charIDToTypeID( \"OpSa\" );\n\t\t\t\tdesc4.putEnumerated( id7, id8, id9 );\n\t\t\t\tvar id10 = charIDToTypeID( \"Fmt \" );\n\t\t\t\tvar id11 = charIDToTypeID( \"IRFm\" );\n\t\t\t\tvar id12 = charIDToTypeID( \"PNG8\" );\n\t\t\t\tdesc4.putEnumerated( id10, id11, id12 );\n\t\t\t\tvar id13 = charIDToTypeID( \"Intr\" ); //Interlaced\n\t\t\t\tdesc4.putBoolean( id13, interlacedValue );\n\t\t\t\tvar id14 = charIDToTypeID( \"RedA\" );\n\t\t\t\tvar id15 = charIDToTypeID( \"IRRd\" );\n\t\t\t\tvar id16 = charIDToTypeID( \"Prcp\" ); //Algorithm\n\t\t\t\tdesc4.putEnumerated( id14, id15, id16 );\n\t\t\t\tvar id17 = charIDToTypeID( \"RChT\" );\n\t\t\t\tdesc4.putBoolean( id17, false );\n\t\t\t\tvar id18 = charIDToTypeID( \"RChV\" );\n\t\t\t\tdesc4.putBoolean( id18, false );\n\t\t\t\tvar id19 = charIDToTypeID( \"AuRd\" );\n\t\t\t\tdesc4.putBoolean( id19, false );\n\t\t\t\tvar id20 = charIDToTypeID( \"NCol\" ); //NO. Of Colors\n\t\t\t\tdesc4.putInteger( id20, 256 );\n\t\t\t\tvar id21 = charIDToTypeID( \"Dthr\" ); //Dither\n\t\t\t\tvar id22 = charIDToTypeID( \"IRDt\" );\n\t\t\t\tvar id23 = charIDToTypeID( \"Dfsn\" ); //Dither type\n\t\t\t\tdesc4.putEnumerated( id21, id22, id23 );\n\t\t\t\tvar id24 = charIDToTypeID( \"DthA\" );\n\t\t\t\tdesc4.putInteger( id24, 100 );\n\t\t\t\tvar id25 = charIDToTypeID( \"DChS\" );\n\t\t\t\tdesc4.putInteger( id25, 0 );\n\t\t\t\tvar id26 = charIDToTypeID( \"DCUI\" );\n\t\t\t\tdesc4.putInteger( id26, 0 );\n\t\t\t\tvar id27 = charIDToTypeID( \"DChT\" );\n\t\t\t\tdesc4.putBoolean( id27, false );\n\t\t\t\tvar id28 = charIDToTypeID( \"DChV\" );\n\t\t\t\tdesc4.putBoolean( id28, false );\n\t\t\t\tvar id29 = charIDToTypeID( \"WebS\" );\n\t\t\t\tdesc4.putInteger( id29, 0 );\n\t\t\t\tvar id30 = charIDToTypeID( \"TDth\" ); //transparency dither\n\t\t\t\tvar id31 = charIDToTypeID( \"IRDt\" );\n\t\t\t\tvar id32 = charIDToTypeID( \"None\" );\n\t\t\t\tdesc4.putEnumerated( id30, id31, id32 );\n\t\t\t\tvar id33 = charIDToTypeID( \"TDtA\" );\n\t\t\t\tdesc4.putInteger( id33, 100 );\n\t\t\t\tvar id34 = charIDToTypeID( \"Trns\" ); //Transparency\n\t\t\t\tdesc4.putBoolean( id34, transparencyValue );\n\t\t\t\tvar id35 = charIDToTypeID( \"Mtt \" );\n\t\t\t\tdesc4.putBoolean( id35, true );\t\t //matte\n\t\t\t\tvar id36 = charIDToTypeID( \"MttR\" ); //matte color\n\t\t\t\tdesc4.putInteger( id36, 255 );\n\t\t\t\tvar id37 = charIDToTypeID( \"MttG\" );\n\t\t\t\tdesc4.putInteger( id37, 255 );\n\t\t\t\tvar id38 = charIDToTypeID( \"MttB\" );\n\t\t\t\tdesc4.putInteger( id38, 255 );\n\t\t\t\tvar id39 = charIDToTypeID( \"SHTM\" );\n\t\t\t\tdesc4.putBoolean( id39, false );\n\t\t\t\tvar id40 = charIDToTypeID( \"SImg\" );\n\t\t\t\tdesc4.putBoolean( id40, true );\n\t\t\t\tvar id41 = charIDToTypeID( \"SSSO\" );\n\t\t\t\tdesc4.putBoolean( id41, false );\n\t\t\t\tvar id42 = charIDToTypeID( \"SSLt\" );\n\t\t\t\tvar list1 = new ActionList();\n\t\t\t\tdesc4.putList( id42, list1 );\n\t\t\t\tvar id43 = charIDToTypeID( \"DIDr\" );\n\t\t\t\tdesc4.putBoolean( id43, false );\n\t\t\t\tvar id44 = charIDToTypeID( \"In \" );\n\t\t\t\tdesc4.putPath( id44, new File( exportInfo.destination + \"/\" + fileNameBody + \".png\") );\n\t\t\t\tvar id45 = stringIDToTypeID( \"SaveForWeb\" );\n\t\t\t\tdesc3.putObject( id6, id45, desc4 );\n\t\t\t\texecuteAction( id5, desc3, DialogModes.NO );\n\t\t\t}\n //var saveFile = new File(exportInfo.destination + \"/\" + fileNameBody + \".png\");\n //bmpSaveOptions = new BMPSaveOptions();\n //bmpSaveOptions.depth = exportInfo.bmpDepth;\n //docRef.saveAs(saveFile, bmpSaveOptions, true, Extension.LOWERCASE);\n break;\n case png24Index:\n \tsaveFile(docRef, fileNameBody, exportInfo, exportInfo.interlaced, exportInfo.transparency);\n \tfunction saveFile( docRef, fileNameBody, exportInfo, interlacedValue, transparencyValue) {\n\t\t\t\tvar id6 = charIDToTypeID( \"Expr\" );\n\t\t\t\tvar desc3 = new ActionDescriptor();\n\t\t\t\tvar id7 = charIDToTypeID( \"Usng\" );\n\t\t\t\tvar desc4 = new ActionDescriptor();\n\t\t\t\tvar id8 = charIDToTypeID( \"Op \" );\n\t\t\t\tvar id9 = charIDToTypeID( \"SWOp\" );\n\t\t\t\tvar id10 = charIDToTypeID( \"OpSa\" );\n\t\t\t\tdesc4.putEnumerated( id8, id9, id10 );\n\t\t\t\tvar id11 = charIDToTypeID( \"Fmt \" );\n\t\t\t\tvar id12 = charIDToTypeID( \"IRFm\" );\n\t\t\t\tvar id13 = charIDToTypeID( \"PN24\" );\n\t\t\t\tdesc4.putEnumerated( id11, id12, id13 );\n\t\t\t\tvar id14 = charIDToTypeID( \"Intr\" );\n\t\t\t\tdesc4.putBoolean( id14, interlacedValue );\n\t\t\t\tvar id15 = charIDToTypeID( \"Trns\" );\n\t\t\t\tdesc4.putBoolean( id15, transparencyValue );\n\t\t\t\tvar id16 = charIDToTypeID( \"Mtt \" );\n\t\t\t\tdesc4.putBoolean( id16, true );\n\t\t\t\tvar id17 = charIDToTypeID( \"MttR\" );\n\t\t\t\tdesc4.putInteger( id17, 255 );\n\t\t\t\tvar id18 = charIDToTypeID( \"MttG\" );\n\t\t\t\tdesc4.putInteger( id18, 255 );\n\t\t\t\tvar id19 = charIDToTypeID( \"MttB\" );\n\t\t\t\tdesc4.putInteger( id19, 255 );\n\t\t\t\tvar id20 = charIDToTypeID( \"SHTM\" );\n\t\t\t\tdesc4.putBoolean( id20, false );\n\t\t\t\tvar id21 = charIDToTypeID( \"SImg\" );\n\t\t\t\tdesc4.putBoolean( id21, true );\n\t\t\t\tvar id22 = charIDToTypeID( \"SSSO\" );\n\t\t\t\tdesc4.putBoolean( id22, false );\n\t\t\t\tvar id23 = charIDToTypeID( \"SSLt\" );\n\t\t\t\tvar list1 = new ActionList();\n\t\t\t\tdesc4.putList( id23, list1 );\n\t\t\t\tvar id24 = charIDToTypeID( \"DIDr\" );\n\t\t\t\tdesc4.putBoolean( id24, false );\n\t\t\t\tvar id25 = charIDToTypeID( \"In \" );\n\t\t\t\tdesc4.putPath( id25, new File( exportInfo.destination + \"/\" + fileNameBody + \".png\") );\n\t\t\t\tvar id26 = stringIDToTypeID( \"SaveForWeb\" );\n\t\t\t\tdesc3.putObject( id7, id26, desc4 );\n\t\t\t\texecuteAction( id6, desc3, DialogModes.NO );\n\t\t\t}\n \n //var saveFile = new File(exportInfo.destination + \"/\" + fileNameBody + \".png\");\n //bmpSaveOptions = new BMPSaveOptions();\n //bmpSaveOptions.depth = exportInfo.bmpDepth;\n //docRef.saveAs(saveFile, bmpSaveOptions, true, Extension.LOWERCASE);\n break;\n default:\n if ( DialogModes.NO != app.playbackDisplayDialogs ) {\n alert(strUnexpectedError);\n }\n break;\n }\n}", "function exportNewWb(newWb, outputSheet) {\n XLSX.writeFile(newWb, outputSheet);\n}", "function convertPdftoDoc(){\n // Recupera a planilha e a aba ativas\n var ss = SpreadsheetApp.getActiveSpreadsheet();\n var ssid = ss.getId();\n \n // Procura dentro da mesma pasta da planilha atual\n var ssparents = DriveApp.getFileById(ssid).getParents();\n var sheet = ss.getActiveSheet(); \n // Percorre todos os arquivos\n var folder = ssparents.next();\n var files = folder.getFiles();\n var i=1;\n //var dir = DriveApp.getFolder();\n\n while(files.hasNext()) {\n var file = files.next();\n if(ss.getId() == file.getId()){ \n continue; \n }\n \n var fileBlob = DriveApp.getFileById(file.getId()).getBlob(); \n var resource = {\n title: fileBlob.getName(),\n \"parents\": [{'id':folder.getId()}], \n mimeType: fileBlob.getContentType()\n };\n var options = {\n ocr: true\n };\n \n var docFile = Drive.Files.insert(resource, fileBlob, options); \n // var dir = DriveApp.getFoldersByName('leitura dos pdfs').next();\n \n Logger.log(docFile.alternateLink); \n }\n \n}", "function downloadGDocContent(fileId, callback) {\t\n\tgetFileMeta(fileId,function(file){\n\t\t//console.log(file);\t\t\n\t\t//only non-google-drive created file have downloadURL, i.e. your uploaded files each has a downloadURL\n\t\t//If the document is created in Google, it has exportLinks and we use exportLink as the downloadLink\n\t\tif (file['exportLinks']){\n\t\t\tvar exportLinks = file['exportLinks'];\n\t\t\tvar plainTxtLink = exportLinks['text/plain'];\n\n\t\t\t//Get content through xml http request\n\t\t\tvar accessToken = gapi.auth.getToken().access_token;\n\t\t\tvar xhr = new XMLHttpRequest();\n\t\t\txhr.open('GET', plainTxtLink);\n\t\t\txhr.setRequestHeader('Authorization', 'Bearer ' + accessToken);\n\t\t\txhr.onload = function() {\n\t\t\t\t//console.log(\"this is the content\",xhr.responseText);\n\n\t\t\t\t//Callback function\n\t\t\t\tcallback && callback(xhr.responseText);\n\t\t\t};\n\n\t\t\t//Error messages\n\t\t\txhr.onerror = function() {\n\t\t\t\tconsole.log(\"Download Gdoc content error\");\n\t\t\t};\n\t\t\txhr.send(); // establish a connection\n\n\t\t}else{\n\t\t\tconsole.log(\"Fail to download Gdoc content.\");\n\t\t};\n\t});\n}", "function renderDocument(document, targetPath, level) {\n var outputDocument = deepcopy(document);\n\n //prepare relative url path\n outputDocument.relativeUrlPath = (new Array(level+1)).join('../');\n\n //prepare document menu\n var documentMenu = deepcopy(documentationMenu);\n markCurrentMenuItems(documentMenu, document.id);\n\n //render markdown\n var renderer = new marked.Renderer();\n renderer.image = function(href, title, text) {\n var externalUrlPattern = /^https?:\\/\\//i;\n if(!externalUrlPattern.test(href)) {\n href = outputDocument.relativeUrlPath + 'img/' + href;\n }\n title = title ? title : '';\n return '<img src=\"'+href+'\" title=\"'+title+'\" alt=\"'+text+'\">';\n };\n try {\n outputDocument.content = marked(document.content, {renderer: renderer});\n } catch(err) {\n log.error('Error occurred while rendering content of page \"%s\" (%s)', targetPath, err.message);\n process.exit(1);\n }\n\n //render swig template\n var pageContent = '';\n try {\n pageContent = compiledPageTemplate({\n config: docConfig,\n menu: documentMenu,\n document: outputDocument\n });\n } catch(err) {\n log.error('Error occurred while rendering page template for file \"%s\" (%s)', targetPath, err.message);\n process.exit(1);\n }\n\n //write into file\n try {\n fs.writeFileSync(targetPath, pageContent);\n } catch(err) {\n log.error('Error occurred while writing file \"%s\" (%s)', targetPath, err.message);\n process.exit(1);\n }\n}", "function downloadFileWeb(ext){\n\tvar text = getStringJSON(globalMAINCONFIG[pageCanvas]);\n\tvar filename = document.getElementById(\"saveConfFileName\").value;\n\tvar splitfile=filename.split(\".\");\n\tvar blob = new Blob([text], {type: \"text/plain;charset=utf-8\"});\n\n\tif(splitfile.length==1){\n\t\tif(ext==\"titan\"){\n\t\t\tsaveAs(blob, filename+\".titan\");\n\t\t}\n\t\telse if(ext==\"topo\"){\n\t\t\tsaveAs(blob, filename+\".topo\");\n\t\t}\n\t\telse{\n\t\t\tvar name = filename+\".xml\";\n\t\t\ttext = getXmlData(name);\n\t\t\tblob = new Blob([text], {type: \"text/plain;charset=utf-8\"});\n\t\t\tsaveAs(blob, filename+\".xml\");\n\t\t}\n\t}else{\n\t\tif(ext==\"titan\"){\n\t\t\tsaveAs(blob, filename);\n\t\t}\n\t\telse if(ext==\"topo\"){\n\t\t\tsaveAs(blob, filename);\n\t\t}\n\t\telse{\n\t\t\ttext = getXmlData(filename);\n\t\t\tblob = new Blob([text], {type: \"text/plain;charset=utf-8\"});\n\t\t\tsaveAs(blob, filename);\n\t\t}\n\t}\n\t$(\"#configPopUp\").dialog('destroy');\n}", "downloadSpreadsheet() {\n if (this.reportKey !== null) {\n window.open(this.properties.reportServerUrl + '?key=' + this.reportKey + '&outputFormat=xlsx', '_blank');\n }\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
minusOne operand by right side
function minusOne() { setExpression((minus) => { minus = minus + ''; return minus .split('') .slice(0, minus.length - 1) .join(''); }); }
[ "function removeMultiplicationByNegativeOne(node) {\n if (node.op !== '*') {\n return Node.Status.noChange(node);\n }\n const minusOneIndex = node.args.findIndex(arg => {\n return Node.Type.isConstant(arg) && arg.value === '-1';\n });\n if (minusOneIndex < 0) {\n return Node.Status.noChange(node);\n }\n\n // We might merge/combine the negative one into another node. This stores\n // the index of that other node in the arg list.\n let nodeToCombineIndex;\n // If minus one is the last term, maybe combine with the term before\n if (minusOneIndex + 1 === node.args.length) {\n nodeToCombineIndex = minusOneIndex - 1;\n }\n else {\n nodeToCombineIndex = minusOneIndex + 1;\n }\n\n let nodeToCombine = node.args[nodeToCombineIndex];\n // If it's a constant, the combining of those terms is handled elsewhere.\n if (Node.Type.isConstant(nodeToCombine)) {\n return Node.Status.noChange(node);\n }\n\n let newNode = node.cloneDeep();\n\n // Get rid of the -1\n nodeToCombine = Negative.negate(nodeToCombine.cloneDeep());\n\n // replace the node next to -1 and remove -1\n newNode.args[nodeToCombineIndex] = nodeToCombine;\n newNode.args.splice(minusOneIndex, 1);\n\n // if there's only one operand left, move it up the tree\n if (newNode.args.length === 1) {\n newNode = newNode.args[0];\n }\n return Node.Status.nodeChanged(\n ChangeTypes.REMOVE_MULTIPLYING_BY_NEGATIVE_ONE, node, newNode);\n}", "minus() {\n this._lastX = this.pop();\n let first = this.pop();\n this._stack.push(first - this._lastX);\n }", "function unaryExpr(stream, a) {\n if (stream.trypop('-')) {\n var e = unaryExpr(stream, a);\n if (null == e) throw new XPathException(XPathException.INVALID_EXPRESSION_ERR, 'Position ' + stream.position() + ': Expected unary expression after -');\n return a.node('UnaryMinus', e);\n } else return unionExpr(stream, a);\n }", "function isNegativeIndexExpression(node, expectedIndexedNode) {\n return ((node.type === utils_1.AST_NODE_TYPES.UnaryExpression &&\n node.operator === '-') ||\n (node.type === utils_1.AST_NODE_TYPES.BinaryExpression &&\n node.operator === '-' &&\n isLengthExpression(node.left, expectedIndexedNode)));\n }", "negate() {\n return new Vector2(-this.x, -this.y);\n }", "function SUBTRACT() {\n for (var _len14 = arguments.length, values = Array(_len14), _key14 = 0; _key14 < _len14; _key14++) {\n values[_key14] = arguments[_key14];\n }\n\n // Return `#NA!` if 2 arguments are not provided.\n if (values.length !== 2) {\n return error$2.na;\n }\n\n // decompose values into a and b.\n var a = values[0];\n var b = values[1];\n\n // Return `#VALUE!` if either a or b is not a number.\n\n if (!ISNUMBER(a) || !ISNUMBER(b)) {\n return error$2.value;\n }\n\n // Return the difference.\n return a - b;\n}", "function evaluateNeg(assignment){\n var myString = \"\";\n while (globalMarker < assignment.length && assignment[globalMarker] == \"neg\"){\n globalMarker += 1;\n myString += \"!\"\n }\n myString += evaluateParen(assignment);\n return eval(myString);\n}", "function mySubtractFunction(number1, number2) {\n console.log(number1 - number2);\n}", "substractionCalculation(expression){\n //makes ifFirstNumberNegative equal to the return value of firstNumberNegative\n let isFirstNumberNegative = this.firstNumberNegative(expression)\n let expressionArray;\n //if isFirstNumberNegative is truthy, then we will use the value that gets returned to slice the expression at the correct\n //- index.\n if(isFirstNumberNegative){\n expressionArray = [];\n expressionArray.push(expression.slice(0, isFirstNumberNegative));\n expressionArray.push(expression.slice((isFirstNumberNegative + 1)));\n //if isFirstNumberNegative is falsy, we will split the expression by -.\n }else{\n expressionArray = expression.split(\"-\");\n }\n let substraction = Number(expressionArray[0]) - Number(expressionArray[1]);\n\n return substraction.toString();\n }", "clearNegatives(expression) {\n if(!expression.includes(\"-\")){\n return expression;\n }\n\n let expressionArr = expression.split(\"\");\n\n for(let i = 0; i < expressionArr.length; i++){\n // if the char at i is \"-\" and the char at i - 1 is +, then we will make the element at index i - 1 an empty string to make \n //the expression into a substraction instead. the char at i and the char at i - 1 are both -, that means we can make the expression\n //into an addition instead by making the element at i - 1 to + and the element at i to an empty string.\n //9--1 would eventually become 9+1\n if(expressionArr[i] === \"-\" && expressionArr[i - 1] === \"+\"){\n expressionArr.splice((i - 1), 1, \"\")\n }else if(expressionArr[i] === \"-\" && expressionArr[i - 1] === \"-\"){\n expressionArr.splice((i - 1), 1, \"+\");\n expressionArr.splice(i, 1, \"\");\n i = i - 2;\n };\n\n };\n\n return expressionArr.join(\"\");\n }", "function negation(){\n while (globalTP < tokens.length && tokens[globalTP] == \"neg\"){\n globalTP+=1;\n }\n quant();\n}", "function OuterDoubleNegationElimination(expr) {\r\n\tif (expr.type == Expressions.TYPE_NEGATION && expr.expr.type == Expressions.TYPE_NEGATION) {\r\n\t\treturn OuterDoubleNegationElimination(expr.expr.expr); // Return the innermost expression.\r\n\t}\r\n\treturn expr;\r\n}", "function invertNum(num)\n{\n\treturn num *= -1;\n}", "handleSubtraction() {\n const left = this.getSelectValue(\"subtract\", 1);\n const right = this.getSelectValue(\"subtract\", 2);\n const matrices = this.getMatrices(left, right);\n\n if (matrices !== null) {\n try {\n const difference = matrices[0].matrixAddition(matrices[1], false);\n this.displayResults(matrices[0], \"-\", matrices[1], \"=\", difference);\n } catch (error) {\n alert(\"Rows and columns of the matrices must match.\");\n }\n }\n }", "negate() {\n return new Vector3(-this.x, -this.y, -this.z);\n }", "clickMinusOrdinary() {\n\t\t$(document).on('click', '#minus-ordinary', () => {\n\t\t\tlet number = Number($('#number-ordinary').text());\n\t\t\tif (number !== 0) {\n\t\t\t\tnumber -= 1;\n\t\t\t\t$('#number-ordinary').html(number);\n\t\t\t}\n\t\t\tthis.onRendered();\n\t\t\tthis.auditorium.render();\n\t\t\tBooking.markedSeats = [];\n\t\t});\n\t}", "DEY() { this.eqFlags_(--this.Y); }", "negate() {\n return new Vector4(-this.x, -this.y, -this.z, -this.w);\n }", "function subtract(str1, str2) {\n var end = endNumber(str1);\n var start = startNumber(str2);\n //if missing a value, setting to 0 ensures that the subtraction will not be\n //affected\n if(!start.value) {\n start.value = 0;\n }\n if(!end.value) {\n end.value = 0;\n }\n var diff = end.value - start.value;\n return end.remainder + diff.toString() + start.remainder;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
checking that the it has less than 100 words
function checkWordCount(inputMessage) { var input = inputMessage; var newInput = input.split(" "); if (newInput.length >= 100) { console.log("input with less than 100", newInput); return false; }; }
[ "function longWord (input) {\n return input.some(x => x.length > 10);\n}", "function checkWordCount(input) {\n\t\tconsole.log(\"count words... \", input);\n\t\tvar output = input.split(\" \").length;\n\t\tconsole.log(output);\n\t\tif (output < 100) {\n\t\t\tconsole.log(\"you have entered < 100 words \", output);\n\t\t\treturn true;\n\t\t} else {\n\t\t\tconsole.log(\"you cannot entered > 100 words \", output);\n\t\t\treturn false;\n\t\t}\n\t}", "function wordsLongerThanThree(str) {\n // TODO: your code here \n str = str.split(\" \");\n return filter(str, function(value){\n return value.length > 3;\n });\n}", "countBigWords(input) {\n // Set a counter equal to 0\n let counter = 0;\n // Split the input into words\n let temp = input.split(\" \");\n // Determine the length of each word by iterating over the array\n //If the word is greater than 6 letters, add 1 to a counter\n // If the word is less than or equal to 6 letters, go on to next word\n for(let i = 0; i < temp.length; i++) {\n if (temp[i].length > 6) {\n counter++;\n }\n }\n // Output the counter\n return counter;\n }", "function filterLongWords(str,n){\n var longWords=[];\n var arr=str.split(' ');\n for(var i=0;i<arr.length;i++){\n if(arr[i].length>n){\n longWords.push(arr[i]);\n }\n }\n return longWords;\n}", "function millionOrMore(data) {\n return data.romanSearchResults > 1000000;\n}", "function scoreOneWord(s) {\n if (s.length < 3) {\n return 1;\n } else if (s.length < 5) {\n return 1;\n } else {\n return 1;\n }\n}", "overflown() {\n let _this = this;\n\n return this.result.split('\\n').some((line) => {\n return line.length > _this.config['max-len'];\n });\n }", "static evalShortTextLengthWithinLimit(dict, limit) {\n return (dict.ShortTextNote.length <= Number(limit));\n }", "function fittingWords(str, strArr){\n var strLength = str.length;\n var retArr = [];\n for (var i = 0; i < strArr.length; i++){\n if (strArr[i].length > strLength) retArr.push(strArr[i]);\n }\n return retArr;\n}", "function longWords(arr) {\n let newWordsArr = [];\n for (let i = 0; i < arr.length; i++) {\n if (arr[i].length >= 5) {\n newWordsArr.push(arr[i]);\n }\n }\n return newWordsArr;\n}", "checkForcedWidth() {\n var maximum_string_width = 0;\n\n for(var i=0;i<this.dispatcher.split_words.length;i++) {\n var block = this.dispatcher.split_words[i];\n if(block.match(/^\\s+$/)) { // только строка из пробелов совершает word-break, так что её не проверяем\n continue;\n }\n if(maximum_string_width < this.getStringWidth(block)) {\n maximum_string_width = this.getStringWidth(block);\n }\n }\n\n for(var i=0;i<99;i++) {\n var proposed_width = i * this.border_size;\n if(proposed_width > maximum_string_width) {\n this.forced_width = i;\n break;\n }\n }\n }", "function percentageMatureWords() {\n\tvar wordCount = 0;\n\tvar matureWordCount = 0;\n\t\n\tvar allElements = document.body.getElementsByTagName(\"*\");\n\tfor (i = 0; i < allElements.length; i++) {\n\t\tif (allElements[i].tagName.toLowerCase() === \"script\") continue;\n\t\tif (allElements[i].childNodes.length == 1 && !allElements[i].firstChild.tagName) {\n\t\t\t//console.log(allElements[i]);\n\t\t\tvar words = allElements[i].innerHTML.trim().replace(/[^\\w\\s]/gi, '').toLowerCase().split(\" \");\n\t\t\tconsole.log(words);\n\t\t\tfor (j = 0; j < words.length; j++) {\n\t\t\t\twordCount++;\n\t\t\t\tif (binarySearch(potentiallyNSFWKeywords, words[j], 0, potentiallyNSFWKeywords.length - 1) > -1) {\n\t\t\t\t\tmatureWordCount++;\n\t\t\t\t\tconsole.log(words[j]);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t\n\tif (wordCount === 0)\n\t\treturn;\n\t\n\tvar percentMatureWords = (matureWordCount / wordCount) * 100;\n\tif (percentMatureWords > 5)\n\t\tisBadPage();\n\t\n\tconsole.log(\"wordCount: \" + wordCount + \". matureWordCount: \" + matureWordCount + \". %: \" + percentMatureWords);\n}", "function filterLongWords(arrayOfWords, i) {\n if (!arrayOfWords || typeof i !== \"number\") return undefined;\n return arrayOfWords.filter(function (word, idx, array) {\n return ('' + word).length > i;\n }, []);\n}", "function tooManyWords(){\n\t\n\tanswer = prompt(\"Please enter a phrase...\");\n\t\n\tif (answer == null || typeof answer == undefined) {\n\t return;\n\t}\n\t // if empty string pass display message\n\t answer.trim();\n\t if (answer.length == 0) {\n\t \talert(\"Acronym can not be created using empty string\");\n\t }\t\n\t // copy split data to temp variable \n\t var temp_line = answer.split(\" \");\n\t \n\t var acronym =\"\";\n\t var acronym_line =\"\";\n\t \n\t for ( var i = 0; i <temp_line.length; i++){\n\t\t // create acronym \n\t\t acronym += temp_line[i].charAt(0).toUpperCase(); \n\t\t \n\t\t //copy acronym line with first letter upper case\n\t\t acronym_line += temp_line[i].charAt(0).toUpperCase();\n\t\t acronym_line += temp_line[i].substring(1, temp_line[i].length);\n\t\t acronym_line += \" \";\n\t\t \n\t }\t \n\t // display acronym to user\n\t alert (acronym + \" stands for \" + acronym_line);\n\t \n\t // count number of acronym created by user\n acronyms++;\n\t \n}", "function setMaxCharacterCount() {\n if ($(\".word\").width() <= 335) {\n return 8;\n } else if ($(\".word\").width() <= 425) {\n return 9;\n } else if ($(\".word\").width() <= 490) {\n return 10;\n } else if ($(\".word\").width() <= 510) {\n return 11;\n } else {\n return 12;\n }\n }", "static validateShortTextExceedsLength(pageClientAPI, dict) {\n\n //New short text length must be <= global maximum\n let max = libCom.getAppParam(pageClientAPI, 'MEASURINGPOINT', 'ShortTextLength');\n\n if (libThis.evalShortTextLengthWithinLimit(dict, max)) {\n return Promise.resolve(true);\n } else {\n let dynamicParams = [max];\n let message = pageClientAPI.localizeText('validation_maximum_field_length', dynamicParams);\n libCom.setInlineControlError(pageClientAPI, libCom.getControlProxy(pageClientAPI, 'ShortTextNote'), message);\n dict.InlineErrorsExist = true;\n return Promise.reject(false);\n }\n }", "function checkOperationLength() {\n if (displayEl.textContent.length > 10) {return false;}\n}", "function well(x){\n let goodArr = x.filter(word => word === 'good')\n if(goodArr.length > 2){\n return 'I smell a series!'\n }else if (goodArr.length > 0){\n return \"Publish!\"\n }else{\n return 'Fail!'\n }\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return a cloned version of 'e' having 'target' as its target property; cancel the original event.
function retargetMouseEvent(e, target) { var clonedEvent = document.createEvent("MouseEvent"); clonedEvent.initMouseEvent(e.type, e.bubbles, e.cancelable, e.view, e.detail, e.screenX, e.screenY, e.clientX, e.clientY, e.ctrlKey, e.altKey, e.shiftKey, e.metaKey, e.button, e.relatedTarget); // Object.defineProperty(clonedEvent, "target", {value: target}); clonedEvent.forwardedTouchEvent = e.forwardedTouchEvent; // IE 9+ creates events with pageX and pageY set to 0. // Trying to modify the properties throws an error, // so we define getters to return the correct values. // Solution based on the approach used in: https://github.com/jquery/jquery-simulate if (clonedEvent.pageX === 0 && clonedEvent.pageY === 0 && Object.defineProperty) { var doc = document.documentElement; var body = document.body; var clientX = e.clientX; var clientY = e.clientY; Object.defineProperty(clonedEvent, "pageX", { get: function() { return clientX + (doc && doc.scrollLeft || body && body.scrollLeft || 0) - (doc && doc.clientLeft || body && body.clientLeft || 0); } }); Object.defineProperty(clonedEvent, "pageY", { get: function() { return clientY + (doc && doc.scrollTop || body && body.scrollTop || 0) - (doc && doc.clientTop || body && body.clientTop || 0); } }); } return clonedEvent; }
[ "function cancelbubbling(e) {\n Event.stop(e);\n }", "function getTarget(e)\r\n{\r\n\tvar value;\r\n\tif(checkBrowser() == \"ie\")\r\n\t{\r\n\t\tvalue = window.event.srcElement;\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvalue = e.target;\r\n\t}\r\n\treturn value;\r\n}", "function extendEvent(e) {\n if (typeof window.addEventListener === 'function') {\n } else {\n e.stopPropagation = function() {\n e.cancelBubble = true;\n };\n\n e.preventDefault = function() {\n e.returnValue = false;\n };\n }\n if (!e.target && e.srcElement) {\n e.target = e.srcElement;\n }\n return e;\n }", "function createClick(e) {\n // TODO. Does copying the properties adequately capture all the semantics of the click event?\n var clonedEvent = document.createEvent(\"MouseEvent\");\n clonedEvent.initMouseEvent('click', true, e.cancelable, e.view, e.detail, e.screenX, e.screenY, e.clientX, e.clientY, e.ctrlKey, e.altKey, e.shiftKey, e.metaKey, e.button, e.relatedTarget);\n return clonedEvent;\n }", "function getParent(eventTarget) {\n return isNode(eventTarget) ? eventTarget.parentNode : null;\n }", "function createMouseEvent(e, type, relatedTarget) {\n var clonedEvent = document.createEvent(\"MouseEvent\");\n clonedEvent.initMouseEvent(type, e.bubbles, e.cancelable, e.view, e.detail, e.screenX, e.screenY, e.clientX, e.clientY, e.ctrlKey, e.altKey, e.shiftKey, e.metaKey, e.button, relatedTarget || e.relatedTarget);\n return clonedEvent;\n }", "function getTargetNode(event) {\n\tif (event.target) {\n\t\treturn event.target;\n\t} else if (event.srcElement) {\n\t\treturn event.srcElement;\t\n\t} else {\n\t\treturn null;\t\n\t}\n}", "_getUpEventTarget(originalTarget) {\n const that = this;\n let target = originalTarget;\n\n while (target) {\n if (target instanceof JQX.ListItem && target.ownerListBox === that.$.listBox) {\n if (target.unselectable || target.disabled) {\n return;\n }\n\n target = 'item';\n break;\n }\n else if (target === that.$.dropDownContainer) {\n target = 'dropDownContainer';\n break;\n }\n\n target = target.parentElement;\n }\n\n if (that.enableShadowDOM && target !== null) {\n target = originalTarget.getRootNode().host;\n\n while (target) {\n if (target === that.$.dropDownContainer) {\n target = 'dropDownContainer';\n break;\n }\n\n target = target.parentElement;\n }\n }\n\n return target;\n }", "function cancelBubble(event) {\r\n\r\n if (event.stopPropagation) {\r\n event.stopPropagation();\r\n } else {\r\n event.cancelBubble = true;\r\n }\r\n}", "function eventPreventer(event) {\r\n\tif ( typeof event.target === 'object' && event.target ) {\r\n\t\tevent.preventDefault();\r\n\t}\r\n}", "_normalizeEvent(event) {\n const rootElement = this.eventManager.getElement();\n return { ...event,\n ...Object(_event_utils__WEBPACK_IMPORTED_MODULE_0__[\"whichButtons\"])(event),\n ...Object(_event_utils__WEBPACK_IMPORTED_MODULE_0__[\"getOffsetPosition\"])(event, rootElement),\n preventDefault: () => {\n event.srcEvent.preventDefault();\n },\n stopImmediatePropagation: null,\n stopPropagation: null,\n handled: false,\n rootElement\n };\n }", "function _editTextBlockCancel ( /*[Object] event*/ e ) {\n\t\te.preventDefault();\n\t\tcloseEditTextBar();\n\t\tcnv.discardActiveObject();\n\t\treturn false;\n\t}", "function cancel(ev) {\n // Set that we should cancel the tap\n cancelled = true;\n // Remove selection on the target item\n $item.removeClass(options.klass);\n // We do not need cancel callbacks anymore\n $el.unbind('drag.tss hold.tss');\n }", "function inspectorCancel(e) {\r\n if (e.which === 27) {\r\n cancelInspector();\r\n }\r\n }", "function onClick(e) {\n if (e.target === target) {\n store.dispatch(boxUnfocused());\n }\n }", "function cancelWheel(e) {\n e = e || window.event;\n e.preventDefault ? e.preventDefault() : (e.returnValue = false);\n }", "get target() {\n\t\treturn this.#target;\n\t}", "function deactivateTargetPawnClickHandler(){\n\t\tcurrentlySelectedPawn = null;\n\n\t\tcurrentPawnList.forEach(function(targetPawn){\n\t\t\ttargetPawn.highlight(true);\n\t\t\ttargetPawn.alpha = 1;\n\t\t\tmakePawnSelectable(targetPawn);\n\t\t});\n\n\t\tBlockSelectabilityLogic.makeBoardBlocksUnselectable();\n\t\tthis.off('click', deactivateTargetPawnClickHandler);\n\t}", "dupHandle(shouldCopyEventListeners = true) {\n const duplicatedHandle = new Curl(this.handle.dupHandle());\n const eventsToCopy = ['end', 'error', 'data', 'header'];\n duplicatedHandle.features = this.features;\n if (shouldCopyEventListeners) {\n for (let i = 0; i < eventsToCopy.length; i += 1) {\n const listeners = this.listeners(eventsToCopy[i]);\n for (let j = 0; j < listeners.length; j += 1) {\n duplicatedHandle.on(eventsToCopy[i], listeners[j]);\n }\n }\n }\n return duplicatedHandle;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
an add measurement button was clicked
function addMeasurement(event) { event.stopPropagation(); // show the add measurement section for the associated measurement type and jump to it var btnID_pieces = $(this).attr('id').split('_'); var form_type = btnID_pieces[0]; var meas_type = btnID_pieces[1]; showFormSection(meas_type, form_type); window.location.assign('#add_' + meas_type + '_section'); }
[ "function pressAdd() {\n\thandleAddSub(PLUS);\n}", "clickPlusPensioner() {\n\t\t$(document).on('click', '#plus-pensioner', () => {\n\t\t\tlet number = Number($('#number-pensioner').text());\n\t\t\tnumber += 1;\n\t\t\t$('#number-pensioner').html(number);\n\t\t\tthis.onRendered();\n\t\t});\n\t}", "function addClicked() {\n addStudent();\n updateData();\n clearAddStudentForm();\n}", "onAddMealButtonPressed(event) {\n\t\tthis.addMeal();\n\t}", "function addPoints() {\n points += pointMulti;\n clickcount++;\n pointsfromclick += pointMulti;\n totalpoints += pointMulti;\n document.getElementById(\"clickcount\").innerHTML = \"You have \" + clickcount + \" total clicks.\";\n document.getElementById(\"pointsfromclick\").innerHTML = \"You have made \" + pointsfromclick + \" bread objects from clicking.\";\n document.getElementById(\"totalpointcount\").innerHTML = \"You have made \" + totalpoints + \" total bread objects.\";\n var pointsArea = document.getElementById(\"pointdisplay\");\n pointsArea.innerHTML = \"You have \" + Math.round(points) + \" bread objects!\";\n if(points >= 1 && buyupgrade === 0) {\n var multiply_button = document.getElementById(\"btn_multiply\");\n multiply_button.style.display = \"inline\";\n }\n }", "function rtGuiClick() { rtGuiAdd(this.id); }", "function addDigit() {\n $(\".number\").on(\"click\", function() {\n clearResult();\n var digit = $(this).data(\"value\");\n concatInput(digit);\n var newValue = $(\".display-bar\").data(\"currentInput\");\n displayValue(newValue);\n });\n}", "onAddVisitButtonPressed(event) {\n\t\tthis.showVisit();\n\t}", "clickPlusChild() {\n\t\t$(document).on('click', '#plus-child', () => {\n\t\t\tlet number = Number($('#number-child').text());\n\t\t\tnumber += 1;\n\t\t\t$('#number-child').html(number);\n\t\t\tthis.onRendered();\n\t\t});\n\t}", "function addButtons() {\n target.css({\n 'border-width': '5px'\n });\n //console.log(\"INSIDE addButtons, thisID: \" + thisId + \" and thisKittenId: \" + thisKittenId);\n // append the delete and edit buttons, with data of metric document id, and kitten document id\n target.append(\"<button type='button' class='btn btn-default btn-xs littleX' data_idKitten=\" + \n thisKittenId + \" data_id=\" + \n thisId + \"><span class='glyphicon glyphicon-remove' aria-hidden='true'></span></button>\");\n target.append(\"<button type='button' class='btn btn-default btn-xs littleE' data_idKitten=\" + \n thisKittenId + \" data_id=\" + \n thisId + \"><span class='glyphicon glyphicon-pencil' aria-hidden='true'></span></button>\");\n // set boolean to true that delete and edit buttons exist\n littleButton = true;\n }", "function addButton(size) {\r\n\r\n}", "function setActiveWidget(type) {\n switch (type) {\n // if measure distance is clicked\n case \"distance\":\n activeWidget = new DistanceMeasurement2D({\n viewModel: {\n view: view,\n mode: \"geodesic\",\n unit: \"feet\"\n }\n });\n\n // skip the initial 'new measurement' button\n activeWidget.viewModel.newMeasurement();\n \n // add the widget window to the view on the bottom right\n view.ui.add(activeWidget, \"bottom-right\");\n \n setActiveButton(document.getElementById(\"distanceButton\"));\n break;\n \n // if measure area button is clicked \n case \"area\":\n activeWidget = new AreaMeasurement2D({\n viewModel: {\n view: view,\n mode: \"planar\",\n unit: \"square-feet\"\n }\n });\n\n // skip the initial 'new measurement' button\n activeWidget.viewModel.newMeasurement();\n\n view.ui.add(activeWidget, \"bottom-right\");\n setActiveButton(document.getElementById(\"areaButton\"));\n break;\n \n case null:\n if (activeWidget) {\n view.ui.remove(activeWidget);\n activeWidget.destroy();\n activeWidget = null;\n }\n break;\n }\n }", "function _btnWeight() {\n //Working\n console.log(\"doing something\");\n }", "function handleClickAddMov() {\r\n alert(`Wow, you added the movie ${title} to your watch list!`);\r\n props.onAdd(id, title, banner, watched);\r\n props.onRemove(id);\r\n }", "handleAddition() {\n const left = this.getSelectValue(\"add\", 1);\n const right = this.getSelectValue(\"add\", 2);\n const matrices = this.getMatrices(left, right);\n\n if (matrices !== null) {\n try {\n const sum = matrices[0].matrixAddition(matrices[1], true);\n this.displayResults(matrices[0], \"+\", matrices[1], \"=\", sum);\n } catch (error) {\n alert(\"Rows and columns of the matrices must match.\");\n }\n }\n }", "function add_room_click() {\n $('li[data-level=\"one\"]').off();\n $('li[data-level=\"one\"]').click(function() {\n if ($('body').hasClass('selecting')) {\n var gridster_id = $(this).attr('data-id');\n var current_gridster = gridsters_holder[gridster_id];\n var html = '<li class=\"workstation type-one\"><div class=\"delete\"></div></li>';\n var coords = get_free_coords(current_gridster);\n console.log(coords);\n // if found a free spot, create the station widget and add change and delete event handlers to it\n if (coords) {\n var new_workstation = current_gridster.add_widget(html, 1, 1, coords.col, coords.row);\n new_workstation.click(function(event) {\n event.stopPropagation();\n change_station_type($(this));\n });\n new_workstation.find('.delete').click(function(event) {\n event.stopPropagation();\n delete_workstation($(this));\n });\n }\n }\n });\n }", "function AddAlert(){\n\t\t\t\talert(\"You already added a score of \" + boxCtrl.value + \" to this box.\");\n\t\t\t}", "function addExercise() {\n // Grab ui inputs\n let name = document.querySelector(el.exerciseInput);\n let weight = document.querySelector(el.weightInput);\n\n // Add exercise to DS\n exercise.addExercise(name.value, weight.value);\n\n // Get recently added exercise\n let current = exercise.getCurrentExercise();\n\n // Display new exercise from data state to ui\n ui.addExercise(current.id, current.name, current.weight);\n\n // Clear input values\n name.value = \"\";\n weight.value = \"\";\n }", "function addListItem(ppNumber) {\n \n document.getElementById('min').style.display = \"none\";\n document.getElementById('max').style.display = \"none\";\n document.getElementById('addps-submit').style.display = \"none\";\n document.getElementById('addps-button').style.display = \"block\";\n $(\"#added\").append('<tr id=ps-list-item-'+ ppNumber + '><td>' + $(\"#pp-1-name\").val() + '</td><td>' + $(\"#pp-1-cost\").val() + '</td><td>' + $(\"#pp-1-co2\").val() +'</td><td><a href=\"javascript:%20deletePowerSource(%22powerPlant'+ ppNumber +'%22);\"><img src=\"images/deleteButton.png\"></a></td></tr>');\n $(\"#new-ps\").html('<tr><td>&nbsp</td><td>&nbsp</td><td>&nbsp</td></tr><tr><td><input type=\"text\" id=\"pp-1-name\" placeholder=\"New Power Plant Name\" class=\"pp-name\"></td><td><input type=\"text\" id=\"pp-1-cost\" placeholder=\"Cost\" class=\"pp-cost\"></td><td><input type=\"text\" id=\"pp-1-co2\" placeholder=\"CO2\" class=\"pp-co2\"></td></tr>');\n $(\"#color-legend tbody tr.data\").remove();\n sharedElectricData.updateVariableArray();\n shifting.output.updateVariableArray();\n updatePowerPlantLegend();\n $(\"#dragsimulate\").trigger(\"customDragEvent\");\n }", "createButton () {\n\n this.button = document.createElement('button')\n\n this.button.title = 'This model has multiple views ...'\n\n this.button.className = 'viewable-selector btn'\n\n this.button.onclick = () => {\n this.showPanel(true)\n }\n\n const span = document.createElement('span')\n span.className = 'fa fa-list-ul'\n this.button.appendChild(span)\n\n const label = document.createElement('label')\n this.button.appendChild(label)\n label.innerHTML = 'Views'\n \n this.viewer.container.appendChild(this.button)\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
grants permissions to users and groups in access_list permissions indicated by perm to a resource indicate by resType and resID if user or group does not exist, it is automatically created. granter is made owner of the new group usage: granPermissions("DID"||"PID"||"GID", DID||PID||GID, READ||CHANGE||MANAGE, [emails|groups], email sender id)
function grantPermission(resType, resID, perm, access_list, granter) { list = typeof(access_list) == 'string' ? [] + access_list : access_list for (var i = 0; i < access_list.length; i++) { //iterate over each email address // console.log("access_list[i]: ", access_list[i]) if(access_list[i].includes("@")){ //if entity name contains '@', assume entity type is User insert_user.run(access_list[i], access_list[i]) entID = get_user.get(access_list[i])?.UserID entType = "UserEnt" } else { //if entity name does not contain '@', assume entity type is Group insert_group.run(access_list[i], granter, "None") entID = find_group.get(access_list[i])?.GroupID entType = "GroupEnt" } insert_perms(entType, entID, resType, resID, perm) update_perms(entType, entID, resType, resID, perm) } }
[ "mayGrant(newPermission, granteePermissions = []) {\n return this._mayGrantOrRevoke('mayGrant', newPermission, granteePermissions);\n }", "mayGrant(permission, granteePermissions = []) {\n const newPermission = new RNPermission(permission);\n if (this.grantsAllowed() === 0 || !this.matchIdentifier(newPermission)) return false;\n\n // All other grantPrivileges must be covered by our grantPrivileges\n return this._areLesserPrivileges(newPermission, granteePermissions);\n }", "function update_perms(entType, entID, resType, resID, perm) {\n return db.prepare(`UPDATE Perms SET Permissions=? WHERE ${entType}=? AND ${resType}=?;`).run(perm, entID, resID)\n}", "async function checkPermission(entType, resType, entID, resID) {\n var level = 0 //no permissions is assumed until proven otherwise\n var anyone = get_group.get(\"all\")\n var groupID = anyone ? anyone.GroupID : null\n var result = get_perms(\"GroupEnt\", groupID, resType, resID) //check if the all group has been granted access and what level\n if(result?.Permissions >= level) { level = result.Permissions }\n\n result = get_perms(entType, entID, resType, resID) //check if the user has been explicitly granted permissions and what level\n if (result?.Permissions >= level) { level = result.Permissions }\n if (entType == \"UserEnt\") {\n groups = get_groups?.get(entID)\n if (groups) {\n groups = Object?.values(groups) //get IDs of all groups that the user belongs to \n groups?.forEach((group) => {\n result = get_perms(\"GroupEnt\", group, resType, resID)\n if (result?.Permissions >= level) { level = result.Permissions } //check permissions of each group that the user belongs to and what level\n })\n }\n }\n return level //return highest level of permission that user has been granted whether explicitly or through some group\n}", "function insert_perms(entType, entID, resType, resID, perm) {\n return db.prepare(`INSERT OR IGNORE INTO Perms(${entType}, ${resType}, Permissions) VALUES (?, ?, ?);`).run(entID, resID, perm)\n}", "_mayGrantOrRevoke(functionName, newPermission, granteePermissions = []) {\n const newPerms = _.flatten(this._unwindParameters(newPermission));\n const ourPerms = this.permissions();\n return _.every(newPerms, (newPerm) => {\n return _.some(ourPerms, (ourPerm) => ourPerm[functionName](newPerm, granteePermissions));\n });\n }", "grantPermission(hub, permission, connectionId, options) {\n const operationOptions = coreHttp.operationOptionsToRequestOptionsBase(options || {});\n return this.client.sendOperationRequest({ hub, permission, connectionId, options: operationOptions }, grantPermissionOperationSpec);\n }", "function addPerm(cb) { \n patchRsc('ictrlREST.json', ictrlA, function () {\n console.log('ACCESS to iControl REST API: ictrlUser');\n cb(); \n });\n}", "async function permissions(req, res, next) {\n\ttry {\n\t\tconst request = await Request.findById(req.params.requestId);\n\t\tif (!request) throw new ApiError(\"REQUEST_NOT_FOUND\");\n\t\tconst user = await User.findById(req.decoded._id).populate();\n\t\tif (!user) throw new ApiError(\"USER_NOT_FOUND\");\n\t\tconst billing = await Billing.findOne({\n\t\t\trequests: { $in: [req.params.requestId] }\n\t\t});\n\t\treq.billing = billing;\n\t\t// bypass if admin:\n\t\tconst isAdmin = user.roles.find(role => role === \"admin\");\n\t\tif (isAdmin) {\n\t\t\treq.permissions = { read: true, write: true };\n\t\t\treturn next();\n\t\t}\n\t\tif (!billing) throw new ApiError(\"BILLING_NOT_FOUND\");\n\t\tif (isRequestFromUser(billing, user)) {\n\t\t\tif (isAdmin) return next();\n\t\t\telse {\n\t\t\t\treq.permissions = userPermissions(req.decoded._id, request);\n\t\t\t\treturn next();\n\t\t\t}\n\t\t} else if (await isRequestFromJournal(req, billing)) {\n\t\t\tif (isAdmin) return next();\n\t\t\telse {\n\t\t\t\treq.permissions = await journalPermissions(\n\t\t\t\t\treq.journal._id.toString(),\n\t\t\t\t\treq.decoded._id\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t\treq.permissions = { read: false, write: false };\n\t\treturn next();\n\t} catch (error) {\n\t\treturn next(error);\n\t}\n}", "static add(permission){\n\t\tlet kparams = {};\n\t\tkparams.permission = permission;\n\t\treturn new kaltura.RequestBuilder('permission', 'add', kparams);\n\t}", "addPermissions(ids, permissions, region) {\n for (const id of ids) {\n const permission = permissions.find((val) => val.id === id);\n this.addPermission(permission || { id }, region);\n }\n }", "[SET_PERMISSION] (state, permissions) {\n state.permissions = permissions\n }", "updatePermissions() {\n this.permissions = this.codenvyAPI.getProject().getPermissions(this.workspaceId, this.projectName);\n }", "function get_perms(entType, entID, resType, resID) {\n return db.prepare(`SELECT Permissions FROM Perms WHERE ${entType}=? AND ${resType}=?;`).get(entID, resID)\n}", "addPermissionToRole (roleId, action, isAllowed = true) {\n assert.equal(typeof roleId, 'string', 'roleId must be string')\n assert.equal(typeof action, 'string', 'action must be string')\n assert.equal(typeof isAllowed, 'boolean', 'isAllowed must be boolean')\n return this._apiRequest(`/role/${roleId}/permission`, 'POST', {\n action: action,\n // TODO: dear api \"programmer\", what's a bool? hint: it's not something you smoke\n allowed: isAllowed ? 'yes' : 'no'\n })\n }", "function page_permission(perm, wcb, scb, rcb)\r\n{\r\n\tif(perm=='w')\r\n\t{\r\n\t\twcb();\r\n\t}\r\n\telse if(perm=='s')\r\n\t{\r\n\t\tscb();\r\n\t}\r\n\telse if(perm=='r')\r\n\t{\r\n\t\trcb();\r\n\t}\r\n\telse// impossable\r\n\t{\r\n\t}\r\n}", "userPermissionSet(\n { commit, dispatch, rootState, rootGetters },\n { id, userId, permission }\n ) {\n dispatch('sync/start', `layersUserPermissionSet`, { root: true })\n return rootState.api\n .setLayerPermissionsForUser(id, userId, permission)\n .then(p => {\n const permissions = p.data\n dispatch('sync/stop', `layersUserPermissionSet`, {\n root: true\n })\n commit('permissionsUpdate', {\n id,\n typeId: userId,\n permission: (permissions.users && permissions.users[userId]) || 0,\n type: 'users'\n })\n dispatch('messages/success', 'User permissions updated', {\n root: true\n })\n\n // If the current user was updated\n // And if the current user is not an admin\n // => the permissions for the current user have changed\n if (\n rootGetters['user/isCurrentUser'](userId) &&\n !rootGetters['user/isAdmin'](permissions)\n ) {\n // Re-list the layers in every corpuUids\n dispatch('listAll')\n commit('popup/close', null, { root: true })\n }\n\n return permissions\n })\n .catch(e => {\n dispatch('sync/stop', `layersUserPermissionSet`, {\n root: true\n })\n dispatch('messages/error', e.message, { root: true })\n\n throw e\n })\n }", "function _initializePermissionGrants(){\n return new Promise(function(resolve, reject){\n user.initializePermissionGrants(function(err){\n if(err){ return reject(err); }\n resolve();\n });\n });\n}", "allows(...permissions) {\n const perms = _.flatten(permissions).map(e => new RNPermission(e));\n return perms.every(e => this.matchIdentifier(e) && this.matchPrivileges(e.privileges()));\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Given a ray direction and a normal, compute and return a direction of reflected ray
function reflect(rayDirection, normal) { return vec3.subtract(vec3.create(), rayDirection, vec3.scale(vec3.create(), normal, 2 * vec3.dot(rayDirection, normal))); }
[ "function refract(rayDirection, normal, ior) {\n let cosi = vec3.dot(rayDirection, normal);\n let etaOut = 1;\n let etaIn = ior;\n if (cosi < 0) {\n cosi = -cosi;\n } else { // ray hits from inside the object\n [etaOut, etaIn] = [etaIn, etaOut]; // swap etaOut and etaIn\n vec3.negate(normal, normal);\n }\n const eta = etaOut / etaIn;\n\n const determinant = 1 - eta * eta * (1 - cosi * cosi);\n if (determinant < 0) { // total internal reflection\n return vec3.create(); // no ray is generated; TODO: right?\n }\n return vec3.add(vec3.create(), vec3.scale(vec3.create(), rayDirection, eta),\n vec3.scale(vec3.create(), normal, eta * cosi - Math.sqrt(determinant)));\n}", "function schlick(rayDirection, normal, ior) {\n // TODO: repetitive\n let cosi = vec3.dot(rayDirection, normal);\n let etaOut = 1;\n let etaIn = ior;\n if (cosi < 0) {\n cosi = -cosi;\n } else { // ray hits from inside the object\n [etaOut, etaIn] = [etaIn, etaOut]; // swap etaOut and etaIn\n }\n const eta = etaOut / etaIn;\n\n const determinant = 1 - eta * eta * (1 - cosi * cosi);\n if (determinant < 0) { // total internal reflection\n return 1; // all reflection, no refraction\n } else {\n let r0 = (etaOut - etaIn) / (etaOut + etaIn);\n r0 = r0 * r0;\n return r0 + (1 - r0) * Math.pow((1 - cosi), 5);\n }\n}", "function calcPlaneEquationForStraightLine(point, direction) {\n var d = direction;\n var n = vec3.create();\n // Calculate n via a second direction.\n //var d1 = vec3.create();\n //vec3.set([d[2],d[1],d[0]],d1);\n //vec3.cross(d, d1, n);\n // Set directly some n perpendicular to d.\n vec3.set([d[1], -d[0], -d[2]], n);\n vec3.normalize(n);\n A = n[0];\n B = n[1];\n C = n[2];\n D = -vec3.dot(n, point);\n AdivC = 0;\n }", "function rayTriangleMollerTrumbore(rayOrigin, rayDirection, v0, v1, v2)\r\n{\r\n let epsilon = 0.000001;\r\n let edge1 = new THREE.Vector3()\r\n let edge2 = new THREE.Vector3()\r\n let h = new THREE.Vector3()\r\n let s = new THREE.Vector3()\r\n let q = new THREE.Vector3()\r\n\r\n let a, f, u, v\r\n //float a,f,u,v;\r\n edge1.subVectors(v1, v0)\r\n edge2.subVectors(v2, v0);\r\n h.crossVectors(rayDirection, edge2);\r\n a = edge1.dot(h);\r\n if (a > -epsilon && a < epsilon) return false; // Le rayon est parallèle au triangle.\r\n\r\n f = 1.0/a;\r\n s.subVectors(rayOrigin, v0);\r\n u = f * s.dot(h);\r\n if (u < 0.0 || u > 1.0) return false;\r\n q.crossVectors(s, edge1);\r\n v = f * rayDirection.dot(q);\r\n if (v < 0.0 || u + v > 1.0) return false;\r\n\r\n // On calcule t pour savoir ou le point d'intersection se situe sur la ligne.\r\n let t = f * edge2.dot(q);\r\n if (t > epsilon) // Intersection avec le rayon\r\n {\r\n let retret = new THREE.Vector3()\r\n retret = rayOrigin.clone()\r\n retret.addScaledVector(rayDirection, t)\r\n return retret;\r\n }else return false;\r\n}", "direction(param) {\n return this._edgeSegment.direction(param);\n }", "awayVector(anotherCollider) {\n if(!anotherCollider instanceof CircleCollider) {\n return [0, 0];\n }\n\n let delta = [\n this.x - anotherCollider.x,\n this.y - anotherCollider.y\n ];\n\n let mag = magnitude(delta);\n\n return [\n delta[0] / mag * anotherCollider.radius,\n delta[1] / mag * anotherCollider.radius\n ]\n }", "getDirection(deltaSpaceObs) {\n return deltaSpaceObs.pipe(operators_7.take(1), operators_2.map(data => data.vel > 0 ? 1 : -1));\n }", "defineDirection() {\n var posRoad = this.road[this.partRoad];\n if (Number(this.pos.getx()) == Number(posRoad.getx())) {\n if (Number(this.pos.gety()) < Number(posRoad.gety())) {\n return SOUTH;\n } else {\n return NORTH;\n }\n }\n if (Number(this.pos.gety()) == Number(posRoad.gety())) {\n if (Number(this.pos.getx()) < Number(posRoad.getx())) {\n return EAST;\n } else {\n return WEST;\n }\n }\n return -1;\n }", "function getDirectionVector(pointA,pointB)\n{\n\treturn new Point(pointB.x-pointA.x, pointB.y - pointA.y);\n\n}", "function face_target_deltas_rad(dx, dy) {\n\tvar rad_angle = Math.atan(Math.abs(dy)/(Math.abs(dx)==0?0.00001:Math.abs(dx)) ); // !DIV0\n\tif (dx<0) rad_angle=Math.PI-rad_angle;\n\tif (dy<0) rad_angle=2*Math.PI-rad_angle;\n\treturn rad_angle;\n}", "get normal() {\n\n // Check if the face is bound to a mesh and if not throw an error\n if (!this.mesh) throw new Error(`Cannot compute the normal of the face - the face is not bound to a Mesh`);\n\n // Return the normal for the face\n return this.plane.normal;\n }", "pointerToRay(pointer) {\n\n const camera = this.viewer.navigation.getCamera()\n const pointerVector = new THREE.Vector3()\n const rayCaster = new THREE.Raycaster()\n const pointerDir = new THREE.Vector3()\n const domElement = this.viewer.canvas\n\n const rect = domElement.getBoundingClientRect()\n\n const x = ((pointer.clientX - rect.left) / rect.width) * 2 - 1\n const y = -((pointer.clientY - rect.top) / rect.height) * 2 + 1\n\n if (camera.isPerspective) {\n\n pointerVector.set(x, y, 0.5)\n\n pointerVector.unproject(camera)\n\n rayCaster.set(camera.position,\n pointerVector.sub(\n camera.position).normalize())\n\n } else {\n\n pointerVector.set(x, y, -15)\n\n pointerVector.unproject(camera)\n\n pointerDir.set(0, 0, -1)\n\n rayCaster.set(pointerVector,\n pointerDir.transformDirection(\n camera.matrixWorld))\n }\n\n return rayCaster.ray\n }", "transform(mat) {\n const orig = mat.transform3(this.orig);\n const dest = mat.transform3(this.orig.add(this.dir));\n const ray = Ray.fromOrigDest(orig, dest);\n return ray;\n }", "function calc_PlaneNormal(p1, p2, p3)\n{\n var normal = {lantitude: 0.0, longitude: 0.0, height: 0.0};\n var vec_p1p2 = formVector(p1, p2);\n var vec_p2p3 = formVector(p2, p3);\n var normal = crossProduct(vec_p1p2, vec_p2p3);\n return normal;\n}", "function findAngle(object, unit, directions) {\n// var dy = (object.y) - (unit.y);\n// var dx = (object.x) - (unit.x);\n var direction;\n if (object.x > unit.x) {\n if (object.y > unit.y) {\n direction = 3;\n } else if (object.y < unit.y) {\n direction = 1;\n } else {\n direction = 2;\n }\n } else if (object.x < unit.x) {\n if (object.y > unit.y) {\n direction = 5;\n } else if (object.y < unit.y) {\n direction = 7;\n } else {\n direction = 6;\n }\n } else if (object.y > unit.y) {\n direction = 4;\n } else if (object.x == unit.x\n && object.y == unit.y) {\n direction = unit.newDirection;\n } else {\n direction = 0;\n }\n return direction;\n //Convert Arctan to value between (0 - directions)\n\n\n// var angle = wrapDirection(directions/2-(Math.atan2(dx,dy)*directions/(2*Math.PI)),directions);//console.log(angle);\n// return angle;\n}", "function arcToRay(d)\n {\n var angle = (d.startAngle - d.endAngle)/2;\n var dr = (rayStyle.outerRadius - rayStyle.innerRadius)/2;\n var dx = dr*Math.cos(angle);\n var dy = dr*Math.sin(angle);\n\n var arc1 = d3.svg.arc()\n .outerRadius(rayStyle.innerRadius)\n .innerRadius(rayStyle.outerRadius);\n\n var arc2 = d3.svg.arc()\n .outerRadius(rayStyle.outerRadius+dr)\n .innerRadius(rayStyle.outerRadius);\n\n var xy1 = arc1.centroid(d);\n var xy2 = arc2.centroid(d);\n\n var xData = [xy1[0], xy2[0], xy2[0]];\n // x = 0 passes through is the centre of the figure\n if ( xData[0] >= 0 )\n {\n xData[2] = xData[2] + dr/2;\n }\n else\n {\n xData[2] = xData[2] - dr/2;\n }\n\n var yData = [xy1[1], xy2[1], xy2[1]];\n var lineData = [];\n xData.forEach(function(d, i){lineData[i] = {x: xData[i], y: yData[i]};});\n return lineData;\n }", "function pixelRayDeltaAngle(distance, x, y) {\n\tvar deltas = [];\n\tvar angle = Math.atan2(x - axis.x, -y + axis.y) + Math.PI;\n\tvar spiralOffset = spirality * distance;\n\n\tfor (var ray = 0; ray < rays; ray++) {\n\t\tvar offsetAngle = 2 * Math.PI / rays * ray;\n\n\t\t// Look 3 rounds back and ahead\n\t\tfor (var i = -3; i < 3; i++) {\n\t\t\tvar roundAngle = i * 2 * Math.PI;\n\t\t\tdeltas.push(Math.abs(angle - cmpAngle - offsetAngle - spreadAngle\n\t\t\t\t+ spiralOffset - roundAngle));\n\t\t}\n\t}\n\n\t// Find the ray with the smallest delta angle\n\tvar mindelta = null;\n\tfor (var d in deltas) {\n\t\tif (mindelta === null || deltas[d] < mindelta) mindelta = deltas[d];\n\t}\n\treturn mindelta;\n}", "_normalVector(v0, vt, va) {\n let normal0;\n let tgl = vt.length();\n if (tgl === 0.0) {\n tgl = 1.0;\n }\n if (va === undefined || va === null) {\n let point;\n if (!Scalar_1.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, types_1.Epsilon)) {\n // search for a point in the plane\n point = new Vector3_1.Vector3(0.0, -1.0, 0.0);\n }\n else if (!Scalar_1.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, types_1.Epsilon)) {\n point = new Vector3_1.Vector3(1.0, 0.0, 0.0);\n }\n else if (!Scalar_1.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, types_1.Epsilon)) {\n point = new Vector3_1.Vector3(0.0, 0.0, 1.0);\n }\n else {\n point = Vector3_1.Vector3.Zero();\n }\n normal0 = Vector3_1.Vector3.Cross(vt, point);\n }\n else {\n normal0 = Vector3_1.Vector3.Cross(vt, va);\n Vector3_1.Vector3.CrossToRef(normal0, vt, normal0);\n }\n normal0.normalize();\n return normal0;\n }", "function computeDiffuse(color, normal, lightDirection) {\n let diffuse = [];\n for (let c = 0; c < 3; c++) {\n diffuse[c] = (color[c] / 255) * (light.color[c] / 255) *\n Math.max(0, vec3.dot(normal, lightDirection));\n }\n return diffuse;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Append characters to the DOM. NOTE: The atag leads to a TEMPORARY destination. Point is to click it and have it lead to that character's character sheet eventually.
function appendCharacters(characters) { let htmlTemplate = ""; for (let character of characters) { htmlTemplate += ` <article> <a href="#profile"> <h2>${character.name}</h2> <img src="${character.img || 'img/placeholder.jpg'}"> <h3>${character.race} ${character.primary_class}</h3> <p>Campaign: ${character.campaign}</p> </a> ${generateOwnCharacterButton(character.id)} </article> `; } document.querySelector('#all-characters-container').innerHTML = htmlTemplate; }
[ "function storeLetters(letters) {\n let letterContainer = document.getElementById(\"letterContainer\");\n for (const char of letters) {\n let underlined = document.createElement(\"div\");\n underlined.setAttribute(\"class\", \"underlined\");\n letterContainer.appendChild(underlined);\n var charContainer = document.createElement(\"div\");\n charContainer.setAttribute(\"hidden\", \"\");\n charContainer.setAttribute(\"class\", \"hiddenChar\");\n charContainer.innerHTML = char;\n underlined.appendChild(charContainer);\n }\n}", "function addExtraLetter() {\n const word = document.querySelector('.word.active') || wordsContainer.firstChild\n const prevLength = word.children.length\n if (letterIndex >= prevLength) {\n const span = document.createElement('span')\n span.className = 'extra';\n span.innerHTML = textarea.value\n word.appendChild(span)\n }\n\n slashCoords()\n}", "addButton(char) {\n //Create an input type dynamically.\n let element = document.createElement(\"button\");\n //Assign different attributes to the element.\n element.textContent = char;\n element.setAttribute(\"id\", char);\n element.setAttribute(\"value\", char);\n element.setAttribute(\"type\", \"button\");\n element.setAttribute(\"name\", char);\n element.setAttribute(\"onclick\", \"game.guess(this)\");\n //Append the element in page (in span).\n buttonsDisplay.appendChild(element);\n }", "appendText(str) {\n this.current.appendChild(browser.createTextNode(str));\n return this;\n }", "function start(){\n\tvar div = \"\";\n\tfor ( i = 0; i < 25; i++) {\n\t\tvar element = \"let\" + i;\n\t\tdiv = div + '<div class = \"letter\" onclick = \"check('+i+')\" id=\"'+element+'\">'+letters[i]+'</div>';\n\t\tif ((i + 1) % 7 == 0) div = div + '<div style = \"clear:both;\"></div>';\n\t}\n\tdocument.getElementById(\"alphabet\").innerHTML = div;\n\tgenerateWord();\n}", "function add_character(char_icon, char_name, char_rarity, char_level) {\n if (char_level == 1) {\n row_1_data['char_icon'].setAttribute(\"src\", char_icon);\n row_1_data['char_name'].innerHTML = char_name;\n row_1_data['char_rarity'].setAttribute(\"src\", char_rarity);\n } else if (char_level == 2) {\n row_2_data['char_icon'].setAttribute(\"src\", char_icon);\n row_2_data['char_name'].innerHTML = char_name;\n row_2_data['char_rarity'].setAttribute(\"src\", char_rarity);\n } else if (char_level == 3) {\n row_3_data['char_icon'].setAttribute(\"src\", char_icon);\n row_3_data['char_name'].innerHTML = char_name;\n row_3_data['char_rarity'].setAttribute(\"src\", char_rarity);\n }\n}", "write(text) {\n this.element.appendChild(document.createElement(\"div\")).textContent = text\n }", "function insertText(a) {\n\t$chatline.val($chatline.val()+a).focus();\n}", "createElement() {\n console.log(this.line);\n this.$line = $('<div></div>')\n .addClass('Hero-graphic__terminal__line');\n\n if (this.line[0] != '') {\n this.$line.append('<span class=\"pre\">'+this.line[0]+'</span>');\n }\n\n this.$line\n .append('<div id=\"'+this.id+'\" class=\"text\"></div>')\n .append('<div class=\"cursor\" style=\"display: none\"></div>');\n }", "function addAnnotation(){\n var selection = window.getSelection();\n var n = selection.rangeCount;\n\n if (n == 0) {\n window.alert(\"Nie zaznaczono żadnego obszaru\");\n return false;\n }\n\n // for now allow only 1 range\n if (n > 1) {\n window.alert(\"Zaznacz jeden obszar\");\n return false;\n }\n\n // remember the selected range\n var range = selection.getRangeAt(0);\n\n if (!verifyTagInsertPoint(range.endContainer)) {\n window.alert(\"Nie można wstawić w to miejsce przypisu.\");\n return false;\n }\n\n // BUG #273 - selected text can contain themes, which should be omitted from\n // defining term\n var text = html2plainText(range.cloneContents());\n var tag = $('<span></span>');\n range.collapse(false);\n range.insertNode(tag[0]);\n\n xml2html({\n xml: '<pe><slowo_obce>' + text + '</slowo_obce> --- </pe>',\n success: function(text){\n var t = $(text);\n tag.replaceWith(t);\n openForEdit(t);\n },\n error: function(){\n tag.remove();\n alert('Błąd przy dodawaniu przypisu:' + errors);\n }\n })\n }", "function writeStory(){\n var docElem2 = document.getElementById(\"cardstory\");\n clearCard(docElem2);\n var newName = document.createElement('p');\n\n var newTxt = document.createTextNode(characters.story.shift());\n newName.appendChild(newTxt);\n docElem2.appendChild(newName);\n}", "function gen_character(params) {\n\t//add character generation code here\n}", "function printPlayerWord() {\n document.getElementById(\"playerWord\").innerHTML = \"\";\n for (var i = 0; i < playerWord.length; i++) {\n document.getElementById(\"playerWord\").innerHTML += playerWord[i];\n }\n document.getElementById(\"guessed\").innerHTML = pastLetters;\n}", "function createCharacters() {\n _case_ = new character('_case_', 110, 4, 20);\n acid = new character('acid', 120, 2, 10);\n brute = new character('Brüte', 170, 1, 15);\n fdat = new character('f.dat', 150, 1, 12);\n }", "function imojieClick(emojie) {\n gMeme.lines.push({\n txt: `${emojie}`,\n size: 20,\n align: 'left',\n color: 'red',\n x: 250,\n y: 300\n }, )\n gMeme.selectedLineIdx = gMeme.lines.length - 1\n drawImgText(elImgText)\n}", "function showCurrentWord() { \n var wordChoiceDiv = document.getElementById(\"wordChoices\");\n wordChoiceDiv.innerHTML = \"<div id=\\\"wordChoices\\\"></div>\"; // Clears the Div tag for each word\n console.log(currentWord); \n for (var i = 0; i < currentWord.length; i++) { // for every letter in the currentWord, type an underscore\n var newSpan = document.createElement(\"span\");\n newSpan.innerHTML= \"_ \";\n newSpan.setAttribute(\"id\",\"letter-\"+i);\n wordChoiceDiv.appendChild(newSpan); \n } \n }", "function addTextToDom(text) {\n console.log('Adding the following Stirng to dom: ' + text);\n\n const textContainer = document.getElementById('greeting-container');\n textContainer.innerText = text;\n}", "function addFoodToDom(foodString){\n const foodDiv = document.querySelector(\".foodList\");\n foodDiv.innerHTML += foodString\n}", "function createTagAppend(loc, tag, id='', el_class='', text='') {\n var element = document.createElement(tag);\n if (id != '') {\n element.setAttribute('id', id);\n }\n if (el_class != '') {\n element.setAttribute('class', el_class);\n }\n if (text != '') {\n element.innerText = text;\n }\n loc.append(element);\n return element;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }