query
stringlengths
9
34k
document
stringlengths
8
5.39M
negatives
sequencelengths
19
20
metadata
dict
create java variable name
function makeJavaVariableName() { var varName = ''; for (var i = 1; i < gValuesOfRange.length; i++) { /** set common var in column range*/ if (!setCommonVar(i)) { return ''; } if (cPhysicalNameOfColumn == '') { break; } varName += '/// <summary>' + newLine; varName += '/// ' + cLogicalNameOfColumn + newLine; varName += '/// </summary>' + newLine; // varName += '@JsonProperty("' + cPhysicalNameOfColumn + '")' + newLine; // varName += '@Column(name = "' + cPhysicalNameOfColumn + '")' + newLine; if (isNotNull) { varName += '@NotNull(message = "' + cLogicalNameOfColumn + 'を入力してください。")' + newLine; varName += '@NotBlank(message = "' + cLogicalNameOfColumn + 'を入力してください。")' + newLine; } varName += 'private ' + cConvTypeVal + ' ' + cJavaPropertyName + ';' + newLine; varName += newLine; } return varName; }
[ "function createVariable() {\n var id = nextVariableId++;\n var name = '$V';\n\n do {\n name += variableTokens[id % variableTokensLength];\n id = ~~(id / variableTokensLength);\n } while (id !== 0);\n\n return name;\n }", "function createVariable() {\n var id = nextVariableId++;\n var name = '$V';\n\n do {\n name += variableTokens[id % variableTokensLength];\n id = ~~(id / variableTokensLength);\n } while (id !== 0);\n\n return name;\n }", "function createVariable() {\n var id = nextVariableId++;\n var name = '$V';\n\n do {\n name += variableTokens[id % variableTokensLength];\n id = ~~(id / variableTokensLength);\n } while (id !== 0);\n\n return name;\n}", "getUniqueVarName() {\n this.randVarCount ++\n return '__' + this.randVarCount\n }", "function generateVariableName(str){\n return str.replace(/ /g, \"_\").toLowerCase();\n }", "function createThisVar(id) {\n var nstr = \"this_\" + id.replace(/\\_/g, \"__\")\n thisVars.push(nstr)\n return nstr\n }", "function createThisVar(id) {\r\n var nstr = \"this_\" + id.replace(/\\_/g, \"__\")\r\n thisVars.push(nstr)\r\n return nstr\r\n }", "function createThisVar(id) {\r\n var nstr = \"this_\" + id.replace(/\\_/g, \"__\")\r\n thisVars.push(nstr)\r\n return nstr\r\n }", "function genTmp(isLbl) {\n var name = tmp_prefix + (tmpCount++);\n if(!isLbl)\n tmps[tmps.length] = new ast.VariableDeclarator(new ast.Identifier(name), null);\n return name;\n }", "static getVariableName(variableName) {\n return `${this.getUniverse()}_${variableName}`;\n }", "function setVariableName(varName, alias, variableData, generateNewName){\n\t// console.log(\"----------------------------------------\");\n\t// console.log(varName, alias, variableData);\n\t// console.log(\"expressionLevelNames\", expressionLevelNames);\n\t// console.log(\"variableNamesClass\", variableNamesClass);\n\t// console.log(\"variableNamesAll\", variableNamesAll);\n\t// console.log(\"rrrrrrrrr\", variableNamesClass[varName]);\n\t// console.log(\"----------------------------------------\");\n\t// console.log(\" \");\n\tif(alias != null) {\n\t\t//console.log(\"1111\", varName, alias);\n\t\tvar aliasSet = false;\n\t\tfor(var key in idTable){\n\t\t\tif (idTable[key] == alias) {\n\t\t\t\tvariableNamesAll[alias] = {\"alias\" : alias + \"_\" +counter, \"nameIsTaken\" : true, \"counter\" : counter, \"isVar\" : true};\n\t\t\t\taliasSet = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif (aliasSet == false) variableNamesAll[alias] = {\"alias\" : alias, \"nameIsTaken\" : true, \"counter\" : 0, \"isVar\" : true};\n\t\t\n\t\treturn variableNamesAll[alias][\"alias\"];\n\t}\n\telse if(variableData[\"kind\"] == \"PROPERTY_NAME\" || typeof variableData[\"kind\"] === 'undefined'){\n\t\t// console.log(\"2222\", varName);\n\t\t//??????????????????????????????????????\n\t\t//if(typeof variableNamesClass[varName] === 'undefined' || (typeof variableNamesClass[varName] !== 'undefined' && typeof variableNamesClass[varName][\"isvar\"] !== 'undefined' && variableNamesClass[varName][\"isvar\"] != true))applyExistsToFilter = true;\n\t\tif(typeof variableNamesClass[varName] === 'undefined' || (typeof variableNamesClass[varName] !== 'undefined' && (variableNamesClass[varName][\"isVar\"] != true ||\n\t\t\tvariableData[\"type\"] != null && (typeof variableData[\"type\"][\"maxCardinality\"] === 'undefined' || variableData[\"type\"][\"maxCardinality\"] > 1 || variableData[\"type\"][\"maxCardinality\"] == -1))))applyExistsToFilter = true;\n\t\t//??????????????????????????????????????\n\t\tif(generateNewName != null && generateNewName == true ){\n\t\t\t// console.log(\"2aaaa\", varName);\n\t\t\tif(typeof expressionLevelNames[varName] === 'undefined'){\n\t\t\t\tif(typeof variableNamesClass[varName]=== 'undefined'){\n\t\t\t\t\tif(typeof variableNamesAll[varName]=== 'undefined'){\n\t\t\t\t\t\texpressionLevelNames[varName] = varName;\n\t\t\t\t\t\tvariableNamesClass[varName] = {\"alias\" : varName, \"nameIsTaken\" : true, \"counter\" : 0, \"isVar\" : false};\n\t\t\t\t\t\tvariableNamesAll[varName] = {\"alias\" : varName, \"nameIsTaken\" : true, \"counter\" : 0, \"isVar\" : false};\n\t\t\t\t\t} else {\n\t\t\t\t\t\tvar count = variableNamesAll[varName][\"counter\"] + 1;\n\t\t\t\t\t\texpressionLevelNames[varName] = varName + \"_\" +count;\n\t\t\t\t\t\tvariableNamesAll[varName][\"counter\"] = count;\n\t\t\t\t\t\tvariableNamesClass[varName] = {\"alias\" : varName + \"_\" +count, \"nameIsTaken\" : variableNamesAll[varName][\"nameIsTaken\"], \"counter\" : count, \"isVar\" : variableNamesAll[varName][\"isVar\"]};\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tvar count = variableNamesClass[varName][\"counter\"] + 1;\n\t\t\t\t\texpressionLevelNames[varName] = varName + \"_\" +count;\n\t\t\t\t\tvariableNamesClass[varName][\"counter\"] = count;\n\t\t\t\t\tvariableNamesAll[varName] = {\"alias\" : varName + \"_\" +count, \"nameIsTaken\" : variableNamesClass[varName][\"nameIsTaken\"], \"counter\" : count, \"isVar\" : variableNamesClass[varName][\"isVar\"]};\n\t\t\t\t\t//console.log(count, varName + \"_\" +count, variableNamesClass[varName][\"counter\"], variableNamesAll[varName][\"counter\"])\n\t\t\t\t}\n\t\t\t}else{\n\t\t\t\treturn expressionLevelNames[varName];\n\t\t\t}\n\t\t// cardinality is more then 1 or is unknown (for each variable new definition)\n\t\t} else if(variableData[\"type\"] != null && (typeof variableData[\"type\"][\"maxCardinality\"] === 'undefined' || variableData[\"type\"][\"maxCardinality\"] > 1 || variableData[\"type\"][\"maxCardinality\"] == -1)){\n\t\t// console.log(\"2bbbb\", varName);\t\t \n\t\t //if not used in given expression\n\t\t\tif(typeof expressionLevelNames[varName] === 'undefined'){\n\t\t\t\t//if not used in class scope\n\t\t\t\tif(typeof variableNamesClass[varName] === 'undefined'){\n\t\t\t\t\t//if not used in query scope\n\t\t\t\t\tif(typeof variableNamesAll[varName]=== 'undefined'){\n\t\t\t\t\t\t//not used at all\n\t\t\t\t\t\t\n\t\t\t\t\t\t//if simple variable\n\t\t\t\t\t\tif(isSimpleVariableForNameDef == true){\n\t\t\t\t\t\t\tvar tempIsVar = false;\n\t\t\t\t\t\t\tif(parseType == \"attribute\") tempIsVar = true;\n\t\t\t\t\t\t\tvariableNamesClass[varName] = {\"alias\" : varName, \"nameIsTaken\" : true, \"counter\" : 0, \"isVar\" : tempIsVar};\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tvariableNamesClass[varName] = {\"alias\" : varName+\"_1\", \"nameIsTaken\" : false, \"counter\" : 1, \"isVar\" : false};\n\t\t\t\t\t\t}\n\t\t\t\t\t\texpressionLevelNames[varName] = variableNamesClass[varName][\"alias\"];\n\t\t\t\t\t\n\t\t\t\t\t//is used in query, but not in a given class (somewhere else)\n\t\t\t\t\t} else {\n\t\t\t\t\t\t//if simple variable\n\t\t\t\t\t\tif(isSimpleVariableForNameDef == true){\n\t\t\t\t\t\t\tvar tempIsVar = false;\n\t\t\t\t\t\t\tif(parseType == \"attribute\") tempIsVar = true;\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t//name is not taken\n\t\t\t\t\t\t\tif(variableNamesAll[varName][\"nameIsTaken\"] != true){\n\t\t\t\t\t\t\t\tvariableNamesClass[varName] = {\"alias\" : varName, \"nameIsTaken\" : true, \"counter\" : variableNamesAll[varName][\"counter\"], \"isVar\" : tempIsVar};\n\t\t\t\t\t\t\t//name is taken\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tvar count = variableNamesAll[varName][\"counter\"] + 1;\n\t\t\t\t\t\t\t\tvariableNamesClass[varName] = {\"alias\" : varName+\"_\"+count, \"nameIsTaken\" : true, \"counter\" : count, \"isVar\" : tempIsVar};\n\t\t\t\t\t\t\t\tvariableNamesAll[varName] = {\"alias\" : varName+\"_\"+count, \"nameIsTaken\" : true, \"counter\" : count, \"isVar\" : tempIsVar}; //????? vai vajag\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t//is expression\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tvar count = variableNamesAll[varName][\"counter\"] + 1;\n\t\t\t\t\t\t\tvariableNamesClass[varName] = {\"alias\" : varName+\"_\"+count, \"nameIsTaken\" : variableNamesAll[varName][\"nameIsTaken\"], \"counter\" : count, \"isVar\" : false};\n\t\t\t\t\t\t}\n\t\t\t\t\t\texpressionLevelNames[varName] = variableNamesClass[varName][\"alias\"];\n\t\t\t\t\t}\n\t\t\t\t\treturn variableNamesClass[varName][\"alias\"];\n\t\t\t\t//is used in a given class\n\t\t\t\t}else{\n\t\t\t\t\t//if simple variable\n\t\t\t\t\tif(isSimpleVariableForNameDef == true){\n\t\t\t\t\t\tvar tempIsVar = false;\n\t\t\t\t\t\tif(parseType == \"attribute\") tempIsVar = true;\n\t\t\t\t\t\t\n\t\t\t\t\t\t//name is not taken\n\t\t\t\t\t\tif(variableNamesClass[varName][\"nameIsTaken\"] != true){\n\t\t\t\t\t\t\tvariableNamesClass[varName] = {\"alias\" : varName, \"nameIsTaken\" : true, \"counter\" : variableNamesClass[varName][\"counter\"], \"isVar\" : tempIsVar};\n\t\t\t\t\t\t//name is taken\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tvar count = variableNamesClass[varName][\"counter\"] + 1;\n\t\t\t\t\t\t\tvariableNamesClass[varName] = {\"alias\" : varName+\"_\"+count, \"nameIsTaken\" : true, \"counter\" : count, \"isVar\" : tempIsVar};\n\t\t\t\t\t\t}\n\t\t\t\t\t//is expression\n\t\t\t\t\t} else {\n\t\t\t\t\t\tvar count = variableNamesClass[varName][\"counter\"] + 1;\n\t\t\t\t\t\tvariableNamesClass[varName] = {\"alias\" : varName+\"_\"+count, \"nameIsTaken\" : true, \"counter\" : count, \"isVar\" : false};\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\texpressionLevelNames[varName] = variableNamesClass[varName][\"alias\"];\n\t\t\t\t\treturn variableNamesClass[varName][\"alias\"];\n\t\t\t\t}\n\t\t\t//used in given expression\n\t\t\t} else {\n\t\t\t\treturn expressionLevelNames[varName];\n\t\t\t}\n\t\t}\n\t\t// cardinality is <=1\n\t\telse{\n\t\t\t// console.log(\"2cccc\", varName, isSimpleVariableForNameDef);\n\t\t\t//if not used in given expression\n\t\t\tif(typeof expressionLevelNames[varName] === 'undefined'){\n\t\t\t\t// console.log(\"2c 1\", varName);\n\t\t\t\t//if not used in class scope\n\t\t\t\tif(typeof variableNamesClass[varName] === 'undefined'){\n\t\t\t\t\t// console.log(\"2c 11\", varName);\n\t\t\t\t\t//if not used in query scope\n\t\t\t\t\tif(typeof variableNamesAll[varName]=== 'undefined'){\n\t\t\t\t\t\t//not used at all\n\t\t\t\t\t\t// console.log(\"2c 111\", varName, parseType);\n\t\t\t\t\t\t//if simple variable\n\t\t\t\t\t\tif(isSimpleVariableForNameDef == true){\n\t\t\t\t\t\t\tvar tempIsVar = false;\n\t\t\t\t\t\t\tif(parseType == \"attribute\") tempIsVar = true;\n\t\t\t\t\t\t\tvariableNamesClass[varName] = {\"alias\" : varName, \"nameIsTaken\" : true, \"counter\" : 0, \"isVar\" : tempIsVar};\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tvariableNamesClass[varName] = {\"alias\" : varName+\"_1\", \"nameIsTaken\" : false, \"counter\" : 1, \"isVar\" : false};\n\t\t\t\t\t\t}\n\t\t\t\t\t\t// console.log(\"variableNamesClass[varName]\", variableNamesClass[varName]);\n\t\t\t\t\t\texpressionLevelNames[varName] = variableNamesClass[varName][\"alias\"];\n\t\t\t\t\t\n\t\t\t\t\t//is used in query, but not in a given class (somewhere else)\n\t\t\t\t\t} else {\n\t\t\t\t\t\t// console.log(\"2c 112\", varName);\n\t\t\t\t\t\t//if simple variable\n\t\t\t\t\t\tif(isSimpleVariableForNameDef == true){\n\t\t\t\t\t\t\tvar tempIsVar = false;\n\t\t\t\t\t\t\tif(parseType == \"attribute\") tempIsVar = true;\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t//name is not taken\n\t\t\t\t\t\t\tif(variableNamesAll[varName][\"nameIsTaken\"] != true){\n\t\t\t\t\t\t\t\tvariableNamesClass[varName] = {\"alias\" : varName, \"nameIsTaken\" : true, \"counter\" : variableNamesAll[varName][\"counter\"], \"isVar\" : tempIsVar};\n\t\t\t\t\t\t\t//name is taken\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tvar count = variableNamesAll[varName][\"counter\"] + 1;\n\t\t\t\t\t\t\t\tvariableNamesClass[varName] = {\"alias\" : varName+\"_\"+count, \"nameIsTaken\" : true, \"counter\" : count, \"isVar\" : tempIsVar};\n\t\t\t\t\t\t\t\tvariableNamesAll[varName] = {\"alias\" : varName+\"_\"+count, \"nameIsTaken\" : true, \"counter\" : count, \"isVar\" : tempIsVar}; //????? vai vajag\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t//is expression\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tvar count = variableNamesAll[varName][\"counter\"] + 1;\n\t\t\t\t\t\t\tvariableNamesClass[varName] = {\"alias\" : varName+\"_\"+count, \"nameIsTaken\" : variableNamesAll[varName][\"nameIsTaken\"], \"counter\" : count, \"isVar\" : false};\n\t\t\t\t\t\t}\n\t\t\t\t\t\texpressionLevelNames[varName] = variableNamesClass[varName][\"alias\"];\n\t\t\t\t\t}\n\t\t\t\t\treturn variableNamesClass[varName][\"alias\"];\n\t\t\t\t//is used in a given class\n\t\t\t\t}else{\n\t\t\t\t\t// console.log(\"2c 12\", varName);\n\t\t\t\t\t//if simple variable\n\t\t\t\t\tif(isSimpleVariableForNameDef == true){\n\t\t\t\t\t\t// console.log(\"2c 121\", varName);\n\t\t\t\t\t\tvar tempIsVar = false;\n\t\t\t\t\t\tif(parseType == \"attribute\") tempIsVar = true;\n\t\t\t\t\t\t\n\t\t\t\t\t\t//name is not taken\n\t\t\t\t\t\tif(variableNamesClass[varName][\"nameIsTaken\"] != true){\n\t\t\t\t\t\t\tvariableNamesClass[varName] = {\"alias\" : varName, \"nameIsTaken\" : true, \"counter\" : variableNamesClass[varName][\"counter\"], \"isVar\" : tempIsVar};\n\t\t\t\t\t\t//name is taken\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t//if name is not defined as variable\n\t\t\t\t\t\t\tif(variableNamesClass[varName][\"isVar\"] != true) {\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\tvar count = variableNamesClass[varName][\"counter\"] + 1;\n\t\t\t\t\t\t\t\tvariableNamesClass[varName] = {\"alias\" : varName+\"_\"+count, \"nameIsTaken\" : true, \"counter\" : count, \"isVar\" : tempIsVar};\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\t// console.log(\"variableNamesClass[varName]\", variableNamesClass[varName]);\n\t\t\t\t\t//is expression\n\t\t\t\t\t} else {\n\t\t\t\t\t\t// console.log(\"2c 122\", varName);\n\t\t\t\t\t\t//name is not taken\n\t\t\t\t\t\tif(variableNamesClass[varName][\"nameIsTaken\"] != true){\n\t\t\t\t\t\t\tvar count = variableNamesClass[varName][\"counter\"] + 1;\n\t\t\t\t\t\t\tvariableNamesClass[varName] = {\"alias\" : varName+\"_\"+count, \"nameIsTaken\" : false, \"counter\" : count, \"isVar\" : false};\n\t\t\t\t\t\t//name is taken\n\t\t\t\t\t\t} //else {\n\t\t\t\t\t\t//\tvar count = variableNamesClass[varName][\"counter\"] + 1;\n\t\t\t\t\t\t//\tvariableNamesClass[varName] = {\"alias\" : varName+\"_\"+count, \"nameIsTaken\" : true, \"counter\" : count};\n\t\t\t\t\t\t//}\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\texpressionLevelNames[varName] = variableNamesClass[varName][\"alias\"];\n\t\t\t\t\treturn variableNamesClass[varName][\"alias\"];\n\t\t\t\t}\n\t\t\t//used in given expression\n\t\t\t} else {\n\t\t\t\t// console.log(\"2c 2\", varName);\n\t\t\t\treturn expressionLevelNames[varName];\n\t\t\t}\n\t\t}\n\t\treturn expressionLevelNames[varName];\n\t} else {\n\t\t//console.log(\"3333\", varName);\n\t\treturn varName;\n\t}\n}", "function createTempVariable(recordTempVariable) {\n var name = createIdentifier(\"\");\n name.autoGenerateKind = 1 /* Auto */;\n name.autoGenerateId = nextAutoGenerateId;\n nextAutoGenerateId++;\n if (recordTempVariable) {\n recordTempVariable(name);\n }\n return name;\n }", "static getNextVariableName() {\n\t\treturn \"_h\" + (DefaultIndexer.nextVariableIndex++);\n\t}", "newTypeName(){\r\n\t\tvar typeName=\"__type__\"+this.typeIdNumber;\r\n\t\tthis.typeIdNumber++;\r\n\t\treturn typeName;\r\n\t}", "function getVarID(variableName) { \n\tfor (var k in g_form.nameMap) { \n\t\tif (g_form.nameMap[k].prettyName == variableName) { \n\t\t\treturn 'ni.VE' + g_form.nameMap[k].realName; \n\t\t} \n\t} \n}", "function generate_variable(name, value, useold)\n{\n\treturn new Variable(name, value, useold);\n}", "i18nGenerateClosureVar(messageId) {\n let name;\n const suffix = this.fileBasedI18nSuffix.toUpperCase();\n if (this.i18nUseExternalIds) {\n const prefix = getTranslationConstPrefix(`EXTERNAL_`);\n const uniqueSuffix = this.constantPool.uniqueName(suffix);\n name = `${prefix}${sanitizeIdentifier(messageId)}$$${uniqueSuffix}`;\n }\n else {\n const prefix = getTranslationConstPrefix(suffix);\n name = this.constantPool.uniqueName(prefix);\n }\n return variable(name);\n }", "function newUName() {\n\treturn '#v_' + __uniqueVarCount++;\n }", "generateVariable(path, name) {\n if (!name) {\n return this.generateVariable(path, 'b');\n }\n // Path predicates can't contain variables\n if (path && (path.subject.value === name || path.object.value === name)) {\n return this.generateVariable(path, `${name}b`);\n }\n return DF.variable(name);\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the currently visible viewport rect in page coordinates.
function clientViewportRect() { var elem = document.documentElement; var x = window.pageXOffset; var y = window.pageYOffset; var width = elem.clientWidth; var height = elem.clientHeight; return { x: x, y: y, width: width, height: height }; }
[ "function clientViewportRect() {\n var elem = document.documentElement;\n var x = window.pageXOffset;\n var y = window.pageYOffset;\n var w = x + elem.clientWidth;\n var h = y + elem.clientHeight;\n return new utility.Rect(x, y, w, h);\n }", "function clientViewportRect() {\r\n var elem = document.documentElement;\r\n var x = window.pageXOffset;\r\n var y = window.pageYOffset;\r\n var width = elem.clientWidth;\r\n var height = elem.clientHeight;\r\n return { x: x, y: y, width: width, height: height };\r\n }", "function clientViewportRect() {\n\t var elem = document.documentElement;\n\t var x = window.pageXOffset;\n\t var y = window.pageYOffset;\n\t var width = elem.clientWidth;\n\t var height = elem.clientHeight;\n\t return { x: x, y: y, width: width, height: height };\n\t }", "function getBoundingVisibleRect(el) {\n // Get the element bounding rect in the layout viewport.\n const rect = getBoundingRect(el);\n\n // Apply the visual viewport transform (i.e. pinch-zoom) to the bounding\n // rect. The viewportX|Y values are in CSS pixels so they don't change\n // with page scale. We first translate so that the viewport offset is\n // at the origin and then we apply the scaling factor.\n const scale = getPageScaleFactor();\n const visualViewportX = chrome.gpuBenchmarking.visualViewportX();\n const visualViewportY = chrome.gpuBenchmarking.visualViewportY();\n rect.top = (rect.top - visualViewportY) * scale;\n rect.left = (rect.left - visualViewportX) * scale;\n rect.width *= scale;\n rect.height *= scale;\n\n // Get the window dimensions.\n const windowHeight = getWindowHeight();\n const windowWidth = getWindowWidth();\n\n // Then clip the rect to the screen size.\n rect.top = clamp(0, rect.top, windowHeight);\n rect.left = clamp(0, rect.left, windowWidth);\n rect.height = clamp(0, rect.height, windowHeight - rect.top);\n rect.width = clamp(0, rect.width, windowWidth - rect.left);\n\n return rect;\n }", "getVisibleBounds() {\n return new (0, _math.Rectangle)(this.left, this.top, this.worldScreenWidth, this.worldScreenHeight);\n }", "function getViewRect() {\n return XYRect.init(\n offsetX,\n offsetY,\n offsetX + viewWidth,\n offsetY + viewHeight);\n }", "function getViewRect() {\n return XYRect.init(\n offsetX, \n offsetY, \n offsetX + viewWidth,\n offsetY + viewHeight);\n }", "function tswUtilsGetVisibleRect()\n{\n\tvar width, height, x, y;\n\t\n\t//From http://thewebdevelopmentblog.com/2008/10/tutorial-pop-overs-part-2-centering-the-pop-over/\n if (document.all) \n\t{\n\t\t// IE\n\t\twidth = (document.documentElement.clientWidth) ? \n\t\tdocument.documentElement.clientWidth : \n\t\tdocument.body.clientWidth;\n\t\theight = (document.documentElement.clientHeight) ? \n\t\tdocument.documentElement.clientHeight : \n\t\tdocument.body.clientHeight;\n\t\ty = (document.documentElement.scrollTop) ? \n\t\tdocument.documentElement.scrollTop : \n\t\tdocument.body.scrollTop;\n\t\tx = (document.documentElement.scrollLeft) ? \n\t\tdocument.documentElement.scrollLeft : \n\t\tdocument.body.scrollLeft;\n\t\t\n } \n\telse \n\t{\n\t\t// Safari, Firefox\n\t\twidth = window.innerWidth;\n\t\theight = window.innerHeight;\n\t\ty = window.pageYOffset;\n\t\tx = window.pageXOffset;\n\t}\n\t\n\treturn [x, y, width, height];\n}", "getScreenActualViewPort() {\n return (this._args.device.viewportRect || this.imageHelper.options.cropRectangle);\n }", "function viewportRect(element) {\n var rect = element.getBoundingClientRect();\n return new Rect(rect.left, rect.top, rect.width, rect.height);\n}", "getVisibleBounds()\n {\n return new Rectangle(this.left, this.top, this.worldScreenWidth, this.worldScreenHeight);\n }", "function getBounds() {\n return viewer.viewport.viewportToImageRectangle(viewer.viewport.getBounds(true));\n }", "function getScreenRect(element) {\n var rect = $.extend({}, getRect(element)),\n top = cachedViewPosition.y,\n left = cachedViewPosition.x;\n rect.top -= top;\n rect.bottom -= top;\n rect.left -= left;\n rect.right -= left;\n return rect;\n }", "function getViewport() { // @return { w, h, sx, sy }\r\n if (_ua.ie) {\r\n _iebody || (_iebody = _mm.compat.body());\r\n return { w: _iebody.clientWidth,\r\n h: _iebody.clientHeight,\r\n sx: _iebody.scrollLeft,\r\n sy: _iebody.scrollTop };\r\n }\r\n // \"window.pageXOffset\" alias \"window.scrollX\" in gecko, webkit\r\n return { w: innerWidth,\r\n h: innerHeight,\r\n sx: pageXOffset,\r\n sy: pageYOffset };\r\n}", "function getViewRect() {\n return cycleRect ? cycleRect : T5.XYRect.fromCenter(\n offsetX, \n offsetY, \n dimensions.width, \n dimensions.height);\n }", "function getLayoutViewportPositionRelativeToPage() {\n var documentClientRect = document.documentElement.getBoundingClientRect();\n return { top: -documentClientRect.top, left: -documentClientRect.left };\n}", "get visibleRect() {\n return this._visibleRect;\n }", "function visible_area(){\n\tlet y = parseInt(window.pageYOffset);\n\tlet height = parseInt(window.innerHeight);\n\treturn {top: y, bottom: y + height, height: height}\n}", "function getVisualViewportRectRelativeToLayoutViewport() {\n var visualViewport = getVisualViewport();\n var pos = {\n left: visualViewport.offsetLeft,\n top: visualViewport.offsetTop\n };\n var size = {\n width: visualViewport.width,\n height: visualViewport.height\n };\n return Geometry.makeClientRect(pos, size);\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
retreive the current selected Go from the workspace state
function getSelectedGo() { return stateUtils_1.getFromWorkspaceState('selectedGo'); }
[ "getSelectedProject() {\n if (this.currentCache) {\n return this.currentCache.selectedProject;\n }\n }", "function initSelectedWorkspace() {\n var selectedName = StorageService.get('selectedWorkspaceName');\n\n if (!selectedName) {\n selectedName = defaultWorkspace.name;\n StorageService.set('selectedWorkspaceName', selectedName);\n }\n\n var currRepos = repositories();\n for (var i = 0; i < currRepos.length; ++i) {\n if (currRepos[i].name == selectedName)\n return currRepos[i];\n }\n\n return null;\n }", "function getCurrentLanguageSelection() {\n return languageSelection;\n}", "currentChoice() {\n return this.opt.choices.getChoice(this.pointer);\n }", "function pageTree_get_selected() {\n return $GLOBAL.pageTree.jstree('get_selected', true)[0];\n}", "function get_selected_feature ()\n {\n return (CURRENT_FEATURE);\n }", "function getCurrComp()\r\n\t\t{\r\n\t\t\tvar comps = getSelectedComps();\r\n\t\t\t\r\n\t\t\tif (comps.length === 1)\r\n\t\t\t\treturn comps;\r\n\t\t\telse\r\n\t\t\t\treturn null;\r\n\t\t}", "function getSelected() {\n return sites[selected];\n }", "function userTree_get_selected() {\n return $GLOBAL.userTree.jstree('get_selected', true)[0];\n}", "function getCurrentSubproject() {\n\treturn subprojectSelect.getSelectedItem();\n}", "current() {\n return this.repository.state;\n }", "function GetWorkingLanguage() {\n\treturn GetWorkingLanguageForChapter(CurrentChapter);\n}", "getProject() {\n return this._S.state.project;\n }", "async loadPreviousSelectedCurrentProject() {\n\t\tlet project = studio.settings.loadValue('projects', 'currentProject', null);\n\t\tlet file = studio.settings.loadValue('projects', 'currentFile', null);\n\n\t\tif (project !== null) {\n\t\t\tif(await studio.filesystem.pathExists(project.folder)) {\n\t\t\t\tif(await this.selectCurrentProject(project, false)) {\n\t\t\t\t\tif (file !== null) {\n\t\t\t\t\t\tawait this.changeFile(project,file);\n\t\t\t\t\t}\n\t\t\t\t} \n\t\t\t} else {\n\t\t\t\tstudio.workspace.showDialog(ProjectsLibrary, {width: 1000});\n\t\t\t}\t\t\t\n\t\t} else if(!studio.settings.loadValue('firstrun', 'firstRun', true)) {\n\t\t\tstudio.workspace.showDialog(ProjectsLibrary, {width: 1000});\n\t\t}\n\t\t\n\t}", "getCurrentProgram() {\n return this.currentProgram;\n }", "function getCurrentIfAny() {\n if (!currentProject) {\n console.error(types.errors.CALLED_WHEN_NO_ACTIVE_PROJECT_GLOBAL);\n throw new Error(types.errors.CALLED_WHEN_NO_ACTIVE_PROJECT_GLOBAL);\n }\n return currentProject;\n }", "function pwGetCurrentSelection() {\n if($('#filter input[type=checkbox]').is(':checked')) {\n var vals = pwGetColVals(null, 'category');\n vals = pwGetColVals(vals, 'volume');\n vals = pwGetColVals(vals, 'type');\n vals = pwGetColVals(vals, 'location');\n vals = pwGetColVals(vals, 'shape');\n currentSelection = objToArr(vals);\n } else {\n currentSelection = [];\n for (var i=0; i < packages.length; i++) {\n currentSelection[i] = i;\n }\n }\n }", "function CLC_GetSelectedText(){\r\n var text = CLC_Window().getSelection().toString();\r\n return text;\r\n }", "function get_current_selection() {\n /* Get the DOM element */\n let brush = document.getElementsByClassName(self.brush_class)[0];\n /* Return the selection of the brush */\n return d3.brushSelection(brush)\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Construct a new KernelFutureHandler.
function KernelFutureHandler(cb, msg, expectShell, disposeOnDone, kernel) { var _this = _super.call(this, cb) || this; _this._status = 0; _this._stdin = Private.noOp; _this._iopub = Private.noOp; _this._reply = Private.noOp; _this._done = new coreutils_1.PromiseDelegate(); _this._hooks = new Private.HookList(); _this._disposeOnDone = true; _this._msg = msg; if (!expectShell) { _this._setFlag(Private.KernelFutureFlag.GotReply); } _this._disposeOnDone = disposeOnDone; _this._kernel = kernel; return _this; }
[ "createHandlerFactory() {\n logger.debug('createHandlerFactory()');\n return () => {\n const internal = { handlerId: (0, uuid_1.v4)() };\n const handler = new Handler_1.Handler({\n internal,\n channel: this._channel\n });\n this._handlers.add(handler);\n handler.on('@close', () => this._handlers.delete(handler));\n return handler;\n };\n }", "function factory() {\n function add(name, initialValue) {\n window.__kbase_semaphores__[name] = initialValue || null;\n }\n\n function set(name, value) {\n window.__kbase_semaphores__[name] = value;\n }\n\n function get(name, defaultValue) {\n const value = window.__kbase_semaphores__[name];\n if (value === undefined) {\n return defaultValue;\n }\n return value;\n }\n\n function remove(name) {\n delete window.__kbase_semaphores__[name];\n }\n\n function when(name, value, timeout) {\n const startTime = new Date().getTime();\n return new Promise((resolve, reject) => {\n function waiter() {\n const elapsed = new Date().getTime() - startTime;\n if (elapsed > timeout) {\n reject(\n new Error(\n 'Timed out waiting for semaphore \"' +\n name +\n '\" with value \"' +\n value +\n '\"'\n )\n );\n return;\n }\n if (get(name) === value) {\n resolve();\n return;\n }\n window.setTimeout(() => {\n waiter();\n }, 100);\n }\n waiter();\n });\n }\n\n return Object.freeze({\n add,\n set,\n remove,\n when,\n });\n }", "function Kernel() {}", "static empty(ec = Scheduler.global.get()) {\n return new FutureMaker(new AsyncFutureState(), ec);\n }", "function startNewKernel(options) {\n options = options || {};\n var baseUrl = options.baseUrl || utils.getBaseUrl();\n var url = utils.urlPathJoin(baseUrl, KERNEL_SERVICE_URL);\n var ajaxSettings = utils.copy(options.ajaxSettings || {});\n ajaxSettings.method = 'POST';\n ajaxSettings.data = JSON.stringify({ name: options.name });\n ajaxSettings.dataType = 'json';\n ajaxSettings.contentType = 'application/json';\n ajaxSettings.cache = false;\n return utils.ajaxRequest(url, ajaxSettings).then(function (success) {\n if (success.xhr.status !== 201) {\n return utils.makeAjaxError(success);\n }\n validate.validateKernelModel(success.data);\n return new Kernel(options, success.data.id);\n }, Private.onKernelError);\n}", "function FiberFuture(fn, context, args) {\n\tthis.fn = fn;\n\tthis.context = context;\n\tthis.args = args;\n\tthis.started = false;\n\tvar that = this;\n\tprocess.nextTick(function() {\n\t\tif (!that.started) {\n\t\t\tthat.started = true;\n\t\t\tFiber(function() {\n\t\t\t\ttry {\n\t\t\t\t\tthat.return(fn.apply(context, args));\n\t\t\t\t} catch(e) {\n\t\t\t\t\tthat.throw(e);\n\t\t\t\t}\n\t\t\t}).run();\n\t\t}\n\t});\n}", "async startNew(options = {}) {\n const newOptions = Object.assign({}, options, { serverSettings: this.serverSettings });\n const kernel = await kernel_1.Kernel.startNew(newOptions);\n this._onStarted(kernel);\n return kernel;\n }", "_createHandler() {\n return {\n get: (obj, methodName) => {\n if (methodName === \"then\" || methodName === \"catch\") return undefined;\n\n if (obj[methodName]) return obj[methodName];\n\n return (...args) => {\n return this._sendRequest(methodName, args, obj.hostName)\n }\n }\n }\n }", "function DOMOperationHandlerFactory() {\n this.dataMap = new DOMOperationNodeDataMap();\n}", "function FiberFuture(fn, context, args) {\n\tthis.fn = fn;\n\tthis.context = context;\n\tthis.args = args;\n\tthis.started = false;\n\taddActiveFuture(this);\n\tvar that = this;\n\tprocess.nextTick(function() {\n\t\tif (!that.started) {\n\t\t\tthat.started = true;\n\t\t\tFiber(function() {\n\t\t\t\ttry {\n\t\t\t\t\tthat.return(fn.apply(context, args));\n\t\t\t\t} catch(e) {\n\t\t\t\t\tthat.throw(e);\n\t\t\t\t}\n\t\t\t}).run();\n\t\t}\n\t});\n}", "construct(target, args, newTarget) {\n return constructTrap(target, args, newTarget);\n }", "function createFuture( init, onDemand ) {\n\tvar callbacks = [];\n\tvar values;\n\tvar future = {\n\t\t// Get the value using function callback( value )\n\t\tg: function( callback ) {\n\t\t\tif ( onDemand ) {\n\t\t\t\tonDemand = false;\n\t\t\t\tif ( init ) {\n\t\t\t\t\tinit( future );\n\t\t\t\t}\n\t\t\t}\n\t\t\tif ( callbacks ) {\n\t\t\t\tcallbacks.push( callback );\n\t\t\t} else {\n\t\t\t\tlater( callback, values );\n\t\t\t}\n\t\t},\n\t\t// Set the value (will control if not already called)\n\t\t// fires all attached callbacks if needed\n\t\ts: function() {\n\t\t\tif ( !values ) {\n\t\t\t\tvar cbs = callbacks,\n\t\t\t\t\ti = 0,\n\t\t\t\t\tlength = cbs.length;\n\t\t\t\tcallbacks = undefined;\n\t\t\t\tvalues = arguments;\n\t\t\t\tfor ( ; i < length ; i++ ) {\n\t\t\t\t\tlater( cbs[ i ], values );\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t\t// Filter the value: returns a new Future which value\n\t\t// will be equal to fn( currentFuture.value )\n\t\tf: function( fn ) {\n\t\t\treturn createFuture( function( filtered ) {\n\t\t\t\tfuture.g( function( value ) {\n\t\t\t\t\tfiltered.s( fn( value ) );\n\t\t\t\t} );\n\t\t\t}, onDemand );\n\t\t}\n\t};\n\tif ( !onDemand && init ) {\n\t\tinit( future );\n\t}\n\treturn future;\n}", "_initThriftHandler() {\n // inner msg handler\n let self = this;\n this._innerThriftProcessor = Processor;\n this._innerHandler = {\n call(cmsg, callback) {\n // get params\n let base = cmsg.base,\n caller = cmsg.call,\n service = self._services.get(caller.name);\n self.emit(EVENT.LOG.DEBUG, 'IN ' + JSON.stringify({\n id : base.id, sender: base.sender,\n alias: caller.name, action: caller.action, params: caller.params\n }));\n // set sender\n base.sender = self._id;\n // handler call\n transport.callingHandler(cmsg, service, (err, rmsg) => {\n self.emit(EVENT.LOG.DEBUG, 'OUT ' + (err || rmsg.res));\n callback(err, rmsg);\n });\n }\n };\n }", "function createDefaultAsyncHandler(callback) {\n\n var dfd = new adguard.utils.Promise();\n dfd.then(\n function (result) {\n callback(null, result);\n }, function (ex) {\n callback(ex);\n });\n\n return dfd;\n }", "function makeKernelKeeper(initialState) {\n const state = JSON.parse(`${initialState}`);\n\n function getInitialized() {\n return !!Object.getOwnPropertyDescriptor(state, 'initialized');\n }\n\n function setInitialized() {\n state.initialized = true;\n }\n\n function createStartingKernelState() {\n state.vats = {};\n state.devices = {};\n state.runQueue = [];\n state.kernelObjects = {}; // kernelObjects[koNN] = { owner: vatID }\n state.nextObjectIndex = 20;\n state.kernelDevices = {}; // kernelDevices[kdNN] = { owner: vatID }\n state.nextDeviceIndex = 30;\n state.kernelPromises = {}; // kernelPromises[kpNN] = {..}\n state.nextPromiseIndex = 40;\n }\n\n function addKernelObject(ownerVatID) {\n const id = state.nextObjectIndex;\n state.nextObjectIndex = id + 1;\n const s = makeKernelSlot('object', id);\n state.kernelObjects[s] = harden({\n owner: ownerVatID,\n });\n return s;\n }\n\n function ownerOfKernelObject(kernelSlot) {\n insistKernelType('object', kernelSlot);\n return state.kernelObjects[kernelSlot].owner;\n }\n\n function addKernelDevice(deviceName) {\n const id = state.nextDeviceIndex;\n state.nextDeviceIndex = id + 1;\n const s = makeKernelSlot('device', id);\n state.kernelDevices[s] = harden({\n owner: deviceName,\n });\n return s;\n }\n\n function ownerOfKernelDevice(kernelSlot) {\n insistKernelType('device', kernelSlot);\n return state.kernelDevices[kernelSlot].owner;\n }\n\n function addKernelPromise(deciderVatID) {\n const kpid = state.nextPromiseIndex;\n state.nextPromiseIndex = kpid + 1;\n const s = makeKernelSlot('promise', kpid);\n\n // we leave this unfrozen, because the queue and subscribers are mutable\n state.kernelPromises[s] = {\n state: 'unresolved',\n decider: deciderVatID,\n queue: [],\n subscribers: [],\n };\n\n return s;\n }\n\n function getKernelPromise(kernelSlot) {\n insistKernelType('promise', kernelSlot);\n const p = state.kernelPromises[kernelSlot];\n if (p === undefined) {\n throw new Error(`unknown kernelPromise '${kernelSlot}'`);\n }\n return p;\n }\n\n function hasKernelPromise(kernelSlot) {\n insistKernelType('promise', kernelSlot);\n return !!Object.getOwnPropertyDescriptor(state.kernelPromises, kernelSlot);\n }\n\n function fulfillKernelPromiseToPresence(kernelSlot, targetSlot) {\n insistKernelType('promise', kernelSlot);\n state.kernelPromises[kernelSlot] = harden({\n state: 'fulfilledToPresence',\n fulfillSlot: targetSlot,\n });\n }\n\n function fulfillKernelPromiseToData(kernelSlot, data, slots) {\n insistKernelType('promise', kernelSlot);\n state.kernelPromises[kernelSlot] = harden({\n state: 'fulfilledToData',\n fulfillData: data,\n fulfillSlots: slots,\n });\n }\n\n function rejectKernelPromise(kernelSlot, val, valSlots) {\n insistKernelType('promise', kernelSlot);\n state.kernelPromises[kernelSlot] = harden({\n state: 'rejected',\n rejectData: val,\n rejectSlots: valSlots,\n });\n }\n\n function deleteKernelPromiseData(kernelSlot) {\n insistKernelType('promise', kernelSlot);\n delete state.kernelPromises[kernelSlot];\n }\n\n function addMessageToPromiseQueue(kernelSlot, msg) {\n insistKernelType('promise', kernelSlot);\n const p = state.kernelPromises[kernelSlot];\n if (p === undefined) {\n throw new Error(`unknown kernelPromise '${kernelSlot}'`);\n }\n if (p.state !== 'unresolved') {\n throw new Error(`${kernelSlot} is '${p.state}', not 'unresolved'`);\n }\n p.queue.push(msg);\n }\n\n function addSubscriberToPromise(kernelSlot, vatID) {\n insistKernelType('promise', kernelSlot);\n const p = state.kernelPromises[kernelSlot];\n if (p === undefined) {\n throw new Error(`unknown kernelPromise '${kernelSlot}'`);\n }\n const subscribersSet = new Set(p.subscribers);\n subscribersSet.add(vatID);\n p.subscribers = Array.from(subscribersSet);\n }\n\n function addToRunQueue(msg) {\n state.runQueue.push(msg);\n }\n\n function isRunQueueEmpty() {\n return state.runQueue.length <= 0;\n }\n\n function getRunQueueLength() {\n return state.runQueue.length;\n }\n\n function getNextMsg() {\n return state.runQueue.shift();\n }\n\n // vatID must already exist\n function getVat(vatID) {\n const vatState = state.vats[vatID];\n if (vatState === undefined) {\n throw new Error(`unknown vatID id '${vatID}'`);\n }\n return makeVatKeeper(vatState, vatID, addKernelObject, addKernelPromise);\n }\n\n function createVat(vatID) {\n vatID = `${vatID}`;\n if (vatID in state.vats) {\n throw new Error(`vatID '${vatID}' already exists in state.vats`);\n }\n const vatState = {};\n state.vats[vatID] = vatState;\n const vk = makeVatKeeper(\n vatState,\n vatID,\n addKernelObject,\n addKernelPromise,\n );\n vk.createStartingVatState();\n return vk;\n }\n\n function getAllVatNames() {\n return Object.getOwnPropertyNames(state.vats).sort();\n }\n\n // deviceID must already exist\n function getDevice(deviceID) {\n const deviceState = state.devices[deviceID];\n if (deviceState === undefined) {\n throw new Error(`unknown deviceID id '${deviceID}'`);\n }\n return makeDeviceKeeper(\n deviceState,\n deviceID,\n addKernelObject,\n addKernelDevice,\n );\n }\n\n function createDevice(deviceID) {\n deviceID = `${deviceID}`;\n if (deviceID in state.devices) {\n throw new Error(`deviceID '${deviceID}' already exists in state.devices`);\n }\n const deviceState = {};\n state.devices[deviceID] = deviceState;\n const dk = makeDeviceKeeper(\n deviceState,\n deviceID,\n addKernelObject,\n addKernelDevice,\n );\n dk.createStartingDeviceState();\n return dk;\n }\n\n function getAllDeviceNames() {\n return Object.getOwnPropertyNames(state.devices).sort();\n }\n\n // used for persistence. This returns a JSON-serialized string, suitable to\n // be passed back into makeKernelKeeper() as 'initialState'.\n function getState() {\n return JSON.stringify(state);\n }\n\n // used for debugging, and tests. This returns a JSON-serializable object.\n // It includes references to live (mutable) kernel state, so don't mutate\n // the pieces, and be sure to serialize/deserialize before passing it\n // outside the kernel realm.\n function dump() {\n const vatTables = [];\n const kernelTable = [];\n\n for (const vatID of getAllVatNames()) {\n const vk = getVat(vatID);\n\n // TODO: find some way to expose the liveSlots internal tables, the\n // kernel doesn't see them\n const vatTable = {\n vatID,\n state: { transcript: vk.getTranscript() },\n };\n vatTables.push(vatTable);\n vk.dumpState().forEach(e => kernelTable.push(e));\n }\n\n for (const deviceName of getAllDeviceNames()) {\n const dk = getDevice(deviceName);\n dk.dumpState().forEach(e => kernelTable.push(e));\n }\n\n function compareNumbers(a, b) {\n return a - b;\n }\n\n function compareStrings(a, b) {\n if (a > b) {\n return 1;\n }\n if (a < b) {\n return -1;\n }\n return 0;\n }\n\n kernelTable.sort(\n (a, b) =>\n compareStrings(a[0], b[0]) ||\n compareStrings(a[1], b[1]) ||\n compareNumbers(a[2], b[2]) ||\n compareStrings(a[3], b[3]) ||\n compareNumbers(a[4], b[4]) ||\n compareNumbers(a[5], b[5]) ||\n 0,\n );\n\n const promises = [];\n\n const { kernelPromises } = state;\n Object.getOwnPropertyNames(kernelPromises).forEach(s => {\n const kp = { id: s };\n const p = kernelPromises[s];\n Object.defineProperties(kp, Object.getOwnPropertyDescriptors(p));\n if (p.subscribers) {\n kp.subscribers = Array.from(p.subscribers);\n }\n promises.push(kp);\n });\n promises.sort((a, b) => compareNumbers(a.id, b.id));\n\n const runQueue = Array.from(state.runQueue);\n\n return {\n vatTables,\n kernelTable,\n promises,\n runQueue,\n };\n }\n\n return harden({\n getInitialized,\n setInitialized,\n createStartingKernelState,\n\n ownerOfKernelObject,\n ownerOfKernelDevice,\n\n addKernelPromise,\n getKernelPromise,\n hasKernelPromise,\n fulfillKernelPromiseToPresence,\n fulfillKernelPromiseToData,\n rejectKernelPromise,\n deleteKernelPromiseData,\n addMessageToPromiseQueue,\n addSubscriberToPromise,\n\n addToRunQueue,\n isRunQueueEmpty,\n getRunQueueLength,\n getNextMsg,\n\n getVat,\n createVat,\n getAllVatNames,\n\n getDevice,\n createDevice,\n getAllDeviceNames,\n\n getState,\n dump,\n });\n}", "of(value) {\n let result = new Future(); // eslint-disable-line prefer-const\n result._state = Resolved(value);\n return result;\n }", "function make_handler(fun, filter) {\n return fun.exec? Handler.init.call(fun, fun.fun, filter)\n : /* otherwise */ Handler.make(fun, filter) }", "static async new(...args) {\n if (!args.length) {\n args = [null]\n }\n return new Promise(next => {\n Reflect.construct(Target, [...args, next]);\n });\n }", "handler(fn){\n this._handler = fn\n return this\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check whether the browser supports scroll behaviors.
function supportsScrollBehavior() { if (scrollBehaviorSupported == null) { // If we're not in the browser, it can't be supported. if (typeof document !== 'object' || !document) { scrollBehaviorSupported = false; } // If the element can have a `scrollBehavior` style, we can be sure that it's supported. if ('scrollBehavior' in document.documentElement.style) { scrollBehaviorSupported = true; } else { // At this point we have 3 possibilities: `scrollTo` isn't supported at all, it's // supported but it doesn't handle scroll behavior, or it has been polyfilled. var scrollToFunction = Element.prototype.scrollTo; if (scrollToFunction) { // We can detect if the function has been polyfilled by calling `toString` on it. Native // functions are obfuscated using `[native code]`, whereas if it was overwritten we'd get // the actual function source. Via https://davidwalsh.name/detect-native-function. Consider // polyfilled functions as supporting scroll behavior. scrollBehaviorSupported = !/\{\s*\[native code\]\s*\}/.test(scrollToFunction.toString()); } else { scrollBehaviorSupported = false; } } } return scrollBehaviorSupported; }
[ "function supportsScrollBehavior() {\n return !!(typeof document == 'object' && 'scrollBehavior' in document.documentElement.style);\n }", "function supportsScrollBehavior() {\n return !!(typeof document == 'object' && 'scrollBehavior' in document.documentElement.style);\n}", "function supportsScrollBehavior() {\n if (scrollBehaviorSupported == null) {\n // If we're not in the browser, it can't be supported.\n if (typeof document !== 'object' || !document) {\n scrollBehaviorSupported = false;\n } // If the element can have a `scrollBehavior` style, we can be sure that it's supported.\n\n\n if ('scrollBehavior' in document.documentElement.style) {\n scrollBehaviorSupported = true;\n } else {\n // At this point we have 3 possibilities: `scrollTo` isn't supported at all, it's\n // supported but it doesn't handle scroll behavior, or it has been polyfilled.\n var scrollToFunction = Element.prototype.scrollTo;\n\n if (scrollToFunction) {\n // We can detect if the function has been polyfilled by calling `toString` on it. Native\n // functions are obfuscated using `[native code]`, whereas if it was overwritten we'd get\n // the actual function source. Via https://davidwalsh.name/detect-native-function. Consider\n // polyfilled functions as supporting scroll behavior.\n scrollBehaviorSupported = !/\\{\\s*\\[native code\\]\\s*\\}/.test(scrollToFunction.toString());\n } else {\n scrollBehaviorSupported = false;\n }\n }\n }\n\n return scrollBehaviorSupported;\n}", "function supportsScrollBehavior() {\n if (scrollBehaviorSupported == null) {\n // If we're not in the browser, it can't be supported.\n if (typeof document !== 'object' || !document) {\n scrollBehaviorSupported = false;\n }\n // If the element can have a `scrollBehavior` style, we can be sure that it's supported.\n if ('scrollBehavior' in document.documentElement.style) {\n scrollBehaviorSupported = true;\n }\n else {\n // At this point we have 3 possibilities: `scrollTo` isn't supported at all, it's\n // supported but it doesn't handle scroll behavior, or it has been polyfilled.\n const scrollToFunction = Element.prototype.scrollTo;\n if (scrollToFunction) {\n // We can detect if the function has been polyfilled by calling `toString` on it. Native\n // functions are obfuscated using `[native code]`, whereas if it was overwritten we'd get\n // the actual function source. Via https://davidwalsh.name/detect-native-function. Consider\n // polyfilled functions as supporting scroll behavior.\n scrollBehaviorSupported = !/\\{\\s*\\[native code\\]\\s*\\}/.test(scrollToFunction.toString());\n }\n else {\n scrollBehaviorSupported = false;\n }\n }\n }\n return scrollBehaviorSupported;\n}", "function supportsScrollBehavior() {\n if (scrollBehaviorSupported == null) {\n // If we're not in the browser, it can't be supported.\n if (typeof document !== 'object' || !document) {\n scrollBehaviorSupported = false;\n return scrollBehaviorSupported;\n }\n // If the element can have a `scrollBehavior` style, we can be sure that it's supported.\n if ('scrollBehavior' in document.documentElement.style) {\n scrollBehaviorSupported = true;\n }\n else {\n // At this point we have 3 possibilities: `scrollTo` isn't supported at all, it's\n // supported but it doesn't handle scroll behavior, or it has been polyfilled.\n const scrollToFunction = Element.prototype.scrollTo;\n if (scrollToFunction) {\n // We can detect if the function has been polyfilled by calling `toString` on it. Native\n // functions are obfuscated using `[native code]`, whereas if it was overwritten we'd get\n // the actual function source. Via https://davidwalsh.name/detect-native-function. Consider\n // polyfilled functions as supporting scroll behavior.\n scrollBehaviorSupported = !/\\{\\s*\\[native code\\]\\s*\\}/.test(scrollToFunction.toString());\n }\n else {\n scrollBehaviorSupported = false;\n }\n }\n }\n return scrollBehaviorSupported;\n}", "supportScrollRestoration() {\n try {\n return !!this.window && !!this.window.scrollTo;\n }\n catch (_a) {\n return false;\n }\n }", "_canScroll(el,deltaX,deltaY){return deltaY>0&&el.scrollTop<el.scrollHeight-el.offsetHeight||deltaY<0&&el.scrollTop>0||deltaX>0&&el.scrollLeft<el.scrollWidth-el.offsetWidth||deltaX<0&&el.scrollLeft>0;}", "_canScroll(el,deltaX,deltaY){return 0<deltaY&&el.scrollTop<el.scrollHeight-el.offsetHeight||0>deltaY&&0<el.scrollTop||0<deltaX&&el.scrollLeft<el.scrollWidth-el.offsetWidth||0>deltaX&&0<el.scrollLeft}", "function userAgentNeedsCustomScrolling() {\n return userAgentIsEdge() || userAgentIsFirefoxBelowVersion(58);\n}", "_canScroll(el, deltaX, deltaY) {\n return (deltaY > 0 && el.scrollTop < el.scrollHeight - el.offsetHeight) ||\n (deltaY < 0 && el.scrollTop > 0) ||\n (deltaX > 0 && el.scrollLeft < el.scrollWidth - el.offsetWidth) ||\n (deltaX < 0 && el.scrollLeft > 0);\n }", "_canScroll(el, deltaX, deltaY) {\n return deltaY > 0 && el.scrollTop < el.scrollHeight - el.offsetHeight || deltaY < 0 && el.scrollTop > 0 || deltaX > 0 && el.scrollLeft < el.scrollWidth - el.offsetWidth || deltaX < 0 && el.scrollLeft > 0;\n }", "autoDetectScrollMode() {\n // let theInnerHtml = this.element;\n const capacity = get(this, 'capacity'),\n selector = `#${this.elementId} .uxs-tiles__item`,\n numberOfTiles = document.querySelectorAll(selector).length;\n\n const allowScroll = get(this, 'scroll');\n if(allowScroll == undefined || allowScroll) {\n if (numberOfTiles > capacity) {\n set(this, 'scroll', true);\n }\n }\n }", "get scrollingEnabled() {\n return this._getOption('scrollingEnabled');\n }", "function supportsSmoothScroll() {\n var supportsScroll = false;\n try {\n var div = document.createElement('div');\n div.scrollTo({\n top: 0,\n get behavior() {\n supportsScroll = true;\n return 'smooth';\n }\n });\n } catch (err) {\n console.log(err);\n }\n return supportsScroll;\n }", "_checkScrollingControls() {\n if (this.disablePagination) {\n this._disableScrollAfter = this._disableScrollBefore = true;\n }\n else {\n // Check if the pagination arrows should be activated.\n this._disableScrollBefore = this.scrollDistance == 0;\n this._disableScrollAfter = this.scrollDistance == this._getMaxScrollDistance();\n this._changeDetectorRef.markForCheck();\n }\n }", "function scrolling_passive(){\n var supportsPassive = false;\n try {\n document.addEventListener(\"test\", null, { get passive() { supportsPassive = true }});\n } catch(e) {}\n\n return supportsPassive;\n}", "checkScrollingControls() {\n if (this.disablePagination) {\n this.disableScrollAfter = this.disableScrollBefore = true;\n }\n else {\n // Check if the pagination arrows should be activated.\n this.disableScrollBefore = this.scrollDistance === 0;\n this.disableScrollAfter = this.scrollDistance === this.getMaxScrollDistance();\n this.changeDetectorRef.markForCheck();\n }\n }", "function CameraCommand_Scroll_IsScrollable(theHTMLObject)\n{\n\t//return either vertical or horizontal scrollability\n\treturn CameraCommand_Scroll_HasHScroll(theHTMLObject) || CameraCommand_Scroll_HasVScroll(theHTMLObject);\n}", "function isScrolled() {\n // IE...\n var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;\n if (scrollTop > 0) {\n return true;\n } else {\n return false;\n }\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function to disable breed input if cat is selected.
function disableBreedInput() { const animalInput = this.value; if (animalInput != "dog") { $("#breed").attr("disabled", "disabled"); } else if (animalInput == "dog") { $("#breed").removeAttr("disabled") } }
[ "function disableBreedInput() {\n const animalInput = this.value;\n if (animalInput == \"cat\") {\n $(\"#breed\").attr(\"disabled\", \"disabled\");\n } else if (animalInput == \"dog\") {\n $(\"#breed\").removeAttr(\"disabled\")\n }\n }", "function disableHeartCats() {\n if (!catRadio.checked) {\n disableButton(heartCats);\n }\n}", "function disableAgeInput(doDisable) {\n\tvar $age = $('#webgrouper_patient_case_age')\n\tvar $age_decoy = $('#webgrouper_patient_case_age_mode_decoy')\n\tif (doDisable) {\n\t\tvar tooltip = I18n.t(\"simple_form.hints.webgrouper_patient_case.disabled_age\");\n\t\t$age.prop('readonly', 'readonly');\n\t\t$age.prop('title', tooltip);\n\t\t$age_decoy.prop('disabled', true);\n\t\t$age_decoy.prop('title', tooltip);\n\t} else {\n\t\t$age.prop('readonly', false);\n\t\t$age.prop('title', \"\");\n\t\t$age_decoy.prop('disabled', false);\n\t\t$age_decoy.prop('title', \"\");\n\t}\n}", "function disableTermInput() {\n var value = $(this).val();\n var disable = value === 'is empty' || value === 'is not empty';\n $(this).siblings('.advanced-search-terms').prop('disabled', disable);\n }", "function disablePregnant() {\r\n let male = document.getElementById(\"male\");\r\n let pregnant = document.getElementById(\"pregnant\");\r\n let lactating = document.getElementById(\"lactating\");\r\n\r\n if (male.checked) {\r\n pregnant.disabled= true;\r\n lactating.disabled = true;\r\n }\r\n}", "function disableInputMode() {\n\tif (mode == 'A' || mode == 'O') {\n\t\t_disabldedAllInput();\n\t\t$('.remark').attr('disabled', false);\n\t}\n}", "function disable() {\r\n\taverage.disabled = true;\r\n\tconvert.disabled = true;\r\n\tfahrenInput.disabled = true;\r\n\tcelciusInput.value = '';\r\n}", "function disable_input(input){\n\tswitch($(input).attr(\"type\")){\n\t\tcase \"checkbox\":\n\t\t\tif ($( input ).prop( \"checked\" )){\n\t\t\t\tvar new_input = $(input).clone().hide();\n\t\t\t\t$(input).after(new_input);\n\t\t\t}\n\t\t\t// Fall-Through to disable original input\n\t\tdefault:\n\t\t\t$(input).prop(\"disabled\", true);\n\t}\n}", "selectCatBreed(breed) {\n this.setState({\n breed,\n cats: []\n });\n if (breed) {\n this.loadCatalogue(1, breed);\n }\n }", "function disableInput() {\n myInput.disabled = true;\n}", "function deselectDog() {\n editDogForm.reset()\n dogId = null\n}", "function btnEatDisable(value)\n\t{\n document.getElementById('btnEat').disabled = value;\n\t}", "function hideShirtColors() {\n if ($('#design').val() === 'Select Theme'){\n $('#colors-js-puns').hide();\n $('#design option').first().attr('disabled', true);\n }\n}", "function boxControl () {\n if (!$(\"#student\").prop(\"checked\")) {\n $(\"#conscript\").removeAttr(\"disabled\");\n } else {\n $(\"#conscript\").attr(\"disabled\", true);\n }\n\n if (!$(\"#conscript\").prop(\"checked\")) {\n $(\"#student\").removeAttr(\"disabled\");\n } else {\n $(\"#student\").attr(\"disabled\", true);\n }\n}", "function lockChoice(){\r\n $(\"input\").attr(\"disabled\", true);\r\n}", "disable() {\n this.setDisabled(true);\n if (this.getInputElement()) {\n this.getInputElement().setAttribute('disabled', '');\n this.getInputElement().setAttribute('style', this.style);\n }\n }", "function disablePrice() {\n $(\"#price-box\").attr(\"disabled\", true);\n $(\"#price-box\").attr(\"required\", false);\n }", "function controlDisable(controlName) {\n\n if (document.querySelector('.jester__system__select').value == 'User traits') {\n\n if (controlName != 'userLevel' && document.getElementById('userLevel').value == 'Nomad') {\n document.getElementById(controlName).disabled = true;\n }\n else if (traits[controlName].tied_to_customer == true && document.getElementById('userLevel').value == 'Customer') {\n document.getElementById(controlName).disabled = false;\n }\n else if (traits[controlName].tied_to_customer == true && document.getElementById('userLevel').value != 'Customer') {\n document.getElementById(controlName).disabled = true;\n }\n else {\n document.getElementById(controlName).disabled = false;\n }\n }\n}", "function specificCategories() {\n $('#all_cat').prop('checked', false);\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Adds a line to the scene (visible and with a hitbox)
function addWall(line) { sceneVisibleLines.push(line); sceneHitboxLines.push(line); }
[ "function addLine() {\n var line = new fabric.Line([250, 125, 250, 175], {\n fill: 'black',\n stroke: 'black',\n strokeWidth: 5\n });\n canvas.add(line);\n}", "function createLine() {\r\n graphEditor.getInteractionHandler().setActiveInteraction(new JSG.graph.interaction.CreateEdgeInteraction(new JSG.graph.model.Edge()));\r\n}", "_createLine() {\n let line = this.createLine();\n line.style.position = 'absolute';\n this._lines.push(line);\n this._lineContainer.appendChild(line);\n }", "function addLine() {\n _createLine()\n}", "beginLine(event) {\n let position = getPixelCoordsOfEvent(event);\n setPreview({\n origin: position,\n destination: position,\n radius: radius,\n tool: TOOLS.line\n });\n }", "function addLine(){\n\t// Declare and set variables\n\tvar x = document.getElementById(\"addShapes\").getContext(\"2d\");\n\t\n\t// Now add the line to the canvas\n\tx.beginPath();\n\tx.moveTo(100, 100);\n\tx.lineTo(40, 40);\n\tx.strokeStyle = \"blue\";\n\tx.stroke();\n}", "function addLine(layer, lineColor = 'black') {\n\tmouse.status = mouseStatus.other;\n\tsetAllBtnColor();\n\tlet line = new fabric.Line(\n\t\t[480, 315, 580, 315],\n\t\t{\n\t\t\tstroke: lineColor,\n\t\t\tstrokeWidth: 2,\n\t\t});\n\tlayer.add(line);\n\tline.name = 'shape';\n}", "function addLine() {\r\n\r\n let direction = 2;\r\n\r\n const cLineData = {\r\n startxy: width / 2,\r\n direction: direction\r\n }\r\n\r\n const mLineData = {\r\n startxy: width / 2,\r\n direction: direction\r\n }\r\n\r\n cLines.push(cLineData);\r\n mLines.push(mLineData);\r\n\r\n}", "_enterDrawLineOnBuffer() {\n // tw: reset attributes when starting pen drawing\n this._resetAttributeIndexes();\n\n const gl = this._renderer.gl;\n twgl.bindFramebufferInfo(gl, this._framebuffer);\n gl.viewport(0, 0, this._size[0], this._size[1]);\n const currentShader = this._lineShader;\n gl.useProgram(currentShader.program);\n twgl.setBuffersAndAttributes(gl, currentShader, this._lineBufferInfo);\n const uniforms = {\n u_skin: this._texture,\n u_stageSize: this._size\n };\n twgl.setUniforms(currentShader, uniforms);\n }", "_enterDrawLineOnBuffer () {\n const gl = this._renderer.gl;\n\n const bounds = this._bounds;\n const currentShader = this._lineShader;\n const projection = twgl.m4.ortho(0, bounds.width, 0, bounds.height, -1, 1, __projectionMatrix);\n\n twgl.bindFramebufferInfo(gl, this._framebuffer);\n\n gl.viewport(0, 0, bounds.width, bounds.height);\n\n gl.useProgram(currentShader.program);\n\n twgl.setBuffersAndAttributes(gl, currentShader, this._lineBufferInfo);\n\n const uniforms = {\n u_skin: this._texture,\n u_projectionMatrix: projection\n };\n\n twgl.setUniforms(currentShader, uniforms);\n }", "function drawLine(fromX, fromY, toX, toY) {\n\n var line = new createjs.Shape();\n updateLine(line, fromX, fromY, toX, toY);\n stage.addChild(line);\n\n return line;\n}", "drawOn(scene) {\n this.sprite = new SHAPES2D.Line(\n {x: this.isHorizontal ? this.start : this.position,\n y: this.isHorizontal ? this.position : this.start, z: 0.0},\n {x: this.isHorizontal ? this.end : this.position,\n y: this.isHorizontal ? this.position : this.end, z: 0.0});\n this.sprite.addTo(scene);\n }", "embedLine(line)\n {\n EX.postProcessor.embedAnotherPolyline(line);\n this.faces = EX.postProcessor.generate_faces_info();\n\n colorGraph(this.faces);\n }", "function addWellPath(x, y, z) {\r\n \r\n var newPoint = v(x,y,z);\r\n\r\n //==|| The New Line material\r\n var theNewLineMaterial = new THREE.LineBasicMaterial( {\r\n transparent: true,\r\n color: WELLVIS.theWellLineColor,\r\n opacity: WELLVIS.theWellLineOpacity, \r\n lineWidth: 1\r\n }\r\n );\r\n\r\n\r\n //==|| The New Line Geometry\r\n var theNewLineGeo = new THREE.Geometry();\r\n theNewLineGeo.vertices.push(\r\n WELLVIS.thePreviousPoint, newPoint\r\n );\r\n\r\n\r\n //==|| The New Line\r\n var theNewLine = new THREE.Line(theNewLineGeo, theNewLineMaterial);\r\n theNewLine.type = THREE.Lines;\r\n\r\n\r\n //==|| Add the line to the list of wellPath Lines\r\n WELLVIS.theWellPathArray.push(new TheLine(WELLVIS.thePreviousPoint, newPoint, WELLVIS.theWellLineColor, 1, WELLVIS.theWellLineOpacity) );\r\n\r\n //==|| Add the new line to the Well Path object in the scene\r\n WELLVIS.theWellPath.add(theNewLine);\r\n\r\n //==|| Keeping the list\r\n WELLVIS.theWellPathList.push(theNewLine);\r\n\r\n //==|| Now new point becomes the previous point\r\n WELLVIS.thePreviousPoint = newPoint;\r\n\r\n\r\n\r\n\r\n}", "display(){\r\n line(this.startPoint.x, this.startPoint.y,this.endPoint.x, this.endPoint.y);\r\n }", "function extendLine(evt, hotspot) {\n let svg = interaction.querySelector(\"svg\");\n\n if (!line && hotspot) {\n line = document.createElementNS(SVG_NS,\"line\");\n let {cx:cx, cy:cy} = getDimensions(hotspot);\n line.setAttribute(\"x1\", cx);\n line.setAttribute(\"y1\", cy);\n line.setAttribute(\"x2\", cx);\n line.setAttribute(\"y2\", cy);\n line.setAttribute(ENDPOINT1, hotspot.getAttribute(ID));\n hotspot.classList.add(ENDPOINT);\n svg.insertBefore(line,svg.firstElementChild);\n interaction.onmousemove = extendLine;\n } else {\n let [x,y] = viewboxOffset(svg, evt.x, evt.y);\n line.setAttribute(\"x2\",x);\n line.setAttribute(\"y2\",y);\n }\n evt.stopPropagation();\n }", "function updateLine()\n{\n\t//clear previous line\n\tlineGraphics.clear();\n\t\n\t//stroke style\n\tlineGraphics.setStrokeStyle(1);\n\t\n\t//stroke color\n\tlineGraphics.beginStroke(targetColor);\n\t\n\t//draw the line between the mouse target and the drone\n\tlineGraphics.moveTo(targetShape.x, targetShape.y);\n\tlineGraphics.lineTo(lastDrone.x, lastDrone.y);\n}", "function drawLine(){\n if(mouseDown){\n c.beginPath();\n c.strokeStyle = 'rgba(0,0,0, 0.75)'; \n c.moveTo(ballX + (ballRadius/2), ballY + (ballRadius/2));\n c.lineTo(mouseX, mouseY);\n c.lineWidth = \"2\";\n c.stroke();\n }\n}", "function useLifeLine(){\r\n \r\n LifeLineGround.visible = true\r\n LifeLineGround.x = Joey.x\r\n LifeLineGround.y = Joey.y + 50\r\n LifeLineGround.lifetime = 800\r\n CollideGroup.add(LifeLineGround)\r\n LifeLineIcon.visible = false\r\n LifeLineIcon.x = 2000\r\n LifelineButton.remove();\r\n LifeLineused = yes\r\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns relevant section of custom format specifier.
getRelevantFormatSection(sections, number) { const that = this, compareResult = that.numericProcessor.compare(number, 0, true); if (compareResult === 1) { return sections[0]; } let negativeNumberGroup, zeroGroup; if (sections.length >= 3) { that._ignoreMinus = true; negativeNumberGroup = 1; zeroGroup = 2; } else if (sections.length === 2) { that._ignoreMinus = true; zeroGroup = 0; negativeNumberGroup = 1; } else if (sections.length === 1) { zeroGroup = 0; negativeNumberGroup = 0; } if (compareResult === 0) { return sections[zeroGroup]; } if (compareResult === -1) { return sections[negativeNumberGroup]; } }
[ "static get Format () {}", "GetFormat() {\n\n }", "function getSpecifierText(specifier) {\n return `${specifier.local.name}${specifier.exported.name !== specifier.local.name\n ? ` as ${specifier.exported.name}`\n : ''}`;\n}", "applyCustomFormat(number, formatSpecifier) {\n const that = this;\n\n //formatSpecifier = formatSpecifier.replace(/_.|\\[\\w*\\]|.\\*|\\*./g, '');\n formatSpecifier = formatSpecifier.replace(/_.|\\[\\w*\\]|\\*/g, '');\n formatSpecifier = formatSpecifier.replace(/\\?/g, '#');\n\n const sections = formatSpecifier.split(';');\n\n if (typeof number === 'string' && isNaN(number)) {\n return sections[sections.length - 1].replace(/\"/g, '').replace(/@/g, number.toString());\n }\n\n if (number._d) {\n that.inputFormat = 'integer';\n }\n else if (number.imaginaryPart) {\n return number.toString();\n }\n else {\n number = parseFloat(number);\n that.inputFormat = 'floatingPoint';\n }\n\n let numericProcessor = new Smart.Utilities.NumericProcessor(that, 'inputFormat'),\n numericObject = numericProcessor.createDescriptor(number);\n\n if (that.inputFormat === 'integer') {\n numericObject = numericProcessor.round(numericObject);\n }\n\n that.numericProcessor = numericProcessor;\n\n const currentSection = that.getRelevantFormatSection(sections, numericObject);\n\n if (currentSection === undefined) {\n return number.toString();\n }\n\n if (currentSection.indexOf('@') !== -1) {\n return sections[sections.length - 1].replace(/\"/g, '').replace(/@/g, number.toString());\n }\n\n const percentage = currentSection.replace(/\".*\"/g, '').indexOf('%') !== -1,\n textParts = that.getTextParts(currentSection);\n\n if (textParts.main.toLowerCase().indexOf('e') !== -1) {\n return that.applyCustomExponentialFormat(numericObject, textParts, numericProcessor);\n }\n\n if (textParts.main.indexOf('/') !== -1) {\n return that.applyCustomFractionalFormat(numericObject, textParts, numericProcessor);\n }\n\n if (percentage) {\n if (that.inputFormat === 'integer') {\n numericObject = numericObject.multiply(100);\n }\n else {\n numericObject = numericObject * 100;\n }\n }\n\n if (textParts.main === '') {\n if (!percentage) {\n return textParts.suffix;\n }\n\n let stringifiedNumber = numericObject.toString();\n\n if (that._ignoreMinus && stringifiedNumber.charAt(0) === '-') {\n stringifiedNumber = stringifiedNumber.slice(1);\n }\n\n return stringifiedNumber + textParts.suffix;\n }\n\n let numberFormat = textParts.main.replace(/[^0#,. \\/]/g, ''),\n indexOfPoint = numberFormat.indexOf('.');\n\n if (indexOfPoint !== -1) {\n numberFormat = numberFormat.substring(0, indexOfPoint + 1) + numberFormat.substring(indexOfPoint + 1).replace(/\\./g, '');\n\n // removes unnecessary trailing zero\n if (numberFormat.charAt(numberFormat.length - 1) === '.') {\n numberFormat = numberFormat.slice(0, numberFormat.length - 1);\n }\n\n if (indexOfPoint === 0) {\n numberFormat = '#' + numberFormat;\n }\n }\n\n // scales the number down by 1000 for every trailing comma\n while (numberFormat.charAt(numberFormat.length - 1) === ',') {\n numberFormat = numberFormat.slice(0, numberFormat.length - 1);\n\n if (that.inputFormat === 'floatingPoint') {\n numericObject /= 1000;\n }\n else {\n numericObject = numericObject.multiply(0.001);\n }\n }\n\n if (that.inputFormat === 'integer') {\n numericObject = numericProcessor.round(numericObject);\n }\n\n const thousandsSeparator = numberFormat.indexOf(',') !== -1;\n\n numberFormat = numberFormat.replace(/,/g, '');\n\n const numberFormatParts = numberFormat.split('.'),\n wholePartFormat = numberFormatParts[0];\n let decimalPartFormat = numberFormatParts[1],\n result = '';\n\n if (numberFormatParts.length === 1) {\n if (that.inputFormat === 'floatingPoint') {\n numericObject = numericProcessor.round(numericObject);\n }\n\n result = numericObject.toString();\n\n return that.setTextParts(that.formatWholeNumber(result, wholePartFormat, thousandsSeparator), textParts);\n }\n\n result = numericObject.toString();\n\n let numberParts = result.split('.'),\n formattedWholeNumber = that.formatWholeNumber(numberParts[0], wholePartFormat, thousandsSeparator),\n decimalNumber = numberParts[1] || '';\n\n if (decimalPartFormat.length <= decimalNumber.length) {\n result = parseFloat(numericObject.toFixed(decimalPartFormat.length)).toString();\n numberParts = result.split('.');\n formattedWholeNumber = that.formatWholeNumber(numberParts[0], wholePartFormat, thousandsSeparator);\n decimalNumber = numberParts[1] || '';\n\n if (decimalNumber) {\n return that.setTextParts(formattedWholeNumber + that.localizationObject.decimalseparator + decimalNumber.slice(0, decimalPartFormat.length), textParts);\n }\n }\n\n decimalPartFormat = decimalPartFormat.slice(decimalNumber.length - decimalPartFormat.length);\n\n let lastZeroIndex = decimalPartFormat.lastIndexOf('0');\n\n if (lastZeroIndex === -1) {\n if (decimalNumber === '') {\n return that.setTextParts(formattedWholeNumber, textParts);\n }\n\n return that.setTextParts(formattedWholeNumber + that.localizationObject.decimalseparator + decimalNumber, textParts);\n }\n else {\n return that.setTextParts(formattedWholeNumber + that.localizationObject.decimalseparator + decimalNumber + '0'.repeat(lastZeroIndex + 1), textParts);\n }\n }", "applyCustomFormat(number, formatSpecifier) {\n const that = this;\n\n formatSpecifier = formatSpecifier.replace(/_.|\\[\\w*\\]|.\\*|\\*./g, '');\n formatSpecifier = formatSpecifier.replace(/\\?/g, '#');\n\n const sections = formatSpecifier.split(';');\n\n if (typeof number === 'string' && isNaN(number)) {\n return sections[sections.length - 1].replace(/\"/g, '').replace(/@/g, number.toString());\n }\n\n if (number._d) {\n that.inputFormat = 'integer';\n }\n else if (number.imaginaryPart) {\n return number.toString();\n }\n else {\n number = parseFloat(number);\n that.inputFormat = 'floatingPoint';\n }\n\n let numericProcessor = new JQX.Utilities.NumericProcessor(that, 'inputFormat'),\n numericObject = numericProcessor.createDescriptor(number);\n\n if (that.inputFormat === 'integer') {\n numericObject = numericProcessor.round(numericObject);\n }\n\n that.numericProcessor = numericProcessor;\n\n const currentSection = that.getRelevantFormatSection(sections, numericObject);\n\n if (currentSection === undefined) {\n return number.toString();\n }\n\n if (currentSection.indexOf('@') !== -1) {\n return sections[sections.length - 1].replace(/\"/g, '').replace(/@/g, number.toString());\n }\n\n const percentage = currentSection.replace(/\".*\"/g, '').indexOf('%') !== -1,\n textParts = that.getTextParts(currentSection);\n\n if (textParts.main.toLowerCase().indexOf('e') !== -1) {\n return that.applyCustomExponentialFormat(numericObject, textParts, numericProcessor);\n }\n\n if (textParts.main.indexOf('/') !== -1) {\n return that.applyCustomFractionalFormat(numericObject, textParts, numericProcessor);\n }\n\n if (percentage) {\n if (that.inputFormat === 'integer') {\n numericObject = numericObject.multiply(100);\n }\n else {\n numericObject = Math.round(numericObject * 100);\n }\n }\n\n if (textParts.main === '') {\n if (!percentage) {\n return textParts.suffix;\n }\n\n let stringifiedNumber = numericObject.toString();\n\n if (that._ignoreMinus && stringifiedNumber.charAt(0) === '-') {\n stringifiedNumber = stringifiedNumber.slice(1);\n }\n\n return stringifiedNumber + textParts.suffix;\n }\n\n let numberFormat = textParts.main.replace(/[^0#,. \\/]/g, ''),\n indexOfPoint = numberFormat.indexOf('.');\n\n if (indexOfPoint !== -1) {\n numberFormat = numberFormat.substring(0, indexOfPoint + 1) + numberFormat.substring(indexOfPoint + 1).replace(/\\./g, '');\n\n // removes unnecessary trailing zero\n if (numberFormat.charAt(numberFormat.length - 1) === '.') {\n numberFormat = numberFormat.slice(0, numberFormat.length - 1);\n }\n\n if (indexOfPoint === 0) {\n numberFormat = '#' + numberFormat;\n }\n }\n\n // scales the number down by 1000 for every trailing comma\n while (numberFormat.charAt(numberFormat.length - 1) === ',') {\n numberFormat = numberFormat.slice(0, numberFormat.length - 1);\n\n if (that.inputFormat === 'floatingPoint') {\n numericObject /= 1000;\n }\n else {\n numericObject = numericObject.multiply(0.001);\n }\n }\n\n if (that.inputFormat === 'integer') {\n numericObject = numericProcessor.round(numericObject);\n }\n\n const thousandsSeparator = numberFormat.indexOf(',') !== -1;\n\n numberFormat = numberFormat.replace(/,/g, '');\n\n const numberFormatParts = numberFormat.split('.'),\n wholePartFormat = numberFormatParts[0];\n let decimalPartFormat = numberFormatParts[1],\n result = '';\n\n if (numberFormatParts.length === 1) {\n if (that.inputFormat === 'floatingPoint') {\n numericObject = numericProcessor.round(numericObject);\n }\n\n result = numericObject.toString();\n\n return that.setTextParts(that.formatWholeNumber(result, wholePartFormat, thousandsSeparator), textParts);\n }\n\n result = numericObject.toString();\n\n let numberParts = result.split('.'),\n formattedWholeNumber = that.formatWholeNumber(numberParts[0], wholePartFormat, thousandsSeparator),\n decimalNumber = numberParts[1] || '';\n\n if (decimalPartFormat.length <= decimalNumber.length) {\n result = parseFloat(numericObject.toFixed(decimalPartFormat.length)).toString();\n numberParts = result.split('.');\n formattedWholeNumber = that.formatWholeNumber(numberParts[0], wholePartFormat, thousandsSeparator);\n decimalNumber = numberParts[1] || '';\n\n if (decimalNumber) {\n return that.setTextParts(formattedWholeNumber + that.localizationObject.decimalseparator + decimalNumber.slice(0, decimalPartFormat.length), textParts);//\n }\n }\n\n decimalPartFormat = decimalPartFormat.slice(decimalNumber.length - decimalPartFormat.length);\n\n let lastZeroIndex = decimalPartFormat.lastIndexOf('0');\n\n if (lastZeroIndex === -1) {\n if (decimalNumber === '') {\n return that.setTextParts(formattedWholeNumber, textParts);\n }\n\n return that.setTextParts(formattedWholeNumber + that.localizationObject.decimalseparator + decimalNumber, textParts);\n }\n else {\n return that.setTextParts(formattedWholeNumber + that.localizationObject.decimalseparator + decimalNumber + '0'.repeat(lastZeroIndex + 1), textParts);\n }\n }", "retrieveSectionFormat(start, end) {\n let startParaSection = this.getContainerWidget(start.paragraph);\n let endParaSection = this.getContainerWidget(end.paragraph);\n if (!isNullOrUndefined(startParaSection)) {\n this.sectionFormat.copyFormat(startParaSection.sectionFormat);\n let startPageIndex = this.viewer.pages.indexOf(startParaSection.page);\n let endPageIndex = this.viewer.pages.indexOf(endParaSection.page);\n for (let i = startPageIndex + 1; i <= endPageIndex; i++) {\n this.sectionFormat.combineFormat(this.viewer.pages[i].bodyWidgets[0].sectionFormat);\n }\n }\n }", "getFormatString(unit) {\r\n switch (unit) {\r\n case DateTimeUnit.Year:\r\n return this.YearPattern;\r\n case DateTimeUnit.Month:\r\n return this.MonthPattern;\r\n case DateTimeUnit.Week:\r\n case DateTimeUnit.Day:\r\n return this.DayPattern;\r\n case DateTimeUnit.Hour:\r\n return this.HourPattern;\r\n case DateTimeUnit.Minute:\r\n return this.MinutePattern;\r\n case DateTimeUnit.Second:\r\n return this.SecondPattern;\r\n case DateTimeUnit.Millisecond:\r\n return this.MillisecondPattern;\r\n }\r\n }", "function getFormat(format) {\n // Undefined?\n if (typeof format === \"undefined\") {\n return _Strings__WEBPACK_IMPORTED_MODULE_5__[\"STRING\"];\n } // Cleanup and lowercase format\n\n\n format = format.toLowerCase().replace(/^\\[[^\\]]*\\]/, \"\"); // Remove style tags\n\n format = format.replace(/\\[[^\\]]+\\]/, \"\"); // Trim\n\n format = format.trim(); // Check for any explicit format hints (i.e. /Date)\n\n var hints = format.match(/\\/(date|number|duration)$/);\n\n if (hints) {\n return hints[1];\n } // Check for explicit hints\n\n\n if (format === _Strings__WEBPACK_IMPORTED_MODULE_5__[\"NUMBER\"]) {\n return _Strings__WEBPACK_IMPORTED_MODULE_5__[\"NUMBER\"];\n }\n\n if (format === _Strings__WEBPACK_IMPORTED_MODULE_5__[\"DATE\"]) {\n return _Strings__WEBPACK_IMPORTED_MODULE_5__[\"DATE\"];\n }\n\n if (format === _Strings__WEBPACK_IMPORTED_MODULE_5__[\"DURATION\"]) {\n return _Strings__WEBPACK_IMPORTED_MODULE_5__[\"DURATION\"];\n } // Detect number formatting symbols\n\n\n if (format.match(/[#0]/)) {\n return _Strings__WEBPACK_IMPORTED_MODULE_5__[\"NUMBER\"];\n } // Detect date formatting symbols\n\n\n if (format.match(/[ymwdhnsqaxkzgtei]/)) {\n return _Strings__WEBPACK_IMPORTED_MODULE_5__[\"DATE\"];\n } // Nothing? Let's display as string\n\n\n return _Strings__WEBPACK_IMPORTED_MODULE_5__[\"STRING\"];\n }", "applyCustomFormat(number, formatSpecifier) {\n const that = this;\n\n //formatSpecifier = formatSpecifier.replace(/_.|\\[\\w*\\]|.\\*|\\*./g, '');\n formatSpecifier = formatSpecifier.replace(/_.|\\[\\w*\\]|\\*/g, '');\n formatSpecifier = formatSpecifier.replace(/\\?/g, '#');\n\n const sections = formatSpecifier.split(';');\n\n if (typeof number === 'string' && isNaN(number)) {\n return sections[sections.length - 1].replace(/\"/g, '').replace(/@/g, number.toString());\n }\n\n if (number._d) {\n that.inputFormat = 'integer';\n }\n else if (number.imaginaryPart) {\n return number.toString();\n }\n else {\n number = parseFloat(number);\n that.inputFormat = 'floatingPoint';\n }\n\n let numericProcessor = new JQX.Utilities.NumericProcessor(that, 'inputFormat'),\n numericObject = numericProcessor.createDescriptor(number);\n\n if (that.inputFormat === 'integer') {\n numericObject = numericProcessor.round(numericObject);\n }\n\n that.numericProcessor = numericProcessor;\n\n const currentSection = that.getRelevantFormatSection(sections, numericObject);\n\n if (currentSection === undefined) {\n return number.toString();\n }\n\n if (currentSection.indexOf('@') !== -1) {\n return sections[sections.length - 1].replace(/\"/g, '').replace(/@/g, number.toString());\n }\n\n const percentage = currentSection.replace(/\".*\"/g, '').indexOf('%') !== -1,\n textParts = that.getTextParts(currentSection);\n\n if (textParts.main.toLowerCase().indexOf('e') !== -1) {\n return that.applyCustomExponentialFormat(numericObject, textParts, numericProcessor);\n }\n\n if (textParts.main.indexOf('/') !== -1) {\n return that.applyCustomFractionalFormat(numericObject, textParts, numericProcessor);\n }\n\n if (percentage) {\n if (that.inputFormat === 'integer') {\n numericObject = numericObject.multiply(100);\n }\n else {\n numericObject = numericObject * 100;\n }\n }\n\n if (textParts.main === '') {\n if (!percentage) {\n return textParts.suffix;\n }\n\n let stringifiedNumber = numericObject.toString();\n\n if (that._ignoreMinus && stringifiedNumber.charAt(0) === '-') {\n stringifiedNumber = stringifiedNumber.slice(1);\n }\n\n return stringifiedNumber + textParts.suffix;\n }\n\n let numberFormat = textParts.main.replace(/[^0#,. \\/]/g, ''),\n indexOfPoint = numberFormat.indexOf('.');\n\n if (indexOfPoint !== -1) {\n numberFormat = numberFormat.substring(0, indexOfPoint + 1) + numberFormat.substring(indexOfPoint + 1).replace(/\\./g, '');\n\n // removes unnecessary trailing zero\n if (numberFormat.charAt(numberFormat.length - 1) === '.') {\n numberFormat = numberFormat.slice(0, numberFormat.length - 1);\n }\n\n if (indexOfPoint === 0) {\n numberFormat = '#' + numberFormat;\n }\n }\n\n // scales the number down by 1000 for every trailing comma\n while (numberFormat.charAt(numberFormat.length - 1) === ',') {\n numberFormat = numberFormat.slice(0, numberFormat.length - 1);\n\n if (that.inputFormat === 'floatingPoint') {\n numericObject /= 1000;\n }\n else {\n numericObject = numericObject.multiply(0.001);\n }\n }\n\n if (that.inputFormat === 'integer') {\n numericObject = numericProcessor.round(numericObject);\n }\n\n const thousandsSeparator = numberFormat.indexOf(',') !== -1;\n\n numberFormat = numberFormat.replace(/,/g, '');\n\n const numberFormatParts = numberFormat.split('.'),\n wholePartFormat = numberFormatParts[0];\n let decimalPartFormat = numberFormatParts[1],\n result = '';\n\n if (numberFormatParts.length === 1) {\n if (that.inputFormat === 'floatingPoint') {\n numericObject = numericProcessor.round(numericObject);\n }\n\n result = numericObject.toString();\n\n return that.setTextParts(that.formatWholeNumber(result, wholePartFormat, thousandsSeparator), textParts);\n }\n\n result = numericObject.toString();\n\n let numberParts = result.split('.'),\n formattedWholeNumber = that.formatWholeNumber(numberParts[0], wholePartFormat, thousandsSeparator),\n decimalNumber = numberParts[1] || '';\n\n if (decimalPartFormat.length <= decimalNumber.length) {\n result = parseFloat(numericObject.toFixed(decimalPartFormat.length)).toString();\n numberParts = result.split('.');\n formattedWholeNumber = that.formatWholeNumber(numberParts[0], wholePartFormat, thousandsSeparator);\n decimalNumber = numberParts[1] || '';\n\n if (decimalNumber) {\n return that.setTextParts(formattedWholeNumber + that.localizationObject.decimalseparator + decimalNumber.slice(0, decimalPartFormat.length), textParts);\n }\n }\n\n decimalPartFormat = decimalPartFormat.slice(decimalNumber.length - decimalPartFormat.length);\n\n let lastZeroIndex = decimalPartFormat.lastIndexOf('0');\n\n if (lastZeroIndex === -1) {\n if (decimalNumber === '') {\n return that.setTextParts(formattedWholeNumber, textParts);\n }\n\n return that.setTextParts(formattedWholeNumber + that.localizationObject.decimalseparator + decimalNumber, textParts);\n }\n else {\n return that.setTextParts(formattedWholeNumber + that.localizationObject.decimalseparator + decimalNumber + '0'.repeat(lastZeroIndex + 1), textParts);\n }\n }", "get labelFormat() {\n return this.i.d9;\n }", "function getFormat(format) {\n // Undefined?\n if (typeof format === \"undefined\") {\n return _Strings__WEBPACK_IMPORTED_MODULE_5__[\"STRING\"];\n }\n // Cleanup and lowercase format\n format = format.toLowerCase().replace(/^\\[[^\\]]*\\]/, \"\");\n // Remove style tags\n format = format.replace(/\\[[^\\]]+\\]/, \"\");\n // Trim\n format = format.trim();\n // Check for any explicit format hints (i.e. /Date)\n var hints = format.match(/\\/(date|number|duration)$/);\n if (hints) {\n return hints[1];\n }\n // Check for explicit hints\n if (format === _Strings__WEBPACK_IMPORTED_MODULE_5__[\"NUMBER\"]) {\n return _Strings__WEBPACK_IMPORTED_MODULE_5__[\"NUMBER\"];\n }\n if (format === _Strings__WEBPACK_IMPORTED_MODULE_5__[\"DATE\"]) {\n return _Strings__WEBPACK_IMPORTED_MODULE_5__[\"DATE\"];\n }\n if (format === _Strings__WEBPACK_IMPORTED_MODULE_5__[\"DURATION\"]) {\n return _Strings__WEBPACK_IMPORTED_MODULE_5__[\"DURATION\"];\n }\n // Detect number formatting symbols\n if (format.match(/[#0]/)) {\n return _Strings__WEBPACK_IMPORTED_MODULE_5__[\"NUMBER\"];\n }\n // Detect date formatting symbols\n if (format.match(/[ymwdhnsqaxkzgtei]/)) {\n return _Strings__WEBPACK_IMPORTED_MODULE_5__[\"DATE\"];\n }\n // Nothing? Let's display as string\n return _Strings__WEBPACK_IMPORTED_MODULE_5__[\"STRING\"];\n}", "function fmt(formatContext) /* (formatContext : formatContext) -> common/formatter */ {\n return formatContext.fmt;\n}", "function getFormat(format) {\r\n // Undefined?\r\n if (typeof format === \"undefined\")\r\n return _Strings__WEBPACK_IMPORTED_MODULE_4__[\"STRING\"];\r\n // Cleanup and lowercase format\r\n format = format.toLowerCase().replace(/^\\[[^\\]]*\\]/, \"\");\r\n // Remove style tags\r\n format = format.replace(/\\[[^\\]]+\\]/, \"\");\r\n // Trim\r\n format = format.trim();\r\n // Check for any explicit format hints (i.e. /Date)\r\n var hints = format.match(/\\/(date|number|duration)$/);\r\n if (hints) {\r\n return hints[1];\r\n }\r\n // Check for explicit hints\r\n if (format === _Strings__WEBPACK_IMPORTED_MODULE_4__[\"NUMBER\"]) {\r\n return _Strings__WEBPACK_IMPORTED_MODULE_4__[\"NUMBER\"];\r\n }\r\n if (format === _Strings__WEBPACK_IMPORTED_MODULE_4__[\"DATE\"]) {\r\n return _Strings__WEBPACK_IMPORTED_MODULE_4__[\"DATE\"];\r\n }\r\n if (format === _Strings__WEBPACK_IMPORTED_MODULE_4__[\"DURATION\"]) {\r\n return _Strings__WEBPACK_IMPORTED_MODULE_4__[\"DURATION\"];\r\n }\r\n // Detect number formatting symbols\r\n if (format.match(/[#0]/)) {\r\n return _Strings__WEBPACK_IMPORTED_MODULE_4__[\"NUMBER\"];\r\n }\r\n // Detect date formatting symbols\r\n if (format.match(/[ymwdhnsqaxkzgtei]/)) {\r\n return _Strings__WEBPACK_IMPORTED_MODULE_4__[\"DATE\"];\r\n }\r\n // Nothing? Let's display as string\r\n return _Strings__WEBPACK_IMPORTED_MODULE_4__[\"STRING\"];\r\n}", "function formatSpec(spec)\n {\n if (spec.long != null && spec.short != null)\n return '--' + spec.long + ', ' + '-' + spec.short;\n else if (spec.long != null)\n return '--' + spec.long;\n else if (spec.short != null)\n return '-' + spec.short;\n }", "function getFormat(format) {\n // Undefined?\n if (typeof format === \"undefined\") {\n return $strings.STRING;\n } // Cleanup and lowercase format\n\n\n format = format.toLowerCase().replace(/^\\[[^\\]]*\\]/, \"\"); // Remove style tags\n\n format = format.replace(/\\[[^\\]]+\\]/, \"\"); // Trim\n\n format = format.trim(); // Check for any explicit format hints (i.e. /Date)\n\n var hints = format.match(/\\/(date|number|duration)$/);\n\n if (hints) {\n return hints[1];\n } // Check for explicit hints\n\n\n if (format === $strings.NUMBER) {\n return $strings.NUMBER;\n }\n\n if (format === $strings.DATE) {\n return $strings.DATE;\n }\n\n if (format === $strings.DURATION) {\n return $strings.DURATION;\n } // Detect number formatting symbols\n\n\n if (format.match(/[#0]/)) {\n return $strings.NUMBER;\n } // Detect date formatting symbols\n\n\n if (format.match(/[ymwdhnsqaxkzgtei]/)) {\n return $strings.DATE;\n } // Nothing? Let's display as string\n\n\n return $strings.STRING;\n}", "function recordFormat(record) {\n\t\tconst leader = record.leader;\n\t\tconst l6 = leader.slice(6, 7);\n\t\tconst l7 = leader.slice(7, 8);\n\t\tif (l6 === 'm') {\n\t\t\treturn 'CF';\n\t\t}\n\n\t\tif (['a', 't'].includes(l6) && ['b', 'i', 's'].includes(l7)) {\n\t\t\treturn 'CR';\n\t\t}\n\n\t\tif (['e', 'f'].includes(l6)) {\n\t\t\treturn 'MP';\n\t\t}\n\n\t\tif (['c', 'd', 'i', 'j'].includes(l6)) {\n\t\t\treturn 'MU';\n\t\t}\n\n\t\tif (l6 === 'p') {\n\t\t\treturn 'MX';\n\t\t}\n\n\t\tif (['g', 'k', 'o', 'r'].includes(l6)) {\n\t\t\treturn 'VM';\n\t\t}\n\n\t\treturn 'BK';\n\t}", "function getFormat(format) {\n // Undefined?\n if (typeof format === \"undefined\") {\n return STRING;\n }\n // Cleanup and lowercase format\n format = format.toLowerCase().replace(/^\\[[^\\]]*\\]/, \"\");\n // Remove style tags\n format = format.replace(/\\[[^\\]]+\\]/, \"\");\n // Trim\n format = format.trim();\n // Check for any explicit format hints (i.e. /Date)\n var hints = format.match(/\\/(date|number|duration)$/);\n if (hints) {\n return hints[1];\n }\n // Check for explicit hints\n if (format === NUMBER) {\n return NUMBER;\n }\n if (format === DATE) {\n return DATE;\n }\n if (format === DURATION) {\n return DURATION;\n }\n // Detect number formatting symbols\n if (format.match(/[#0]/)) {\n return NUMBER;\n }\n // Detect date formatting symbols\n if (format.match(/[ymwdhnsqaxkzgtei]/)) {\n return DATE;\n }\n // Nothing? Let's display as string\n return STRING;\n}", "function format() {\n\t\t\tif (arguments.length === 0) {\n\t\t\t\treturn undefined;\n\t\t\t}\n\t\t\tvar fmt = arguments[0];\n\t\t\tvar re = /(?:\\{(.*?)\\})/g;\n\t\t\tvar args = arguments;\n\t\t\tvar text = fmt.replace(re, function (match, token) {\n\t\t\t\tvar idxFmt = token.split(\":\", 2);\n\t\t\t\tvar idxAlignment = idxFmt.shift().split(\",\", 2);\n\t\t\t\tvar arg = args[parseInt(idxAlignment[0], 10) + 1];\n\t\t\t\tvar argFmt = idxFmt.shift();\n\n\t\t\t\tif (isNumber(arg) && isDefined(argFmt)) {\n\t\t\t\t\tvar leading, decimals;\n\t\t\t\t\targFmt.replace(/^([0#]*)(?:\\.([0#]*))?/, function (mm, lead, dec) {\n\t\t\t\t\t\tleading = lead;\n\t\t\t\t\t\tdecimals = dec;\n\t\t\t\t\t});\n\n\t\t\t\t\tif (isDefined(leading) || isDefined(decimals)) {\n\t\t\t\t\t\targ = String(arg.toFixed((decimals || \"\").length));\n\t\t\t\t\t\tvar left = arg.indexOf(\".\");\n\t\t\t\t\t\tif (left < 0) {\n\t\t\t\t\t\t\tleft = arg.length;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tleft = (leading || \"\").length - left;\n\t\t\t\t\t\twhile (left-- > 0) {\n\t\t\t\t\t\t\targ = \"0\" + arg;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (idxAlignment.length === 2) {\n\t\t\t\t\tvar alignment = parseInt(idxAlignment[1], 10);\n\t\t\t\t\tvar padCount = (alignment > 0 ? alignment : -alignment) - arg.length;\n\t\t\t\t\tif (padCount > 0) {\n\t\t\t\t\t\tvar padding = [];\n\t\t\t\t\t\twhile (padCount > 0) {\n\t\t\t\t\t\t\tpadding.push(\" \");\n\t\t\t\t\t\t\tpadCount--;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (alignment > 0) {\n\t\t\t\t\t\t\tpadding.push(arg);\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tpadding.unshift(arg);\n\t\t\t\t\t\t}\n\t\t\t\t\t\targ = padding.join(\"\");\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn arg;\n\t\t\t});\n\t\t\treturn text;\n\t\t}", "get formatting() {\r\n return this.formattingType;\r\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Draw the lines for the second section below the hero Intro animation system while scrolling landing only
function drawline() { var start_in = win_height * .3; var start_out = win_height; if (scroll_top >= (start_in - 25) && scroll_top <= (start_out * 2)) { var svg_container = document.getElementById("whatwedo"); var svg_paths = svg_container.getElementsByTagNameNS(ns, "path"); var svg_lines = svg_container.getElementsByTagNameNS(ns, "line"); if (scroll_top - start_in < 0) { var percent_done = 0; } else { var percent_done = (scroll_top - start_in) / (start_out - start_in); } for (var x = 0; x < svg_paths.length; x++) { var path = svg_paths[x]; var path_length = path.getTotalLength(); var length = percent_done * path_length; path.style.strokeDasharray = [length, path_length].join(' '); path.style.fillOpacity = percent_done - .4; } for (var x = 0; x < svg_lines.length; x++) { var line = svg_lines[x]; var line_height = path.getTotalLength(); var length = percent_done * line_height + 36; line.style.strokeOpacity = percent_done; line.style.strokeDasharray = [length, path_length].join(' '); } } }
[ "function introAnimation(){\n introTL\n .fromTo(heroImage, {opacity: 0, x: 20, y: -10, scale: 1.4}, {duration: 1, x: 0, y: 0, ease: Power4.easeInOut, opacity:1, scale: 1.3})\n .to(day, .9, {ease: Power4.easeInOut, y: 0}, \"sync-=.9\")\n .to(group1, .9, {y: -15, ease: Power4.easeInOut}, \"sync-=.9\")\n .to(menu, .9, {x: 0, ease: Power4.easeInOut}, \"sync-=.9\")\n .fromTo(credit, .9, {opacity: 0, x: 10}, {opacity: 1, x: 0, ease: Power4.easeInOut, onComplete: addEventListeners}, \"sync-=.8\")\n}", "function storyLine(){\n \n background.draw(); \n }", "function storyLine(){\n\t \n\t background.draw(); \n\t }", "function runIntroduction() {\r\n \"use strict\";\r\n // NOTE: you can't count on anything being set correctly before this runs even with a reset call.... not sure why but it seems a 1 run show this way.\r\n //resetIntro();\r\n\r\n bIntroScreen = true;\r\n\r\n // hide intro button now.\r\n PlayIntroButton.disabled = true;\r\n PlayIntroButton.hidden = true;\r\n\r\n // hide start adventure button too: This because I have not found a way to stop an animation in progress.. sigh.\r\n AdventureButton.disabled = true;\r\n AdventureButton.hidden = true;\r\n\r\n // set intro sound.\r\n overlayAudio.setAttribute(\"src\", OtherSounds[0]);\r\n overlayAudio.play();\r\n\r\n let myTL2 = new TimelineMax();\r\n // run timeline\r\n myTL2.delay(10.0)\r\n .to(\"#IntroStartPicture\", 0.1, { display: \"none\", ease: Power0.easeNone }) // remove starting picture\r\n .to(\"#IntroPicture1\", 0.1, { display: \"initial\", scale: 0.0001, ease: Power0.easeNone })\r\n .to(\"#IntroPicture1\", 2.0, { opacity: 1, scale: 1, ease: Power0.easeNone }) // bring up crystal picture to start\r\n\r\n .to(\"#LegendText1\", 8.0, { top: -250, ease: Power0.easeNone }) // scroll text\r\n .to(\"#LegendText2\", 8.0, { top: -250, ease: Power0.easeNone }, \"-= 3.0\") // scroll text\r\n\r\n .to(\"#IntroPicture2\", 0.1, { display: \"initial\", scale: 0.0001, ease: Power0.easeNone }) // set up initial river picture\r\n .to(\"#IntroPicture2\", 0.1, { scale: 1, ease: Power0.easeNone }) // scale up but still not shown.\r\n .to(\"#LegendText4\", 8.0, { top: -250, ease: Power0.easeNone }, \"-= 3.0\") // scroll text\r\n .to(\"#LegendText5\", 8.0, { top: -250, ease: Power0.easeNone }, \"-= 3.0\") // scroll text\r\n .to(\"#LegendText6\", 8.0, { top: -250, ease: Power0.easeNone }, \"-= 3.0\") // scroll text\r\n .to(\"#IntroPicture1\", 3.0, { opacity: 0, ease: Power0.easeNone }, \"-= 3.0\") // fade out first image\r\n .to(\"#IntroPicture2\", 3.0, { opacity: 1, ease: Power0.easeNone }, \"-= 1.0\") // fade in second image\r\n .to(\"#LegendText7\", 8.0, { top: -250, ease: Power0.easeNone }, \"-= 1.5\") // scroll text over fadin\r\n .to(\"#LegendText8\", 8.0, { top: -250, ease: Power0.easeNone }, \"-= 3.0\") // scroll text\r\n .to(\"#LegendText9\", 8.0, { top: -250, ease: Power0.easeNone }, \"-= 3.0\") // scroll text\r\n .to(\"#LegendText10\", 8.0, { top: -250, ease: Power0.easeNone }, \"-= 3.0\") // scroll text\r\n .to(\"#IntroPicture1\", 0.1, { backgroundImage: \"url('images/RiverCut.jpg')\", ease: Power0.easeNone }) // switch to travel river.\r\n .to(\"#LegendText11\", 8.0, { top: -250, ease: Power0.easeNone }, \"-= 3.0\") // scroll text\r\n .to(\"#IntroPicture2\", 3.0, { opacity: 0, ease: Power0.easeNone }, \"-= 3.0\") // fade out country river image\r\n .to(\"#IntroPicture1\", 3.0, { opacity: 1, ease: Power0.easeNone }, \"-= 1.0\") // fade in rivercut image\r\n .to(\"#LegendText12\", 8.0, { top: -250, ease: Power0.easeNone }, \"-= 3.0\") // scroll text\r\n .to(\"#IntroPicture2\", 0.1, { backgroundImage: \"url('images/RiverSunset.jpg')\", ease: Power0.easeNone }) // switch to sunset\r\n .to(\"#LegendText13\", 8.0, { top: -250, ease: Power0.easeNone }) // scroll text\r\n .to(\"#IntroPicture1\", 3.0, { opacity: 0, ease: Power0.easeNone }, \"-= 3.0\") // fade out river cut image\r\n .to(\"#IntroPicture2\", 3.0, { opacity: 1, ease: Power0.easeNone }, \"-= 1.0\") // fade in sunset image\r\n .to(\"#LegendText14\", 8.0, { top: -250, ease: Power0.easeNone }, \"-= 3.0\") // scroll text\r\n .to(\"#IntroPicture1\", 0.1, { backgroundImage: \"url('images/OutsideWaterfall.jpg')\", ease: Power0.easeNone }) // switch to mountain stream\r\n .to(\"#IntroPicture2\", 3.0, { opacity: 0, ease: Power0.easeNone }) // fade out sunset image\r\n .to(\"#IntroPicture1\", 3.0, { opacity: 1, ease: Power0.easeNone }, \"-= 1.0\") // fade in moutain stream image\r\n .to(\"#IntroPicture2\", 0.1, { backgroundImage: \"url('images/mountainStream.jpg')\", ease: Power0.easeNone }) // switch to waterfa;;\r\n .to(\"#IntroPicture1\", 3.0, { opacity: 0, ease: Power0.easeNone }) // fade out mountain stream image\r\n .to(\"#IntroPicture2\", 3.0, { opacity: 1, ease: Power0.easeNone }, \"-= 1.0\") // fade in waterfall image\r\n .to(\"#IntroPicture1\", 0.1, { backgroundImage: \"url('images/FaceInClif.jpg')\", ease: Power0.easeNone }) // switch to face cliff\r\n .to(\"#IntroPicture2\", 3.0, { opacity: 0, ease: Power0.easeNone }) // fade out waterfall image\r\n .to(\"#IntroPicture1\", 3.0, { opacity: 1, ease: Power0.easeNone }, \"-= 1.0\") // fade in face in cliff image\r\n .to(\"#LegendText15\", 8.0, { top: -250, ease: Power0.easeNone }, \"-= 3.0\") // scroll text\r\n .to(\"#IntroPicture2\", 0.1, { backgroundImage: \"url('images/TopOfTheWorld.jpg')\", ease: Power0.easeNone }) // switch to top of the world\r\n .to(\"#IntroPicture1\", 3.0, { opacity: 0, ease: Power0.easeNone }) // fade out face in clif image\r\n .to(\"#IntroPicture2\", 3.0, { opacity: 1, ease: Power0.easeNone }, \"-= 1.0\") // fade in top of the world image\r\n .to(\"#LegendText16\", 8.0, { top: -250, ease: Power0.easeNone }, \"-= 3.0\") // scroll text\r\n .to(\"#IntroPicture1\", 0.1, { backgroundImage: \"url('images/CrackedEarth.jpg')\", ease: Power0.easeNone }) // switch to CrackedEarth\r\n .to(\"#IntroPicture2\", 3.0, { opacity: 0, ease: Power0.easeNone }) // fade out top of world image\r\n .to(\"#IntroPicture1\", 3.0, { opacity: 1, ease: Power0.easeNone }, \"-= 1.0\") // fade crackedEarth image\r\n .to(\"#LegendText17\", 8.0, { top: -250, ease: Power0.easeNone }, \"-= 3.0\") // scroll text\r\n .to(\"#LegendText18\", 8.0, { top: -250, ease: Power0.easeNone }, \"-= 3.0\") // scroll text\r\n\r\n\r\n // need to have new audio here..\r\n\r\n .call(() => {\r\n overlayAudio.pause();\r\n overlayAudio.setAttribute(\"src\", OtherSounds[10]);\r\n overlayAudio.currentTime = 0;\r\n overlayAudio.loop = true;\r\n overlayAudio.volume = 0.7;\r\n overlayAudio.play();\r\n }, [], this, \"-=0.0\")\r\n\r\n\r\n // start the shaking and expansion..\r\n .to(\"#IntroPicture1\", 0.2, { top: -5, left: -5, ease: Power0.easeNone })\r\n .to(\"#IntroPicture1\", 0.2, { top: 5, left: 5, ease: Power0.easeNone })\r\n .to(\"#IntroPicture1\", 0.2, { top: -5, left: 10, ease: Power0.easeNone })\r\n .to(\"#IntroPicture1\", 0.2, { top: 5, left: -5, ease: Power0.easeNone })\r\n .to(\"#IntroPicture1\", 0.2, { top: -5, left: -5, ease: Power0.easeNone })\r\n .to(\"#IntroPicture1\", 0.2, { top: 5, left: 5, ease: Power0.easeNone })\r\n .to(\"#IntroPicture1\", 0.2, { top: -5, left: 10, ease: Power0.easeNone })\r\n .to(\"#IntroPicture1\", 0.2, { top: 5, left: -5, ease: Power0.easeNone })\r\n .to(\"#IntroPicture1\", 0.2, { top: -5, left: -5, ease: Power0.easeNone })\r\n .to(\"#IntroPicture1\", 0.2, { top: 5, left: 5, ease: Power0.easeNone })\r\n .to(\"#IntroPicture1\", 0.2, { top: -5, left: 10, ease: Power0.easeNone })\r\n .to(\"#IntroPicture1\", 0.2, { top: 5, left: -5, ease: Power0.easeNone })\r\n .to(\"#IntroPicture1\", 0.2, { top: -5, left: -5, ease: Power0.easeNone })\r\n .to(\"#IntroPicture1\", 0.2, { top: 5, left: 5, ease: Power0.easeNone })\r\n .to(\"#IntroPicture1\", 0.2, { top: -5, left: 10, ease: Power0.easeNone })\r\n .to(\"#IntroPicture1\", 0.2, { top: 5, left: -5, ease: Power0.easeNone })\r\n .to(\"#IntroPicture1\", 0.2, { top: -5, left: -5, ease: Power0.easeNone })\r\n .to(\"#IntroPicture1\", 0.2, { top: 5, left: 5, ease: Power0.easeNone })\r\n .to(\"#IntroPicture1\", 0.2, { top: -5, left: 10, ease: Power0.easeNone })\r\n .to(\"#IntroPicture1\", 0.2, { top: 5, left: -5, ease: Power0.easeNone })\r\n .to(\"#IntroPicture1\", 0.2, { top: -5, left: -5, ease: Power0.easeNone })\r\n .to(\"#IntroPicture1\", 0.2, { top: 5, left: 5, ease: Power0.easeNone })\r\n .to(\"#IntroPicture1\", 0.2, { top: -5, left: 10, ease: Power0.easeNone })\r\n .to(\"#IntroPicture1\", 0.2, { top: 5, left: -5, ease: Power0.easeNone })\r\n .to(\"#IntroPicture1\", 0.2, { top: -5, left: -5, ease: Power0.easeNone })\r\n .to(\"#IntroPicture1\", 0.2, { top: 5, left: 5, ease: Power0.easeNone })\r\n .to(\"#IntroPicture1\", 0.2, { top: -5, left: 10, ease: Power0.easeNone })\r\n .to(\"#IntroPicture1\", 0.2, { top: 5, left: -5, ease: Power0.easeNone })\r\n .to(\"#IntroPicture1\", 0.2, { top: -5, left: -5, ease: Power0.easeNone })\r\n .to(\"#IntroPicture1\", 0.2, { top: 5, left: 5, ease: Power0.easeNone })\r\n .to(\"#IntroPicture1\", 0.2, { top: -5, left: 10, ease: Power0.easeNone })\r\n .to(\"#IntroPicture1\", 0.2, { top: 5, left: -5, ease: Power0.easeNone })\r\n .to(\"#IntroPicture1\", 0.2, { top: -5, left: -5, ease: Power0.easeNone })\r\n .to(\"#IntroPicture1\", 0.2, { top: 5, left: 5, ease: Power0.easeNone })\r\n .to(\"#IntroPicture1\", 0.2, { top: -5, left: 10, ease: Power0.easeNone })\r\n .to(\"#IntroPicture1\", 0.2, { top: 5, left: -5, ease: Power0.easeNone })\r\n .to(\"#IntroPicture1\", 0.2, { top: -5, left: -5, ease: Power0.easeNone })\r\n .to(\"#IntroPicture1\", 0.2, { top: 5, left: 5, ease: Power0.easeNone })\r\n .to(\"#IntroPicture1\", 0.2, { top: -5, left: 10, ease: Power0.easeNone })\r\n .to(\"#IntroPicture1\", 0.2, { top: 5, left: -5, ease: Power0.easeNone })\r\n\r\n // plung to darkness\r\n .to(\"#IntroPicture1\", 2.0, { opacity: 0, scale: 120, ease: Power0.easeNone }, \"-= 1.0\")\r\n .call(function () {\r\n overlayAudio.pause();\r\n overlayAudio.setAttribute(\"src\", OtherSounds[3]);\r\n overlayAudio.currentTime = 0;\r\n overlayAudio.loop = false;\r\n overlayAudio.volume = 0.5;\r\n overlayAudio.play();\r\n }, [], this, \"-=2.0\")\r\n\r\n .to(\"#LegendText19\", 8.0, { top: -250, ease: Power0.easeNone }, \"-=1.0\") // scroll final text\r\n\r\n // So, here is the problem: it seems this timeline tween thing sticks around, intact, AFTER the function ends. \r\n // In fact, if the animation has not ended, it will continue after the function returns.\r\n // IF i add a \"kill()\" at the end, it kills the whole thing and never plays anything, even though the kill is at the end...\r\n // So, the only recourse is to use the tween to reset the objects like the picture sources and the text locations back to \r\n // the starting postions or it just won't run the second time... sigh...\r\n // what's also sad is that if this was set to repeat, I don't think you would have to do any of this cleanup.\r\n\r\n .to(\"#IntroStartPicture\", 0.1, { display: \"block\", ease: Power0.easeNone }) // restore starting picture\r\n .to(\"#IntroPicture1\", 0.01, { top: 0, left: 0, display: \"none\", backgroundImage: \"url('images/Amethyst.jpg')\", ease: Power0.easeNone })\r\n .to(\"#IntroPicture2\", 0.01, { display: \"none\", backgroundImage: \"url('images/creekThroughPastureland.jpg')\", ease: Power0.easeNone })\r\n\r\n // we have to hide the text, then move it, then unhide. Otherwise it causes flashing on the screen.\r\n // first hide:\r\n .to(\"#LegendText1\", 0.01, { display: \"none\", ease: Power0.easeNone })\r\n .to(\"#LegendText2\", 0.01, { display: \"none\", ease: Power0.easeNone })\r\n .to(\"#LegendText3\", 0.01, { display: \"none\", ease: Power0.easeNone })\r\n .to(\"#LegendText4\", 0.01, { display: \"none\", ease: Power0.easeNone })\r\n .to(\"#LegendText5\", 0.01, { display: \"none\", ease: Power0.easeNone })\r\n .to(\"#LegendText6\", 0.01, { display: \"none\", ease: Power0.easeNone })\r\n .to(\"#LegendText7\", 0.01, { display: \"none\", ease: Power0.easeNone })\r\n .to(\"#LegendText8\", 0.01, { display: \"none\", ease: Power0.easeNone })\r\n .to(\"#LegendText9\", 0.01, { display: \"none\", ease: Power0.easeNone })\r\n .to(\"#LegendText10\", 0.01, { display: \"none\", ease: Power0.easeNone })\r\n .to(\"#LegendText11\", 0.01, { display: \"none\", ease: Power0.easeNone })\r\n .to(\"#LegendText12\", 0.01, { display: \"none\", ease: Power0.easeNone })\r\n .to(\"#LegendText13\", 0.01, { display: \"none\", ease: Power0.easeNone })\r\n .to(\"#LegendText14\", 0.01, { display: \"none\", ease: Power0.easeNone })\r\n .to(\"#LegendText15\", 0.01, { display: \"none\", ease: Power0.easeNone })\r\n .to(\"#LegendText16\", 0.01, { display: \"none\", ease: Power0.easeNone })\r\n .to(\"#LegendText17\", 0.01, { display: \"none\", ease: Power0.easeNone })\r\n .to(\"#LegendText18\", 0.01, { display: \"none\", ease: Power0.easeNone })\r\n .to(\"#LegendText19\", 0.01, { display: \"none\", ease: Power0.easeNone })\r\n\r\n\r\n // now move.\r\n .to(\"#LegendText1\", 0.01, { top: 700, ease: Power0.easeNone })\r\n .to(\"#LegendText2\", 0.01, { top: 700, ease: Power0.easeNone })\r\n .to(\"#LegendText3\", 0.01, { top: 700, ease: Power0.easeNone })\r\n .to(\"#LegendText4\", 0.01, { top: 700, ease: Power0.easeNone })\r\n .to(\"#LegendText5\", 0.01, { top: 700, ease: Power0.easeNone })\r\n .to(\"#LegendText6\", 0.01, { top: 700, ease: Power0.easeNone })\r\n .to(\"#LegendText7\", 0.01, { top: 700, ease: Power0.easeNone })\r\n .to(\"#LegendText8\", 0.01, { top: 700, ease: Power0.easeNone })\r\n .to(\"#LegendText9\", 0.01, { top: 700, ease: Power0.easeNone })\r\n .to(\"#LegendText10\", 0.01, { top: 700, ease: Power0.easeNone })\r\n .to(\"#LegendText11\", 0.01, { top: 700, ease: Power0.easeNone })\r\n .to(\"#LegendText12\", 0.01, { top: 700, ease: Power0.easeNone })\r\n .to(\"#LegendText13\", 0.01, { top: 700, ease: Power0.easeNone })\r\n .to(\"#LegendText14\", 0.01, { top: 700, ease: Power0.easeNone })\r\n .to(\"#LegendText15\", 0.01, { top: 700, ease: Power0.easeNone })\r\n .to(\"#LegendText16\", 0.01, { top: 700, ease: Power0.easeNone })\r\n .to(\"#LegendText17\", 0.01, { top: 700, ease: Power0.easeNone })\r\n .to(\"#LegendText18\", 0.01, { top: 700, ease: Power0.easeNone })\r\n .to(\"#LegendText19\", 0.01, { top: 700, ease: Power0.easeNone })\r\n\r\n\r\n // now reset display\r\n .to(\"#LegendText1\", 0.01, { display: \"initial\", ease: Power0.easeNone })\r\n .to(\"#LegendText2\", 0.01, { display: \"initial\", ease: Power0.easeNone })\r\n .to(\"#LegendText3\", 0.01, { display: \"initial\", ease: Power0.easeNone })\r\n .to(\"#LegendText4\", 0.01, { display: \"initial\", ease: Power0.easeNone })\r\n .to(\"#LegendText5\", 0.01, { display: \"initial\", ease: Power0.easeNone })\r\n .to(\"#LegendText6\", 0.01, { display: \"initial\", ease: Power0.easeNone })\r\n .to(\"#LegendText7\", 0.01, { display: \"initial\", ease: Power0.easeNone })\r\n .to(\"#LegendText8\", 0.01, { display: \"initial\", ease: Power0.easeNone })\r\n .to(\"#LegendText9\", 0.01, { display: \"initial\", ease: Power0.easeNone })\r\n .to(\"#LegendText10\", 0.01, { display: \"initial\", ease: Power0.easeNone })\r\n .to(\"#LegendText11\", 0.01, { display: \"initial\", ease: Power0.easeNone })\r\n .to(\"#LegendText12\", 0.01, { display: \"initial\", ease: Power0.easeNone })\r\n .to(\"#LegendText13\", 0.01, { display: \"initial\", ease: Power0.easeNone })\r\n .to(\"#LegendText14\", 0.01, { display: \"initial\", ease: Power0.easeNone })\r\n .to(\"#LegendText15\", 0.01, { display: \"initial\", ease: Power0.easeNone })\r\n .to(\"#LegendText16\", 0.01, { display: \"initial\", ease: Power0.easeNone })\r\n .to(\"#LegendText17\", 0.01, { display: \"initial\", ease: Power0.easeNone })\r\n .to(\"#LegendText18\", 0.01, { display: \"initial\", ease: Power0.easeNone })\r\n .to(\"#LegendText19\", 0.01, { display: \"initial\", ease: Power0.easeNone })\r\n\r\n\r\n // enable start adventure button:\r\n .to(\"#Adventure\", 0.5, { hidden: false, disabled: false, ease: Power0.easeNone });\r\n\r\n\r\n} // end runIntroduction", "function storyLine(){\n background.draw(); \n }", "function linesOnScroll() {\n $('.line-container').each(function () {\n if (!$(this).parents('aside').hasClass('aside') && !$(this).parent().hasClass('aside-block')) {\n w_h = $(window).height();\n winTop = $(window).scrollTop();\n elOffTop = $(this).offset().top;\n line = $(this).find('.vertical-line');\n if (!mainPage && window.matchMedia(\"(max-width: 991px)\").matches) {\n line.attr('style', ' ');\n return true\n }\n if (window.matchMedia(\"(max-width:767px)\").matches) {\n line.attr('style', ' ');\n return true\n }\n// alert(elOffTop < winTop + w_h - 300)\n elOffTop < winTop + w_h - 300 ? ($(this).addClass('active'), line.css({height: line.attr('data-height') + 'px'})) : ($(this).removeClass('active'), line.css({height: 0 + 'px'}));\n }\n });\n}", "function scroller() {\n SDFont = new image(DEMO_ROOT + \"/common/resources/largeFont.png\");\t\t// Get the source font image\n \tSDFont.initTile(32,16,32);\t\t\t\t\t\t\t\t\t\t\t\t// Set up the font\n \tscrollScreen = new canvas(640,140);\t\t\t\t\t\t\t\t\t\t// Set the main scroll screen (after dist)\n \tscrollOffScreen = new canvas(640,32);\t\t\t\t\t\t\t\t\t// Set the inital scroll screen (pre dist)\n \tscrollBackScreen = new canvas(640,scrollBackSegmentHeight * 7);\t\t\t// Set the background source screen\n \tvar backgroundTempScreen = new canvas(640, scrollBackSegmentHeight );\t// Set the temp screen for the various background segements\n \tscrollLine = new scrolltext_horizontal();\t\t\t\t\t\t\t\t// Set up the scroller object\n scrollyWibbles=[\t\t\t\t\t\t\t\t\t\t\t\t\t\t// Set up the y-dist parameters\n {value: 0, amp: 20, inc:0.03, offset: -0.05},\n {value: 0, amp: 35, inc:0.01, offset: -0.04}\n ];\n // Set up the scrolltext!\n \tscrollLine.scrtxt = \n \t\t\". . . . ...... YEEEEEAAAHH!!!! THE DADS ARE BACK!!!!^P2 \" +\n \t\t\"WITH A NEW CODEF-TRO CALLED... . . . ^P7\" +\n \t\t\"RELEASED 29 AUG 2015!^P3!!!!! \" +\n \t\t\"Rejoice!!!!! ^P2 \" +\n \t\t\"If u think this is YouTube, your so wrong!!!! This detnro is happening now on your browsey-wowsey!!!!!!! \" +\n \t\t\"Ja!!!! Dis CODEC is CODED by our CODEEs in CODEF!!!!! And Javascript, obviously. \" +\n \t\t\"CREDITS!!!!! Code(f!!) by OLD FART & DODDERING GIT!!! Art by JACKSON POLLOCK!!!! DJ MusixMix by DAME VERA LYN!!!!! \" +\n \t\t\". . . . ...... Welcome to our first demo of the millenium!!!! We wanted to do an Atari prod for our 20th Anniversary!! Then we saw someone did an Atari demo on a webpage!!!! So we thot: 'Hay!!! Let's do that!!!!'!! \" +\n \t\t\"So we toiled for yonks to learn tha CODEF, and here are our first fruits of our labour!!!!! This CODEF/JS/HTML5 malarkey was a bit funy at first- like doing a fullscreen in Turbo Pascal!!!! In fact, you can't even do fullscreen by flipping to 60Hz like on the old Atarri!!!!! \" +\n \t\t\"If you havent seen our Atari demoes (Where you been!!!), get thee to our w3sitey at \" +\n \t\t\"seniordads.atari.org ^P3!!!!!!! \" +\n \t\t\"and you can run them in Atari emulators!!! And soon- IN HTML5!!!!!!!!!^P2 \" +\n \t\t\"This is just a simple demo of wot we can do in 'def- nearly all the GFX is old stuff by Jackson Pollock for our website, and the DJ mix was done by Dame Vera Lynn at the Reservoir Gods Cwmvention in 1997!!!! Our next newie will contain all new GFX, Zix, and FX!!!!!! So watch out!!!!!!! \" +\n \t\t\" THE SENIOR DADS!! If it's too old, you're loud!!!!!!!!!! Go on, press space bar, you div!!!!!! \" +\n \t\t\" \";\n scrollFx = new FX(scrollOffScreen,scrollScreen,scrollyWibbles);\t\t\t// Set up the y-dist\n \tscrollLine.init(scrollOffScreen,SDFont,5);\t\t\t\t\t\t\t\t// initalise the scroller\n \t// Set up first background segment (gradient)\n \tmakeGradient( backgroundTempScreen,\n \t\t[ rgbBlack, '#00FFFF', '#FF0000', '#00FF00', '#FF00FF', '#FFFF00', '#0000FF', rgbBlack ]\n \t).drawH();\n \tbackgroundTempScreen.draw(scrollBackScreen,0,0);\n \t// Set up second background segment (gradient)\n \tmakeGradient( backgroundTempScreen,\n \t\t[ rgbBlack, '#FF4422', '#4422FF', '#FF4422', '#4422FF', '#FF4422', rgbBlack]\n \t).drawH();\n \tbackgroundTempScreen.draw(scrollBackScreen,0,scrollBackSegmentHeight);\n \t// Set up third segment background segment (\"Press Trail\" backdrop)\n \tbackDropImages[\"ptrail_bkg\"].drawPart(scrollBackScreen,0,scrollBackSegmentHeight*2,0,50,640,scrollBackSegmentHeight);\n \t// Set up fourth background segment (gradient)\n \tmakeGradient( backgroundTempScreen,\n \t\t[ rgbBlack, '#FFFF66', '#00FF00', '#FFFF66', '#FF0000', '#FFFF66', '#0088FF', '#FFFF66', rgbBlack ]\n \t).drawH();\n \tbackgroundTempScreen.draw(scrollBackScreen,0,scrollBackSegmentHeight*3);\n \t// Set up fifth background segment (gradient)\n \tmakeGradient( backgroundTempScreen,\n \t\t[ rgbBlack, rgbWhite, '#44FF88', rgbWhite, '#FF4488', rgbWhite, '#4488FF', rgbWhite, rgbBlack ]\n \t).drawH();\n \tbackgroundTempScreen.draw(scrollBackScreen,0,scrollBackSegmentHeight*4);\n \t// Set up sixth segment background segment (\"Trump\" backdrop)\n \tbackDropImages[\"trump\"].drawPart(scrollBackScreen,0,scrollBackSegmentHeight*5,0,50,640,scrollBackSegmentHeight);\n \t// Set up seventh segment background segment (\"Senior Dads presents\" backdrop)\n \tbackDropImages[\"presents\"].drawPart(scrollBackScreen,0,scrollBackSegmentHeight*6,0,50,640,scrollBackSegmentHeight);\n \t// Set up wobbler for backdrop\n \tscrollBackWobbler = new SeniorDads.Wobbler([\n \t\t\t\t \t{value: 0, amp: 3, inc:0.30},\n \t\t\t\t \t{value: 0.5, amp: 3, inc:0.40}\n \t\t\t\t]);\n \t}", "function draw_scroller() {\n \t\tcopperScreen.show();\n \t\tcopperScreen.clear();\t\t\t\t\n \t\t// Draw from the credits panel, using the scroll position, and with a wobble applied to it.\n \t\tcreditsScreenText.drawPart(copperScreen, 0, 0, creditsWobbler.h(), currentScrollPos + creditsWobbler.v(), 640, 400 );\n \t\t// If we're not at the end of the panel, increase the scroll position.\n \t\t// If we're at the end, it'll just stop.\n \t\tif (currentScrollPos < scrollEndpoint) currentScrollPos += 1;\n \t}", "function ring_on_finger() {\r\n var t1 = gsap.timeline({\r\n scrollTrigger: {\r\n trigger: \".section2\",\r\n pin: \".section2\",\r\n scrub: 1,\r\n start: \"top top\"\r\n\r\n },\r\n ease: \"power1.inOut\"\r\n });\r\n t1.to(finger_imgs, 20, {\r\n frame: frameCount - 1,\r\n snap: \"frame\",\r\n onUpdate: render\r\n });\r\n\r\n const section2_translate_texts = gsap.utils.toArray(\".section2 .translate_text p\");\r\n\r\n section2_translate_texts.forEach((translate_text, i) => {\r\n t1.from(translate_text, 4, {\r\n opacity: 0,\r\n yPercent: 100\r\n })\r\n .to(translate_text, 7, {\r\n opacity: 1,\r\n yPercent: 0\r\n })\r\n if (i < 2) {\r\n t1.to(translate_text, 4, {\r\n yPercent: -100,\r\n opacity: 0\r\n })\r\n }\r\n })\r\n\r\n}", "function drawBackgroundScroll () {\n ctx.font = titleSettings.scrollFont\n ctx.fillStyle = titleSettings.scrollColor\n for (let j = 0; j < game.width/10; j++) {\n for (let i = 0; i < letterArray.length; i++) {\n if (titleSettings.scrollIndex % 2) {\n ctx.fillText(letterArray[i], (30*j), (30*i)+frame)\n ctx.fillText(letterArray[i], (30*j), (30*i)+frame-750)\n } else {\n ctx.fillText(letterArray[i], (30*j), (30*i)-frame)\n ctx.fillText(letterArray[i], (30*j), (30*i)-frame+750)\n }\n }\n titleSettings.scrollIndex++\n }\n titleSettings.scrollIndex = 0\n}", "function parallaxIntro(wScroll) {\n $intro.css('transform', 'translateY(' + (wScroll * 0.2) + 'px)');\n }", "function linesOnScroll() {\n $('.line-container').each(function () {\n w_h = $(window).height();\n winTop = $(window).scrollTop();\n elOffTop = $(this).offset().top;\n line = $(this).find('.vertical-line');\n elOffTop < winTop + w_h - 300 ? ($(this).addClass('active'), line.css({height: line.attr('data-height') + 'px'})) : ($(this).removeClass('active'), line.css({height: 0 + 'px'}));\n });\n}", "drawOn(scene) {\n this.sprite = new SHAPES2D.Line(\n {x: this.isHorizontal ? this.start : this.position,\n y: this.isHorizontal ? this.position : this.start, z: 0.0},\n {x: this.isHorizontal ? this.end : this.position,\n y: this.isHorizontal ? this.position : this.end, z: 0.0});\n this.sprite.addTo(scene);\n }", "function part1() {\n var tl = new TimelineMax();\n\n tl.fromTo(\".logo\", 2, {x:-400, scale:0.1}, {x:0, rotation: 360, scale:1});\n tl.fromTo(\".clock\", 2, {x:-400, scale:0.1}, {x:0, rotation: 360, scale:1},\"-=2\");\n tl.fromTo(\".sun\", 3, {x:-400, scale:0.1, opacity:0.0}, {x:0 , scale:1, ease: Bounce.easeOut, opacity:1});\n tl.fromTo(\".moon\", 3, {x:-400, scale:0.1}, {x:0 , scale:1, ease: Bounce.easeOut});\n tl.fromTo(\".laagstaande-sun\", 3, {x:-400, scale:0.1}, {x:0 , scale:1, ease: Bounce.easeOut});\n return tl;\n}", "function splitLineHeadings() {\r\n\t\t\t\t\t\r\n\t\t\t\t\tvar $splitLineOffsetPos = ($('#nectar_fullscreen_rows').length > 0) ? '200%' : 'bottom-in-view';\r\n\t\t\t\t\t$($fullscreenSelector + '.nectar-split-heading').each(function () {\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\tvar $that = $(this);\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\tvar waypoint = new Waypoint({\r\n\t\t\t\t\t\t\telement: $that,\r\n\t\t\t\t\t\t\thandler: function () {\r\n\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\tif ($that.parents('.wpb_tab').length > 0 && $that.parents('.wpb_tab').css('visibility') == 'hidden' || $that.hasClass('animated-in')) {\r\n\t\t\t\t\t\t\t\t\twaypoint.destroy();\r\n\t\t\t\t\t\t\t\t\treturn;\r\n\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\tif (!nectarDOMInfo.usingMobileBrowser || $('body[data-responsive=\"0\"]').length > 0) {\r\n\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t$that.find('.heading-line').each(function (i) {\r\n\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\t$(this).find('> div').delay(i * 70).transition({\r\n\t\t\t\t\t\t\t\t\t\t\t'y': '0px'\r\n\t\t\t\t\t\t\t\t\t\t}, $animationDuration, $animationEasing);\r\n\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t});\r\n\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t$that.addClass('animated-in');\r\n\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\twaypoint.destroy();\r\n\t\t\t\t\t\t\t},\r\n\t\t\t\t\t\t\toffset: $splitLineOffsetPos\r\n\t\t\t\t\t\t});\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t});\r\n\t\t\t\t}", "function HeroParallax() {\r\n\t\r\n\t\tvar page_title = $('body');\r\n\t\tvar block_intro = $('#hero-styles');\r\n\t\tif( block_intro.length > 0 ) var block_intro_top = block_intro.offset().top;\t\r\n\t\r\n\t\tvar current_top = $(document).scrollTop(); \r\n\t\tvar hero_height = $('#hero-styles').height();\r\n\t\tif( $('#hero-styles').hasClass('parallax-hero')){\t\t\t \r\n\t\t\tblock_intro.css('transform', 'translate3d(0, ' + current_top * 0.5 + 'px, 0)');\t\t\r\n\t\t}\t\t\t\r\n\t\t\r\n\t\r\n\t}", "function scrollLayers(){\r\n var scrolled = $(window).scrollTop();\r\n $('.drawn-bg1').css('top',(0-(scrolled*.25))+'px');\r\n $('.drawn-bg2').css('top',(0-(scrolled*.65))+'px');\r\n }", "function timelineCount() {\n const containerStops = [mainProjectsContainer.offsetTop, mainContactContainer.offsetTop];\n const bodyHeight = Math.abs(document.body.getBoundingClientRect().y) +300;\n\n if (bodyHeight > containerStops[0] && bodyHeight < containerStops[1]) {\n timeline.firstElementChild.textContent = '2';\n } else if (bodyHeight > containerStops[1]) {\n timeline.firstElementChild.textContent = '3';\n } else {\n timeline.firstElementChild.textContent = '1';\n }\n }", "function setupEnterTimeline(setupIntro) {\n if (setupIntro) {\n enterTimeline.stop();\n // enterTimeline.timeScale(1);\n\n // --- Intro\n enterTimeline.addLabel('intro', 0);\n enterTimeline.set(elements.phoneObj.rotation, { x: 0, y: 0, z: 0 });\n enterTimeline.set(elements.intro, { autoAlpha: 1 });\n enterTimeline.add(SSG.disableNavToggleButton, 'intro');\n enterTimeline.to(elements.container, 0.5, { ease: Sine.easeInOut, autoAlpha: 1 }, 'intro');\n enterTimeline.staggerFrom(elements.introChildren, 0.667, { ease: Sine.easeInOut, autoAlpha: 0 }, 0.333);\n enterTimeline.addPause('intro+=3');\n enterTimeline.addLabel('post-intro', 'intro+=3');\n enterTimeline.staggerTo(elements.introChildren, 0.667, { ease: Sine.easeInOut, autoAlpha: 0 }, -0.167, 'intro+=3');\n enterTimeline.to(elements.intro, 0.667, { ease: Sine.easeInOut, autoAlpha: 0 }, 'intro+=3.5');\n enterTimeline.add(SSG.enableNavToggleButton, 'intro+=3');\n } else {\n // --- Main\n enterTimeline.addLabel('main', '-=0.25');\n\n // TODO More dynamic wiggle/motion for bg?\n enterTimeline.add(_dstage2.default.show(), 'main+=0.01');\n enterTimeline.set(sprites.phoneBackground, { opacity: 1 }, 'main');\n enterTimeline.add(enableDrawPhoneScreen, 'main');\n enterTimeline.add(enableRotatePhoneBackground, 'main');\n\n // --- Dots\n enterTimeline.addLabel('dots', 'main+=1.3');\n enterTimeline.add(dotPool.restart, 'dots');\n\n // --- Object Found\n enterTimeline.addLabel('objectFound', 'dots+=2.5');\n enterTimeline.add(dotPool.collapse, 'objectFound');\n enterTimeline.add(disableRotatePhoneBackground, 'objectFound');\n enterTimeline.from(shapes.objectMaskHole, 0.5, {\n ease: Sine.easeInOut,\n width: 0,\n height: 0\n }, 'objectFound');\n enterTimeline.from(shapes.objectMask, 0.5, { ease: Sine.easeInOut, opacity: 0 }, 'objectFound');\n enterTimeline.from(shapes.objectMaskHoleOutline, 0.5, { ease: Sine.easeInOut, opacity: 0 }, 'objectFound+=0.167');\n\n // --- Search Buttons\n enterTimeline.addLabel('searchButtons', '+=0.4');\n enterTimeline.to(sprites.instructions, 0.333, { ease: Sine.easeInOut, opacity: 0 }, 'searchButtons');\n enterTimeline.to(sprites.searchButtons, 0.667, { ease: Sine.easeInOut, opacity: 1 }, 'searchButtons');\n\n // Shopping button tap\n enterTimeline.addLabel('shoppingButtonTap', '+=1.5');\n enterTimeline.to(shapes.shoppingButtonTap, 0.167, { opacity: 0.65 }, 'shoppingButtonTap');\n enterTimeline.to(shapes.shoppingButtonTap, 0.5, { ease: Sine.easeInOut, opacity: 0 });\n\n // --- Results\n enterTimeline.addLabel('results', '+=0.5');\n enterTimeline.to(sprites.searchButtons, 0.333, { ease: Sine.easeInOut, opacity: 0 }, 'results');\n enterTimeline.to(shapes.flashlightCover, 0.333, { ease: Sine.easeOut, opacity: 1 }, 'results');\n enterTimeline.from(elements.amazonDisclaimer, 0.5, { ease: Sine.easeInOut, autoAlpha: 0 }, 'results');\n\n // UI Elements\n enterTimeline.to(sprites.bottomBarWhite, 0.167, { opacity: 1 }, 'results');\n enterTimeline.set(sprites.bottomBar, { opacity: 0 });\n enterTimeline.from(sprites.resultsList, 0.667, {\n ease: Power2.easeOut,\n y: canvasSize.height\n }, 'results');\n enterTimeline.set(shapes.bottomBg, { opacity: 0 });\n\n var phoneBackgroundScaleAmount = 0.618;\n enterTimeline.to(sprites.phoneBackground, 0.5, {\n ease: Sine.easeInOut,\n u: '-=' + (sprites.phoneBackground.srcWidth - sprites.phoneBackground.srcWidth * phoneBackgroundScaleAmount) / 2,\n v: '+=' + (sprites.phoneBackground.srcHeight - sprites.phoneBackground.srcHeight * phoneBackgroundScaleAmount) / 3.4,\n // srcWidth: '+=' + phoneBackgroundScaleAmount,\n // srcHeight: '+=' + phoneBackgroundScaleAmount * bikeArea.aspectRatio,\n scale: 2 - phoneBackgroundScaleAmount\n }, 'results');\n enterTimeline.to(shapes.objectMaskHole, 0.5, {\n ease: Sine.easeInOut,\n // x: '+=15',\n y: 225,\n height: '-=50',\n scale: 1 - phoneBackgroundScaleAmount / 4\n }, 'results');\n enterTimeline.to(shapes.objectMaskHoleOutline, 0.667, { ease: Sine.easeIn, opacity: 0 });\n\n enterTimeline.add(disableDrawPhoneScreen);\n // enterTimeline.to(sprites.topBar, 2, { y: '+=768' }, 'main');\n }\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
get dot style grid path
_getDotPath() { const graph = this.graph; const width = graph.getWidth(); const height = graph.getHeight(); const tl = graph.getPoint({ x: 0, y: 0 }); const br = graph.getPoint({ x: width, y: height }); const cell = this.cell; const flooX = Math.ceil(tl.x / cell) * cell; const flooY = Math.ceil(tl.y / cell) * cell; const matrix = graph.getMatrix(); const detalx = 2 / matrix[0]; const path = []; for (let i = 0; i <= br.x - tl.x; i += cell) { const x = flooX + i; for (let j = 0; j <= br.y - tl.y; j += cell) { const y = flooY + j; path.push([ 'M', x, y ]); path.push([ 'L', x + detalx, y ]); } } return path; }
[ "getPathCell(x, y) {\n return this.pathCells.find(cell => cell.y == y * this.gridSize && cell.x == x * this.gridSize)\n }", "_getLinePath() {\n const graph = this.graph;\n const width = graph.getWidth();\n const height = graph.getHeight();\n const tl = graph.getPoint({\n x: 0,\n y: 0\n });\n const br = graph.getPoint({\n x: width,\n y: height\n });\n const cell = this.cell;\n const flooX = Math.ceil(tl.x / cell) * cell;\n const flooY = Math.ceil(tl.y / cell) * cell;\n const path = [];\n for (let i = 0; i <= br.x - tl.x; i += cell) {\n const x = flooX + i;\n path.push([ 'M', x, tl.y ]);\n path.push([ 'L', x, br.y ]);\n }\n for (let j = 0; j <= br.y - tl.y; j += cell) {\n const y = flooY + j;\n path.push([ 'M', tl.x, y ]);\n path.push([ 'L', br.x, y ]);\n }\n return path;\n }", "function drawDjikstraPath()\n {\n for(let i = 1; i < path.length; i++)\n {\n let gridIndex = rcToIndex(path[i].first, path[i].second , gridRowSize);\n $('.cell').eq(gridIndex).html('<div class=\"marker_path bg-dark\"></div>'); \n }\n\n }", "get containingPath() {\n return this.pathTokens.slice(0, -1).join('.');\n }", "get stackPath() {\n return this.node.ancestors(this.node.stack).map(c => c.node.id).join(construct_1.PATH_SEP);\n }", "function robotPaths (grid) {\n var resultPath = [];\n var columnLength = grid.length - 1;\n var rowLength = grid[0].length - 1;\n\n function innerTraverseHelper(column, row, currentPath){\n \n if (column === columnLength && row === rowLength) {\n resultPath = currentPath;\n }\n\n if(column <= columnLength && row <= rowLength) {\n if(column < columnLength && grid[column+1][row] !== 'x') {\n innerTraverseHelper(column+1, row, currentPath.concat([[column, row]]));\n }\n if(row < rowLength && grid[column][row+1] !== 'x') {\n innerTraverseHelper(column, row+1, currentPath.concat([[column, row]]));\n }\n }\n }\n\n innerTraverseHelper(0,0,[[0,0]]);\n\n return resultPath;\n}", "connectorPaths(items) {\n let prev, next;\n prev = _util_js__WEBPACK_IMPORTED_MODULE_0__.default.normalizeBBox(lodash__WEBPACK_IMPORTED_MODULE_1___default().first(items).getBBox());\n return lodash__WEBPACK_IMPORTED_MODULE_1___default().map(items.slice(1), item => {\n try {\n next = _util_js__WEBPACK_IMPORTED_MODULE_0__.default.normalizeBBox(item.getBBox());\n return `M${prev.ax2},${prev.ay}H${next.ax}`;\n } finally {\n prev = next;\n }\n });\n }", "GetDigPath() {\n let digPath = new Array();\n \n this._digCells.forEach( cell => { \n digPath.push( \n { x: cell.x, y: cell.y }\n )\n });\n return digPath; \n }", "get stackPath() {\n return this.ancestors(this.stack).map(c => c.id).join(construct_1.PATH_SEP);\n }", "connectorPaths(items) {\n let prev, next;\n\n prev = util.normalizeBBox(_.first(items).getBBox());\n return _.map(items.slice(1), item => {\n try {\n next = util.normalizeBBox(item.getBBox());\n return `M${prev.ax2},${prev.ay}H${next.ax}`;\n }\n finally {\n prev = next;\n }\n });\n }", "findPaths(){\n gridArray.forEach(function(yValue, yCoord){\n yValue.forEach(function(xValue, xCoord){\n BadBoggle.searchPath([[yCoord, xCoord]], yCoord, xCoord);\n });\n });\n }", "function visualizePaths(){\n\tlet Visual = require('visual');\n\tlet colors = [];\n\tlet COLOR_BLACK = colors.push('#000000') - 1;\n\tlet COLOR_PATH = colors.push('rgba(255,255,255,0.5)') - 1;\n\t_.each(Game.rooms,(room,name)=>{\n\t\tlet visual = new Visual(name);\n\t\tvisual.defineColors(colors);\n\t\tvisual.setLineWidth = 0.5;\n\t\t_.each(Game.creeps,creep=>{\n\t\t\tif(creep.room != room) return;\n\t\t\tlet mem = creep.memory;\n\t\t\tif(mem._move){\n\t\t\t\tlet path = Room.deserializePath(mem._move.path);\n\t\t\t\tif(path.length){\n\t\t\t\t\tvisual.drawLine(path.map(p=>([p.x,p.y])),COLOR_PATH,{ lineWidth: 0.1 });\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t\tvisual.commit();\n\t});\n}", "createPaths(target) {\r\n const paths = [\r\n {\r\n class: 'digit__top',\r\n d: 'M23.19,19.77h54.1L96,2.13A10.24,10.24,0,0,0,89.74,0H10.26A10.27,10.27,0,0,0,4,2.1Z'\r\n },\r\n {\r\n class: 'digit__topLeft',\r\n d: 'M2.3,3.75A10.16,10.16,0,0,0,0,10.18V79.23A10.18,10.18,0,0,0,5.6,88.3L21.27,76.64V21.26Z'\r\n },\r\n {\r\n class: 'digit__topRight',\r\n d: 'M78.73,21.7V76.64L94.4,88.3a10.18,10.18,0,0,0,5.6-9.07V10.18a10.11,10.11,0,0,0-2.28-6.39Z'\r\n },\r\n {\r\n class: 'digit__middle',\r\n d: 'M77.15,79.2H22.85L8.39,89.78l14.46,10.58h54.3L91.61,89.78Z'\r\n },\r\n {\r\n class: 'digit__bottomLeft',\r\n d: 'M2.3,176.24A10.11,10.11,0,0,1,0,169.82v-69A10.18,10.18,0,0,1,5.6,91.7l15.67,11.66v55.38Z'\r\n },\r\n {\r\n class: 'digit__bottomRight',\r\n d: 'M78.73,158.3V103.36L94.4,91.7a10.18,10.18,0,0,1,5.6,9.07v69.05a10.11,10.11,0,0,1-2.28,6.39Z'\r\n },\r\n {\r\n class: 'digit__bottom',\r\n d: 'M23.19,160.23h54.1L96,177.87A10.24,10.24,0,0,1,89.74,180H10.26A10.27,10.27,0,0,1,4,177.9Z'\r\n }\r\n ];\r\n\r\n paths.forEach(path => {\r\n let el = document.createElementNS(this.ns, 'path');\r\n\r\n el.classList.add(path.class);\r\n el.setAttribute('d', path.d);\r\n target.appendChild(el);\r\n })\r\n }", "getPath(width = 100, height = 75) {\n const outletY = this.outletY(false);\n const path = ['M4,1']; // start top-left, after corner\n path.push(`L${width - 2},1`); // line to top-right\n path.push(`C${width - 0.3431},1 ${width + 1},2.34314575 ${width + 1},4`); // top-right corner\n path.push(\n `L${width + 1},${outletY - 8.5} L${width + 1},${outletY - 8.5} L${width +\n arrowWidth +\n 1},${outletY} L${width + 1},${outletY + 8.5} L${width + 1},${height -\n 2}`,\n ); // right side\n path.push(\n `C${width + 1},${height - 0.3431} ${width - 0.3431},${height +\n 1} ${width - 2},${height + 1}`,\n ); // bottom-right corner\n path.push(`L4,${height + 1}`); // line to bottom left\n\n path.push(`C2.34314575,${height + 1} 1,${height - 0.3431} 1,${height - 2}`); // bottom-left corner\n path.push(\n `L1,${outletY + 8.5} L1,${outletY + 8.5} L${arrowWidth +\n 1},${outletY} L1,${outletY - 8.5} L1,4`,\n ); // left side\n path.push('C1,2.34314575 2.34314575,1 4,1'); // top-left corner\n path.push('Z'); // end\n\n return path.join(' ');\n }", "function path() {\n\tvar sel = '.ngi-scope > .ngi-drawer ';\n\tfor (var i = 0; i < arguments.length; i++) {\n\t\tif (typeof arguments[i] == 'object' && arguments[i].length == 2)\n\t\t\tsel += ' > .' + arguments[i][0] + ':nth-child(' + arguments[i][1] + ')'\n\t\telse\n\t\t\tsel += ' > .' + arguments[i];\n\n\t\tif (i < arguments.length - 1)\n\t\t\tsel += ' > .ngi-drawer'\n\t}\n\treturn sel;\n}", "function drawDotGrid() {\n push();\n noStroke();\n let spacing = windowWidth / gridModules;\n for(let y = 0; y < windowHeight; y += spacing) {\n for(let x = 0; x < windowWidth; x += spacing) { \n fill(fills[0]);\n ellipse(x,y,dotSize,dotSize);\n }\n }\n pop();\n}", "function highlightPath(path) {\n path.forEach(function (cell) {\n let cellClass = \"cell_\" + cell.y + \"_\" + cell.x;\n document.getElementById(cellClass).className = cell.getClass() + \" gridactive\";\n });\n } // end highlightPath", "_getPath(element) {\n if(this.blueRecycle.inRecycle(element)) {\n return this.blueRecycle.getItemPath(element);\n }\n else if(this.greenRecycle.inRecycle(element)) {\n return this.greenRecycle.getItemPath(element);\n }\n else if(this.brownRecycle.inRecycle(element)) {\n return this.brownRecycle.getItemPath(element);\n }\n else if(this.yellowRecycle.inRecycle(element)) {\n return this.yellowRecycle.getItemPath(element);\n }\n return \"assets/poub-template-closed.png\";\n }", "function getDotWalkValueFromGr(valuePath, gr) {\n\tvar r = null;\n\t\n\tvaluePath = \"\"+valuePath; // Force it into a string\n\tvaluePathSplit = valuePath.split(\".\");\n\tfor (var iPath=0; iPath < valuePathSplit.length; iPath++) {\n\t\tvar pathSegment = valuePathSplit[iPath].trim();\n\t\t\n\t\t//gs.print(\"Segment: \"+pathSegment);\n\t\t\n\t\tif (pathSegment == \"\") continue; // Skip empty segments\n\t\t\n\t\tif (r == null) r = gr[pathSegment];\n\t\telse r = r[pathSegment];\n\t\t\n\t\t//gs.print(\"r: \"+r);\n\t}\n\n\treturn r;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a JSON structure of the current Layout state. Does not contain any HTML references. Used for local storaging.
getJSONStructure() { return this.getState(true); }
[ "layout(state) {\n return state.layout;\n }", "generateLayoutData() {\n // This class is base class, can be called with this method.\n return {\n id: this.id,\n className: this.constructor.name,\n prop: map2json(this.prop),\n layout: {\n width: this.ui.width,\n height: this.ui.height,\n left: this.ui.left,\n top: this.ui.top,\n hidden: this.ui.hidden,\n }\n };\n }", "static getLayout(){\n if (!this.layout || config.debug.isDebug) {\n this.layout = HTTP.call('GET', Meteor.absoluteUrl()).content;\n }\n return this.layout;\n }", "readLayoutJSON ()\n {\n this._layoutJSONLoader = new JSONLoader(this._layoutToLoad);\n this._layoutJSONLoader.addListener(Event.READY, this.loadLayoutBound);\n this._layoutJSONLoader.load();\n }", "getKernelStateAsJSON() {\n return JSON.stringify({history: this.history, hiddenHistory: this.hiddenHistory});\n }", "makeLayout() {\n\n if (this.state.projectData === undefined) {\n return;\n }\n\n // Clear stack\n this.resetLayout();\n\n // Recursively build the layout\n this.getBlock(this.state.htmlBlockId, true, [0]);\n }", "function getLayout() {\n\n // get the chart data\n var data = getData();\n\n // get the output from tree layout algorithm\n var tree = getTree();\n\n // get the tree node data\n var nodeData = tree.nodes(data)\n .reverse();\n\n // increase the depth value of each\n nodeData.forEach(function(d) {\n d.y = d.depth * 180;\n });\n\n // determine links from the nodes\n var linkData = tree.links(nodeData);\n\n return {\n nodes: nodeData,\n links: linkData\n };\n }", "get layout() {\n return this._layout;\n }", "_loadFromStorage(){\n try {\n let raw = LocalStorage.getItem(\n STORAGE_NAMES.LAYOUT\n );\n if (raw) {\n return JSON.parse(raw);\n }\n }catch(e){\n base.log(\"error when trying to read layout locally: \"+e);\n }\n\n }", "function getSerializedViewState() {\r\n var jsonViewState = \"\";\r\n\r\n var viewState = jQuery(document).data(kradVariables.VIEW_STATE);\r\n if (!jQuery.isEmptyObject(viewState)) {\r\n var jsonViewState = jQuery.toJSON(viewState);\r\n\r\n // change double quotes to single because escaping causes problems on URL\r\n jsonViewState = jsonViewState.replace(/\"/g, \"'\");\r\n }\r\n\r\n return jsonViewState;\r\n}", "function getTreeState() {\n var tree = viewTree.getData().getAllNodes();\n //isc.JSON.encode(\n return { width: viewTree.getWidth(),\n time: isc.timeStamp(),\n pathOfLeafShowing: viewInstanceShowing ? viewInstanceShowing.path : null,\n // selectedPaths: pathShowing, //viewTree.getSelectedPaths(),\n //only store data needed to rebuild the tree \n state: tree.map(function(n) {\n return {\n\t type: n.type,\n\t id: n.id,\n\t parentId: n.parentId,\n\t isFolder: n.isFolder,\n\t name: n.name,\n\t isOpen: n.isOpen,\t\n\t state: n.state,\n icon: n.icon\n };\n\t\t })\n };\n }", "layout() {\n return this.text(poc2go.config.design.layout.html)\n .then(htm => {poc2go.render._layout = new Layout(htm);});\n }", "function normalizeState(saved, current) {\n if (!saved) {\n return coreutils_1.JSONExt.deepCopy(DEFAULT_LAYOUT);\n }\n if (!('sizes' in saved) || !numberArray(saved.sizes)) {\n saved.sizes = coreutils_1.JSONExt.deepCopy(DEFAULT_LAYOUT.sizes);\n }\n if (!('container' in saved)) {\n saved.container = coreutils_1.JSONExt.deepCopy(DEFAULT_LAYOUT.container);\n return saved;\n }\n const container = 'container' in saved &&\n saved.container &&\n typeof saved.container === 'object'\n ? saved.container\n : {};\n saved.container = {\n editor: container.editor === 'raw' || container.editor === 'table'\n ? container.editor\n : DEFAULT_LAYOUT.container.editor,\n plugin: typeof container.plugin === 'string'\n ? container.plugin\n : DEFAULT_LAYOUT.container.plugin,\n sizes: numberArray(container.sizes)\n ? container.sizes\n : coreutils_1.JSONExt.deepCopy(DEFAULT_LAYOUT.container.sizes)\n };\n return saved;\n }", "function normalizeState(saved, current) {\n if (!saved) {\n return coreutils_1.JSONExt.deepCopy(DEFAULT_LAYOUT);\n }\n if (!('sizes' in saved) || !numberArray(saved.sizes)) {\n saved.sizes = coreutils_1.JSONExt.deepCopy(DEFAULT_LAYOUT.sizes);\n }\n if (!('container' in saved)) {\n saved.container = coreutils_1.JSONExt.deepCopy(DEFAULT_LAYOUT.container);\n return saved;\n }\n var container = 'container' in saved && saved.container && typeof saved.container === 'object'\n ? saved.container\n : {};\n saved.container = {\n plugin: typeof container.plugin === 'string' ? container.plugin : DEFAULT_LAYOUT.container.plugin,\n sizes: numberArray(container.sizes) ? container.sizes : coreutils_1.JSONExt.deepCopy(DEFAULT_LAYOUT.container.sizes),\n };\n return saved;\n }", "function getState() {\n var state;\n\n state = internal.loader.cache().state();\n state = sys.extend(state, internal.loader.state());\n\n //We rename maxItems to maxPages\n state.maxPages = state.maxItems;\n delete state.maxItems;\n\n state = sys.extend(state, {\n index: self.index(),\n padLow: self.padLow(),\n padHigh: self.padHigh(),\n countMode: self.countMode(),\n filter: self.filter()\n });\n\n return state;\n }", "function getCurrentLayout () {\n return currentKeyboardLayout;\n }", "function _orbitLayout() {\n\t\treturn _orbitLayout;\n\t}", "function Layout() {return;}", "function LayoutHistory () {\n\t\tthis._aLayoutHistory = [];\n\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Given a protocol and a port, try to guess the other one if it's undefined eslintdisablenextline maxlen
function determineProtocolAndPort(protocol, port) { if (protocol === undefined && port === undefined) { return [undefined, undefined]; } if (protocol === undefined) { protocol = defaultProtocolForPort(port); } if (port === undefined) { port = defaultPortForProtocol(protocol); } return [protocol, port]; }
[ "function inferPort(protocol) {\n if (protocol === 'http:') {\n return 80\n }\n\n if (protocol === 'https:') {\n return 443\n }\n}", "function defaultPort(protocol) {\n return {'http:':80, 'https:':443}[protocol];\n }", "function defaultPort(protocol) {\n return { 'http:': 80, 'https:': 443 }[protocol]\n }", "vaidateProtocol(host){\r\n let protocols = ['https://', 'http://'];\r\n if (protocols.map(protocol => host.includes(protocol)).includes(true)) return host\r\n throw new Error('Host String must include http:// or https://')\r\n }", "function defaultPort (protocol) {\n return { 'http:': 80, 'https:': 443 }[protocol]\n }", "vaidateProtocol(host){\n let protocols = ['https://', 'http://']\n if (protocols.map(protocol => host.includes(protocol)).includes(true)) return host\n throw new Error('Host String must include http:// or https://')\n }", "vaidateProtocol(host) {\n let protocols = [\"https://\", \"http://\"];\n if (protocols.map((protocol) => host.includes(protocol)).includes(true)) return host;\n throw new Error(\"Host String must include http:// or https://\");\n }", "function get_addr_port(s) {\n var spl = s.split(\":\");\n if (spl.length === 1)\n return { host: spl[0], port: 80 };\n else if (spl[0] === '')\n return { port: parseInt(spl[1]) };\n else\n return { host: spl[0], port: parseInt(spl[1]) };\n}", "function normalizePort(val) {\n const port = parseInt(val, 10); // eslint-disable-line no-shadow\n\n if (isNaN(port)) {\n // named pipe\n return val;\n }\n\n if (port >= 0) {\n // port number\n return port;\n }\n\n return false;\n}", "_validImplicitUrlDomainEnd(start, max)\n {\n // First, find the end of the domain\n let domainEnd = start + 1;\n while (domainEnd <= max && /[a-z]/i.test(this.text[domainEnd]))\n {\n ++domainEnd;\n }\n\n let domain = this.text.substring(start + 1, domainEnd);\n if (!/^(?:com|org|net|edu|gov|de|ru|uk|jp|it|fr|nl|ca|au|es|ch|se|us|no|mil|io|blog|cc|co|dev|mp|eu|ly|global|services)$/.test(domain))\n {\n return -1;\n }\n\n if (domainEnd <= max && this.text[domainEnd] == ':')\n {\n // Check for a valid port\n let portStart = domainEnd + 1;\n let portEnd = portStart;\n while (portEnd <= max && /\\d/.test(this.text[portEnd]))\n {\n ++portEnd;\n }\n\n let port = parseInt(this.text.substring(portStart, portEnd));\n if (!isNaN(port) && port > 0 && port < 65536)\n {\n return portEnd;\n }\n }\n\n return domainEnd;\n }", "function checkValidPortsToProtocolsHttp() {\n let httpData = getHttpData();\n let bedHttpPorts = [];\n httpData.forEach(log => {\n if ((log['id.resp_p'] == 80) || (log['id.resp_p'] == 8080)) {\n console.log(\"Legit http trafic\");\n }\n else {\n bedHttpPorts.push(log['id.resp_p']);\n console.log(\"Bad port for http trafic\");\n }\n });\n return bedHttpPorts;\n}", "function isValidPort(port) {\r\n var fromport = 0;\r\n var toport = 100;\r\n\r\n portrange = port.split(':');\r\n if ( portrange.length < 1 || portrange.length > 2 ) {\r\n return false;\r\n }\r\n if ( isNaN(portrange[0]) )\r\n return false;\r\n fromport = parseInt(portrange[0]);\r\n if ( isNaN(fromport) )\r\n return false;\r\n \r\n if ( portrange.length > 1 ) {\r\n if ( isNaN(portrange[1]) )\r\n return false;\r\n toport = parseInt(portrange[1]);\r\n if ( isNaN(toport) )\r\n return false;\r\n if ( toport <= fromport )\r\n return false; \r\n }\r\n \r\n if ( fromport < 1 || fromport > 65535 || toport < 1 || toport > 65535 )\r\n return false;\r\n \r\n return true;\r\n}", "function _normalizePort(val) {\n var port = parseInt(val, 10);\n\n if (isNaN(port)) {\n // named pipe\n return val;\n }\n\n if (port >= 0) {\n // port number\n return port;\n }\n\n return false;\n}", "function normalizePort(val) {\n if (val === undefined || val.length === 0) {\n return null;\n }\n\n const portNumber = parseInt(val, 10);\n\n if (isNaN(portNumber)) {\n // named pipe\n return [ 'pipe', val ];\n }\n\n if (portNumber >= 0) {\n // port number\n return [ 'port', portNumber ];\n }\n\n return null;\n}", "function normalizePort(val) {\n const port2 = parseInt(val, 10);\n if (Number.isNaN(port2)) {\n // named pipe\n return val;\n }\n if (port2 >= 0) {\n // port number\n return port2;\n }\n return false;\n}", "function normalizePort (val) {\n const port = parseInt(val, 10);\n\n if (isNaN(port)) {\n // named pipe\n return val;\n }\n\n if (port >= 0) {\n // port number\n return port;\n }\n\n return false;\n}", "normalizePort(val){\n /**\n * Normalize a port into a number, string, or false.\n */\n var port = parseInt(val, 10);\n if (isNaN(port)) {\n // named pipe\n return val;\n }\n if (port >= 0) {\n // port number\n return port;\n }\n return false;\n }", "function normalisePort(val) {\n\tlet port = parseInt(val, 10);\n\tif (isNaN(port))\n\t\treturn val; // named pipe\n\tif (port >= 0)\n\t\treturn val; // port number\n\treturn false;\n}", "function normalizePort(val) {\n\tconst port = parseInt(val, 10)\n\n\tif (isNaN(port)) {\n\t\t// named pipe\n\t\treturn val\n\t}\n\n\tif (port >= 0) {\n\t\t// port number\n\t\treturn port\n\t}\n\n\treturn false\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
test if start and end angles match with radians tolerance. This is equivalent to isAlmostEqualNoPeriodShift. it is present for consistency with other classes It is recommended that all callers use one of he longer names to be clear of their intentions: isAlmostEqualAllowPeriodShift isAlmostEqualRadiansNoPeriodShift
isAlmostEqual(other) { return this.isAlmostEqualNoPeriodShift(other); }
[ "static isAlmostEqualRadiansAllowPeriodShift(radiansA, radiansB) {\n // try to get simple conclusions with un-shifted radians ...\n const delta = Math.abs(radiansA - radiansB);\n if (delta <= Geometry_1.Geometry.smallAngleRadians)\n return true;\n const period = Math.PI * 2.0;\n if (Math.abs(delta - period) <= Geometry_1.Geometry.smallAngleRadians)\n return true;\n const numPeriod = Math.round(delta / period);\n const delta1 = delta - numPeriod * period;\n return Math.abs(delta1) <= Geometry_1.Geometry.smallAngleRadians;\n }", "static isAlmostEqualRadiansNoPeriodShift(radiansA, radiansB) { return Math.abs(radiansA - radiansB) < Geometry_1.Geometry.smallAngleRadians; }", "isAlmostEqualNoPeriodShift(other) { return Math.abs(this._radians - other._radians) < Geometry_1.Geometry.smallAngleRadians; }", "function similarRadians(expected, actual, eps) {\n return Math.abs(CesiumMath.negativePiToPi(expected - actual)) <= eps;\n}", "function compareBiggerAngle(a1, a2)\n{\n if(a2 < a1 || (a2 + 180) % 360 > a1)\n return true;\n return false;\n}", "isAlmostEqual(other) {\n return this.yaw.isAlmostEqualAllowPeriodShift(other.yaw)\n && this.pitch.isAlmostEqualAllowPeriodShift(other.pitch)\n && this.roll.isAlmostEqualAllowPeriodShift(other.roll);\n }", "function nudgeCartographic(start, end) {\n const absStartLon = Math.abs(start.longitude);\n const absEndLon = Math.abs(end.longitude);\n if (\n CesiumMath.equalsEpsilon(absStartLon, CesiumMath.PI, CesiumMath.EPSILON11)\n ) {\n const endSign = CesiumMath.sign(end.longitude);\n start.longitude = endSign * (absStartLon - CesiumMath.EPSILON11);\n return 1;\n } else if (\n CesiumMath.equalsEpsilon(absEndLon, CesiumMath.PI, CesiumMath.EPSILON11)\n ) {\n const startSign = CesiumMath.sign(start.longitude);\n end.longitude = startSign * (absEndLon - CesiumMath.EPSILON11);\n return 2;\n }\n return 0;\n}", "static computeActualEndAngle(startAngle, endAngle, anticlockwise) {\n if (anticlockwise) {\n // angle is 'decreasing'\n // -2pi <= end - start < 2pi\n if (startAngle > endAngle) {\n return endAngle;\n } else if (startAngle < endAngle) {\n return endAngle - 2 * Math.PI;\n } else {\n // equal\n return startAngle;\n }\n } else {\n // angle is 'increasing'\n // -2pi < end - start <= 2pi\n if (startAngle < endAngle) {\n return endAngle;\n } else if (startAngle > endAngle) {\n return endAngle + Math.PI * 2;\n } else {\n // equal\n return startAngle;\n }\n }\n }", "_validateAngles() {\n const that = this;\n\n that._normalizedStartAngle = that._normalizeAngle(that.startAngle);\n that.endAngle = that._normalizeAngle(that.endAngle);\n\n if (that._normalizedStartAngle < that.endAngle) {\n that.startAngle = that._normalizedStartAngle;\n }\n else {\n that.startAngle = that._normalizedStartAngle - 360;\n }\n\n that._angleDifference = that.endAngle - that.startAngle;\n }", "function Tol(n1, n2, tolerance) {\n var upperlimit = n1 + tolerance;\n var lowerlimit = n1 - tolerance;\n\n if (n2 >= lowerlimit && n2 <= upperlimit) {\n return true;\n } else {\n if (n2 - lowerlimit < 1 && n2 - lowerlimit > -1) {\n }\n return false;\n }\n}", "AngleIsBetweenAngles(a, b) {\n const firstAngle = C3.toRadians(a)\n const secondAngle = C3.toRadians(b)\n const angle = this._inst.GetWorldInfo().GetAngle()\n return angle >= firstAngle && angle <= secondAngle;\n }", "function angleRangeIsWithin(range1, range2) {\n if (range2[0] == (range2[0] + range2[1]).mod(360)) {\n return true;\n }\n ////console.log(\"r1: \" + range1[0] + \", \" + range1[1] + \" ... r2: \" + range2[0] + \", \" + range2[1]);\n\n var distanceFrom0 = (range1[0] - range2[0]).mod(360);\n var distanceFrom1 = (range1[1] - range2[0]).mod(360);\n\n if (distanceFrom0 < range2[1] && distanceFrom1 < range2[1] && distanceFrom0 < distanceFrom1) {\n return true;\n }\n return false;\n }", "function angleRangeIsWithin(range1, range2) {\n if (range2[0] == (range2[0] + range2[1]).mod(360)) {\n return true;\n }\n //console.log(\"r1: \" + range1[0] + \", \" + range1[1] + \" ... r2: \" + range2[0] + \", \" + range2[1]);\n\n var distanceFrom0 = (range1[0] - range2[0]).mod(360);\n var distanceFrom1 = (range1[1] - range2[0]).mod(360);\n\n if (distanceFrom0 < range2[1] && distanceFrom1 < range2[1] && distanceFrom0 < distanceFrom1) {\n return true;\n }\n return false;\n }", "function approxEqual(a, b, tolerance) {\n\t if (tolerance === void 0) { tolerance = 0.00001; }\n\t return Math.abs(a - b) <= tolerance;\n\t}", "function check_relative_difference(val1, val2, tolerance)\n{\n return ((Math.min(val1, val2) / Math.max(val1, val2)) >= tolerance);\n}", "function approxEqual(a, b, tolerance) {\n if (tolerance === void 0) { tolerance = 0.00001; }\n return Math.abs(a - b) <= tolerance;\n}", "function angleBetween_(angle, start, end) {\n if(start<end) return start<=angle && angle<=end;\n return start<=angle || angle<=end;\n}", "_withinTolerance(actual, expected, tolerance) {\n const tolerances = {\n lower: actual,\n upper: actual,\n };\n if (tolerance) {\n tolerances.lower -= Math.max(tolerance, 0);\n tolerances.upper += Math.max(tolerance, 0);\n }\n return Math.max(expected, 0) >= Math.max(tolerances.lower, 0) &&\n Math.max(expected, 0) <= Math.max(tolerances.upper, 0);\n }", "function inTolerance(actual, projected, tolerance) {\n return projected - tolerance < actual && projected + tolerance > actual;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
waits a second to check if the user is still typing out the graph equation. If not, update the graph.
function requestEquationInput() { graphEquations[curGraphNo] = expressionInput.value; if (!requestingEquationInput) { requestingEquationInput = true; equationInputWait = 0; //the updated expression string let curString = "y=" + expressionInput.value; let interval = window.setInterval(function () { equationInputWait++; //if the wait is complete and the equation isn't changed, do nothing if (equationInputWait == 10 && curString == begString) { equationInputWait = 0; requestingEquationInput = false; window.clearInterval(interval); } //otherwise, if the wait is complete and the equation is changed, draw() else if (equationInputWait == 10 && curString != begString) { //SHH if (expressionInput.value == "ecocity") { Plotly.animate('plot' + curGraphNo, { data: [{ y: [2, 4, 4, 10, 4, 4, 2, 2], x: [-0.1, -0.1, -0.5, 0, 0.5, 0.1, 0.1, -0.1] }], traces: [0], layout: {} }, { transition: { duration: 500, easing: 'cubic-in-out' }, frame: { duration: 500 } }); } else { equationInputWait = 0; requestingEquationInput = false; draw(curGraphNo); window.clearInterval(interval); } } }, 100); } else {//if the user keeps typing while the input is waiting, restart the wait equationInputWait = 0; } }
[ "function tryDraw() {\n let inputGraph = document.querySelector(\"#inputGraph\");\n if (oldInputGraphValue !== inputGraph.value) {\n oldInputGraphValue = inputGraph.value;\n network.drawNetwork(oldInputGraphValue);\n }\n}", "function graphMoveByInput(e) {\n if (lock) {\n if (failedInputs) {\n lock = false;\n } else {\n //var w = $('#word').attr('value');\n //$('#word').attr('value', w.substr(0, w.length-1));\n lock = false;\n return false;\n }\n } else {\n lock = true;\n }\n\n\t// no graph\n\tif(!graphit) return;\n\t\n\t// we are at the beginning\n\tif (!gCurrentState || !gPrevState) {\n\t\tgPrevStates.push(g.nodes[0]);\n\t\tgPrevState = g.nodes[0];\n\t\tgCurrentState = g.nodes[0];\n\t};\n\t\n\t// backspace\n\tif (e.which == 8) {\n\t\t// step over failed inputs.\n\t\tif (window.failedInputs.length > 0) {\n\t\t\tif(window.failedInputs.length == 1) {\n\t\t\t\tif (ttable[gCurrentState.name].isFinal) {\n\t\t\t\t\tgraph_success();\n\t\t\t\t} else {\n\t\t\t\t\tgraph_inprogress();\n\t\t\t\t};\n\t\t\t};\n\t\t\twindow.failedInputs.pop();\n\t\t\treturn;\n\t\t}\n\t\t\n\t\t// no state change\n\t\tif (window.inSameState.length > 0) {\n\t\t\tvar mx = g.mover.attr('cx');\n\t\t\tvar my = g.mover.attr('cy');\n\t\t\tvar ll = g.paper.path('M'+mx+','+my+' '+mx+','+(my-25)+'Z').attr({stroke: 0});\n\t\t\twindow.setTimeout(function() { g.mover.animateAlong(ll, 250, \"bounce\"); }, 250);\n\t\t\twindow.inSameState.pop();\n\t\t\tif (ttable[window.gCurrentState.name].isFinal) {\n\t\t\t\tgraph_success();\n\t\t\t} else {\n\t\t\t\tgraph_inprogress();\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t\t\n\t\t// go back one state\n\t\twindow.gPrevState = gPrevStates.pop();\n if (!window.gPrevState) return; // none of word left\n\t\twindow.setTimeout(function() {\n if (!window.gPrevState) return; // none of word left\n g.mover.animate({cx:gPrevState.node[1][0].cx.baseVal.value, cy:gPrevState.node[1][0].cy.baseVal.value}, 250);\n lock = false;\n }, 250);\n\t\twindow.gCurrentState = gPrevState;\n\t\tif (ttable[window.gCurrentState.name].isFinal) {\n\t\t\tgraph_success();\n\t\t} else {\n\t\t\tgraph_inprogress();\n\t\t};\n\t\treturn;\n\t};\n\t\n\t// getting input\n\tvar key = String.fromCharCode(e.which);\n\tvar gNextState = g.graphNodeByName[window.ttable[window.gCurrentState.name][key]];\n\n\tgraph_inprogress();\n\t\n\t// --> failure\n\tif (!gNextState) {\n\t\twindow.failedInputs.push(true);\n\t\tgraph_failure();\n\t\treturn;\n\t};\n\t\n\t// no state change\n\tif(gNextState.name == gCurrentState.name) {\n\t\twindow.setTimeout(function() {\n g.mover.animateAlong(gCurrentState.node[4], 350);lock = false;\n }, 125);\n\t\twindow.inSameState.push(true);\n if (ttable[window.gCurrentState.name].isFinal) {\n\t\t\tgraph_success();\n\t\t} else {\n\t\t\tgraph_inprogress();\n\t\t};\n\t\treturn;\n\t} else {\n\t\t// state change\n\t\tvar theConn;\n\t\tfor (var c in g.connections) {\n\t\t\tif ((window.gCurrentState.name == g.connections[c].name1) && (gNextState.name == g.connections[c].name2)) {\n\t\t\t\ttheConn = g.connections[c];\n\t\t\t\tbreak;\n\t\t\t};\n\t\t};\n\t\tvar x = gCurrentState.node[1][0].cx.baseVal.value;\n\t\tvar y = gCurrentState.node[1][0].cy.baseVal.value;\n\t\tline = g.paper.path(\n\t\t\t'M'+x+gCurrentState.node[1][0].r.baseVal.value+','+y+' '+theConn.line.attr('path').toString().substring(1)\n\t\t\t+'L'+(gNextState.node[1][0].cx.baseVal.value)+','+gNextState.node[1][0].cy.baseVal.value\n\t\t\t).attr({stroke:'none'});\n\t (function(g, line) {\n\t setTimeout(function() {\n\t \tg.mover.animateAlong(line, 164);\n lock = false;\n\t\t\t\treturn line;\n\t\t\t}, 250);\n\t })(g, line);\n\t};\n\twindow.gPrevStates.push(gCurrentState);\n\twindow.gPrevState = gCurrentState;\n\twindow.gCurrentState = gNextState;\n\tif (ttable[window.gCurrentState.name].isFinal) {\n\t\tgraph_success();\n\t};\n}", "function updateEquation(){\n // clear if previous button clicked is equal\n if (equalClickedPrev){\n clearClickUpdate();\n // update equation if previous button clicked was an operator\n } else if (curOperator != ''){\n equation = equation+displayVal+curOperator;\n curOperator = '';\n displayVal = '';\n } \n}", "function drawGraph() {\n uncheckAllButtons();\n equation = document.getElementById('equationInput').value;\n let stax = document.getElementById('equationStartX').value;\n let endx = document.getElementById('equationEndX').value;\n let equationList = equation.split('=');\n if (equationList.length != 2) {\n document.getElementById('graphOutput').style.color = '#9e0000';\n document.getElementById('graphOutput').innerText = 'Invalid Equation';\n return;\n }\n equation = equationList[1];\n if (equation[0] == '-') {\n equation = '0' + equation;\n }\n for (let id = 0; id < equation.length; id++) {\n if (equation[id] == '+' || equation[id] == '-' || equation[id] == '*'\n || equation[id] == '/' || equation[id] == ')' || equation[id] == '(') {\n equation = equation.slice(0, id) + ' ' + equation[id]\n + ' ' + equation.slice(id+1, equation.length);\n id += 2;\n } else if (equation[id+1] == 'x') {\n equation = equation.slice(0, id+1) + ' * '\n + equation.slice(id+1, equation.length);\n id += 3;\n }\n }\n for (let xc=parseFloat(stax); xc<parseFloat(endx); xc+= minTrailLen) {\n trail.push({x: xc, y: calculateY(xc)});\n }\n trails.push(trail);\n trail = [];\n document.getElementById('graphOutput').style.color = '#2a9e00';\n document.getElementById('graphOutput').innerText = 'Graph Drawn';\n drawRemain += 1;\n updateScreen();\n}", "function graphClicked(graphNo) {\n curGraphNo = graphNo;\n expressionInput.style.display = \"block\";\n expressionInput.value = graphEquations[graphNo];\n}", "function drawGraph() {\n uncheckAllButtons();\n equation = document.getElementById('equationInput').value;\n let stax = document.getElementById('equationStartX').value;\n let endx = document.getElementById('equationEndX').value;\n\n for (let id = 0; id < equation.length; id++) {\n if (equation[id] == '+' || equation[id] == '-' || equation[id] == '*'\n || equation[id] == '/' || equation[id] == ')' || equation[id] == '(') {\n equation = equation.slice(0, id) + ' ' + equation[id]\n + ' ' + equation.slice(id+1, equation.length);\n id += 2;\n }\n }\n\n for (let xc=parseFloat(stax); xc<parseFloat(endx); xc+= epsilon) {\n trail.push({x: xc, y: calculateY(xc)});\n }\n trails.push(trail);\n trail = [];\n updateScreen();\n}", "function redraw() {\n if (mainSvg == null)\n return;\n let textfield = document.querySelector(\"#textfield\");\n let sentence = Parse.ParseSentence(textfield.value);\n Render.render(mainSvg, sentence);\n if (downloadButton != null)\n downloadButton.disabled = false;\n}", "function updateGraphHandler(e, control, graph) {\n if (control.hasClass(\"hidden\")) // Don't update graph if the controls are hidden\n return;\n else if ($(\"input[type=checkbox]:checked\").length === 0) { // Don't update if no \"Active\" boxes are checked\n let message = 'Please tick one of the checkboxes above before clicking \"Update graph\" again.';\n inactiveError(e, message);\n }\n else { // Don't update if the start game week is later than end game week\n let gameWeekEndPoints = checkGameweek();\n if (gameWeekEndPoints)\n graph.update(gameWeekEndPoints[0], gameWeekEndPoints[1]);\n }\n}", "softUpdate(){\n \n this.updateInputs()\n\n if (this.errorList.length == 0){\n this.scene.updateCylinders()\n this.scene.updatePlot(false)\n var totalVol = this.getTotalCylinderVolume()\n this.volumeGraph.addPoint(this.n, totalVol)\n this.updateCylinderVolumeText(totalVol)\n }\n }", "_updateAudioGraph()\n {\n\n /// first of all, disconnect everything\n this._input.disconnect();\n this._gainsNode.disconnect();\n\n this._input.connect( this._gainsNode._input );\n this._gainsNode.connect( this._output );\n\n this._update();\n }", "function updateAnalysisRequestWithCurrentState() {\n console.log('updateAnalysisRequestwithCurrentState');\n console.log(myInputJSObject.request);\n // Create temporary variable for previous results.\n var newPreviousAnalysis = myInputJSObject.results;\n // Increment selected time point, because the user selected the values for this state.\n newPreviousAnalysis.set('selectedTimePoint', newPreviousAnalysis.get('selectedTimePoint') + 1);\n\n // Get the page number currently selected on the interface.\n var currentPage = document.getElementById(\"currentPage\").value; // Page number associated with the selected state.\n\n // Get the name associated with the selected state.\n var stateName;\n for (var key in allSolutionIndex) {\n if (allSolutionIndex[key] <= currentPage) {\n stateName = key;\n }\n }\n\n // Determine the next time point.\n var timePointPath = newPreviousAnalysis.get('timePointPath');\n var nextTimePointAbsVal;\n if (stateName == 'TNS-A' && newPreviousAnalysis.get('nextPossibleAbsValue') != null) {\n nextTimePointAbsVal = newPreviousAnalysis.get('nextPossibleAbsValue');\n } else {\n nextTimePointAbsVal = newPreviousAnalysis.get('nextPossibleRndValue');\n }\n timePointPath.push(nextTimePointAbsVal);\n\n // Iterates over each of the time point values and get them an assignment to the next time point.\n var listStateTPs = newPreviousAnalysis.get('nextStateTPs')[stateName];\n listStateTPs.forEach(\n solution => {\n newPreviousAnalysis.get('timePointAssignments')[solution] = nextTimePointAbsVal;\n })\n\n // Update the elementList with the new states satisfaction values.\n var elementList = newPreviousAnalysis.get('elementList');\n for (let i = 0; i < elementList.length; i++) {\n elementList[i].status.push(allSolutionArray[currentPage][i]);\n }\n\n // Update values that are no longer needed. \n newPreviousAnalysis.set('name', null);\n newPreviousAnalysis.set('colorVis', null);\n newPreviousAnalysis.set('nextStateTPs', null);\n newPreviousAnalysis.set('allSolutions', null);\n newPreviousAnalysis.set('nextPossibleAbsValue', null);\n newPreviousAnalysis.set('nextPossibleRndValue', null);\n\n // Assign back to request.\n myInputJSObject.request.set('previousAnalysis', newPreviousAnalysis);\n // myInputJSObject.request.set('results', null);\n console.log(\"New Request:\" + JSON.stringify(myInputJSObject.request.toJSON()));\n }", "function updateState(){ \n var numberGuess = d3.select(\"#number-guess\");\n\n d3.event.preventDefault();\n d3.selectAll(\".bull-cow\").remove();\n d3.selectAll(\".warning-message\").remove();\n d3.selectAll(\".attempt-message\").remove()\n\n //checking the guess is valid and updating the DOM with appropriate # of bulls and cows \n checkGuessDigits(numberGuess.property(\"value\"));\n updateBullsAndCows(numberGuess.property(\"value\"));\n updateNumberOfAttempts();\n //empty the search field after a guess\n numberGuess.property(\"value\",\"\");\n }", "updateIfShould(){\n const fieldForLegend = this.getFieldForLegend();\n const shouldUpdate = (\n fieldForLegend &&\n fieldForLegend.terms && fieldForLegend.terms.length > 0 &&\n fieldForLegend.terms[0] && fieldForLegend.terms[0].color === null\n );\n\n if (shouldUpdate){\n setTimeout(()=>{\n this.forceUpdate();\n }, 750);\n }\n }", "notifyUpdate() {\n if (this.hasUpdate)\n return; // already notified\n this.hasUpdate = true;\n this.schematic.notifyUpdate();\n }", "updateData() {\n forXAndY(8, (x, y) => {\n this.inputNumber(parseInt(document.getElementById(`${x}, ${y}`).value), x, y);\n });\n\n if (this.isSolved()) {\n this.stopTimer();\n setTitle(`Congratulations!`);\n }\n this.updateOptions();\n }", "function updateuserbalance(user, graph, time, data){\n\n userbalance = parseFloat(validate(data[\"balance\"].toString())); //Update the global var\n var rounded = Math.round(userbalance * 100) / 100;\n document.getElementById(\"balance_dashboard\").innerHTML = rounded + \"ᕲ\"; //Update userbalance text box\n \n if(wait==0){ //set the firt userbalance for the Duco per day valculation tool\n oldb = userbalance; \n }\n if(wait==10){ //After 30s (because this gets executed every 3s) call the calculatedaily funtion and reset the counter\n wait=0;\n calculdaily(userbalance, oldb)\n }\n else{ //If shorter than 15s since last recalculation add 1 to i\n wait++;\n }\n addgraph(time, userbalance, graph); //Update the userbalance graph\n}", "function update_graph() {\n console.log(\"data\", data);\n if(data[0].length > 0) {\n console.log(\"Show the graph with information\", data[0]);\n document.getElementById(\"graph_box\").style.display = 'block';\n setChart(data[0], data[1]);\n } else {\n console.log(\"Hide the graph\", data[0]);\n document.getElementById(\"graph_box\").style.display = 'none';\n }\n}", "function updateInput(q) {\n if (q >= Object.keys(inputs).length) {\n // generate results and display here\n $(\"#calcForm\").fadeOut(400, () => {\n let p = atRetirement();\n let e = throughRetirement(p);\n toPortfolio(e);\n });\n return;\n } else {\n $('#calcInputLabel').fadeOut(250, () => {\n document.getElementById('calcInputLabel').innerHTML = inputs[q];\n if (q === (Object.keys(inputs).length - 1)) {\n $('#calcInputButton').fadeOut(250, () => {\n document.getElementById('calcInputButton').innerHTML = 'Finish';\n $('#calcInputButton').fadeIn(250);\n });\n } else {\n document.getElementById('calcInputButton').innerHTML = 'Next';\n }\n $('#calcInputLabel').fadeIn(250);\n document.getElementById('calcInput').value = '';\n });\n document.getElementById('calcInput').focus();\n }\n}", "function tick()\n{\n\tif (mywindow.findChild(\"_update\").checked)\n\t{\n\t\tquery();\n\t}\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
create a IPv4 subnet mask based on a number of bits
function IPAddress$createIpv4Mask(maskSize) { return -1<<(32-maskSize); }
[ "function bitsToNetmask(bits) {\n var n = 0;\n\n for (var i = 0; i < (32 - bits); i++) {\n n |= 1 << i;\n }\n return numberToAddress(MAX_IP - n);\n}", "function generateMask() {\n var ct = 10; // infinite loop prevention :-)\n while (ct-- > 0) {\n var octs = [255, 255, 255, 255];\n var which = getRandomInt(0, 4);\n\n octs[which] = 256 - Math.pow(2, getRandomInt(0, 9));\n for (var i = which + 1; i < 4; i++) {\n octs[i] = 0;\n }\n\n var netmaskString = octs.join('.');\n // sanity check\n if (netmaskString != '0.0.0.0' &&\n netmaskString != '128.0.0.0' &&\n netmaskString != '255.255.255.255' &&\n netmaskString != '255.255.255.254') {\n // good netmask\n break;\n }\n }\n\n return DottedDecimalIp.new(octs[0], octs[1], octs[2], octs[3]);\n }", "function subnetID(aNet,aMask){\n var a = new Array(0,0,0,0);\n for(var i=0;i<4;i++){\n a[i] = aNet[i] & aMask[i];\n }\n return a;\n}", "maskForRemainingSubnets(subnetCount) {\n const remaining = this.networkCidr.maxAddress() - this.nextAvailableIp + 1;\n const ipsPerSubnet = Math.floor(remaining / subnetCount);\n return 32 - Math.floor(Math.log2(ipsPerSubnet));\n }", "static calculateNetmask(mask) {\n return NetworkUtils.numToIp(2 ** 32 - 2 ** (32 - mask));\n }", "function prefixToNetMask(prefixLen) {\n var prefix = Math.pow(2,prefixLen) - 1;\n var binaryString = prefix.toString(2);\n for(var i=binaryString.length;i<32;i++) {\n binaryString += '0';\n }\n return v4.Address.fromHex(parseInt(binaryString,2).toString(16)).address;\n}", "function createMask() {\n\tvar nMask = 0, nFlag = 0, nLen = arguments.length > 32 ? 32 : arguments.length;\n \tfor (nFlag; nFlag < nLen; nMask |= arguments[nFlag] << nFlag++);\n \treturn nMask;\n}", "function createMask() {\n var nMask = 0,\n nFlag = 0,\n nLen = arguments.length > 32 ? 32 : arguments.length;\n for (nFlag; nFlag < nLen; nMask |= arguments[nFlag] << nFlag++);\n return nMask;\n}", "function IPv4_Calc_netaddrBinStr(addressBinStr, netmaskBinStr) {\n var netaddressBinStr = '';\n var aBit = 0;\n var nmBit = 0;\n for (let pos = 0; pos < 32; pos++) {\n aBit = addressBinStr.substr(pos, 1);\n nmBit = netmaskBinStr.substr(pos, 1);\n if (aBit == nmBit) {\n netaddressBinStr += aBit.toString();\n }\n else {\n netaddressBinStr += '0';\n }\n }\n return netaddressBinStr;\n}", "function IPv4_Calc_netaddrBinStr(addressBinStr, netmaskBinStr) {\n let netaddressBinStr = '';\n let aBit = 0;\n let nmBit = 0;\n for (let pos = 0; pos < 32; pos++) {\n aBit = addressBinStr.substr(pos, 1);\n nmBit = netmaskBinStr.substr(pos, 1);\n if (aBit == nmBit) {\n netaddressBinStr += aBit.toString();\n } else {\n netaddressBinStr += '0';\n }\n }\n return netaddressBinStr;\n}", "function findIpV4Netmask(value) {\n var netmask = '24'; // Di default ho una /24\n /* Estraggo l'eventuale netmask dall'indirizzo ip */\n var netmaskPosition = value.indexOf('/');\n if (netmaskPosition !== -1) {\n netmask = value.substring(netmaskPosition + 1, value.length);\n }\n /* Calcolo il prefisso utilizzando un'apposita libreria */\n IPv4_Address(value, netmask);\n //this.netaddressDotQuad è il prefisso ricavato.\n return netaddressDotQuad + '/' + netmask;\n}", "function makeBitmask() {\n var nMask = 0, nFlag = 0, nLen = arguments.length > 32 ? 32 : arguments.length;\n for (nFlag; nFlag < nLen; nMask |= arguments[nFlag] << nFlag++);\n return nMask;\n}", "function BITS_MASK(n) { return ((1<<(n))-1) }", "function maskAnd(ip, mask) {\n /* The following line adjusts the ip address to match the first address in the subnet (filtering all non-subnet mask bits in the ip */\n /* Not that this is done for the left 16 bits and the right 16 bits separately since the bitwise operator works on 32 bit signed integers yielding negative values */\n return ((parseInt(ip.toBin().substr(0,16), 2) & parseInt(mask.toBin().substr(0,16), 2)) * factor16 + (parseInt(ip.toBin().substr(16,16), 2) & parseInt(mask.toBin().substr(16,16), 2)));\n}", "function checkIp_Mask(lanIp,lanMask)\r\n{\r\n\r\n var count = 0;\r\n var count2 = 0;\r\n var l1a_n,l1m_n;\r\n\r\n var _lanIp = lanIp.split('.');\r\n var _lanMask = lanMask.split('.');\r\n\r\n for (i = 0; i < 4; i++) {\r\n l1a_n = parseInt(_lanIp[i]);\r\n l1m_n = parseInt(_lanMask[i]);\r\n if ((l1a_n & l1m_n)==0)\r\n count++;\r\n\t else if((l1a_n & l1m_n)==1)\r\n\t \t count2++;\r\n }\r\n if (count == 4)\r\n {\r\n\t // alertError('CheckIp_Mask',1);\r\n return false;\r\n }\r\n else if(count2 == 4)\r\n {\r\n\t // alertError('CheckIp_Mask',1);\r\n return false;\r\n }\r\n else\r\n return true;\r\n}", "function generateBroadcastAndNetworsAddresses(ip, sMask ) {\n\tvar check = 0;\n \tvar arrIp = ip.split('.');\n \tfor(var i = 0; i < 4; i++){\n\t\tif ( arrIp[i] <= 255){\n\t\t\tcheck++;\n\t\t}\n\t}\n\tif(check != 4){\n\t\treturn 'Некоректный IP'\n\t} else {\n\t\tvar mask = Math.pow(2,8) - Math.pow(2,32 - sMask);\n\t\tmask = mask.toString(2);\n\t \tvar last = arrIp[3].toString(2);\n\t arrIp[3] = last&mask;\n\t console.log('Network -', arrIp.join('.'));\n\t var brCast = arrIp;\n\t brCast[3] = arrIp[3]+Math.pow(2,32 - sMask) - 1;\n\t \treturn 'Broadcast - ' + brCast.join('.'); \n\t}\n\n}", "function checkIp_Mask(lanIp,lanMask)\r\n{\r\nvar count = 0;\r\nvar count2 = 0;\r\nvar l1a_n,l1m_n;\r\nvar _lanIp = lanIp.split('.');\r\nvar _lanMask = lanMask.split('.');\r\nfor (i = 0; i < 4; i++) {\r\nl1a_n = parseInt(_lanIp[i]);\r\nl1m_n = parseInt(_lanMask[i]);\r\nif ((l1a_n & l1m_n)==0)\r\ncount++;\r\nelse if((l1a_n & l1m_n)==1)\r\ncount2++;\r\n}\r\nif (count == 4)\r\n{\r\nalertError('CheckIp_Mask',1);\r\nreturn false;\r\n}\r\nelse if(count2 == 4)\r\n{\r\nalertError('CheckIp_Mask',1);\r\nreturn false;\r\n}\r\nelse\r\nreturn true;\r\n}", "constructor(ip, netmask) {\n if (typeof ip !== 'string') {\n throw new Error('Missing ip')\n }\n if (!netmask) {\n [ip, netmask] = ip.split('/', 2)\n }\n if (!netmask) {\n throw new Error(`Invalid ip address: ${ip}`)\n }\n\n if (netmask) {\n this.bitmask = parseInt(netmask, 10)\n this.maskLong = 0\n if (this.bitmask > 0) {\n this.maskLong = (0xffffffff << (32 - this.bitmask)) >>> 0\n }\n } else {\n throw new Error('Invalid netmask: empty')\n }\n \n if (isNaN(this.bitmask) || this.bitmask > 32 || this.bitmask < 0) {\n throw new Error(`Invalid netmask: ${netmask}`)\n }\n\n try {\n this.netLong = (ipTolong(ip) & this.maskLong) >>> 0\n } catch (err) {\n throw new Error(`Invalid ip address: ${ip}`)\n }\n\n this.ip = ip\n this.cidr = `${ip}/${this.bitmask}`\n this.size = Math.pow(2, 32 - this.bitmask)\n this.netmask = longToIp(this.maskLong)\n\n // The host netmask, the opposite of the netmask (eg.: 0.0.0.255)\n this.hostmask = longToIp(~this.maskLong)\n\n this.first = longToIp(this.netLong)\n this.last = longToIp(this.netLong + this.size - 1)\n }", "function createMask() {\n return crypto.getRandomValues(new Uint8Array(4));\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
fill in code that creates the triangles for a sphere with diameter 1 (centered at the origin) with number of slides (longitude) given by slices and the number of stacks (lattitude) given by stacks. For this function, you will implement the tessellation method based on spherical coordinates as described in the video (as opposed to the recursive subdivision method).
function makeSphere (slices, stacks) { // fill in your code here. var triangles = []; var origin = [0.0, 0.0, 0.0]; const radius = 0.5; const longi_step = radians(360 / slices); // in radian const lati_step = radians(180 / stacks); // in radian var theta = 0.0; for (var i=0; i<slices; i++){ var phi = 0.0; for(var j=0; j<stacks; j++){ var v1 = [radius * Math.sin(theta) * Math.sin(phi), radius * Math.cos(phi), radius * Math.cos(theta) * Math.sin(phi)]; var v2 = [radius * Math.sin(theta + longi_step) * Math.sin(phi), radius * Math.cos(phi), radius * Math.cos(theta + longi_step) * Math.sin(phi)]; var v3 = [radius * Math.sin(theta) * Math.sin(phi + lati_step), radius * Math.cos(phi + lati_step), radius * Math.cos(theta) * Math.sin(phi + lati_step)]; var v4 = [radius * Math.sin(theta + longi_step) * Math.sin(phi + lati_step), radius * Math.cos(phi + lati_step), radius * Math.cos(theta + longi_step) * Math.sin(phi + lati_step)]; triangles.push([v1, v3, v2]); triangles.push([v2, v3, v4]); phi += lati_step; } theta += longi_step; } console.log(triangles.length); for (tri of triangles){ addTriangle( tri[0][0], tri[0][1], tri[0][2], tri[1][0], tri[1][1], tri[1][2], tri[2][0], tri[2][1], tri[2][2] ); } }
[ "function makeSphere (slices, stacks) {\n // fill in your code here.\n var sliceDivision = radians(360) / slices;\n var stackDivision = radians(180) / stacks;\n var radius = 0.5;\n\n for (var longitude = 0; longitude < radians(360); longitude += sliceDivision) {\n for (var latitude = 0; latitude < radians(180); latitude += stackDivision) {\n addTriangle(radius * Math.cos(longitude) * Math.sin(latitude + stackDivision), radius * Math.sin(longitude) * Math.sin(latitude + stackDivision), radius * Math.cos(latitude + stackDivision), \n radius * Math.cos(longitude) * Math.sin(latitude), radius * Math.sin(longitude) * Math.sin(latitude), radius * Math.cos(latitude), \n radius * Math.cos(longitude + sliceDivision) * Math.sin(latitude + stackDivision), radius * Math.sin(longitude + sliceDivision) * Math.sin(latitude + stackDivision), radius * Math.cos(latitude + stackDivision));\n \n addTriangle(radius * Math.cos(longitude + sliceDivision) * Math.sin(latitude + stackDivision), radius * Math.sin(longitude + sliceDivision) * Math.sin(latitude + stackDivision), radius * Math.cos(latitude + stackDivision), \n radius * Math.cos(longitude) * Math.sin(latitude), radius * Math.sin(longitude) * Math.sin(latitude), radius * Math.cos(latitude), \n radius * Math.cos(longitude + sliceDivision) * Math.sin(latitude), radius * Math.sin(longitude + sliceDivision) * Math.sin(latitude), radius * Math.cos(latitude));\n\n }\n }\n}", "function makeSphere (slices, stacks) {\n var pi = Math.PI;\n var rad = 360 * (pi/180); //360 in radians\n var points = [];\n \n var cols = slices;\n var rows = stacks;\n \n //Calculate all the points of the sphere\n var r = .5;\n for( var i = 0; i < cols+1; i++ ) {\n points[i] = [];\n var lat = map_range(i, 0, cols, 0, Math.PI);\n for( var j = 0; j < rows+1; j++ ) {\n var lon = map_range(j, 0, rows, 0, Math.PI * 2);\n \n var x = r * Math.sin( lat ) * Math.cos( lon );\n var y = r * Math.sin( lat ) * Math.sin( lon );\n var z = r * Math.cos( lat );\n var point = [x, y, z];\n \n points[i][j] = point;\n }\n }\n \n //iterate through the points, drawing a \"rectangle\" at a time.\n\n for( i = 0; i < cols; i++ ) {\n for( j = 0; j < rows; j++ ) {\n var topl = [ points[i][j][0], points[i][j][1], points[i][j][2] ];\n var botl = [ points[i+1][j][0], points[i+1][j][1], points[i+1][j][2] ];\n var topr = [ points[i][j+1][0], points[i][j+1][1], points[i][j+1][2] ];\n var botr = [ points[i+1][j+1][0], points[i+1][j+1][1], points[i+1][j+1][2] ];\n \n addTriangle(topl[0], topl[1], topl[2], \n botl[0], botl[1], botl[2],\n topr[0], topr[1], topr[2]);\n \n addTriangle(topr[0], topr[1], topr[2],\n botl[0], botl[1], botl[2],\n botr[0], botr[1], botr[2]);\n }\n }\n //If anyone reads this, know that I came to the point of breaking on this section,\n //as I was getting a shope, but not a sphere. ~5 hours later (replicating this problem\n //in another language and trying three different methods of storing points), I found the solution.\n //I had typed my 'y' formula wrong, using cos(lat) * sin(lon) instead of two sin's. \n //Ignore this if you must, but my pain must be recorded somewhere.\n \n //I need to get me a rubber duck.... it would've helped\n \n}", "function Sphere(radius, stacks, slices){\n var stackAngle = 180.0 / stacks;\n var degree = 360.0 / slices;\n var currentRadius;\n\n var vertices = [];\n var allStackVertices = [];\n\n //Duplicate vertices for starting point of cube\n var firstPath = [];\n for (var i = 0; i < slices; i++ ) {\n var x, y, z;\n x = 0; y = radius; z = 0;\n firstPath.push({x, y, z});\n }\n allStackVertices.push(firstPath);\n\n //Calculate vertices for each stack\n for (var j = 1; j < stacks; j++){\n var y;\n var angle = stackAngle * j;\n currentRadius = Math.sin(degreeToRadian(angle)) * radius;\n\n y = Math.cos(degreeToRadian(angle)) * radius;\n\n for(var i = 0; i < slices; i++){\n var x, z;\n angle = degree * i;\n x = Math.cos(degreeToRadian(angle)) * currentRadius;\n z = Math.sin(degreeToRadian(angle)) * currentRadius;\n vertices.push({x, y, z});\n }\n allStackVertices.push(vertices);\n vertices = [];\n }\n\n //Duplicate vertices for starting point of cube\n var lastPath = [];\n for (var i = 0; i < slices; i++ ) {\n var x, y, z;\n x = 0; y = -radius; z = 0;\n lastPath.push({x, y, z});\n }\n allStackVertices.push(lastPath);\n\n return allStackVertices;\n}", "function setSphere(radius, numSlices, numStacks, r, g, b, colorMix) {\n\tvar x = 0.0;\n\tvar y = 0.0;\n\tvar z = 0.0;\n\tvar rad = radius;\n\tvertexArray = [];\n\tnormalArray = [];\n\tfor (i = 0; i < numStacks; i++) {\n\t\tfor (j = 0; j < numSlices; j++) {\n\t\t\tx = rad * Math.cos(2*Math.PI * (j / numSlices)) * Math.sin(Math.PI * (i / numStacks));\n\t\t\ty = rad * Math.sin(2*Math.PI * (j / numSlices)) * Math.sin(Math.PI * (i / numStacks));\n\t\t\tz = rad * Math.cos(Math.PI * (i / numStacks));\n\t\t\tvertexArray.push(x, y, z);\n\t\t\tnormalArray.push(x, y, z);\n\t\t\tx = rad * Math.cos(2*Math.PI * ((j+1) / numSlices)) * Math.sin(Math.PI * (i / numStacks));\n\t\t\ty = rad * Math.sin(2*Math.PI * ((j+1) / numSlices)) * Math.sin(Math.PI * (i / numStacks));\n\t\t\tvertexArray.push(x, y, z);\t\t\n\t\t\tnormalArray.push(x, y, z);\t\t\t\n\t\t\tx = rad * Math.cos(2*Math.PI * (j / numSlices)) * Math.sin(Math.PI * ((i+1) / numStacks));\n\t\t\ty = rad * Math.sin(2*Math.PI * (j / numSlices)) * Math.sin(Math.PI * ((i+1) / numStacks));\n\t\t\tz = rad * Math.cos(Math.PI * ((i+1) / numStacks));\n\t\t\tvertexArray.push(x, y, z);\n\t\t\tnormalArray.push(x, y, z);\t\t\t\t\n\t\t\tx = rad * Math.cos(2*Math.PI * ((j+1) / numSlices)) * Math.sin(Math.PI * (i / numStacks));\n\t\t\ty = rad * Math.sin(2*Math.PI * ((j+1) / numSlices)) * Math.sin(Math.PI * (i / numStacks));\n\t\t\tz = rad * Math.cos(Math.PI * (i / numStacks));\t\t\t\n\t\t\tvertexArray.push(x, y, z);\n\t\t\tnormalArray.push(x, y, z);\t\t\t\t\t\n\t\t\tx = rad * Math.cos(2*Math.PI * (j / numSlices)) * Math.sin(Math.PI * ((i+1) / numStacks));\n\t\t\ty = rad * Math.sin(2*Math.PI * (j / numSlices)) * Math.sin(Math.PI * ((i+1) / numStacks));\n\t\t\tz = rad * Math.cos(Math.PI * ((i+1) / numStacks));\n\t\t\tvertexArray.push(x, y, z);\n\t\t\tnormalArray.push(x, y, z);\t\t\t\t\n\t\t\tx = rad * Math.cos(2*Math.PI * ((j+1) / numSlices)) * Math.sin(Math.PI * ((i+1) / numStacks));\n\t\t\ty = rad * Math.sin(2*Math.PI * ((j+1) / numSlices)) * Math.sin(Math.PI * ((i+1) / numStacks));\n\t\t\tvertexArray.push(x, y, z);\n\t\t\tnormalArray.push(x, y, z);\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t}\n\t}\n\t// color\n\ttextureArray = [];\n\tvar numVertices = (6 * numStacks * numSlices);\n\tfor (i = 0; i < numVertices; i++) {\n\t\tif (i % 4 == 0) {\n\t\t\ttextureArray.push(0.0, 0.0);\n\t\t} else if (i % 4 == 1) {\n\t\t\ttextureArray.push(1.0, 0.0);\n\t\t} else if (i % 2 == 2) {\n\t\t\ttextureArray.push(1.0, 1.0);\n\t\t} else {\n\t\t\ttextureArray.push(0.0, 1.0);\n\t\t}\n\t}\n}", "function sphere(nDiv, shading){\n function tetrahedron(a, b, c, d, nDiv, shading){\n divideTriangle(a, b, c, nDiv, shading);\n divideTriangle(d, c, b, nDiv, shading);\n divideTriangle(a, d, b, nDiv, shading);\n divideTriangle(a, c, d, nDiv, shading);\n }\n\n function divideTriangle(a, b, c, count, shading) {\n if ( count > 0 ) {\n \n var ab = mix( a, b, 0.5);\n var ac = mix( a, c, 0.5);\n var bc = mix( b, c, 0.5);\n \n ab = normalize(ab, true);\n ac = normalize(ac, true);\n bc = normalize(bc, true);\n \n divideTriangle( a, ab, ac, count - 1, shading);\n divideTriangle( ab, b, bc, count - 1, shading);\n divideTriangle( bc, c, ac, count - 1, shading);\n divideTriangle( ab, bc, ac, count - 1, shading);\n }\n else { \n triangle( a, b, c, shading);\n }\n }\n\n function triangle(a, b, c, shading) {\n points.push(a);\n points.push(b); \n points.push(c);\n \n //normals are vectors\n \n //Single normal per triangle\n if (shading == 0){\n var t1 = subtract(b, a);\n var t2 = subtract(c, a);\n var normal = normalize(cross(t2, t1));\n normal = vec4(normal);\n normal[3] = 0.0;\n\n normalsArray.push(normal);\n normalsArray.push(normal);\n normalsArray.push(normal);\n }\n if (shading == 1 || shading == 2){\n normalsArray.push(vec4(a[0],a[1], a[2], 0.0));\n normalsArray.push(vec4(b[0],b[1], b[2], 0.0));\n normalsArray.push(vec4(c[0],c[1], c[2], 0.0));\n }\n }\n\n //initial tetrahedron points\n var va = vec4(0.0, 0.0, -1.0,1);\n var vb = vec4(0.0, 0.942809, 0.333333, 1);\n var vc = vec4(-0.816497, -0.471405, 0.333333, 1);\n var vd = vec4(0.816497, -0.471405, 0.333333,1);\n tetrahedron(va, vb, vc, vd, nDiv, shading);\n}", "function buildSphere() {\n vertices = [];\n normals = [];\n indices = [];\n textureCoords = [];\n\n // The resolution of the sphere. (In vertices)\n vSegs = 32;\n hSegs = 32;\n\n // For each vertex, calculate it's position using a cosine and sin wave.\n for (var i = 0; i <= vSegs; ++i)\n for (var t = 0; t <= hSegs; ++t) {\n arrayPush(vertices, [Math.cos((t / (hSegs)) * Math.PI * 2) * Math.sin((i / vSegs / 2) * 2 * Math.PI),\n\t\t\t\t\t\t\t\t Math.cos((i / vSegs / 2) * Math.PI * 2),\n\t\t\t\t\t\t\t\t Math.sin((t / hSegs) * Math.PI * 2) * Math.sin((i / vSegs / 2) * 2 * Math.PI)]);\n\n arrayPush(normals, [Math.cos((t / (hSegs)) * Math.PI * 2) * Math.sin((i / vSegs / 2) * 2 * Math.PI),\n\t\t\t\t\t\t\t\t Math.cos((i / vSegs / 2) * Math.PI * 2),\n\t\t\t\t\t\t\t\t Math.sin((t / hSegs) * Math.PI * 2) * Math.sin((i / vSegs / 2) * 2 * Math.PI)]);\n }\n\n // Generate a list indexes that make up all the triangles out of the position data.\n for (var i = 0; i <= vSegs - 1; ++i)\n for (var t = 0; t <= hSegs - 1; ++t) {\n arrayPush(indices, [(i * (hSegs + 1)) + t, (i * (hSegs + 1)) + t + 1, ((i + 1) * (hSegs + 1)) + t]);\n arrayPush(indices, [(i * (hSegs + 1)) + t + 1, ((i + 1) * (hSegs + 1)) + t, ((i + 1) * (hSegs + 1)) + (t + 1)]);\n }\n\n // Generate the texture coordinate of each of the vertices.\n tx = 0.1;\n ty = 0;\n tw = 0.85;\n th = 1.2;\n for (var i = 0; i <= vSegs; ++i)\n for (var t = 0; t <= hSegs; ++t) {\n var x = (tw * (1 - (t / hSegs))) + tx,\n\t\t\t\ty = (th * (i / vSegs)) + ty;\n arrayPush(textureCoords,\n\t\t\t\t\t [clamp(x, 0, 1),\n\t\t\t\t\t clamp(y, 0, 1)]);\n }\n\n return new Model(vertices, indices, textureCoords, normals);\n}", "function unit_sphere(num_subdivisions) {\n if (typeof num_subdivisions === \"undefined\") { num_subdivisions = 7; }\n\n let num_triangles = Math.pow(4, num_subdivisions); // number of triangles per face of tetrahedron\n let indices = new Uint16Array(12 * num_triangles);\n let coords = new Float32Array(6 * num_triangles + 6); // see https://oeis.org/A283070\n let indices_pos = 0, coords_pos = 0; // current position in each of the arrays\n let map = new Map();\n\n /**\n * Gets the index of the coordinate c. If c already exists than its previous index is\n * returned otherwise c is added and its new index is returned. The whole point of this\n * function (and the map variable) is so that duplicate coordinates get merged into a single\n * vertex.\n */\n function add_coord(c) {\n let str = c.toString();\n if (!map.has(str)) {\n map.set(str, coords_pos);\n coords.set(c, coords_pos*3);\n coords_pos++;\n }\n indices[indices_pos++] = map.get(str);\n }\n\n /**\n * Recursive function to continually divide a triangle similar to the Sierpinski's triangle\n * recursive function.\n */\n function divide_triangle(a, b, c, n) {\n if (n === 0) {\n // Base case: add the triangle\n add_coord(b);\n add_coord(a);\n add_coord(c);\n } else {\n // Get the midpoints\n let ab = vec3.lerp(vec3.create(), a, b, 0.5);\n let ac = vec3.lerp(vec3.create(), a, c, 0.5);\n let bc = vec3.lerp(vec3.create(), b, c, 0.5);\n\n // Recursively divide\n divide_triangle(a, ab, ac, n-1);\n divide_triangle(ab, b, bc, n-1);\n divide_triangle(ac, bc, c, n-1);\n divide_triangle(ab, bc, ac, n-1);\n }\n }\n\n // Initial tetrahedron to be divdied, 4 equidistant points at approximately:\n // <0,0,-1>, <0,2*√2/3,1/3>, <-√6/3, -√2/3, 1/3>, and <√6/3, -√2/3, 1/3>\n\tlet a = vec3.fromValues(0.0, 0.0, -1.0);\n\tlet b = vec3.fromValues(0.0, 0.94280904158, 0.33333333333);\n\tlet c = vec3.fromValues(-0.81649658093, -0.4714045207, 0.33333333333);\n\tlet d = vec3.fromValues( 0.81649658093, -0.4714045207, 0.33333333333);\n \n // Subdivide each face of the tetrahedron\n\tdivide_triangle(a, b, c, num_subdivisions);\n\tdivide_triangle(d, c, b, num_subdivisions);\n\tdivide_triangle(a, d, b, num_subdivisions);\n divide_triangle(a, c, d, num_subdivisions);\n\n // Normalize each vertex so that it is moved to the surface of the unit sphere\n\tfor (let i = 0; i < coords.length; i += 3) {\n let coord = coords.subarray(i, i+3);\n vec3.normalize(coord, coord);\n }\n\n return [coords, indices];\n}", "function buildSphere(sphere){\n\n\tvert3 = [];\n\tind3 = [];\n\n\t//Let's start by creating an octahedron\n\n\tvert3 = [\n\n\t\t/*[0,-1,0, 0,0,0], [1,0,0, 0,0,0],\n\t\t[0,0,1, 0,0,0], [-1,0,0, 0,0,0],\n\t\t[0,0,-1, 0,0,0], [0,1,0, 0,0,0]*/\n\n\t\t[0,0,1, 0,0,0], [1,0,0, 0,0,0],\n\t\t[0,1,0, 0,0,0], [-1,0,0, 0,0,0],\n\t\t[0,-1,0, 0,0,0], [0,0,-1, 0,0,0]\n\n\n\t]\n\n\tind3 = [ //All the triangles have the vertices specified in clockwise order.\n\t\t/*0,1,2,\n\t\t0,2,3,\n\t\t0,3,4,\n\t\t0,4,1,\n\t\t1,5,2,\n\t\t2,5,3,\n\t\t3,5,4,\n\t\t4,5,1,*/\n\n\t\t1,5,2,\n\t\t1,0,4,\n\t\t2,5,3,\n\t\t4,0,3,\n\t\t3,5,4,\n\t\t3,0,2,\n\t\t4,5,1,\n\t\t2,0,1\n\n\n\t]\n\n\t//Now we have to recursively split the edges and normalize the distance of the points:\n\tvar iterations = 5; //Leave this reasonably low (4 or 5) or the algorithm will take too much time\n\n\t\n\tfor(i=0; i<iterations; i++){ //For each iteration, we split each face of the pyramid into 4 more faces\n\n\t\tvar newVert3 = [];\n\t\tvar newInd3 = [];\n\t\tvar d = 0;\n\t\tvar k = 0;\n\t\tvar faces = ind3.length / 3;\n\n\t\tfor(j=0; j<faces; j++){ //This is the algorithm that splits the single face. It is repeated for each face.\n\n\n\t\t\t//For each face, I retrieve its vertices by reading indexes in triplets\n\t\t\tvar vertex0_index = ind3[(j*3)];\n\t\t\tvar vertex1_index = ind3[(j*3)+1];\n\t\t\tvar vertex2_index = ind3[(j*3)+2];\n\n\t\t\tvar vertex0 = vert3[vertex0_index];\n\t\t\tvar vertex1 = vert3[vertex1_index];\n\t\t\tvar vertex2 = vert3[vertex2_index];\n\n\t\t\t//I add a point in the middle of each vertex by using a custom function:\n\t\t\tvar midpoint_01 = middlepoint(vertex0, vertex1);\n\t\t\tvar midpoint_02 = middlepoint(vertex0, vertex2);\n\t\t\tvar midpoint_12 = middlepoint(vertex1, vertex2);\n\n\n\t\t\t//I normalize the distance of each point by using a custom function\n\t\t\tmidpoint_01 = normalize(midpoint_01);\n\t\t\tmidpoint_02 = normalize(midpoint_02);\n\t\t\tmidpoint_12 = normalize(midpoint_12);\n\n\t\t\t//I add the vertices to a new vertices vector:\n\t\t\tnewVert3[d] = vertex0;\n\t\t\tnewVert3[d+1] = vertex1;\n\t\t newVert3[d+2] = vertex2;\n\t\t\tnewVert3[d+3] = midpoint_01;\n\t\t\tnewVert3[d+4] = midpoint_02;\n\t\t\tnewVert3[d+5] = midpoint_12;\n\t\t\t\n\n\t\t\t//I add the indexes to the array respecting the clockwise order of each triangle:\n\t\t\tnewInd3[k] = d; //vertex0\n\t\t\tnewInd3[k+1] = d+3; //midpoint_01\n\t\t\tnewInd3[k+2] = d+4; //midpoint_02\n\n\t\t\tnewInd3[k+3] = d+1; //vertex1\n\t\t\tnewInd3[k+4] = d+5; //midpoint_12\n\t\t\tnewInd3[k+5] = d+3; //midpoint_01\n\n\t\t\tnewInd3[k+6] = d+2; //vertex2\n\t\t\tnewInd3[k+7] = d+4; //midpoint_02\n\t\t\tnewInd3[k+8] = d+5; //midpoint_12\n\n\t\t\tnewInd3[k+9] = d+5; //midpoint_12\n\t\t\tnewInd3[k+10] = d+4; //midpoint_02\n\t\t\tnewInd3[k+11] = d+3;//midpoint_01\n\t\t\t\n\t\t\t//Increment of indexes used in the arrays:\n\t\t\tk = k+12;\n\t\t\td = d+6;\n\t\t}\n\n\t\t//When all the faces are completed, the result is treated as a new polyhedron.\n\t\tvert3 = newVert3;\n\t\tind3 = newInd3;\n\t}\n\n\tsphere.vert = vert3;\n\tsphere.ind = ind3;\n\treturn sphere;\n\n}", "function sphere(radius, n) {\n var thetaCount = 0;\n var phiCount;\n var thetaStep = (2*Math.PI)/(n+1);\n var phiStep = Math.PI/(n+1);\n var colorIndex = 0;\n var thetaAdd;\n\n for (var i = 0; i <= n; i++) {\n if (i == n) {\n thetaAdd = 0;\n } else {\n thetaAdd = thetaCount+thetaStep;\n }\n phiCount = 0;\n // longitudanel strip\n points.push(vec3(0.0,radius,0.0));\n colors.push(baseColors[(colorIndex++)%7]);\n for (var j = 1; j <= n; j++) {\n phiCount += phiStep;\n points.push(vec3(radius*Math.cos(thetaCount)*Math.sin(phiCount), radius*Math.cos(phiCount), radius*Math.sin(thetaCount)*Math.sin(phiCount)));\n colors.push(baseColors[(colorIndex++)%7]);\n points.push(vec3(radius*Math.cos(thetaAdd)*Math.sin(phiCount), radius*Math.cos(phiCount), radius*Math.sin(thetaAdd)*Math.sin(phiCount)));\n colors.push(baseColors[(colorIndex++)%7]);\n triangleStripCount += 2;\n }\n points.push(vec3(0.0,-1*radius,0.0));\n colors.push(baseColors[(colorIndex++)%7]);\n triangleStripCount += 2;\n thetaCount += thetaStep\n }\n}", "function unit_sphere(num_subdivisions) {\r\n if (typeof num_subdivisions === \"undefined\") { num_subdivisions = 7; }\r\n\r\n let num_triangles = Math.pow(4, num_subdivisions); // number of triangles per face of tetrahedron\r\n let indices = new Uint16Array(12 * num_triangles);\r\n let coords = new Float32Array(6 * num_triangles + 6); // see https://oeis.org/A283070\r\n let indices_pos = 0, coords_pos = 0; // current position in each of the arrays\r\n let map = new Map();\r\n\r\n /**\r\n * Gets the index of the coordinate c. If c already exists than its previous index is\r\n * returned otherwise c is added and its new index is returned. The whole point of this\r\n * function (and the map variable) is so that duplicate coordinates get merged into a single\r\n * vertex.\r\n */\r\n function add_coord(c) {\r\n let str = c.toString();\r\n if (!map.has(str)) {\r\n map.set(str, coords_pos);\r\n coords.set(c, coords_pos*3);\r\n coords_pos++;\r\n }\r\n indices[indices_pos++] = map.get(str);\r\n }\r\n\r\n /**\r\n * Recursive function to continually divide a triangle similar to the Sierpinski's triangle\r\n * recursive function.\r\n */\r\n function divide_triangle(a, b, c, n) {\r\n if (n === 0) {\r\n // Base case: add the triangle\r\n add_coord(b);\r\n add_coord(a);\r\n add_coord(c);\r\n } else {\r\n // Get the midpoints\r\n let ab = vec3.lerp(vec3.create(), a, b, 0.5);\r\n let ac = vec3.lerp(vec3.create(), a, c, 0.5);\r\n let bc = vec3.lerp(vec3.create(), b, c, 0.5);\r\n\r\n // Recursively divide\r\n divide_triangle(a, ab, ac, n-1);\r\n divide_triangle(ab, b, bc, n-1);\r\n divide_triangle(ac, bc, c, n-1);\r\n divide_triangle(ab, bc, ac, n-1);\r\n }\r\n }\r\n\r\n // Initial tetrahedron to be divdied, 4 equidistant points at approximately:\r\n // <0,0,-1>, <0,2*√2/3,1/3>, <-√6/3, -√2/3, 1/3>, and <√6/3, -√2/3, 1/3>\r\n\tlet a = vec3.fromValues(0.0, 0.0, -1.0);\r\n\tlet b = vec3.fromValues(0.0, 0.94280904158, 0.33333333333);\r\n\tlet c = vec3.fromValues(-0.81649658093, -0.4714045207, 0.33333333333);\r\n\tlet d = vec3.fromValues( 0.81649658093, -0.4714045207, 0.33333333333);\r\n \r\n // Subdivide each face of the tetrahedron\r\n\tdivide_triangle(a, b, c, num_subdivisions);\r\n\tdivide_triangle(d, c, b, num_subdivisions);\r\n\tdivide_triangle(a, d, b, num_subdivisions);\r\n divide_triangle(a, c, d, num_subdivisions);\r\n\r\n // Normalize each vertex so that it is moved to the surface of the unit sphere\r\n\tfor (let i = 0; i < coords.length; i += 3) {\r\n let coord = coords.subarray(i, i+3);\r\n vec3.normalize(coord, coord);\r\n }\r\n\r\n return [coords, indices];\r\n}", "static sphere(subdivisions = 3) {\n const golden = (1 + Math.sqrt(5)) / 2, u = new V3(1, golden, 0).unit(), s = u.x, t = u.y;\n // base vertices of isocahedron\n const vertices = [\n new V3(-s, t, 0),\n new V3(s, t, 0),\n new V3(-s, -t, 0),\n new V3(s, -t, 0),\n new V3(0, -s, t),\n new V3(0, s, t),\n new V3(0, -s, -t),\n new V3(0, s, -t),\n new V3(t, 0, -s),\n new V3(t, 0, s),\n new V3(-t, 0, -s),\n new V3(-t, 0, s),\n ];\n // base triangles of isocahedron\n // prettier-ignore\n const triangles = [\n // 5 faces around point 0\n 0, 11, 5,\n 0, 5, 1,\n 0, 1, 7,\n 0, 7, 10,\n 0, 10, 11,\n // 5 adjacent faces\n 1, 5, 9,\n 5, 11, 4,\n 11, 10, 2,\n 10, 7, 6,\n 7, 1, 8,\n // 5 faces around point 3\n 3, 9, 4,\n 3, 4, 2,\n 3, 2, 6,\n 3, 6, 8,\n 3, 8, 9,\n // 5 adjacent faces\n 4, 9, 5,\n 2, 4, 11,\n 6, 2, 10,\n 8, 6, 7,\n 9, 8, 1,\n ];\n /**\n * Tesselates triangle a b c\n * a b c must already be in vertices with the indexes ia ib ic\n * res is the number of subdivisions to do. 0 just results in triangle and line indexes being added to the\n * respective buffers.\n */\n function tesselateRecursively(a, b, c, res, vertices, triangles, ia, ib, ic, lines) {\n if (0 == res) {\n triangles.push(ia, ib, ic);\n if (ia < ib)\n lines.push(ia, ib);\n if (ib < ic)\n lines.push(ib, ic);\n if (ic < ia)\n lines.push(ic, ia);\n }\n else {\n // subdivide the triangle abc into 4 by adding a vertex (with the correct distance from the origin)\n // between each segment ab, bc and cd, then calling the function recursively\n const abMid1 = a.plus(b).toLength(1), bcMid1 = b.plus(c).toLength(1), caMid1 = c.plus(a).toLength(1);\n // indexes of new vertices:\n const iabm = vertices.length, ibcm = iabm + 1, icam = iabm + 2;\n vertices.push(abMid1, bcMid1, caMid1);\n tesselateRecursively(abMid1, bcMid1, caMid1, res - 1, vertices, triangles, iabm, ibcm, icam, lines);\n tesselateRecursively(a, abMid1, caMid1, res - 1, vertices, triangles, ia, iabm, icam, lines);\n tesselateRecursively(b, bcMid1, abMid1, res - 1, vertices, triangles, ib, ibcm, iabm, lines);\n tesselateRecursively(c, caMid1, bcMid1, res - 1, vertices, triangles, ic, icam, ibcm, lines);\n }\n }\n const mesh = new Mesh$$1()\n .addVertexBuffer('normals', 'ts_Normal')\n .addIndexBuffer('TRIANGLES')\n .addIndexBuffer('LINES');\n mesh.vertices.push(...vertices);\n subdivisions = undefined == subdivisions ? 4 : subdivisions;\n for (let i = 0; i < 20; i++) {\n const [ia, ic, ib] = triangles.slice(i * 3, i * 3 + 3);\n tesselateRecursively(vertices[ia], vertices[ic], vertices[ib], subdivisions, mesh.vertices, mesh.TRIANGLES, ia, ic, ib, mesh.LINES);\n }\n mesh.normals = mesh.vertices;\n mesh.compile();\n return mesh;\n }", "constructor( max_subdivisions ) // unit sphere) and group them into triangles by following the predictable pattern of the recursion.\r\n { super( \"positions\", \"normals\", \"texture_coords\" ); // Start from the following equilateral tetrahedron:\r\n this.positions.push( ...Vec.cast( [ 0, 0, -1 ], [ 0, .9428, .3333 ], [ -.8165, -.4714, .3333 ], [ .8165, -.4714, .3333 ] ) );\r\n \r\n this.subdivideTriangle( 0, 1, 2, max_subdivisions); // Begin recursion.\r\n this.subdivideTriangle( 3, 2, 1, max_subdivisions);\r\n this.subdivideTriangle( 1, 0, 3, max_subdivisions);\r\n this.subdivideTriangle( 0, 2, 3, max_subdivisions); \r\n \r\n for( let p of this.positions )\r\n { this.normals.push( p.copy() ); // Each point has a normal vector that simply goes to the point from the origin.\r\n\r\n // Textures are tricky. A Subdivision sphere has no straight seams to which image \r\n // edges in UV space can be mapped. The only way to avoid artifacts is to smoothly \r\n this.texture_coords.push( // wrap & unwrap the image in reverse - displaying the texture twice on the sphere.\r\n Vec.of( Math.asin( p[0]/Math.PI ) + .5, Math.asin( p[1]/Math.PI ) + .5 ) ) }\r\n }", "function drawSphere(numberToSubdivide, useFlatShading, isSun) {\n divideTriangle(va, vb, vc, numberToSubdivide);\n divideTriangle(vd, vc, vb, numberToSubdivide);\n divideTriangle(va, vd, vb, numberToSubdivide);\n divideTriangle(va, vc, vd, numberToSubdivide);\n \n function triangle(a, b, c) {\n pointsArray.push(a, b, c);\n \n //push normal vectors \n if(useFlatShading){\n var t1 = subtract(c,b);\n var t2 = subtract(c,a);\n var normal = vec4(normalize(cross(t1,t2)));\n if(isSun){\n normal = subtract(vec4(0,0,0,0), normal);\n }\n normalsArray.push(normal, normal, normal);\n }\n else{\n normalsArray.push(a, b, c);\n } \n\n index += 3;\n }\n\n function divideTriangle(a, b, c, count) {\n if ( count <= 0 ) { \n triangle(a, b, c);\n }\n else{ \n var ab = mix( a, b, 0.5);\n var ac = mix( a, c, 0.5);\n var bc = mix( b, c, 0.5);\n \n ab = normalize(ab, true);\n ac = normalize(ac, true);\n bc = normalize(bc, true);\n \n divideTriangle( a, ab, ac, count - 1 );\n divideTriangle( ab, b, bc, count - 1 );\n divideTriangle( bc, c, ac, count - 1 );\n divideTriangle( ab, bc, ac, count - 1 );\n }\n }\n\n}", "makeSphere(radius, stackCount, sectorCount) {\r\n\t\tconst thetaStep = 2 * Math.PI / sectorCount;\r\n\t\tconst phiStep = Math.PI / stackCount;\r\n\t\tlet vertices = [];\r\n\t\tlet normals = [];\r\n\t\tlet texCoords = [];\r\n\t\tfor(let i = 0; i <= stackCount; i++) {\r\n\t\t\tconst stackAngle = Math.PI / 2 - i * phiStep;\r\n\t\t\tconst rCosPhi = radius * Math.cos(stackAngle);\r\n\t\t\tconst z = radius * Math.sin(stackAngle);\r\n\t\t\t\r\n\t\t\tfor(let j = 0; j <= sectorCount; j++) {\r\n\t\t\t\tconst sectorAngle = j * thetaStep;\r\n\t\t\t\tconst x = rCosPhi * Math.cos(sectorAngle);\r\n\t\t\t\tconst y = rCosPhi * Math.sin(sectorAngle);\r\n\t\t\t\tvertices = vertices.concat([x, y, z]);\r\n\t\t\t\t\r\n\t\t\t\tnormals = normals.concat(this.normalize([x, y, z]));\r\n\t\t\t\t\r\n\t\t\t\tconst u = j / sectorCount;\r\n\t\t\t\tconst v = i / stackCount;\r\n\t\t\t\ttexCoords.push(u, v);\r\n\t\t\t}\r\n\t\t}\r\n\t\tthis.vertices = vertices;\r\n\t\tthis.normals = normals;\r\n\t\tthis.texCoords = texCoords;\r\n\t\tthis.indices = this.makeSphereIndices(stackCount, sectorCount);\r\n\t}", "function sphere(numSubdivisions) {\r\n\r\n var subdivisions = 3;\r\n if(numSubdivisions) subdivisions = numSubdivisions;\r\n\r\n\r\n var data = {};\r\n\r\n\r\n//var radius = 0.5;\r\n\r\n var sphereVertexCoordinates = [];\r\n var sphereVertexCoordinatesNormals = [];\r\n var sphereVertexColors = [];\r\n var sphereTextureCoordinates = [];\r\n var sphereNormals = [];\r\n var blue2 = [];\r\n var orange = [];\r\n var green = [];\r\n var silver = [];\r\n\r\n var va = vec4(0.0, 0.0, -1.0,1);\r\n var vb = vec4(0.0, 0.942809, 0.333333, 1);\r\n var vc = vec4(-0.816497, -0.471405, 0.333333, 1);\r\n var vd = vec4(0.816497, -0.471405, 0.333333,1);\r\n\r\n function triangle(a, b, c) {\r\n\r\n sphereVertexCoordinates.push([a[0],a[1], a[2], 1]);\r\n sphereVertexCoordinates.push([b[0],b[1], b[2], 1]);\r\n sphereVertexCoordinates.push([c[0],c[1], c[2], 1]);\r\n\r\n // normals are vectors\r\n\r\n sphereNormals.push([a[0],a[1], a[2]]);\r\n sphereNormals.push([b[0],b[1], b[2]]);\r\n sphereNormals.push([c[0],c[1], c[2]]);\r\n\r\n sphereVertexColors.push([(1+a[0])/2.0, (1+a[1])/2.0, (1+a[2])/2.0, 1.0]);\r\n sphereVertexColors.push([(1+b[0])/2.0, (1+b[1])/2.0, (1+b[2])/2.0, 1.0]);\r\n sphereVertexColors.push([(1+c[0])/2.0, (1+c[1])/2.0, (1+c[2])/2.0, 1.0]);\r\n\r\n blue2.push([0.075, 0.306, 0.306, 1.0]);\r\n blue2.push([0.075, 0.306, 0.306, 1.0]);\r\n blue2.push([0.075, 0.306, 0.306, 1.0]);\r\n\r\n orange.push([0.502, 0.208, 0.0, 1.0]);\r\n orange.push([0.502, 0.208, 0.0, 1.0]);\r\n orange.push([0.502, 0.208, 0.0, 1.0]);\r\n\r\n green.push([0.0, 0.204, 0.082, 1.0]);\r\n green.push([0.0, 0.204, 0.082, 1.0]);\r\n green.push([0.0, 0.204, 0.082, 1.0]);\r\n\r\n silver.push([0.929, 0.929, 0.929, 1.0]);\r\n silver.push([0.929, 0.929, 0.929, 1.0]);\r\n silver.push([0.929, 0.929, 0.929, 1.0]);\r\n\r\n sphereTextureCoordinates.push([0.5*Math.acos(a[0])/Math.PI, 0.5*Math.asin(a[1]/Math.sqrt(1.0-a[0]*a[0]))/Math.PI]);\r\n sphereTextureCoordinates.push([0.5*Math.acos(b[0])/Math.PI, 0.5*Math.asin(b[1]/Math.sqrt(1.0-b[0]*b[0]))/Math.PI]);\r\n sphereTextureCoordinates.push([0.5*Math.acos(c[0])/Math.PI, 0.5*Math.asin(c[1]/Math.sqrt(1.0-c[0]*c[0]))/Math.PI]);\r\n\r\n //sphereTextureCoordinates.push([0.5+Math.asin(a[0])/Math.PI, 0.5+Math.asin(a[1])/Math.PI]);\r\n //sphereTextureCoordinates.push([0.5+Math.asin(b[0])/Math.PI, 0.5+Math.asin(b[1])/Math.PI]);\r\n //sphereTextureCoordinates.push([0.5+Math.asin(c[0])/Math.PI, 0.5+Math.asin(c[1])/Math.PI]);\r\n\r\n }\r\n\r\n\r\n\r\n function divideTriangle(a, b, c, count) {\r\n if ( count > 0 ) {\r\n\r\n var ab = mix( a, b, 0.5);\r\n var ac = mix( a, c, 0.5);\r\n var bc = mix( b, c, 0.5);\r\n\r\n ab = normalize(ab, true);\r\n ac = normalize(ac, true);\r\n bc = normalize(bc, true);\r\n\r\n divideTriangle( a, ab, ac, count - 1 );\r\n divideTriangle( ab, b, bc, count - 1 );\r\n divideTriangle( bc, c, ac, count - 1 );\r\n divideTriangle( ab, bc, ac, count - 1 );\r\n }\r\n else {\r\n triangle( a, b, c );\r\n }\r\n }\r\n\r\n\r\n function tetrahedron(a, b, c, d, n) {\r\n divideTriangle(a, b, c, n);\r\n divideTriangle(d, c, b, n);\r\n divideTriangle(a, d, b, n);\r\n divideTriangle(a, c, d, n);\r\n }\r\n\r\n tetrahedron(va, vb, vc, vd, subdivisions);\r\n\r\n\r\n function translate(x, y, z){\r\n for(var i=0; i<sphereVertexCoordinates.length; i++) {\r\n sphereVertexCoordinates[i][0] += x;\r\n sphereVertexCoordinates[i][1] += y;\r\n sphereVertexCoordinates[i][2] += z;\r\n };\r\n }\r\n\r\n function scale(sx, sy, sz){\r\n for(var i=0; i<sphereVertexCoordinates.length; i++) {\r\n sphereVertexCoordinates[i][0] *= sx;\r\n sphereVertexCoordinates[i][1] *= sy;\r\n sphereVertexCoordinates[i][2] *= sz;\r\n sphereNormals[i][0] /= sx;\r\n sphereNormals[i][1] /= sy;\r\n sphereNormals[i][2] /= sz;\r\n };\r\n }\r\n\r\n function radians( degrees ) {\r\n return degrees * Math.PI / 180.0;\r\n }\r\n\r\n function rotate( angle, axis) {\r\n\r\n var d = Math.sqrt(axis[0]*axis[0] + axis[1]*axis[1] + axis[2]*axis[2]);\r\n\r\n var x = axis[0]/d;\r\n var y = axis[1]/d;\r\n var z = axis[2]/d;\r\n\r\n var c = Math.cos( radians(angle) );\r\n var omc = 1.0 - c;\r\n var s = Math.sin( radians(angle) );\r\n\r\n var mat = [\r\n [ x*x*omc + c, x*y*omc - z*s, x*z*omc + y*s ],\r\n [ x*y*omc + z*s, y*y*omc + c, y*z*omc - x*s ],\r\n [ x*z*omc - y*s, y*z*omc + x*s, z*z*omc + c ]\r\n ];\r\n\r\n for(var i=0; i<sphereVertexCoordinates.length; i++) {\r\n var u = [0, 0, 0];\r\n var v = [0, 0, 0];\r\n for( var j =0; j<3; j++)\r\n for( var k =0 ; k<3; k++) {\r\n u[j] += mat[j][k]*sphereVertexCoordinates[i][k];\r\n v[j] += mat[j][k]*sphereNormals[i][k];\r\n };\r\n for( var j =0; j<3; j++) {\r\n sphereVertexCoordinates[i][j] = u[j];\r\n sphereNormals[i][j] = v[j];\r\n };\r\n };\r\n }\r\n//for(var i =0; i<sphereVertexCoordinates.length; i++) console.log(sphereTextureCoordinates[i]);\r\n\r\n data.TriangleVertices = sphereVertexCoordinates;\r\n data.TriangleNormals = sphereNormals;\r\n data.TriangleVertexColors = sphereVertexColors;\r\n data.TextureCoordinates = sphereTextureCoordinates;\r\n data.colorBlue2 = blue2;\r\n data.colorOrange = orange;\r\n data.colorGreen = green;\r\n data.colorSilver = silver;\r\n data.rotate = rotate;\r\n data.translate = translate;\r\n data.scale = scale;\r\n return data;\r\n\r\n}", "function MakeSphere(r, sl, buff)\n{\n\tvar lRad;\t// Radius of the lower layer\n\tvar uRad;\t// Radius of the upper layer\n\t\n\t//Constructing the bottom Triangle Fan\n\tfor(i = 0; i < sl; i++)\n\t{\n\t\tlRad = Math.sqrt(Math.pow(r, 2) - Math.pow(r * (Math.cos(DegToRad(180 / sl * 0))), 2));\n\t\tuRad = Math.sqrt(Math.pow(r, 2) - Math.pow(r * (Math.cos(DegToRad(180 / sl * 1))), 2));\n\t\t\n\n\t\tbuff.push(lRad * Math.sin(DegToRad(360 / sl) * i));\n\t\tbuff.push(-r * Math.cos(DegToRad(180 / sl) * 0));\n\t\tbuff.push(lRad * Math.cos(DegToRad(360 / sl) * i));\n\t\t\n\t\tbuff.push(uRad * Math.sin(DegToRad(360 / sl) * i));\n\t\tbuff.push(-r * Math.cos(DegToRad(180 / sl) * 1));\n\t\tbuff.push(uRad * Math.cos(DegToRad(360 / sl) * i));\n\t\t\n\t\tbuff.push(uRad * Math.sin(DegToRad(360 / sl) * (i + 1)));\n\t\tbuff.push(-r * Math.cos(DegToRad(180 / sl) * 1));\n\t\tbuff.push(uRad * Math.cos(DegToRad(360 / sl) * (i + 1)));\n\t}\n\t\n\t//Constructing the body\n\tfor(i = 1; i < sl-1; i++)\n\t{\n\t\tlRad = Math.sqrt(Math.pow(r, 2) - Math.pow(r * (Math.cos(DegToRad(180 / sl * i))), 2));\n\t\tuRad = Math.sqrt(Math.pow(r, 2) - Math.pow(r * (Math.cos(DegToRad(180 / sl * (i + 1)))), 2));\n\t\t\n\t\tfor(j = 0; j < sl+1; j++)\n\t\t{\t\t\n\t\t\tbuff.push(lRad * Math.sin(DegToRad(360 / sl * j)));\n\t\t\tbuff.push(-r * Math.cos(DegToRad(180 / sl * i)));\n\t\t\tbuff.push(lRad * Math.cos(DegToRad(360 / sl * j)));\n\t\t\n\t\t\tbuff.push(uRad * Math.sin(DegToRad(360 / sl * (j + 1))));\n\t\t\tbuff.push(-r * Math.cos(DegToRad(180 / sl * (i + 1))));\n\t\t\tbuff.push(uRad * Math.cos(DegToRad(360 / sl * (j + 1))));\n\t\t\n\t\t\tbuff.push(lRad * Math.sin(DegToRad(360 / sl * (j + 1))));\n\t\t\tbuff.push(-r * Math.cos(DegToRad(180 / sl * i)));\n\t\t\tbuff.push(lRad * Math.cos(DegToRad(360 / sl * (j + 1))));\n\t\t\t\n\t\t\tbuff.push(uRad * Math.sin(DegToRad(360 / sl * j)));\n\t\t\tbuff.push(-r * Math.cos(DegToRad(180 / sl * (i + 1))));\n\t\t\tbuff.push(uRad * Math.cos(DegToRad(360 / sl * j)));\n\t\t\n\t\t\tbuff.push(uRad * Math.sin(DegToRad(360 / sl * (j + 1))));\n\t\t\tbuff.push(-r * Math.cos(DegToRad(180 / sl * (i + 1))));\n\t\t\tbuff.push(uRad * Math.cos(DegToRad(360 / sl * (j + 1))));\n\t\t\n\t\t\tbuff.push(lRad * Math.sin(DegToRad(360 / sl * j)));\n\t\t\tbuff.push(-r * Math.cos(DegToRad(180 / sl * i)));\n\t\t\tbuff.push(lRad * Math.cos(DegToRad(360 / sl * j)));\n\t\t\n\t\t}\n\t}\n\t\n\t//Constructing the Top Triangle Fan\n\tfor(i = 0; i < sl; i++)\n\t{\n\t\tlRad = Math.sqrt( Math.pow(r, 2) - Math.pow(r * (Math.cos(DegToRad(180 / sl * 0))), 2));\n\t\tuRad = Math.sqrt( Math.pow(r, 2) - Math.pow(r * (Math.cos(DegToRad(180 / sl * 1))), 2));\n\n\t\t\n\t\tbuff.push(lRad * Math.sin(DegToRad(360 / sl) * i));\n\t\tbuff.push(-r * Math.cos(DegToRad(180 / sl * sl)));\n\t\tbuff.push(lRad * Math.cos(DegToRad(360 / sl) * i));\n\t\t\n\t\tbuff.push(uRad * Math.sin(DegToRad(360 / sl) * (i+1)));\n\t\tbuff.push(-r * Math.cos(DegToRad(180 / sl * (sl- 1 )) * 1));\n\t\tbuff.push(uRad * Math.cos(DegToRad(360 / sl) * (i + 1)));\n\t\t\n\t\tbuff.push(uRad * Math.sin(DegToRad(360 / sl) * i));\n\t\tbuff.push(-r * Math.cos(DegToRad(180 / sl * (sl - 1)) * 1));\n\t\tbuff.push(uRad * Math.cos(DegToRad(360 / sl) * i));\n\t}\n}", "function makeSphere(numLongSteps) {\n \n try {\n if (numLongSteps % 2 != 0)\n throw \"in makeSphere: uneven number of longitude steps!\";\n else if (numLongSteps < 4)\n throw \"in makeSphere: number of longitude steps too small!\";\n else { // good number longitude steps\n \n// // make vertices and normals\n// \t\n// var sphereVertices = [0,-1,0]; // vertices to return, init to south pole\n// var sphereTextureCoords = [0.5,0];\n// var angleIncr = (Math.PI+Math.PI) / numLongSteps; // angular increment \n// var latLimitAngle = angleIncr * (Math.floor(numLongSteps/4)-1); // start/end lat angle\n// var latRadius, latY; // radius and Y at current latitude\n// for (var latAngle=-latLimitAngle; latAngle<=latLimitAngle; latAngle+=angleIncr) {\n// latRadius = Math.cos(latAngle); // radius of current latitude\n// latY = Math.sin(latAngle); // height at current latitude\n// for (var longAngle=0; longAngle<2*Math.PI; longAngle+=angleIncr){ // for each long\n// sphereVertices.push(latRadius*Math.sin(longAngle),latY,latRadius*Math.cos(longAngle));\n// sphereTextureCoords.push((latRadius*Math.sin(longAngle)+1)/2,(latY+1)/2);\n// }\n// } // end for each latitude\n// sphereVertices.push(0,1,0); // add north pole\n// sphereTextureCoords.push(0.5,1);\n// var sphereNormals = sphereVertices.slice(); // for this sphere, vertices = normals; return these\n// \n// // make triangles, from south pole to middle latitudes to north pole\n// var sphereTriangles = []; // triangles to return\n// for (var whichLong=1; whichLong<numLongSteps; whichLong++) // south pole\n// sphereTriangles.push(0,whichLong,whichLong+1);\n// sphereTriangles.push(0,numLongSteps,1); // longitude wrap tri\n// var llVertex; // lower left vertex in the current quad\n// for (var whichLat=0; whichLat<(numLongSteps/2 - 2); whichLat++) { // middle lats\n// for (var whichLong=0; whichLong<numLongSteps-1; whichLong++) {\n// llVertex = whichLat*numLongSteps + whichLong + 1;\n// sphereTriangles.push(llVertex,llVertex+numLongSteps,llVertex+numLongSteps+1);\n// sphereTriangles.push(llVertex,llVertex+numLongSteps+1,llVertex+1);\n// } // end for each longitude\n// sphereTriangles.push(llVertex+1,llVertex+numLongSteps+1,llVertex+2);\n// sphereTriangles.push(llVertex+1,llVertex+2,llVertex-numLongSteps+2);\n// } // end for each latitude\n// for (var whichLong=llVertex+2; whichLong<llVertex+numLongSteps+1; whichLong++) // north pole\n// sphereTriangles.push(whichLong,sphereVertices.length/3-1,whichLong+1);\n// sphereTriangles.push(sphereVertices.length/3-2,sphereVertices.length/3-1,sphereVertices.length/3-numLongSteps-1); // longitude wrap\n \t\n \t/**Using the sphere from the lesson: http://learningwebgl.com/blog/?p=1253*/\n \tvar vertexPositionData = [];\n var normalData = [];\n var textureCoordData = [];\n for (var latNumber = 0; latNumber <= numLongSteps; latNumber++) {\n var theta = latNumber * Math.PI / numLongSteps;\n var sinTheta = Math.sin(theta);\n var cosTheta = Math.cos(theta);\n\n for (var longNumber = 0; longNumber <= numLongSteps; longNumber++) {\n var phi = longNumber * 2 * Math.PI / numLongSteps;\n var sinPhi = Math.sin(phi);\n var cosPhi = Math.cos(phi);\n\n var x = cosPhi * sinTheta;\n var y = cosTheta;\n var z = sinPhi * sinTheta;\n var u = 1 - (longNumber / numLongSteps);\n var v = 1 - (latNumber / numLongSteps);\n\n normalData.push(x);\n normalData.push(y);\n normalData.push(z);\n textureCoordData.push(u);\n textureCoordData.push(v);\n vertexPositionData.push(x);\n vertexPositionData.push(y);\n vertexPositionData.push(z);\n }\n }\n var indexData = [];\n for (var latNumber = 0; latNumber < numLongSteps; latNumber++) {\n for (var longNumber = 0; longNumber < numLongSteps; longNumber++) {\n var first = (latNumber * (numLongSteps + 1)) + longNumber;\n var second = first + numLongSteps + 1;\n indexData.push(first);\n indexData.push(second);\n indexData.push(first + 1);\n\n indexData.push(second);\n indexData.push(second + 1);\n indexData.push(first + 1);\n }\n }\n \t\n } // end if good number longitude steps\n// return({vertices:sphereVertices, normals:sphereNormals, triangles:sphereTriangles, texture:sphereTextureCoords});\n return({vertices:vertexPositionData, normals:normalData, triangles:indexData, texture:textureCoordData});\n } // end try\n \n catch(e) {\n console.log(e);\n } // end catch\n } // end make sphere", "constructor( max_subdivisions ) // detail is obtained. Project all new vertices to unit vectors (onto the unit sphere) and group them into triangles by \r\n { super(); // following the predictable pattern of the recursion.\r\n this.positions.push( ...Vec.cast( [ 0, 0, -1 ], [ 0, .9428, .3333 ], [ -.8165, -.4714, .3333 ], [ .8165, -.4714, .3333 ] ) ); // Start with this equilateral tetrahedron\r\n \r\n this.subdivideTriangle( 0, 1, 2, max_subdivisions); // Begin recursion.\r\n this.subdivideTriangle( 3, 2, 1, max_subdivisions);\r\n this.subdivideTriangle( 1, 0, 3, max_subdivisions);\r\n this.subdivideTriangle( 0, 2, 3, max_subdivisions); \r\n \r\n for( let p of this.positions )\r\n { this.normals .push( Vec.of( ...p ) ); // Each point has a normal vector that simply goes to the point from the origin. Copy array by value.\r\n this.texture_coords.push( Vec.of( .5 + Math.atan2( p[2], p[0] ) / 2 / Math.PI, .5 - 2 * Math.asin( p[1] ) / 2 / Math.PI ) ); }\r\n }", "function makeSphere(numLongSteps) {\n \n try {\n if (numLongSteps % 2 != 0)\n throw \"in makeSphere: uneven number of longitude steps!\";\n else if (numLongSteps < 4)\n throw \"in makeSphere: number of longitude steps too small!\";\n else { // good number longitude steps\n \n // make vertices, normals and uvs -- repeat longitude seam\n const INVPI = 1/Math.PI, TWOPI = Math.PI+Math.PI, INV2PI = 1/TWOPI, epsilon=0.001*Math.PI;\n var sphereVertices = [0,-1,0]; // vertices to return, init to south pole\n var sphereUvs = [0.5,0]; // uvs to return, bottom texture row collapsed to one texel\n var angleIncr = TWOPI / numLongSteps; // angular increment \n var latLimitAngle = angleIncr * (Math.floor(numLongSteps*0.25)-1); // start/end lat angle\n var latRadius, latY, latV; // radius, Y and texture V at current latitude\n for (var latAngle=-latLimitAngle; latAngle<=latLimitAngle+epsilon; latAngle+=angleIncr) {\n latRadius = Math.cos(latAngle); // radius of current latitude\n latY = Math.sin(latAngle); // height at current latitude\n latV = latAngle*INVPI + 0.5; // texture v = (latAngle + 0.5*PI) / PI\n for (var longAngle=0; longAngle<=TWOPI+epsilon; longAngle+=angleIncr) { // for each long\n sphereVertices.push(-latRadius*Math.sin(longAngle),latY,latRadius*Math.cos(longAngle));\n sphereUvs.push(longAngle*INV2PI,latV); // texture u = (longAngle/2PI)\n } // end for each longitude\n } // end for each latitude\n sphereVertices.push(0,1,0); // add north pole\n sphereUvs.push(0.5,1); // top texture row collapsed to one texel\n var sphereNormals = sphereVertices.slice(); // for this sphere, vertices = normals; return these\n\n // make triangles, first poles then middle latitudes\n var sphereTriangles = []; // triangles to return\n var numVertices = Math.floor(sphereVertices.length/3); // number of vertices in sphere\n for (var whichLong=1; whichLong<=numLongSteps; whichLong++) { // poles\n sphereTriangles.push(0,whichLong,whichLong+1);\n sphereTriangles.push(numVertices-1,numVertices-whichLong-1,numVertices-whichLong-2);\n } // end for each long\n var llVertex; // lower left vertex in the current quad\n for (var whichLat=0; whichLat<(numLongSteps/2 - 2); whichLat++) { // middle lats\n for (var whichLong=0; whichLong<numLongSteps; whichLong++) {\n llVertex = whichLat*(numLongSteps+1) + whichLong + 1;\n sphereTriangles.push(llVertex,llVertex+numLongSteps+1,llVertex+numLongSteps+2);\n sphereTriangles.push(llVertex,llVertex+numLongSteps+2,llVertex+1);\n } // end for each longitude\n } // end for each latitude\n } // end if good number longitude steps\n return({vertices:sphereVertices, normals:sphereNormals, uvs:sphereUvs, triangles:sphereTriangles});\n } // end try\n \n catch(e) {\n console.log(e);\n } // end catch\n } // end make sphere" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Convert world coordinates into local coordinates in respect to your character.
function WorldToLocal(x, y, scale) { var relativeX = (character.real_x - x)*scale * -1; var relativeY = (character.real_y - y)*scale * -1; return {x: relativeX, y: relativeY}; }
[ "worldToLocal(world) {\r\n let m = this.matrix;\r\n let a = m.a, b = m.c, c = m.b, d = m.d;\r\n let invDet = 1 / (a * d - b * c);\r\n let x = world.x - m.tx, y = world.y - m.ty;\r\n world.x = (x * d * invDet - y * b * invDet);\r\n world.y = (y * a * invDet - x * c * invDet);\r\n return world;\r\n }", "worldToScreen(x, y) {\n if (y === undefined) {\n y = x.y;\n x = x.x;\n }\n\n let M = this.ctx.getTransform();\n\n let ret = {\n x: x * M.a + y * M.c + M.e,\n y: x * M.b + y * M.d + M.f,\n };\n\n return ret;\n }", "screenToWorld(x, y) {\n if (y === undefined) {\n y = x.y;\n x = x.x;\n }\n\n let M = this.ctx.getTransform().invertSelf();\n\n let ret = {\n x: x * M.a + y * M.c + M.e,\n y: x * M.b + y * M.d + M.f,\n };\n\n return ret;\n }", "function normalize(coord, worldBounds) {\n return [\n (coord[0] - worldBounds.left) / worldBounds.width,\n (coord[1] - worldBounds.bottom) / worldBounds.height,\n (coord[2] - worldBounds.left) / worldBounds.width,\n (coord[3] - worldBounds.bottom) / worldBounds.height\n ];\n}", "function worldTo2Dcoordinates(x, y){\n\tif(!currentMap)\n\t\treturn false;\n return {\n x: (Math.abs(currentMap.x) + x) / (currentMap.scale * 1024) * canvas.width,\n y: (Math.abs(currentMap.y) - y) / (currentMap.scale * 1024) * canvas.height\n };\n}", "get worldToLocalMatrix() {}", "convertToLocalCoords(x, y) {\n this.pt.x = x;\n this.pt.y = y;\n\n // The cursor point, translated into svg coordinates\n const local = this.pt.matrixTransform(this.svg.getScreenCTM().inverse());\n return {\n x: local.x,\n y: 1024 - local.y,\n };\n }", "function toWorldCoords(position) {\n var vector = new THREE.Vector3();\n if (position) {\n var vector = new THREE.Vector3(position.x, position.y, 1);\n vector.x = ( vector.x - widthHalf ) / widthHalf;\n vector.y = ( vector.y - heightHalf ) / -heightHalf;\n vector.unproject( camera );\n }\n return vector;\n}", "function worldToScreen ( worldPos ) {\n\n var windowHalfX = window.innerWidth / 2;\n var windowHalfY = window.innerHeight / 2;\n\n var screenPos = worldPos.clone();\n projector.projectVector( screenPos, camera );\n screenPos.x = ( screenPos.x + 1 ) * windowHalfX;\n screenPos.y = ( - screenPos.y + 1) * windowHalfY;\n return screenPos;\n}", "ComputeWorldCoordinate () {\n const obj = Mercator(this.gps.latitude, this.gps.longitude)\n\n const center = Mercator(this.center.latitude, this.center.longitude)\n this.world.x = (center.x - obj.x) * this.scale\n this.world.z = (center.y - obj.y) * this.scale\n this.world.y = this.gps.altitude\n\n // const { MercatorX, MercatorY } = await import('../wasm/main.wasm')\n // console.log(MercatorX(this.gps.latitude), MercatorY(this.gps.longitude))\n\n return this\n }", "get localToWorldMatrix() {}", "function pixelCoordsToWorldCoords(x, y) {\n x -= panX;\n y -= panY;\n x /= SCALE;\n y /= SCALE;\n return createVector(x, y);\n}", "function coord_to_position(coordinates) {\n return vec3(coordinates[0] * BLOCK_SIZE, coordinates[1] * BLOCK_SIZE, coordinates[2] * BLOCK_SIZE);\n}", "static geoToWorld ( latlng ) {\n\n\t\tconst latitudeRadians = latlng[ 0 ] * Math.PI / 180;\n\n\t\tconst x = ( latlng[ 1 ] + 180 ) / 360 * 256;\n\t\tconst y = ( ( 1 - Math.log( Math.tan( latitudeRadians ) + 1 / Math.cos( latitudeRadians ) ) / Math.PI ) / 2 ) * 256;\n\n\t\treturn [ x, y ];\n\n\t}", "_getWorldTranslatedBy(world, x, y) {\n const newWorld = JSON.parse(JSON.stringify(world));\n let objects = newWorld.actualShips.concat(newWorld.apparentShips);\n objects = objects.concat(newWorld.staticObjects);\n for (const object of objects) {\n const position = object.position;\n position.x += x;\n position.y += y;\n object.position = Positions.normalized(position);\n }\n return newWorld;\n }", "function setUpWorldCoordinates() {\n const projectionMat = mat4.create();\n mat4.fromScaling(projectionMat, [2.0/gl.drawingBufferWidth, 2.0/gl.drawingBufferHeight]);\n gl.uniformMatrix4fv(ctx.uProjectionMatId, false, projectionMat);\n}", "function convertToLocalCoordinates(buildings, mapCenter)\n{\n var circumference = Helpers.getEarthCircumference();\n var lngScale = Math.cos( mapCenter.lat / 180 * Math.PI);\n \n for (var i in buildings)\n {\n var bld = buildings[i];\n \n for (var j = 0; j < bld.nodes.length; j++)\n {\n var dLat = bld.nodes[j][\"lat\"] - mapCenter.lat;\n var dLng = bld.nodes[j][\"lon\"] - mapCenter.lng;\n\n bld.nodes[j].dx = dLng / 360 * circumference * lngScale;\n bld.nodes[j].dy = -dLat / 360 * circumference;\n }\n }\n return buildings;\n\n}", "function screenToWorld(x, y) {\n return {x: x + -globals.background.x, y: y + -globals.background.y};\n}", "toWorld(camera)\n\t{\n\t\tlet pos = new NodeGraph.Position(this.x, this.y);\n\n\t\tif (!this.worldSpace)\n\t\t{\n\t\t\tpos.x = (pos.x + camera.xSmooth) / camera.zoomSmooth;\n\t\t\tpos.y = (pos.y + camera.ySmooth) / camera.zoomSmooth;\n\n\t\t}\n\n\t\treturn pos;\n\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
edge detection using Sobel operator in both x and y direction edge intensity is sqrt( |Gx|^2 + |Gy|^2 )
function edge( __src ) { var gx = grayscale( filter(__src, new Filter.hsobel()) ); var gy = grayscale( filter(__src, new Filter.vsobel()) ); // sqrt(gx^2 + gy^2) var h = gx.h, w = gx.w; var g = new RGBAImage(w, h); var data = g.data, data1 = gx.data, data2 = gy.data; for (var idx=0;idx<w*h*4;idx++) { data[idx] = clamp(Math.sqrt(data1[idx] * data1[idx] + data2[idx] * data2[idx]), 0.0, 255.0); } var dst = new RGBAImage(w, h); var ddata = dst.data, sdata = __src.data; for (var y= 0, idx = 0;y<h;y++) { for (var x=0;x<w;x++, idx+=4) { ddata[idx+0] = sdata[idx+0] * data[idx] / 255.0; ddata[idx+1] = sdata[idx+1] * data[idx] / 255.0; ddata[idx+2] = sdata[idx+2] * data[idx] / 255.0; ddata[idx+3] = 255; } } return dst; }
[ "edgeDetect(){\n if (this.y + this.radius + this.velocity.y > this.canvas.height) {\n this.velocity.y *= -1\n }\n else if(this.y - this.radius <= 0){\n this.velocity.y *= -1\n }\n\n if (this.x + this.radius + this.velocity.x > this.canvas.width) {\n this.velocity.x *= -1\n }\n else if (this.x - this.radius <= 0) {\n this.velocity.x *= -1\n }\n }", "function filterSobel(gsData){\n\tvar h = gsData.height;\n\tvar w = gsData.width;\n\tif (h < 3 || w < 3){\n\t\tconsole.log(\"Image to small: cannot run Sobel filter.\");\n\t\treturn {\n\t\t\theight: 0,\n\t\t\twidth: 0,\n\t\t\tdataX: null,\n\t\t\tdataY: null\n\t\t};\n\t}\n\tvar sobelX = new Int16Array((h - 2) * (w - 2));\n\tvar sobelY = new Int16Array((h - 2) * (w - 2));\n\tvar pos;\n\tvar sX;\n\tvar sY;\n\tfor (var y = 1; y < h - 1; y++){\n\t\tfor (var x = 1; x < w - 1; x++){\n\t\t\tpos = xyToPos(x - 1, y - 1, w - 2);\n\t\t\t\n\t\t\tsX = 0;\n\t\t\tsX += -1*gsData.data[xyToPos(x - 1, y - 1, w)];\n\t\t\tsX += -2*gsData.data[xyToPos(x - 1, y, w)];\n\t\t\tsX += -1*gsData.data[xyToPos(x - 1, y + 1, w)];\n\t\t\tsX += 1*gsData.data[xyToPos(x + 1, y - 1, w)];\n\t\t\tsX += 2*gsData.data[xyToPos(x + 1, y, w)];\t\t\n\t\t\tsX += 1*gsData.data[xyToPos(x + 1, y + 1, w)];\n\t\t\tsobelX[pos] = Math.floor(sX);\n\t\t\t\n\t\t\tsY = 0;\n\t\t\tsY += -1*gsData.data[xyToPos(x - 1, y - 1, w)];\n\t\t\tsY += -2*gsData.data[xyToPos(x, y - 1, w)];\n\t\t\tsY += -1*gsData.data[xyToPos(x + 1, y - 1, w)];\n\t\t\tsY += 1*gsData.data[xyToPos(x - 1, y + 1, w)];\n\t\t\tsY += 2*gsData.data[xyToPos(x, y + 1, w)];\n\t\t\tsY += 1*gsData.data[xyToPos(x + 1, y + 1, w)];\n\t\t\tsobelY[pos] = Math.floor(sY);\n\t\t}\n\t}\n\treturn {\n\t\theight: gsData.height - 2,\n\t\twidth: gsData.width - 2,\n\t\tdataX: sobelX,\n\t\tdataY: sobelY\n\t};\n}", "function energyFunction(imgdata) {\n // Effectively get the pixel, clamped into range, for the Sobel operator\n function getSobelPixel(imgdata, x, y) {\n if (x < 0) {\n x = 0;\n } else if (x >= imgdata.width) {\n x = imgdata.width - 1;\n }\n\n if (y < 0) {\n y = 0;\n } else if (y >= imgdata.height) {\n y = imgdata.height - 1;\n }\n var px = getPixel(imgdata, x, y);\n return (px.r + px.g + px.b) / 3;\n }\n\n function getSobelEnergy(imgdata, x, y) {\n var pixels = [];\n\n pixels.push(getSobelPixel(imgdata, x - 1, y - 1));\n pixels.push(getSobelPixel(imgdata, x, y - 1));\n pixels.push(getSobelPixel(imgdata, x + 1, y - 1));\n pixels.push(getSobelPixel(imgdata, x + 1, y));\n pixels.push(getSobelPixel(imgdata, x, y));\n pixels.push(getSobelPixel(imgdata, x + 1, y));\n pixels.push(getSobelPixel(imgdata, x - 1, y + 1));\n pixels.push(getSobelPixel(imgdata, x, y + 1));\n pixels.push(getSobelPixel(imgdata, x + 1, y + 1));\n\n var xSobel = pixels[0] + (pixels[1] + pixels[1]) + pixels[2] - pixels[6] - (pixels[7] + pixels[7]) - pixels[8];\n var ySobel = pixels[2] + (pixels[5] + pixels[5]) + pixels[8] - pixels[0] - (pixels[3] + pixels[3]) - pixels[6];\n\n var sobel = Math.sqrt((xSobel * xSobel) + (ySobel * ySobel));\n\n if (sobel > 255)\n {\n sobel = 255;\n }\n\n return sobel;\n }\n\n var nrgimg = document.createElement('canvas').getContext('2d').createImageData(imgdata.width, imgdata.height);\n\n for (var ix = 0; ix < imgdata.width; ix++) {\n for (var iy = 0; iy < imgdata.height; iy++) {\n // R, G, B channels\n for (var k = 0; k < 3; k++) {\n nrgimg.data[pixelIndex(nrgimg, ix, iy) + k] = getSobelEnergy(imgdata, ix, iy);\n }\n nrgimg.data[pixelIndex(nrgimg, ix, iy) + 3] = 255; // alpha channel\n }\n }\n\n return nrgimg;\n}", "function cannyEdgeDetector(img) {\n\t// First, blur image with 5x5 Gaussian kernel to remove noise\n\tconst blurKernel = tf.tensor([\n\t\t[2, 4, 5, 4, 2],\n\t\t[4, 9, 12, 9, 4],\n\t\t[5, 12, 15, 12, 5],\n\t\t[2, 4, 5, 4, 2],\n\t\t[4, 9, 12, 9, 4]\n\t]).div(159);\n\tlet blurred = convolve(img, blurKernel)\n\n\t// Calculate gradient along each direction\n\tconst xKernel = tf.tensor([\n\t\t[-1, 0, 1],\n\t\t[-2, 0, 2],\n\t\t[-1, 0, 1]\n\t]);\n\tconst yKernel = tf.tensor([\n\t\t[-1, -2, -1],\n\t\t[0, 0, 0],\n\t\t[1, 2, 1]\n\t]);\n\tlet xGrad = convolve(blurred, xKernel)\n\tlet yGrad = convolve(blurred, yKernel)\n\n\t// Compute the magnitude and direction of the gradient\n\tlet grad = tf.add(xGrad.square(), yGrad.square()).arraySync()\n\tlet dir = tf.atan2(yGrad, xGrad)\n\tlet rDir = dir.mul(4/Math.PI).round().mul(Math.PI/4).arraySync()\n\tdir = dir.arraySync()\n\n\t// For each pixel, determine if it is an edge.\n\t// A pixel is an edge if its gradient is above the threshold, and both\n\t// neighboring pixels along the gradient direction (perpendicular to edge)\n\t// have a smaller gradient direction\n\tconst h = xGrad.shape[0], w = xGrad.shape[1];\n\tlet mask = tf.buffer([h, w], 'bool')\t// To keep track of which edges have been added\n\tlet edges = [];\n\tconst threshold = 0.15;\n\tfor(let c = 0; c < 3; c++) {\n\t\tfor(let y = 0; y < h; y++) {\n\t\t for(let x = 0; x < w; x++) {\n\t\t if(grad[y][x][c] < threshold || mask.get(y, x))\n\t\t continue;\n\n\t\t angle = rDir[y][x][c];\n\t\t const dx = Math.round(Math.cos(angle));\n\t\t const dy = Math.round(Math.sin(angle));\n\n\t\t if(0 <= y+dy && y+dy < h && 0 <= y-dy && y-dy < h)\n\t\t if(0 <= x+dx && x+dx < w && 0 <= x-dx && x-dx < w)\n\t\t if(grad[y+dy][x+dx][c] < grad[y][x][c] && grad[y-dy][x-dx][c] < grad[y][x][c]) {\n\t\t // We lose 3 pixels on each edge when performing the convolutions, so we add those back in here\n\t\t\t\t\t\t\tedges.push([x+3, y+3, dir[y][x][c]]);\n\t\t\t\t\t\t\tmask.set(true, y, x);\n\t\t\t\t\t\t}\n\t\t }\n\t\t}\n\t}\n\n\treturn edges;\n}", "function highlightEdges(img){\r\n let b = 0;\r\n let output = img.copy();\r\n for(let i = 0; i < img.width ; ++i){\r\n for(let j = 0 ; j < img.height; j = j+1){\r\n let a = output.getPixel(i,j);\r\n if(i+1 === img.width){\r\n b = output.getPixel(0,j);\r\n }\r\n else{\r\n b = output.getPixel(i+1, j) ;\r\n } \r\n let m1 = (a[0] +a[1] +a[2]) / 3 ;\r\n let m2 = (b[0] +b[1] +b[2]) / 3;\r\n let pass = Math.abs(m1-m2) ;\r\n output.setPixel(i,j,[pass, pass, pass]);\r\n }\r\n }\r\n return output;\r\n}", "function getSobelPixel(imgdata, x, y) {\n if (x < 0) {\n x = 0;\n } else if (x >= imgdata.width) {\n x = imgdata.width - 1;\n }\n\n if (y < 0) {\n y = 0;\n } else if (y >= imgdata.height) {\n y = imgdata.height - 1;\n }\n var px = getPixel(imgdata, x, y);\n return (px.r + px.g + px.b) / 3;\n }", "edges(){\n if(this.pos.x < 0 || this.pos.x > width){\n this.vel.x *= -1;\n }\n if(this.pos.y < 0 || this.pos.y > height){\n this.vel.y *= -1;\n }\n }", "edgeCheck() {\n var d = dist(this.circleX, this.circleY, this.posX, this.posY);\n if(d + this.rad2 > this.bounds || d - this.rad2 > this.bounds){\n this.deltaX *= -1;\n this.deltaY *= -1;\n }\n }", "function EdgeDetection(){\n}", "function mouseEdgeFind(m) {\n //Request the color of the pixel that the mouse is over and see if it matches an edge color\n var x = m[0] + (margin.left + width / 2);\n var y = m[1] + (margin.top + height / 2);\n var col = ctx_hidden.getImageData(x, y, 1, 1).data;\n var col_string = 'rgb(' + col[0] + ',' + col[1] + ',' + col[2] + ')';\n var found_edge = color_to_edge[col_string];\n return found_edge;\n } //function mouseEdgeFind", "edgeElasticity(edge) { return 32; }", "function getEdgeEstimate (points, width=20) {\n/* var theta1, theta2;\n if ((points[0][0] - points[1][0] == 0)) {\n theta1 = -90;\n } else {\n theta1 = Math.atan((points[1][1] - points[0][1]) /\n (points[1][0] - points[0][0]));\n }\n if ((points[2][0] - points[1][0] == 0)) {\n theta2 = -90;\n } else {\n theta2 = Math.PI + Math.atan((points[1][1] - points[2][1]) /\n (points[1][0] - points[2][0]));\n }\n var angle = (theta1 + theta2) / 2;\n var point1 = [points[1][0] + radius * Math.cos(angle),\n [points[1][1] + radius * Math.sin(angle)]\n ];\n var point2 = [points[1][0] - radius * Math.cos(angle),\n [points[1][1] - radius * Math.sin(angle)]\n ];\n return [point1, point2];*/\n var vector1, vector2;\n vector1 = [points[1][0] - points[0][0], points[1][1] - points[0][1]];\n vector2 = [points[2][0] - points[1][0], points[2][1] - points[1][1]];\n var avgVector = [(vector1[0] + vector2[0]) / 2,\n (vector1[1] + vector2[1]) / 2\n ];\n var point1, point2;\n var deltaVector = norm(MatrixVectorMult(avgVector, [[0, 1], [-1, 0]]));\n point1 = [points[1][0] + width * deltaVector[0],\n points[1][1] + width * deltaVector[1]\n ];\n point2 = [points[1][0] - width * deltaVector[0],\n points[1][1] - width * deltaVector[1]\n ];\n return [point1, point2];\n}", "hitsEdges() {\n return (\n this.coordinates.x - this.radius <= 0 ||\n this.coordinates.x + this.radius >= width ||\n this.coordinates.y - this.radius <= 0 ||\n this.coordinates.y + this.radius >= height\n );\n }", "function edge_detection(pixeldata, direction) {\n var direction_function = null;\n if (direction>0) {direction_function = function(i_val){return i_val<pixeldata.length;}}\n if (direction<0) {direction_function = function(i_val){return i_val>0 ;}}\n \n var edge_threshhold = 0.2;\n \n var run_length = 0; // Run is a term for a set of ajacent pixels with the same value\n var run_value = 0;\n \n var run_start = pixeldata.length/2;\n var run_max = 0;\n var run_max_start = 0;\n for (var i = run_start ; direction_function(i) ; i+=direction) {\n // If pixel is within threashhold\n var diff = Math.abs(pixeldata[i]-run_value);\n //console.log('diff',diff,'i',i,'val',run_value)\n if (diff < edge_threshhold) {\n run_length += 1; // increment the run length\n \n }\n // Else next pixel is outside of threshold\n else { // Next pixel is not in threshhold\n if (run_length >= run_max) { // Record the end of the run\n c.fillStyle = \"rgb(0,255,128)\";\n c.fillRect(run_start ,y_debug,1,5);\n run_max = run_length;\n run_max_start = run_start;\n //console.log('best',run_max_start,' ',run_max);\n }\n run_start = i; // record the start of the run\n run_value = pixeldata[i]; // record the next comparison value as this value // AllanC - humm ... maybe this isnt enough?\n run_length = 0; // reset the number of matchs so far\n }\n //console.log('i',i,'len',run_length);\n }\n //console.log('best_before',run_start,' ',run_length);\n if (run_length >= run_max) { // had to duplicte this at the end, because the last one should always be checked and recorded if it's the longest\n c.fillStyle = \"rgb(0,255,255)\";\n c.fillRect(run_start ,y_debug,1,5);\n \n run_max = run_length;\n run_max_start = run_start;\n //console.log('best_final',run_max_start,' ',run_max);\n }\n //console.log('yo', run_max_start);\n return run_max_start;\n }", "function isEdgeConnected(x,y,edge)\r\n{\r\n\tif (edge == \"left\" || edge == \"top\"){edge = 0;}\r\n\tif (edge == \"right\" || edge == \"bottom\"){edge = 1;}\r\n\treturn cgrid[x][y][edge];\r\n}", "checkIfPixelIsEdge(x, y, dataArray){\n \n const xCurr = x,\n yCurr = y,\n \n size = 1;\n \n \n const data = dataArray;\n \n let alphaCount = 0;\n \n for(let y = yCurr - size; y <= yCurr + size; y+=size)\n for(let x = xCurr - size; x <= xCurr + size; x+=size)\n { \n if((y !== yCurr || x !== xCurr))\n {\n if(!data[((y * this.width + x) * 4) + 3])\n alphaCount++;\n }\n }\n \n return alphaCount;\n \n }", "function processEdgeDetect(img, filename){\n let image = img.clone();\n image.convolute([\n\t[1, 1, 1],\n\t[1, -8, 1],\n\t[1, 1, 1]\n ]);\n image.write(filename);\n console.log(getCurrentTime() + '> Edge detection image saved as <' + filename + '>.');\n}", "edgeCheck(){\n if (this.spotX + this.rStar >= width || this.spotX - this.rStar <= .1) {\n this.finiteX *= -.09;\n//if the border is reached the star will change to this color\n this.color = 'rgb(230, 230, 255)';\n\n }\n\n//this will check if the stars hit the borders of the canvas\n if (this.spotY + this.rStar >= height || this.spotY - this.rStar <= .1){\n this.finiteX *= -.09;\n//if the border is reached the star will change to this color\n this.color = 'rgb(142, 257, 6)';\n\n\n }\n\n }", "function checkEdgesCollision() {\n\tif (x + dx > WIDTH || x + dx < 0)\n dx = -dx;\n if (y + dy > HEIGHT || y + dy < 0)\n dy = -dy;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function saves the current project to the server based off of the values that the user entered INNER FUNCTION CALLS: isValidInput_CLOSEOUT()
function saveProject_CLOSEOUT() { console.log('Saving Closeout Information'); var costcoSignoff = $('#closeoutData').find('#costcoSignoff').val(); var punchList = $('#closeoutData').find('#punchList').val(); var alarmHvac = $('#closeoutData').find('#alarmHvac').val(); var verisae = $('#closeoutData').find('#verisae').val(); var asBuilts = $('#closeoutData').find('#asBuilts').val(); /* tempholder var buildingPermitCL = $('#closeoutData').find("#buildingPermitCL").val(); */ var closeoutPhotosCL = $('#closeoutData').find('#closeoutPhotosCL').val(); var MCSWarranty = $('#closeoutData').find('#MCSWarranty').val(); var equipmentSubCL = $('#closeoutData').find('#equipmentSubCL').val(); // NEW Closeout CONTENT var mg2CompletionStatus = $('#closeoutData') .find('#mg2CompletionStatus') .val(); var mg2CompletionDate = $('#closeoutData').find('#mg2CompletionDate').val(); var numOfChangeOrders = $('#closeoutData').find('#numOfChangeOrders').val(); var numOfChangeOrdersCompleted = $('#closeoutData') .find('#numOfChangeOrdersCompleted') .val(); var numOfMCSChangeOrders = $('#closeoutData') .find('#numOfMCSChangeOrders') .val(); var numOfMCSChangeOrdersCompleted = $('#closeoutData') .find('#numOfMCSChangeOrdersCompleted') .val(); // LIENS var MCSStatus = $('#closeoutData').find('#MCSStatus').val(); var MCSDate = $('#closeoutData').find('#MCSDate').val(); var GCStatus = $('#closeoutData').find('#GCStatus').val(); var GCDate = $('#closeoutData').find('#GCDate').val(); var mechanicalStatus = $('#mechanicalStatus').val(); var mechanicalDate = $('#mechanicalDate').val(); var electricalStatus = $('#closeoutData').find('#electricalStatus').val(); var electricalDate = $('#closeoutData').find('#electricalDate').val(); var plumbingStatus = $('#closeoutData').find('#plumbingStatus').val(); var plumbingDate = $('#closeoutData').find('#plumbingDate').val(); var gasStatus = $('#closeoutData').find('#gasStatus').val(); var gasDate = $('#closeoutData').find('#gasDate').val(); var sprinkleStatus = $('#closeoutData').find('#sprinkleStatus').val(); var sprinkleDate = $('#closeoutData').find('#sprinkleDate').val(); var HTIStatus = $('#closeoutData').find('#HTIStatus').val(); var HTIDate = $('#closeoutData').find('#HTIDate').val(); var otherFinalLeinsStatus = $('#closeoutData') .find('#otherFinalLiensStatus') .val(); var otherFinalLeinsDate = $('#closeoutData') .find('#otherFinalLiensDate') .val(); var otherFinalLeinsBStatus = $('#closeoutData') .find('#otherFinalLiensBStatus') .val(); var otherFinalLeinsBDate = $('#closeoutData') .find('#otherFinalLiensBDate') .val(); var finalLiensNotes = $('#closeoutData').find('#finalLiensNotes').val(); // INSPECTIONS /* Field not being used anymore var tmpCertificateStatus = $('#closeoutData').find("#tmpCertificateStatus").val(); var tmpCertificateDate = $('#closeoutData').find("#tmpCertificateDate").val(); var mechFinalStatus = $('#closeoutData').find("#mechFinalStatus").val(); var mechFinalDate = $('#closeoutData').find("#mechFinalDate").val(); var elecFinalDate = $('#closeoutData').find("#elecFinalDate").val(); var elecFinalStatus = $('#closeoutData').find("#elecFinalStatus").val(); var plumbingFinalDate = $('#closeoutData').find("#plumbingFinalDate").val(); var plumbingFinalStatus = $('#closeoutData').find("#plumbingFinalStatus").val(); var gasFinalDate = $('#closeoutData').find("#gasFinalDate").val(); var gasFinalStatus = $('#closeoutData').find("#gasFinalStatus").val(); var ceilingFinalDate = $('#closeoutData').find("#ceilingFinalDate").val(); var ceilingFinalStatus = $('#closeoutData').find("#ceilingFinalStatus").val(); var fireAlarmFinalDate = $('#closeoutData').find("#fireAlarmFinalDate").val(); var fireAlarmFinalStatus = $('#closeoutData').find("#fireAlarmFinalStatus").val(); var lowVolFinalDate = $('#closeoutData').find("#lowVolFinalDate").val(); var lowVolFinalStatus = $('#closeoutData').find("#lowVolFinalStatus").val(); var sprinkleFinalStatus = $('#closeoutData').find("#sprinkleFinalStatus").val(); var sprinkleFinalDate = $('#closeoutData').find("#sprinkleFinalDate").val(); var certificateStatus = $('#closeoutData').find("#certificateStatus").val(); var certificateDate = $('#closeoutData').find("#certificateDate").val(); var buildingFinalStatus = $('#closeoutData').find("#buildFinalStatus").val(); var finalInspectionNotes = $('#closeoutData').find("#finalInspectionNotes").val(); */ // WARRANTIES var MCSWarrantyStatus = $('#closeoutData').find('#MCSWarrantyStatus').val(); // MCSWarranty = MCSWarrantyDate var GCWarrantyStatus = $('#closeoutData').find('#GCWarrantyStatus').val(); var GCWarrantyDate = $('#closeoutData').find('#GCWarrantyDate').val(); var mechanicalWarrantyStatus = $('#closeoutData') .find('#mechanicalWarrantyStatus') .val(); var mechanicalWarrantyDate = $('#closeoutData') .find('#mechanicalWarrantyDate') .val(); var electricalWarrantyStatus = $('#closeoutData') .find('#electricalWarrantyStatus') .val(); var electricalWarrantyDate = $('#closeoutData') .find('#electricalWarrantyDate') .val(); var plumbingWarrantyStatus = $('#closeoutData') .find('#plumbingWarrantyStatus') .val(); var plumbingWarrantyDate = $('#closeoutData') .find('#plumbingWarrantyDate') .val(); var gasWarrantyStatus = $('#closeoutData').find('#gasWarrantyStatus').val(); var gasWarrantyDate = $('#closeoutData').find('#gasWarrantyDate').val(); var sprinkleWarrantyStatus = $('#closeoutData') .find('#sprinkleWarrantyStatus') .val(); var sprinkleWarrantyDate = $('#closeoutData') .find('#sprinkleWarrantyDate') .val(); var HTIWarrantyStatus = $('#closeoutData').find('#HTIWarrantyStatus').val(); var HTIWarrantyDate = $('#closeoutData').find('#HTIWarrantyDate').val(); var otherWarrantyStatusA = $('#closeoutData') .find('#otherWarrantyStatusA') .val(); var otherWarrantyDateA = $('#closeoutData').find('#otherWarrantyDateA').val(); var otherWarrantyStatusB = $('#closeoutData') .find('#otherWarrantyStatusB') .val(); var otherWarrantyDateB = $('#closeoutData').find('#otherWarrantyDateB').val(); var warrantyNotes = $('#closeoutData').find('#warrantyNotes').val(); // CLOSEOUT DOCUMENTS var equipmentSubmittalStatus = $('#closeoutData') .find('#equipmentSubmittalStatus') .val(); // equipmentSubCL = equipmentSubmittalDate var manualStatus = $('#closeoutData').find('#manualStatus').val(); var manualDate = $('#closeoutData').find('#manualDate').val(); var hvacCloseoutStatus = $('#closeoutData').find('#hvacCloseoutStatus').val(); var refrigerationCloseoutStatus = $('#closeoutData') .find('#refrigerationCloseoutStatus') .val(); var costcoSignoffStatus = $('#closeoutData') .find('#costcoSignoffStatus') .val(); var punchListStatus = $('#closeoutData').find('#punchListStatus').val(); //punchList = punchListDate var asBuiltDrawingsStatus = $('#closeoutData') .find('#asBuiltDrawingsStatus') .val(); // asBuilts = asBuiltDrawingsDate var closeOutPhotosStatus = $('#closeoutData') .find('#closeOutPhotosStatus') .val(); //closeoutPhotosCL = closeOutPhotosDate var HVACstartupFormStatus = $('#closeoutData') .find('#HVACstartupFormStatus') .val(); var HVACstartupFormDate = $('#closeoutData') .find('#HVACstartupFormDate') .val(); var pbnMTStatus = $('#closeoutData').find('#pbnMTStatus').val(); var pbnMTDate = $('#closeoutData').find('#pbnMTDate').val(); var salvageStatus = $('#closeoutData').find('#salvageStatus').val(); var alarmFormStatus = $('#closeoutData').find('#alarmFormStatus').val(); // alarmHVAC = alarmFormDate var verisaeReportStatus = $('#closeoutData') .find('#verisaeReportStatus') .val(); // verisae = verisaeReportDate var closeoutDocumentsNotes = $('#closeoutData') .find('#closeoutDocumentsNotes') .val(); var salvageDate = $('#otherItemsSalvageTable').find('#salvageDate').val(); var salvageAmount = $('#otherItemsSalvageTable').find('#salvageAmount').val(); if (salvageAmount === 'N/A') salvageAmount = -1; else if (salvageAmount === 'TBD') salvageAmount = -2; console.log('SALVAGE AMOUNT ', salvageAmount); var substantialCompletionStatus = $('#closeoutData') .find('#substantialCompletionStatus') .val(); var substantialCompletionDate = $('#closeoutData') .find('#substantialCompletionDate') .val(); var paymentOfDebtsAndClaimsStatus = $('#closeoutData') .find('#paymentOfDebtsAndClaimsStatus') .val(); var paymentOfDebtsAndClaimsDate = $('#closeoutData') .find('#paymentOfDebtsAndClaimsDate') .val(); var releaseOfLiensStatus = $('#closeoutData') .find('#releaseOfLiensStatus') .val(); var releaseOfLiensDate = $('#closeoutData').find('#releaseOfLiensDate').val(); var mulvannySignOffStatus = $('#closeoutData') .find('#mulvannySignOffStatus') .val(); var mulvannySignOffDate = $('#closeoutData') .find('#mulvannySignOffDate') .val(); ////////////// END NEW CONTENT var dates_CLOSEOUT = [ /* Field not being used anymore buildingPermitCL, */ closeoutPhotosCL, MCSWarranty, //41 equipmentSubCL, // new closeout info //mg2CompletionDate, MCSDate, GCDate, mechanicalDate, electricalDate, plumbingDate, gasDate, sprinkleDate, HTIDate, otherFinalLeinsDate, /* Fields not being used anymore sprinkleFinalDate, certificateDate, mechFinalDate, elecFinalDate, plumbingFinalDate, gasFinalDate, ceilingFinalDate, fireAlarmFinalDate, lowVolFinalDate, tmpCertificateDate, */ GCWarrantyDate, mechanicalWarrantyDate, electricalWarrantyDate, sprinkleWarrantyDate, plumbingWarrantyDate, gasWarrantyDate, HTIWarrantyDate, otherWarrantyDateA, otherWarrantyDateB, manualDate, HVACstartupFormDate, salvageDate, substantialCompletionDate, paymentOfDebtsAndClaimsDate, releaseOfLiensDate, mulvannySignOffDate, asBuilts, costcoSignoff, punchList, alarmHvac, verisae, ]; if (isValidInput_CLOSEOUT(dates_CLOSEOUT)) { console.log('we got valid data now'); for (var i = 0; i < dates_CLOSEOUT.length; i++) { if (dates_CLOSEOUT[i]) dates_CLOSEOUT[i] = dateCleaner(dates_CLOSEOUT[i]); /* Field not being used anymore if(i == 0) buildingPermitCL = dates_CLOSEOUT[i]; */ if (i == 0) closeoutPhotosCL = dates_CLOSEOUT[i]; if (i == 1) MCSWarranty = dates_CLOSEOUT[i]; if (i == 2) equipmentSubCL = dates_CLOSEOUT[i]; if (i == 3) MCSDate = dates_CLOSEOUT[i]; if (i == 4) GCDate = dates_CLOSEOUT[i]; if (i == 5) mechanicalDate = dates_CLOSEOUT[i]; if (i == 6) electricalDate = dates_CLOSEOUT[i]; if (i == 7) plumbingDate = dates_CLOSEOUT[i]; if (i == 8) gasDate = dates_CLOSEOUT[i]; if (i == 9) sprinkleDate = dates_CLOSEOUT[i]; if (i == 10) HTIDate = dates_CLOSEOUT[i]; if (i == 11) otherFinalLeinsDate = dates_CLOSEOUT[i]; /* Field not being used anymore if(i == 13) sprinkleFinalDate = dates_CLOSEOUT[i]; if(i == 14) certificateDate = dates_CLOSEOUT[i]; if(i == 15) mechFinalDate = dates_CLOSEOUT[i]; if(i == 16) elecFinalDate = dates_CLOSEOUT[i]; if(i == 17) plumbingFinalDate = dates_CLOSEOUT[i]; if(i == 18) gasFinalDate = dates_CLOSEOUT[i]; if(i == 19) ceilingFinalDate = dates_CLOSEOUT[i]; if(i == 20) fireAlarmFinalDate = dates_CLOSEOUT[i]; if(i == 21) lowVolFinalDate = dates_CLOSEOUT[i]; if(i == 22) tmpCertificateDate = dates_CLOSEOUT[i]; */ if (i == 12) GCWarrantyDate = dates_CLOSEOUT[i]; if (i == 13) mechanicalWarrantyDate = dates_CLOSEOUT[i]; if (i == 14) electricalWarrantyDate = dates_CLOSEOUT[i]; if (i == 15) sprinkleWarrantyDate = dates_CLOSEOUT[i]; if (i == 16) plumbingWarrantyDate = dates_CLOSEOUT[i]; if (i == 17) gasWarrantyDate = dates_CLOSEOUT[i]; if (i == 18) HTIWarrantyDate = dates_CLOSEOUT[i]; if (i == 19) otherWarrantyDateA = dates_CLOSEOUT[i]; if (i == 20) otherWarrantyDateB = dates_CLOSEOUT[i]; if (i == 21) manualDate = dates_CLOSEOUT[i]; if (i == 22) HVACstartupFormDate = dates_CLOSEOUT[i]; if (i == 23) salvageDate = dates_CLOSEOUT[i]; if (i == 24) substantialCompletionDate = dates_CLOSEOUT[i]; if (i == 25) paymentOfDebtsAndClaimsDate = dates_CLOSEOUT[i]; if (i == 26) releaseOfLiensDate = dates_CLOSEOUT[i]; if (i == 27) mulvannySignOffDate = dates_CLOSEOUT[i]; if (i == 28) asBuilts = dates_CLOSEOUT[i]; if (i == 29) costcoSignoff = dates_CLOSEOUT[i]; if (i == 30) punchList = dates_CLOSEOUT[i]; if (i == 31) alarmHvac = dates_CLOSEOUT[i]; if (i == 32) verisae = dates_CLOSEOUT[i]; } var action = 'editCloseout'; var CLOSEOUT_ID = PROJECT_DATA.closeoutDetails.id; var SALVAGE_ID = 0; if (PROJECT_DATA.closeoutDetails.salvageValue != null) SALVAGE_ID = PROJECT_DATA.closeoutDetails.salvageValue.id; if (!PROJECT_DATA || !PROJECT_DATA.id) { alert('Server Error! (Project ID)'); return; } if (!CLOSEOUT_ID) { alert('Server Error! (Closeout ID)'); return; } $.ajax({ type: 'POST', url: 'Project', dataType: 'json', data: { domain: 'project', action: action, projectID: PROJECT_DATA.id, closeoutID: CLOSEOUT_ID, salvageID: SALVAGE_ID, asBuilts: asBuilts, costcoSignoff: costcoSignoff, punchList: punchList, alarmHvac: alarmHvac, verisae: verisae, /* field not being used anymore 'buildingPermitCL':buildingPermitCL, */ closeoutPhotosCL: closeoutPhotosCL, MCSWarranty: MCSWarranty, equipmentSubCL: equipmentSubCL, // new closeout info mg2CompletionStatus: mg2CompletionStatus, //'mg2CompletionDate': mg2CompletionDate, numOfChangeOrders: numOfChangeOrders, numOfChangeOrdersCompleted: numOfChangeOrdersCompleted, numOfMCSChangeOrders: numOfMCSChangeOrders, numOfMCSChangeOrdersCompleted: numOfMCSChangeOrdersCompleted, MCSStatus: MCSStatus, MCSDate: MCSDate, GCStatus: GCStatus, GCDate: GCDate, mechanicalStatus: mechanicalStatus, mechanicalDate: mechanicalDate, electricalStatus: electricalStatus, electricalDate: electricalDate, plumbingStatus: plumbingStatus, plumbingDate: plumbingDate, gasStatus: gasStatus, gasDate: gasDate, sprinkleStatus: sprinkleStatus, sprinkleDate: sprinkleDate, HTIStatus: HTIStatus, HTIDate: HTIDate, finalLiensNotes: finalLiensNotes, otherFinalLeinsStatus: otherFinalLeinsStatus, otherFinalLeinsDate: otherFinalLeinsDate, otherFinalLeinsBStatus: otherFinalLeinsBStatus, otherFinalLeinsBDate: otherFinalLeinsBDate, /* field not being used anymore 'mechFinalStatus': mechFinalStatus, 'mechFinalDate': mechFinalDate, 'elecFinalStatus': elecFinalStatus, 'elecFinalDate': elecFinalDate, 'plumbingFinalStatus': plumbingFinalStatus, 'plumbingFinalDate': plumbingFinalDate, 'gasFinalStatus': gasFinalStatus, 'gasFinalDate': gasFinalDate, 'ceilingFinalStatus': ceilingFinalStatus, 'ceilingFinalDate': ceilingFinalDate, 'fireAlarmFinalStatus': fireAlarmFinalStatus, 'fireAlarmFinalDate': fireAlarmFinalDate, 'lowVolFinalStatus': lowVolFinalStatus, 'lowVolFinalDate': lowVolFinalDate, 'sprinkleFinalStatus': sprinkleFinalStatus, 'sprinkleFinalDate': sprinkleFinalDate, 'buildingFinalStatus': buildingFinalStatus, 'tmpCertificateStatus': tmpCertificateStatus, 'tmpCertificateDate': tmpCertificateDate, 'certificateStatus': certificateStatus, 'certificateDate': certificateDate, 'finalInspectionNotes': finalInspectionNotes, */ MCSWarrantyStatus: MCSWarrantyStatus, GCWarrantyStatus: GCWarrantyStatus, GCWarrantyDate: GCWarrantyDate, mechanicalWarrantyStatus: mechanicalWarrantyStatus, mechanicalWarrantyDate: mechanicalWarrantyDate, electricalWarrantyStatus: electricalWarrantyStatus, electricalWarrantyDate: electricalWarrantyDate, plumbingWarrantyStatus: plumbingWarrantyStatus, plumbingWarrantyDate: plumbingWarrantyDate, gasWarrantyStatus: gasWarrantyStatus, gasWarrantyDate: gasWarrantyDate, sprinkleWarrantyStatus: sprinkleWarrantyStatus, sprinkleWarrantyDate: sprinkleWarrantyDate, HTIWarrantyStatus: HTIWarrantyStatus, HTIWarrantyDate: HTIWarrantyDate, otherWarrantyStatusA: otherWarrantyStatusA, otherWarrantyDateA: otherWarrantyDateA, otherWarrantyStatusB: otherWarrantyStatusB, otherWarrantyDateB: otherWarrantyDateB, warrantyNotes: warrantyNotes, equipmentSubmittalStatus: equipmentSubmittalStatus, manualStatus: manualStatus, manualDate: manualDate, costcoSignoffStatus: costcoSignoffStatus, punchListStatus: punchListStatus, hvacCloseoutStatus: hvacCloseoutStatus, refrigerationCloseoutStatus: refrigerationCloseoutStatus, asBuiltDrawingsStatus: asBuiltDrawingsStatus, closeOutPhotosStatus: closeOutPhotosStatus, HVACstartupFormStatus: HVACstartupFormStatus, HVACstartupFormDate: HVACstartupFormDate, pbnMTStatus: pbnMTStatus, pbnMTDate: pbnMTDate, salvageStatus: salvageStatus, alarmFormStatus: alarmFormStatus, verisaeReportStatus: verisaeReportStatus, closeoutDocumentsNotes: closeoutDocumentsNotes, salvageDate: salvageDate, salvageAmount: salvageAmount, substantialCompletionDate: substantialCompletionDate, substantialCompletionStatus: substantialCompletionStatus, paymentOfDebtsAndClaimsDate: paymentOfDebtsAndClaimsDate, paymentOfDebtsAndClaimsStatus: paymentOfDebtsAndClaimsStatus, releaseOfLiensDate: releaseOfLiensDate, releaseOfLiensStatus: releaseOfLiensStatus, mulvannySignOffDate: mulvannySignOffDate, mulvannySignOffStatus: mulvannySignOffStatus, }, success: function (data) { updateFrontEnd(); alert('Project Saved'); console.log(data); //UPDATE CLOSEOUT SUMMARY $('#closeoutData').find('#saveButton > button').prop('disabled', false); }, /*commented out because of error. Error dictates that their is a parse error and unexpected end of input. * Code works perfectly with error statement Need to figure out how to fix this error to work 100 percent correctly*/ //error: function(XMLHttpRequest, textStatus, errorThrown) { error: function () { alert('Project Saved'); $('#closeoutData').find('#saveButton > button').prop('disabled', false); //UPDATE CLOSEOUT SUMMARY //getProject_PROJECT_MANAGER(projectID , 1); //goToProjectManager(); //alert("Status: " + textStatus); //alert("Error: " + errorThrown); //error:function(xhr){ //alert(xhr.responceText); //console.log(xhr.responseText); }, }); } }
[ "function saveProject_CLOSEOUT()\n{\n console.log(\"Saving Closeout Information\");\n var punchList = $('#closeoutData').find(\"#punchList\").val();\n\tvar alarmHvac = $('#closeoutData').find(\"#alarmHvac\").val();\n\tvar verisae = $('#closeoutData').find(\"#verisae\").val();\n\tvar asBuilts = $('#closeoutData').find(\"#asBuilts\").val();\n\t\n\tvar buildingPermitCL = $('#closeoutData').find(\"#buildingPermitCL\").val();\n\t\n\tvar closeoutPhotosCL = $('#closeoutData').find(\"#closeoutPhotosCL\").val();\n\tvar MCSWarranty = $('#closeoutData').find(\"#MCSWarranty\").val();\n\tvar equipmentSubCL = $('#closeoutData').find(\"#equipmentSubCL\").val();\n \n \n // NEW Closeout CONTENT\n\t\n\tvar mg2CompletionStatus = $('#closeoutData').find(\"#mg2CompletionStatus\").val();\n\tvar mg2CompletionDate = $('#closeoutData').find(\"#mg2CompletionDate\").val();\n\t\n\tvar numOfChangeOrders = $('#closeoutData').find(\"#numOfChangeOrders\").val();\n\tvar numOfChangeOrdersCompleted = $('#closeoutData').find(\"#numOfChangeOrdersCompleted\").val();\n\t\n\tvar numOfMCSChangeOrders = $('#closeoutData').find(\"#numOfMCSChangeOrders\").val();\n\tvar numOfMCSChangeOrdersCompleted = $('#closeoutData').find(\"#numOfMCSChangeOrdersCompleted\").val();\n \n // LIENS\n var MCSStatus = $('#closeoutData').find(\"#MCSStatus\").val(); \n var MCSDate = $('#closeoutData').find(\"#MCSDate\").val(); \n \n var GCStatus = $('#closeoutData').find(\"#GCStatus\").val();\n var GCDate = $('#closeoutData').find(\"#GCDate\").val();\n \n var mechanicalStatus = $(\"#mechanicalStatus\").val();\n var mechanicalDate = $(\"#mechanicalDate\").val();\n \n var electricalStatus = $('#closeoutData').find(\"#electricalStatus\").val();\n var electricalDate = $('#closeoutData').find(\"#electricalDate\").val();\n \n var plumbingStatus = $('#closeoutData').find(\"#plumbingStatus\").val();\n var plumbingDate = $('#closeoutData').find(\"#plumbingDate\").val();\n \n var gasStatus = $('#closeoutData').find(\"#gasStatus\").val();\n var gasDate = $('#closeoutData').find(\"#gasDate\").val();\n \n var sprinkleStatus = $('#closeoutData').find(\"#sprinkleStatus\").val();\n var sprinkleDate = $('#closeoutData').find(\"#sprinkleDate\").val();\n \n var HTIStatus = $('#closeoutData').find(\"#HTIStatus\").val();\n var HTIDate = $('#closeoutData').find(\"#HTIDate\").val();\n \n var otherFinalLeinsStatus = $('#closeoutData').find(\"#otherFinalLiensStatus\").val();\n var otherFinalLeinsDate = $('#closeoutData').find(\"#otherFinalLiensDate\").val();\n\n var otherFinalLeinsBStatus = $('#closeoutData').find(\"#otherFinalLiensBStatus\").val();\n var otherFinalLeinsBDate = $('#closeoutData').find(\"#otherFinalLiensBDate\").val();\n \n var finalLiensNotes = $('#closeoutData').find(\"#finalLiensNotes\").val();\n \n \t// INSPECTIONS\n \n var tmpCertificateStatus = $('#closeoutData').find(\"#tmpCertificateStatus\").val();\n var tmpCertificateDate = $('#closeoutData').find(\"#tmpCertificateDate\").val();\n \n var mechFinalStatus = $('#closeoutData').find(\"#mechFinalStatus\").val();\n var mechFinalDate = $('#closeoutData').find(\"#mechFinalDate\").val();\n \n var elecFinalDate = $('#closeoutData').find(\"#elecFinalDate\").val();\n var elecFinalStatus = $('#closeoutData').find(\"#elecFinalStatus\").val();\n \n var plumbingFinalDate = $('#closeoutData').find(\"#plumbingFinalDate\").val();\n var plumbingFinalStatus = $('#closeoutData').find(\"#plumbingFinalStatus\").val();\n \n var gasFinalDate = $('#closeoutData').find(\"#gasFinalDate\").val();\n var gasFinalStatus = $('#closeoutData').find(\"#gasFinalStatus\").val();\n \n var ceilingFinalDate = $('#closeoutData').find(\"#ceilingFinalDate\").val();\n var ceilingFinalStatus = $('#closeoutData').find(\"#ceilingFinalStatus\").val();\n \n var fireAlarmFinalDate = $('#closeoutData').find(\"#fireAlarmFinalDate\").val();\n var fireAlarmFinalStatus = $('#closeoutData').find(\"#fireAlarmFinalStatus\").val();\n \n var lowVolFinalDate = $('#closeoutData').find(\"#lowVolFinalDate\").val();\n var lowVolFinalStatus = $('#closeoutData').find(\"#lowVolFinalStatus\").val();\n \n var sprinkleFinalStatus = $('#closeoutData').find(\"#sprinkleFinalStatus\").val();\n var sprinkleFinalDate = $('#closeoutData').find(\"#sprinkleFinalDate\").val();\n \n var certificateStatus = $('#closeoutData').find(\"#certificateStatus\").val();\n var certificateDate = $('#closeoutData').find(\"#certificateDate\").val();\n \n var buildingFinalStatus = $('#closeoutData').find(\"#buildFinalStatus\").val();\n \n var finalInspectionNotes = $('#closeoutData').find(\"#finalInspectionNotes\").val();\n\n \t// WARRANTIES\n \n var MCSWarrantyStatus = $('#closeoutData').find(\"#MCSWarrantyStatus\").val();\n // MCSWarranty = MCSWarrantyDate\n \n var GCWarrantyStatus = $('#closeoutData').find(\"#GCWarrantyStatus\").val();\n var GCWarrantyDate = $('#closeoutData').find(\"#GCWarrantyDate\").val();\n \n var mechanicalWarrantyStatus = $('#closeoutData').find(\"#mechanicalWarrantyStatus\").val();\n var mechanicalWarrantyDate = $('#closeoutData').find(\"#mechanicalWarrantyDate\").val();\n \n var electricalWarrantyStatus = $('#closeoutData').find(\"#electricalWarrantyStatus\").val();\n var electricalWarrantyDate = $('#closeoutData').find(\"#electricalWarrantyDate\").val();\n \n var plumbingWarrantyStatus = $('#closeoutData').find(\"#plumbingWarrantyStatus\").val();\n var plumbingWarrantyDate = $('#closeoutData').find(\"#plumbingWarrantyDate\").val();\n \n var gasWarrantyStatus = $('#closeoutData').find(\"#gasWarrantyStatus\").val();\n var gasWarrantyDate = $('#closeoutData').find(\"#gasWarrantyDate\").val();\n \n var sprinkleWarrantyStatus = $('#closeoutData').find(\"#sprinkleWarrantyStatus\").val();\n var sprinkleWarrantyDate = $('#closeoutData').find(\"#sprinkleWarrantyDate\").val();\n \n var HTIWarrantyStatus = $('#closeoutData').find(\"#HTIWarrantyStatus\").val();\n var HTIWarrantyDate = $('#closeoutData').find(\"#HTIWarrantyDate\").val();\n \n var otherWarrantyStatusA = $('#closeoutData').find(\"#otherWarrantyStatusA\").val();\n var otherWarrantyDateA = $('#closeoutData').find(\"#otherWarrantyDateA\").val();\n \n var otherWarrantyStatusB = $('#closeoutData').find(\"#otherWarrantyStatusB\").val();\n var otherWarrantyDateB = $('#closeoutData').find(\"#otherWarrantyDateB\").val();\n \n var warrantyNotes = $('#closeoutData').find(\"#warrantyNotes\").val();\n \n // CLOSEOUT DOCUMENTS\n var equipmentSubmittalStatus = $('#closeoutData').find(\"#equipmentSubmittalStatus\").val();\n // equipmentSubCL = equipmentSubmittalDate\n \n var manualStatus = $('#closeoutData').find(\"#manualStatus\").val();\n var manualDate = $('#closeoutData').find(\"#manualDate\").val();\n \n var punchListStatus = $('#closeoutData').find(\"#punchListStatus\").val();\n //punchList = punchListDate\n \n var asBuiltDrawingsStatus = $('#closeoutData').find(\"#asBuiltDrawingsStatus\").val();\n // asBuilts = asBuiltDrawingsDate\n \n var closeOutPhotosStatus = $('#closeoutData').find(\"#closeOutPhotosStatus\").val();\n //closeoutPhotosCL = closeOutPhotosDate\n \n var HVACstartupFormStatus = $('#closeoutData').find(\"#HVACstartupFormStatus\").val();\n var HVACstartupFormDate = $('#closeoutData').find(\"#HVACstartupFormDate\").val();\n \n var alarmFormStatus = $('#closeoutData').find(\"#alarmFormStatus\").val();\n \n \n var salvageStatus = $('#closeoutData').find(\"#salvageStatus\").val();\n // alarmHVAC = alarmFormDate\n \n var verisaeReportStatus = $('#closeoutData').find(\"#verisaeReportStatus\").val();\n // verisae = verisaeReportDate\n\n var closeoutDocumentsNotes = $('#closeoutData').find(\"#closeoutDocumentsNotes\").val();\n \n var salvageDate = $('#otherItemsSalvageTable').find(\"#salvageDate\").val();\n var salvageAmount = $('#otherItemsSalvageTable').find(\"#salvageAmount\").val();\n \n if(salvageAmount === \"N/A\")\n \tsalvageAmount = -1;\n else if(salvageAmount === \"TBD\")\n \tsalvageAmount = -2;\n \n console.log(\"SALVAGE AMOUNT \" , salvageAmount);\n \n var substantialCompletionStatus = $('#closeoutData').find('#substantialCompletionStatus').val();\n var substantialCompletionDate = $('#closeoutData').find('#substantialCompletionDate').val();\n \n var paymentOfDebtsAndClaimsStatus = $('#closeoutData').find('#paymentOfDebtsAndClaimsStatus').val();\n var paymentOfDebtsAndClaimsDate = $('#closeoutData').find('#paymentOfDebtsAndClaimsDate').val();\n \n var releaseOfLiensStatus = $('#closeoutData').find('#releaseOfLiensStatus').val();\n var releaseOfLiensDate = $('#closeoutData').find('#releaseOfLiensDate').val();\n \n var mulvannySignOffStatus = $('#closeoutData').find('#mulvannySignOffStatus').val();\n var mulvannySignOffDate = $('#closeoutData').find('#mulvannySignOffDate').val();\n ////////////// END NEW CONTENT\n \n var dates_CLOSEOUT =[\n\t\t\t\t \n\t\t\t\tbuildingPermitCL,\n\t\t\t\t \n\t\t\t\tcloseoutPhotosCL,\n\t\t\t\tMCSWarranty,//41\n\t\t\t\tequipmentSubCL,\n\t\t\t\t\n\t\t\t\t\n\t\t\t\t// new closeout info\n\t\t\t\t//mg2CompletionDate,\n\t\t\t\t\n\t\t\t\tMCSDate, GCDate, mechanicalDate, electricalDate, plumbingDate, gasDate,\n\t\t\t\tsprinkleDate, HTIDate, otherFinalLeinsDate,\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tsprinkleFinalDate, certificateDate, mechFinalDate, elecFinalDate, plumbingFinalDate, gasFinalDate,\n\t\t\t\tceilingFinalDate, fireAlarmDate, lowVolDate, tmpCertificateDate,\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tGCWarrantyDate, mechanicalWarrantyDate, electricalWarrantyDate, sprinkleWarrantyDate, plumbingWarrantyDate, \n\t\t\t\tgasWarrantyDate, HTIWarrantyDate, otherWarrantyDateA, otherWarrantyDateB,\n\t\t\t\t\n\t\t\t\tmanualDate, HVACstartupFormDate, salvageDate, substantialCompletionDate, \n\t\t\t\tpaymentOfDebtsAndClaimsDate, releaseOfLiensDate, mulvannySignOffDate, asBuilts,\n\t\t\t\tpunchList, alarmHvac, verisae\n ];\n \n \n if(isValidInput_CLOSEOUT(dates_CLOSEOUT))\n {\n \tconsole.log(\"we got valid data now\");\n \tfor(var i = 0; i < dates_CLOSEOUT.length; i++) {\n \t\tif(dates_CLOSEOUT[i]) dates_CLOSEOUT[i] = dateCleaner(dates_CLOSEOUT[i]);\n \n \t\t\n \t\tif(i == 0) buildingPermitCL = dates_CLOSEOUT[i];\n \t\tif(i == 1) closeoutPhotosCL = dates_CLOSEOUT[i];\n \t\tif(i == 2) MCSWarranty = dates_CLOSEOUT[i];\n \t\tif(i == 3) equipmentSubCL = dates_CLOSEOUT[i];\n \t\tif(i == 4) MCSDate = dates_CLOSEOUT[i];\n \t\tif(i == 5) GCDate = dates_CLOSEOUT[i];\n \t\tif(i == 6) mechanicalDate = dates_CLOSEOUT[i];\n \t\tif(i == 7) electricalDate = dates_CLOSEOUT[i];\n \t\tif(i == 8) plumbingDate = dates_CLOSEOUT[i];\n \t\tif(i == 9) gasDate = dates_CLOSEOUT[i];\n \t\tif(i == 10) sprinkleDate = dates_CLOSEOUT[i];\n \t\tif(i == 11) HTIDate = dates_CLOSEOUT[i];\n \t\tif(i == 12) otherFinalLeinsDate = dates_CLOSEOUT[i];\n \t\tif(i == 13) sprinkleFinalDate = dates_CLOSEOUT[i];\n \t\tif(i == 14) certificateDate = dates_CLOSEOUT[i];\n \t\tif(i == 15) mechFinalDate = dates_CLOSEOUT[i];\n \t\tif(i == 16) elecFinalDate = dates_CLOSEOUT[i];\n \t\tif(i == 17) plumbingFinalDate = dates_CLOSEOUT[i];\n \t\tif(i == 18) gasFinalDate = dates_CLOSEOUT[i];\n \t\tif(i == 19) ceilingFinalDate = dates_CLOSEOUT[i];\n \t\tif(i == 20) fireAlarmFinalDate = dates_CLOSEOUT[i];\n \t\tif(i == 21) lowVolFinalDate = dates_CLOSEOUT[i];\n \t\tif(i == 22) tmpCertificateDate = dates_CLOSEOUT[i];\n \t\tif(i == 23) GCWarrantyDate = dates_CLOSEOUT[i];\n \t\tif(i == 24) mechanicalWarrantyDate = dates_CLOSEOUT[i];\n \t\tif(i == 25) electricalWarrantyDate = dates_CLOSEOUT[i];\n \t\tif(i == 26) sprinkleWarrantyDate = dates_CLOSEOUT[i];\n \t\tif(i == 27) plumbingWarrantyDate = dates_CLOSEOUT[i];\n \t\tif(i == 28) gasWarrantyDate = dates_CLOSEOUT[i];\n \t\tif(i == 29) HTIWarrantyDate = dates_CLOSEOUT[i];\n \t\tif(i == 30) otherWarrantyDateA = dates_CLOSEOUT[i];\n \t\tif(i == 31) otherWarrantyDateB = dates_CLOSEOUT[i];\n \t\tif(i == 32) manualDate = dates_CLOSEOUT[i];\n \t\tif(i == 33) HVACstartupFormDate = dates_CLOSEOUT[i];\n \t\tif(i == 34) salvageDate = dates_CLOSEOUT[i];\n \t\tif(i == 35) substantialCompletionDate = dates_CLOSEOUT[i];\n \t\tif(i == 36) paymentOfDebtsAndClaimsDate = dates_CLOSEOUT[i];\n \t\tif(i == 37) releaseOfLiensDate = dates_CLOSEOUT[i];\n \t\tif(i == 38) mulvannySignOffDate = dates_CLOSEOUT[i];\n \t\tif(i == 39) asBuilts = dates_CLOSEOUT[i];\n \t\tif(i == 40) punchList = dates_CLOSEOUT[i];\n \t\tif(i == 41) alarmHvac = dates_CLOSEOUT[i];\n \t\tif(i == 42) verisae = dates_CLOSEOUT[i];\n \t}\n\t\tvar action = \"editCloseout\";\n\t\tvar CLOSEOUT_ID = PROJECT_DATA.closeoutDetails.id\n\t\tvar SALVAGE_ID = 0;\n\t\tif(PROJECT_DATA.closeoutDetails.salvageValue != null)\n\t\t\tSALVAGE_ID = PROJECT_DATA.closeoutDetails.salvageValue.id;\n\t\t\n\t\tif( (!PROJECT_DATA || !PROJECT_DATA.id))\n\t\t{\n\t\t\talert(\"Server Error! (Project ID)\");\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tif(!CLOSEOUT_ID)\n\t\t{\n\t\t\talert(\"Server Error! (Closeout ID)\");\n\t\t\treturn;\n\t\t}\n\t\t\n\t\t$.ajax({\n\t\t\ttype: 'POST',\n\t\t\turl: 'Project', \n\t\t\tdataType: 'json',\n\t\t\tdata: \n\t\t\t{\n\t\t\t\t'domain': 'project',\n\t\t\t\t'action': action,\n\t\t\t\t'projectID':PROJECT_DATA.id,\n\t\t\t\t'closeoutID':CLOSEOUT_ID,\n\t\t\t\t'salvageID': SALVAGE_ID,\n\n\t\t\t\t'asBuilts':asBuilts,\n\t\t\t\t'punchList':punchList,\n\t\t\t\t'alarmHvac':alarmHvac,\n\t\t\t\t'verisae':verisae,\n\t\t\t\t\n\n\t\t\t\t'buildingPermitCL':buildingPermitCL,\n\t\t\t\t\n\t\t\t\t'closeoutPhotosCL': closeoutPhotosCL,\n\t\t\t\t'MCSWarranty': MCSWarranty,\n\t\t\t\t'equipmentSubCL': equipmentSubCL, \n\t\t\t\t\n\t\t\t\t// new closeout info\n\t\t\t\t'mg2CompletionStatus': mg2CompletionStatus,\n\t\t\t\t//'mg2CompletionDate': mg2CompletionDate,\n\t\t\t\t\n\t\t\t\t'numOfChangeOrders': numOfChangeOrders,\n\t\t\t\t'numOfChangeOrdersCompleted': numOfChangeOrdersCompleted,\n\t\t\t\t\n\t\t\t\t'numOfMCSChangeOrders': numOfMCSChangeOrders,\n\t\t\t\t'numOfMCSChangeOrdersCompleted': numOfMCSChangeOrdersCompleted,\n\t\t\t\t\n\t\t\t\t'MCSStatus': MCSStatus,\n\t\t\t\t'MCSDate': MCSDate,\n\t\t\t\t\n\t\t\t\t'GCStatus': GCStatus,\n\t\t\t\t'GCDate': GCDate,\n\t\t\t\t\n\t\t\t\t'mechanicalStatus': mechanicalStatus,\n\t\t\t\t'mechanicalDate': mechanicalDate,\n\t\t\t\t\n\t\t\t\t'electricalStatus': electricalStatus,\n\t\t\t\t'electricalDate': electricalDate,\n\t\t\t\t\n\t\t\t\t'plumbingStatus': plumbingStatus,\n\t\t\t\t'plumbingDate': plumbingDate,\n\t\t\t\t\n\t\t\t\t'gasStatus': gasStatus,\n\t\t\t\t'gasDate': gasDate,\n\t\t\t\t\n\t\t\t\t'sprinkleStatus': sprinkleStatus,\n\t\t\t\t'sprinkleDate': sprinkleDate,\n\t\t\t\t\n\t\t\t\t'HTIStatus': HTIStatus,\n\t\t\t\t'HTIDate': HTIDate,\n\t\t\t\t\n\t\t\t\t'finalLiensNotes': finalLiensNotes,\n\t\t\t\t\n\t\t\t\t'otherFinalLeinsStatus': otherFinalLeinsStatus,\n\t\t\t\t'otherFinalLeinsDate': otherFinalLeinsDate,\n\t\t\t\t\n\t\t\t\t'otherFinalLeinsBStatus': otherFinalLeinsBStatus,\n\t\t\t\t'otherFinalLeinsBDate': otherFinalLeinsBDate,\n\t\t\t\t\n\t\t\t\t'mechFinalStatus': mechFinalStatus,\n\t\t\t\t'mechFinalDate': mechFinalDate,\n\t\t\t\t\n\t\t\t\t'elecFinalStatus': elecFinalStatus,\n\t\t\t\t'elecFinalDate': elecFinalDate,\n\t\t\t\t\n\t\t\t\t'plumbingFinalStatus': plumbingFinalStatus,\n\t\t\t\t'plumbingFinalDate': plumbingFinalDate,\n\t\t\t\t\n\t\t\t\t'gasFinalStatus': gasFinalStatus,\n\t\t\t\t'gasFinalDate': gasFinalDate,\n\t\t\t\t\n\t\t\t\t'ceilingFinalStatus': ceilingFinalStatus,\n\t\t\t\t'ceilingFinalDate': ceilingFinalDate,\n\t\t\t\t\n\t\t\t\t'fireAlarmFinalStatus': fireAlarmFinalStatus,\n\t\t\t\t'fireAlarmFinalDate': fireAlarmFinalDate,\n\t\t\t\t\n\t\t\t\t'lowVolFinalStatus': lowVolFinalStatus,\n\t\t\t\t'lowVolFinalDate': lowVolFinalDate,\n\t\t\t\t\n\t\t\t\t'sprinkleFinalStatus': sprinkleFinalStatus,\n\t\t\t\t'sprinkleFinalDate': sprinkleFinalDate,\n\t\t\t\t\n\t\t\t\t'buildingFinalStatus': buildingFinalStatus,\t\n\t\t\t\t\n\t\t\t\t'tmpCertificateStatus': tmpCertificateStatus,\n\t\t\t\t'tmpCertificateDate': tmpCertificateDate,\n\t\t\t\t\n\t\t\t\t'certificateStatus': certificateStatus,\n\t\t\t\t'certificateDate': certificateDate,\n\t\t\t\t\n\t\t\t\t'finalInspectionNotes': finalInspectionNotes,\n\t\t\t\n\t\t\t\t'MCSWarrantyStatus': MCSWarrantyStatus,\n\t\t\t\t\n\t\t\t\t'GCWarrantyStatus': GCWarrantyStatus,\n\t\t\t\t'GCWarrantyDate': GCWarrantyDate,\n\t\t\t\t\n\t\t\t\t'mechanicalWarrantyStatus': mechanicalWarrantyStatus,\n\t\t\t\t'mechanicalWarrantyDate': mechanicalWarrantyDate,\n\t\t\t\t\n\t\t\t\t'electricalWarrantyStatus': electricalWarrantyStatus,\n\t\t\t\t'electricalWarrantyDate': electricalWarrantyDate,\n\t\t\t\t\n\t\t\t\t'plumbingWarrantyStatus': plumbingWarrantyStatus,\n\t\t\t\t'plumbingWarrantyDate': plumbingWarrantyDate,\n\t\t\t\t\n\t\t\t\t'gasWarrantyStatus': gasWarrantyStatus,\n\t\t\t\t'gasWarrantyDate': gasWarrantyDate,\n\t\t\t\t\n\t\t\t\t'sprinkleWarrantyStatus': sprinkleWarrantyStatus,\n\t\t\t\t'sprinkleWarrantyDate': sprinkleWarrantyDate,\n\t\t\t\t\t\t\t\t\n\t\t\t\t'HTIWarrantyStatus': HTIWarrantyStatus,\n\t\t\t\t'HTIWarrantyDate': HTIWarrantyDate,\n\t\t\t\t\n\t\t\t\t'otherWarrantyStatusA': otherWarrantyStatusA,\n\t\t\t\t'otherWarrantyDateA': otherWarrantyDateA,\n\t\t\t\t\n\t\t\t\t'otherWarrantyStatusB': otherWarrantyStatusB,\n\t\t\t\t'otherWarrantyDateB': otherWarrantyDateB,\n\t\t\t\t\n\t\t\t\t'warrantyNotes': warrantyNotes,\n\t\t\t\t\t\t\t\t\n\t\t\t\t'equipmentSubmittalStatus': equipmentSubmittalStatus,\n\t\t\t\t\n\t\t\t\t'manualStatus': manualStatus,\n\t\t\t\t'manualDate': manualDate,\n\t\t\t\t\n\t\t\t\t'punchListStatus': punchListStatus,\n\t\t\t\t\n\t\t\t\t'asBuiltDrawingsStatus': asBuiltDrawingsStatus,\n\t\t\t\t\n\t\t\t\t'closeOutPhotosStatus': closeOutPhotosStatus,\n\t\t\t\t\n\t\t\t\t'HVACstartupFormStatus': HVACstartupFormStatus,\n\t\t\t\t'HVACstartupFormDate': HVACstartupFormDate,\n\t\t\t\t\n\t\t\t\t'alarmFormStatus': alarmFormStatus,\n\t\t\t\t\n\t\t\t\t'salvageStatus': salvageStatus,\n\t\t\t\t\n\t\t\t\t'verisaeReportStatus': verisaeReportStatus,\n\t\t\t\t\n\t\t\t\t'closeoutDocumentsNotes': closeoutDocumentsNotes,\n\t\t\t\t\n\t\t\t\t'salvageDate': salvageDate,\n\t\t\t\t'salvageAmount': salvageAmount,\n\t\t\t\t\n\t\t\t\t'substantialCompletionDate': substantialCompletionDate,\n\t\t\t\t'substantialCompletionStatus': substantialCompletionStatus,\n\t\t\t\t\n\t\t\t\t'paymentOfDebtsAndClaimsDate': paymentOfDebtsAndClaimsDate,\n\t\t\t\t'paymentOfDebtsAndClaimsStatus': paymentOfDebtsAndClaimsStatus,\n\t\t\t\t\n\t\t\t\t'releaseOfLiensDate': releaseOfLiensDate,\n\t\t\t\t'releaseOfLiensStatus': releaseOfLiensStatus,\n\t\t\t\t\n\t\t\t\t'mulvannySignOffDate': mulvannySignOffDate,\n\t\t\t\t'mulvannySignOffStatus': mulvannySignOffStatus,\n\t\t\t},\n\t\t\tsuccess:function(data){\n\t\t\t\tupdateFrontEnd();\t\t\t\n\t\t\t\t//getProject_PROJECT_MANAGER(projectID , 1);\n\t\t\t\talert('Project Saved');\n\t\t\t\tconsole.log(data);\n\t\t\t\t//UPDATE CLOSEOUT SUMMARY\n\t\t\t\t$('#closeoutData').find('#saveButton > button').prop('disabled', false);\n\t\t\t\tgoToProjectManager();\n\n\t\t\t},\n\t\t\t/*commented out because of error. Error dictates that their is a parse error and unexpected end of input. \n\t\t\t * Code works perfectly with error statement \n\t\t\t Need to figure out how to fix this error to work 100 percent correctly*/\n\t\t\t\n\t\t\t //error: function(XMLHttpRequest, textStatus, errorThrown) { \n\t\t\terror: function()\n\t\t\t{\n\t\t\t\talert('Project Saved');\n\t\t\t\t$('#closeoutData').find('#saveButton > button').prop('disabled', false);\n\t\t\t\t//UPDATE CLOSEOUT SUMMARY\n\t\t\t\t//getProject_PROJECT_MANAGER(projectID , 1);\n\t\t\t\tgoToProjectManager();\n\n\t\t\t //alert(\"Status: \" + textStatus); \n\t\t\t\t //alert(\"Error: \" + errorThrown);\n\t\t\t//error:function(xhr){\n\t\t\t\t//alert(xhr.responceText);\n\t\t\t\t//console.log(xhr.responseText);\n\t\t\t\t\t\t\t\n\t\t\t}\n\t\t});\n\n }\n \n}", "function saveProject_PERMIT()\n{\n console.log(\"Saving Permit Information\");\n\t\n var buildingPermitStatus = $('#permitData').find(\"#buildingPermitStatus\").val();\n var buildingPermitLastUpdated = $('#permitData').find(\"#buildingPermitLastUpdated\").val();\n var buildingInspectionStatus = $('#permitData').find(\"#buildingInspectionStatus\").val();\n var buildingInspectionLastUpdated = $('#permitData').find(\"#buildingInspectionLastUpdated\").val();\n \n var ceilingPermitStatus = $('#permitData').find(\"#ceilingPermitStatus\").val();\n var ceilingPermitLastUpdated = $('#permitData').find(\"#ceilingPermitLastUpdated\").val();\n var ceilingInspectionStatus = $('#permitData').find(\"#ceilingInspectionStatus\").val();\n var ceilingInspectionLastUpdated = $('#permitData').find(\"#ceilingInspectionLastUpdated\").val();\n \n var mechanicalPermitStatus = $('#permitData').find(\"#mechanicalPermitStatus\").val();\n var mechanicalPermitLastUpdated = $('#permitData').find(\"#mechanicalPermitLastUpdated\").val();\n var mechanicalInspectionStatus = $('#permitData').find(\"#mechanicalInspectionStatus\").val();\n var mechanicalInspectionLastUpdated = $('#permitData').find(\"#mechanicalInspectionLastUpdated\").val();\n \n var electricalPermitStatus = $('#permitData').find(\"#electricalPermitStatus\").val();\n var electricalPermitLastUpdated = $('#permitData').find(\"#electricalPermitLastUpdated\").val();\n var electricalInspectionStatus = $('#permitData').find(\"#electricalInspectionStatus\").val();\n var electricalInspectionLastUpdated = $('#permitData').find(\"#electricalInspectionLastUpdated\").val();\n \n var plumbingPermitStatus = $('#permitData').find(\"#plumbingPermitStatus\").val();\n var plumbingPermitLastUpdated = $('#permitData').find(\"#plumbingPermitLastUpdated\").val();\n var plumbingInspectionStatus = $('#permitData').find(\"#plumbingInspectionStatus\").val();\n var plumbingInspectionLastUpdated = $('#permitData').find(\"#plumbingInspectionLastUpdated\").val();\n \n var gasPermitStatus = $('#permitData').find(\"#gasPermitStatus\").val();\n var gasPermitLastUpdated = $('#permitData').find(\"#gasPermitLastUpdated\").val();\n var gasInspectionStatus = $('#permitData').find(\"#gasInspectionStatus\").val();\n var gasInspectionLastUpdated = $('#permitData').find(\"#gasInspectionLastUpdated\").val();\n \n var sprinklerPermitStatus = $('#permitData').find(\"#sprinklerPermitStatus\").val();\n var sprinklerPermitLastUpdated = $('#permitData').find(\"#sprinklerPermitLastUpdated\").val();\n var sprinklerInspectionStatus = $('#permitData').find(\"#sprinklerInspectionStatus\").val();\n var sprinklerInspectionLastUpdated = $('#permitData').find(\"#sprinklerInspectionLastUpdated\").val();\n \n var fireAlarmPermitStatus = $('#permitData').find(\"#fireAlarmPermitStatus\").val();\n var fireAlarmPermitLastUpdated = $('#permitData').find(\"#fireAlarmPermitLastUpdated\").val();\n var fireAlarmInspectionStatus = $('#permitData').find(\"#fireAlarmInspectionStatus\").val();\n var fireAlarmInspectionLastUpdated = $('#permitData').find(\"#fireAlarmInspectionLastUpdated\").val();\n \n var voltagePermitStatus = $('#permitData').find(\"#voltagePermitStatus\").val();\n var voltagePermitLastUpdated = $('#permitData').find(\"#voltagePermitLastUpdated\").val();\n var voltageInspectionStatus = $('#permitData').find(\"#voltageInspectionStatus\").val();\n var voltageInspectionLastUpdated = $('#permitData').find(\"#voltageInspectionLastUpdated\").val();\n \n var otherAPermitStatus = $('#permitData').find(\"#otherAPermitStatus\").val();\n var otherAPermitLastUpdated = $('#permitData').find(\"#otherAPermitLastUpdated\").val();\n var otherAInspectionStatus = $('#permitData').find(\"#otherAInspectionStatus\").val();\n var otherAInspectionLastUpdated = $('#permitData').find(\"#otherAInspectionLastUpdated\").val();\n \n var otherBPermitStatus = $('#permitData').find(\"#otherBPermitStatus\").val();\n var otherBPermitLastUpdated = $('#permitData').find(\"#otherBPermitLastUpdated\").val();\n var otherBInspectionStatus = $('#permitData').find(\"#otherBInspectionStatus\").val();\n var otherBInspectionLastUpdated = $('#permitData').find(\"#otherBInspectionLastUpdated\").val();\n\n var permitNotes = $('#permitData').find('#permitNotes').val();\n var inspectionNotes = $('#permitData').find('#inspectionNotes').val();\n \n console.log(permitNotes);\n console.log(inspectionNotes);\n \n var dates_PERMIT =[\n\t\t\t\tbuildingPermitLastUpdated, buildingInspectionLastUpdated,\n\t\t\t\tceilingPermitLastUpdated, ceilingInspectionLastUpdated,\n\t\t\t\tmechanicalPermitLastUpdated, mechanicalInspectionLastUpdated, \n\t\t\t\telectricalPermitLastUpdated, electricalInspectionLastUpdated,\n\t\t\t\tplumbingPermitLastUpdated, plumbingInspectionLastUpdated,\n\t\t\t\tgasPermitLastUpdated, gasInspectionLastUpdated,\n\t\t\t\tsprinklerPermitLastUpdated, sprinklerInspectionLastUpdated,\n\t\t\t\tfireAlarmPermitLastUpdated, fireAlarmInspectionLastUpdated,\n\t\t\t\tvoltagePermitLastUpdated, voltageInspectionLastUpdated,\n\t\t\t\totherAPermitLastUpdated, otherAInspectionLastUpdated,\n\t\t\t\totherBPermitLastUpdated, otherBInspectionLastUpdated,\n ];\n \n \n if(isValidInput_PERMIT(dates_PERMIT))\n {\n \tconsole.log(\"we got valid data now\");\n \t\n \tfor(var i = 0; i < dates_PERMIT.length; i++) {\n \t\tif(dates_PERMIT[i]) dates_PERMIT[i] = dateCleaner(dates_PERMIT[i]);\n \t\tif(i == 0) buildingPermitLastUpdated = dates_PERMIT[i];\n \t\tif(i == 1) buildingInspectionLastUpdated = dates_PERMIT[i];\n \t\tif(i == 2) ceilingPermitLastUpdated = dates_PERMIT[i];\n \t\tif(i == 3) ceilingInspectionLastUpdated = dates_PERMIT[i];\n \t\tif(i == 4) mechanicalPermitLastUpdated = dates_PERMIT[i];\n \t\tif(i == 5) mechanicalInspectionLastUpdated = dates_PERMIT[i];\n \t\tif(i == 6) electricalPermitLastUpdated = dates_PERMIT[i];\n \t\tif(i == 7) electricalInspectionLastUpdated = dates_PERMIT[i];\n \t\tif(i == 8) plumbingPermitLastUpdated = dates_PERMIT[i];\n \t\tif(i == 9) plumbingInspectionLastUpdated = dates_PERMIT[i];\n \t\tif(i == 10) gasPermitLastUpdated = dates_PERMIT[i];\n \t\tif(i == 11) gasInspectionLastUpdated = dates_PERMIT[i];\n \t\tif(i == 12) sprinklerPermitLastUpdated = dates_PERMIT[i];\n \t\tif(i == 13) sprinklerInspectionLastUpdated = dates_PERMIT[i];\n \t\tif(i == 14) fireAlarmPermitLastUpdated = dates_PERMIT[i];\n \t\tif(i == 15) fireAlarmInspectionLastUpdated = dates_PERMIT[i];\n \t\tif(i == 16) voltagePermitLastUpdated = dates_PERMIT[i];\n \t\tif(i == 17) voltageInspectionLastUpdated = dates_PERMIT[i];\n \t\tif(i == 18) otherAPermitLastUpdated = dates_PERMIT[i];\n \t\tif(i == 19) otherAInspectionLastUpdated = dates_PERMIT[i];\n \t\tif(i == 20) otherBPermitLastUpdated = dates_PERMIT[i];\n \t\tif(i == 21) otherBInspectionLastUpdated = dates_PERMIT[i];\n \t}\n\t\tvar action = \"editPermits\";\n\t\tvar PERMIT_ID = 0;\n\t\tif(PROJECT_DATA.permits != null)\n\t\t\tPERMIT_ID = PROJECT_DATA.permits.id;\n\t\telse\n\t\t\tPERMIT_ID = 0;\n\t\t\n\t\tif(!PROJECT_DATA || !PROJECT_DATA.id)\n\t\t{\n\t\t\talert(\"Server Error! (Project ID)\");\n\t\t\treturn;\n\t\t}\n\t\tif(!PERMIT_ID)\n\t\t{\n\t\t\talert(\"Server Error! (Permit ID)\");\n\t\t\treturn;\n\t\t}\n\t\t\n\t\t\n\t\t$.ajax({\n\t\t\ttype: 'POST',\n\t\t\turl: 'Project', \n\t//\t\tdataType: 'json',\n\t\t\tdata: \n\t\t\t{\n\t\t\t\t'domain': 'project',\n\t\t\t\t'action': action,\n\t\t\t\t'projectID':PROJECT_DATA.id,\n\t\t\t\t\n\t\t\t\t'permitsID':PERMIT_ID,\n\t\t\t\t\n\t\t\t\t'building_p':buildingPermitLastUpdated, \n\t\t\t\t'buildingPermitStatus': buildingPermitStatus,\n\t\t\t\t'buildingInspectionStatus': buildingInspectionStatus,\n\t\t\t\t'buildingInspectionLastUpdated': buildingInspectionLastUpdated,\n\t\t\t\t\n\t\t\t\t'mechanical_p' :mechanicalPermitLastUpdated,\n\t\t\t\t'mechanicalPermitStatus': mechanicalPermitStatus,\n\t\t\t\t'mechanicalInspectionStatus': mechanicalInspectionStatus,\n\t\t\t\t'mechanicalInspectionLastUpdated': mechanicalInspectionLastUpdated,\n\t\t\t\t\n\t\t\t\t'electrical_p':electricalPermitLastUpdated,\n\t\t\t\t'electricalPermitStatus': electricalPermitStatus,\n\t\t\t\t'electricalInspectionStatus': electricalInspectionStatus,\n\t\t\t\t'electricalInspectionLastUpdated': electricalInspectionLastUpdated,\n\t\t\t\t\n\t\t\t\t'plumbing_p':plumbingPermitLastUpdated,\n\t\t\t\t'plumbingPermitStatus': plumbingPermitStatus,\n\t\t\t\t'plumbingInspectionStatus': plumbingInspectionStatus,\n\t\t\t\t'plumbingInspectionLastUpdated': plumbingInspectionLastUpdated,\n\t\t\t\t\n\t\t\t\t'fireSprinkler_p':sprinklerPermitLastUpdated,\n\t\t\t\t'sprinklerPermitStatus': sprinklerPermitStatus,\n\t\t\t\t'sprinklerInspectionStatus': sprinklerInspectionStatus,\n\t\t\t\t'sprinklerInspectionLastUpdated': sprinklerInspectionLastUpdated,\n\t\t\t\t\n\t\t\t\t'fireAlarm_p':fireAlarmPermitLastUpdated, \n\t\t\t\t'fireAlarmPermitStatus': fireAlarmPermitStatus,\n\t\t\t\t'fireAlarmInspectionStatus': fireAlarmInspectionStatus,\n\t\t\t\t'fireAlarmInspectionLastUpdated': fireAlarmInspectionLastUpdated,\n\t\t\t\t\n\t\t\t\t'lowVoltage_p':voltagePermitLastUpdated,\n\t\t\t\t'voltagePermitStatus': voltagePermitStatus,\n\t\t\t\t'voltageInspectionStatus': voltageInspectionStatus,\n\t\t\t\t'voltageInspectionLastUpdated': voltageInspectionLastUpdated,\n\t\t\t\t\n\t\t\t\t'ceilingPermit': ceilingPermitLastUpdated,\n\t\t\t\t'ceilingPermitStatus': ceilingPermitStatus,\n\t\t\t\t'ceilingInspectionStatus': ceilingInspectionStatus,\n\t\t\t\t'ceilingInspectionLastUpdated': ceilingInspectionLastUpdated,\n\t\t\t\t\n\t\t\t\t'gasPermit': gasPermitLastUpdated,\n\t\t\t\t'gasPermitStatus': gasPermitStatus,\n\t\t\t\t'gasInspectionStatus': gasInspectionStatus,\n\t\t\t\t'gasInspectionLastUpdated': gasInspectionLastUpdated,\n\t\t\t\t\n\t\t\t\t'otherPermitA': otherAPermitLastUpdated,\n\t\t\t\t'otherAPermitStatus': otherAPermitStatus,\n\t\t\t\t'otherAInspectionStatus': otherAInspectionStatus,\n\t\t\t\t'otherAInspectionLastUpdated': otherAInspectionLastUpdated,\n\t\t\t\t\n\t\t\t\t'otherBPermit': otherBPermitLastUpdated,\n\t\t\t\t'otherBPermitStatus': otherBPermitStatus,\n\t\t\t\t'otherBInspectionStatus': otherBInspectionStatus,\n\t\t\t\t'otherBInspectionLastUpdated': otherBInspectionLastUpdated,\n\n\t\t\t\t'permitNotes': permitNotes,\n\t\t\t\t'inspectionNotes': inspectionNotes,\n\t\t\t},\n\t\t\tsuccess:function(data){\n\t\t\t\tconsole.log(data);\n\t\t\t\tupdateFrontEnd();\n\t\t\t\talert('Save Complete!');\n\t\t\t\t\n\t\t\t\t\n\t\t\t\t//getProject_PROJECT_MANAGER(projectID , 1);\n\t\t\t\t/*\n\t\t\t\t$('#permitData').find('#saveButton > button').prop('disabled', false);\n\t\t\t\t$('#permitData').find('.active').removeClass('active');\n\t\t\t\t$('#permitData').find('#buildingPermit').addClass('active');\n\n\t\t\t\t$(\".editProject\").hide();\n\t\t\t\t$(\"#projectManager\").show();\n\t\t\t\t*/\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tgoToProjectManager();\n\n\t\t\t},\n\t\t\t/*commented out because of error. Error dictates that their is a parse error and unexpected end of input. \n\t\t\t * Code works perfectly with error statement \n\t\t\t Need to figure out how to fix this error to work 100 percent correctly*/\n\t\t\t\n\t\t\t //error: function(XMLHttpRequest, textStatus, errorThrown) { \n\t\t\terror: function(data)\n\t\t\t{\n\t\t\t\tconsole.log(data);\n\t\t\t\tupdateFrontEnd();\n\t\t\t\t//getProject_PROJECT_MANAGER(projectID , 1);\n\t\t\t\talert('Save Complete!');\n\t\t\t\t/*\n\t\t\t\t$('#permitData').find('#saveButton > button').prop('disabled', false);\n\t\t\t\t$('#permitData').find('.active').removeClass('active');\n\t\t\t\t$('#permitData').find('#buildingPermit').addClass('active');\n\n\t\t\t\t$(\".editProject\").hide();\n\t\t\t\t$(\"#projectManager\").show();\n\t\t\t\t*/\n\t\t\t\tgoToProjectManager();\n\t\t\t\n\t\t\t\t\n\t\t\t}\n\t\t});\n } \n}", "function saveProject(op, loc){\n\t\tvar projData; //, processMessage;\n\t\tconsole.log('op: ' + op);\n\t\tconsole.log('loc: ' + loc);\n\t\t//$(\"#saving\").show();\n\t\t$(\"#saving\").modal('show');\n\t\tif (op == 'edit'){\n\t\t\tconsole.log('Edit Project - ' + op);\n\t\t\t//$('#form-edit-project #process-type').val(op);\n\t\t\tprojData = $('form#form-edit-project').serialize();\n\t\t\tprojectID = $('form#form-edit-project #project-id').val();\n\t\t\tprojectTitle = $('form#form-edit-project #project-title').val();\n\t\t} else if (op == 'add'){\n\t\t\tconsole.log('Add Project - ' + op);\n\t\t\t//$('#form-add-project #process-type').val(op);\n\t\t\tprojData = $('form#form-add-project').serialize();\n\t\t\tprojectTitle = $('form#form-add-project #project-title').val();\n\t\t} else if (op == 'del') {\n\t\t\tconsole.log('Delete Project - ' + op);\n\t\t\t$('#form-edit-project #process-type').val('d');\n\t\t\tprojData = $('form#form-edit-project').serialize();\n\t\t\tprojectID = $('form#form-edit-project #project-id').val();\n\t\t\tprojectTitle = $('form#form-edit-project #project-title').val();\n\t\t}\n\t\t\n\t\t$.ajax({\n\t\t\ttype : \"POST\",\n\t\t\turl : \"assets/php-custom/process-project.php\",\t// save project first\n\t\t\tdata : { proj : projData, locn : loc },\t// locn indicates whether to process locations or not\n\t\t\tsuccess\t: function (msg) {\n\t\t\t\tconsole.log(op + ' project - SUCCESS; Locations: ' + loc);\n\t\t\t\teditProjectFormState = \"hidden\";\n\t\t\t\t//console.log('msg: ' + msg);\n\t\t\t\t//console.log('projectTitle: ' + projectTitle);\n\t\t\t\t//processMessage = msg;\n\t\t\t\tif (loc == 1){ // true\n\t\t\t\t\t$(\"#map-location-msg\").html(msg);\n\t\t\t\t\tsidebar.open('locations');\n\t\t\t\t\t$('#locations').trigger('showpane');\n\t\t\t\t\t$('#mapTabs a[href=\\'#map-location-info\\']').tab('show');\n\t\t\t\t\tif (op == 'edit') {\t// if edit project and add/edit locations\n\t\t\t\t\t\tconsole.log('edit locations');\n\t\t\t\t\t\teditLocations (projectID, projectTitle);\t// use current project ID and title\n\t\t\t\t\t} else if (op == 'add'){\t// if add project and add locations\n\t\t\t\t\t\tconsole.log('add locations');\n\t\t\t\t\t\taddLocations (projectID, projectTitle);\n\t\t\t\t\t} else if (op == 'del'){\n\t\t\t\t\t\tconsole.log('delete project');\n\t\t\t\t\t\t//$(\"#map-project-msg\").empty().html(msg);\n\t\t\t\t\t}\n\t\t\t\t} else if (loc == 0) { // false\n\t\t\t\t\tconsole.log('save project only');\n\t\t\t\t\tconsole.log(msg);\n\t\t\t\t\tconsole.log('op: ' + op);\n\t\t\t\t\tif (op != 'del'){\n\t\t\t\t\t\tconsole.log('here');\n\t\t\t\t\t\t$(\"#map-project-msg\").empty().html(msg);\n\t\t\t\t\t\t$('#map-project-details').empty().load(\"./assets/php-custom/view-project.php?p=\" + projectID);\n\t\t\t\t\t\t$(\"#projects-add\").empty().load(\"./assets/php-custom/add-project.php\", function() {\n\t\t\t\t\t\t\tloadTooltips();\n\t\t\t\t\t\t});\n\t\t\t\t\t\tsidebar.open('locations');\n\t\t\t\t\t\t$('#locations').trigger('showpane');\n\t\t\t\t\t\t$('#mapTabs a[href=\\'#map-project-info\\']').tab('show');\n\t\t\t\t\t} else {\n\t\t\t\t\t\tconsole.log('delete project');\n\t\t\t\t\t\t$(\"#map-project-msg\").empty().html(msg);\n\t\t\t\t\t\t//reloadPanes();\n\t\t\t\t\t\t//sidebar.open('database')\n\t\t\t\t\t\tvar deleteProjectActionButtons = '<div class=\"btn-group\" role=\"group\">' +\n\t\t\t\t\t\t\t\t'<button type=\"button\" id=\"del-proj-btn-all-proj\" class=\"btn btn-sm btn-default\" onclick=\"$(\\'#del-proj-btn-all-proj\\').tooltip(\\'destroy\\'); reloadPanes();\" data-toggle=\"tooltip\" data-placement=\"top\" title=\"View the list of all projects\">View All Projects</button>' +\n\t\t\t\t\t\t\t'</div>'+ \n\t\t\t\t\t\t\t'<div class=\"btn-group\" role=\"group\">' +\n\t\t\t\t\t\t\t\t'<button type=\"button\" id=\"del-proj-btn-add-proj\" class=\"btn btn-sm btn-default\" onclick=\"$(\\'#del-proj-btn-add-proj\\').tooltip(\\'destroy\\'); $(\\'#projectsTabs a[href=/\\'#projects-add/\\']\\').tab(\\'show\\'); return false;\" data-toggle=\"tooltip\" data-placement=\"top\" title=\"Add a new project\">Add Project</button>' +\n\t\t\t\t\t\t\t'</div>';\n\t\t\t\t\t\t$(\"#map-project-details\").empty().html(deleteProjectActionButtons);\n\t\t\t\t\t\tloadTooltips();\n\t\t\t\t\t\t$('#projectsTabs a[href=\\'#projects\\']').tab('show');\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t$('#btn-edit-proj-save').tooltip('hide');\n\t\t\t\t//$(\"#saving\").hide();\n\t\t\t\t$(\"#saving\").modal('hide');\n\t\t\t},\n\t\t\terror\t\t: function () {\n\t\t\t\tconsole.log(\"Edit Project - Save - FAILED\");\n\t\t\t}\n\t\t});\n\n\t}", "function saveAsProgramToServer() {\n $formSingleModal.validate();\n if ($formSingleModal.valid()) {\n $('.modal').modal('hide'); // close all opened popups\n var xml = Blockly.Xml.workspaceToDom(blocklyWorkspace);\n var xmlText = Blockly.Xml.domToText(xml);\n var progName = $('#singleModalInput').val().trim();\n LOG.info('saveAs program ' + GUISTATE_C.getProgramName());\n PROGRAM.saveAsProgramToServer(progName, GUISTATE_C.getProgramTimestamp(), xmlText, function(result) {\n UTIL.response(result);\n if (result.rc === 'ok') {\n result.name = progName;\n result.programShared = false;\n GUISTATE_C.setProgram(result);\n MSG.displayInformation(result, \"MESSAGE_EDIT_SAVE_PROGRAM_AS\", result.message, GUISTATE_C.getProgramName());\n }\n });\n }\n }", "function saveToServer() {\n $('.modal').modal('hide'); // close all opened popups\n var xml = Blockly.Xml.workspaceToDom(blocklyWorkspace);\n var xmlText = Blockly.Xml.domToText(xml);\n PROGRAM.saveProgramToServer(GUISTATE_C.getProgramName(), GUISTATE_C.getProgramShared() ? true : false, GUISTATE_C.getProgramTimestamp(), xmlText, function(\n result) {\n if (result.rc === 'ok') {\n GUISTATE_C.setProgramTimestamp(result.lastChanged);\n GUISTATE_C.setProgramSaved(true);\n LOG.info('save program ' + GUISTATE_C.getProgramName());\n }\n MSG.displayInformation(result, \"MESSAGE_EDIT_SAVE_PROGRAM\", result.message, GUISTATE_C.getProgramName());\n });\n }", "function saveToServer() {\n if (userState.program) {\n var xml = Blockly.Xml.workspaceToDom(blocklyWorkspace);\n var xmlText = Blockly.Xml.domToText(xml);\n $('.modal').modal('hide'); // close all opened popups\n PROGRAM.saveProgramToServer(userState.program, userState.programShared, userState.programTimestamp, xmlText, function(result) {\n if (result.rc === 'ok') {\n $('#menuSaveProg').parent().addClass('disabled');\n blocklyWorkspace.robControls.disable('saveProgram');\n userState.programSaved = true;\n LOG.info('save program ' + userState.program + ' login: ' + userState.id);\n userState.programTimestamp = result.lastChanged;\n }\n MSG.displayInformation(result, \"MESSAGE_EDIT_SAVE_PROGRAM\", result.message, userState.program);\n });\n }\n }", "function saveAsProgramToServer() {\n $formSingleModal.validate();\n if ($formSingleModal.valid()) {\n var xml = Blockly.Xml.workspaceToDom(blocklyWorkspace);\n var xmlText = Blockly.Xml.domToText(xml);\n var progName = $('#singleModalInput').val().trim();\n LOG.info('saveAs program ' + userState.program + ' login: ' + userState.id);\n PROGRAM.saveAsProgramToServer(progName, userState.programTimestamp, xmlText, function(result) {\n UTIL.response(result);\n if (result.rc === 'ok') {\n ROBERTA_USER.setProgram(progName);\n $('#menuSaveProg').parent().addClass('disabled');\n blocklyWorkspace.robControls.disable('saveProgram');\n userState.programSaved = true;\n userState.programTimestamp = result.lastChanged;\n MSG.displayInformation(result, \"MESSAGE_EDIT_SAVE_PROGRAM_AS\", result.message, userState.program);\n }\n });\n }\n }", "function MPUBORD_Save () {\n console.log(\"=== MPUBORD_Save =====\") ;\n\n if (permit_dict.permit_submit_orderlist) {\n mod_MPUBORD_dict.step += 1;\n\n const upload_dict = {\n table: \"orderlist\",\n now_arr: get_now_arr()\n };\n\n\n if (mod_MPUBORD_dict.step === 1){\n UploadChanges(upload_dict, urls.url_orderlist_request_verifcode);\n } else if (mod_MPUBORD_dict.step === 3){\n\n upload_dict.mode = \"submit_save\";\n upload_dict.verificationcode = el_MPUBORD_input_verifcode.value\n upload_dict.verificationkey = mod_MPUBORD_dict.verificationkey;\n\n upload_dict.mode = \"submit_save\";\n\n upload_dict.send_email = !!el_MPUBORD_send_email.checked;\n\n UploadChanges(upload_dict, urls.url_orderlist_publish);\n };\n MPUBORD_SetInfoboxesAndBtns() ;\n } ;\n }", "function closeCurrentProject(bSave){\r if(!bSave){\r app.project.close(CloseOptions.DO_NOT_SAVE_CHANGES)\r }else{\r app.project.close(CloseOptions.SAVE_CHANGES)\r }\r }", "function saveBracket() {\n //Only save the bracket if something is onscreen\n if(currentStat !== \"\") {\n let userName = document.getElementById(\"save-user-name\").value;\n //Tell server which stat was used to generate the current bracket;\n //when loading from server, it will be user to recreate the bracket\n const message = { \"name\": userName, \"stat\" : currentStat };\n const fetchOptions = {\n method : 'POST',\n headers : {\n 'Accept' : 'application/json',\n 'Content-Type' : 'application/json'\n },\n body : JSON.stringify(message)\n };\n let url = siteUrl;\n //Post the new bracket (as JSON) onto the server\n fetch(url, fetchOptions)\n .then(checkStatus)\n .then(function(responseText) {\n //Show success message to user\n displayError(responseText);\n })\n .catch(function(error) {\n //Tell user that bracket did not properly save\n displayError(error);\n });\n }\n }", "_saveToServer(projects) {\n // TODO: not sure this is necessary if I'll be updating the server\n // instruction by instruction.\n return;\n }", "function editCloseout (source_id) {\n\tif(source_id) prepareCloseout(source_id);\n\tdocument.getElementById(\"projectManager\").style.display = 'none';\n\tEDIT_INTENTION = true;\n\tgetProjectEnums_CLOSEOUT(true);\n\tcurrentDivLocation = \"closeoutData\";\n\tdocument.getElementById(\"closeoutData\").style.display = 'inline';\n\n\t//window.location.href = PROJECT_CLOSEOUT + '?id=' + projectID;\n}", "function _saveProjectDetail() {\n if ($scope.projectForm.$valid) {\n $scope.project.startdate = $scope.project.startdateCn;\n $scope.project.enddate = $scope.project.enddateCn;\n serverRequestService.serverRequest(ADD_EDIT_PROJECT_CTRL_API_OBJECT.createNewProject, 'POST', $scope.project).then(function(res) {\n serverRequestService.showNotification('success', 'Porject Save successfully', 'Save', 2000);\n $mdDialog.cancel();\n }, function(res) {\n angular.forEach(res.result.errors, function(value) {\n serverRequestService.showNotification('error', value.message, value.path, 4000);\n });\n });\n } else {\n $scope.projectForm.$setSubmitted();\n }\n }", "function saveProject(mode = 0, dataA = \"\", dataB = \"\", dataC = \"\", kw = [], notes = [], done = false, country = \"\", lang = \"\") { \n\n // NEED TO CALL GETSETTINGS!!!! \n logger.debug(\"saveProject\");\n var file_source = window.currentFile;\n var proj_name = window.currentProject;\n var window_json = window.currentFileContent;\n var current_event = window.currentEvent;\n\n if ((file_source === undefined) || (proj_name === undefined) || (window_json === undefined)) {\n logger.error(\"Unable to save project, because current file, project name or file contents(JSON) is undefined!\");\n return;\n }\n // just writing down if we have open event in the edit-view\n if (current_event === undefined) {\n logger.info(\"No event open in edit-view while saving...\");\n // we can only save notes....\n }\n else {\n logger.info(\"Event '\"+current_event+\"' open in edit-view while saving...\");\n }\n\n var backup_base = path.join(remote.app.getPath(\"userData\"), \"backup_files\");\n // trying to create backup directory if not already existing\n try {\n if (!fs.existsSync(backup_base)) {\n fs.mkdirSync(backup_base);\n }\n else if (!fs.statSync(backup_base).isDirectory()) {\n // not directory\n logger.error(\"Backup location not a directory! Creating new...\");\n fs.mkdirSync(backup_base);\n }\n } catch (err) {\n logger.error(\"Unable to create backup directory! Reason: \" + err.message);\n return;\n }\n\n var config_opt = {\n name: \"app-configuration\",\n cwd: remote.app.getPath('userData')\n }\n //\n var config_store = new Store(config_opt);\n\n // discard backups. we are not saving any changes, nor are keeping backups\n if (mode === 2) {\n logger.info(\"Not saving changes! Removing backups without saving to file...\");\n try {\n fs.unlinkSync(path.join(backup_base, proj_name + \".json\"));\n config_store.set(\"edits\", [false, null]);\n $(\"#save-cur-edits-btn\").addClass(\"w3-disabled\");\n $(\"#save-cur-edits-btn\").attr('disabled', 'disabled');\n $(\"#preview-cur-edits-title\").text(\"No pending changes\");\n $(\"#preview-cur-edits-title\").css(\"background-color\", \"lightgreen\");\n } catch (err) {\n logger.error(\"Unable to remove backup file! Reason: \" + err.message);\n return;\n }\n return;\n }\n\n var backup_opt = {\n defaults: window_json,\n name: proj_name,\n cwd: backup_base\n }\n var backup_store = new Store(backup_opt);\n\n // basics set up, now adding new data to window-variable....\n window_json[\"notes\"] = notes; // saving notes, if nothing else can be saved\n if (current_event !== undefined) {\n logger.info(\"Because window.currentEvent is not undefined, now saving all data into window.currentFileContent\");\n if (window_json[\"project-files\"].hasOwnProperty(current_event)) {\n window_json[\"project-files\"][current_event][\"a\"] = dataA;\n window_json[\"project-files\"][current_event][\"b\"] = dataB;\n window_json[\"project-files\"][current_event][\"c\"] = dataC;\n window_json[\"project-files\"][current_event][\"country\"] = country;\n window_json[\"project-files\"][current_event][\"lang\"] = lang;\n window_json[\"project-files\"][current_event][\"kw\"] = kw;\n window_json[\"project-files\"][current_event][\"done\"] = done;\n } else {\n //\n logger.error(\"Window.currentFileContent variable doesn't have 'current_event' property! Unable to save!\");\n }\n } else {\n logger.warn(\"Current_event undefined! No event currently open!\");\n }\n\n //intUtils.sectionUtils.clearCsectionUI(); // is this needed?\n\n // adding new json version into window-variable and backup\n window.currentFileContent = window_json;\n backup_store.store = window_json;\n logger.info(\"successfully saved new data into window-variable and backup file for project '\" + proj_name + \"'!\");\n \n config_store.set(\"edits\", [true, file_source])\n $(\"#save-cur-edits-btn\").removeClass(\"w3-disabled\");\n $(\"#save-cur-edits-btn\").removeAttr('disabled', 'disabled');\n $(\"#preview-cur-edits-title\").text(\"There are pending changes!\");\n $(\"#preview-cur-edits-title\").css(\"background-color\", \"yellow\");\n //testing if mode 1 has beens set (write to actual file, and remove backup)\n if (mode === 1) {\n logger.info(\"Saving into actual project file '\"+file_source+\"'!\");\n // need to write to the actual file... and set \"edits\" value to [false, null]\n\n try {\n //\n fs.writeFileSync(file_source, JSON.stringify(window_json), \"utf8\");\n fs.unlinkSync(path.join(backup_base, proj_name + \".json\"));\n config_store.set(\"edits\", [false, null]);\n $(\"#save-cur-edits-btn\").addClass(\"w3-disabled\");\n $(\"#save-cur-edits-btn\").attr('disabled', 'disabled');\n $(\"#preview-cur-edits-title\").text(\"No pending changes\");\n $(\"#preview-cur-edits-title\").css(\"background-color\", \"lightgreen\");\n } catch (err) {\n logger.error(\"Unable to write new source file or remove backup file! Reason: \" + err.message);\n return;\n }\n logger.info(\"Backup file successfully removed, and changes saved!\");\n }\n \n}", "function goalModalSave (){\n let description = document.getElementById('goalDescModal');\n let start = document.getElementById('goalStartModal'); \n let freqNum = document.getElementById('goalFreqModal');\n let denomination = document.getElementById('goalDenoModal');\n let until = document.getElementById('goalUntilModal'); \n let type = document.getElementById('goalTypeModal');\n let reminder = document.getElementById('goalRemiModal');\n \n console.log( 'description', description.value, '\\nstart', start.value, '\\ntype', type.value, '\\nfreqNum', freqNum.value, '\\ndenomination', denomination.value, '\\nuntil', until.value, '\\nreminder', reminder.value);\n // Make sure date until is filled out \n if ( description.value != '' && start.value != '' && until.value != '' ){\n // Turn date until into moment object to format for adding or updating avenue in initiative object and ui\n let startDate = moment(start.value, 'YYYY-MM-DD', true); \n let untilDate = moment(until.value, 'YYYY-MM-DD', true); \n // Make sure that until date is not before start date\n if ( startDate.isSameOrBefore(untilDate) ) {\n // Add goal to initiative object and initative tab. \n let goalId = addGoal('modalAdd', '', startDate.toString(), freqNum.value, denomination.value, untilDate.toString(), type.value, reminder.value, description.value); // use Moment date format\n \n // Generate linked avenues in initiative object\n currentInitiative.goal_generate_aves(goalId);\n // Load avenues to both message manager and initiative tab\n let goal = currentInitiative.goals.get(goalId);\n for ( id of goal.linked_aves ){\n console.log('ave id for ave ui load on goal generation', id);\n addAve('goalGen', id ); // Event is used to change ui options depending on type of add\n };\n\n // Save everything to main\n let ipcInit = currentInitiative.pack_for_ipc();\n ipc.send('save', currentInitiativeId, ipcInit);\n // Close modal\n goalModal.style.display = \"none\";\n // Reset modal\n description.value = '';\n freqNum.value = 1;\n let i, L= denomination.options.length - 1;\n for(i = L; i >= 0; i--) {\n denomination.remove(i);\n };\n start.value = '';\n until.value = '';\n i = 0;\n L = type.options.length - 1;\n for(i = L; i >= 0; i--) {\n type.remove(i);\n };\n reminder.value = '';\n // Reset backgroup of date until incase they had been changed on unfilled attempt to save\n description.style.backgroundColor = 'rgb(245, 245,230)';\n start.style.backgroundColor = 'rgb(245, 245,230)';\n until.style.backgroundColor = 'rgb(245, 245,230)';\n } else { // If date until is before start date change backgrounds\n until.style.backgroundColor = 'rgb(225, 160, 140)';\n start.style.backgroundColor = 'rgb(225, 160, 140)';\n };\n } else { // Change backgroup of date or description if not filled out \n if (description.value == ''){\n description.style.backgroundColor = 'rgb(225, 160, 140)';\n };\n if (until.value == ''){\n until.style.backgroundColor = 'rgb(225, 160, 140)';\n };\n if (start.value == ''){\n start.style.backgroundColor = 'rgb(225, 160, 140)';\n };\n };\n }", "function saveProjectConfiguration() {\n println('Save Project Configuration ...')\n\n var validateInput = true\n\n var projectname = getHTMLValue(\"projectname\");\n if(isEmpty(projectname)) {\n validateInput = false \n }\n \n var projectdetails = getHTMLValue(\"projectdetails\");\n if(isEmpty(projectdetails)) {\n validateInput = false \n }\n \n var projecttype = getHTMLValue(\"projecttype\");\n if(isEmpty(projecttype)) {\n validateInput = false \n }\n\n var projectserver = getHTMLValue(\"projectserver\");\n if(isEmpty(projectserver)) {\n validateInput = false \n }\n \n // Check Validation \n if(validateInput) {\n\n println(projectname)\n println(projectdetails)\n println(projecttype)\n println(projectserver)\n\n // Update Database\n let dbData = {}\n dbData['NAME'] = projectname\n dbData['DETAILS'] = projectdetails\n dbData['TYPE'] = projecttype\n dbData['SERVER'] = projectserver\n\n setNewDocument(getFirestorePath('BASEPATH'),project_name,dbData,'Project Configuration Updated !!')\n\n\n } else {\n println('Validation FAILED !!')\n\n toastMsg('MESSAGE ', 'PROJECT : Please provide all field details !!')\n }\n\n\n}", "function applyParams() \n{\n // Get the current values from the UI and set the values.\n intNoofDays = document.myForm.numDays.value;\n // Get the current values from the UI and set the values. \n testServer = document.myForm.otherLocation.value;\n \n //Validate the inputs\n if (DAYS_MODIFIED_OBJ.getSelectedIndex() == 0)\n {\n if (!validateInput())\n return;\n }\n \n //Validate Testing Server\n if (document.myForm.ViewPath[1].checked)\n {\n if (!validateTestServer())\n\t{ \t\n document.myForm.otherLocation.select();\n\t document.myForm.otherLocation.focus();\n\t return;\t\n\t}\n }\n\n PREF_OBJ.set(); \n PREF_OBJ.save(); \n window.close();\n}", "function closeSettings(shouldSave) {\n if (shouldSave) {\n //If the inputs should be saved set them to the variables\n fSpacing = parseFloat(document.getElementById(\"spacingInput\").value);\n fSmoothing = parseFloat(document.getElementById(\"smoothingInput\").value);\n fMaxSpeed = parseFloat(document.getElementById(\"maxSpeedInput\").value);\n fMinSpeed = parseFloat(document.getElementById(\"minSpeedInput\").value);\n fMaxAcceleration = parseFloat(document.getElementById(\"maxAccelerationInput\").value);\n fMaxDeceleration = parseFloat(document.getElementById(\"maxDecelerationInput\").value);\n fTurnSpeed = parseFloat(document.getElementById(\"turnSpeedInput\").value);\n\n //Update the display\n update();\n\n //Close the main menu\n closeMenu();\n }\n\n //Set the settings menu to be hidden\n setVisibility(document.getElementById(\"settingsPopup\"), false);\n}", "function savePopup(f_as)\n{\n if (initialPopName != \"\" && initialPopName != getPopDescription()) {\n\t\t\tvar nameHasChanged = confirm (lab_arr[117]+\"\\n\\n\"+lab_arr[118]+\"\\n\\n'\"+initialPopName+\"'\\n\\n\\n\"+lab_arr[119]+\"\\n\"+lab_arr[120]+\". \");\n\t\t\tif (!nameHasChanged) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t\tneedToSaveChanges=false;\n\t\tdoMouseOut(dynmenu1,0);\n //send the current page name in order to open the popup after save on this page \n\t if (current_div_index!=\"\") {\n\t \tdocument.frm.currentpagename.value = listPages[current_div_index].page_name;\n\t }\n\t \n\t \n\t var war_str = \"\";\n\t \n\t \n\t if (!f_as && popType ==\"OUT\") {//click on save for outbopund popup\n\t \t\tif (popupObjects[0].propList['TablesList'].arrMulti.length ==0) { //the user shoudl add a calling list table\n\t \t\t\twar_str = \"- \"+lab_arr[75]+\"\\n\";\n\t \t\t}\n\n\t\t\t//test wheter mandatory fields of the calling list table are all added to pages\n\t\t\t\n\t \t\tvar f_exist = 0;\n\t \t\tvar mywar = \"\";\n\t \t\tfor (var i=0; i < arr_outbound.length ; i++) {\n\t \t\t f_exist = 0;\n\t \t\t for (var j=0; j <listPages.length && f_exist==0; j++) { \n\t\t\t\tvar pobj = listPages[j].listObj;\n\t\t\t\t if (pobj.length > 0) {\n\t\t\t\t \tfor (var k=0 ; k < pobj.length && f_exist==0 ; k++) {\n\t\t\t\t \t\tif (pobj[k].fdelete ==0 && getPropertyValueWithIndex(\"Field\",j,k)==arr_outbound[i] ) {\n\t\t\t\t \t\t\tf_exist = 1;\n\t\t\t\t \t\t}\n\t\t\t\t \t}\n\t\t\t\t }\n\t\t\t\t}\t\n\t \t\t \t\n\t \t\t \tif (f_exist==0) {\n\t \t\t \t\tif (mywar==\"\") {mywar=lab_arr[76]+\":\\n - \"+arr_outbound[i]+\"\\n\";} else {\n\t \t\t \t\t\tmywar += \" - \"+arr_outbound[i]+\"\\n\";\n\t \t\t \t\t}\n\t \t\t \t}\n\t \t\t}\n\t \t\t\n\t \t\twar_str += mywar;\n\t\n\t\t}\n\t if (war_str!=\"\") {\n\t \talert(lab_arr[87]+\"\\n\\n\"+war_str);\n\t }\n\n//\t alert(\"code to run on save or change state - set inner html for hideloading and set visible\");\n\t\tif (difstate == 1) {\n\t\t\tdocument.getElementById(\"progressBar\").innerHTML = lab_arr[121]+\"<br /><br />\"+lab_arr[122]+\".\";\n\t\t\tdocument.getElementById(\"hideloading\").style.display=\"\";\n\n\t\t}else{\n\t\t\tdocument.getElementById(\"progressBar\").innerHTML = lab_arr[123]+\"<br /><br />\"+lab_arr[122]+\".\";\n\t \t\tdocument.getElementById(\"hideloading\").style.display=\"\";\n\n\t\t}\n\t\tforSaveAs = f_as;\n\t\tvar waiting = setTimeout(\"doXml()\",1); // allow pause for previous line to complete action before continuing\n\t\t\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Initialization of the module. This loads `site.json` at the root of the project and calls the follow on functions to generate the pages.
function init() { fse .readJson('./site.json') .then(function(site) { // if the destination dir exists if (fse.pathExistsSync(config.baseDir)) { // clean it out before writing files fse.emptyDirSync(config.baseDir); } else { // ensure the destination dir exists fse.ensureDirSync(config.baseDir); } // copy assets in `/media` copyDirectory(config.mediaRoot, config.baseDir); // builds the CSS and JS bundles buildBundles(site.bundles); // generates the pages buildPages(site.pages); // clean up removeJSBundles(); }) .catch(function(err) { console.error('Error thrown while loading JSON', err); }); }
[ "function init() {\n fse\n .readJson('./site.json')\n .then(function(site) {\n // if the destination dir exists\n if (fse.pathExistsSync(config.baseDir)) {\n // clean it out before writing files\n fse.emptyDirSync(config.baseDir);\n } else {\n // ensure the destination dir exists\n fse.ensureDirSync(config.baseDir);\n }\n\n // copy assets in `/media`\n utils.copyDirectory(config.mediaRoot, config.baseDir);\n\n // builds the CSS and JS bundles\n bundler.buildBundles(site.bundles);\n\n // generated pages using glob.\n const metaJSONArray = glob.sync('live-examples/**/meta.json', {});\n for (const metaJson of metaJSONArray) {\n const file = fse.readJsonSync(metaJson);\n pageBuilder.buildPages(file.pages);\n }\n\n // clean up\n utils.removeJSBundles();\n // done\n console.log('Pages built successfully'); // eslint-disable-line no-console\n })\n .catch(function(err) {\n console.error('Error thrown while loading JSON', err);\n });\n}", "loadPages() {\n this._pages = utility.getJSONFromFile(this._absoluteFile);\n }", "async init() {\n const {transports, formats, fetchers, pages} = this.config;\n await this._initSubmodule('transport', transports);\n await this._initSubmodule('format', formats);\n await this._initSubmodule('fetcher', fetchers);\n this._initPages(pages);\n }", "function init() {\n $.getJSON('content.json', function (data) {\n slides = data.slides;\n var tmpl_selector;\n var slide;\n destinationSlide = getSlideNumberFromHash(document.location.hash);\n currentSlide = destinationSlide;\n setTitle();\n for (var i = 0, len = slides.length; i < len; i++) {\n tmpl_selector = '#' + slides[i].type + '-template';\n slide = $(tmpl_selector).tmpl(slides[i]).appendTo('#main');\n if (i == destinationSlide) {\n slide.addClass('current');\n }\n else if (i < destinationSlide) {\n slide.addClass('previous');\n }\n else {\n slide.addClass('next');\n }\n }\n showSlideNumbers();\n //syntax highlighting\n hljs.tabReplace = ' ';\n hljs.initHighlighting();\n });\n }", "function initPages() {\n // Initialize the pages which may be dependent upon some of the data.\n\tpageStack[0] = pages.loading;\n\t\n\tfor (p in pages) {\n\t\tvar pg = pages[p];\n\t\tif (typeof (pg.init) == \"function\") {\n\t\t\tpg.init();\n\t\t}\n\t}\n}", "function Initialize()\n\t{\n\t\tfetchGlobalVars();\n\t\tPageSetup();\n\t}", "function initLunr() {\r\n // First retrieve the index file\r\n $.getJSON(\"/index.json\")\r\n .done(function (index) {\r\n pagesIndex = index;\r\n lunrIndex = lunr(function () {\r\n this.field(\"title\", { boost: 10 });\r\n this.field(\"tags\", { boost: 5 });\r\n this.field(\"summary\");\r\n this.ref(\"uri\");\r\n\r\n pagesIndex.forEach(function (page) {\r\n this.add(page)\r\n }, this)\r\n });\r\n })\r\n .fail(function (jqxhr, textStatus, error) {\r\n var err = textStatus + \", \" + error;\r\n console.error(\"Error getting Hugo index file:\", err);\r\n });\r\n}", "function init() {\n var promise = PageService.findAllPagesForWebsite(websiteId);\n promise\n .success(function(pages) {\n vm.pages = pages;\n })\n }", "async function initializePage() {\n loadProjectsContainer();\n loadCalisthenicsContainer();\n loadCommentsContainer();\n}", "function initLunr() {\n // First retrieve the index file\n $.getJSON(\"/js/lunr/PagesIndex.json\")\n .done(function(index) {\n pagesIndex = index;\n //console.log(\"index:\", pagesIndex);\n\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.field(\"title\", {\n boost: 10\n });\n this.field(\"tags\", {\n boost: 5\n });\n this.field(\"content\", {\n boost: 1\n });\n\n // ref is the result item identifier (I chose the page URL)\n this.ref(\"href\");\n });\n\n // Feed lunr with each file and let lunr actually index them\n pagesIndex.forEach(function(page) {\n lunrIndex.add(page);\n });\n })\n .fail(function(jqxhr, textStatus, error) {\n var err = textStatus + \", \" + error;\n console.error(\"Error getting Hugo index flie:\", err);\n });\n}", "async function main() {\n await loadAllPages();\n routes = {\n '': home,\n 'home': home,\n 'index.html': home,\n 'music': music,\n 'videos': videos,\n 'gallery': gallery,\n 'about': about,\n 'contact': contact\n };\n titles = {\n '': homeTitle,\n 'home': homeTitle,\n 'index.html': homeTitle,\n 'music': musicTitle,\n 'videos': videosTitle,\n 'gallery': galleryTitle,\n 'about': aboutTitle,\n 'contact': contactTitle\n }\n const page = window.location.pathname.split('/').pop().split('#')[0];\n setPage(page);\n}", "function init() {\n setupApplication();\n createWorld();\n createCamera();\n\n loadLevel(app.level.name);\n\n console.info('Web app loaded');\n }", "function initLunr() {\n if (!endsWith(baseurl,\"/\")){\n baseurl = baseurl+'/'\n };\n\n // First retrieve the index file\n $.getJSON(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 = new lunr.Index\n lunrIndex.ref(\"uri\");\n lunrIndex.field('title', {\n boost: 15\n });\n lunrIndex.field('tags', {\n boost: 10\n });\n lunrIndex.field(\"content\", {\n boost: 5\n });\n\n // Feed lunr with each file and let lunr actually index them\n pagesIndex.forEach(function(page) {\n lunrIndex.add(page);\n });\n lunrIndex.pipeline.remove(lunrIndex.stemmer)\n })\n .fail(function(jqxhr, textStatus, error) {\n var err = textStatus + \", \" + error;\n console.error(\"Error getting Hugo index flie:\", err);\n });\n}", "function initPage(){\n var url = \"https://eng1003.monash/api/campusnav/?campus=clayton&callback=getPaths\";\n var script = document.createElement('script');\n script.src = url;\n document.body.appendChild(script);\n}", "function initLunr(callback) {\n // First retrieve the index file\n $.getJSON(\"/js/lunr/PagesIndex.json\")\n .done(function(index) {\n pagesIndex = index;\n console.log(\"index:\", pagesIndex);\n\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.field(\"title\", {\n boost: 10\n });\n this.field(\"tags\", {\n boost: 5\n });\n this.field(\"content\");\n\n // ref is the result item identifier (I chose the page URL)\n this.ref(\"href\");\n\n // Feed lunr with each file and let lunr actually index them\n pagesIndex.forEach(function(page) {\n if (page != null) {\n this.add(page);\n }\n }, this);\n });\n console.log(\"index built!!!\");\n callback();\n\n })\n\n .fail(function(jqxhr, textStatus, error) {\n var err = textStatus + \", \" + error;\n console.error(\"Error getting Hugo index file:\", err);\n });\n }", "function Site() {\n var self = this\n , files = []\n , dirs = []\n , contentPath = './content/';\n\n this.pages = [];\n this.sections = [];\n this.updated = new Date().toString();\n\n fs.readdirSync(contentPath).forEach(function(item) {\n if ((/^\\./).test(item)) return;\n item = contentPath + item;\n if (/\\.md/.test(item)) {\n files.push(item);\n } else {\n dirs.push(item);\n fs.readdirSync(item).forEach(function(file) {\n files.push(item + '/' + file);\n });\n }\n });\n\n files.forEach(function(file, i) {\n self.pages.push(new Page(file, i + 1));\n });\n\n dirs.forEach(function(dir) {\n self.sections.push(new Section(dir));\n });\n}", "function initData() {\n data = $.getJSON('./data/weathers.json').done(() => {\n console.log(\"Loaded: JSON - data\");\n data = data.responseJSON;\n console.log(data);\n initPage();\n }).fail(() => {\n console.log(\"Error when loading JSON - data.\");\n });\n}", "async init() {\n let dataNav = new Data();\n let configObj = new Config();\n dataNav\n .getJson(configObj.jsonPath)\n .then(data => {\n let hugeNav = new Nav(data);\n hugeNav.buildNav();\n })\n .catch(err => {\n console.error();\n });\n }", "function init() {\n\n\t\t// Check if on mobile\n\t\tif (global.innerWidth <= 1000) {\n\t\t\tmobile = true;\n\t\t}\n\n\t\t// Load tutorials\n\t\tm.request({\n\t\t\tmethod: 'GET',\n\t\t\turl: 'config/tutorials.json',\n\t\t}).then(function (data) {\n\t\t\ttutorials = data;\n\t\t\tloaded = true;\n\t\t});\n\n\t\t// Load i18n strings\n\t\tlanguages.forEach(function (lang) {\n\t\t\tm.request({\n\t\t\t\tmethod: 'GET',\n\t\t\t\turl: `config/i18n/${lang}.json`\n\t\t\t}).then(function (data) {\n\t\t\t\tstrings[lang] = data;\n\t\t\t});\n\t\t});\n\n\t\t// Configure routes\n\t\tm.route(root, '/', {\n\t\t\t'/': HomeView,\n\t\t\t'/learn/:id': PlaygroundView,\n\t\t\t'/play/:simulator': PlaygroundView\n\t\t});\n\n\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This will display the warning for low stock clinics
function displayLowStockWarning(clinics) { var alertOutput = "Warning! The Following Clinics are low on stock: \n"; for (var i in clinics) { var nev = clinics[i]["nevirapineStock"]; var sta = clinics[i]["stavudineStock"]; var zid = clinics[i]["zidotabineStock"]; var clinName = clinics[i]["clinicName"]; var cls = "\t•" + clinName + " is low on:"; var flag = 0; if (nev < 5) { cls += " Nevirapine;"; flag++; } if (sta < 5) { cls += " Stavudine;" flag++; } if (zid < 5) { cls += " Zidotabine" flag++; } if (flag == 0) { alertOutput += ""; continue; } cls += "\n"; alertOutput += cls; } alert(alertOutput); }
[ "function alert_low_quantity(){\n for(var part of global_table){\n if(part['stock'] <= config_json[\"Low Stock Quantity\"]){\n // TODO: CHange 'value' to a part description/manufacturer ID\n toastr.warning(`Low quantity (${part['stock']}) for ${part['value']}`);\n }\n }\n}", "function showSpecialWarning() {\r\n return true;\r\n}", "function handleNoCurrenciesToDisplayWarningMsg() {\r\n const errMsg = \"There are no currencies selected!\";\r\n const alertCodeClass = \"alert-warning\";\r\n // Display beautified message to the user.\r\n displayBeautifiedMsg(errMsg, alertCodeClass);\r\n } // End of function handleNoCurrenciesToDisplayWarningMsg", "function showOldPrimoMessage() {\n var newBlock = '<div class=\"largeWarning\">' + 'This is an outdated version of Library Search. Please access the new version from ' + '<a href=\"https://www.library.uq.edu.au/\">the Library home page</a>' + '</div>';\n var mainBlock = '#contentEXL.EXLCustomLayoutContainer.EXLContent.EXLBriefDisplay';\n\n $(newBlock).prependTo(mainBlock);\n}", "showWarnings(warnings) {\n logger.info('[showWarnings]', warnings);\n let messages = [];\n Object.keys(warnings).forEach(key => {\n // Don't show the empty field wanrings or billing/shipping\n let field = warnings[key].split(' - ')[0];\n if (warnings[key] != global.localizer.get('THIS_FIELD_IS_REQUIRED') && field != global.localizer.get('SHIPPING_INFORMATION') && field != global.localizer.get('BILLING_INFORMATION')) {\n messages.push(warnings[key]);\n }\n });\n // Display warnings if there are any\n if (messages.length > 0)\n return (\n <div className={\"quote-error\"}>\n {messages}\n </div>\n )\n }", "function ACCwarnings(value)\n{\n\tif (value) showWarnings = true; else showWarnings = false;\n}", "function lowStockClinic(clinic) {\n return clinic[\"stavudineStock\"] < 5 || clinic[\"zidotabineStock\"] < 5 || clinic[\"nevirapineStock\"] < 5;\n}", "function displayLowInventory() {\n\n\t// Construct the db query string\n\tqueryStr = 'SELECT * FROM products WHERE stock_quantity < 30';\n\n\t// Make the db query\n\tconnection.query(queryStr, function(err, res) {\n\t\tif (err) throw err;\n\n\t\tconsole.log('Low Inventory Items (below 30): ');\n\t\tconsole.table(res);\n connection.end();\n\t\t})\n }", "function aWarning(errorObject){\n if(!terminal.symbolProgress) terminal.symbolProgress=\"? \";\n if(errorObject.aux){\n if(!terminal.colors.aux) terminal.colors.aux= chalk.white;\n console.log(terminal.colors.warning(terminal.symbolProgress+\" Warning: \"+errorObject.message)+\" \" +terminal.colors.aux(errorObject.aux));\n console.log();\n }\n else{\n console.log(terminal.colors.warning(terminal.symbolProgress+\" Warning: \"+errorObject.message));\n console.log();\n }\n}", "function showNWSWarnings(){\r\n\t\ttimeVal = timeCanvasVal.getAttr('time');\r\n\t\tnwsWarnings.removeAllFeatures();\r\n\t\tif(nwsTorWarnings.getVisibility()){\r\n\t\t\tetn = [];\r\n\t\t\tindices = [];\r\n\t\t\tissues = [];\r\n\t\t\tfor(i=0;i<nwsTorWarnings.features.length;i++){\r\n\t\t\t\td = new Date(nwsTorWarnings.features[i].attributes.issue);\r\n\t\t\t\tissue = d.getTime() / 1000;\r\n\t\t\t\td = new Date(nwsTorWarnings.features[i].attributes.expire);\r\n\t\t\t\texpire = d.getTime() / 1000;\r\n\t\t\t\tif(etn.indexOf(nwsTorWarnings.features[i].attributes.etn) == -1 && timeVal <= expire && timeVal >= issue){\r\n\t\t\t\t\tetn.push(nwsTorWarnings.features[i].attributes.etn);\r\n\t\t\t\t\tindices.push(i);\r\n\t\t\t\t\tissues.push(issue);\r\n\t\t\t\t}\r\n\t\t\t\telse if(etn.indexOf(nwsTorWarnings.features[i].attributes.etn) != -1 && timeVal <= expire && timeVal >= issue){\r\n\t\t\t\t\tindex = etn.indexOf(nwsTorWarnings.features[i].attributes.etn);\r\n\t\t\t\t\tif(issue > issues[index]){\r\n\t\t\t\t\t\tindices[index] = i;\r\n\t\t\t\t\t\tissues[index] = issue;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tfor(i=0;i<indices.length;i++){\r\n\t nwsWarnings.addFeatures([nwsTorWarnings.features[indices[i]].clone()]);\r\n\t }\r\n\t\t}\r\n\t\tif(nwsSvrWarnings.getVisibility()){\r\n\t\t\tetn = [];\r\n indices = [];\r\n issues = [];\r\n\t\t\tfor(i=0;i<nwsSvrWarnings.features.length;i++){\r\n \td = new Date(nwsSvrWarnings.features[i].attributes.issue);\r\n issue = d.getTime() / 1000;\r\n d = new Date(nwsSvrWarnings.features[i].attributes.expire);\r\n expire = d.getTime() / 1000;\r\n if(etn.indexOf(nwsSvrWarnings.features[i].attributes.etn) == -1 && timeVal <= expire && timeVal >= issue){\r\n etn.push(nwsSvrWarnings.features[i].attributes.etn);\r\n indices.push(i);\r\n issues.push(issue);\r\n }\r\n else if(etn.indexOf(nwsSvrWarnings.features[i].attributes.etn) != -1 && timeVal <= expire && timeVal >= issue){\r\n index = etn.indexOf(nwsSvrWarnings.features[i].attributes.etn);\r\n if(issue > issues[index]){\r\n indices[index] = i;\r\n issues[index] = issue;\r\n }\r\n }\r\n \t }\r\n\t\t\tfor(i=0;i<indices.length;i++){\r\n nwsWarnings.addFeatures([nwsSvrWarnings.features[indices[i]].clone()]);\r\n }\r\n\t\t}\r\n\t}", "function updateNotEnoughFundsText() {\n\tif (gamestate.money < waterhoseCost) {\n\t\t// Player can't afford any towers\n\t\tcantAffordWaterhoseText.alpha = 1.0;\n\t\tcantAffordSignalDisruptorText.alpha = 1.0;\n\t\tcantAffordLaserText.alpha = 1.0;\n\n\t\treturn;\n\t} else if (gamestate.money < signaldisruptorCost) {\n\t\t// Player can afford at least a Waterhose\n\t\tcantAffordWaterhoseText.alpha = 0.0;\n\t\tcantAffordSignalDisruptorText.alpha = 1.0;\n\t\tcantAffordLaserText.alpha = 1.0;\n\n\t\treturn;\n\t} else if (gamestate.money < laserCost) {\n\t\t// Player can affor at least a Signal Disruptor\n\t\tcantAffordWaterhoseText.alpha = 0.0;\n\t\tcantAffordSignalDisruptorText.alpha = 0.0;\n\t\tcantAffordLaserText.alpha = 1.0;\n\n\t\treturn;\n\t} else {\n\t\tcantAffordWaterhoseText.alpha = 0.0;\n\t\tcantAffordSignalDisruptorText.alpha = 0.0;\n\t\tcantAffordLaserText.alpha = 0.0;\n\t}\n}", "displayUnreliableSuppressed() {\n // Don't display unreliable/suppressed unless the selected maternal health is one of the following values.\n if ([\"Maternal Mortality Rate\", \"Late Maternal Death Rate\"].includes(this.getMaternalHealthSelected())) {\n return true;\n }\n return false;\n }", "function parkingWarning (availableLots) {\n if (parseInt(availableLots.innerHTML) <= 10 && parseInt(availableLots.innerHTML) >= 1 ) {\n availableLots.style.color = \"#FFA500\";\n } else if (availableLots.innerHTML === \"FULL\") {\n availableLots.style.color = \"#FF0000\";\n } else if (parseInt(availableLots.innerHTML) > 10) {\n availableLots.style.color = \"#ADFF2F\";\n }\n}", "function resultWarning() {\n chart.finishLoading( RateCheckerChart.STATUS_WARNING );\n}", "function sustainableEnergy() {\n\talert(\"SUSTAINABLE ENERGY:\\n\\nIn November of 2009, we helped the people of La Toti install solar panels on the community clinic and public toilets. Solar expert Bruce Gardiner went to La Toti with BIF members and showed local residents how to install and maintain solar panels, beginning the local development of renewable power.\");\n}", "_displayNoCarriersWarning() {\n this._showContainer();\n this._hideForm();\n this._showNoCarrierBlock();\n }", "function addWarning(){\n jQuery('#major-publishing-actions').prepend(\n '<div class=\"warn-user\" style=\"display:none;text-indent: -20px;margin-left: 20px;margin-bottom: 10px;padding-bottom: 10px;border-bottom: 1px solid;\"><input type=\"checkbox\" name=\"tai_checked\" style=\"position: relative;top: 4px;\"><label for=\"_tai_checked\">Please be aware that Taiwan needs to be referred to using the UN nomenclature of \\'Taiwan, province of China\\' - please click here to acknowledge this message.</label></div>');\n }", "function showNotSupportedMsg() {\n updateTool($not_supported_text);\n }", "function showNricWarning() {\n emptyNricWarning$('#emptyNricWarning').css(\"display\", \"block\");\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Funtion Declarations Function: startScoreboard() This function surrounds runScoreboard() in a try/catch block so it can easily display any error messages to the user through an alert popup.
function startScoreboard(){ try { runScoreboard(); } catch (e){ alert("Error: " + e + "\n"); console.error(e.stack); } }
[ "function init() {\n previousScoreboard();\n }", "function startGame(){\n score = 0;\n timer = time;\n clearScreen();\n fillBoard();\n runTimer();\n }", "function loadFlashmathScoreboard() {\n clearScreen();\n loadCursor();\n\n loadNavBars(\"Flashmath Scoreboard\");\n\n let scoreboard = addFlashmathScoreboard();\n document.body.appendChild(scoreboard);\n}", "startWebcamGameWithScoreBoard(){\r\n this.session.put('game-event-type','webcam')\r\n $('#window').empty();\r\n $('#window').append(dom.getWebcamWindow());\r\n $('#human_score').append(`<label>`+this.localeModel.getCurrentLanguage('human')+`</label><label>`+this.gameModel.getHumanScore()+`</label>`);\r\n $('#computer_score').append(`<label>`+this.localeModel.getCurrentLanguage('computer')+`</label><label>`+this.gameModel.getComputerScore()+`</label>`);\r\n this.webcam.setupCAM();\r\n }", "function leaderBoard(){\n if(restarted){\n translate(-1*width/2, -1*height/2);\n }\n\n //background\n background(0);\n image(menuBackground,0,0,windowWidth,windowHeight);\n\n //says high scores for the difficulty user was on\n textSize(75);\n fill(200,0,200);\n text(\"High Scores\", width/2, height*1/8);\n\n textSize(40);\n fill(200,0,200);\n text(\"For difficulty \" + difficulty, width/2, height*7/32);\n\n //writes top scores\n textSize(50);\n fill(255,165,0);\n push();\n\n //places each score on-screen\n if(difficulty===5){\n translate(width*11/32, height*2/8);\n for(var i=0; i<getItem(\"High Scores 5\").length; i++){\n translate(0, height*1/16);\n if(i===9){\n translate(-12,0);\n }\n //score\n text((i+1) + \". \" + getItem(\"High Scores 5\")[i].score, 0, 0);\n }\n pop();\n \n //writes date top scores were made\n push();\n translate(width*19/32, height*2/8);\n textSize(30);\n for(var i=0; i<getItem(\"High Scores 5\").length; i++){\n translate(0, height*1/16);\n //date\n text(getItem(\"High Scores 5\")[i].month + \" \" + getItem(\"High Scores 5\")[i].day + \", \" + getItem(\"High Scores 5\")[i].year, 0, 0);\n }\n pop();\n }\n if(difficulty===6){\n translate(width*11/32, height*2/8);\n for(var i=0; i<getItem(\"High Scores 6\").length; i++){\n translate(0, height*1/16);\n if(i===9){\n translate(-12,0);\n }\n text((i+1) + \". \" + getItem(\"High Scores 6\")[i].score, 0, 0);\n }\n pop();\n\n //writes date top scores were made\n push();\n translate(width*19/32, height*2/8);\n textSize(30);\n for(var i=0; i<getItem(\"High Scores 6\").length; i++){\n translate(0, height*1/16);\n text(getItem(\"High Scores 6\")[i].month + \" \" + getItem(\"High Scores 6\")[i].day + \", \" + getItem(\"High Scores 6\")[i].year, 0, 0);\n }\n pop();\n }\n if(difficulty===7){\n translate(width*11/32, height*2/8);\n for(var i=0; i<getItem(\"High Scores 7\").length; i++){\n translate(0, height*1/16);\n if(i===9){\n translate(-12,0);\n }\n text((i+1) + \". \" + getItem(\"High Scores 7\")[i].score, 0, 0);\n }\n pop();\n\n //writes date top scores were made\n push();\n translate(width*19/32, height*2/8);\n textSize(30);\n for(var i=0; i<getItem(\"High Scores 7\").length; i++){\n translate(0, height*1/16);\n text(getItem(\"High Scores 7\")[i].month + \" \" + getItem(\"High Scores 7\")[i].day + \", \" + getItem(\"High Scores 7\")[i].year, 0, 0);\n }\n pop();\n }\n if(difficulty===8){\n translate(width*11/32, height*2/8);\n for(var i=0; i<getItem(\"High Scores 8\").length; i++){\n translate(0, height*1/16);\n if(i===9){\n translate(-12,0);\n }\n text((i+1) + \". \" + getItem(\"High Scores 8\")[i].score, 0, 0);\n }\n pop();\n\n //writes date top scores were made\n push();\n translate(width*19/32, height*2/8);\n textSize(30);\n for(var i=0; i<getItem(\"High Scores 8\").length; i++){\n translate(0, height*1/16);\n text(getItem(\"High Scores 8\")[i].month + \" \" + getItem(\"High Scores 8\")[i].day + \", \" + getItem(\"High Scores 8\")[i].year, 0, 0);\n }\n pop();\n }\n if(difficulty===9){\n translate(width*11/32, height*2/8);\n for(var i=0; i<getItem(\"High Scores 9\").length; i++){\n translate(0, height*1/16);\n if(i===9){\n translate(-12,0);\n }\n text((i+1) + \". \" + getItem(\"High Scores 9\")[i].score, 0, 0);\n }\n pop();\n\n //writes date top scores were made\n push();\n translate(width*19/32, height*2/8);\n textSize(30);\n for(var i=0; i<getItem(\"High Scores 9\").length; i++){\n translate(0, height*1/16);\n text(getItem(\"High Scores 9\")[i].month + \" \" + getItem(\"High Scores 9\")[i].day + \", \" + getItem(\"High Scores 9\")[i].year, 0, 0);\n }\n pop();\n }\n if(difficulty===10){\n translate(width*11/32, height*2/8);\n for(var i=0; i<getItem(\"High Scores 10\").length; i++){\n translate(0, height*1/16);\n if(i===9){\n translate(-12,0);\n }\n text((i+1) + \". \" + getItem(\"High Scores 10\")[i].score, 0, 0);\n }\n pop();\n\n //writes date top scores were made\n push();\n translate(width*19/32, height*2/8);\n textSize(30);\n for(var i=0; i<getItem(\"High Scores 10\").length; i++){\n translate(0, height*1/16);\n text(getItem(\"High Scores 10\")[i].month + \" \" + getItem(\"High Scores 10\")[i].day + \", \" + getItem(\"High Scores 10\")[i].year, 0, 0);\n }\n pop();\n }\n if(difficulty===11){\n translate(width*11/32, height*2/8);\n for(var i=0; i<getItem(\"High Scores 11\").length; i++){\n translate(0, height*1/16);\n if(i===9){\n translate(-12,0);\n }\n text((i+1) + \". \" + getItem(\"High Scores 11\")[i].score, 0, 0);\n }\n pop();\n\n //writes date top scores were made\n push();\n translate(width*19/32, height*2/8);\n textSize(30);\n for(var i=0; i<getItem(\"High Scores 11\").length; i++){\n translate(0, height*1/16);\n text(getItem(\"High Scores 11\")[i].month + \" \" + getItem(\"High Scores 11\")[i].day + \", \" + getItem(\"High Scores 11\")[i].year, 0, 0);\n }\n pop();\n }\n if(difficulty===12){\n translate(width*11/32, height*2/8);\n for(var i=0; i<getItem(\"High Scores 12\").length; i++){\n translate(0, height*1/16);\n if(i===9){\n translate(-12,0);\n }\n text((i+1) + \". \" + getItem(\"High Scores 12\")[i].score, 0, 0);\n }\n pop();\n\n //writes date top scores were made\n push();\n translate(width*19/32, height*2/8);\n textSize(30);\n for(var i=0; i<getItem(\"High Scores 12\").length; i++){\n translate(0, height*1/16);\n text(getItem(\"High Scores 12\")[i].month + \" \" + getItem(\"High Scores 12\")[i].day + \", \" + getItem(\"High Scores 12\")[i].year, 0, 0);\n }\n pop();\n }\n if(difficulty===13){\n translate(width*11/32, height*2/8);\n for(var i=0; i<getItem(\"High Scores 13\").length; i++){\n translate(0, height*1/16);\n if(i===9){\n translate(-12,0);\n }\n text((i+1) + \". \" + getItem(\"High Scores 13\")[i].score, 0, 0);\n }\n pop();\n\n //writes date top scores were made\n push();\n translate(width*19/32, height*2/8);\n textSize(30);\n for(var i=0; i<getItem(\"High Scores 13\").length; i++){\n translate(0, height*1/16);\n text(getItem(\"High Scores 13\")[i].month + \" \" + getItem(\"High Scores 13\")[i].day + \", \" + getItem(\"High Scores 13\")[i].year, 0, 0);\n }\n pop();\n }\n if(difficulty===14){\n translate(width*11/32, height*2/8);\n for(var i=0; i<getItem(\"High Scores 14\").length; i++){\n translate(0, height*1/16);\n if(i===9){\n translate(-12,0);\n }\n text((i+1) + \". \" + getItem(\"High Scores 14\")[i].score, 0, 0);\n }\n pop();\n\n //writes date top scores were made\n push();\n translate(width*19/32, height*2/8);\n textSize(30);\n for(var i=0; i<getItem(\"High Scores 14\").length; i++){\n translate(0, height*1/16);\n text(getItem(\"High Scores 14\")[i].month + \" \" + getItem(\"High Scores 14\")[i].day + \", \" + getItem(\"High Scores 14\")[i].year, 0, 0);\n }\n pop();\n }\n if(difficulty===15){\n translate(width*11/32, height*2/8);\n for(var i=0; i<getItem(\"High Scores 15\").length; i++){\n translate(0, height*1/16);\n if(i===9){\n translate(-12,0);\n }\n text((i+1) + \". \" + getItem(\"High Scores 15\")[i].score, 0, 0);\n }\n pop();\n\n //writes date top scores were made\n push();\n translate(width*19/32, height*2/8);\n textSize(30);\n for(var i=0; i<getItem(\"High Scores 15\").length; i++){\n translate(0, height*1/16);\n text(getItem(\"High Scores 15\")[i].month + \" \" + getItem(\"High Scores 15\")[i].day + \", \" + getItem(\"High Scores 15\")[i].year, 0, 0);\n }\n pop();\n }\n\n //red button to leave leaderboard\n fill(255,0,0);\n rectMode(CENTER);\n stroke(0);\n rect(width*0.9, 50, 30, 20);\n fill(255);\n stroke(255);\n textSize(20)\n text(\"X\", width*0.9, 50);\n if(mouseX>width*0.9-15&&mouseX<width*0.9+15&&mouseY>38&&mouseY<60&&mouseIsPressed){\n //returns to correct screen\n if(leaderBoardFrom==='Menu'){\n state=\"Menu\";\n }else{\n state=\"Game Over\";\n }\n setup();\n }\n}", "function handleScore(){\n\n // display score.\n push();\n fill(0);\n textSize(height/36);\n noStroke();\n let guessesLeft = strikeOut - incorrectGuess;\n fill(225);\n text(\"score : \"+points+\", incorrect guesses left: \"+guessesLeft, width/2, height/32);\n fill(5);\n text(\"score : \"+points+\", incorrect guesses left: \"+guessesLeft, width/2-1, height/32-1);\n pop();\n // trigger game over if user runs out of incorrect guesses\n if(incorrectGuess>=strikeOut){\n\n // squawk game over and set state.\n parrot.squawk(\"game over!\");\n\n guesses =0;\n gameOver = true;\n // prevent clicking for a hot second.\n setTimeout(function(){ gameOverClickable = true; }, 400);\n }\n\n // trigger new round if maximum number of guesses was reached for this round.\n if(guesses>=maxGuesses){\n\n // reveal all cards\n for(let i=0; i<game.cards.length; i++){\n game.cards[i].wordRevealed = true;\n game.cards[i].typeRevealed = true;\n game.cards[i].defRevealed = true;\n }\n\n // set game to restart in 10 seconds\n guesses =0;\n timerDisplay = 10;\n setTimeout(function(){cueStartAgain = true;}, 10000);\n }\n}", "function submitScore(){\n saveScore();\n hideResult();\n showScoreBoard();\n}", "function showScoreBoard() {\n let title = level >= 15 ? 'Congrats, you won!' : 'Ah, you lost!',\n titleX = level >= 15 ? 152 : 220,\n titleY = 280,\n totalScore = level * 60 + GemsCollected.blue * 30 + GemsCollected.green * 40 + GemsCollected.orange * 50,\n scoreBoard = Resources.get('images/score-board.jpg'),\n starResource = Resources.get('images/Star.png'),\n gemBlueResource = Resources.get('images/Gem-Blue.png'),\n gemGreenResource = Resources.get('images/Gem-Green.png'),\n gemOrangeResource = Resources.get('images/Gem-Orange.png'),\n offset = 70;\n // Draw image assets\n ctx.drawImage(scoreBoard, (canvas.width - scoreBoard.width) / 2, (canvas.height - scoreBoard.height - offset) / 2);\n ctx.drawImage(starResource, 175, 260 - offset, starResource.width / 1.5, starResource.height / 1.5);\n ctx.drawImage(gemBlueResource, 180, 345 - offset, gemBlueResource.width / 1.8, gemBlueResource.height / 1.8);\n ctx.drawImage(gemGreenResource, 180, 425 - offset, gemGreenResource.width / 1.8, gemGreenResource.height / 1.8);\n ctx.drawImage(gemOrangeResource, 180, 505 - offset, gemOrangeResource.width / 1.8, gemOrangeResource.height / 1.8);\n // Draw text\n ctx.font = \"50px Gaegu\";\n ctx.fillStyle = \"#fff\";\n ctx.strokeStyle = \"#000\";\n ctx.lineWidth = 3;\n ctx.strokeText(title, titleX, titleY - offset);\n ctx.fillText(title, titleX, titleY - offset);\n ctx.font = \"45px Gaegu\";\n ctx.strokeText(level + ' x 60 = ' + level * 60, 270, 340 - offset);\n ctx.fillText(level + ' x 60 = ' + level * 60, 270, 340 - offset);\n ctx.strokeText(GemsCollected.blue + ' x 30 = ' + GemsCollected.blue * 30, 270, 420 - offset);\n ctx.fillText(GemsCollected.blue + ' x 30 = ' + GemsCollected.blue * 30, 270, 420 - offset);\n ctx.strokeText(GemsCollected.green + ' x 40 = ' + GemsCollected.green * 40, 270, 500 - offset);\n ctx.fillText(GemsCollected.green + ' x 40 = ' + GemsCollected.green * 40, 270, 500 - offset);\n ctx.strokeText(GemsCollected.orange + ' x 50 = ' + GemsCollected.orange * 50, 270, 580 - offset);\n ctx.fillText(GemsCollected.orange + ' x 50 = ' + GemsCollected.orange * 50, 270, 580 - offset);\n ctx.strokeText('_______', 270, 640 - offset);\n ctx.fillText('_______', 270, 640 - offset);\n ctx.strokeText('Total: ' + totalScore.toString(), 270, 640 - offset);\n ctx.fillText('Total: ' + totalScore.toString(), 270, 640 - offset);\n ctx.strokeText('Spacebar to restart', 170, 680);\n ctx.fillText('Spacebar to restart', 170, 680);\n }", "function init_scoreboard() {\n\tvar tbody = document.getElementsByTagName('tbody')[0];\n\tvar str = '';\n\t\n\t// create rows \n\tfor (var i = 0; i < rows.length; i++) {\n\t\tvar row = rows[i];\n\t\tvar team = row[1];\n\t\tvar name = team[1];\n\t\tif(team.length >= 3){\n\t\t\tname = team[2] + ' ( ' + name + ' )';\n\t\t}\n\t\tstr += '<tr><td>' + row[0] + '</td>' +\n '<td class=\"team\" data=\"' + row[4] + '\">' +\n generateSchoolLogo(team[3]) +\n '<div class=\"team-name-school\">' + name +\n generateRemark(team[4]) +\n '<span class=\"muted\">' + team[0] + '</span></div></td>' +\n '<td>' + row[2] + '</td><td>' + row[3] + '</td>';\n\t // problems cols\n\t\tfor (var j = 5; j < row.length - 1; j++){\n\t\t\tvar prob = row[j];\n\t\t\tif (prob != 0) {\n\t\t\t\tvar score = prob[0].split('/');\n\t\t\t\tvar cls = prob[1] ? ' class=\"' + prob[1] + '\"' : '';\n\t\t\t\tvar dat = score[2] ? ' data=\"' + score[2] + '\"' : '';\n\t\t\t\tstr += '<td' + cls + dat + '>' + \n\t\t\t\t\tscore[0] + '<span class=\"muted\"> ' + score[1] + '</span></td>';\n\t\t\t}\n\t\t\telse\n\t\t\t\t// space before -- is necessary\n\t\t\t\tstr += '<td>0<span class=\"muted\"> --</span></td>'; \n\t\t}\n\n\t\t// att/solv col\n\t\tvar att = row[j][0].split('/');\n\t\tstr += '<td>' + att[0] + '<br>' + att[1] + '</td>';\n\t}\n\ttbody.innerHTML = str + tbody.innerHTML;\n}", "function UpdateScoreboard() {\n\tvar message = Configstring('message');\n\n\tscoreboard_model.mapname(cgs.arena.name === 'default' ? message : cgs.arena.name);\n\tscoreboard_model.gametype(BG.GametypeNames[cgs.arena.gametype]);\n\tscoreboard_model.timelimit(cgs.timelimit);\n\tscoreboard_model.fraglimit(cgs.fraglimit);\n\tscoreboard_model.capturelimit(cgs.capturelimit);\n}", "function updateScore() {\n scoreboard.updateScore();\n scoreboard.checkWin(gameOver);\n scoreboard.server();\n}", "function draw_scoreboard()\r\n{\r\n\tvar scoreboardHTML = \"<center>\" + this.mScore + \"</center>\"\r\n\tscoreboardHTML = this.get_div_html( this.mDivId, scoreboardHTML );\r\n\tdocument.getElementById( this.mDivId ).innerHTML = scoreboardHTML;\r\n}", "function openLeaderboard() {\n leaderboardScreen.style.display = 'flex';\n homeScreen.style.display = 'none';\n endQuiz.style.display = 'none';\n quizPrompts.style.display = 'none';\n timer.style.visibility = 'hidden';\n generateScore();\n}", "function validScore() {\n var e = document.getElementById('scoreErr'),\n preScore = document.getElementById(\"score\").value;\n\n try {\n if (preScore === \"\") {\n throw \"Please enter what you expect to earn.\";\n }\n if (isNaN(preScore)) {\n throw \"Please enter a number for the score you think you'd earn.\";\n }\n if (preScore < 0) {\n throw \"Please enter a score greater than or equal to 0.\";\n }\n if (preScore > 100) {\n throw \"Please enter a score less than or equal to 100.\";\n }\n\n } catch (err) {\n e.innerHTML = err;\n e.style.display = \"inline\";\n document.getElementById(\"score\").focus();\n\n } finally {\n if ((preScore !== \"\") && (isNaN(preScore) === false) && (preScore >= 0)\n && (preScore <= 100)) {\n e.innerHTML = \"\";\n e.style.display = \"none\";\n\n displayDiagram();\n }\n }\n }", "function startGame(){\n entireGameboard.start();\n}", "function checkForWin() {\n // if grid does not contain any cells with class of bones\n if (boneCount === 0) {\n alert(`You win and Winston is victorious! Your score was ${score}!`)\n const newName = prompt('Please enter your name!')\n const newScore = score\n const player = { name: newName, finalScore: newScore }\n playerScores.push(player)\n if (localStorage) {\n localStorage.setItem('scoreboard', JSON.stringify(playerScores))\n orderAndDisplayScores()\n }\n window.location.reload()\n } else {\n return\n }\n }", "function drawScoreboard(scene) {\n scoreboard[0] = scene.add.text(scene.cameras.main.worldView.x + ($(window).width()/2) - 100, scene.cameras.main.worldView.y - (scene.cameras.main.height/2), \"Scoreboard\", { fontSize: '32px', fill: '#A64545' })\n for(let i = 1; i < 6; i++) {\n scoreboard[i] = scene.add.text(scene.cameras.main.worldView.x + ($(window).width()/2) - 100, scene.cameras.main.worldView.y - (scene.cameras.main.height/2) + (25 * i), \"Score: \", { fontSize: '20px', fill: '#A64545' })\n }\n}", "function startBoard() {\n resetBoard();\n getNewCards();\n shuffleBoard();\n loadBoardElemets();\n updateCounters();\n startTimer();\n}", "function UpdateScoreboard()\n{\n /**\n * Compute the \"Squirrel\" rating from the given silver & gold crown counts,\n * and the current tier minimums. (The ratings may have changed even if the\n * member's crowns did not).\n * @param {(number|string)[]} record A member's new database record (modified in-place).\n * @param {[number, string, string][]} squirrelTiers an array of crown count minimums and the corresponding Squirrel tier\n * @param {number} mhccIndex The array index corresponding to the squirrel data.\n * @param {number} squirrelIndex The array index corresponding to the Squirrel data.\n */\n function _setCurrentSquirrel(record, squirrelTiers, mhccIndex, squirrelIndex)\n {\n for (var k = 0; k < squirrelTiers.length; ++k)\n if (record[mhccIndex] >= squirrelTiers[k][0]) {\n // Crown count meets/exceeds required crowns for this level.\n record[squirrelIndex] = squirrelTiers[k][2];\n return;\n }\n }\n /**\n * Function that handles the prediction of the next scoreboard update.\n * @param {string} targetSheet The sheet on which scoreboard timings are logged\n * @param {string} predictionCell The cell in which the next scoreboard update time is estimated\n * @param {string} logCell The cell in which the current scoreboard update's start time is logged\n * @param {Date} start The time at which the current update began running.\n */\n function _estimateNextScoreboard(targetSheet, predictionCell, logCell, start)\n {\n const s = wb.getSheetByName(targetSheet), r = s.getRange(logCell);\n s.getRange(predictionCell).setValue((start - r.getValue()) / (24 * 3600 * 1000));\n r.setValue(start);\n }\n\n const startTime = new Date(), wb = SpreadsheetApp.getActive();\n try { const aRankTitle = wb.getSheetByName('Members').getRange(3, 8, numCustomTitles, 3).getValues(); }\n catch (e) { throw new Error(\"'Members' sheet was renamed or deleted - cannot locate crown-title relationship data.\"); }\n\n const lock = LockService.getScriptLock();\n if (!lock.tryLock(30000))\n return;\n\n // To build the scoreboard....\n // 1) Store the most recent snapshots of all members on SheetDb\n if (!saveMyDb_(wb, bq_getLatestRows_('Core', 'Crowns').rows))\n throw new Error('Unable to save snapshots retrieved from crown database');\n\n // 2) Sort it by MHCC crowns, then LastCrown, then LastSeen. This means the first to have a\n // particular crown total should rank above someone who (was seen) attaining it at a later time.\n // TODO: use the new MHCCCrownChange column rather than LastCrown, to avoid penalizing for upgrading crowns.\n const allHunters = getMyDb_(wb, [{ column: 9, ascending: false }, { column: 4, ascending: true }, { column: 3, ascending: true }]),\n len = allHunters.length, scoreboardArr = [],\n plotLink = 'https://script.google.com/macros/s/AKfycbxvvtBNQ66BBlB-md1jn_y-TlujQf1ytDkYG-7nEAG4SDaecMFF/exec?uid=';\n var rank = 1;\n if (!len)\n return;\n\n // 3) Build the array with this format: Rank UpdateDate CrownChangeDate Squirrel MHCCCrowns Name Profile\n do {\n var ah_i = rank - 1;\n _setCurrentSquirrel(allHunters[ah_i], aRankTitle, 8, 9);\n scoreboardArr.push([\n rank,\n Utilities.formatDate(new Date(allHunters[ah_i][2]), 'EST', 'yyyy-MM-dd'), // Last Seen\n Utilities.formatDate(new Date(allHunters[ah_i][3]), 'EST', 'yyyy-MM-dd'), // Last Crown\n allHunters[ah_i][9], // Squirrel\n '=HYPERLINK(\"' + plotLink + allHunters[ah_i][1] + '\",\"' + allHunters[ah_i][8] + '\")', // # MHCC Crowns\n allHunters[ah_i][0], // Name\n 'https://apps.facebook.com/mousehunt/profile.php?snuid=' + allHunters[ah_i][1],\n 'https://www.mousehuntgame.com/profile.php?snuid=' + allHunters[ah_i][1]\n ]);\n if (rank % 150 === 0)\n scoreboardArr.push(['Rank', 'Last Seen', 'Last Crown', 'Squirrel Rank', 'G+S Crowns', 'Hunter', 'Profile Link', 'MHG']);\n\n // Store the time this rank was generated.\n allHunters[ah_i][10] = startTime.getTime();\n // Store the counter as the hunters' rank, then increment the counter.\n allHunters[ah_i][11] = rank++;\n } while (rank <= len);\n\n // 4) Write it to the spreadsheet\n const sheet = wb.getSheetByName('Scoreboard');\n sheet.getRange(2, 1, sheet.getLastRow(), scoreboardArr[0].length).setValue('');\n sheet.getRange(2, 1, scoreboardArr.length, scoreboardArr[0].length).setValues(scoreboardArr);\n\n // 5) Upload it to the Rank History DB.\n const rankUpload = allHunters.map(function (record) {\n // Name, UID, LastSeen, RankTime, Rank, MHCC Crowns\n // [0], [1], [2], [10], [11], [8]\n return [record[0], String(record[1]), record[2], record[10], record[11], record[8]];\n });\n if (rankUpload.length && rankUpload[0].length === 6)\n bq_addRankSnapshots_(rankUpload);\n\n // Provide estimate of the next new scoreboard posting and the time this one was posted.\n _estimateNextScoreboard('Members', 'I23', 'H23', startTime);\n\n // Overwrite the latest db version with the version that has the proper ranks, Squirrel, and ranktimes.\n saveMyDb_(wb, allHunters);\n\n // If a member hasn't been seen in the last 20 days, then request a high-priority update\n UpdateStale_(wb, 20 * 86400 * 1000);\n\n console.log(\"%s sec. for all scoreboard operations\", (new Date() - startTime) / 1000);\n lock.releaseLock();\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
xRemoveEventListener, Copyright 20012007 Michael Foster (CrossBrowser.com) Part of X, a CrossBrowser Javascript Library, Distributed under the terms of the GNU LGPL
function xRemoveEventListener(e,eT,eL,cap) { if(!(e=xGetElementById(e)))return; eT=eT.toLowerCase(); if(e.removeEventListener)e.removeEventListener(eT,eL,cap||false); else if(e.detachEvent)e.detachEvent('on'+eT,eL); else e['on'+eT]=null; }
[ "function xRemoveEventListener2(e,eT,eL,cap)\r\n{\r\n if(!(e=xGetElementById(e))) return;\r\n eT=eT.toLowerCase();\r\n if(e==window) {\r\n if(eT=='resize' && e.xREL) {e.xREL=null; return;}\r\n if(eT=='scroll' && e.xSEL) {e.xSEL=null; return;}\r\n }\r\n if(e.removeEventListener) e.removeEventListener(eT,eL,cap||false);\r\n else if(e.detachEvent) e.detachEvent('on'+eT,eL);\r\n else e['on'+eT]=null;\r\n}", "function xRemoveEventListener(e,eT,eL,cap)\n{\n if(!(e=xGetElementById(e))) return;\n eT=eT.toLowerCase();\n if((!xIE4Up && !xOp7Up) && e==window) {\n if(eT=='resize') { window.xREL=null; return; }\n if(eT=='scroll') { window.xSEL=null; return; }\n }\n var eh='e.on'+eT+'=null';\n if(e.removeEventListener) e.removeEventListener(eT,eL,cap);\n else if(e.detachEvent) e.detachEvent('on'+eT,eL);\n else eval(eh);\n}", "function removeListener(w,event,cb){w.detachEvent?w.detachEvent(\"on\"+event,cb):w.removeEventListener&&w.removeEventListener(event,cb,!1)}", "removeAllEventListeners() {\n\t\tObject.keys(this.evtCallbacks).forEach((evtName) => {\n\t\t\tconst events = this.evtCallbacks[evtName];\n\t\t\tevents.forEach(({ element, callback }) => {\n\t\t\t\telement.removeEventListener(evtName, callback);\n\t\t\t});\n\t\t});\n\t}", "removeCloseEventListener() {\n this.win_.removeEventListener('click', this.sendCloseRequestFunction_);\n }", "function deleteEvent(obj, type, fn){\r\n if(obj && obj.removeEventListener){\r\n obj.removeEventListener(type, fn);\r\n }else if(obj && obj.detachEvent){\r\n obj.detachEvent(\"on\" + type, fn);\r\n }else{\r\n alert(\"please use another browser\");\r\n }\r\n}", "function removeListener(w, event, cb) {\n\t if(w.detachEvent) w.detachEvent('on' + event, cb);\n\t else if (w.removeEventListener) w.removeEventListener(event, cb, false);\n\t }", "_removeListeners() {\n document.removeEventListener('click', this._handleWindowClick);\n window.removeEventListener('resize', this._handleResize);\n this.el.removeEventListener('keydown', this._handleKeyDown);\n document.removeEventListener('blur', this._handleBlur, true);\n document.removeEventListener('focus', this._handleFocus, true);\n document.removeEventListener('spark.visible-children', this._handleVisibleChildren, true);\n }", "_removeWindowEventListeners() {\n window.removeEventListener('click', this._onWindowClickBound);\n window.removeEventListener('keyup', this._onKeyupBound);\n window.removeEventListener('keydown', this._onKeydownBound);\n }", "removeListener(event: string, listener: Function) {\n var idx;\n\n if (typeof this.__events[event] === 'object') {\n idx = indexOf(this.__events[event], listener);\n\n if (idx > -1) {\n this.__events[event].splice(idx, 1);\n }\n }\n }", "removeEvent(eventListener) {\n delete this.func[eventListener];\n this.removeEventFromBlob(this.html, eventListener)\n }", "unregisterEventListeners_() {\n this.submenuOpenElements_.forEach(element => {\n element.removeEventListener('click', this.submenuOpenHandler_);\n });\n this.submenuCloseElements_.forEach(element => {\n element.removeEventListener('click', this.submenuCloseHandler_);\n });\n\n this.documentElement_.removeEventListener('keydown', this.keydownHandler_);\n }", "removeEventListeners() {\n const { listener } = this.context;\n if( listener ){\n listener.remove('mousemove', this.handleMouseMove);\n listener.remove('resize', this.handleResize);\n } else {\n window.removeEventListener('mousemove', this.handleMouseMove);\n window.removeEventListener('resize', this.handleResize);\n }\n this.listening = false;\n }", "function removeEventListener(handle) {\n GEvent.removeListener(handle);\n }", "_removeHistoryEventListener() {\n this.listElement.removeEventListener('click', this._eventHandler.history);\n }", "function removeEvent(obj,event_name,func_name){\r\n\tif (obj.detachEvent){\r\n\t\tobj.detachEvent(\"on\"+event_name,func_name);\r\n\t}else if(obj.removeEventListener){\r\n\t\tobj.removeEventListener(event_name,func_name,true);\r\n\t}else{\r\n\t\tobj[\"on\"+event_name] = null;\r\n\t}\r\n}", "function removeEventListeners() {\n\t\t$(document).unbind('mousemove')\n\t\tdocument.removeEventListener('mousedown', mouseDown)\n\t}", "function removeEventListener(){\n\tmenu.removeEventListener('mouseleave', leaveAnimation, false)\n\tmenu.removeEventListener('mouseenter', enterAnimation, false)\n}", "removeEvents() {\n const eventTarget = this.isIframe ? this.target.contentWindow.document : this.target;\n Util.removeElementEvents(eventTarget);\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the name of the repository for this session. Asynchronous. cb callback function to invoke with result scope scope used to invoke the callback function TODO Consolidate repository information into global context for current user.
function getRepositoryName(cb, scope) { function success(response, options) { var repoName = Ext.decode(response.responseText); cb.call(scope, repoName); } Ext.Ajax.request({ url: "application/currentUser/repository", scope: this, disableCaching: true, success: success }); }
[ "function getRepositoryInfo(username, repoName, callback) {\n var request = new XMLHttpRequest();\n request.open(\"GET\", \"https://api.github.com/repos/\" + username + \"/\" + repoName + IDSecret, true);\n request.onreadystatechange = function () {\n if (request.readyState === 4 && request.status === 200) {\n var response = JSON.parse(request.responseText);\n\n callback ? callback(response) : null;\n }\n };\n request.send();\n}", "function getRepo() {\n\treturn sessionStorage.getItem('repo');\n}", "function getRepoOwner() {\n\treturn sessionStorage.getItem('repoOwner');\n}", "function fullName() {\n return function(repo) {\n if (repo === undefined) { return \"\"; }\n return repo.owner+\"/\"+repo.name;\n }\n }", "static get repositoryName() {\n return events.EventField.fromPath('$.detail.repositoryName');\n }", "function getrepoinfo(repo, callback) {\n _get('getrepoinfo', `?r=${repo}`, callback);\n}", "function getRepoName() {\n // Repo url might have more than just the repo name\n var repoParts = window.location.href.split(/[\\/#]+/);\n // 0: http(s)\n // 1: Hostname\n scheme = repoParts[0];\n var repo = repoParts[2] + '/' + repoParts[3];\n\n return repo;\n}", "function getRepoName(body) {\n if (body && body.repository && body.repository.full_name) {\n return body.repository.full_name;\n } else {\n return null;\n }\n}", "function fetchRepoInfo (scopeName) {\n return fetchGitHubAPIWithPath(`/repos/${scopeName}`)\n}", "function fetchRepoInfo(scopeName) {\n return fetchGitHubAPIWithPath(`/repos/${scopeName}`)\n}", "name() {\n return this.repository.name;\n }", "name() { // ???\n return this.repository.name;\n }", "function get_repo_name(container)\n{\n\treturn new Promise(function(resolve, reject) {\n\n\t\t//\n\t\t// 1. Add new data to the container\n\t\t//\n\t\tcontainer.repo_name = container.github_event.repository.name;\n\n\t\t//\n\t\t// -> Move to the next chain\n\t\t//\n\t\treturn resolve(container);\n\n\t});\n}", "_getRepo () {\n let pkg = this._loadPackageJson()\n\n let url = pkg.repository.url.split('/')\n return url[3] + '/' + url[4].replace(/\\.[^/.]+$/, '')\n }", "async function getRepository() {\n const [, origin] = await await_to_js_1.default(exec_promise_1.default(\"git\", [\"remote\", \"get-url\", \"origin\"]));\n if (origin) {\n const info = parse_github_url_1.default(origin) || {};\n const { name, owner } = info;\n if (name && owner) {\n return { repo: name, owner };\n }\n }\n}", "get name() {\n return shell.exec( 'git config --get beanstalk.repo_name' ).stdout.trim();\n\n }", "function getRepo() {\n\t\t\treturn this.getHref().match(/(.*\\/rest\\/.*)\\/\\d+/)[1];\n\t\t}", "function ajaxRepoDetails(repoName, cb) {\n $.ajax({\n type: 'GET',\n url: 'https://api.github.com/repos/' + ns.userData.username + '/' + repoName,\n headers: {Authorization: 'token ' + ns.userData.token},\n dataType: 'JSON',\n success: function repoListAcquired(data) {\n ns.reponewissue.repoName = data.name;\n ns.reponewissue.repoURL = data.html_url;\n ns.reponewissue.repoOwner = data.owner.login;\n var element = createRepoDetails(data);\n cb(element);\n },\n error: function repoListNotAcquired(xhr) {\n console.log(xhr);\n }\n });\n }", "function getUserName(callback){\r\n dropboxClient.authenticate(function (error, client) {\r\n if (error) { throw error; }\r\n //null is options setting for dropbox getUserInfo funtion\r\n client.getUserInfo(null, function (error, userInfo, userOptions){\r\n var username = userInfo.name;\r\n var useremail = userInfo.email;\r\n callback(username, useremail);\r\n //console.log(username);\r\n });\r\n });\r\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Starts the HTTPS server with the given Express app
function startHttpsServer(app) { var httpServer; var credentials = loadSslCredentials(); if (!credentials) { console.log('SSL issue'); } try { httpServer = https.createServer(credentials, app); httpServer.on('error', httpError); httpServer.listen(config.httpsPort); console.log('Server started on HTTPS: ' + config.httpsPort); } catch (e) { console.error('Error while starting HTTPS server on ' + config.httpsPort + ':'); console.error(e); throw e; } }
[ "function startWebServer() {\n if (sslEnabled) {\n const key = fs.readFileSync(\"cert/server.key\", \"utf8\");\n const cert = fs.readFileSync(\"cert/domain.crt\", \"utf8\");\n const httpsServer = https.createServer({ key, cert }, app);\n app.use(graceful(httpsServer, { logger: console, forceTimeout: 30000 }));\n\n httpsServer.listen(sslPort, function () {\n console.info(`\\n🌎 https://localhost:${sslPort} 🌎\\n`);\n });\n return;\n }\n const httpServer = http.createServer(app);\n app.use(graceful(httpServer, { logger: console, forceTimeout: 30000 }));\n\n httpServer.listen(port, function () {\n console.info(`\\n🌎 https://localhost:${port} 🌎\\n`);\n });\n}", "function startServer () {\n https.createServer({\n key: fs.readFileSync('key.pem'),\n cert: fs.readFileSync('cert.pem')\n }, app).listen(3000);\n console.log(\"Secure server started on port 3000.\")\n\n}", "async function startWebServer() {\n if (sslEnabled) {\n const key = fs.readFileSync(\"cert/server.key\", \"utf8\");\n const cert = fs.readFileSync(\"cert/domain.crt\", \"utf8\");\n const httpsServer = https.createServer({ key, cert }, app);\n app.use(graceful(httpsServer, { logger: console, forceTimeout: 30000 }));\n httpsServer.listen(sslPort, checkPublicIpAddress);\n } else {\n const httpServer = http.createServer(app);\n app.use(graceful(httpServer, { logger: console, forceTimeout: 30000 }));\n httpServer.listen(port, checkPublicIpAddress);\n }\n}", "async function startWebServer () {\n const shutdownOptions = {\n logger: console,\n forceTimeout: 30000\n }\n\n if (sslEnabled) {\n secureCtx = await createSecureContext()\n // create with `secureCtx` so we can renew certs without restarting the server\n const httpsServer = https.createServer(\n {\n SNICallback: (_, cb) => cb(null, secureCtx)\n },\n app\n )\n // update secureCtx to reassign the new cert files\n app.use(\n '/reload-certs',\n async () => (secureCtx = await createSecureContext())\n )\n // graceful shutdown prevents new clients from connecting & waits for to diconnect\n app.use(graceful(httpsServer, shutdownOptions))\n // websocket uses same fd\n attachWebSocket(httpsServer)\n // callback gets public facing ip\n httpsServer.listen(sslPort, checkPublicIpAddress)\n }\n\n const httpServer = http.createServer(app)\n app.use(graceful(httpServer, shutdownOptions))\n\n if (sslEnabled) {\n // set up a route to redirect http to https\n httpServer.get('*', function (req, res) {\n res.redirect('https://' + req.headers.host + req.url)\n })\n } else {\n attachWebSocket(httpServer)\n }\n httpServer.listen(port, checkPublicIpAddress)\n}", "async function startWebServer () {\n if (sslEnabled) {\n // Get CA cert\n secureCtx = await createSecureContext()\n\n // renew certs without restarting the server\n const httpsServer = https.createServer(\n {\n SNICallback: (_, cb) => cb(null, secureCtx)\n },\n app\n )\n\n // update secureCtx to refresh certificate\n app.use(\n certLoadPath,\n async () => (secureCtx = await createSecureContext(true))\n )\n\n // graceful shutdown prevents new clients from connecting & waits\n // up to `shutdownOptions.forceTimeout` for them to disconnect\n app.use(shutdown(httpsServer))\n\n // service mesh uses same port\n attachServiceMesh(httpsServer)\n\n // callback figures out public-facing addr\n httpsServer.listen(sslPort, checkPublicIpAddress)\n }\n // run unsecured port regardless\n const httpServer = http.createServer(app)\n\n // Use graceful shutdown middleware\n app.use(shutdown(httpServer))\n\n if (sslEnabled) {\n // set up a route to redirect http to https\n httpServer.all('*', function (req, res) {\n res.redirect('https://' + req.headers.host + req.url)\n })\n } else {\n attachServiceMesh(httpServer)\n }\n\n httpServer.listen(port, checkPublicIpAddress)\n // write out our process id for stop scripts\n fs.writeFileSync(`${process.title}.pid`, `${process.pid}\\n`, 'utf-8')\n}", "function https_start(){\n\t\n\t//Log the server address and port\n\tconsole.log(\"Starting secure server\", httpsServer.address().address + PORT_SECURE);\n\t\n}", "function startExpressServer(){\n\tserver = app.listen(environmentVariables.portNo, function(){\n\t\tvar host = server.address().address;\n\t\tvar port = server.address().port;\n\n\t\tlogger.info(\"Express Server - Server is operational: \" + host + \" \" + port);\n\t});\n\t//Function call to load routes\n\trouteLoader.loadAppRoutes(app);\n}", "function runApp() {\n var app = express();\n configureApp(app);\n app.listen(8080);\n console.log(\"Server Started\")\n }", "function createServer(key, cert, port) {\n https.createServer({\n key,\n cert,\n }, app.callback()).listen(port);\n}", "function start() {\r\n test();\r\n var httpService = http.createServer(serve);\r\n httpService.listen(ports[0], 'localhost');\r\n var options = { key: key, cert: cert };\r\n var httpsService = https.createServer(options, serve);\r\n httpsService.listen(ports[1], 'localhost');\r\n}", "serve() {\n // setup port for express application that using based on config on .env file\n this\n .core\n .app\n .set('port', this.core.env.APP_PORT)\n // create server for http\n this\n .core\n .make('server', http.createServer(this.core.app))\n // listen those port for http server\n this\n .core\n .server\n .listen(this.core.env.APP_PORT)\n // make event handler listening when application is listen to those port\n this\n .core\n .server\n .on('listening', () => {\n this.onListening()\n })\n }", "function createServer(port, sslopts) {\n return sslopts && sslopts.key && sslopts.cert\n ? https.createServer(sslopts, app).listen(port, () => {\n console.log(`https on port ${port}`);\n })\n : http.createServer(app).listen(port, () => {\n console.log(`http on port ${port}`);\n });\n}", "function enableSSL(app, env) {\n if (env.sslKey) {\n var crypto = require('crypto');\n app.setSecure(crypto.createCredentials({\n key: env.sslKey,\n cert: env.sslCrt\n }));\n }\n}", "_createHttpsServer(binding) {\n if (binding.key === undefined ||\n binding.cert === undefined) {\n throw new Error('Missing private key or certificate for ' + binding.address + ':' + binding.port);\n }\n\n return https.createServer({\n key: binding.key,\n cert: binding.cert\n }, this._express);\n }", "function createServer(app)\n{\n http.createServer(app).listen(app.get('port'), function ()\n {\n const INIT_MESSAGE = 'AUTH service listening on port ';\n logger.info(\"[\" + new Date() + \"]\", INIT_MESSAGE + app.get('port'));\n });\n}", "function startAppRegistrationServer(){\n\tvar credentials = {key:privateKey,cert:certificate};\n\tvar app = express();\n\tvar staticFilePath = __dirname + '/webPortal/public';\n\tapp.use('/static',express.static(staticFilePath));\n\tapp.use('/static',express.static(staticFilePath));\n\tapp.use('/static',express.static(staticFilePath));\n\tapp.use(cors());\n\tapp.use(bodyParser.urlencoded({extended:false}));\n\tapp.use(bodyParser.json({limit:'50mb'}));\n\tvar httpsServer;\n\tvar listeningPort = 80;\n\tif(appRegistrationSecureMode){\n\t\thttpsServer = https.createServer(credentials,app);\n\t\tlisteningPort = 443;\n\t}\n\telse{\n\t\thttpsServer = http.createServer(app);\n\t}\n\n\tapp.get('/', function(req, res){\n\t\tres.sendFile(path.join(staticFilePath,'voiceInput.html'));\n\t});\n\tapp.post('/voice', function(req,res){\n\t\tSpeechHandler(req,res, connectionsManager);\n\t});\n\tapp.post('/text', function(req,res){\n\t\tTextHandler(req, res, connectionsManager);\n\t});\n\tapp.post('/talkbackdummy', function(req, res){\n\t\tconnectionsManager.emitEvent(\"sendToTalkback\", \"dummy\", req.body);\n\t\tres.send(\"ok\");\n\t});\n\thttpsServer.listen(process.env.PORT || listeningPort,function(){\n\t\tconsole.log(\"App Registration portal started\");\n\t});\n}", "function startHttpListener() {\n\n // build our app\n const app = express();\n\n // use CORS (default is allow everything when enabled)\n app.use(cors());\n\n // have express decode URLs\n app.use(\n express.urlencoded({\n extended: true\n })\n );\n\n // have express do basic JSON parsing\n app.use(express.json({type: ['application/json', 'application/fhir+json']}));\n\n // configure root handler people can make sure it works\n app.get('/', async (req, res) => {\n res.send('Server is alive and listening...');\n });\n\n app.post('/notification', handleNotificationPost)\n\n // configure 404 handler\n // eslint-disable-next-line no-unused-vars\n app.use(function(req, res, next) {\n res.status(404).send('404 - Not Found');\n });\n\n // listen on the default port or the one sepcified\n app.listen(\n localListenPort, \n () => console.log(`Listening on http://localhost:${localListenPort}`)\n );\n}", "async function start( env, args ) {\n\n // Create an express server as the main mount point.\n const mount = Express();\n\n // Fetch the server property from the environment and attach the\n // express mount point to it.\n const { server } = env;\n if( !server ) {\n throw new Error('No \"server\" property in environment');\n }\n server.mount = mount;\n\n // Configure the server by running the ds:configure command.\n const configure = this['ds:configure'];\n if( !configure ) {\n throw new Error('ds:configure command not found');\n }\n await configure( env, args );\n\n const { config } = server;\n const { port, mountPath } = config;\n\n // Check for non-root mount path.\n let httpServer = mount;\n if( mountPath != '/' ) {\n mountPath = absPath( mountPath );\n httpServer = Express();\n httpServer.use( mountPath, mount );\n }\n\n // The server's (locally) public URL.\n const serverURL = `http://localhost:${port}`;\n\n // Attach proxy endpoints.\n setupProxies( config, httpServer, serverURL );\n\n // Start the HTTP server.\n httpServer.listen( port, () => {\n const url = serverURL+mountPath;\n console.log(`Dev server running @ ${url}`);\n opn( url );\n });\n}", "_initialise() {\n if (this._productionFlag) {\n this._express.set('port', this._portHttps);\n try {\n this._httpsOptions = {\n 'cert': fs.readFileSync(this._sslCertificatePath),\n 'key': fs.readFileSync(this._sslPrivateKeyPath),\n 'ca': fs.readFileSync(this._sslCertificateAuthorityPath),\n };\n }\n catch (error) {\n Log.fatal(`Unable to load SSL certificate files.`);\n }\n this._server = https.createServer(this._httpsOptions, this._express);\n this._server.listen(this._portHttps, this._ipAddress);\n this._server.on('listening', () => Log.info(`HTTPS web server started listening on ${this._ipAddress}:${this._portHttps}.`));\n if (this._redirectFlag) {\n this._serverRedirect = http.createServer((request, response) => {\n response.writeHead(301, { 'Location': `https://${this._hostname}${request.url}` });\n response.end();\n });\n this._serverRedirect.listen(this._portHttp);\n this._serverRedirect.on('listening', () => Log.info(`Fallback redirect HTTP server started listening on ${this._ipAddress}:${this._portHttp}.`));\n }\n }\n else {\n this._express.set('port', this._portHttp);\n this._server = http.createServer(this._express);\n this._server.listen(this._portHttp);\n this._server.on('listening', () => Log.info(`HTTP web server started listening on port ${this._ipAddress}:${this._portHttp}.`));\n }\n this._server.on('error', (error) => this._errorCallback(error));\n Log.info('HTTPServer initialised.');\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
query a participant of a study
async participant(parent, args, ctx, info) { if (!ctx.request.userId) { throw new Error("You must be logged in to do that!"); } // TODO check authorization (being an admin or a researcher of the study) const participant = await ctx.db.query.profile( { where: { id: args.participantId, }, }, info ); return participant; }
[ "async participantStudyResults(parent, args, ctx, info) {\n if (!ctx.request.userId) {\n throw new Error(\"You must be logged in to do that!\");\n }\n\n const results = await ctx.db.query.results(\n {\n where: {\n OR: [\n {\n user: {\n id: args.participantId,\n },\n },\n {\n guest: {\n id: args.participantId,\n },\n },\n ],\n study: {\n id: args.studyId,\n },\n },\n },\n info\n );\n return results;\n }", "async myParticipatedStudies(parent, args, ctx, info) {\n // check if the user has permission to see all users\n if (!ctx.request.userId) {\n throw new Error(\"You must be logged in\");\n }\n const profile = await ctx.db.query.profile(\n {\n where: {\n id: ctx.request.userId,\n },\n },\n `{ id participantIn { id } }`\n );\n return ctx.db.query.studies(\n {\n where: {\n id_in: profile.participantIn.map((study) => study.id),\n },\n orderBy: \"createdAt_DESC\",\n },\n info\n );\n }", "async participantResults(parent, args, ctx, info) {\n if (!ctx.request.userId) {\n throw new Error(\"You must be logged in to do that!\");\n }\n\n const results = await ctx.db.query.results(\n {\n where: {\n OR: [\n {\n user: {\n id: args.participantId,\n },\n },\n {\n guest: {\n id: args.participantId,\n },\n },\n ],\n study: {\n id: args.studyId,\n },\n },\n },\n info\n );\n return results;\n }", "function readParticipant(req, res) {\n const idConference = req.sanitize('idconf').escape();\n const post = { idConference: idConference };\n const query = connect.con.query('SELECT idParticipant, nomeParticipante FROM conf_participant where ? order by idParticipant desc',\n post,\n function(err, rows, fields) {\n console.log('query: ', query.sql);\n if(err){\n console.log(err);\n res.status(jsonMessages.db.dbError.status).send(jsonMessages.db.dbError);\n } else {\n if(rows.length == 0) {\n res.status(jsonMessages.db.noRecords.status).send(jsonMessages.db.noRecords);\n } else {\n res.send(rows);\n }\n }\n });\n}", "async myStudies(parent, args, ctx, info) {\n // check if the user has permission to see all users\n if (!ctx.request.userId) {\n throw new Error(\"You must be logged in\");\n }\n\n // query parameters where author is the current user\n return ctx.db.query.studies(\n {\n where: {\n AND: [\n {\n OR: [{ isHidden: null }, { isHidden: false }],\n },\n {\n OR: [\n {\n author: {\n id: ctx.request.userId,\n },\n },\n {\n collaborators_some: {\n id: ctx.request.userId,\n },\n },\n ],\n },\n ],\n },\n orderBy: \"createdAt_DESC\",\n },\n info\n );\n }", "function getAnalyses(study, name, id) {\r\n var session = driver.session();\r\n //partie cypher de base pour récupérer les analyses\r\n var query = \"MATCH (s:Study)-[r:hasAnalysis]->(a:AnalysisEntityClass) WHERE \"\r\n //Partie cypher si l'input est une Study\r\n if (study.length > 0) {\r\n for (var i = 0; i < study.length; i++) {\r\n if (i != study.length - 1) {\r\n query = query + \"toLower(s.name) CONTAINS toLower('\" + study[i] + \"') OR \"\r\n }\r\n else {\r\n query = query + \"toLower(s.name) CONTAINS toLower('\" + study[i] + \"')\"\r\n }\r\n }\r\n } else { // partie cypher si l'input est une analyse.\r\n if (name.length > 0) {\r\n query = query + \"toLower(a.name) CONTAINS toLower('\" + name + \"') AND a.uuid = '\" + id + \"'\"\r\n\r\n }\r\n }\r\n query = query + \" RETURN DISTINCT a\"\r\n return session\r\n .run(\r\n query)\r\n .then(result => {\r\n return result.records.map(record => {\r\n return new Study(record.get('a'))\r\n });\r\n })\r\n .catch(error => {\r\n throw error;\r\n })\r\n .finally(() => {\r\n return session.close();\r\n });\r\n}", "async getInvitationalStudy (invitationCode) {\n const query = 'FOR study IN studies FILTER study.invitationCode == @invitationCode RETURN study'\n const bindings = { invitationCode: invitationCode }\n applogger.trace(bindings, 'Querying \"' + query + '\"')\n const cursor = await db.query(query, bindings)\n const study = await cursor.next()\n return study\n }", "async getMatchedNewStudies (userKey) {\n // TODO add BMI to query\n const query = `FOR study IN studies\n FILTER !!study.publishedTS\n LET partsN = FIRST (\n RETURN COUNT(\n FOR part IN participants\n FILTER !!part.studies\n FILTER study._key IN part.studies[* FILTER !!CURRENT.acceptedTS].studyKey\n RETURN 1\n )\n )\n FILTER !study.numberOfParticipants || study.numberOfParticipants > partsN\n FOR participant IN participants\n LET age = DATE_DIFF(participant.dateOfBirth, DATE_NOW(), \"year\")\n FILTER participant.userKey == @userKey\n AND study._key NOT IN participant.studies[*].studyKey\n AND participant.language IN study.generalities.languages[*]\n AND participant.country IN study.inclusionCriteria.countries[*]\n AND age >= study.inclusionCriteria.minAge AND age <= study.inclusionCriteria.maxAge\n AND participant.sex IN study.inclusionCriteria.sex\n AND participant.studiesSuggestions == TRUE\n AND study.inclusionCriteria.diseases[*].conceptId ALL IN participant.diseases[*].conceptId\n AND study.inclusionCriteria.medications[*].conceptId ALL IN participant.medications[*].conceptId\n AND !study.invitational\n RETURN study._key`\n\n const bindings = { userKey: userKey }\n applogger.trace(bindings, 'Querying \"' + query + '\"')\n const cursor = await db.query(query, bindings)\n return cursor.all()\n }", "async studyResults(parent, args, ctx, info) {\n const study = await ctx.db.query.study(\n { where: { slug: args.slug } },\n `{ id }`\n );\n\n const results = await ctx.db.query.results(\n {\n where: {\n study: {\n id: study.id,\n },\n },\n },\n info\n );\n return results;\n }", "function queryAssetsByParticipant(qType, pType, elementId, formId) {\n var id = document.forms[formId][\"participantId\"].value;\n\n if (pType == 'Artist') {\n id = \"?artist=resource%3Aorg.artledger.Artist%23\"+id;\n } else {\n id = \"?owner=resource%3Aorg.artledger.Owner%23\"+id;\n }\n httpGET(RESTQUERYAPI+qType+\"/\"+id, elementId);\n}", "function searchStudyByID() {\n const id = document.querySelector('#inputID').value;\n fetch(studyByIdURL + id, {\n method: \"GET\",\n })\n .then(response => response.json())\n .then(function(response) {\n console.log(response);\n // clear container for cards\n clearCards();\n // create card for study\n createCard(response);\n })\n .catch(error => console.error('Error:', error))\n}", "function getParticipants(callback) {\n\tquery(\"select * from participants\", callback);\n}", "static getStudyInSession(opencgaSession, studyId) {\n let study = {};\n for (const p of opencgaSession?.projects) {\n for (const s of p.studies) {\n if (s.id === studyId || s.fqn === studyId) {\n study = s;\n break;\n }\n }\n }\n return study;\n }", "async countStudyParticipants(parent, args, ctx, info) {\n const { where } = args;\n if (!ctx.request.userId) {\n throw new Error(\"You must be logged in to do that!\");\n }\n return ctx.db.query.profilesConnection({ where }, info);\n }", "static async getSessions(credentials, query) {\n let params = { doctor: credentials.staff, hospital: credentials.hospital };\n //params = {};\n if (query.status) params[\"originalConversation.status\"] = query.status;\n try {\n const sessions = await Session.find(params)\n .select(\"associatedEMR originalConversation lastEdit\")\n .populate({\n path: \"associatedEMR\",\n select: \"hospital\",\n populate: {\n path: \"hospital\",\n model: \"Hospital\",\n select: \"name email\",\n },\n })\n .populate(\"patient\");\n return successMessage(sessions, \"doctor's session have been retrieved\");\n } catch (err) {\n return serverError(\n {\n request: err.message,\n },\n \"failed to retrieve session list\"\n );\n }\n }", "function runParticipants(people) {\n if(people == \"turk\"){ //if running study on Mturk, want to read in data normally and take next available row \n //also want to change so here in the child coniditon you don't see the input slide, only in other condition\n experiment.subage = \"turk\";\n participants = \"turk\"; \n }\n //if you are NOT running the mturk condition\n if(people == \"child\"){\n participants = \"child\";\n } if(people == \"adult\"){\n experiment.subage = \"adult\"; //otherwise would input in the child condition\n participants = \"adult\";\n }\n //want to only take in available row based on the condition you are in -- in child condition, only take in available adult rows; in adult condition, only take in available child rows\n experiment.uniqueTurker(); \n}", "study(id) {\n return new Study({ clientSession: this.clientSession, id, parent: this });\n }", "async function getChatsByParticipants(participant) {\n try {\n // define chat collection\n const chatsCollection = await getCollection();\n\n const chat = await chatsCollection.find({ participants: { $all: participant } }).toArray();\n\n return chat;\n } catch (error) {\n console.log(error.message);\n }\n}", "function getParticipant(){\n let e = document.getElementById(\"participantSelection\");\n return e.options[e.selectedIndex].value;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
returns password string generated based on options propery
generate() { let password = ''; let characters = this.getAllPossibleCharacters(); let randomValues = new Uint8Array(this.options.length || 16); crypto.getRandomValues(randomValues); for (let i = 0; i < randomValues.length; i++) { password += characters[randomValues[i] % characters.length]; } if (!this.isPasswordMatchesOptions(password)) { return this.generate(); } else { return password; } }
[ "function generatePassword() {\n password_generated = \"\";\n for (let i = 0; i < pass_length; i++) {\n password_generated = password_generated + password_options[randomGen(string_length)];\n }\n }", "function generatePassword() {\n // Gather inputs from password criteria form\n const length = lengthSlider.value;\n\n // Gather the password criteria\n const passwordCriteria = getCriteria();\n\n // Generate the password output\n let passwordOutput = \"\";\n if (passwordCriteria != null && passwordCriteria.length > 0) {\n for(var i = 0; i < length; i++) {\n let p = Math.floor(Math.random() * passwordCriteria.length);\n\n if (passwordCriteria[p] === \"0\") {\n passwordOutput = passwordOutput += getOptions(\"letters\");\n }\n\n if (passwordCriteria[p] === \"1\") {\n passwordOutput = passwordOutput += getOptions(\"letters\").toUpperCase();\n } \n\n if (passwordCriteria[p] === \"2\") {\n passwordOutput = passwordOutput += getOptions(\"numbers\");\n } \n\n if (passwordCriteria[p] === \"3\") {\n passwordOutput = passwordOutput += getOptions(\"characters\");\n } \n }\n }\n\n // Return the generated password\n return passwordOutput\n}", "function generatePassword() {\n let criteria = getCriteria();\n let charStringandLength = confirmOptions(criteria);\n return constructPassword(charStringandLength);\n}", "function generatePassword() {\n\t// 1 = useSymbols, 2 = length, 3 = useMixedCase\n\tvar options = getOptions();\n\tvar finalStr = \"\";\n\n\t// depending if the user chose to include symbols then create an\n\t// array of arrays to use Math.random() twice\n\tif(options[0] && options[2]) {\n\t\tvar arraysCon = [lowerAlpha, upperAlpha, numbers, allowedSymbols];\n\t} else if(options[0] && !options[2]) {\n\t\tvar arraysCon = [lowerAlpha, allowedSymbols, numbers];\n\t} else if(options[2] && !options[0]) {\n\t\tvar arraysCon = [lowerAlpha, upperAlpha, numbers];\n\t} else {\n\t\t// default back to just lowerAlpha and numbers\n\t\tvar arraysCon = [lowerAlpha, numbers];\n\t}\n\t\n\t// loop through the length for what the user supplied\n\tfor(var i = 0; i < options[1]; i++) {\n\t\t// first random is to choose between alphaUpper, alphaLower, number \n\t\t// or symbols (if used selected it)\n\t\tvar firstNum = Math.floor(Math.random() * arraysCon.length);\n\t\tfinalStr = finalStr + (arraysCon[firstNum][Math.floor(Math.random() * arraysCon[firstNum].length)]);\n\t}\n\n\tdocument.getElementById(\"generatedPass\").innerHTML = finalStr;\n}", "function generatePassword() {\n userInput();\n var output = characterOptions(passwordLength);\n return output;\n}", "function buildPassword() {\n var password = \"\";\n var selectedCharType = [];\n\n // Use if statements to determine which arrays to add to selectedCharType\n if (useLowerCase) {\n selectedCharType = selectedCharType.concat(lowerCase);\n }\n if (useUpperCase) {\n selectedCharType = selectedCharType.concat(upperCase);\n }\n if (useNumber) {\n selectedCharType = selectedCharType.concat(number);\n }\n if (useSpecialChar) {\n selectedCharType = selectedCharType.concat(specialChar);\n }\n\n // Build password using requirements for length and character type\n for (var i = 0; i < passwordLength; i++) {\n password = password + selectedCharType[Math.floor(Math.random() * selectedCharType.length)];\n }\n console.log(\"Password\", password);\n return password;\n}", "function generatePassword() {\n var finalPasswordoptions = []\n var finalPassword = []\n characterElements = lowerCaseCharacters.join(\"\")\n var options = choosePasswordOptions(); \n console.log(options) \n if (options.numbers===true) {\n finalPasswordoptions.push(...numericCharacters);\n } if (options.special===true) {\n finalPasswordoptions.push(...specialCharacters);\n } if (options.uppercase===true) {\n finalPasswordoptions.push(...upperCaseCharacters);\n } if (options.lowercase===true) {\n finalPasswordoptions.push(...lowerCaseCharacters);\n } \n for (var i = 0; i < options.length; i++) {\n var finalCharacter = getRandom(finalPasswordoptions)\n finalPassword.push(finalCharacter)\n }\n return finalPassword.join(\"\")\n}", "function generatePwdCharset() {\n setLength(); \n // validate the length \n if (isLengthSet()) {\n \n setCharOptions();\n //validate the char options\n if (validateCharOptions()) {\n var chars = \"\";\n var keys = Object.keys(builder);\n keys.forEach(k => {\n if (k !== \"pwdLength\") {\n if (builder[k].inUse) {\n chars += builder[k].chars;\n }\n }\n });\n \n return chars;\n\n } else {\n alert(\"Please confirm at least one of the Characters options!\");\n }\n } else {\n alert(\"Please select a number between 8 and 128!\");\n }\n}", "function getRandomPassword(pLength, useUpperCase, useLowerCase, useNums, useSpecChars) {\n // Password string that will be returned.\n var pwd = \"\";\n\n // Initialize string of possible characters that will be used\n // to generate password.\n var charsToUse = \"\";\n\n // If Upper Case was selected then add all the upper case letters to \n // the characters that can be used in password.\n if (useUpperCase) {\n charsToUse += \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\";\n };\n\n // If Lower Case was selected then add all the lower case letters to\n // the characters that can be used in the password.\n if (useLowerCase) {\n charsToUse += \"abcdefghijklmnopqrstuvwxyz\";\n };\n\n // If Numbers were selected then add all the integers from 0 to 9 to\n // the characters that can be used in the password.\n if (useNums) {\n charsToUse += \"0123456789\";\n };\n\n // If Special Characters were selected then add special characters to\n // the characters that can be used in the password.\n if (useSpecChars) {\n charsToUse += \" !#$%&'()*+,-./:;<=>?@[\\]^_`{|}~\";\n };\n\n // Concatenate a random character from the charsToUse string for the length\n // of password entered.\n for (var i = 1; i <= pLength; i++) {\n // Get a random number and use this to index into the available characters string.\n pwd += charsToUse[Math.floor(Math.random() * charsToUse.length)];\n };\n\n // Return the password created.\n return pwd;\n}", "function generatePassword() {\n // set the criteria conditions\n setConditions();\n // randomize the password\n randomize();\n // return the generated password\n return password.pwd;\n}", "function generatePassword() {\n let password = \"\";\n\n // Reset the passwordDetails object to a \"clean slate\" for the current password generation attempt.\n initializePasswordDetails();\n\n // Gather user input, including criteria and desired password length.\n if (getUserInput()) {\n // If we have valid criteria and desired password length, construct the new password one character at a time.\n while (passwordDetails.desiredPasswordLength > 0) {\n password += getNextPasswordCharacter();\n passwordDetails.desiredPasswordLength--;\n }\n }\n\n // Return the new password.\n return password;\n}", "function generatePassword() {\n var result = \"\";\n var pwLength = chooseLength;\n var characterSet = [];\n characterSet = charSet1.concat(charSet2, charSet3, charSet4);\n for (var i = 0; i < pwLength; i++)\n result += characterSet[(Math.floor(Math.random() * characterSet.length))];\n return result;\n}", "function makePassword() {\n var text = \"\";\n var possible = \"ABCDEFGHJKLMNPQRSTUVWXYZabcdefhjlxyz2456789\";\n\n for( var i=0; i < 10; i++ )\n text += possible.charAt(Math.floor(Math.random() * possible.length));\n\n return text;\n }", "function generatePassword() {\n var password = \"\"; // empty string to hold generated password \n var available = []; // An array placeholder for user generated amount of length\n\n // if statements concatenantes any of the confirms that return true\n if (confirmLower) {\n available = available.concat(lowercase);\n };\n\n if (confirmUpper) {\n available = available.concat(uppercase);\n };\n\n if (confirmNumeric) {\n available = available.concat(number);\n };\n\n if(confirmSymbol) {\n available = available.concat(symbol);\n };\n\n // Start random selection for passwordLength, based on selected options\n for (var i = 0; i < passwordLength; i++) {\n password += available[Math.floor(Math.random() * available.length)]; \n }; \n \n return password; // returns password onto the screen\n}", "function generatePassword() {\n const passLen = askLength();\n const charSet = buildCharSet();\n if (charSet.length < 1) {\n alert(\"You must select at least one character type!\");\n return \"\";\n }\n\n return Array.from({ length: passLen }, () => randomChar(charSet)).join(\"\");\n}", "function buildPassword( len, sets) {\n const charSets = [\n \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\",\n \"abcdefghijklmnopqrstuvwxyz\",\n \"0123456789\",\n \"!@#$%&[]{}|<>/?\"\n ];\n\n let selectorStr = \"\";\n for (let i = 0; i < 4; i++) { //already validated there are only 4 characters\n if (sets.charAt(i).toUpperCase() === 'Y') {\n selectorStr += charSets[i];\n }\n }\n\n let password = \"\";\n for (let i = 0; i < len; i++) {\n // get random number for index into charSet\n let index = Math.floor(Math.random(selectorStr.length) * selectorStr.length);\n password += selectorStr.charAt(index);\n }\n\n return password;\n}", "function generatePassword(){\n var options = getUserInput();\n var guaranteedChars = [];\n var possibleChars = [];\n var passwordResult = [];\n\n // each of these adds all characters of that type to possibleChars array and pushes 1 of the characters from the character options array at the top of the page to the guaranteedChars array\n if (options.wantsSpecial){\n possibleChars = possibleChars.concat(specialCharacterOptions)\n guaranteedChars.push(getRandom(specialCharacterOptions))\n }\n if (options.wantsNumber){\n possibleChars = possibleChars.concat(numberOptions)\n guaranteedChars.push(getRandom(numberOptions))\n }\n if (options.wantsUpper){\n possibleChars = possibleChars.concat(upperLetterOptions)\n guaranteedChars.push(getRandom(upperLetterOptions))\n }\n if (options.wantsLower){\n possibleChars = possibleChars.concat(lowerLetterOptions)\n guaranteedChars.push(getRandom(lowerLetterOptions))\n }\n // for loop to loop through the number of times the user chose calls the get random function of the possibleChars array to get random characters from that array. then pushes the result of that to passwordResult array\n for(i=0; i<options.length; i++){\n var possibleChar = getRandom(possibleChars)\n passwordResult.push(possibleChar)\n }\n for(i=0; i<guaranteedChars.length; i++){\n passwordResult[i] = guaranteedChars[i]\n }\n // returns all the objects in the passwordResult array and joins them together to create a single string\n return passwordResult.join(\"\")\n}", "function generatePassword() {\n const length = getLength();\n let charsetString = getCharset();\n\n if (charsetString == \"\") {\n alert(\"Please select at least one valid character type!\");\n return \"\";\n }\n\n let password = \"\";\n \n for (let i=0; i<length; i++) {\n password += charsetString[Math.floor(Math.random() * charsetString.length)];\n }\n return password;\n}", "password() {\n if (!this.options.password) this.error('An app-password is required');\n // reject Nextcloud user passord (enforce 'app-password')\n if (!/^([a-z0-9]{5}-){4}[a-z0-9]{5}$/i.test(this.options.password)) {\n this.error('Please use a Nextcloud app-password, not your login password.');\n return '';\n }\n return this.options.password;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Handles changes to DocumentManager.getCurrentDocument()
function _onCurrentDocumentChange() { var doc = DocumentManager.getCurrentDocument(), container = _editorHolder.get(0); var perfTimerName = PerfUtils.markStart("EditorManager._onCurrentDocumentChange():\t" + (!doc || doc.file.fullPath)); // Remove scroller-shadow from the current editor if (_currentEditor) { ViewUtils.removeScrollerShadow(container, _currentEditor); } // Update the UI to show the right editor (or nothing), and also dispose old editor if no // longer needed. if (doc) { _showEditor(doc); ViewUtils.addScrollerShadow(container, _currentEditor); } else { _showNoEditor(); } PerfUtils.addMeasurement(perfTimerName); }
[ "function _getCurrentDocument() {\n return DocumentManager.getCurrentDocument();\n }", "_onDocumentChanged() {\n this._updateButton(true)\n\n this.extendState({\n unsavedChanges: true\n })\n }", "function documentEdited() {\n\ttry {\n \t MM.BC.documentEdited();\n\t\tupdateRelatedFiles();\n\t\tcheckIfDocumentChanged();\n\t} catch (e) {\t\n\tMM.BC.log('error in documentEdited:' + e);\n\t}\n}", "function getCurrentDocument() {\n return service.currentBook.currentDocument;\n }", "function onDocumentClick(currentDocument) {\n onUpdate(currentDocument.documentId);\n closeModal();\n }", "function change_doc() {\n\tdoc.changed = true;\n\tinitialize_mandatory_fields();\n\tremove_mandatory_highlight(mandatory_fields);\n\tenable_save_button();\n}", "function setDocumentDetails() {\n //self.singleDoc.currentlyusedby = self.singleDoc.currentlyusedby.trim();\n //self.singleDoc.document_ext = angular.lowercase(self.singleDoc.document_ext);\n var doc_ext = getFileExtention(self.singleDoc);\n doc_ext = angular.lowercase(doc_ext);\n self.singleDoc.doc_ext = doc_ext;\n if (doc_ext == 'pdf' || doc_ext == 'txt' || doc_ext == 'png' || doc_ext == 'jpg' || doc_ext == 'jpeg' || doc_ext == 'gif') {\n /* Generate view link if document is pdf/image/txt */\n if (self.singleDoc.doc_uri !== null) {\n var uriArr = self.singleDoc.doc_uri.split('/');\n var filename = uriArr[uriArr.length - 2] + '/' + uriArr[uriArr.length - 1];\n var filenameArr = filename.split('.');\n var extension = filenameArr[filenameArr.length - 1].toLowerCase();\n\n try {\n var dfilename = decodeURIComponent(filename);\n filename = dfilename;\n } catch (err) { }\n var filenameEncoded = encodeURIComponent(filename);\n var documentNameEncoded = encodeURIComponent(self.singleDoc.documentname);\n documentsDataService.viewdocument(self.singleDoc.doc_id).then(function (res) {\n self.singleDoc.viewdocumenturi = res;\n })\n } else {\n self.singleDoc.viewdocumenturi = '';\n }\n } else {\n self.viewable = false;\n }\n\n if (self.editdoc == true) {\n // if (self.globalDocview == true) { for US4153\n matters = [{\n name: self.singleDoc.matter.matter_name,\n matterid: self.singleDoc.matter.matter_id\n }];\n self.categorySelected = self.singleDoc.doc_category.doc_category_name;\n self.docModel.matter_id = self.singleDoc.matter.matter_id;\n // }\n self.docModel.doc_name = self.singleDoc.doc_name;\n self.docModel.date_filed_date = (utils.isEmptyVal(self.singleDoc.date_filed_date) || self.singleDoc.date_filed_date == 0 || self.singleDoc.date_filed_date == null) ? '' : moment.unix(self.singleDoc.date_filed_date).format('MM/DD/YYYY');\n localStorage.setItem(\"documentName\", self.docModel.doc_name);\n self.docModel.category = self.singleDoc.doc_category;\n self.docModel.needs_review = (self.singleDoc.needs_review == \"1\") ? true : false;\n self.docModel.showNeedReview = (self.singleDoc.needs_review == \"1\") ? true : false;\n self.docModel.review_user = self.docModel.review_user; // set review user id\n self.docModel.memo = utils.isNotEmptyVal(self.singleDoc.memo) ? self.singleDoc.memo : '';\n if (self.singleDoc.review_user) {\n self.docModel.reviewUser = (self.singleDoc.review_user.length == 1 || self.singleDoc.review_user.length == 0) ? [self.singleDoc.review_user.toString()] : self.singleDoc.review_user.toString().split(\",\");\n } else {\n self.docModel.reviewUser = '';\n }\n //self.singleDoc.plaintiff_name = $.trim(self.singleDoc.plaintiff_name);\n self.singleDoc.plaintiff_name = $.trim(self.singleDoc.associated_party.associated_party_name);\n\n if (self.singleDoc.associated_party && self.singleDoc.associated_party.associated_party_id == 0) {\n self.docModel.associated_party = '';\n } else {\n self.docModel.associated_party = utils.isNotEmptyVal(self.singleDoc.associated_party) ? self.singleDoc.associated_party : '';\n }\n\n // if (self.singleDoc.plaintiff_name != null && self.singleDoc.plaintiff_name != \"\") {\n // self.docModel.associated_party_id = self.singleDoc.doc_plaintiff;\n // } else {\n // self.docModel.associated_party_id = '';\n // }\n self.docModel.party_role = self.singleDoc.associated_party.associated_party_role;\n if (self.singleDoc.doc_tags != null && self.singleDoc.doc_tags != '') {\n //var tagsOfDoc = self.singleDoc.doc_tags.split(' ');\n angular.forEach(self.singleDoc.doc_tags, function (datavalue, datakey) {\n self.docAddTags.push({\n \"name\": datavalue.tag_name\n });\n });\n }\n\n\n // self.categorySelected = self.singleDoc.categoryname;\n self.moreInfoSelect = self.singleDoc.more_info_type;\n setMoreInfoType(self.singleDoc.more_info_type);\n self.setMoreInformationType(self.docModel.category.doc_category_id);\n self.moreinfoPrased = self.singleDoc.more_info_type;\n\n //self.docModel.associated_party_id = utils.isNotEmptyVal(self.singleDoc.moreInfo_parsed.associated_party_id) ?\n //self.singleDoc.moreInfo_parsed.associated_party_id : '';\n\n // self.docModel.party_role = utils.isNotEmptyVal(self.singleDoc.moreInfo_parsed.party_role) ?\n // self.singleDoc.moreInfo_parsed.party_role : '';\n }\n return true;\n }", "get newDoc() {\n return this._doc || (this._doc = this.changes.apply(this.startState.doc));\n }", "get newDoc() {\n return this._doc || (this._doc = this.changes.apply(this.startState.doc));\n }", "get newDoc() {\n return this._doc || (this._doc = this.changes.apply(this.startState.doc));\n }", "function _clearCurrentDocument() {\n // If editor already blank, do nothing\n if (!_currentDocument) {\n return;\n }\n \n // Change model & dispatch event\n _currentDocument = null;\n $(exports).triggerHandler(\"currentDocumentChange\");\n // (this event triggers EditorManager to actually clear the editor UI)\n }", "get newDoc() {\n return this._doc || (this._doc = this.changes.apply(this.startState.doc));\n }", "function onChangeDocument(event) {\n\n initDocEventsForFile();\n //keep the local asciidoc up to date\n if (that.fileRevision) {\n that.fileRevision.asciidoc = that.getValue();\n that.syncFileRevision.$loaded().then(\n function(data){\n that.syncFileRevision.asciidoc = that.getValue();\n if (that.syncFileRevision.fileId && that.syncFileRevision.projectId){\n that.syncFileRevision.$save().then(function(data){\n var fileRevToStore = {\n $id : that.syncFileRevision.$id,\n asciidoc : that.syncFileRevision.asciidoc,\n fileId: that.syncFileRevision.fileId,\n projectId: that.syncFileRevision.projectId\n }\n Storage.save(\"fileRevision\", fileRevToStore);\n //console.log(\"update asciidoc on firebase\");\n });\n\n }\n }\n );\n }\n\n //synchronize event on firebase if the user is connected\n //and if this event is not send by the server\n if (editor && editor.curOp && editor.curOp.command.name){\n //User change\n if (that.user != null){\n //Try with a push\n that.refFileRevisionEvent = SyncCollaborative.syncFileRevisionEvent(that.syncFileRevision.projectId, that.syncFileRevision.fileId, that.syncFileRevision.$id);\n that.refFileRevisionEvent.push({\n \"user\": that.user,\n \"event\": event\n }).setPriority(Firebase.ServerValue.TIMESTAMP);\n }\n } else {\n //API Change\n //console.log(\"doc : API change (don't fire event to firebase)\");\n if (editor){\n editor.getSession().setAnnotations([{\n row: event.data.range.start.row,\n column: event.data.range.end.column,\n text: \"a user is typing...\",\n type: \"warning\" // also warning and information\n }]);\n }\n }\n\n }", "onDocumentOpenOrContentChanged(document) {\n if (!this.startDataLoaded) {\n return;\n }\n // No need to handle file opening because we have preloaded all the files.\n // Open and changed event will be distinguished by document version later.\n if (this.shouldTrackFile(vscode_uri_1.URI.parse(document.uri).fsPath)) {\n this.trackOpenedDocument(document);\n }\n }", "function checkDocChanged() {\n if (docChanged) {\n // ignore zero-content untitled document\n if (curFileName == null &&\n editor.document.length == 0) {\n return;\n }\n\n if (confirm(\"Do you want to save the changes?\",\n \"The document has changed\")) {\n actionSave();\n }\n }\n }", "onDidSaveTextDocument(doc) {\n if (this._connectionMgr === undefined) {\n // Avoid processing events before initialization is complete\n return;\n }\n let savedDocumentUri = doc.uri.toString();\n // Keep track of which file was last saved and when for detecting the case when we save an untitled document to disk\n this._lastSavedTimer = new Utils.Timer();\n this._lastSavedTimer.start();\n this._lastSavedUri = savedDocumentUri;\n }", "function didChangeTextDocument (change) {\n\tlint(change.document);\n}", "function setDocListener() {\n var doc = editor.getDocument();\n docChanged = false;\n doc.addDocumentListener( new guiPkgs.DocumentListener() {\n equals: function(o) {\n return this === o; },\n toString: function() {\n return \"doc listener\"; },\n changeUpdate: function() {\n docChanged = true; },\n insertUpdate: function() {\n docChanged = true; },\n removeUpdate: function() {\n docChanged = true; }\n });\n }", "function replaceDoc() {\n self.docModel.documentname = '';\n self.uploaddoc = true;\n self.officeDocs = false;\n toggleButtons(false);\n toggleButtons(true, 'Cancel');\n initializeSingleFileDropnzone();\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Toggles the focused pin/card off
function toggleFocusOff() { if (focusedCard) { focusedCard.classList.remove('active-card'); } if (focusedPin) { let iconPath = focusedPin.getIcon(); let iconName = iconPath.split('/')[2].split('.')[0]; focusedPin.setIcon(ICON_PATHS.defaultIcons[iconName]); } focusedCard = null; focusedPin = null; }
[ "setFocusedFalse () {\n this._isFocused = false\n }", "focus() {\n this.toggle.focus();\n }", "function clickOff() {\n openedCards.forEach(function(card) {\n card.off('click');\n });\n}", "_toggleFocused() {\n let focused = document.activeElement === this.inputNode;\n this.toggleClass('p-mod-focused', focused);\n }", "deactivateFocus() {\n this.isFocused_ = false;\n this.adapter_.deactivateLineRipple();\n const input = this.getNativeInput_();\n const shouldRemoveLabelFloat = !input.value && !this.isBadInput_();\n const isValid = this.isValid();\n this.styleValidity_(isValid);\n this.styleFocused_(this.isFocused_);\n if (this.adapter_.hasLabel()) {\n this.adapter_.shakeLabel(this.shouldShake);\n this.adapter_.floatLabel(this.shouldFloat);\n this.notchOutline(this.shouldFloat);\n }\n if (shouldRemoveLabelFloat) {\n this.receivedUserInput_ = false;\n }\n }", "onFocusOut() {\n this.updateFocused(false);\n }", "_toggleClick() {\n const { input } = this.refs;\n if (this.maskState === 'visible') {\n this.maskState = 'hidden';\n input.value = this._obfuscatedValue;\n } else {\n this.maskState = 'visible';\n input.value = this.maskedValue;\n }\n this._toggleButtonText();\n }", "_toggleFocused() {\n let focused = document.activeElement === this.inputNode;\n this.toggleClass('lm-mod-focused', focused);\n }", "deactivateFocus() {\n this.isFocused_ = false;\n this.adapter_.deactivateLineRipple();\n const input = this.getNativeInput_();\n const shouldRemoveLabelFloat = !input.value && !this.isBadInput_();\n const isValid = this.isValid();\n this.styleValidity_(isValid);\n this.styleFocused_(this.isFocused_);\n if (this.adapter_.hasLabel()) {\n this.adapter_.shakeLabel(this.shouldShake);\n this.adapter_.floatLabel(this.shouldFloat);\n this.notchOutline(this.shouldFloat);\n }\n if (shouldRemoveLabelFloat) {\n this.receivedUserInput_ = false;\n }\n }", "onFocusOut() {\n this.updateFocused(false);\n }", "toggle() {\n if (this.isSelected) {\n this.deselect();\n } else {\n this.select();\n }\n }", "toggleControlsOff() {\n this.setState({selected: false});\n }", "disableActiveFocus() {\n this.activeFocus = false;\n }", "setFocusedTrue () {\n this._isFocused = true\n }", "focus() {\n this.$.pin.focus();\n }", "deselect() {\n this.checked = false;\n this.focused = false;\n this.cdr.markForCheck();\n }", "function focusClassToggle() {\n investAmountWrapper.classList.toggle('invest-amount-wrapper--focus');\n}", "function togglePayFocus() {\n\t\tvar $this = $(this).find(\"a\");\n\t\tmodels.togglePaymentFocus(\n\t\t\t\t$this.parents(\".ticket\").attr(\"tKey\"),\n\t\t\t\t$this.parents(\".payment\").attr(\"cID\"));\n\t}", "toggle() {\n if (!this.picker.active) {\n this.show();\n } else if (this.inputField) {\n this.picker.hide();\n }\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Triggered when a new buy token is selected and the src input requires an update based on the new expected exchange rate
function updateSrcValue() { destAmount = document.getElementById('dest-amount').value srcAmount = destAmount * (1 / (expectedRate / (10 ** 18))); displaySrcAmount(); }
[ "modifyBuyRate (newValue) {\n console.log('modifyBuyRate triggered with', newValue)\n this.state.buyRate = newValue\n }", "changeBuyRate(card) {\n Service.get(this).changeBuyRate(card);\n }", "rateFieldChanged () {\n const order = this.parseOrder()\n if (order.rate <= 0) {\n this.page.rateField.value = 0\n return\n }\n // Truncate to rate step. If it is a market buy order, do not adjust.\n const rateStep = this.market.quoteCfg.rateStep\n const adjusted = order.rate - (order.rate % rateStep)\n this.page.rateField.value = (adjusted / 1e8)\n this.previewOrder(true)\n }", "marketBuyChanged () {\n const page = this.page\n const qty = asAtoms(page.mktBuyField.value)\n const gap = this.midGap()\n if (!gap || !qty) {\n page.mktBuyLots.textContent = '0'\n page.mktBuyScore.textContent = '0'\n return\n }\n const lotSize = this.market.baseCfg.lotSize\n const received = qty / gap\n page.mktBuyLots.textContent = (received / lotSize).toFixed(1)\n page.mktBuyScore.textContent = Doc.formatCoinValue(received / 1e8)\n }", "handlePlaybackRateschange(event) {\n this.update();\n }", "function updateDestValue() {\n srcAmount = document.getElementById('src-amount').value\n destAmount = (srcAmount * (expectedRate / 10 ** 18));\n displayDestAmount();\n}", "function updatePrice() {\n // Disable purchase button until price updates\n executeTransactionButton.addClass(\"disabled\");\n\n // Toggle loading message\n loadingAlertMsg.show();\n\n $.ajax({\n url: (`https://min-api.cryptocompare.com/data/price?fsym=${selectedCoin.symbol}` +\n `&tsyms=USD&extraParams=School-project`),\n method: \"GET\",\n }).then(function (response) {\n var totalPrice = (quantityField.val() * response.USD).toFixed(2);\n pricePerDisplay.text(response.USD);\n totalPriceDisplay.text(totalPrice);\n\n // Check for sufficient funds\n if (totalPrice > availableFunds && executeTransactionButton.text() === \"PURCHASE\") {\n insufficientFundsAlert.show();\n executeTransactionButton.addClass(\"disabled\");\n } else {\n insufficientFundsAlert.hide();\n executeTransactionButton.removeClass(\"disabled\");\n }\n\n loadingAlertMsg.hide();\n });\n \n }", "function onFundingRateChanged(symbol, oldRate, newRate) {\n if (rateUpdates[symbol] === undefined) {\n rateUpdates[symbol] = 0;\n }\n rateUpdates[symbol] += 1;\n if (rateUpdates[symbol] > 100) {\n logger.results(`${symbol.toUpperCase()} rate: ${util.roundDown(newRate * 100, 4)}% (APR ${util.roundDown(newRate * 100 * 365, 2)}%)`);\n rateUpdates[symbol] = 0;\n }\n\n // only interested in the rate going up...\n if (oldRate > newRate) {\n return;\n }\n\n // See if they have a webhook url defined\n if (!alertWebhook) {\n return;\n }\n\n // Any alert levels configured for this market\n const options = fundingMarkets.find(market => market.symbol === symbol);\n if (!options.alerts) {\n return;\n }\n\n // get the alerts into rate order (lowest rate first)\n options.alerts.sort((a, b) => a.rate - b.rate);\n\n // See if we've crossed over the alert threshold\n options.alerts.forEach((alert) => {\n if (alert.lastTriggered === undefined) {\n alert.lastTriggered = moment().subtract(1, 'hours');\n }\n const freq = alert.maxFrequency || 5;\n const justNow = moment().subtract(freq, 'minutes');\n const rate = alert.rate / 100.0;\n if (newRate >= rate && oldRate < rate) {\n if (alert.lastTriggered.isBefore(justNow)) {\n logger.error(`Alert fired - ${symbol} rates crossed over ${alert.rate}%. was ${oldRate}, now ${newRate}`);\n\n callWebhook(alertWebhook, alert.alertMessage, rate, newRate, oldRate);\n alert.lastTriggered = moment();\n } else {\n logger.results(`${symbol} rates crossed over ${alert.rate}%. But sent alert in last ${freq} minutes.`);\n }\n }\n });\n}", "function onFundingRateChanged(symbol, oldRate, newRate) {\n if (rateUpdates[symbol] === undefined) {\n rateUpdates[symbol] = 0;\n }\n rateUpdates[symbol] += 1;\n trackRate(symbol, newRate);\n\n // only interested in the rate going up...\n if (oldRate > newRate) {\n return;\n }\n\n // Show the rate (occasionally)\n if (rateUpdates[symbol] > 100) {\n const best = recentBestRate(symbol);\n logger.results(`${symbol.toUpperCase()} Last Rate: ${util.roundDown(newRate * 100, 4)}% (APR ${util.roundDown(newRate * 100 * 365, 2)}%).`);\n rateUpdates[symbol] = 0;\n }\n\n // See if they have a webhook url defined\n if (!alertWebhook) {\n return;\n }\n\n // Any alert levels configured for this market\n const options = fundingMarkets.find(market => market.symbol === symbol);\n if (!options.alerts) {\n return;\n }\n\n // get the alerts into rate order (lowest rate first)\n options.alerts.sort((a, b) => a.rate - b.rate);\n\n // See if we've crossed over the alert threshold\n options.alerts.forEach((alert) => {\n if (alert.lastTriggered === undefined) {\n alert.lastTriggered = moment().subtract(1, 'hours');\n }\n const freq = alert.maxFrequency || 5;\n const justNow = moment().subtract(freq, 'minutes');\n const rate = alert.rate / 100.0;\n if (newRate >= rate && oldRate < rate) {\n if (alert.lastTriggered.isBefore(justNow)) {\n logger.error(`Alert fired - ${symbol} rates crossed over ${alert.rate}%. was ${oldRate}, now ${newRate}`);\n\n callWebhook(alertWebhook, alert.alertMessage, rate, newRate, oldRate);\n alert.lastTriggered = moment();\n } else {\n logger.results(`${symbol} rates crossed over ${alert.rate}%. But sent alert in last ${freq} minutes.`);\n }\n }\n });\n}", "function onChangeSrcAmount(e){\n setSrcAmount(e.target.value);\n }", "function openBuy(currency, value) {\n // renders the buy form\n\n // value targets the ticker element (.blink class) with its currency name and updates accordingly\n\n document.getElementById(\"buy-sell\").innerHTML = `\n <div class=\"level-item has-text-centered\">\n <article class=\"tile is-child notification is-info\">\n <h2 class=\"title\">Buy Shares</h2>\n <p id=\"live-value\">${currency} @ <strong>$${value}</strong></p>\n <div class=\"field\">\n <div class=\"control\">\n <input class=\"input is-medium\" id=\"shares-input\" type=\"number\" min=\"0\" placeholder=\"0\">\n </div>\n </div>\n <h3 class=\"title\" id=\"total-buy\">Total: <strong>$0</strong></h3>\n <a class=\"button is-medium is-warning\" id=\"confirm-buy\">CONFIRM PURCHASE</a>\n </article>\n </div>\n `;\n\n // adds an event listener to the shares input. OnChange it runs calcTotalBuys\n document.getElementById(\"buy-sell\").addEventListener(\"input\", e => {\n let amountShares = e.target.value; // number of shares entered\n let total = calcTotalBuy(value, amountShares, currency); // total cost (if affordable)\n let confirmBuyButton = document.getElementById(\"confirm-buy\");\n\n // total is true if user can afford the transaction\n total\n ? displayTotal(confirmBuyButton, total)\n : removeTotal(confirmBuyButton);\n e.stopPropagation(); // prevents duplicate event listeners\n });\n}", "function exhange_rate_update()\n{\n\n rate_value = format_currency_value($(\"#exhange_rate\").val());\n $(\"#exhange_rate\").val(rate_value);\n $.each(transactions_array, function()\n {\n this.update_zl(rate_value);\n } \n );\n update_transaction_summary();\n}", "function getRateSuccess(data){\n vm.rate = data.rates[vm.selectedBuySymbol];\n vm.buyAmount = vm.sellAmount * vm.rate;\n }", "function onDeliveryRateChanged(doc) {\n doc.amount = doc.rate * doc.qty;\n }", "function amountChanged() {\n if (isTransfer) {\n convert();\n }\n}", "async _buyAtMarketPrice(price) {\n this.initialPrice = price;\n }", "changeBuyAmount(card) {\n Service.get(this).changeBuyAmount(card);\n }", "async refresh() {\n try {\n let data = await cc.price('BTC', 'USD', { exchanges: this.exchange });\n this.updateValue(data.USD);\n } catch(err) {\n console.error(chalk.red(\"Couldn't reach Cryptocompare API\"));\n }\n }", "function onSellClick() {\n toggleNum = 0;\n $('.tokenQtyValue').text(`${coinTwoQty.toFixed(8)} ${coinTwoName}`);\n $('.tokenQtyBox').css('animation', 'outlineAnim 1s forwards 0s linear');\n setTimeout(function() {$('.tokenQtyBox').css('animation', 'none')}, 1000);\n $('.arrowTransform').css('transform', 'rotate(180deg)');\n if (maxOneRate) {\n $('.ethToToken').text(`1 ${coinTwoName} = ${maxOneRate.toFixed(6)} ${coinOneName}`);\n }\n $('.coinOneInput').on();\n changeMinRateText();\n changeOnInput(1);\n // transFee(2);\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Pretty Print XML text
static ppXML(theXML, pres = true) { return Pretty.xml(theXML, pres); }
[ "static prettifyXml(xmlDoc) {\n var xsltDoc = new DOMParser().parseFromString([\n // describes how we want to modify the XML - indent everything\n '<xsl:stylesheet xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\">',\n ' <xsl:strip-space elements=\"*\"/>',\n ' <xsl:template match=\"para[content-style][not(text())]\">',\n ' <xsl:value-of select=\"normalize-space(.)\"/>',\n ' </xsl:template>',\n ' <xsl:template match=\"node()|@*\">',\n ' <xsl:copy><xsl:apply-templates select=\"node()|@*\"/></xsl:copy>',\n ' </xsl:template>',\n ' <xsl:output indent=\"yes\"/>',\n '</xsl:stylesheet>',\n ].join('\\n'), 'application/xml');\n var xsltProcessor = new XSLTProcessor();\n xsltProcessor.importStylesheet(xsltDoc);\n var resultDoc = xsltProcessor.transformToDocument(xmlDoc);\n return resultDoc;\n }", "function formatXml(xml, escape) {\n\t xml = vkbeautify.xml(xml);\n\t if (escape) {\n\t xml = xml.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/\"/g, '&quot;');\n\t }\n\t return xml;\n\t }", "function formatxmlstring(text) {\n var ar = text.replace(/>\\s{0,}</g, \"><\")\n\t\t\t\t .replace(/</g, \"~::~<\")\n\t\t\t\t .replace(/\\s*xmlns\\:/g, \"~::~xmlns:\")\n\t\t\t\t .replace(/\\s*xmlns\\=/g, \"~::~xmlns=\")\n\t\t\t\t .split('~::~'),\n len = ar.length,\n\t\tinComment = false,\n\t\tdeep = 0,\n\t\tstr = '',\n\t\tix = 0;\n\n for (var i = 0; i < len; i++) {\n var newline = \"\\r\\n\";\n var space = \" \";\n if (ar[i].search(\"<rules\") > -1 || ar[i].search(\"</path>\") > -1)\n str += ar[i];\n //EMIE Section\n if (ar[i].search(\"<emie>\") > -1 || ar[i].search(\"</emie>\") > -1 || ar[i].search(\"<docMode>\") > -1 || ar[i].search(\"</docMode>\") > -1)\n str += newline + space + ar[i];\n //Common Section\n //for domain add two space\n if (ar[i].search(\"<domain\") > -1) {\n str += newline + space + space + ar[i];\n //if there is no path then use the next array element without new line or space and advance the loop by 1 as it is already added\n //say continue so that other entry might not affect\n if (ar[i + 1].search(\"</domain>\") > -1) {\n str += ar[i + 1]; i += 1; continue;\n }\n }\n if (ar[i].search(\"<path\") > -1) {\n //if this is the second path in a domain we need to put it in new line otherwise keep it in same line without space\n if (ar[i - 2].search(\"<path\") > -1)\n str += newline + space + space + space + ar[i];\n else\n str += ar[i];\n }\n if (ar[i].search(\"</domain>\") > -1)\n str += newline + space + space + ar[i];\n if (ar[i].search(\"</rules>\") > -1)\n str += newline + ar[i];\n }\n return (str[0] == '\\n') ? str.slice(1) : str;\n }", "function printXML(xml)\n{\n\tvar count = 0;\n\twhile(xml!=null)\n\t{\n\t\t//debugText += \"count : \"+count+\"\\n\";\n\t\t//debugText += \"knoten typ : \"+xml.nodeType+\"\\n\";\n\t\tif(xml.nodeType != 3)\n\t\t{\t\t\t\n\t\t\t//debugText += \"knoten name : \"+xml.nodeName+\"\\n\";\n\t\t\tif( xml.attributes != null)\n\t\t\t{\n\t\t\t\tdebugText += \"knoten inhalt : \"+xml.getAttribute(\"n\")+\"\\n\";\n\t\t\t}\n\t\t}\n\t\tif(xml.hasChildNodes())\n\t\t{\n\t\t\t//debugText += \"hat kinder\\n------\\n\";\n\t\t\tprintXML(xml.firstChild);\n\t\t}\n\t\txml=xml.nextSibling;\n\t\tcount++;\n\t}\t\n}", "function formatXml(xml, escape) {\n xml = vkbeautify.xml(xml);\n if (escape) {\n xml = xml\n .replace(/&/g, '&amp;')\n .replace(/</g, '&lt;')\n .replace(/>/g, '&gt;')\n .replace(/\"/g, '&quot;');\n }\n return xml;\n }", "function XMLdump(XML) {\r\n var settings = '';\r\n if (explorer == true) {\r\n settings='ActiveXobject Version : ' + microsofthttp + '<br/>';\r\n } else {\r\n settings='Standard DOM-XMLRPC<br/>';\r\n }\r\n\r\n XML = str_replace('<', '&lt;', XML);\r\n XML = str_replace('>', '&gt;', XML);\r\n document.getElementById(\"debug\").innerHTML = settings + \"<pre>\" + XML + \"</pre>\";\r\n}", "function xmldump2 (xmlNode) {\n var text = false;\n try {\n // Firefox\n var serializer = new XMLSerializer();\n text = serializer.serializeToString(xmlNode);\n }\n catch (e) {\n try {\n // IE\n if(xmlNode.nodeType == document.ELEMENT_NODE) {\n text = \"ELEMENT\" //xmlNode.outerHTML;\n } else if(xmlNode.nodeType == document.TEXT_NODE) {\n text = xmlNode.nodeValue\n } else {\n throw (\"can only xmldump element and text nodes in IE\")\n }\n }\n catch (e) {}\n }\n return text;\n // return (new XMLSerializer()).serializeToString(xml)\n }", "function printText()\n\t{\n\t\tvar codedText = '',\n\t\tnode = document.first_child;\n\n\t\twhile(node)\n\t\t{\n\t\t\tif(node == Node.TEXT_NODE)\n\t\t\t\tcodedText += (\"**\"+node.nodeValue)\n\t\t\tnode = node.nextSibling;\n\t\t}\n\n\t\tdocument.write(codedText);\n\t}", "function escapeXml(text)\n{\n var rval = '';\n \n var LT = new RegExp(\"<\", \"g\"); \n var GT = new RegExp(\">\", \"g\"); \n var AMP = new RegExp(\"&\", \"g\"); \n var TAB = new RegExp(\"\\t\", \"g\");\n \n rval = text.replace(AMP,\"&amp;\").replace(LT, \"&lt;\").replace(GT, \"&gt;\").replace(TAB, \" \");\n\n return rval;\n}", "pretty() {\n // output pretty formatted string\n let str = [];\n /**\n * Make a specified length space string\n * @param numberOfSpaces Length of output string\n */\n function makeSpaceStr(numberOfSpaces) {\n let res = [];\n for (let i = 0; i < numberOfSpaces; i++) {\n res.push(' ');\n }\n return res.join('');\n }\n function recursive(node, prefix, isLastChild, isRoot = false) {\n str.push(prefix);\n if (!isRoot) {\n str.push(\"--\");\n }\n str.push(node.name + '\\n');\n if (isLastChild) {\n prefix = makeSpaceStr(prefix.length);\n }\n if (!isRoot) {\n prefix += ' ';\n }\n if (node.childs != null) {\n let numberOfChilds = node.childs.length;\n for (let indexOfChild = 0; indexOfChild < numberOfChilds; indexOfChild++) {\n let child = node.childs[indexOfChild];\n if (indexOfChild == numberOfChilds - 1) {\n recursive(child, prefix + '`', true);\n }\n else {\n recursive(child, prefix + '|', false);\n }\n }\n }\n }\n recursive(this.root, '', false, true);\n return str.join('');\n }", "function formatXml(objDom, strIndent)\r\n{\r\n\tvar objChild;\r\n\tvar objNew;\r\n\r\n\tif (indentOrigLen == 0) \r\n\t{\r\n\t\ttempstrIndent = new String;\r\n\t\ttempstrIndent = strIndent;\r\n\t\tindentOrigLen = tempstrIndent.length;\r\n\t}\r\n\r\n\tif (objDom.childNodes.length > 0)\r\n\t{\r\n\t\tfor(var i = 1; i < objDom.childNodes.count; i++)\r\n\t\t{\r\n\t\t\tvar temp = new String;\r\n\t\t\ttemp = strIndent;\r\n\t\t\ttemp = temp.substr(0, indentOrigLen);\r\n\t\t\tformatXml(objChild, strIndent + temp);\r\n\t\t\tif (objDom.nodeType == 1)\r\n\t\t\t{\r\n\t\t\t\tif (objDom.nodeName == \"configName\" )\r\n\t\t\t\t{\r\n\t\t\t\t}\r\n\t\t\t\telse\r\n\t\t\t\t{\r\n\t\t\t\t\tobjNew = objDom.ownerDocument.createNode(3, \"\", \"\");\r\n\t\t\t\t\tobjNew.nodeValue = \"\\r\\n\" + strIndent;\r\n\t\t\t\t\tobjNew = objDom.insertBefore(objNew, objChild);\r\n\t\t\t\t\tobjNew = null;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\tif (objDom.nodeType == 1)\r\n\t\t{\r\n\t\t\tif (objDom.nodeName == \"configName\")\r\n\t\t\t{\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\tobjNew = objDom.ownerDocument.createNode(3, \"\", \"\");\r\n\t\t\t\tvar temp = new String;\r\n\t\t\t\ttemp = strIndent;\r\n\t\t\t\ttemp = temp.substr(0, temp.lenght - 1);\r\n\t\t\t\tobjNew.nodeValue = \"\\r\\n\" + temp;\r\n\t\t\t\tobjNew = objDom.appendChild(objNew);\r\n\t\t\t\tobjNew = null;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n}", "function formatDOMStrForDisplay(str){\n var formatedStr = \"\" ,\n startPos = 0 , \n nextLineIndent = 0 ,\n curLineIndent = 0 ,\n tmpStr = \"\" ,\n indentStr = \"\" ,\n xmlHeader = '<?xml version=\"1.0\" encoding=\"utf-8\" ?>';\n for(var i = 0 ; i < str.length ; i++){\n switch(str.charAt(i)){\n case '<' :\n if(i+1 < str.length && str.charAt(i+1) == '/'){\n curLineIndent -- ;\n break ;\n }\n nextLineIndent ++ ;\n break ;\n case '/' :\n nextLineIndent -- ;\n break ;\n case '>' :\n tmpStr = str.slice(startPos , i + 1 ) ;\n startPos = i + 1 ;\n indentStr = (function(){ var tmpIndentStr = \"\" ; for(var k = 0 ; k < curLineIndent ; k++){tmpIndentStr += \"\\t\" ; } return tmpIndentStr ;})() ;\n formatedStr += indentStr + tmpStr + \"\\n\" ;\n curLineIndent = nextLineIndent ;\n break ;\n default :\n break ;\n }\n }\n return xmlHeader + '\\n' + formatedStr ;\n}", "function formatXMLDocument($xml, noStrip) {\n\t if (!isDocument($xml)) {\n\t console.warn('Called formatXMLDocument with an argument which is not a XML document');\n\t return formatXML($xml);\n\t }\n\t stripEmptyTextNodes($xml[0], _.object(noStrip, noStrip));\n\t indent($xml[0].childNodes[0], 1);\n\t return $xml;\n\t }", "function prettify(document) {\n var treeWalker = document.createTreeWalker(\n document.body,\n NodeFilter.SHOW_TEXT,\n {\n acceptNode: function (node) {\n return node.data.charCodeAt() !== 10 && node.parentElement.nodeName === 'DIV'\n ? NodeFilter.FILTER_ACCEPT\n : NodeFilter.FILTER_SKIP;\n }\n },\n false\n );\n\n var nodes = [];\n\n while (treeWalker.nextNode()) {\n nodes.push(treeWalker.currentNode)\n }\n\n nodes.forEach(function (node) {\n let wrapper = document.createElement('p');\n wrapper.appendChild(node.cloneNode());\n node.parentElement.replaceChild(wrapper, node);\n });\n}", "function xmlToString(node) {\r\n if (node.xml) { // Only IE supports this property.\r\n return node.xml;\r\n } else if (XMLSerializer) { // Firefox supports this.\r\n var my_serializer = new XMLSerializer();\r\n return my_serializer.serializeToString(node);\r\n } else {\r\n alert('Your browser does not support XML serialization.');\r\n return \"\";\r\n }\r\n }", "function printTree(html) {\r\n html = html.match(/<[a-z]+|<\\/[a-z]+>|./ig);\r\n if (!html) return '';\r\n var indent = '\\n', tree = [];\r\n for (var i = 0; i < html.length; i += 1) {\r\n var token = html[i];\r\n if (token.charAt(0) === '<') {\r\n if (token.charAt(1) === '/') { //dedent on close tag\r\n indent = indent.slice(0,-2);\r\n if (html[i+1] && html[i+1].slice(0,2) === '</') //but maintain indent for close tags that come after other close tags\r\n token += indent.slice(0,-2);\r\n }\r\n else { //indent on open tag\r\n tree.push(indent);\r\n indent += ' ';\r\n }\r\n\r\n token = token.toLowerCase();\r\n }\r\n\r\n tree.push(token);\r\n }\r\n return tree.join('').slice(1);\r\n}", "function renderXMLasXML(/*XML DOM*/dom) {\n\tvar newDiv = document.createElement('div');\n\tprint(dom.documentElement, newDiv, 0);\n\treturn newDiv;\n}", "function formatXML(xml){\n var parser = new DOMParser();\n xml = parser.parseFromString(xml,\"text/xml\");\n if(xml.getElementsByTagName(\"parsererror\").length>0){\n return ['error'];\n }\n var errors = getParticularTag(\"error\",xml);\n var warnings = getParticularTag(\"warning\", xml);\n errors[0] = specialChars(errors[0]);\n warnings[0] = specialChars(warnings[0]);\n xml = new XMLSerializer().serializeToString(xml);\n xml = xml.replace(/(>)(<)/, '$1\\n$2');\n xml = specialChars(xml);\n return [xml, errors, warnings];\n}", "function formatV2(text) {\n var ar = text.replace(/>\\s{0,}</g, \"><\")\n .replace(/</g, \"~::~<\")\n .replace(/\\s*xmlns\\:/g, \"~::~xmlns:\")\n .replace(/\\s*xmlns\\=/g, \"~::~xmlns=\")\n .split('~::~'),\n len = ar.length,\n inComment = false,\n str = '';\n for (var i = 0; i < len; i++) {\n var newline = \"\\r\\n\";\n var space = \" \";\n if (ar[i].search(\"<site-list\") > -1)\n str += ar[i];\n if (ar[i].search(\"<created-by>\") > -1 || ar[i].search(\"</created-by>\") > -1 || ar[i].search(\"<site \") > -1 || ar[i].search(\"</site>\") > -1) {\n str += newline + space + ar[i];\n }\n if (ar[i].search(\"<tool>\") > -1 || ar[i].search(\"<version>\") > -1 || ar[i].search(\"<date-created>\") > -1 || ar[i].search(\"<compat-mode>\") > -1 || ar[i].search(\"<open-in>\") > -1) {\n str += newline + space + space + ar[i] + ar[i + 1]; i++; continue;\n }\n if (ar[i].search(\"</site-list\") > -1)\n str += newline + ar[i];\n }\n return (str[0] == '\\n') ? str.slice(1) : str;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
function rotate() Allows to change the source image to the next or last in the list. Options: srcimage defines the image that will be replaced by the others direction 1 forward 1 backward
function rotate(srcimage,direction){ n=n+direction; if (n==allImages) n=0; if (n==-1) n=allImages-1; document.images[srcimage].src=imgObjects[n].src; }
[ "function rotateImages(image){\n\n //available options\n \n \n\n var option = '';\n\n \n img = 'img/' + option + '.png';\n\n $(image).attr('src', img);\n\n\n \n\n\n\n }", "function rotate()\n{\n // get the value of the current image displayed\n var imageSrc = pic.getAttribute(\"src\");\n // make sure that \"src\" is present\n if (imageSrc != null && imageSrc != \"\")\n {\n // get the index of the \"imageSrc\" in the imgs array\n var index = imgs.indexOf(imageSrc);\n // reset or increment the index so the next\n // image is displayed \n if (index == imgs.length-1)\n {\n index = 0;\n }\n else\n {\n index++;\n }\n \n // set the \"src\" attribute to be the next image in the \"imgs\" array\n pic.setAttribute(\"src\", imgs[index]); \n \n setTimeout(\"rotate()\", pause);\n }\n}", "function rotate() {\n var images = new Array ('img/1.jpg', 'img/2.jpg', 'img/3.jpg' )\n \n /*ebb: This line randomizes the order of the images:*/\n var thisImage = Math.floor(Math.random() *(images.length));\n \n document.getElementById(\"rotator\").src = images[thisImage];\n \n /*ebb: Uncomment this if you want continual image rotation in seconds*/\n setTimeout(rotate, 5 * 1000);\n}", "function rotateImgs(direction) {\r\n\t\t\r\n\t\t// Next\r\n\t\t// Current picture will rotate right and hide\r\n\t\t// Next picture will rotate left and show\r\n\t\tif (direction === \"next\") {\r\n\t\t\tlet arcOptions1 = {\r\n\t\t\t\t\"direction\": \"right\"\r\n\t\t\t}\r\n\r\n\t\t\tlet arcOptions2 = {\r\n\t\t\t\t\"direction\": \"left\"\r\n\t\t\t}\r\n\r\n\t\t\timgs[currentImgIndex].hide(\"arc\", arcOptions1);\r\n\t\t\r\n\t\t\tif (currentImgIndex === 0) {\r\n\t\t\t\tcurrentImgIndex = imgs.length-1;\r\n\t\t\t}\r\n\t\t\telse {\r\n\t\t\t\tcurrentImgIndex--;\r\n\t\t\t}\r\n\r\n\t\t\timgs[currentImgIndex].show(\"arc\", arcOptions2);\r\n\t\t}\r\n\r\n\t\t// Previous\r\n\t\t// Current picture will rotate left and hide\r\n\t\t// Previous picture will rotate right and show\r\n\t\telse {\r\n\t\t\tlet arcOptions1 = {\r\n\t\t\t\"direction\": \"left\"\r\n\t\t\t}\r\n\r\n\t\t\tlet arcOptions2 = {\r\n\t\t\t\"direction\": \"right\"\r\n\t\t\t}\r\n\r\n\t\t\timgs[currentImgIndex].hide(\"arc\", arcOptions1);\r\n\t\t\r\n\t\t\tif (currentImgIndex === imgs.length-1) {\r\n\t\t\t\tcurrentImgIndex = 0;\r\n\t\t\t}\r\n\t\t\telse {\r\n\t\t\t\tcurrentImgIndex++;\r\n\t\t\t}\r\n\r\n\t\t\timgs[currentImgIndex].show(\"arc\", arcOptions2);\r\n\t\t}\r\n\r\n\t}", "function rotateImages(whichHolder, startIndex) {\n var rotatingImageArray = eval(\"rotatingImageArray\" + whichHolder);\n var rotatingImageHolder = eval(\"rotatingImageHolder\" + whichHolder);\n if(startIndex >= rotatingImageArray.length)\n {\n startIndex = 0;\n }\n rotatingImageHolder.src = rotatingImageArray[startIndex];\n window.setTimeout(\"rotateImages(\" + whichHolder + \",\" + (startIndex + 1) + \")\", 3000);\n}", "function rotate() {\n var thisImage = 0;\n var images = new Array ('img/rotator/1.jpg', 'img/rotator/2.jpg', 'img/rotator/3.jpg', 'img/rotator/4.jpg', 'img/rotator/5.jpg', 'img/rotator/6.jpg', 'img/rotator/7.jpg')\n \n /* ebb: This line randomizes the order of the images:*/\n var thisImage = Math.floor(Math.random() *(images.length));\n document.getElementById(\"rotator\").src = images[thisImage];\n \n /* ebb: Uncomment this if you want continual image rotation in seconds*/\n setTimeout(rotate, 5 * 1000);\n}", "function rotateImage(direction) {\r\n\t// Get the current image angle.\r\n\timageObject = document.getElementById('content_preview_image1');\r\n\tif (imageObject.Wilq32) {\r\n\t\tcurrentAngle = imageObject.Wilq32.PhotoEffect._angle;\r\n\t} else {\r\n\t\tcurrentAngle = 0;\r\n\t}\r\n\r\n\tswitch (direction) {\r\n\t\tcase 'right':\r\n\r\n\t\t\tswitch (currentAngle) {\r\n\t\t\t\tcase 0:\r\n\t\t\t\t\tnewAngle = 90;\r\n\t\t\t\t\tbreak;\r\n\t\t\t\tcase 90:\r\n\t\t\t\t\tnewAngle = 180;\r\n\t\t\t\t\tbreak;\r\n\t\t\t\tcase 180:\r\n\t\t\t\t\tnewAngle = 270;\r\n\t\t\t\t\tbreak;\r\n\t\t\t\tcase 270:\r\n\t\t\t\t\tnewAngle = 0;\r\n\t\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t \tbreak;\r\n\t\tcase 'left':\r\n\t\t \tswitch (currentAngle) {\r\n\t\t\t\tcase 0:\r\n\t\t\t\t\tnewAngle = 270;\r\n\t\t\t\t\tbreak;\r\n\t\t\t\tcase 90:\r\n\t\t\t\t\tnewAngle = 0;\r\n\t\t\t\t\tbreak;\r\n\t\t\t\tcase 180:\r\n\t\t\t\t\tnewAngle = 90;\r\n\t\t\t\t\tbreak;\r\n\t\t\t\tcase 270:\r\n\t\t\t\t\tnewAngle = 180;\r\n\t\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t \tbreak;\r\n\t}\r\n\r\n\t$(\"#content_preview_image1\").rotate({angle: newAngle});\r\n\t$(\"#content_preview_image2\").rotate({angle: newAngle});\r\n\t$(\"#content_preview_image3\").rotate({angle: newAngle});\r\n\t$(\"#content_preview_image4\").rotate({angle: newAngle});\r\n\t$(\"#content_preview_image5\").rotate({angle: newAngle});\r\n\t$(\"#content_preview_image6\").rotate({angle: newAngle});\r\n\t$(\"#content_preview_image7\").rotate({angle: newAngle});\r\n\t$(\"#content_preview_image8\").rotate({angle: newAngle});\r\n\t$(\"#content_preview_image9\").rotate({angle: newAngle});\r\n\t\r\n}", "function rotatePropertyImage(){\n if(position == total){\n position = 1;\n }\n else{\n position++;\n }\n\n image.src = '../img/properties/' + property + '/0' + position + '.jpg';\n image.style.width = width + 'px';\n image.style.height = height + 'px';\n}", "function resetNextAngle(id_image) {\n nextAngle = 0;\n //rotate right image 0 degree\n // rotateRight(id_image, 0);\n}", "function rotateForward(myImg, g_images){\n var opacity = 1;\n counter = 0\n setInterval(function() {\n myImg.src = g_images[counter].src;\n myImg.style.opacity = opacity;\n opacity -= handle;\n if (opacity <= 0)\n {\n counter >= g_images.length - 1 ? counter = 0 : counter++;\n handle = 0 - handle;\n }\n if (opacity >= 1)\n {\n handle = 0.02;\n }\n }, 50); \n}", "function rotateImages(){ \n\n // grab the id from the HTML \n var jumbo = document.getElementById(\"jumbotron\");\n \n // Step one: Make the image change everytime we click on the image\n //rotateImages.style.backgroundImage = \"url('images/pdxcg_02.jpg')\"\n\n //break down the string just like I did in the gallery \n var imageStrBeg = \"url('images/pdxcg_\"; \n var imageStrEnd = \".jpg')\"; \n \n // Since there is no number 42, if the number is equal to 42, \n //add one to it to skip it and make it 43\n if (i === 42){\n i++; \n\n // else if the number is less than 9, add 0 to the number to make \n //it match file name\n } else if (i <= 9){\n // add 0 to the number \n i = \"0\" + i;\n };\n\n //concatinate the string together to make the image number increment and \n // hold into variable\n var singleImage = (imageStrBeg + i + imageStrEnd)\n //console.log(singleImage)\n\n //change jumbo url to equal the concatinated equasion \n jumbo.style.backgroundImage = singleImage\n\n //if i - the number of photo - is equal to 60, change it to equal one\n // so it loops back \n if (i === 60){\n i = 1\n }\n\n // increment each photo \n i++\n}", "function RotateOneImage(element)\n{\n //console.log(element);\n var originalAngle = document.getElementById(element[8]).value;\n var myImage = document.getElementById(element[0])\n //console.log(\"orginalAngle: \" + originalAngle);\n if(originalAngle == null || originalAngle == \"undefined\" || originalAngle == \"\")\n {\n originalAngle = 0;\n }\n var rotateAngle = parseInt(originalAngle) + 90\n\n //Set the image margin based on the degre to aovide overlapping with other objects/elements\n if(rotateAngle == 90 || rotateAngle == 270)\n {\n //console.log(\"the degree is 90 or 270\");\n myImage.style.marginTop = \"35px\";\n myImage.style.marginBottom = \"35px\";\n $(\"#\" + element[0]).rotate(rotateAngle);\n }\n else\n {\n myImage.style.marginTop = \"0px\";\n myImage.style.marginBottom = \"0px\";\n $(\"#\" + element[0]).rotate(rotateAngle);\n }\n\n if(rotateAngle==360)\n {\n rotateAngle = 0;\n }\n document.getElementById(element[8]).value = rotateAngle;\n \n}", "function rotateImage(imageList, imageIndex) {\n\t\n\t// where the image is displayed.\n\tslideshowDiv = $(\"#slideshow div:first\");\n\n\t// This is the placeholder div for each newly created image:\n\tplaceholderDiv = $(\"#placeholder\");\n\n\t// get the current image if it exists.\n\tcurrentImage = $(\"#slideshow div img\").not(\"#spinner\");\n\t// send it to the back.\n\tcurrentImage.css('z-index', '0');\n\n\t// load the image at index imageIndex into the next-image div.\n\tvar nextImage = $(\"<img />\", { src: imageList[imageIndex][\"url\"], \"css\" : {\"opacity\" : \"0\"} });\n\n\t// get the title and artist info for the attribution.\n\tvar imageTitle = imageList[imageIndex][\"title\"];\n\tvar imageAuthor = imageList[imageIndex][\"author\"];\n\tvar deviationPage = imageList[imageIndex][\"link\"];\n\tvar attributionText = \"\\\"\" + imageTitle + \"\\\" by \" + imageAuthor;\n\t// Once the image is loaded, do some schmaculating about how big it should be and where to put it.\n\t// There should be a 15px space between the image and all sides of the window.\n\n\t// Get window height, width.\n\twindowWidth = $(window).width();\n\twindowHeight = $(window).height();\n\n\t// when nextImage has loaded, we can get it's height and width, then go from there.\n\tnextImage.load(function() {\n\n\t\t// get the current attribution p so we can fade it out and replace it with the next one.\n\t\tvar currentAttribution = $(\".attribution-current\");\n\n\t\t// create a new attribution p with the correct text.\n\t\tvar nextAttribution = $(\"<p />\", { \"class\" : \"attribution-next\", \"css\" : {\"display\" : \"none\"} } );\n\t\tvar link = $(\"<a />\", { \"href\" : deviationPage, \"target\" : \"_blank\" } );\n\t\t$(nextAttribution).append(link);\n\t\tlink.text(attributionText);\n\n\t\t// append this new image to the placeholder.\n\t\t$(this).appendTo(placeholderDiv);\n\n\t\t// append the new attribution div to the .credited div.\n\t\t$(\".credited\").append(nextAttribution);\n\n\t\t// get the natural dimensions of the image.\n\t\tvar imgWidth = $(this).get(0).naturalWidth;\n\t\tvar imgHeight = $(this).get(0).naturalHeight;\n\n\t\t// get the maximum values the image can be displayed at.\n\t\t// There should be a 15px border on each side. That means the max = total - 30.\n\t\tvar maxWidth = windowWidth - 30;\n\t\tvar maxHeight = windowHeight - 30;\n\n\t\tformatImage(nextImage, maxWidth, maxHeight, imgWidth, imgHeight, windowWidth, windowHeight);\n\n\t\tslideshowDiv.append(nextImage);\n\n\t\tif ( $(\"#spinner\").css('display') == \"none\" ) {\n\t\t\t// No spinner to deal with. animate the images.\n\t\t\tcurrentImage.animate({\n\t\t\t\t\"opacity\": \"0\"},\n\t\t\t\t2000, function() {\n\t\t\t\tcurrentImage.remove();\n\t\t\t});\n\n\t\t\tnextImage.animate({\n\t\t\t\topacity: 1},\n\t\t\t\t2000, function() {\n\t\t\t\t\tnextImage.css('z-index', '0');\n\t\t\t});\n\n\t\t\t// fade out the current attribution if it's visible\n\t\t\tif ( $(\".attribution-current\").css(\"display\") === \"block\" ) {\n\t\t\t\t\n\t\t\t\tcurrentAttribution.fadeOut(2000);\n\t\t\t\t// fade in the new one, then delete the old one and set the id in the callback.\n\t\t\t\tnextAttribution.fadeIn(2000, function() {\n\t\t\t\t\tcurrentAttribution.remove();\n\t\t\t\t\t// $(this).attr('id', 'attribution');\n\t\t\t\t\t$(this).addClass('attribution-current').removeClass('attribution-next');\n\t\t\t\t});\n\n\t\t\t}\telse {\n\t\t\t\t// just swap 'em out if they're not visible.\n\t\t\t\tcurrentAttribution.remove();\n\t\t\t\tnextAttribution.addClass('attribution-current').removeClass('attribution-next');\n\t\t\t}\n\n\t\t\t\n\t\t}\telse {\n\t\t\t// fade out the spinner, animate images with a callback.\n\t\t\t$(\"#spinner\").fadeOut(300, function() {\n\t\t\t\tslideshowDiv.append(nextImage);\n\n\t\t\t\tnextImage.animate({\n\t\t\t\t\topacity: 1},\n\t\t\t\t\t2000, function() {\n\t\t\t\t\t\tnextImage.css('z-index', '0');\n\t\t\t\t});\n\n\t\t\t\tcurrentImage.animate({\n\t\t\t\t\t\"opacity\": \"0\"},\n\t\t\t\t\t2000, function() {\n\t\t\t\t\tcurrentImage.remove();\n\t\t\t\t});\n\n\t\t\t\t// fade out the current attribution if it's visible\n\t\t\t\tif ( $(\".attribution-current\").css(\"display\") === \"block\" ) {\n\t\t\t\t\t\n\t\t\t\t\tcurrentAttribution.fadeOut(2000);\n\t\t\t\t\t// fade in the new one, then delete the old one and set the id in the callback.\n\t\t\t\t\tnextAttribution.fadeIn(2000, function() {\n\t\t\t\t\t\tcurrentAttribution.remove();\n\t\t\t\t\t\t$(this).addClass('attribution-current').removeClass('attribution-next');\n\t\t\t\t\t});\n\n\t\t\t\t}\telse {\n\t\t\t\t\t// just swap 'em out if they're not visible.\n\t\t\t\t\tcurrentAttribution.remove();\n\t\t\t\t\tnextAttribution.addClass('attribution-current').removeClass('attribution-next');\n\t\t\t\t}\n\n\t\t\t});\n\n\t\t}\n\n\n\n\t}); //end of load function.\n\n}", "function RotateOneImage(element)\n{\n //console.log(element);\n var originalAngle = document.getElementById(element[8]).value;\n var myImage = document.getElementById(element[0])\n //console.log(\"orginalAngle: \" + originalAngle);\n if(originalAngle == null || originalAngle == \"undefined\" || originalAngle == \"\")\n {\n originalAngle = 0;\n }\n var rotateAngle = parseInt(originalAngle) + 90\n\n //Set the image margin based on the degre to aovide overlapping with other objects/elements\n if(rotateAngle == 90 || rotateAngle == 270)\n {\n console.log(\"the degree is 90 or 270\");\n myImage.style.marginTop = \"35px\";\n myImage.style.marginBottom = \"35px\";\n $(\"#\" + element[0]).rotate(rotateAngle);\n }\n else\n {\n myImage.style.marginTop = \"0px\";\n myImage.style.marginBottom = \"0px\";\n $(\"#\" + element[0]).rotate(rotateAngle);\n }\n\n if(rotateAngle==360)\n {\n rotateAngle = 0;\n }\n document.getElementById(element[8]).value = rotateAngle;\n \n}", "rotate(time){\n this.time = time;\n this.timout = setTimeout(()=>{\n this.nextImage();\n this.rotate(time);\n }, time);\n }", "function applyImageRotation(carousel_img, thumbnail_img, rotation, pageSource){\n // console.log(' ');\n // console.log('apply image rotation');\n if(pageSource==\"edit\" || pageSource==\"new\"){\n var carousel_width = '337px'; // width of image in carousel on edit page\n }else if(pageSource==\"index\"){\n var carousel_width = '381px'; // width of image in carousel on index page\n }\n \n var thumbnail_width = '99px'; // width of thumbnail image in thumbGallery\n var rotation_string = 'rotate('+rotation+'deg)';\n\n carousel_img.css('webkitTransform', rotation_string);\n carousel_img.css('-moz-transform', rotation_string);\n\n // set rotation for project overview carousel\n $('.projectOverviewCarousel img[src=\"' + carousel_img.attr('src') + '\"]').css('webkitTransform', rotation_string);\n $('.projectOverviewCarousel img[src=\"' + carousel_img.attr('src') + '\"]').css('-moz-transform', rotation_string);\n $('.projectOverviewCarousel img[src=\"' + carousel_img.attr('src') + '\"]').css('height', $('.projectOverviewPhoto').width()+\"px\");\n\n thumbnail_img.css('webkitTransform', rotation_string);\n thumbnail_img.css('-moz-transform', rotation_string);\n\n if(rotation/90 %2 == 0){\n // 180, 360 degrees\n carousel_img.height('auto');\n carousel_img.removeClass('rotated_odd');\n carousel_img.addClass('rotated_even'); \n\n thumbnail_img.height('auto');\n thumbnail_img.removeClass('rotated_odd');\n thumbnail_img.addClass('rotated_even');\n }else{\n // 90, 270 degrees\n carousel_img.css('height', carousel_width);\n carousel_img.removeClass('rotated_even');\n carousel_img.addClass('rotated_odd'); \n \n if(pageSource == \"edit\" || pageSource == \"new\"){\n setCarouselImageMargins(carousel_img, carousel_width, undefined, undefined);\n }\n else if(pageSource==\"index\"){\n $('<img/>').on('load', function(){\n // console.log($(this).attr('src'));\n // console.log('carousel_img dimensions: ' + this.width + ' ' + this.height);\n // calculate expanded dimensions\n this.width = this.width * parseInt(carousel_width) / this.height;\n this.height = parseInt(carousel_width); //width is actually height with rotated image\n // console.log('final image and width: ' + this.width + ' ' + this.height);\n setCarouselImageMargins(carousel_img, carousel_width, this.width, this.height); \n }).attr('src', carousel_img[0].src);\n }\n \n thumbnail_img.css('height', thumbnail_width);\n thumbnail_img.removeClass('rotated_even');\n thumbnail_img.addClass('rotated_odd');\n\n if(pageSource==\"edit\" || pageSource==\"new\"){\n setThumbnailMargins(thumbnail_img, thumbnail_width);\n }else if(pageSource==\"index\"){\n thumbnail_img.on('load', function(){\n // console.log('applying thumbnail image margins');\n setThumbnailMargins($(this), thumbnail_width); \n });\n }\n }\n }", "function jd_rotate() {\n\tjd_theAd++;\n\tif (jd_theAd == jd_adImages.length) {\n\t\tjd_theAd = 0;\n\t}\n\n\t/*the new source for \"adBanner\" are in the array jd_adImages and the\n\t value of jd_theAd determines which image appears\n\t */\n\tdocument.getElementById(\"adBanner\").src = jd_adImages[jd_theAd];\n\n// function rotate is called every 3 seconds\n\tsetTimeout(jd_rotate, 2 * 1000);\n}", "function rotarImagenes() {\n // cambiamos la imagen y la url\n contador++;\n document.getElementById(\"imagenes\").src = imagenes[contador % imagenes.length][0];\n document.getElementById(\"banner\").href = imagenes[contador % imagenes.length][1];\n}", "function rotate() {\r\n\r\n var imgs = document.getElementsByTagName('img');\r\n\r\n for (var i= 0; i < imgs.length; i++) {\r\n if (imgs[i].className == \"point\") {\r\n\r\n var thisImg = imgs[i];\r\n \r\n // IF THE ANGLE GOES OVER 360 RESET IT, STOPS NUMEBR INCREASING FOR EVER.\r\n if (thisImg.angle > 360){thisImg.angle = rotationDir;} \r\n \r\n // UPDATE THE ANGLE THEN MOVE IMAGE WITH THE moveElements() FUNCTION\r\n thisImg.angle += rotationDir;\r\n moveElements(imgs[i], thisImg.angle);\r\n }\r\n }\r\n \r\n loop(); // GO BACK TO LOOP\r\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
api call to green.js to pull goal total for selected Category
function getGoalAmount(categorySelected) { jQuery.ajaxSetup({async:false}); $.post("/api/getUserGoals", {username:user}, function(data) { amountSet = 0; $(jQuery.parseJSON(JSON.stringify(data))).each(function() { amountSet = this[categorySelected]; }); }); }
[ "calculateTotal() {\n let total = 0;\n for (let category of this.categories) {\n total += category.calculateTotal();\n }\n return total;\n }", "function totalCostPerCat() {\n knexInstance\n .select('*')\n .sum('total')\n .from('shopping-list')\n .groupBy('category')\n .then(res => {\n console.log('Total Cost of Category', res)\n })\n}", "static async getTotal() {\n const query = `\n {\n talkCollection {\n total\n }\n }\n `;\n\n const response = await this.callContentful(query);\n const totalTalks = response.data.talkCollection.total\n ? response.data.talkCollection.total\n : 0;\n\n return totalTalks;\n }", "function totalKanban(componentId,filterTeamId) {\r\n\t\t\treturn $http.get(HygieiaConfig.local ? testTotal : buildTotal + filterTeamId + param + componentId + agileType.kanban)\r\n\t\t\t\t\t.then(function(response) {\r\n\t\t\t\t\t\treturn response.data;\r\n\t\t\t\t\t});\r\n\t\t}", "function totalPerCategory(){\n db\n .select('category')\n .sum('price as total')\n .from('shopping_list')\n .groupBy('category')\n .then(result => {\n console.log(result)\n })\n}", "function sumCategory() {\n\tconst currentCategory = budgetApp.storage.getCategoryByIndex(\n\t\tbudgetApp.currentCategory\n\t);\n\tcurrentCategory.total = 0;\n\n\tcurrentCategory.inputs.forEach(function(item) {\n\t\tcurrentCategory.total += item.value ? item.value : 0;\n\t});\n}", "function totalCostPerCategory() {\n knexInstance\n .select(\"category\")\n .sum(\"price as total\")\n .from(\"shopping_list\")\n .groupBy(\"category\")\n .then((result) => {\n console.log(\"Total cost per category:\");\n console.log(result);\n });\n}", "function totalCostForCategory() {\n knexInstance('shopping_list')\n .select('category')\n .sum('price as total')\n .groupBy('category')\n .then(res => console.log(res))\n .catch(error => console.log(error.message))\n .finally(() => knexInstance.destroy());\n}", "function getPercent(category) {\n let completed = category.completed;\n let total = category.total;\n return (completed / total) * 100;\n }", "function totalCost() {\n knexInstance\n .select('category')\n .sum('price as total')\n .from('shopping_list')\n .groupBy('category')\n .then(result => {\n console.log(result)\n })\n }", "static async categoryPopular(req, res, next) {\n const CategoryId = req.params.CategoryId;\n const { page } = req.params;\n try {\n const rank = await Campaigns.findAll({\n where: {\n CategoryId,\n },\n });\n if (rank) {\n const options = {\n page,\n paginate: 12,\n order: [[\"point\", \"DESC\"]],\n where: { CategoryId },\n include: [Category],\n };\n const { docs, pages, total } = await Campaigns.paginate(options);\n if (page <= pages) {\n res.status(200).json({\n Status: 200,\n Success: true,\n on_page: page,\n total_data: total,\n total_pages: pages,\n ranked: docs,\n });\n } else {\n res.status(404).json({\n msg: \"Page not found\",\n });\n }\n } else {\n res.status(404).json({\n msg: \"no campaign available\",\n });\n }\n } catch (err) {\n next(err);\n }\n }", "async function countCategory(category){\n var listSnap = await promiseGetCategory(category);\n // console.log(listSnap);\n var runningTotal = 0;\n for (let ingName of Object.keys(listSnap)) {\n //get the name of the item\n // console.log(ingName);\n //get the quantity of that item\n var ingQuan = await promiseIngQuan(ingName);\n //then get the quantity for each item\n // console.log(ingName + \" quantity: \" + ingQuan);\n runningTotal += ingQuan;\n // console.log(\"Running total of \" + category + \"s: \" + runningTotal);\n }\n // console.log(\"Return: \" + runningTotal);\n return runningTotal;\n}", "function getQuestionCount(categoryId) {\n let queryURL;\n if (categoryId) {\n queryURL = \"https://opentdb.com/api_count.php?category=\" + categoryId;\n }\n else {\n queryURL = \"https://opentdb.com/api_count_global.php\";\n }\n return $.get(queryURL)\n .then(res => res.overall || res.category_question_count);\n}", "function calcTotalPriceByCategory(products, category) {\n\t// YOUR CODE HERE\n}", "function getNumberCategories() {\r\n settings = {\r\n url: \"https://\" + baseURL + \"/api/v2/admins/\" + adminId + \"/categories\",\r\n method: \"GET\",\r\n async: false\r\n };\r\n $.ajax(settings).done(function (response) {\r\n currentCategories = response.TotalRecords;\r\n });\r\n}", "function totalCost(){\n knexInstance\n .select('category')\n .sum('price as total')\n .from('shopping_list')\n .groupBy('category')\n .then(result => {\n console.log('Drill 4:', result)\n })\n}", "function displayExpTotals() {\n\tconst categoryArr = ['gas', 'restaurants', 'entertainment', 'groceries', 'medical', 'misc'];\n\n\tfor (i = 0; i < categoryArr.length; i++) {\n\t\t$.ajax({\n\t\t\ttype: 'GET',\n\t\t\turl: `/items/${categoryArr[i]}`,\t\n\t\t\tdataType: 'json',\n\t\t\theaders: {Authorization: `Bearer ${token}`},\n\t\t\tsuccess: function(data) {\n\t\t\t\tconst eachObj = data.expenses[0];\n\t\t\t\tlet totalExp = 0; let totalExp2 = 0; let totalExp3 = 0;\tlet totalExp4 = 0; let totalExp5 = 0; let totalExp6 = 0;\n\t\t\t\t\n\t\t\t\tif (eachObj === undefined) { //this category total taken care of in displayAllTotal() in if statement.\n\t\t\t\t\tconsole.log('One more more category has no expenses');\n\t\t\t\t} else if (eachObj.category === 'gas') {\t\t\n\t\t\t\t\tfor (index in data.expenses) {\n\t\t\t\t\t\ttotalExp += Number(data.expenses[index].cost);\n\t\t\t\t\t}\t\t\t\t\t\t\t\t //formats to contain commas and 2 decimals\n\t\t\t\t\t$('.total-1').html('$' + totalExp.toLocaleString(undefined, { minimumFractionDigits: 2}));\n\t\t\t\t} else if (eachObj.category === 'restaurants') {\t\t\t\t\t\n\t\t\t\t\tfor (index in data.expenses) {\n\t\t\t\t\t\ttotalExp2 += Number(data.expenses[index].cost);\n\t\t\t\t\t}\n\t\t\t\t\t$('.total-2').html('$' + totalExp2.toLocaleString(undefined, { minimumFractionDigits: 2 }));\n\t\t\t\t} else if (eachObj.category === 'entertainment') {\t\t\t\t\n\t\t\t\t\tfor (index in data.expenses) {\n\t\t\t\t\t\ttotalExp3 += Number(data.expenses[index].cost);\n\t\t\t\t\t}\n\t\t\t\t\t$('.total-3').html('$' + totalExp3.toLocaleString(undefined, { minimumFractionDigits: 2 })); \n\t\t\t\t} else if (eachObj.category === 'groceries') {\t\t\t\t\n\t\t\t\t\tfor (index in data.expenses) {\n\t\t\t\t\t\ttotalExp4 += Number(data.expenses[index].cost);\n\t\t\t\t\t}\n\t\t\t\t\t$('.total-4').html('$' + totalExp4.toLocaleString(undefined, { minimumFractionDigits: 2 }));\n\t\t\t\t} else if (eachObj.category === 'medical') {\t\t\t\t\n\t\t\t\t\tfor (index in data.expenses) {\n\t\t\t\t\t\ttotalExp5 += Number(data.expenses[index].cost);\n\t\t\t\t\t}\n\t\t\t\t\t$('.total-5').html('$' + totalExp5.toLocaleString(undefined, { minimumFractionDigits: 2 }));\n\t\t\t\t} else if (eachObj.category === 'misc') {\t\t\t\t\n\t\t\t\t\tfor (index in data.expenses) {\n\t\t\t\t\t\ttotalExp6 += Number(data.expenses[index].cost);\n\t\t\t\t\t}\n\t\t\t\t\t$('.total-6').html('$' + totalExp6.toLocaleString(undefined, { minimumFractionDigits: 2 }));\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t}\n}", "function calculateTotalCaloriesByGoal(goal, tdee) {\n if(goal === \"gain\") {\n return tdee + (tdee * .20);\n }\n if(goal === \"lose\") {\n return tdee - (tdee * .20);\n }\n}", "function getTotalCost() {\n knexInstance\n .select('category')\n .sum('price as total')\n .from('shopping_list')\n .groupBy('category')\n .orderBy([\n {column: 'total', order: 'DESC' },\n ])\n .then(results => {\n console.log('Cost per category');\n console.log(results);\n })\n .catch(err => console.log(err))\n .finally(() => knexInstance.destroy());\n\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
run the actual callbacks
function runCallbacks() { callbacks.forEach(function (callback) { callback(); }); running = false; }
[ "function runCallbacks() {\n\n\t callbacks.forEach(function(callback) {\n\t callback();\n\t });\n\n\t running = false;\n\t }", "function runCallbacks() {\n\n callbacks.forEach(function(callback) {\n callback();\n });\n\n running = false;\n }", "function runCallbacks() {\n callbacks.forEach(function (callback) {\n callback();\n });\n running = false;\n }", "function runCallbacks() {\n\n callbacks.forEach(function (callback) {\n callback();\n });\n\n running = false;\n }", "function runCallbacks() {\n callbacks.forEach((callback) => {\n callback();\n });\n\n running = false;\n }", "function runCallbacks() {\n callbacks.forEach(function(callback) {\n callback();\n });\n\n running = false;\n }", "function runCallbacks() {\n\n callbacks.forEach(function(callback) {\n callback();\n });\n\n running = false;\n }", "function callback(){}", "runCallbacks(event, data, requestInfo, additionalData) {\n let callbacksToRun = this.callbacks[event];\n\n if (callbacksToRun) {\n for (let callback of callbacksToRun) {\n callback(data, requestInfo, additionalData);\n }\n }\n }", "function executeCallbacks() {\n\t while (callbacks.length > 0) {\n\t var callback = callbacks.shift();\n\t callback();\n\t }\n\t}", "runCallbacks(callbacks, args) {\r\n for (let i = 0; i < callbacks.length; i++) {\r\n if (typeof callbacks[i] !== 'function') continue;\r\n callbacks[i].apply(null, args);\r\n }\r\n }", "function processCallbacks() {\n while (callbacks.length) {\n var cb = callbacks.pop();\n setupHub(cb);\n }\n }", "function runCallbacks(callbacks, args) {\n for (var i = 0; i < callbacks.length; i++) {\n if (typeof callbacks[i] !== 'function') continue;\n callbacks[i].apply(null, args);\n }\n }", "function executeCallbacks() {\n while (callbacks.length > 0) {\n var callback = callbacks.shift();\n callback();\n }\n}", "doCallback_ () {\n this.callback_.apply(null, this.lastResult_);\n }", "callcallbacks(...args) {\n for (let id of Object.keys(this.callbacks)) {\n this.callbacks[id](...args);\n }\n }", "function executeCallbacks() {\n while (callbacks.length > 0) {\n const callback = callbacks.shift();\n callback();\n }\n}", "function exec() {\n\t\t\tlastExec = Date.now();\n\t\t\tcallback.apply(self, arguments_);\n\t\t}", "function _runCallback (name, args) {\n\t\tif (typeof _callbacks[name] == 'function') {\n\t\t\t_callbacks[name].apply(this, args);\n\t\t}\n\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
! moment.js locale configuration
function Os(e,t,n){return"m"===n?t?"хвилина":"хвилину":"h"===n?t?"година":"годину":e+" "+ //! moment.js locale configuration function(e,t){var n=e.split("_");return t%10==1&&t%100!=11?n[0]:t%10>=2&&t%10<=4&&(t%100<10||t%100>=20)?n[1]:n[2]}({ss:t?"секунда_секунди_секунд":"секунду_секунди_секунд",mm:t?"хвилина_хвилини_хвилин":"хвилину_хвилини_хвилин",hh:t?"година_години_годин":"годину_години_годин",dd:"день_дні_днів",MM:"місяць_місяці_місяців",yy:"рік_роки_років"}[n],+e)}
[ "function za(e,t,o){return\"m\"===o?t?\"хвилина\":\"хвилину\":\"h\"===o?t?\"година\":\"годину\":e+\" \"+\n//! moment.js locale configuration\nfunction(e,t){var o=e.split(\"_\");return t%10==1&&t%100!=11?o[0]:t%10>=2&&t%10<=4&&(t%100<10||t%100>=20)?o[1]:o[2]}({ss:t?\"секунда_секунди_секунд\":\"секунду_секунди_секунд\",mm:t?\"хвилина_хвилини_хвилин\":\"хвилину_хвилини_хвилин\",hh:t?\"година_години_годин\":\"годину_години_годин\",dd:\"день_дні_днів\",MM:\"місяць_місяці_місяців\",yy:\"рік_роки_років\"}[o],+e)}", "function v(e,t,n){return e+\" \"+function(e,t){return 2===t?function(e){var t={m:\"v\",b:\"v\",d:\"z\"};return void 0===t[e.charAt(0)]?e:t[e.charAt(0)]+e.substring(1)}(e):e}({mm:\"munutenn\",MM:\"miz\",dd:\"devezh\"}[n],e)}//! moment.js locale configuration", "function cl(e,t,n){return\"m\"===n?t?\"минута\":\"минуту\":e+\" \"+\n//! moment.js locale configuration\n//! locale : Russian [ru]\n//! author : Viktorminator : https://github.com/Viktorminator\n//! Author : Menelion Elensúle : https://github.com/Oire\n//! author : Коренберг Марк : https://github.com/socketpair\nfunction(e,t){var n=e.split(\"_\");return t%10==1&&t%100!=11?n[0]:t%10>=2&&t%10<=4&&(t%100<10||t%100>=20)?n[1]:n[2]}({ss:t?\"секунда_секунды_секунд\":\"секунду_секунды_секунд\",mm:t?\"минута_минуты_минут\":\"минуту_минуты_минут\",hh:\"час_часа_часов\",dd:\"день_дня_дней\",MM:\"месяц_месяца_месяцев\",yy:\"год_года_лет\"}[n],+e)}", "function b(e,t,n){return e+\" \"+function(e,t){return 2===t?function(e){var t={m:\"v\",b:\"v\",d:\"z\"};return void 0===t[e.charAt(0)]?e:t[e.charAt(0)]+e.substring(1)}(e):e}({mm:\"munutenn\",MM:\"miz\",dd:\"devezh\"}[n],e)}//! moment.js locale configuration", "function kn(e,a,t){return e+\" \"+function(e,a){if(2===a)return function(e){var a={m:\"v\",b:\"v\",d:\"z\"};if(void 0===a[e.charAt(0)])return e;return a[e.charAt(0)]+e.substring(1)}(e);return e}({mm:\"munutenn\",MM:\"miz\",dd:\"devezh\"}[t],e)}//! moment.js locale configuration", "function init() {\n if (navigator && navigator.language) {\n moment.locale(navigator.language);\n }\n else {\n moment.locale('es');\n }\n }", "function _initMomentLocale () {\n if (typeof (moment) === 'function') {\n let m = jQuery('html').attr('lang')\n if (m) {\n moment.locale(m)\n }\n }\n}", "function hd(i,ee,te){return i+\" \"+function kd(i,ee){return 2===ee?function ld(i){var ee={m:\"v\",b:\"v\",d:\"z\"};return void 0===ee[i.charAt(0)]?i:ee[i.charAt(0)]+i.substring(1)}\n//! moment.js locale configuration\n//! locale : bosnian (bs)\n//! author : Nedim Cholich : https://github.com/frontyard\n//! based on (hr) translation by Bojan Marković\n(i):i}({mm:\"munutenn\",MM:\"miz\",dd:\"devezh\"}[te],i)}", "setLocaleForMoment() {\n if (\n moment.locale() !== window.navigator.language.toLowerCase()\n ) {\n moment.locale(window.navigator.language.toLowerCase());\n }\n }", "function setupMoment() {\n moment.updateLocale(\"en\", {\n week: {\n dow: 1,\n doy: 4 // The week that contains Jan 4th is the first week of the year.}});\n }\n });\n }", "function getSetGlobalLocale(key,values){var data;if(key){if(isUndefined(values)){data=getLocale(key)}else{data=defineLocale(key,values)}if(data){\n// moment.duration._locale = moment._locale = data;\nglobalLocale=data}else{if(typeof console!==\"undefined\"&&console.warn){\n//warn user if arguments are passed but the locale could not be set\nconsole.warn(\"Locale \"+key+\" not found. Did you forget to load it?\")}}}return globalLocale._abbr}", "loadLocale() {\n const { locale } = this.options;\n const isRfc3066 = locale.indexOf('_') !== -1;\n const baseLocale = isRfc3066 ? locale.split('_')[0] : locale;\n // const momentLocale = isRfc3066 ? [locale, baseLocale] : locale;\n const phrasesLocale = isRfc3066 ? [baseLocale, locale] : [locale];\n\n moment.locale(locale);\n Text.setLocale(baseLocale);\n\n if (typeof this.options.phrases[baseLocale] !== 'undefined') {\n const { phrases } = this.options;\n const localePhrases = _.reduce(\n phrasesLocale,\n (allPhrases, phraseLocale) => _.extend(allPhrases, phrases[phraseLocale] || {}),\n {},\n );\n Text.setPhrases(localePhrases);\n } else {\n Text.clearPhrases();\n }\n }", "function localize() {\n // localize event types\n $q($alpbros.MTBEventTypes).ForEach(function (x) { return $.extend(x.Value, $alpbros.$res.eventTypes[x.Key]); });\n // localize moment\n moment.locale($cfg.lang);\n }", "loadCustomizedMoment() {\n const custom = this.buildCustomizedMoment();\n const currentLang = moment.locale();\n\n moment.updateLocale(currentLang, custom);\n this.moment = moment().locale(currentLang, custom);\n }", "function setLocaleDateTime () {\n wialon.util.DateTime.setLocale(Locale.days, Locale.months, Locale.days_abbrev, Locale.months_abbrev);\n }", "locale() {\n return settingsCache.get('default_locale');\n }", "function getSetGlobalLocale (key, values) {\n/* 1847 */ var data;\n/* 1848 */ if (key) {\n/* 1849 */ if (isUndefined(values)) {\n/* 1850 */ data = getLocale(key);\n\n/* moment.js */\n\n/* 1851 */ }\n/* 1852 */ else {\n/* 1853 */ data = defineLocale(key, values);\n/* 1854 */ }\n/* 1855 */ \n/* 1856 */ if (data) {\n/* 1857 */ // moment.duration._locale = moment._locale = data;\n/* 1858 */ globalLocale = data;\n/* 1859 */ }\n/* 1860 */ else {\n/* 1861 */ if ((typeof console !== 'undefined') && console.warn) {\n/* 1862 */ //warn user if arguments are passed but the locale could not be set\n/* 1863 */ console.warn('Locale ' + key + ' not found. Did you forget to load it?');\n/* 1864 */ }\n/* 1865 */ }\n/* 1866 */ }\n/* 1867 */ \n/* 1868 */ return globalLocale._abbr;\n/* 1869 */ }", "static get DEFAULT_LOCALE() { return 'en'; }", "static set locale(value) { _locale = value; }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Whether the sector's data is invalid. Normally FB is normal and F8 is deleted, but the singledensity version has two other values (F9 and FA), which we also consider deleted, to match xtrs.
isDeleted() { const dam = this.flags & Flags.DAM_MASK; if (this.isDoubleDensity()) { return dam === Flags.DAM_DD_F8; } else { return dam !== Flags.DAM_SD_FB; } }
[ "isDeleted() {\n const dam = this.getByte(this.dataIndex - 1);\n if (dam !== 0xF8 && dam !== 0xFB) {\n console.error(\"Unknown DAM: \" + z80_base_2.toHexByte(dam));\n }\n // Normally, 0xFB, but 0xF8 if sector is considered deleted.\n return dam === 0xF8;\n }", "verify() {\n const drive = this.drives[this.currentDrive];\n if (drive.floppyDisk === undefined) {\n this.status |= STATUS_NOT_FOUND;\n }\n else if (drive.physicalTrack !== this.track) {\n this.status |= STATUS_SEEK_ERROR;\n }\n else {\n // Make sure a sector exists on this track.\n const sectorData = drive.floppyDisk.readSector(this.track, trs80_base_1.Side.FRONT, undefined);\n if (sectorData === undefined) {\n this.status |= STATUS_NOT_FOUND;\n }\n if (this.doubleDensity && !drive.floppyDisk.supportsDoubleDensity) {\n this.status |= STATUS_NOT_FOUND;\n }\n }\n }", "function hasdensity() {\r\n return density!=-1.0\r\n}", "verify() {\n const drive = this.drives[this.currentDrive];\n if (drive.floppyDisk === undefined) {\n this.status |= STATUS_NOT_FOUND;\n }\n else if (drive.physicalTrack !== this.track) {\n this.status |= STATUS_SEEK_ERROR;\n }\n else {\n // Make sure a sector exists on this track.\n const sectorData = drive.floppyDisk.readSector(this.track, Side.FRONT, undefined);\n if (sectorData === undefined) {\n this.status |= STATUS_NOT_FOUND;\n }\n if (this.doubleDensity && !drive.floppyDisk.supportsDoubleDensity) {\n this.status |= STATUS_NOT_FOUND;\n }\n }\n }", "function checkIfDensity(fileContents) {\n\t\ttry {\n\t\t\tvar tmpFloat = new Float32Array(fileContents);\n\t\t\tvar dim = 256;\n\t\t\t// Todo: Why is the file size this size??\n\t\t\tif(tmpFloat.length != dim*dim*dim && 16908288 != tmpFloat.length) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\telse {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t} catch(e) {\n\t\t\treturn false;\n\t\t}\n\t}", "function segmentIsInvalid(segment) {\n return segment.subWordTextChunks.length === 0;\n }", "function isValidSV(svinfo) {\n var self = this;\n var checks = [];\n \n if ( ['DUP', 'DEL', 'INV'].indexOf(svinfo.type) >= 0) {\n checks.push(svinfo.len > 1);\n }\n\n /*\n dna.getChromList(svinfo.rname).some(function(rname) {\n try {\n checks.push(!self.freader.hasN(rname, svinfo.start, svinfo.end - svinfo.start));\n return true;\n }\n catch (e) {\n return false;\n }\n });\n */\n\n return checks.every(function(v) {return v });\n}", "function isFileFormatValid(data) {\n try {\n //determines if the format of each object in the file is valid\n let isFormatInvalid = data.filter( item => \n !item.name &&\n !item.completedDuration.hr &&\n !item.completedDuration.min &&\n !item.completedDuration.sec &&\n !item.totalDuration.hr &&\n !item.totalDuration.min &&\n !item.totalDuration.sec\n );\n \n console.log(`isFileFormatValid() invalid count: ${isFormatInvalid.length}`);\n if ( isFormatInvalid.length > 0 ) { //format is invalid at at least once\n console.log('isFileFormatValid(): loaded file is INVALID');\n return false;\n }\n \n console.log('isFileFormatValid(): loaded file is VALID :D');\n return true; //format is valid\n }\n catch(err) {\n console.log(`ERR isFileFormatValid(): ${err.message}`);\n return false;\n }\n}", "isValid(){\n return (this.header !== undefined && this.header !== \"\" && this.datatype !== undefined);\n }", "hasCrcError() {\n return (this.flags & Flags.BAD_CRC) !== 0;\n }", "function segmentIsInvalid(segment) {\n return segment.subWordTextChunks.length === 0;\n }", "function validShape(piece) {\n return (piece.shape !== undefined) && (turfArea(piece.shape) > 0.33);\n}", "function isFertilzerValid(data){\n\tlet isValid = true;\n let validationRulesLenghtMoreThan0 = ['name','log','quantity','location','quantityUnit','unit','type','tc','no3','nh4','k2o','p2o5','price','currency'];\n validationRulesLenghtMoreThan0.forEach((rule) =>{\n if(data[rule] && !data[rule].toString().length){\n \tisValid = isValid && false\n }\n });\n return isValid;\n}", "function check_nonzero_denominators() {\n if (row1_den.value == 0 || row2_den.value == 0 ||\n row3_den.value == 0 || row4_den.value == 0) {\n return false;\n }\n return true;\n}", "function checkValida(ficha){\n var valida=false\n for (i=0; i<fichasValidas.length; i++){\n for (j=0; j<fichasValidas[i].length; j++){ \n\n if(fichasValidas[i][j].coord[0]*anchoficha==ficha.coord[0]\n &&fichasValidas[i][j].coord[1]*altoficha==ficha.coord[1]\n &&ficha.rot==i){\n valida=true;\n }\n \n }\n }\n return valida;\n }", "function isInvalid(journal) {\n return !isValid(journal);\n}", "function validateSectors() {\n var selectedSectors = sectors.filter(':checked').length;\n var isValid = selectedSectors >= requiredSectors;\n if (!isValid) {\n errorElement.addClass('field-validation-error').removeClass('field-validation-valid').text(errorMessage);\n } else {\n errorElement.addClass('field-validation-valid').removeClass('field-validation-error').text('');\n }\n return (isValid);\n}", "isValid() {\n return this.isValidRGB() && this.isValidHex();\n }", "isValid() {\n return this.isNumberValid(this.health) &&\n this.isNumberValid(this.protection) &&\n this.isNumberValid(this.speed) &&\n this.isNumberValid(this.potency) &&\n this.isNumberValid(this.tenacity) &&\n this.isNumberValid(this.physDmg) &&\n this.isNumberValid(this.physCritRating) &&\n this.isNumberValid(this.armor) &&\n this.isNumberValid(this.specDmg) &&\n this.isNumberValid(this.specCritRating) &&\n this.isNumberValid(this.resistance) &&\n this.isNumberValid(this.physDmgPercent);\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the value at a certain position in the Tic Tac Toe Board
valueAt(x, y){ return this.ticTacToeGameBoard[x][y]; }
[ "function PboardGet(x, y)\n{\n return board[x * 7 + y];\n}", "function getPieceAt(row, col) {\n \n var player = checkerboard[row][col];\n \n return player;\n \n}", "valueAt(row, column){\n if(!this.validPick(row, column)){\n return false;\n }\n return this.gameArray[row][column].value;\n }", "function getCell(pos) { return gameField.querySelector(\"table\").rows[pos[1]].cells[pos[0]]; }", "function ticTacToe(board) {\n for (let i = 0; i < 3; i ++) {\n // Check horizontal wins\n if(board[i][0] === board[i][1] && board[i][1] === board[i][2]) {\n return board[i][0];\n // Check vertical wins\n } else if(board[0][i] === board [1][i] && board[1][i] === board[2][i]) {\n return board[0][i];\n }\n }\n // Check diagonal wins\n if(board[0][0] === board[1][1] && board[1][1] === board[2][2]) {\n return board[1][1];\n } else if(board[2][0] === board[1][1] && board[1][1] === board[0][2]) {\n return board[1][1];\n }\n}", "function cell(row, column) {\n return $scope.game.board[row][column]\n }", "function getboardArrayValue(x, y) {\n return boardArray[x][y];\n}", "valueAt(row, column) {\n if (!this.validPick(row, column)) {\n return false;\n }\n return this.gameArray[row][column].value;\n }", "pieceAt(row, col) {\r\n return this.board[row][col];\r\n }", "function getPosition(position) {\n\t\treturn board[position];\n\t}", "function getBoardCell(row, col) {\n return document\n .getElementById(attached)\n .getElementsByClassName(\"boardRow_\" + row)[0].childNodes[col];\n }", "findNextCoord() {\n for(let row = 0; row < 9; row++){\n for(let col = 0; col < 9; col++){\n if(this.board[row][col].getValue() == 0){\n return row * 9 + col;\n }\n }\n }\n return -1;\n }", "cursorValue(x, y) {\n //List of game states.\n const history = this.state.history;\n //Current game state\n const current = history[this.state.stepNumber];\n\n return current.squares[y][x];\n }", "function getTileFromIndex(index){ //index refers to array index\n return board[index];\n}", "get(posn) {\n\t\tif (!this.outOfBounds(posn)) {\n\t\t\treturn this.board[posn.x][posn.y];\n\t\t} else {\n\t\t\t//console.log(\"ERROR: Cannot get value - posn out of bounds: \" + posn.x + \",\" + posn.y);\n\t\t}\n\t}", "function getPuzzleValue(r, c) {\n\treturn puzzle[r][c];\n}", "function getPiece(board, square){\n // we represent each value as a bit\n // because operation on bit level are faster\n return ((board >> (square << 1)) & 3);\n\n // explanation what it means\n // square * 2^ 1\n // board / (square * 2^ 1)\n // '& 3' means we multiply by 3 because there are 3 values\n // we get bit value whenever we are in the game\n }", "function at(x,y){\n\treturn $('.board .row').eq(x).find('div').eq(y);\n}", "function getTileFromBoard( parentBoard, x, y ) {\n return parentBoard.boardArray[x][y];\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
console.log("6. ", findSubmissionByName(submissions)); 7.Declare a function named findLowestScore with parameter array. Return the object in the array with the lowest score. Use forEach method to loop through whole array.
function findLowestScore(array) { let lowest = null; submissions.forEach(function (submissions) { if (lowest === null || lowest.score > submissions.score) { lowest = submissions; } }); return lowest; }
[ "function findLowestScore(array) {\n let lowest = null;\n\n array.forEach(function (submission) {\n\n if (lowest === null || lowest.score > submission.score) {\n lowest = submission; \n }\n });\n return lowest;\n }", "function findLowestScore(array) {\n let lowest = array[0];\n array.forEach(submission => {\n if (lowest.score > submission.score) {\n lowest = submission\n }\n })\n return lowest\n}", "function findLowestScore(array) {\r\n let lowestScore = null;\r\n submissions.forEach(findLowestScore);\r\n if (lowestScore === null || lowestScore < newScore) {\r\n lowest = newScore;\r\n return newScore;\r\n }\r\n}", "function findLowestScore(array){\n score.forEach(function(){\n return Math.min(array);\n });\n findLowestScore();\n }", "function findLowestScore (array) {\n let scoreArray = array.map(a => a.score);\n let lowScore = scoreArray[0];\n scoreArray.forEach(function(score){\n if (score <= lowScore){\n lowScore = score;\n }\n })\n let lowestScoreObject = array.find(element => element.score === lowScore);\n console.log(lowestScoreObject);\n}", "function findLowestScore(array){\n let lowestScore = 100;\n\n array.forEach(element => {\n \n if(element.score<lowestScore){\n \n lowestScore=element.score;\n \n }\n });\n \n return lowestScore;\n}", "function findLowestScore(array){\n let lowestScore = 100;\n console.log(\"testing function here:\");\n console.log(lowestScore);\n lowestScore = array.forEach(getLower, lowestScore);\n console.log(lowestScore);\n let ind = array.findIndex(isScore, lowestScore);\n console.log(ind);\n return array[ind];\n\n}", "function getLowestScore(arrScores)\n{\n var lowestScore = arrScores[0];\n\n for (var i = 1; i < arrScores.length; i++)\n {\n if (arrScores[i] < lowestScore)\n lowestScore = arrScores[i];\n }\n\n return lowestScore;\n}", "function findWinningScore(){\n let smallestscore = scoresArray[0];\n for (let l = 0; l<=scoresArray.length-1; l++){\n if(smallestscore>scoresArray[l]){\n smallestscore = scoresArray[l];\n }\n }\n return smallestscore;\n }", "function getLowestGrade(array) {\n var student = array[0];\n for (let i = 1; i < array.length; i++) {\n if (array[i].grade < student.grade) {\n student = array[0];\n }\n }\n return student;\n}", "function Lowest(name_score){\n const combined = Split(name_score);\n var small = Math.min.apply(Math, combined);\n for (i = 1; i < name_score.length; i++){\n nameScore = name_score[i];\n if (small == nameScore[1]){\n var low = nameScore[0];\n }\n }\n document.getElementById(\"lowest\").innerHTML = low;\n}", "function minScore(array, elements) {\n // add this code body\n var miniScore = MAX_SCORE;\n\n // score lower than max score\n for (i = 0; i < array.length; i++) {\n if (array[i] < miniScore) {\n miniScore = array[i];\n }\n }\n return miniScore;\n}", "function getLowest(scoreboard){\n\tmin = 0;\n\tfor (var i=1; i<scoreboard.length; i++){\n\t\tif (parseInt(scoreboard[i].score) < parseInt(scoreboard[min].score))\n\t\t\tmin=i;\n\t}\n\treturn min;\n}", "function findLowestAverages(arr){\n // initially set avg of grade 6 to 100, as that is the max grade\n let avg6 = 100;\n let avg7 = 100;\n let avg8 = 100; \n let temp6 = 0;\n let temp7 = 0;\n let temp8 = 0;\n let names6 = [];\n let names7 = [];\n let names8 =[];\n for (let i=0; i <arr.length; i++ ){\n if(arr[i].grade===6){\n for (let r=0; r < arr[i].scores.length; r++){\n temp6 += (arr[i].scores[r].value)/arr[i].scores.length;\n }\n names6.push(arr[i].name)\n if(temp6<avg6){\n avg6 = temp6\n names6.pop();\n names6.push(arr[i].name)\n\n }\n else{\n names6.pop();\n }\n temp6=0;\n \n }\n if(arr[i].grade===7){\n for (let r=0; r < arr[i].scores.length; r++){\n temp7 += (arr[i].scores[r].value)/arr[i].scores.length;\n \n }\n names7.push(arr[i].name)\n if(temp7<avg7){\n avg7 = temp7\n names7.pop();\n names7.push(arr[i].name)\n }\n else{\n names7.pop();\n }\n temp7=0;\n }\n if(arr[i].grade===8){\n for (let r=0; r < arr[i].scores.length; r++){\n temp8 += (arr[i].scores[r].value)/arr[i].scores.length; \n }\n names8.push(arr[i].name)\n if(temp8<avg8){\n avg8 = temp8 \n names8.pop();\n names8.push(arr[i].name)\n }\n else{\n names8.pop();\n \n }\n temp8=0;\n } \n }\n const lowestAvgs = [{'grade': 6, 'name': names6[names6.length-1],'average': avg6},{'grade': 7, 'name': names7[names7.length-1], 'average': avg7},{'grade': 8, 'name': names8[names8.length-1], 'average': avg8}] \n return lowestAvgs\n}", "function indexofSmallestNumber() {\n var min = scoreArray[0];\n var minIndex = 0;\n for (var i = 0; i < scoreArray.length; i++) {\n if (scoreArray[i] < min) {\n minIndex = i;\n min = scoreArray[i];\n }\n }\n\n $(\"#match\").text(allFriends[minIndex].name);\n }", "function findMinScoreMember() {\n\t\t\t\n\t\t\tfor(var j = 0;j< resultArrayList.length;j++){\n\t\t\t\t//var temparray = resultArrayList[j;]\n\t\t\t\tvar sum=0;\n\t\t\t\tfor(let i = 0; i < resultArrayList[j].length; i++) {\n\t\t\t\t\tsum += resultArrayList[j][i];\n\t\t\t\t}\n\t\t\t\tsumarray.push(sum);\n\t\t\t\tconsole.log(\"sumarray\",sumarray);\n\t\t\t}\n\t\t\tvar tempSmallId = findSmallestDiffIndex();\n\t\t\t//console.log(\"---- minimum score person -----\\n\");\n\t\t\t//console.log(\"index:\"+tempSmallId);\n\t\t\t//console.log(\"name:\"+friendsData[tempSmallId].name);\n\t\t\t//console.log(\"photo:\"+friendsData[tempSmallId].photo);\n\t\t\treturn friendsData[tempSmallId];\n\n\t\t}", "function minScore(array, elements) {\n lowScore = 100\n for (i = 0; i < array.length; i++) {\n if (array[i] < lowScore) {\n lowScore = array[i]\n }\n }\n return lowScore;\n}", "function sortForLow(){ \n// set value of lowestScore to the sorted array lowest to highest (a-b)\nlet lowestScore = scores.sort(function(a,b){return a-b}) \n//console log the value of lowestScore at index 0\nconsole.log('the lowest score is', lowestScore[0])\n}", "function minScoreIndex(array, elements) {\n // add this code body\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Moves the character in the argument in the direction desired, if possible. If not, returns false.
moveCharacter(character, direction) { var candidateTile; var currTileX = character.getCurrentTile().getTileX(); var currTileY = character.getCurrentTile().getTileY(); var charState; var result = true; switch (direction) { case 'up': candidateTile = this.gameBoard[currTileX][currTileY - 1]; break; case 'left': candidateTile = this.gameBoard[currTileX - 1][currTileY]; charState = 'idleLeft'; break; case 'down': candidateTile = this.gameBoard[currTileX][currTileY + 1]; break; case 'right': candidateTile = this.gameBoard[currTileX + 1][currTileY]; charState = 'idleRight'; break; default: console.log("Debug method: moveCharacter"); break; } //If the candidate tile contains the survivor, it cannot be moved into. if (this.Survivor.getCurrentTile() == candidateTile) { result = false; } //If the candidate tile contains is not passable, it cannot be moved into. if (candidateTile.canBePassed() == false) { result = false; } //If the candidate tile contains an active, alive zombie, it cannot be moved into. for (const z of this.activeZombies) { if (z.getCurrentTile() == candidateTile && z.isZombieAlive()) { result = false; } } //If the tile can be moved into, move the entity and change animation state. if (result) { character.moveChar(candidateTile); } if (charState != null) { character.setState(charState); } return result; }
[ "move(direction) {\n if (direction === 'n' && this._confirmDirection(this.y - 1, this.x)) {\n this.prev = [...this.position];\n this.position[0] -= 1;\n return true;\n } else if (direction === 's' && this._confirmDirection(this.y + 1, this.x)) {\n this.prev = [...this.position];\n this.position[0] += 1;\n return true;\n } else if (direction === 'w' && this._confirmDirection(this.y, this.x - 1)) {\n this.prev = [...this.position];\n this.position[1] -= 1;\n return true;\n } else if (direction === 'e' && this._confirmDirection(this.y, this.x + 1)) {\n this.prev = [...this.position];\n this.position[1] += 1;\n return true;\n } else {\n return false;\n }\n }", "move(direction) {\r\n let pathX = this._positionX;\r\n let pathY = this._positionY;\r\n\r\n switch(direction.toLowerCase()) {\r\n case \"d\": pathX++; break;\r\n case \"u\": pathX--; break;\r\n case \"r\": pathY++; break;\r\n case \"l\": pathY--; break;\r\n default: return invalid;\r\n }\r\n\r\n if (this.checkMove(pathX, pathY)) {\r\n if (this._field[pathX][pathY] === hat) return foundHat;\r\n this._field[pathX][pathY] = pathCharacter;\r\n this._positionX = pathX;\r\n this._positionY = pathY;\r\n \r\n }\r\n else {\r\n return false;\r\n }\r\n\r\n}", "check_valid_move(direction){\n if (\n (direction === 'u' || direction === 'U' || direction === 'up')\n && this.poss[0] === 0) {\n return false;\n }else if (\n (direction === 'd' || direction === 'D' || direction === 'down')\n && this.poss[0] === this.field.length) {\n return false;\n }else if (\n (direction === 'r' || direction === 'R' || direction === 'right')\n && this.poss[1] >= this.field[0].length-1) {\n return false;\n }else if (\n (direction === 'l' || direction === 'L' || direction === 'left')\n && this.poss[1] === 0) {\n return false;\n }else {\n return true;\n }\n }", "move (startSpace, endSpace) {\r\n const { valid, reason, jump } = this.isMoveValid(startSpace, endSpace)\r\n\r\n if (!valid) {\r\n console.error(`Invalid move: ${reason}`)\r\n return false\r\n }\r\n\r\n // Move the start piece to the end piece\r\n this.board[endSpace] = this.board[startSpace]\r\n this.remove(startSpace)\r\n this.remove(jump)\r\n\r\n return true\r\n }", "function moveCharacter(characterWrap){\n\t\t\tvar sizeY = characterWrap.outerHeight() / 2;\n\t\t\tvar sizeX = characterWrap.outerWidth() / 2;\n\t\t\tvar character = characterWrap.find('.active');\n\n\t\t\tif(supportTransitions()){\n\t\t\t\tif(character.hasClass('moveRight')){\n\t\t\t\t\tif(!characterWrap.hasClass('moved')){\n\t\t\t\t\t\tcharacterWrap.css('left', '-' + sizeX + 'px');\n\t\t\t\t\t}else{\n\t\t\t\t\t\tcharacterWrap.css('left', '0px');\n\t\t\t\t\t}\n\t\t\t\t} else if(character.hasClass('moveLeft')){\n\t\t\t\t\tif(!characterWrap.hasClass('moved')){\n\t\t\t\t\t\tcharacterWrap.css('left', '0px');\n\t\t\t\t\t}else{\n\t\t\t\t\t\tcharacterWrap.css('left', '-' + sizeX + 'px');\n\t\t\t\t\t}\n\t\t\t\t} else if(character.hasClass('moveUp')){\n\t\t\t\t\tif(!characterWrap.hasClass('moved')){\n\t\t\t\t\t\tcharacterWrap.css('top', '0px');\n\t\t\t\t\t}else{\n\t\t\t\t\t\tcharacterWrap.css('top', '-' + sizeY + 'px');\n\t\t\t\t\t}\n\t\t\t\t} else if(character.hasClass('moveDown')){\n\t\t\t\t\tif(!characterWrap.hasClass('moved')){\n\t\t\t\t\t\tcharacterWrap.css('top', '-' + sizeY + 'px');\n\t\t\t\t\t}else{\n\t\t\t\t\t\tcharacterWrap.css('top', '0px');\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\t//jquery fallback \n\t\t\telse{\n\t\t\t\tif(character.hasClass('moveRight')){\n\t\t\t\t\tif(!characterWrap.hasClass('moved')){\n\t\t\t\t\t\tcharacterWrap.animate({\n\t\t\t\t\t\t\t'left': '-' + sizeX + 'px'\n\t\t\t\t\t\t}, 400);\n\t\t\t\t\t}else{\n\t\t\t\t\t\tcharacterWrap.animate({\n\t\t\t\t\t\t\t'left': '0px'\n\t\t\t\t\t\t},400);\n\t\t\t\t\t}\n\t\t\t\t} else if(character.hasClass('moveLeft')){\n\t\t\t\t\tif(!characterWrap.hasClass('moved')){\n\t\t\t\t\t\tcharacterWrap.animate({\n\t\t\t\t\t\t\t'left': '0px'\n\t\t\t\t\t\t},400);\n\t\t\t\t\t}else{\n\t\t\t\t\t\tcharacterWrap.animate({\n\t\t\t\t\t\t\t'left' : '-' + sizeX + 'px'\n\t\t\t\t\t\t},400);\n\t\t\t\t\t}\n\t\t\t\t} else if(character.hasClass('moveUp')){\n\t\t\t\t\tif(!characterWrap.hasClass('moved')){\n\t\t\t\t\t\tcharacterWrap.animate({\n\t\t\t\t\t\t\t'top': '0px'\n\t\t\t\t\t\t}, 400);\n\t\t\t\t\t}else{\n\t\t\t\t\t\tcharacterWrap.animate({\n\t\t\t\t\t\t\t'top': '-' + sizeY + 'px'\n\t\t\t\t\t\t}, 400);\n\t\t\t\t\t}\n\t\t\t\t} else if(character.hasClass('moveDown')){\n\t\t\t\t\tif(!characterWrap.hasClass('moved')){\n\t\t\t\t\t\tcharacterWrap.animate({\n\t\t\t\t\t\t\t'bottom' : sizeY + 'px'\n\t\t\t\t\t\t}, 400);\n\t\t\t\t\t}else{\n\t\t\t\t\t\tcharacterWrap.animate({\n\t\t\t\t\t\t\t'bottom':'0px'\n\t\t\t\t\t\t},400);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tcharacterWrap.toggleClass('moved');\n\t\t}", "isValidMove(direction) {\r\n try\r\n {\r\n switch (direction)\r\n {\r\n case \"Up\":\r\n return this._data[this._playerRow - 1][this._playerCol] == 0;\r\n case \"Down\":\r\n return this._data[this._playerRow + 1][this._playerCol] == 0;\r\n case \"Right\":\r\n return this._data[this._playerRow][this._playerCol + 1] == 0;\r\n case\"Left\":\r\n return this._data[this._playerRow][this._playerCol - 1] == 0;\r\n default:\r\n var e = new Error();\r\n e.message = \"wrong argument in isValidMove\";\r\n throw e;\r\n }\r\n }\r\n //in case the movement is outside the maze\r\n catch (e)\r\n {\r\n return false;\r\n } \r\n }", "function move(direction) {}", "function tryMovePlayer(x, y, direction) {\n\n\tswitch (direction) {\n\t\tcase \"up\":\n\t\t\t//console.log(\"TRYING TO MOVE PLAYER WITH XPOS: \"+x+\" , ypos: \"+y)\n\t\t\tfor (var counter = 0 ; counter < gridItemArr.length; counter++) {\n\n\t\t\t\tif (gridItemArr[counter].ypos === y - 1 && gridItemArr[counter].xpos === x) {\n\t\t\t\t\t\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn false;\n\t\t\tbreak;\n\n\t\tcase \"down\":\n\t\t\t//console.log(\"TRYING TO MOVE PLAYER WITH XPOS: \"+x+\" , ypos: \"+y)\n\t\t\tfor (var counter = 0 ; counter < gridItemArr.length; counter++) {\n\t\t\t\tif (gridItemArr[counter].ypos === y + 1 && gridItemArr[counter].xpos === x) {\n\t\t\t\t\t\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn false;\n\t\t\tbreak;\n\n\t\tcase \"left\":\n\t\t\tfor (var counter = 0 ; counter < gridItemArr.length; counter++) {\n\t\t\t\tif (gridItemArr[counter].ypos === y && gridItemArr[counter].xpos === x - 1) {\n\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\n\t\t\t}\n\t\t\treturn false;\n\t\t\tbreak;\n\n\t\tcase \"right\":\n\t\t\tfor (var counter = 0 ; counter < gridItemArr.length; counter++) {\n\t\t\t\tif (gridItemArr[counter].ypos === y && gridItemArr[counter].xpos === x + 1) {\n\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn false;\n\t\t\tbreak;\n\n\t\tdefault:\n\t\t\tconsole.log(\"ERROR SOMEWHERE WHEN TRYING TO MOVE\");\n\n\t}\n\n}", "checkBackwardsMove(piece, newLocation, prevLocation) {\n if (piece.classList.contains(\"playerP\")) {\n if (newLocation[0] >= prevLocation[0])\n return false;\n else return true;\n }\n else if (piece.classList.contains(\"playerG\")) {\n if (newLocation[0] <= prevLocation[0])\n return false;\n else return true;\n }\n }", "runMovement(...args) {\n // Normalize the various argument forms.\n const [direction, granularity] = (typeof (args[0]) === \"string\") && (args.length === 1)\n ? args[0].trim().split(/\\s+/)\n : (args.length === 1 ? args[0] : args.slice(0, 2));\n\n // Native word movements behave differently on Linux and Windows, see #1441. So we implement\n // some of them character-by-character.\n if ((granularity === vimword) && (direction === forward)) {\n while (this.nextCharacterIsWordCharacter()) {\n if (this.extendByOneCharacter(forward) === 0) {\n return;\n }\n }\n while (this.getNextForwardCharacter() && !this.nextCharacterIsWordCharacter()) {\n if (this.extendByOneCharacter(forward) === 0) {\n return;\n }\n }\n } else if (granularity === vimword) {\n this.selection.modify(this.alterMethod, backward, word);\n }\n\n // As above, we implement this character-by-character to get consistent behavior on Windows and\n // Linux.\n if ((granularity === word) && (direction === forward)) {\n while (this.getNextForwardCharacter() && !this.nextCharacterIsWordCharacter()) {\n if (this.extendByOneCharacter(forward) === 0) {\n return;\n }\n }\n while (this.nextCharacterIsWordCharacter()) {\n if (this.extendByOneCharacter(forward) === 0) {\n return;\n }\n }\n } else {\n return this.selection.modify(this.alterMethod, direction, granularity);\n }\n }", "movePlayer() {\n if (this.getChainLength() > 1) {\n let playerStartPosition = this.chain.shift();\n let playerEndPosition = this.getFirstChainItem();\n this.setPlayerPosition(playerEndPosition.row, playerEndPosition.column);\n this.swapItems(playerStartPosition.row, playerStartPosition.column, playerEndPosition.row, playerEndPosition.column);\n this.setEmpty(playerStartPosition.row, playerStartPosition.column);\n return {\n from: playerEndPosition,\n to: playerStartPosition\n }\n }\n this.emptyChain();\n return false;\n }", "function move() {\n // TODO esto puede entrar en un loop infinito en el que no encuentra dead ends\n // siempre va a poder volver a donde vino\n if (canMoveRight()) {\n moveRight()\n console.log(\"derecha\")\n } else if (canMoveDown()) {\n moveDown()\n console.log(\"abajo\")\n } else if (canMoveLeft()) {\n moveLeft()\n console.log(\"izquierda\")\n } else if (canMoveUp()) {\n moveUp()\n console.log(\"arriba \")\n } else {\n // TODO chequear que pasa cuando entra acá\n console.log(\"wtf\")\n deadEnds.push([actualRow, actualColumn])\n resetPositionToStart()\n clearPath()\n }\n return newPosition\n}", "function turnAround() {\n if (direction === \"right\") {\n direction = \"left\";\n }\n else if (direction === \"left\") {\n direction = \"right\";\n }\n }", "move() {\n\t\tif(this._current_position === 'down' && this.is_full()) {\n\t\t\tthis._current_position = 'up';\n\t\t}\n\t\telse if(this._current_position === 'up' && this.is_full()) {\n\t\t\tthis._current_position = 'up1';\n\t\t}\n\t\telse if (this._current_position === 'up1' && !this.is_full()){\n\t\t\tthis._current_position = 'down';\n\t\t}\n\t}", "function movePlayerToken(player, direction){\n\n if(!isValidInput(player, direction)){\n console.log(\"Bad input\");\n return false;\n }\n\n switch (direction) {\n case 'north':\n playerPositions[player][1] -= 1;\n console.log(\"north!\");\n break;\n case 'south':\n playerPositions[player][1] += 1;\n break;\n case 'east':\n playerPositions[player][0] += 1;\n break;\n case 'west':\n playerPositions[player][0] -= 1;\n break;\n default:\n console.log(\"Not a direction!\");\n }\n\n return true;\n\n}//end movePlayerToken()", "function move(x) {\n direction = x;\n}", "move(command) {\n console.log(`moving disk from ${command.from} to ${command.to}`);\n if (commandIsValid(command)) {\n console.log('valid command');\n moveDisk(command);\n checkIfGameIsSolved();\n notifyListeners();\n return true;\n }\n console.log('invalid command');\n return false;\n }", "moveByChar(start, forward, by) {\n return moveByChar(this, start, forward, by);\n }", "moveForward() {\n switch (this.coordinates.currDirection) {\n case DIRECTIONS[0]:\n if (this.checkPosition(this.coordinates.x, this.coordinates.y + 1)) {\n this.coordinates.y += 1\n }\n break;\n case DIRECTIONS[1]:\n if (this.checkPosition(this.coordinates.x + 1, this.coordinates.y)) {\n this.coordinates.x += 1\n }\n break;\n case DIRECTIONS[2]:\n if (this.checkPosition(this.coordinates.x, this.coordinates.y - 1)) {\n this.coordinates.y -= 1\n }\n break;\n case DIRECTIONS[3]:\n if (this.checkPosition(this.coordinates.x - 1, this.coordinates.y)) {\n this.coordinates.x -= 1\n }\n break;\n default:\n console.log(`Error: There's no direction to move! currentDirection is ${this.coordinates.currDirection}`)\n }\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
this should implement the archive view
function archiveView() { const tasklist = $("#tasklist"); const archivelist = $("#archivelist"); // first, update the archive with data from the DOM const archivedList = getIDList("archivelist"); const tasks = $("body").data("tasks"); const archive = tasks["archive"]; const archiveKeys = Object.keys(archive); if (archivedList.length > 0) // there are already entries in the table { for (let i = 0; i < archiveKeys.length; i++) { if (!archivedList.find(element => element === archiveKeys[i])) { // write the task to the table addArchiveTask(archiveKeys[i], archive[archiveKeys[i]]); } } } else { for (let j = 0; j < archiveKeys.length; j++) { // write the task to the table probably by calling addTask addArchiveTask(archiveKeys[j], archive[archiveKeys[j]]); } } // hide the tasklist tasklist.hide(); // show the archive archivelist.show(); // switch our links around switchViewLinks("tasks"); }
[ "_onArchiveClicked(ev) {\n ev.stopPropagation();\n ev.preventDefault();\n\n this.model.updateVisibility('archive');\n }", "function archive() {\n if (this.id == \"archive\") {\n mark_archived(this.dataset.id, true);\n } else {\n mark_archived(this.dataset.id, false);\n }\n}", "function getArchiveView(apiurl, handler) {\r\n\treturn $.ajax({\r\n\t\turl: apiurl,\r\n\t\theaders: getAuthHeader(),\r\n\t\tdataType:DEFAULT_DATATYPE\r\n\t}).always(function(){\r\n\t\t//Remove old information, clear the form data hide the content information(no selected)\r\n\t\t$(\"#form-content\").empty();\r\n\t\t$(\"#main-content\").hide();\r\n\r\n\t}).done(function (data, textStatus, jqXHR){\r\n\t\tif (DEBUG) {\r\n\t\t\tconsole.log (\"RECEIVED RESPONSE: data:\",data,\"; textStatus:\",textStatus)\r\n\t\t}\r\n\t\t// Create a form from the template with initial values from the collection item\r\n\t\tvar item_data = data.collection.items[0].data;\r\n\t\tvar course_url = findLink(data.collection.items[0].links, \"course_list\");\r\n\t\tvar template = data.collection.template;\r\n\t\tvar links = data.collection.links;\r\n\t\tvar initial_data = data.collection.items[0].data;\r\n\t\tvar edit_url = data.collection.href;\r\n\t\tvar archive_name = findField(item_data,\"name\");\r\n\t\tvar organisationName = findField(item_data,\"organisationName\");\r\n\r\n\t\tvar identification_needed = findField(item_data,\"identificationNeeded\");\r\n\t\tif(identification_needed == 0)\r\n\t\t identification = \"No\";\r\n\t\telse\r\n\t\t identification = \"Yes\";\r\n\r\n // Print page header\r\n $(\"#page-header\")\r\n .html(\"<h1>Archive \"+findField(item_data,\"name\")+\"</h1>\");\r\n\r\n $(\"#page-info\")\r\n .html(\"<tr>\"+\r\n \"<td>Archive name: \"+archive_name+\"</td>\"+\r\n \"<td class='admin-only'><a class='edit-archive' href='\"+apiurl+\"'>Edit archive</a></td>\"+\r\n \"</tr>\"+\r\n \"<tr>\"+\r\n \"<td>Organisation name: \"+organisationName+\"</td>\"+\r\n \"<td></td>\"+\r\n \"</tr>\"+\r\n \"<tr>\"+\r\n // Functions around indentification needed value will be implemented later\r\n // \"<td>Indentification needed: \"+identification+\"</td>\"+\r\n \"<td></td>\"+\r\n \"<td></td>\"+\r\n \"<tr>\");\r\n\r\n // Print list header\r\n $(\"#list-header\").html(\"<h4>Courses of the archive</h4>\")\r\n\r\n getCourseList(course_url);\r\n\r\n\t\t$(\"#form-content\").show();\r\n\r\n addNavigationLink(archive_name, \"archive\", apiurl, handleGetArchiveView);\r\n\r\n\t}).fail(function (jqXHR, textStatus, errorThrown){\r\n\t\tif (DEBUG) {\r\n\t\t\tconsole.log (\"RECEIVED ARCHIVELIST/GET ERROR: textStatus:\",textStatus, \";error:\",errorThrown)\r\n\t\t}\r\n\t\t//Inform user about the error using an alert message.\r\n\t\talert (\"Could not fetch the list of archives. Please, try again\");\r\n\t});\r\n}", "function archive() {\n vm.error = undefined;\n var promises = [];\n vm.todos.filter(function (todo) {\n return todo.completed;\n }).forEach(function (todo) {\n promises.push(_archive(todo));\n });\n\n $q.all(promises).then(function () {\n _fetch();\n }).catch(function () {\n vm.error = 'An error occurred when archiving completed todos';\n });\n }", "async archive() {\n await this.update({\"archived\": true});\n }", "function getArchive() {\n //buscar las tareas guardadas\n let todos = getLocalDataArchive();\n //iterar entre todos los elementos\n todos.forEach(function(todo) {\n createNewTodo(todo);\n\n });\n}", "function menuArchiveClick()\n {\n var url = \"/lists/\" + currentList.name;\n if (currentList.archived)\n {\n url += '/unarchive';\n $.ajax({\n url: url,\n method: \"POST\",\n error: function(hdr, status, error)\n {\n gsd.errorMessage(\"menuArchiveClick \" + status + ' - ' + error);\n },\n success: function(data)\n {\n if (data && data.error)\n {\n gsd.errorMessage(data.error);\n return;\n }\n gsd.loadList(currentList.name, false);\n gsd.successMessage(\"List successfully unarchived.\");\n }\n });\n\n return false;\n }\n\n // The archive version\n url += '/archive';\n $.ajax({\n url: url,\n method: \"POST\",\n error: function(hdr, status, error)\n {\n gsd.errorMessage(\"menuArchiveClick \" + status + ' - ' + error);\n },\n success: function(data)\n {\n if (data && data.error)\n {\n gsd.errorMessage(data.error);\n return;\n }\n gsd.loadList(currentList.name, true);\n gsd.successMessage(\"List successfully archived.\");\n }\n });\n return false;\n }", "function archiveTool() {\n // Configuration\n var userconfig = (window.ArchiveToolConfig) ? window.ArchiveToolConfig : {};\n var config = $.extend(true, {\n archiveListTemplate: 'Archives',\n archivePageTemplate: 'Archivepage',\n archiveSubpage: 'Archive',\n userLang: false,\n // English\n en: {\n buttonArchiveTool: \"Archive\",\n buttonArchiveToolTooltip: \"Archive this page\",\n buttonSelectAll: \"Select all\",\n buttonDeselectAll: \"Deselect all\",\n buttonSaveArchive: \"Save archive\",\n buttonAbort: \"Abort\",\n labelLines: \"Lines\",\n labelSections: \"Sections\",\n summaryArchiveFrom: \"ArchiveTool: Archiving from\",\n summaryArchiveTo: \"ArchiveTool: Archiving to\"\n }\n }, userconfig);\n\n // Function for multi-language support\n function msg(name) {\n if ( config.userLang && wgUserLanguage in config && name in config[wgUserLanguage] )\n return config[wgUserLanguage][name];\n if ( wgContentLanguage in config && name in config[wgContentLanguage] )\n return config[wgContentLanguage][name];\n return config.en[name];\n }\n \n if (skin != \"monaco\" && skin != 'monobook' && skin != 'oasis' && skin != 'wikia') {\n return;\n }\n\n if ((wgNamespaceNumber%2 != 0 && wgNamespaceNumber != 501) && (wgAction == \"view\" || wgAction == \"purge\")) {\n var skinConfig = {\n textCont: '', pageControls: '', controlsMarkup: '',\n buttonOpenPri: '', buttonOpenSec: '', buttonClose: ''\n };\n\n switch(skin) {\n case 'monaco':\n skinConfig.textCont = '#bodyContent';\n skinConfig.pageControls = '#page_controls';\n skinConfig.controlsMarkup = '<li id=\"control_archive\"><img src=\"/skins/common/blank.gif\" class=\"sprite move\" /><a id=\"ca-archive\" title=\"' + msg('buttonArchiveToolTooltip') + '\" href=\"#\" rel=\"nofollow\">' + msg('buttonArchiveTool') + '</a></li>';\n skinConfig.buttonOpenPri = '<a class=\"wikia-button\">';\n skinConfig.buttonOpenSec = '<a class=\"wikia-button secondary\">';\n skinConfig.buttonClose = '</a>';\n break;\n case 'monobook':\n skinConfig.textCont = '#bodyContent';\n skinConfig.pageControls = '#p-cactions > div > ul';\n skinConfig.controlsMarkup = '<li id=\"control_archive\"><a id=\"ca-archive\" title=\"' + msg('buttonArchiveToolTooltip') + '\" href=\"#\" rel=\"nofollow\">' + msg('buttonArchiveTool') + '</a></li>';\n skinConfig.buttonOpenPri = '<input type=\"submit\" style=\"font-weight: bold;\" value=\"';\n skinConfig.buttonOpenSec = '<input type=\"submit\" value=\"';\n skinConfig.buttonClose = '\" />';\n break;\n case 'oasis':\n case 'wikia':\n skinConfig.textCont = '#WikiaArticle';\n skinConfig.pageControls = ($('#WikiaUserPagesHeader').length ? '.UserProfileActionButton' : '#WikiaPageHeader') + ' > .wikia-menu-button > ul';\n skinConfig.controlsMarkup = '<li id=\"control_archive\"><a id=\"ca-archive\" rel=\"nofollow\">' + msg('buttonArchiveTool') + '</a></li>';\n skinConfig.buttonOpenPri = '<a class=\"wikia-button\">';\n skinConfig.buttonOpenSec = '<a class=\"wikia-button secondary\">';\n skinConfig.buttonClose = '</a>';\n break;\n }\n\n $(function() {\n function api(q, fn) {\n q.format = 'json';\n return $.post(wgScriptPath + '/api.php', q, fn, \"json\");\n }\n function token(page, fn) {\n api({\n action: 'query',\n query: 'prop',\n prop: 'info',\n titles: page,\n intoken: 'edit'\n }, function(q) {\n for ( var k in q.query.pages )\n return fn(q.query.pages[k]);\n });\n }\n \n function startArchiving() {\n var c = config.archiveListTemplate.substr(0,1);\n var archiveListRegex = '['+c.toUpperCase()+c.toLowerCase()+']'+config.archiveListTemplate.substr(1);\n var bc = $(skinConfig.textCont).addClass('va-archiving').empty();\n\n $('<img class=\"ajax\" alt=\"Loading...\" />')\n .attr({src: stylepath+'/common/progress-wheel.gif'}).appendTo(bc);\n api({\n action: 'query',\n prop: 'revisions',\n titles: wgPageName,\n rvprop: 'timestamp|content'\n }, function(q) {\n bc.empty();\n var rev = q.query.pages[wgArticleId].revisions[0];\n var time = rev.timestamp;\n var talkToken, tokenTime;\n var content = rev['*'];\n token(wgPageName, function(p) {\n talkToken = p.edittoken;\n tokenTime = p.starttimestamp;\n });\n \n var lines = content.split('\\n');\n \n var table = $('<table style=\"margin: 10px 0;\"><thead><tr><th>' + msg('labelLines') + '</th><th title=\"' + msg('labelSections') + '\">{&hellip;}</th></tr></thead></table>').appendTo(bc);\n var ul = $('<tbody/>').appendTo(table);\n \n for ( var l = 0; l < lines.length; l++ ) {\n var line = lines[l];\n $('<tr/>').toggleClass('noarchive', (new RegExp('^\\\\{\\\\{'+archiveListRegex+'\\}\\}')).test(line))\n .attr({line:line})\n .append( $('<td class=line />').text(line).append('&nbsp;') ).appendTo(ul);\n }\n \n var sections = [];\n var sectionEnd = lines.length-1;\n for ( var l = lines.length-1; l >= 0; l-- ) {\n var line = lines[l];\n \n if ( /^=.+?=/.test(line) || l === 0 ) {\n var section = { start: l, end: sectionEnd };\n section.length = section.end - section.start + 1;\n sections.unshift(section);\n \n sectionEnd = l-1;\n }\n }\n \n var section;\n while( section = sections.shift() ) {\n var tr = ul.children().eq(section.start);\n $('<td class=section />').attr({rowspan: section.length}).appendTo(tr);\n }\n \n $('<div class=\"buttons\" style=\"text-align: right;\" />').append(\n $(skinConfig.buttonOpenSec + msg('buttonSelectAll') + skinConfig.buttonClose).click(function(e) {\n e.preventDefault();\n ul.children('tr').addClass('archive');\n }), ' ',\n $(skinConfig.buttonOpenSec + msg('buttonDeselectAll') + skinConfig.buttonClose).click(function(e) {\n e.preventDefault();\n ul.children('tr').removeClass('archive');\n }), ' ',\n $(skinConfig.buttonOpenPri + msg('buttonSaveArchive') + skinConfig.buttonClose).click(function(e) {\n archive();\n }), ' ',\n $(skinConfig.buttonOpenPri + msg('buttonAbort') + skinConfig.buttonClose).click(function(e) {\n bc.find('.ajax').remove();\n location = wgServer+wgScript+'?title='+encodeURI(wgPageName)+'&action=purge';\n })\n ).prependTo(bc).clone(true).appendTo(bc);\n \n var click = false;\n var add;\n table.mousedown(function(e) {\n e.preventDefault();\n var $li = $(e.target).closest('tr');\n if(!$li.length) return;\n var $section = $(e.target).closest('.section');\n if ( $section.length ) {\n var slist = $li.nextAll(':lt('+(parseInt($section.attr('rowspan'),10)-1)+')').andSelf();\n var sadd = slist.filter(function() { return !$(this).hasClass('archive') }).length;\n slist.toggleClass('archive', !!sadd);\n return;\n }\n click = true;\n add = !$li.hasClass('archive');\n \n $li.toggleClass('archive', !!add);\n });\n table.mouseover(function(e) {\n if (!click) return;\n var $li = $(e.target).closest('tr');\n if(!$li.length) return;\n \n $li.toggleClass('archive', !!add);\n });\n $('body').mouseup(function(e) {\n click = false;\n });\n \n function archive() {\n var talkLines = [];\n var archiveLines = [];\n ul.children().each(function() {\n var arr = $(this).hasClass('noarchive') || !$(this).hasClass('archive')\n ? talkLines : archiveLines;\n \n arr.push( $(this).attr('line') );\n });\n \n if ( !(new RegExp('^\\\\{\\\\{'+archiveListRegex+'\\}\\}')).test(talkLines[0]) )\n talkLines = ['{{'+config.archiveListTemplate+'}}', ''].concat(talkLines);\n archiveLines = ['{{'+config.archivePageTemplate+'}}', ''].concat(archiveLines);\n \n bc.empty();\n $('<img class=\"ajax\" alt=\"Loading...\" />')\n .attr({src: stylepath+'/common/progress-wheel.gif'}).appendTo(bc);\n \n runArchive(talkLines.join('\\n'), archiveLines.join('\\n'));\n }\n \n var archiveTitle;\n function runArchive(talkContent, archiveContent) {\n var archiveNo;\n function findArchives() {\n var m = $('<p>Finding archive id: </p>').appendTo(bc);\n api({\n action: 'query',\n list: 'allpages',\n apnamespace: wgNamespaceNumber,\n apprefix: wgTitle+'/'+config.archiveSubpage,\n aplimit: 1,\n apdir: 'descending'\n }, function(q) {\n archiveNo = q.query.allpages.length ?\n parseInt(q.query.allpages[0].title.substr(wgPageName.length+(\"/\"+config.archiveSubpage).length),10)+1 :\n 1;\n archiveTitle = wgPageName+'/'+config.archiveSubpage+' '+archiveNo;\n m.append('done... (using '+archiveNo+')');\n \n saveArchive();\n });\n }\n \n function saveArchive() {\n var m = $('<p>Finding token for '+archiveTitle+': </p>').appendTo(bc);\n token(archiveTitle, function(p) {\n m.append('done...');\n m = $('<p>Saving archive page: </p>').appendTo(bc);\n api({\n action: 'edit',\n title: archiveTitle,\n text: archiveContent,\n token: p.edittoken,\n summary: msg('summaryArchiveFrom') + \" [[\" + wgPageName + \"]].\",\n minor: true,\n createonly: true\n }, function(q) {\n if ( q.error && q.error.code === \"articleexists\" ) {\n m.append('failed...');\n bc.append(\"<p>The archive page we tried to create already exists.</p>\");\n return abort();\n }\n m.append('done...');\n \n saveTalk();\n });\n });\n }\n \n function saveTalk() {\n var m = $('<p>Finding token for '+wgPageName+': </p>').appendTo(bc);\n m.append('done...');\n m = $('<p>Updating talk page: </p>').appendTo(bc);\n api({\n action: 'edit',\n title: wgPageName,\n text: talkContent,\n token: talkToken,\n summary: msg('summaryArchiveTo') + \" [[\" + archiveTitle + \"]].\",\n minor: true,\n basetimestamp: time,\n starttimestamp: tokenTime\n }, function(q) {\n if ( q.edit.result === \"Success\" ) {\n m.append('done...');\n bc.find('.ajax').remove();\n location = wgServer+wgScript+'?title='+encodeURI(wgPageName)+'&action=purge';\n } else {\n m.append('failed...');\n bc.append(\"<p>Failed to update talkpage, you may wish to have the archive subpage we just created deleted.</p>\");\n return abort();\n }\n });\n }\n \n function abort() {\n bc.find('.ajax').remove();\n bc.append(\"<p>Aborting...</p>\");\n \n $(\"<p>You may want to </p>\")\n .append( $('<a>refresh</a>').attr({href: wgServer+wgArticlePath.replace('$1', encodeURI(wgPageName))}) )\n .append(' and try again.')\n .appendTo(bc);\n }\n \n // start\n findArchives();\n }\n });\n }\n \n $(skinConfig.controlsMarkup)\n .click(startArchiving)\n .appendTo(skinConfig.pageControls);\n });\n }\n}", "function archiveTool() {\n // Configuration\n var userconfig = (window.ArchiveToolConfig) ? window.ArchiveToolConfig : {};\n var config = $.extend(true, {\n archiveListTemplate: 'Archives',\n archivePageTemplate: 'Archivepage',\n archiveSubpage: 'Archive',\n userLang: false,\n // English\n en: {\n buttonArchiveTool: \"Archive\",\n buttonArchiveToolTooltip: \"Archive this page\",\n buttonSelectAll: \"Select all\",\n buttonDeselectAll: \"Deselect all\",\n buttonSaveArchive: \"Save archive\",\n buttonAbort: \"Abort\",\n labelLines: \"Lines\",\n labelSections: \"Sections\",\n summaryArchiveFrom: \"ArchiveTool: Archiving from\",\n summaryArchiveTo: \"ArchiveTool: Archiving to\"\n }\n }, userconfig);\n \n // Function for multi-language support\n function msg(name) {\n if ( config.userLang && wgUserLanguage in config && name in config[wgUserLanguage] )\n return config[wgUserLanguage][name];\n if ( wgContentLanguage in config && name in config[wgContentLanguage] )\n return config[wgContentLanguage][name];\n return config.en[name];\n }\n \n if (skin != \"monaco\" && skin != 'monobook' && skin != 'oasis' && skin != 'wikia') {\n return;\n }\n \n if ((wgNamespaceNumber%2 != 0 && wgNamespaceNumber != 501) && (wgAction == \"view\" || wgAction == \"purge\")) {\n var skinConfig = {\n textCont: '', pageControls: '', controlsMarkup: '',\n buttonOpenPri: '', buttonOpenSec: '', buttonClose: ''\n };\n \n switch(skin) {\n case 'monaco':\n skinConfig.textCont = '#bodyContent';\n skinConfig.pageControls = '#page_controls';\n skinConfig.controlsMarkup = '<li id=\"control_archive\"><img src=\"/skins/common/blank.gif\" class=\"sprite move\" /><a id=\"ca-archive\" title=\"' + msg('buttonArchiveToolTooltip') + '\" href=\"#\" rel=\"nofollow\">' + msg('buttonArchiveTool') + '</a></li>';\n skinConfig.buttonOpenPri = '<a class=\"wikia-button\">';\n skinConfig.buttonOpenSec = '<a class=\"wikia-button secondary\">';\n skinConfig.buttonClose = '</a>';\n break;\n case 'monobook':\n skinConfig.textCont = '#bodyContent';\n skinConfig.pageControls = '#p-cactions > div > ul';\n skinConfig.controlsMarkup = '<li id=\"control_archive\"><a id=\"ca-archive\" title=\"' + msg('buttonArchiveToolTooltip') + '\" href=\"#\" rel=\"nofollow\">' + msg('buttonArchiveTool') + '</a></li>';\n skinConfig.buttonOpenPri = '<input type=\"submit\" style=\"font-weight: bold;\" value=\"';\n skinConfig.buttonOpenSec = '<input type=\"submit\" value=\"';\n skinConfig.buttonClose = '\" />';\n break;\n case 'oasis':\n case 'wikia':\n skinConfig.textCont = '#WikiaArticle';\n skinConfig.pageControls = ($('#WikiaUserPagesHeader').length ? '.UserProfileActionButton' : '#WikiaPageHeader') + ' > .wikia-menu-button > ul';\n skinConfig.controlsMarkup = '<li id=\"control_archive\"><a id=\"ca-archive\" rel=\"nofollow\">' + msg('buttonArchiveTool') + '</a></li>';\n skinConfig.buttonOpenPri = '<a class=\"wikia-button\">';\n skinConfig.buttonOpenSec = '<a class=\"wikia-button secondary\">';\n skinConfig.buttonClose = '</a>';\n break;\n }\n \n $(function() {\n function api(q, fn) {\n q.format = 'json';\n return $.post(wgScriptPath + '/api.php', q, fn, \"json\");\n }\n function token(page, fn) {\n api({\n action: 'query',\n query: 'prop',\n prop: 'info',\n titles: page,\n intoken: 'edit'\n }, function(q) {\n for ( var k in q.query.pages )\n return fn(q.query.pages[k]);\n });\n }\n \n function startArchiving() {\n var c = config.archiveListTemplate.substr(0,1);\n var archiveListRegex = '['+c.toUpperCase()+c.toLowerCase()+']'+config.archiveListTemplate.substr(1);\n var bc = $(skinConfig.textCont).addClass('va-archiving').empty();\n \n $('<img class=\"ajax\" alt=\"Loading...\" />')\n .attr({src: stylepath+'/common/progress-wheel.gif'}).appendTo(bc);\n api({\n action: 'query',\n prop: 'revisions',\n titles: wgPageName,\n rvprop: 'timestamp|content'\n }, function(q) {\n bc.empty();\n var rev = q.query.pages[wgArticleId].revisions[0];\n var time = rev.timestamp;\n var talkToken, tokenTime;\n var content = rev['*'];\n token(wgPageName, function(p) {\n talkToken = p.edittoken;\n tokenTime = p.starttimestamp;\n });\n \n var lines = content.split('\\n');\n \n var table = $('<table style=\"margin: 10px 0;\"><thead><tr><th>' + msg('labelLines') + '</th><th title=\"' + msg('labelSections') + '\">{&hellip;}</th></tr></thead></table>').appendTo(bc);\n var ul = $('<tbody/>').appendTo(table);\n \n for ( var l = 0; l < lines.length; l++ ) {\n var line = lines[l];\n $('<tr/>').toggleClass('noarchive', (new RegExp('^\\\\{\\\\{'+archiveListRegex+'\\}\\}')).test(line))\n .attr({line:line})\n .append( $('<td class=line />').text(line).append('&nbsp;') ).appendTo(ul);\n }\n \n var sections = [];\n var sectionEnd = lines.length-1;\n for ( var l = lines.length-1; l >= 0; l-- ) {\n var line = lines[l];\n \n if ( /^=.+?=/.test(line) || l === 0 ) {\n var section = { start: l, end: sectionEnd };\n section.length = section.end - section.start + 1;\n sections.unshift(section);\n \n sectionEnd = l-1;\n }\n }\n \n var section;\n while( section = sections.shift() ) {\n var tr = ul.children().eq(section.start);\n $('<td class=section />').attr({rowspan: section.length}).appendTo(tr);\n }\n \n $('<div class=\"buttons\" style=\"text-align: right;\" />').append(\n $(skinConfig.buttonOpenSec + msg('buttonSelectAll') + skinConfig.buttonClose).click(function(e) {\n e.preventDefault();\n ul.children('tr').addClass('archive');\n }), ' ',\n $(skinConfig.buttonOpenSec + msg('buttonDeselectAll') + skinConfig.buttonClose).click(function(e) {\n e.preventDefault();\n ul.children('tr').removeClass('archive');\n }), ' ',\n $(skinConfig.buttonOpenPri + msg('buttonSaveArchive') + skinConfig.buttonClose).click(function(e) {\n archive();\n }), ' ',\n $(skinConfig.buttonOpenPri + msg('buttonAbort') + skinConfig.buttonClose).click(function(e) {\n bc.find('.ajax').remove();\n location = wgServer+wgScript+'?title='+encodeURI(wgPageName)+'&action=purge';\n })\n ).prependTo(bc).clone(true).appendTo(bc);\n \n var click = false;\n var add;\n table.mousedown(function(e) {\n e.preventDefault();\n var $li = $(e.target).closest('tr');\n if(!$li.length) return;\n var $section = $(e.target).closest('.section');\n if ( $section.length ) {\n var slist = $li.nextAll(':lt('+(parseInt($section.attr('rowspan'),10)-1)+')').andSelf();\n var sadd = slist.filter(function() { return !$(this).hasClass('archive') }).length;\n slist.toggleClass('archive', !!sadd);\n return;\n }\n click = true;\n add = !$li.hasClass('archive');\n \n $li.toggleClass('archive', !!add);\n });\n table.mouseover(function(e) {\n if (!click) return;\n var $li = $(e.target).closest('tr');\n if(!$li.length) return;\n \n $li.toggleClass('archive', !!add);\n });\n $('body').mouseup(function(e) {\n click = false;\n });\n \n function archive() {\n var talkLines = [];\n var archiveLines = [];\n ul.children().each(function() {\n var arr = $(this).hasClass('noarchive') || !$(this).hasClass('archive')\n ? talkLines : archiveLines;\n \n arr.push( $(this).attr('line') );\n });\n \n if ( !(new RegExp('^\\\\{\\\\{'+archiveListRegex+'\\}\\}')).test(talkLines[0]) )\n talkLines = ['{{'+config.archiveListTemplate+'}}', ''].concat(talkLines);\n archiveLines = ['{{'+config.archivePageTemplate+'}}', ''].concat(archiveLines);\n \n bc.empty();\n $('<img class=\"ajax\" alt=\"Loading...\" />')\n .attr({src: stylepath+'/common/progress-wheel.gif'}).appendTo(bc);\n \n runArchive(talkLines.join('\\n'), archiveLines.join('\\n'));\n }\n \n var archiveTitle;\n function runArchive(talkContent, archiveContent) {\n var archiveNo;\n function findArchives() {\n var m = $('<p>Finding archive id: </p>').appendTo(bc);\n api({\n action: 'query',\n list: 'allpages',\n apnamespace: wgNamespaceNumber,\n apprefix: wgTitle+'/'+config.archiveSubpage,\n aplimit: 1,\n apdir: 'descending'\n }, function(q) {\n archiveNo = q.query.allpages.length ?\n parseInt(q.query.allpages[0].title.substr(wgPageName.length+(\"/\"+config.archiveSubpage).length),10)+1 :\n 1;\n archiveTitle = wgPageName+'/'+config.archiveSubpage+' '+archiveNo;\n m.append('done... (using '+archiveNo+')');\n \n saveArchive();\n });\n }\n \n function saveArchive() {\n var m = $('<p>Finding token for '+archiveTitle+': </p>').appendTo(bc);\n token(archiveTitle, function(p) {\n m.append('done...');\n m = $('<p>Saving archive page: </p>').appendTo(bc);\n api({\n action: 'edit',\n title: archiveTitle,\n text: archiveContent,\n token: p.edittoken,\n summary: msg('summaryArchiveFrom') + \" [[\" + wgPageName + \"]].\",\n minor: true,\n createonly: true\n }, function(q) {\n if ( q.error && q.error.code === \"articleexists\" ) {\n m.append('failed...');\n bc.append(\"<p>The archive page we tried to create already exists.</p>\");\n return abort();\n }\n m.append('done...');\n \n saveTalk();\n });\n });\n }\n \n function saveTalk() {\n var m = $('<p>Finding token for '+wgPageName+': </p>').appendTo(bc);\n m.append('done...');\n m = $('<p>Updating talk page: </p>').appendTo(bc);\n api({\n action: 'edit',\n title: wgPageName,\n text: talkContent,\n token: talkToken,\n summary: msg('summaryArchiveTo') + \" [[\" + archiveTitle + \"]].\",\n minor: true,\n basetimestamp: time,\n starttimestamp: tokenTime\n }, function(q) {\n if ( q.edit.result === \"Success\" ) {\n m.append('done...');\n bc.find('.ajax').remove();\n location = wgServer+wgScript+'?title='+encodeURI(wgPageName)+'&action=purge';\n } else {\n m.append('failed...');\n bc.append(\"<p>Failed to update talkpage, you may wish to have the archive subpage we just created deleted.</p>\");\n return abort();\n }\n });\n }\n \n function abort() {\n bc.find('.ajax').remove();\n bc.append(\"<p>Aborting...</p>\");\n \n $(\"<p>You may want to </p>\")\n .append( $('<a>refresh</a>').attr({href: wgServer+wgArticlePath.replace('$1', encodeURI(wgPageName))}) )\n .append(' and try again.')\n .appendTo(bc);\n }\n \n // start\n findArchives();\n }\n });\n }\n \n $(skinConfig.controlsMarkup)\n .click(startArchiving)\n .appendTo(skinConfig.pageControls);\n });\n }\n}", "function archivePartial(archive, options, filterAttr) {\n function url(link, text) {\n return '<a href=\"/' + link + '\" >' + (text || link) + '</a>';\n }\n if (!options) return null;\n var basePath = settings.pages.archive.path || 'archive';\n var partial = '<ul class=\"css-treeview\" id=\"archive-partial\">\\n' +\n Object.keys(archive)\n .map(function(y) {\n return ' <li>' + url(Path.join(basePath, y), y) + '\\n' + ' <ul>\\n' +\n Object.keys(archive[y]).map(function(m) {\n return ' <li>' + url(Path.join(basePath, y + '/' + monthByName[m]),\n monthByName[m]) + '\\n' + ' <ul>\\n' +\n archive[y][m]\n .filter(function(p) {\n return !filterAttr || p[filterAttr];\n })\n .map(function(p) {\n var outPath = p.published ?\n settings.pages.post.path : settings.pages.unpublished.path;\n var path = Path.join(outPath || 'post',\n p.slug + settings.pages.post.ext);\n return ' <li>' + url(path, p.title) + '</li>';\n }).join('\\n') +\n '\\n </ul>\\n </li>';\n }).join('\\n') +\n '\\n </ul>\\n </li>';\n }).join('\\n') +\n '\\n</ul>';\n\n if (options.save) {\n fs.outputFileSync(Path.join(settings.paths.www,\n settings.paths.widgets, 'archive.html'), partial);\n }\n return partial;\n}", "function getArchiveList(apiurl) {\r\n\treturn $.ajax({\r\n\t\turl: apiurl,\r\n\t\theaders: getAuthHeader(),\r\n\t\tdataType:DEFAULT_DATATYPE\r\n\t}).always(function(){\r\n\r\n\t\t//Remove old list of arcchives, clear the form data hide the content information(no selected)\r\n\t\t$(\"#main-content\").hide();\r\n\t\t$(\"#form-content\").empty().hide();\r\n\r\n\t}).done(function (data, textStatus, jqXHR){\r\n\t\tif (DEBUG) {\r\n\t\t\tconsole.log (\"RECEIVED RESPONSE: data:\",data,\"; textStatus:\",textStatus)\r\n\t\t}\r\n\t\t//Extract the archives\r\n \tarchives = data.collection.items;\r\n\t\tfor (var i=0; i < archives.length; i++){\r\n\t\t\tvar archive = archives[i];\r\n\t\t\tvar archive_data = archive.data;\r\n\r\n\t\t\tfor (var j=0; j<archive_data.length;j++){\r\n\t\t\t\tif (archive_data[j].name==\"archiveId\"){\r\n\t\t\t\t\tarchive_id = archive_data[j].value;\r\n\t\t\t\t}\r\n\t\t\t\tif (archive_data[j].name==\"name\"){\r\n\t\t\t\t\tarchive_name = archive_data[j].value;\r\n\t\t\t\t}\r\n\t\t\t\tif (archive_data[j].name==\"organisationName\"){\r\n\t\t\t\t\tarchive_organsation = archive_data[j].value;\r\n\t\t\t\t}\r\n\r\n\t\t\t}\r\n\t\t\t// Move extracted data to archive list\r\n\t\t\tappendArchiveToList(archive.href, archive_id, archive_name, archive_organsation);\r\n\t\t}\r\n\r\n\t\t// Show New archive-button\r\n\t\t$(\"#list-body\").append(makeButton(\"New archive\", apiurl, handleAddArchive));\r\n\r\n var edit_url = data.collection.href;\r\n var template = data.collection.template;\r\n\r\n // Show form for editing archive\r\n $form = createFormFromTemplate(edit_url, \"archive-form\", \"Save\", handleSaveNewArchive, template)\r\n\r\n // Add the form to DOM\r\n $(\"#form-content\").append($form);\r\n $(\"#form-content\").append(makeButton(\"Cancel\", apiurl, returnToPreviousView));\r\n displayMessage();\r\n\r\n\t}).fail(function (jqXHR, textStatus, errorThrown){\r\n\t\tif (DEBUG) {\r\n\t\t\tconsole.log (\"RECEIVED ERROR: textStatus:\",textStatus, \";error:\",errorThrown)\r\n\t\t}\r\n\t\t//Inform user about the error using an alert message.\r\n\t\talert (\"Could not fetch the list of archives. Please, try again\");\r\n\t});\r\n}", "function setupArchiveList() {\n $(\"#archived-plan-list-header\").show();\n $(\"#archived-plan-list-titles\").show();\n $(\"#archived-plan-list-wrapper\").slideDown();\n}", "onArchive(handler) {\n return this.onOperation(handler, 'object.archive');\n }", "_onUnarchiveClicked(ev) {\n ev.stopPropagation();\n ev.preventDefault();\n\n this.model.updateVisibility('unarchive');\n }", "function contentArchives(oLocation)\n{\n\tvar sContent = '';\n\tvar aLocPathname = oLocation.pathname.split(\"/\");\n\tvar sLocQuery = oLocation.search;\n\tvar sLocName = aLocPathname[aLocPathname.length-1];\n\tvar sQuery = sLocName + sLocQuery;\n\tsContent = \"<span class='archives'>\"+\n\t\t\t\t\"<a title='Archive sites' onclick='infoPopUpArchives(\\\"\"+sQuery+\"\\\")'>Archive sites</a>\"+\n\t\t\t\t\"</span>\";\n\treturn sContent;\n}", "archive() {\n Socket.send(\"integrations_archive\", {});\n\n window.events.emit(\"notification\", {\n title: \"Archiving ended matches...\",\n color: \"primary\"\n });\n\n route('/');\n }", "onClickArchiveAll() {\n this._onCallPatch(\n status => status === 'complete',\n { archive: true }\n );\n }", "dispalyArchivedItems() {\n this.clickBackIconMenuTable();\n this.clickMenuMoreOption();\n this.clickMenuArchivedItems();\n }", "printArchive() {\n $(\"#errandArchive\").empty();\n\n for (let errand of this.archivedErrands) {\n $(\"#errandArchive\").append(errand);\n }\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return the award list Return current award Return flag whether todays needs claiming. What the current day is.
function GetLoginAwards() { var DaysLoggedIn = 0; var currentRewardDay = 0; var isNewLogin = false; var profileInfo = server.GetUserAccountInfo({PlayFabId : currentPlayerId}); if(profileInfo.UserInfo.TitleInfo.LastLogin) { var lastLoginDate = profileInfo.UserInfo.TitleInfo.LastLogin; var arrayOfStrings = lastLoginDate.split('T'); var lastLogin = Date.parse(arrayOfStrings[0]); var userData = server.GetUserReadOnlyData( { PlayFabId: currentPlayerId, Keys: ["DailyLogins", "ClaimedRewardDay"] }); if (userData.Data["DailyLogins"]) { var DailyLogins = JSON.parse(userData.Data["DailyLogins"].Value); // How many rewards currently if (userData.Data["ClaimedRewardDay"]) { currentRewardDay = userData.Data["ClaimedRewardDay"].Value; } // Is todays login date in the array. // if not, that means its new if( DailyLogins.includes(lastLogin) == false) { isNewLogin = true; IncrementDailyChallengeRollover(currentPlayerId); // If the array has 28 entries, we need to start Fresh again. But not reset the array/write into it until we claim if( DailyLogins.length >=28) { DaysLoggedIn = 0; currentRewardDay = 0; } else { DaysLoggedIn = DailyLogins.length; } } else { DaysLoggedIn = DailyLogins.length; } } } var retData = {}; retData["DaysLoggedIn"] = DaysLoggedIn; retData["ClaimedRewardDay"] = currentRewardDay; retData["IsNewLogin"] = isNewLogin; var loginRewards = server.GetTitleData({Keys:["DailyLoginRewards"]}); if(loginRewards.Data["DailyLoginRewards"]) { // Get the award table retData["DailyLoginRewards"] = loginRewards.Data["DailyLoginRewards"]; } return retData; }
[ "function AwardCurrentAY(){\n\n\t$(\"#awardAlertDiv\").hide();\n\t\n\tif ($(\"#award_yes\").is(':checked')) {\n\t\t$(\"#add_award_div\").show();\n\t}\n\telse if ($(\"#award_no\").is(':checked')){\n\t\t$('#add_award_div').hide();\n\t\t$(\"#awardsTableAlertDiv\").hide();\n\t}\n\tsetAwardsTableTemplate();\n}", "function getDramasAiringToday() { \n var today = (new Date()).getDay();\n var dramaUrls = userInfo.dramaUrls;\n\n var airingTodayUrls = [];\n\n for (var url in dramaUrls) {\n var airDays = dramaUrls[url].airDays;\n\n for (var i = 0; i < airDays.length; i++) {\n if (airDays[i] == today) {\n airingTodayUrls.push(url);\n }\n }\n }\n\n return airingTodayUrls;\n}", "function getGoalInfo() {\n return restProfile.one(\"goals\", today).get();\n }", "function getBurnerdCalories() {\n return restWorkoutDiary.one(\"burnedcalories\", today).get();\n }", "function earnedAchievements() {\n return achievedList;\n\n}", "async getAllGiveaways(){\n // Get all the giveaway in the database\n return db.get(\"giveaways\");\n }", "async getAvailabilities() {\n const bkgs = await getBookings(this.props.token, this.props.userType, this.props.userName).then()\n var avs = []\n\n var future = false\n var currentTime = roundedCurrentTime(30)\n var formattedTime = formatTime(currentTime)\n var next = formatTime(nextSlot(currentTime, 30))\n var nextNext = formatTime(nextSlot(currentTime, 60))\n\n // Filter available timeslots from booked timeslots\n for (let i = 0; i < bkgs.length; i++) { \n if (bkgs[i][\"customer\"] === null) { \n\n // Only add slots in the future\n if (future)\n avs.push(bkgs[i]) \n if (parseDateString(bkgs[i][\"timeslot\"][\"date\"]) > parseDateString(formattedTime) || parseDateString(bkgs[i][\"timeslot\"][\"date\"]) > parseDateString(next) ||parseDateString(bkgs[i][\"timeslot\"][\"date\"]) > parseDateString(nextNext)) { \n future = true\n }\n\n }\n }\n this.setState({availabilites: avs})\n return avs\n }", "function getNextAthan() {\n let currTime = new Date();\n let athanTimes = getAthanTimes(currTime);\n\n let nextPrayer = null;\n let prayers = ['fajr', 'dhuhr', 'asr', 'maghrib', 'isha']\n\n for (let i=0; i<prayers.length; i++) {\n let prayer = prayers[i]\n let athanTime = timeToDate( athanTimes[prayer] );\n\n if (athanTime >= currTime) {\n nextPrayer = prayer;\n break;\n }\n }\n\n if (nextPrayer) {\n let nextAthanTime = timeToDate( athanTimes[nextPrayer] );\n\n debug(`Next prayer is ${nextPrayer} at ${nextAthanTime}.`);\n return {nextPrayer, nextAthanTime};\n }\n else {\n let nextPrayer = 'fajr';\n\n let tomorrow = addDays(currTime, 1);\n athanTimes = getAthanTimes(tomorrow);\n\n let nextAthanTime = timeToDate( athanTimes[nextPrayer] );\n nextAthanTime = addDays(nextAthanTime, 1); //Having to do this is non-intuitive. Improve your APIs.\n\n debug(`Next prayer is ${nextPrayer} at ${nextAthanTime}.`);\n return {nextPrayer, nextAthanTime};\n }\n}", "getGoalAchieved(membr,newAssessment){\n \n// need to iterate throgh the open goals, find goalcategory and goal\n// then compare with latest assessment\n logger.info('Check to see any goals have be accomplished',);\n let attained = false;\n const membrGoals = membr.goals;\n let goalCategory = \"\"\n let goalValue = 0.00;\n let d0 = new Date(newAssessment.date);\n let d1 = d0.valueOf(); \n logger.info('assessment date is ',d0);\n \n // d1 represents the number of seconds since a particular date, 1970\n // this allows for comparison of date objects\n \n // goals are held in a goals array, some will be open others closed.\n // need to iterate through them to find the status of gaols which are open or not achieved yet\n for (let i = 0; i < membrGoals.length; i++) {\n \n if(membrGoals[i].status === \"open\" || membrGoals[i].status === \"not achieved yet, but within timeframe\" ) {\n logger.info('goal status is ',membrGoals[i].status);\n goalCategory = membrGoals[i].goalcategory;\n goalValue = parseFloat(membrGoals[i].goal);\n // once we find a goal that is open or not achieved yet \n // we extract the goal category and the value of the goal\n // the new Assessment the we received has many properties, so we need to loop through each\n // to see if a match with the goal category\n for(let propt in newAssessment){\n\n if (propt === goalCategory) {\n logger.info('Assessment property match found',goalCategory);\n let d22 = new Date(membrGoals[i].Gdate);\n let d2 = d22.valueOf();\n // goal date, which is the target date, is converted to number to allow comparison with Assessment date \n \n if ((parseFloat(newAssessment[propt]) === goalValue) && (d1 <= d2)) {\n \n membrGoals[i].status = \"achieved within time frame\";\n logger.info('goal status ',membrGoals[i].status);\n membrGoals[i].achieveddate = newAssessment.date;\n attained = true;\n \n } else if ((parseFloat(newAssessment[propt]) === goalValue) && (d1 > d2)) {\n \n membrGoals[i].status = \"achieved outside time frame\";\n logger.info('goal status ',membrGoals[i].status);\n membrGoals[i].achieveddate = newAssessment.date;\n attained = true;\n \n }else if ((parseFloat(newAssessment[propt]) !== goalValue) && (d1 < d2)) {\n \n membrGoals[i].status = \"not achieved yet, but within timeframe\";\n logger.info('goal status not ach date ',d2);\n } else {\n logger.info('else d1',d1);\n logger.info('else d2',d2);\n membrGoals[i].status = \"missed target\";\n }\n\n } \n }\n \n }\n }\n return attained\n }", "async getEstatesCreatedToday() {\n let newEstatesList = [];\n let returnList = [];\n const response = await axios\n .get(API_URL + 'estate-list/', {\n headers: {\n Authorization: `JWT ${localStorage.getItem('token')}`,\n },\n })\n .then((response) =>\n response.data.map((item) => newEstatesList.push(item))\n );\n\n newEstatesList.forEach((element) => {\n if (element.date_created == formatDate()) {\n returnList.push(element);\n }\n });\n return returnList;\n }", "async getAllGiveaways() {\n // Get all giveaways from the database\n return await db.get('giveaways');\n }", "function currentRecord(date) {\n var daybefore = new Date(date);\n daybefore.setHours(0,0);\n return patient['json']['effective_time'] > daybefore / 1000;\n\n }", "upcomings() {\n return this.meetups.filter(meetup => new Date(meetup.happeningOn.toString()) > new Date());\n }", "function checkAllDueAlarm() {\n var currentDate = new Date();\n $scope.allAlarms.forEach(function (alarmObj) {\n if (new Date(alarmObj.time).getTime() < currentDate.getTime() && alarmObj.isDue) {\n var message = $filter('date')(alarmObj.time, 'dd-MM-yy HH:mm') + \" Due\";\n toaster.pop({\n type: 'info',\n title: 'Pending Alarm',\n body: message,\n timeout: 15000\n });\n\n }\n });\n }", "function currentRecord(date) {\n var daybefore = new Date(date);\n daybefore.setHours(0, 0);\n return (patient['json']['effective_time'] > daybefore / 1000);\n }", "function currentCECondition(){\r\n\tvar activeCond = false\r\n\tvar todayDate = new Date()\r\n\tparCondArray = getParcelConditions(\"Code Enforcement\",\"Applied\",\"Continuous Enforcement\",null)\r\n\r\n\tfor(cond in parCondArray){\r\n\t\tvar expireDate = new Date(String(parCondArray[cond].expireDate.getYear()),String(parCondArray[cond].expireDate.getMonth()-1),\r\n\t\t\t\t\t\t\tString(parCondArray[cond].expireDate.getDayOfMonth()))\r\n\t\tif(expireDate > todayDate){\r\n\t\t\tactiveCond = true\r\n\t\t}\r\n\t}\r\n\treturn activeCond\r\n}", "function getBeerEvents() {\n $scope.beerEvents = [];\n\n beeroundService.getBreweryEvent($rootScope.userSettings).then(result => {\n\n result.map(event => {\n if(event.start > $scope.today){\n $scope.beerEvents.push(event)\n }\n });\n });\n }", "function currentRecord(date) {\n var daybefore = new Date(date);\n daybefore.setHours(0,0);\n return patient['json']['effective_time'] > daybefore/1000;\n }", "function currentRecord(date) {\n var daybefore = new Date(date);\n daybefore.setHours(0, 0);\n return patient['json']['effective_time'] > daybefore / 1000;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This sample demonstrates how to Lists all of the outputs under the specified streaming job.
async function listAllOutputsInAStreamingJob() { const subscriptionId = "56b5e0a9-b645-407d-99b0-c64f86013e3d"; const resourceGroupName = "sjrg2157"; const jobName = "sj6458"; const credential = new DefaultAzureCredential(); const client = new StreamAnalyticsManagementClient(credential, subscriptionId); const resArray = new Array(); for await (let item of client.outputs.listByStreamingJob(resourceGroupName, jobName)) { resArray.push(item); } console.log(resArray); }
[ "getOutputs(jobId, callback) {\n this.getLogs(jobId, logs => {\n this.getResults(jobId, results => {\n callback(results, logs)\n })\n })\n }", "function getJobOutput(jobId) {\n var options = { method: 'GET',\n url: `${config.RESTAPIEndpoint}/Jobs('${jobId}')/OutputMediaAssets`,\n headers: header}\n return new Promise ((resolve, reject)=>{\n request(options, function (error, response, body) {\n if (response.statusCode == 200){\n body = JSON.parse(body)\n body['d'] ? resolve(body.d['results']) : resolve(body['results'])\n } else reject(body)\n });\n })\n}", "_buildLogStreams(jobs) {\n let logStreamNames = []\n if (jobs && jobs.length > 0) {\n logStreamNames = jobs.reduce((acc, job) => {\n if (job.attempts && job.attempts.length > 0) {\n job.attempts.forEach(attempt => {\n let streamObj = {\n // Prior to August 21st, 2017 default was job.jobId\n name:\n job.jobName +\n '/default/' +\n attempt.container.taskArn.split('/').pop(),\n environment: job.container.environment,\n exitCode: job.container.exitCode,\n }\n acc.push(streamObj)\n })\n }\n return acc\n }, [])\n }\n return logStreamNames\n }", "getLogsByJobId(jobId, callback) {\n c.crn.jobs.findOne({ _id: ObjectID(jobId) }, {}, (err, job) => {\n if (err) {\n callback(err)\n }\n let logStreamNames = job.analysis.logstreams || []\n let logStreams = logStreamNames.reduce((streams, ls) => {\n let stream = this.formatLegacyLogStream(\n ls,\n this.streamNameVersion(job),\n )\n streams[stream.name] = stream\n return streams\n }, {})\n mapValuesLimit(\n logStreams,\n 10,\n (params, logStreamName, cb) => {\n this.getLogs(\n logStreamName,\n [],\n null,\n false,\n this._includeJobParams(params, cb),\n )\n },\n (err, logs) => {\n callback(err, logs)\n },\n )\n })\n }", "static list() {\n\t\tHttp.getRequest(\"jobs\").then(response =>\n\t \tresponse.json().then(\n\t \t\t\tjson => {\n\t \t\t\t\tlet output = document.querySelector(\"#jobsListOutput\");\n\n\t \t\t\t\tjson.forEach(job => {\n\t \t\t\t\t\tlet table = document.createElement(\"table\");\n\t \t\t\t\t\tlet tbody = document.createElement(\"tbody\");\n\n\t \t\t\t\t\t// display id\n\t \t\t\t\t\ttbody.appendChild(JobService.createRow(\"ID:\", job._id));\n\n\t \t\t\t\t\t// display position\n\t \t\t\t\t\ttbody.appendChild(JobService.createRow(\"Position:\", job.position));\n\n\t \t\t\t\t\t// display description\n\t \t\t\t\t\ttbody.appendChild(JobService.createRow(\"Description:\", job.description));\n\n\t \t\t\t\t\t// display requirements\n\t \t\t\t\t\tjob.requirements.forEach(requirement => tbody.appendChild(JobService.createRow(\"Requirement:\", requirement)));\n\n\t \t\t\t\t\t// display table\n\t \t\t\t\t\ttable.appendChild(tbody);\n\t \t\t\t\t\toutput.appendChild(table);\n\t \t\t\t\t});\n\t \t\t\t}\n\t \t));\n }", "_buildLogStreams(jobs) {\n let logStreamNames;\n if(jobs && jobs.length > 0) {\n logStreamNames = jobs.reduce((acc, job) => {\n if (job.attempts && job.attempts.length > 0) {\n job.attempts.forEach((attempt)=> {\n let streamObj = {\n name: job.jobName + '/' + job.jobId + '/' + attempt.container.taskArn.split('/').pop(),\n environment: job.container.environment,\n exitCode: job.container.exitCode\n };\n acc.push(streamObj);\n });\n }\n return acc;\n }, []);\n }\n\n return logStreamNames;\n }", "createOutputList(jobtype){\n // let status = (jobtype === \"pdb2pqr\") ? this.state.pdb2pqr.status : this.state.apbs.status;\n let completion_status = this.state[jobtype].status;\n let outputList = null;\n \n // console.log(new Date(this.state[jobtype].startTime*1000))\n \n let displayed_job_state = '';\n let running_icon = null;\n if(completion_status !== null){\n displayed_job_state = completion_status.charAt(0).toUpperCase() + completion_status.substr(1)\n if(completion_status == 'running')\n running_icon = <LoadingOutlined />\n // else if(completion_status == 'complete')\n // message.success(jobtype.toUpperCase()+' job completed')\n }\n\n let start_time = this.state[jobtype].startTime\n let end_time = this.state[jobtype].endTime\n start_time = (this.state[jobtype].startTime !== null) ? new Date(start_time*1000).toLocaleString() : null\n end_time = (this.state[jobtype].endTime !== null) ? new Date(end_time*1000).toLocaleString() : null\n\n outputList = <div>\n <h2 style={{ margin: '10px 0' }}>{jobtype.toUpperCase()}:</h2>\n\n <Row>\n <Col span={12}>\n <h3 style={{color: this.statusColor}}>\n {displayed_job_state} &nbsp;&nbsp; {running_icon}\n </h3>\n {/* Start time: {this.state[jobtype].startTime}<br/>\n End time: {this.state[jobtype].endTime}<br/> */}\n Start time: {start_time}<br/>\n End time: {end_time}<br/>\n <h3>{this.state.elapsedTime[jobtype]}</h3>\n {/* Elapsed time ({jobtype.toUpperCase()}): <strong>{this.state.elapsedTime[jobtype]}</strong> */}\n </Col>\n </Row>\n\n <List\n size=\"small\"\n bordered\n dataSource={this.state[jobtype].files}\n // dataSource={(jobtype === \"pdb2pqr\") ? this.state.pdb2pqr.files : this.state.apbs.files}\n renderItem={ item => (\n <List.Item actions={[<a href={window._env_.STORAGE_URL+'/'+item}><Button type=\"primary\" icon={<DownloadOutlined />}>Download</Button></a>]}>\n {/* {window._env_.API_URL+'/download/'+item} */}\n {item.split('/')[1]}\n </List.Item>\n )}\n />\n </div>\n return (\n <Col span={12}>\n {outputList}\n </Col>\n );\n }", "async function createAStreamingJobShellAStreamingJobWithNoInputsOutputsTransformationOrFunctions() {\n const subscriptionId = \"56b5e0a9-b645-407d-99b0-c64f86013e3d\";\n const resourceGroupName = \"sjrg6936\";\n const jobName = \"sj59\";\n const streamingJob = {\n compatibilityLevel: \"1.0\",\n dataLocale: \"en-US\",\n eventsLateArrivalMaxDelayInSeconds: 16,\n eventsOutOfOrderMaxDelayInSeconds: 5,\n eventsOutOfOrderPolicy: \"Drop\",\n functions: [],\n inputs: [],\n location: \"West US\",\n outputErrorPolicy: \"Drop\",\n outputs: [],\n sku: { name: \"Standard\" },\n tags: { key1: \"value1\", key3: \"value3\", randomKey: \"randomValue\" },\n };\n const credential = new DefaultAzureCredential();\n const client = new StreamAnalyticsManagementClient(credential, subscriptionId);\n const result = await client.streamingJobs.beginCreateOrReplaceAndWait(\n resourceGroupName,\n jobName,\n streamingJob\n );\n console.log(result);\n}", "function _jobs(jobs) {\n if(_.size(jobs)>0) {\n _jobsHeader();\n _.each(jobs, function(job) { \n console.log(sprintf(headerstr,job.id, job.next, Number(job.progress*100).toFixed(0), job.name, job.description));\n });\n } else {\n console.log('** no jobs **');\n }\n}", "function listStreams (lambdas) {\n lambdas.forEach(function (lambda) {\n cmdListStreams.run(lambda, function (err, streams) {\n if (err) return logError(err)\n\n if (lambdas.length >= 1) console.log(lambda + ':')\n\n for (let stream of streams) {\n console.log(stream)\n }\n\n if (lambdas.length >= 1) console.log('')\n })\n })\n}", "function listOutputs(event) {\nvar outputs=\"\";\nfor (var i = 0; i < event[\"outputs\"].length; i++) {\noutputs += event[\"outputs\"][i];\nif (i < event[\"outputs\"].length-1) {\noutputs += \", \";\n}\n}\nreturn outputs;\n}", "async function listAllJobExecutionsInAJobAgent() {\n const subscriptionId =\n process.env[\"SQL_SUBSCRIPTION_ID\"] || \"00000000-1111-2222-3333-444444444444\";\n const resourceGroupName = process.env[\"SQL_RESOURCE_GROUP\"] || \"group1\";\n const serverName = \"server1\";\n const jobAgentName = \"agent1\";\n const credential = new DefaultAzureCredential();\n const client = new SqlManagementClient(credential, subscriptionId);\n const resArray = new Array();\n for await (let item of client.jobExecutions.listByAgent(\n resourceGroupName,\n serverName,\n jobAgentName\n )) {\n resArray.push(item);\n }\n console.log(resArray);\n}", "function getTaskOutputContents(containerID, tInstanceId){\n return $http.get(KieServerService.getTaskManagementUrl(containerID) + '/' + tInstanceId + '/contents/output');\n }", "function listStream() {\n return through.obj(function (item, encoding, cb) {\n this.push(formatLine(item));\n cb();\n });\n}", "function output(toOutput)\n{\n for (var i in toOutput) \n {\n var metricToOutput = toOutput[i];\n\n if (metrics.hasOwnProperty(metricToOutput.variableName)) \n {\n if(metrics[metricToOutput.variableName].retrieveMetric === 1)\n {\n var output = '';\n \n output += metricToOutput.id + '|';\n output += metricToOutput.value + '|';\n \n console.log(output);\n }\n }\n }\n}", "async function listAllJobExecutionsInAJobAgentWithFiltering() {\n const subscriptionId =\n process.env[\"SQL_SUBSCRIPTION_ID\"] || \"00000000-1111-2222-3333-444444444444\";\n const resourceGroupName = process.env[\"SQL_RESOURCE_GROUP\"] || \"group1\";\n const serverName = \"server1\";\n const jobAgentName = \"agent1\";\n const createTimeMin = new Date(\"2017-03-21T19:00:00Z\");\n const createTimeMax = new Date(\"2017-03-21T19:05:00Z\");\n const endTimeMin = new Date(\"2017-03-21T19:20:00Z\");\n const endTimeMax = new Date(\"2017-03-21T19:25:00Z\");\n const isActive = false;\n const options = {\n createTimeMin,\n createTimeMax,\n endTimeMin,\n endTimeMax,\n isActive,\n };\n const credential = new DefaultAzureCredential();\n const client = new SqlManagementClient(credential, subscriptionId);\n const resArray = new Array();\n for await (let item of client.jobExecutions.listByAgent(\n resourceGroupName,\n serverName,\n jobAgentName,\n options\n )) {\n resArray.push(item);\n }\n console.log(resArray);\n}", "async function showJobList() {\n // reset all settings\n settings.reset();\n\n // get job data\n let data;\n try {\n data = await Fetcher.fetchJobs();\n } catch (error) {\n showFetchError(error);\n return;\n }\n\n $jobList.empty(); // clear before filling with new data\n\n for (const job of data) {\n // add list item for each job\n const html = `\n <a href=\"#\" class=\"list-group-item list-group-item-action job\" data-id=\"${job.beruf_id}\">\n ${job.beruf_name}\n </a>`;\n $jobList.append(html);\n }\n\n await view.showView($jobList);\n }", "list ({commit, state}, {flow, page, size}) {\n commit('setName', flow)\n\n return http.get('jobs/' + flow,\n (page) => {\n commit('list', page)\n },\n {\n page: page - 1,\n size\n }\n )\n }", "async output(outputId) {\r\n return this.fetchJson(\"get\", `outputs/${outputId}`);\r\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Display wait message on screen text = message to display force = display even if trace not enabled
function waitMsg (text) { WaitMsg.textContent = text; }
[ "function display_waiting_message() {\n display_overlay_message(MSG_WELCOME, 'waiting');\n}", "function showMonitoringControlWaitingScreen(text) {\n //Set a default text\n if (!text) {\n text = 'Please wait...';\n }\n\n //Show waiting screen\n $(MONITORING_CONTROL_CARD_SELECTOR).waitMe({\n effect: 'bounce',\n text: text,\n bg: 'rgba(255,255,255,0.85)'\n });\n }", "function showWaitingScreen(text) {\n //Set a default text\n if (!text) {\n text = 'Please wait...';\n }\n\n //Show waiting screen\n $(SELECTOR_INFO_CARD).waitMe({\n effect: 'bounce',\n text: text,\n bg: 'rgba(255,255,255,0.85)'\n });\n }", "function showDetailsWaitingScreen(text) {\n //Set a default text\n if (!text) {\n text = 'Please wait...';\n }\n\n //Show waiting screen\n $(DETAILS_CARD_SELECTOR).waitMe({\n effect: 'bounce',\n text: text,\n bg: 'rgba(255,255,255,0.85)'\n });\n }", "function showDeploymentWaitingScreen(text) {\r\n //Set a default text\r\n if (!text) {\r\n text = 'Please wait...';\r\n }\r\n\r\n //Show waiting screen\r\n $(DEPLOYMENT_CARD_SELECTOR).waitMe({\r\n effect: 'bounce',\r\n text: text,\r\n bg: 'rgba(255,255,255,0.85)'\r\n });\r\n }", "function ShowWaitScreen() {\n EnsureScript('sp.ui.dialog.js', typeof (SP.UI.ModalDialog), function () {\n waitDialog = SP.UI.ModalDialog.showWaitScreenWithNoClose('Processing...');\n });\n }", "function displayWaiting() {\r\n $('#display').html('<br><br><br><p>Waiting for ' + opponentName + '\\'s move</br>');\r\n }", "function drawWaitScreen () {\n\t\tcanvas.canvas.width = canvas.getWidth();\n\t\tcanvas.drawText(\n\t\t\t'Waiting for a player to join',\n\t\t\tcanvas.getWidth() / 2 - 50,\n\t\t\t200,\n\t\t\t'black'\n\t\t);\n\t}", "function please_wait()\n{\n\t\tstatus_msg(\"status-msg\",\"please wait...\")\n}", "function displayWait(message) {\n\n if (message == null) {\n // Display the default wait message\n message = $('div.processMessage span[id*=loadingMessage]').data('defaultmessage');\n }\n\n if (message != null) {\n // Set up the message to display\n $('div.processMessage span[id*=loadingMessage]').html(message);\n }\n\n if ($('div.waitContainer').length > 0) {\n // Dialogue should have been setup, just display it\n $('div.waitContainer').css({ display: 'block' });\n\n $('div.processMessage div.loadingMessageDiv').attr('aria-live', 'polite');\n }\n}", "function customStartWaiting(msg){\r\n startWaiting();\r\n var pleaseWaitCaption = document.getElementById('pleaseWaitMessage');\r\n if (pleaseWaitCaption)\r\n pleaseWaitCaption.innerHTML = msg;\r\n}", "function wait(message) {\n document.getElementById(\"edit-mode\").style.display = \"none\";\n document.getElementById(\"wait-mode\").style.display = \"block\";\n document.getElementById(\"list-mode\").style.display = \"none\";\n document.getElementById(\"wait-message\").firstChild.nodeValue = message;\n}", "function waitFunction() {\n setTimeout(showDescription, 700);\n }", "function trace (text, force = false) {\r\n if (options.traceEnabled || force) {\r\n\tconsole.log(text+\"\\r\\n\");\r\n }\r\n}", "function showPleaseWait(msg) {\n var msg = ((msg == \"\" || msg === undefined) ? \"<img src='../images/busy.gif' />Please Wait ...\" : msg);\n $.blockUI({\n message: msg,\n css: {\n 'background-position': 'center center',\n 'background-repeat': 'no-repeat',\n 'width': '200px',\n 'height': '20px',\n 'padding-top': '6px',\n 'border-radius': '10px',\n 'font-size': '0.8em'\n },\n overlayCSS: {\n 'backgroundColor': '#C0C0C0',\n 'opacity': '0.6'\n }\n });\n}", "function trace (text, force = false) {\n if (options.traceEnabled || force) {\n TracePlace.textContent += text + \"\\r\\n\";\n }\n}", "function delayedShowStatusText() {\n let text = makeStatusText();\n\n setTimeout((aText) => updateStatusText(aText), 0, text);\n\n return text;\n }", "function buildWaitText ( ) {\n var element = document.createElement('div');\n element.classList.add('waiting');\n element.textContent = 'waiting...';\n fMainWrapper.appendChild(element);\n\n }", "function printMessage(message) {\n var times = 0;\n screen.style.vivibility = \"hidden\";\n screen.innerHTML = message;\n var blink = setInterval(function () {\n times++;\n if (times === 4) {\n clearInterval(blink);\n }\n screen.style.visibility = (screen.style.visibility === \"hidden\" ? \"\" : \"hidden\");\n }, 200);\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a promise that will be resolved with the numeric fhir version 2 for DSTU2 3 for STU3 4 for R4 0 if the version is not known
getFhirRelease() { return this.getFhirVersion().then(v => { var _a; return (_a = settings_1.fhirVersions[v]) !== null && _a !== void 0 ? _a : 0; }); }
[ "getFhirVersion() {\n return (0, lib_1.fetchConformanceStatement)(this.state.serverUrl).then(metadata => metadata.fhirVersion);\n }", "getVersion() {\n return new Promise(resolve => {\n ffmpeg()\n .addOptions([`-version`])\n .output('./')\n .on('end', (result = '') => {\n result = result.replace(/copyright[\\s\\S]*/gi, '');\n let version = result.split(' ')[2];\n version = version.split('.').join('');\n resolve(parseInt(version));\n })\n .on('error', () => {\n let version = '4.2.2';\n version = version.split('.').join('');\n resolve(parseInt(version));\n })\n .run();\n });\n }", "getVarnishVersion(version) {\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tif (version) {\n\t\t\t\treturn resolve(version);\n\t\t\t}\n\n\t\t\t// Get version from varnishd\n\t\t\texec('varnishd -V', (error, stdout, stderr) => {\n\t\t\t\tlet match;\n\n\t\t\t\tif (error) {\n\t\t\t\t\treject(i18n.t('could_not_get_version'));\n\t\t\t\t}\n\n\t\t\t\t// Version data comes from stderr... Which is odd, but I'm sure\n\t\t\t\t// there are reasons.\n\t\t\t\tmatch = stderr.match(/varnish-(\\d+\\.\\d+\\.\\d+)\\s/);\n\n\t\t\t\tif (match !== null) {\n\t\t\t\t\t// Resolve to version match\n\t\t\t\t\tresolve(match[1]);\n\t\t\t\t} else {\n\t\t\t\t\treject(i18n.t('could_not_get_version'));\n\t\t\t\t}\n\t\t\t});\n\t\t});\n\t}", "getHardwareVersion () {\n debug$5('GetHardwareVersionn')\n\n return this.writeCommand(\n new Uint8Array([\n 0x0a // \"Version Command\" opcode\n ])\n )\n .then(this.read.bind(this))\n .then(this.assertPacket(0x0a, 20))\n .then(bytes => {\n // Decode little-endian fields, by using a DataView with the\n // same buffer *and* offset than the Uint8Array for the packet payload\n const dataView = new DataView(bytes.buffer, bytes.byteOffset)\n return {\n part: dataView.getInt32(0, true),\n variant: dataView.getInt32(4, true),\n memory: {\n romSize: dataView.getInt32(8, true),\n ramSize: dataView.getInt32(12, true),\n romPageSize: dataView.getInt32(16, true)\n }\n }\n })\n .then(hwVersion => {\n debug$5('HardwareVersion part: ', hwVersion.part.toString(16))\n debug$5('HardwareVersion variant: ', hwVersion.variant.toString(16))\n debug$5('HardwareVersion ROM: ', hwVersion.memory.romSize)\n debug$5('HardwareVersion RAM: ', hwVersion.memory.ramSize)\n debug$5('HardwareVersion ROM page size: ', hwVersion.memory.romPageSize)\n\n return hwVersion\n })\n }", "loadVersion(options){\n let that = this;\n return Promise.resolve().then(function(){\n let versions = that._versions = that._versions || {};\n let info = versions[options.versionId];\n return info;\n });\n }", "async function getCDAPVersion() {\n return new Promise((resolve, reject) => {\n var parser = new xml2js.Parser();\n fs.readFile(path.join(__dirname , '..', '..', 'pom.xml'), function(err, data) {\n if (err) {\n reject(err);\n }\n parser.parseString(data, function (err, result) {\n if (err) {\n reject(err);\n } \n const version = result.project.version[0];\n resolve(version);\n });\n });\n });\n}", "async getDatabaseVersion(database) {\n // Select the highest version number from the version table\n return database\n .executeSql(\"SELECT version FROM Version ORDER BY version DESC LIMIT 1;\")\n .then(([results]) => {\n if (results.rows && results.rows.length > 0) {\n const version = results.rows.item(0).version;\n return version;\n } else {\n return 0;\n }\n })\n .catch((error) => {\n console.log(`No version set. Returning 0. Details: ${error}`);\n return 0;\n });\n }", "getHardwareVersion() {\n debug('GetHardwareVersionn');\n\n return this.writeCommand(new Uint8Array([\n 0x0A, // \"Version Command\" opcode\n ]))\n .then(this.read.bind(this))\n .then(this.assertPacket(0x0A, 20))\n .then(bytes => {\n // Decode little-endian fields, by using a DataView with the\n // same buffer *and* offset than the Uint8Array for the packet payload\n const dataView = new DataView(bytes.buffer, bytes.byteOffset);\n return {\n part: dataView.getInt32(0, true),\n variant: dataView.getInt32(4, true),\n memory: {\n romSize: dataView.getInt32(8, true),\n ramSize: dataView.getInt32(12, true),\n romPageSize: dataView.getInt32(16, true),\n },\n };\n })\n .then(hwVersion => {\n debug('HardwareVersion part: ', hwVersion.part.toString(16));\n debug('HardwareVersion variant: ', hwVersion.variant.toString(16));\n debug('HardwareVersion ROM: ', hwVersion.memory.romSize);\n debug('HardwareVersion RAM: ', hwVersion.memory.ramSize);\n debug('HardwareVersion ROM page size: ', hwVersion.memory.romPageSize);\n\n return hwVersion;\n });\n }", "getServerVersion() {\n let rqst = this.newPublicRequest('GET', '/', null, '');\n return this._wrapWithPromise(rqst);\n }", "get fhirVersion () {\n\t\treturn this._fhirVersion;\n\t}", "async getGet5Version() {\n if (process.env.NODE_ENV === \"test\") {\n return \"unknown\";\n }\n\n let get5Status = await this.execute(\"get5_status\");\n get5Status = await this.fixIncompletePackets(get5Status);\n\n if (get5Status.includes(\"Unknown command\")) {\n return \"unknown\";\n }\n let get5JsonStatus = await JSON.parse(get5Status);\n return get5JsonStatus.plugin_version;\n }", "function getDBVersion()\n{\n var rs;\n db.transaction(\n function(tx) {\n // Create the version table if it doesn't already exist\n tx.executeSql('CREATE TABLE IF NOT EXISTS version(version dec(5,2) DEFAULT 0.0)');\n rs = tx.executeSql('SELECT DISTINCT version FROM version;');\n });\n // not records => fresh install\n if (rs.rows.length === 0 ) {\n console.log(\"no version record -> fresh install, return 0\");\n return 0;\n }\n // record but a string => pre\n // recreate version table with 2.2 as decimal\n console.log(\"found version: \" + rs.rows.item(0).version);\n if (rs.rows.item(0).version === \"2.2\") {\n console.log(\"found version: 2.2 as string -> recreate table as 2.2\");\n db.transaction(\n function(tx) {\n tx.executeSql('DROP TABLE IF EXISTS version');\n tx.executeSql('CREATE TABLE IF NOT EXISTS version(version dec(5,2) DEFAULT 0.0)');\n tx.executeSql('INSERT OR REPLACE INTO version values (?);', 2.2 ); \n });\n return 2.2;\n }\n // final model with version as decimal and incremental intalls\n return rs.rows.item(0).version;\n}", "function resolveVersion(version) {\n var _version = version;\n\n return availableVersions()\n .then(function(available) {\n // Resolve if tag\n if (available.tags[version]) version = available.tags[version];\n\n version = _.find(available.versions, function(v) {\n return semver.satisfies(v, version);\n });\n\n // Check version\n if (!version) throw \"Invalid version or tag '\"+_version+\"', see available using 'gitbook versions:available'\";\n return version;\n });\n}", "function getVersion() {\n return new Promise(resolve => {\n const defaultVersion = 'latest';\n\n matcher.getChromeDriverVersion()\n .then(result => {\n if (result.chromeDriverVersion) {\n resolve(result.chromeDriverVersion);\n } else {\n resolve(defaultVersion);\n }\n })\n .catch(() => resolve(defaultVersion));\n });\n}", "function e368_GetVersionString(devIndx)\n{\n var version = 0.0;\n if((e368info[devIndx]).isOld)\n {\n return 1.0; // Call old boards 1.0 since they have no version function\n } \n else {\n var read = new Array;\n e368_SendCommand( \"version\", read, devIndx );\n // Split the line of the reply which actually contains the version number (line 1) into chunks delimited by spaces:\n var versionLine = (read[1]).split(/\\s/g);\n // Make sure response is what we're looking for- 2nd word should contain \"version\"\n if((versionLine[1]).search(\"Version\") != -1)\n {\n // Version string is the 3rd chunk (index =2). \n var versionStr = (versionLine[2]);\n return versionStr;\n }\n else {\n Out.Printf(Out.PriNormal, \"Error getting Version. Line read:\\n%s\\n\",read[1]);\n }\n }\n if(e368verbose) Out.Printf(Out.PriNormal, \"Version of firmware on e368 at index %d is %f\",devIndx,version);\n return version;\n}", "_computeNewVersion() {\n const { version } = this.active.releaseCandidate;\n return semver.parse(`${version.major}.${version.minor}.${version.patch}`);\n }", "version () {\n var p = this.cli.exec(['--version'])\n\n return p.then(pro => {\n return pro.compact().toPromise(Promise).then(v => {\n var matches = v.toString().match(/Ledger (.*),/)\n if (matches) return matches[1]\n else throw new Error('Failed to match Ledger version')\n })\n })\n }", "_retrieveSubscriberPackageVersionId(dependency, branchFromFlagOrDef) {\n return BBPromise.resolve().then(() => this._validateDependencyValues(dependency).then(() => {\n if (dependency.subscriberPackageVersionId) {\n delete dependency.package;\n // if an 04t id is specified just use it.\n return dependency;\n }\n const versionNumber = dependency.versionNumber.split(pkgUtils.VERSION_NUMBER_SEP);\n const buildNumber = versionNumber[3];\n // use the dependency.branch if present otherwise use the branch of the version being created\n const branch = dependency.branch || dependency.branch === '' ? dependency.branch : branchFromFlagOrDef;\n const branchString = _.isNil(branch) || branch === '' ? 'null' : `'${branch}'`;\n // resolve a build number keyword to an actual number, if needed\n return this._resolveBuildNumber(versionNumber, dependency.packageId, branch).then((queryResult) => {\n const records = queryResult.records;\n if (!records || records.length === 0 || records[0].expr0 == null) {\n if (buildNumber === pkgUtils.RELEASED_BUILD_NUMBER_TOKEN) {\n throw new Error(`No released version was found in Dev Hub for package id ${dependency.packageId} and version number ${versionNumber.join(pkgUtils.VERSION_NUMBER_SEP)}`);\n }\n else {\n throw new Error(`No version number was found in Dev Hub for package id ${dependency.packageId} and branch ${branchString} and version number ${versionNumber.join(pkgUtils.VERSION_NUMBER_SEP)}`);\n }\n }\n // now that we have a full build number, query for the associated 04t.\n // because the build number may not be unique across versions, add in conditionals for\n // the branch or the RELEASED token (if used)\n const resolvedBuildNumber = records[0].expr0;\n const branchOrReleasedCondition = buildNumber === pkgUtils.RELEASED_BUILD_NUMBER_TOKEN\n ? 'AND IsReleased = true'\n : `AND Branch = ${branchString}`;\n const query = `SELECT SubscriberPackageVersionId FROM Package2Version WHERE Package2Id = '${dependency.packageId}' AND MajorVersion = ${versionNumber[0]} AND MinorVersion = ${versionNumber[1]} AND PatchVersion = ${versionNumber[2]} AND BuildNumber = ${resolvedBuildNumber} ${branchOrReleasedCondition}`;\n return this.force.toolingQuery(this.org, query).then((pkgVerQueryResult) => {\n const subRecords = pkgVerQueryResult.records;\n if (!subRecords || subRecords.length !== 1) {\n throw new Error(`No version number was found in Dev Hub for package id ${dependency.packageId} and branch ${branchString} and version number ${versionNumber.join(pkgUtils.VERSION_NUMBER_SEP)} that resolved to build number ${resolvedBuildNumber}`);\n }\n dependency.subscriberPackageVersionId = pkgVerQueryResult.records[0].SubscriberPackageVersionId;\n // warn user of the resolved build number when LATEST and RELEASED keywords are used\n if (Number.isNaN(parseInt(buildNumber))) {\n versionNumber[3] = resolvedBuildNumber;\n if (buildNumber === pkgUtils.LATEST_BUILD_NUMBER_TOKEN) {\n logger.log(messages.getMessage('buildNumberResolvedForLatest', [\n dependency.package,\n versionNumber.join(pkgUtils.VERSION_NUMBER_SEP),\n branchString,\n dependency.subscriberPackageVersionId,\n ], 'package_version_create'));\n }\n else if (buildNumber === pkgUtils.RELEASED_BUILD_NUMBER_TOKEN) {\n logger.log(messages.getMessage('buildNumberResolvedForReleased', [\n dependency.package,\n versionNumber.join(pkgUtils.VERSION_NUMBER_SEP),\n dependency.subscriberPackageVersionId,\n ], 'package_version_create'));\n }\n }\n delete dependency.packageId;\n delete dependency.package;\n delete dependency.versionNumber;\n delete dependency.branch;\n return dependency;\n });\n });\n }));\n }", "async getRpcVersion() {\n const options = {\n uri: 'https://pgorelease.nianticlabs.com/plfe/version',\n headers: {\n 'accept': '*/*',\n 'user-agent': 'pokemongo/0 CFNetwork/894 Darwin/17.4.0',\n 'accept-language': 'en-us',\n 'x-unity-version': '2017.1.2f1'\n },\n gzip: true,\n };\n const version = await request.get(options);\n return version.replace(/[^(\\d|\\.)+]/g, '');\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Market Data Viewer Demo Extract search params. "$location" requires html5 mode which we can't switch to quite yet. Doesn't handle multivalued keys.
function ekGetSearchParams() { var result = {}; var searchParams = window.location.href.split('?'); if (searchParams && searchParams.length > 1) { var vals = searchParams[1].split('&'); for (var i = 0; i < vals.length; i++) { var next = vals[i].split('='); var key = next[0]; var val = decodeURIComponent(next[1].replace(/\+/g,' ')); result[key] = val; } } return result; }
[ "function get_location_search() {\n return new URLSearchParams(location.search);\n}", "getQueryValues() {\n var search = this.window_obj.location.search;\n\n if (search.length <= 1) {\n return {};\n }\n\n search = this.window_obj.location.search.substr(1);\n return this.getRawValues(search, '&', true);\n }", "function parseSearchParameters(keys) {\n var parameters = {}, params;\n params = location.search.substr(1).split('&').sort();\n\n $.each(keys, function(i,k){\n var values = [];\n for (var i = 0; i < params.length; i++) {\n if (k == params[i].substr(0, k.length)) {\n values.push(params[i].split('=').pop());\n }\n }\n parameters[k] = values;\n });\n\n /**\n * Get value for k location search parameter.\n *\n * @param k\n */\n function getParams(k) {\n\n // returns all parameters.\n if (typeof k == 'undefined') {\n return JSON.parse(JSON.stringify(parameters));\n }\n\n return typeof parameters[k] != 'undefined' ? parameters[k].slice(0) : [];\n }\n\n return getParams;\n }", "searchParams() {\n let text = \"query=\";\n text += this.service ? (this.service + \" \") : \"\";\n text += this.city ? (this.city + \" \") : \"\";\n text += getDoctorNameWithoutTitle(this.name) + \"&hitsPerPage=4\";\n return text.replace(/ /g, \"%20\");\n }", "static getSearchParams() {\n // TODO(zhangtiff): Make this use page.js's queryParams object instead\n // of parsing URL params multuple times, once charts is integrated with the SPA.\n return new URLSearchParams(document.location.search.substring(1));\n }", "function getSearchData() {\n\t//object with name value pairs in the url string\n\tvar searchParams = {};\n\n\t//if there is a string to parse\n\tif (window.location.search !== '' && window.location.search.length > 1) {\n\t\t//throw out the ?\n\t\tvar searchString = window.location.search.substring(1);\n\n\t\t//split by & for params\n\t\tvar pairs = searchString.split('&');\n\n\t\t//for each name/value pair from the url\n\t\t$.each(pairs, function(i, pair) {\n\t\t\t//split into key/value\n\t\t\tvar pairSplit = pair.split('=');\n\n\t\t\t//add to searchParams\n\t\t\tsearchParams[pairSplit[0]] = pairSplit[1];\n\t\t});\n\t}\n\n\treturn searchParams;\n}", "function finderParamas(){\n\tconst url = new window.URL(\"https://worker.mturk.com/\");\n\t// url.searchParams.append(\"sort\", storage.hitFinder[\"filter-sort\"]);\n\t// url.searchParams.append(\"page_size\", storage.hitFinder[\"filter-page-size\"]);\n\t// url.searchParams.append(\"filters[masters]\", storage.hitFinder[\"filter-masters\"]);\n\t// url.searchParams.append(\"filters[qualified]\", storage.hitFinder[\"filter-qualified\"]);\n\t// url.searchParams.append(\"filters[min_reward]\", storage.hitFinder[\"filter-min-reward\"]);\n\t// url.searchParams.append(\"filters[search_term]\", storage.hitFinder[\"filter-search-term\"]);\n\turl.searchParams.append(\"format\", \"json\");\n\n\treturn url;\n}", "function getParams() {\n // Get the search params out of the URL, namely the search query\n var searchParamsArr = document.location.search.split('&');\n // Get the query and remove the 'q='\n var query = searchParamsArr[0].split('=').pop();\n searchApi(query);\n}", "function getUrlArgs() {\n\tvar qs = (location.search.length > 0 ? location.search.substring(1) : \"\")\n\tvar args = {};\n\tvar items = qs.split(\"&\");\n\tvar item = null;\n\tname = null;\n\tvalue = null;\n\tfor (var i = 0; i < items.length; i++) {\n\t\titem = items[i].split(\"=\");\n\t\tname = decodeURIComponent(item[0]);\n\t\tvalue = decodeURIComponent(item[1]);\n\t\targs[name] = value;\n\t}\n\treturn args;\n}", "function parseSearchUrl() {\n var valuePairs = {};\n window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function (x, key, value) {\n value = value.replace(\"+\", \" \");\n valuePairs[key] = value;\n });\n return valuePairs.search;\n}", "function getViewargs() {\n\t\tconsole.log(\"getViewargs(): search string is: \" + window.location.search);\n\t\tvar argstr = decodeURIComponent(window.location.search.substring(\"?args=\".length));\n\t\tvar args = JSON.parse(argstr);\n\n\t\treturn args;\n\t}", "get_search_query() {\n const urlParams = new URLSearchParams(window.location.search);\n return this.search_query = urlParams.get(\"q\");\n }", "function parseArgs() {\n var args = {};\n var query = document.location.search.substring(1);\n var pairs = query.split('&');\n for (var i = 0; i < pairs.length; i++) {\n pos = pairs[i].indexOf('=');\n if (pos == -1) continue;\n var argname = pairs[i].substring(0, pos);\n var value = pairs[i].substring(pos+1);\n args[argname] = value;\n }\n return args;\n }", "function useLocationQuery() {\n return new URLSearchParams(useLocation().search);\n}", "function parseSearch() {\n // Get search value and remove leading '?'\n var search = document.location.search ? document.location.search.substring(1) : '';\n var params = [];\n if (search) {\n search.split('&').forEach(function (pair) {\n var parts = pair.split('=');\n params.push(parts);\n });\n }\n return params;\n }", "function getKvpParams() {\n var params = {};\n window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi,\n function(m, key, value) {\n params[key] = value;\n });\n return params;\n}", "function getSearchParameters(urlStr, callback) {\n \n // Url parameters - search terms\n var parameterUrl = urlStr.substring(17);\n var d = new Date();\n var whenSearch = d.toISOString(); //date and time (when) of the search\n \n var searchStr = parameterUrl;\n var offset = '';\n if (parameterUrl.indexOf('?offset=') >= 0){\n var searchArr = parameterUrl.split('?'); // search parameter\n searchStr = searchArr[0]; // search term string\n var pageArr = searchArr[1].split('='); // offset parameter\n offset = pageArr[1]; //offset value\n }\n var url = \"https://www.googleapis.com/customsearch/v1?key=\"+process.env.API_KEY+\"&cx=\"+process.env.GCSE_ID+\"&q=\"+searchStr\n if (offset |= ''){\n url += \"&start=\"+offset;\n }\n if (searchStr != ''){\n callback('', url, whenSearch, searchStr);\n } else {\n callback('Search string empty', '', '', '');\n }\n}", "function getUtmParams() {\n let search;\n\n try {\n search = parseQS(getWindowLocation().search);\n } catch (e) {\n search = {};\n }\n\n return Object.keys(search).reduce((accum, param) => {\n if (param.match(/utm_/)) {\n accum[param.replace(/utm_/, '')] = search[param];\n }\n return accum;\n }, {});\n}", "static parseQueryString() {\n let returnValues = {};\n let queries = window.location.search.substring(1).split(\"&\");\n for (let query of queries) {\n let queryPair = query.split(\"=\", 2);\n let queryKey = decodeURIComponent(queryPair[0]);\n let queryValue = decodeURIComponent(queryPair.length === 2 ? queryPair[1] : \"\");\n returnValues[queryKey] = queryValue;\n }\n return returnValues;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
gets the score object from the given array of scores which matches the given site (using idx as a hint to its position in the array)
function getScoreForSite(scores, site, idx, suppressWarnings) { var score = (scores.length > idx) && scores[idx]; // <-- attempt to shortcut the full ID search if (!score || (score.site && score.site.id !== site.id)) { // try to find this score the hard way... (may be time consuming for our supported edge case of using many sites) var filteredScores = scores.filter(function (s) { return s.site.id === site.id; }); score = filteredScores.length && filteredScores[0]; // perform some logging etc. if (console && console.warn && !suppressWarnings) console.warn("Warning: score for site ID='" + site.id + (score ? "' missing from score line." : "' misaligned in score line ID='" + (score.scoreLine && score.scoreLine.id) + "'")); if (console && console.assert) console.assert(filteredScores.length <= 1, "Warning: score line holds duplicate scores for site ID='" + site.id + "'"); } return score; }
[ "function getScoreForTeam(scores) {\n for(var i = 0; i < scores.length; i++) {\n var score = scores[i];\n if(score.team.id === team.id) {\n return score.score;\n }\n }\n return 0;\n }", "function findLowestScore(array){\n let lowestScore = 100;\n console.log(\"testing function here:\");\n console.log(lowestScore);\n lowestScore = array.forEach(getLower, lowestScore);\n console.log(lowestScore);\n let ind = array.findIndex(isScore, lowestScore);\n console.log(ind);\n return array[ind];\n\n}", "function getMinScoreIndex(scores){\n var minScore = scores[0];\n var minScoreIndex = 0;\n\n for (var i = 1; i < scores.length; i++) {\n if(minScore > scores[i]){\n minScore = scores[i];\n minScoreIndex = i;\n }\n }\n return minScoreIndex;\n}", "function findMatch(fProfile, mProfile){\n var resultScoreArray = [];\n var fProfScore = fProfile.scores;\n var mProfScore = mProfile[0].scores;\n for (var i = 0; i<fProfile.length; i++){\n var fprofScore = fProfile[i].scores;\n var netScore = 0;\n //console.log (\"Friends Profile Scores [\" + i + \"] =\" + fprofScore);\n // Score calculation begins\n for (var j=0; j<10; j++){\n var diffScore = Math.abs(parseInt(fprofScore[j]) - parseInt(mProfScore[j]));\n netScore = netScore + diffScore;\n }\n resultScoreArray.push(netScore);\n //console.log(\"Result Array = \" + resultScoreArray);\n\n // Find the index of the lowest score, just so we can get the correct profile from the Friends Profile Array\n var min = resultScoreArray[0];\n var minIndex = 0;\n for (var k=1; k < resultScoreArray.length; k++){\n if (parseInt(resultScoreArray[k]) < parseInt(min)){\n minIndex = k;\n min = resultScoreArray[k];\n }\n }\n //console.log(\"Result Array = \" + resultScoreArray);\n //console.log(\"Position of the Lowest Score = \" + minIndex);\n }\n return minIndex;\n}", "function findBestMatched(score){\n for (i of friendData) {\n if(i.totalScore === score) {\n return [i.name, i.photo, i.totalScore]\n }\n }\n }", "function getScoreApertif( site , url, produkt){\n scorePos = site.search('rating-points') + 12;\n score = site[scorePos+3] + site[scorePos+4];\n if(checkValue(score[0])){\n insertScore(produkt , score , url , aperitifLogo )\n }\n else {\n noScoreFound();\n }\n\n}", "function findLowestScore (array) {\n let scoreArray = array.map(a => a.score);\n let lowScore = scoreArray[0];\n scoreArray.forEach(function(score){\n if (score <= lowScore){\n lowScore = score;\n }\n })\n let lowestScoreObject = array.find(element => element.score === lowScore);\n console.log(lowestScoreObject);\n}", "function minScoreIndex(array, elements) {\n // add this code body\n}", "function getScoreApertif( site , url){\n scorePos = site.search('rating-points') + 12;\n score = site[scorePos+3] + site[scorePos+4];\n if(checkValue(score[0])){\n insertScore('ap', score , url , 'https://static.gfx.no/images/main/aperitif.png')\n }\n else {\n noScoreFound();\n }\n\n}", "function createResults(scores) {\r\n // Set up an array to track which scores have been visited.\r\n var visited = new Array(scores.length);\r\n algorithm_1.ArrayExt.fill(visited, false);\r\n // Set up the search results array.\r\n var results = [];\r\n // Iterate over each score in the array.\r\n for (var i = 0, n = scores.length; i < n; ++i) {\r\n // Ignore a score which has already been processed.\r\n if (visited[i]) {\r\n continue;\r\n }\r\n // Extract the current item and indices.\r\n var _a = scores[i], item = _a.item, categoryIndices = _a.categoryIndices;\r\n // Extract the category for the current item.\r\n var category = item.category;\r\n // Add the header result for the category.\r\n results.push({ type: 'header', category: category, indices: categoryIndices });\r\n // Find the rest of the scores with the same category.\r\n for (var j = i; j < n; ++j) {\r\n // Ignore a score which has already been processed.\r\n if (visited[j]) {\r\n continue;\r\n }\r\n // Extract the data for the current score.\r\n var _b = scores[j], item_1 = _b.item, labelIndices = _b.labelIndices;\r\n // Ignore an item with a different category.\r\n if (item_1.category !== category) {\r\n continue;\r\n }\r\n // Create the item result for the score.\r\n results.push({ type: 'item', item: item_1, indices: labelIndices });\r\n // Mark the score as processed.\r\n visited[j] = true;\r\n }\r\n }\r\n // Return the final results.\r\n return results;\r\n }", "function getBestMatches(results) {\n if (results.length == 0) return results;\n var bestScore = results[0].score;\n var bestMatches = results.filter(function(i) { return i.score == bestScore; });\n return bestMatches;\n }", "function getScores(boards) {\n var scores = [];\n for (var i = 0; i < boards.length; i++) {\n scores.push(boards[i] ? boards[i].getScore() : -1);\n }\n return scores;\n}", "function createResults(scores) {\n // Set up an array to track which scores have been visited.\n var visited = new Array(scores.length);\n algorithm_1.ArrayExt.fill(visited, false);\n // Set up the search results array.\n var results = [];\n // Iterate over each score in the array.\n for (var i = 0, n = scores.length; i < n; ++i) {\n // Ignore a score which has already been processed.\n if (visited[i]) {\n continue;\n }\n // Extract the current item and indices.\n var _a = scores[i], item = _a.item, categoryIndices = _a.categoryIndices;\n // Extract the category for the current item.\n var category = item.category;\n // Add the header result for the category.\n results.push({ type: 'header', category: category, indices: categoryIndices });\n // Find the rest of the scores with the same category.\n for (var j = i; j < n; ++j) {\n // Ignore a score which has already been processed.\n if (visited[j]) {\n continue;\n }\n // Extract the data for the current score.\n var _b = scores[j], item_1 = _b.item, labelIndices = _b.labelIndices;\n // Ignore an item with a different category.\n if (item_1.category !== category) {\n continue;\n }\n // Create the item result for the score.\n results.push({ type: 'item', item: item_1, indices: labelIndices });\n // Mark the score as processed.\n visited[j] = true;\n }\n }\n // Return the final results.\n return results;\n }", "function minScoreIndex(array, elements) {\n index = 0\n lowScore = 100\n for (i = 0; i < array.length; i++) {\n if (array[i] < lowScore) {\n lowScore = array[i]\n index = i\n }\n }\n return index;\n}", "function best(n, matches, scoring) {\n return range(0, n-1).map(i => bestNth(i));\n\n // XXX: sorting and computing the scores each time is far from\n // optimal, but we are dealing with very small numbers here.\n function bestNth(n) {\n return function() {\n // Convert to array for sorting\n var scores_array = [];\n scores(matches, scoring)\n .forEach(([k,v]) => { scores_array.push([k,v]) });\n scores_array.sort(([k1,v1], [k2,v2]) => v2 - v1);\n\n var best = scores_array[n];\n if (best[1] === 0) return undefined;\n else return best[0];\n }\n }\n}", "function maxScoreIndex(array, elements) {\n // add this code body\n}", "function compareScore(arrScore) {\n var range = friendsData.length - 1; // avoid the last object which is just added\n\n var allComparisons =[];\n for (let i = 0; i < range; i++){\n let result = compareTwoScores(arrScore, friendsData[i].scores);\n allComparisons.push(result);\n }\n \n console.log(allComparisons);\n\n // now pick the friend with the best match meaning least difference in scores\n var bestMatchIndex = 0;\n for (let i = 0; i < allComparisons.length; i++) {\n if (allComparisons[bestMatchIndex] >= allComparisons[i]) {\n bestMatchIndex = i;\n }\n }\n console.log(bestMatchIndex);\n\n var bestMatch = friendsData[bestMatchIndex];\n console.log(bestMatch);\n return bestMatch;\n\n }", "function maxScoreIndex(array, elements) {\n // add this code body\n}", "function getBest(boards, scores) {\n var bestBoard = null;\n var bestScore = -100;\n for (var i = 0; i < boards.length; i++) {\n if (bestScore < scores[i]) {\n bestBoard = boards[i];\n bestScore = scores[i];\n }\n }\n return bestBoard;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Merender node ke trashlistcontainer
function renderTrashHtmlNode(node) { const trashListContainer = document.getElementById("trash-list-container") trashListContainer.appendChild(node) }
[ "addTrash(data){\n this.trashList.firstElementChild.append(data);\n }", "function addTrashIconToCustomMenuNodes(){\n \n var targetElements = $('#toolbar-menu-manager .node-id');\n\n for (var i = 0; i < targetElements.length; ++i) {\n\n var currentItem = targetElements[i];\n var currentItemParent = $(currentItem).parent();\n\n var nodeIdValue = $(currentItem).attr('data');\n\n if(nodeIdValue.indexOf('unique-node-') !== -1){\n $(currentItemParent).append('<i class=\"fa fa-trash-o delete-node-item delete-custom-node-item\" title=\"Remove menu item\" aria-hidden=\"true\"></i>');\n }\n } \n }", "function addnewnode() {\r\n $(\"#showAllFolder\").html('');\r\n var arrCollectionDocumentFolder = [];\r\n var $tree = $('#treeviewFolderMoveOption');\r\n var nodeselected = $tree.tree('getSelectedNode');\r\n if (nodeselected == false) {\r\n nodeselected = $tree.tree('getTree');\r\n var parent_node = $tree.tree('getNodeById', nodeselected.children[0].id);\r\n $tree.tree(\r\n 'appendNode',\r\n {\r\n name: 'New folder',\r\n id: nodeselected.children[0].id + '/New folder'\r\n },\r\n parent_node\r\n\r\n );\r\n var nodeexpand = $tree.tree('getNodeById', nodeselected.children[0].id);\r\n $tree.tree('openNode', nodeexpand);\r\n var nodeselect = $tree.tree('getNodeById', nodeselected.children[0].id + '/New folder');\r\n $tree.tree('selectNode', nodeselect);\r\n $(\"#hdnnewfolderurl\").val(nodeselected.children[0].id + '/New folder');\r\n\r\n //manoj\r\n var strReplace = contractItem.ContractDocumentsUrl.substring(0, contractItem.ContractDocumentsUrl.length - 1);\r\n var arrDocumentFolder = nodeselected.children[0].id.replace(strReplace, \";\").split(';').filter(function (vfld) {\r\n return vfld !== ''\r\n });\r\n if (arrDocumentFolder.length > 1) {\r\n arrCollectionDocumentFolder = (contractItem.ContractDocumentsUrl + arrDocumentFolder.pop()).split('/').filter(function (vflds) {\r\n return vflds !== ''\r\n });\r\n } else {\r\n arrCollectionDocumentFolder = (contractItem.ContractDocumentsUrl).split('/').filter(function (vflds) {\r\n return vflds !== ''\r\n });\r\n }\r\n //arrCollectionDocumentFolder = (contractItem.ContractDocumentsUrl + arrDocumentFolder).split('/').filter(function (vflds) { return vflds !== '' });\r\n arrCollectionDocumentFolder = arrCollectionDocumentFolder.slice(1);\r\n //manoj\r\n\r\n } else {\r\n var parent_node = $tree.tree('getNodeById', nodeselected.id);\r\n $tree.tree(\r\n 'appendNode',\r\n {\r\n name: 'New folder',\r\n id: nodeselected.id + '/New folder'\r\n },\r\n parent_node\r\n );\r\n var nodeexpand = $tree.tree('getNodeById', nodeselected.id);\r\n $tree.tree('openNode', nodeexpand);\r\n var nodeselect = $tree.tree('getNodeById', nodeselected.id + '/New folder');\r\n $tree.tree('selectNode', nodeselect);\r\n $(\"#hdnnewfolderurl\").val(nodeselected.id + '/New folder');\r\n\r\n //manoj\r\n var strReplace = contractItem.ContractDocumentsUrl.substring(0, contractItem.ContractDocumentsUrl.length - 1);\r\n var arrDocumentFolder = nodeselected.id.replace(strReplace, \";\").split(';').filter(function (vfld) {\r\n return vfld !== ''\r\n });\r\n if (arrDocumentFolder.length > 1) {\r\n arrCollectionDocumentFolder = (contractItem.ContractDocumentsUrl + arrDocumentFolder.pop()).split('/').filter(function (vflds) {\r\n return vflds !== ''\r\n });\r\n } else {\r\n arrCollectionDocumentFolder = (contractItem.ContractDocumentsUrl).split('/').filter(function (vflds) {\r\n return vflds !== ''\r\n });\r\n }\r\n arrCollectionDocumentFolder = arrCollectionDocumentFolder.slice(1);\r\n }\r\n $(\"#hdnnewfoldercreatedfrom\").val(\"jqtree\");\r\n $(\"#txtnewfoldervalue\").removeClass('error');\r\n $(\"#errormsg_txtnewfoldervalue\").remove();\r\n\r\n //manoj\r\n var fldratrical = \"\";\r\n if (arrCollectionDocumentFolder.length == 1) {\r\n fldratrical = '<img src=\"../Content/Images/icon/folder_open.png\" style=\"margin-right: 5px;\"><span>' + arrCollectionDocumentFolder.toString() + '</span>';\r\n } else {\r\n for (var fldr = 0; fldr < arrCollectionDocumentFolder.length; fldr++) {\r\n if (arrCollectionDocumentFolder.length - 1 == fldr) {\r\n fldratrical += '/<img src=\"../Content/Images/icon/folder_open.png\" style=\"margin-right: 5px;\"><span>' + arrCollectionDocumentFolder[fldr].toString() + '</a>';\r\n } else {\r\n fldratrical += '/<img src=\"../Content/Images/icon/folder.png\" style=\"margin-right: 5px;\"><span>' + arrCollectionDocumentFolder[fldr].toString() + '</a>';\r\n }\r\n }\r\n }\r\n if (fldratrical.charAt(0) == '/') {\r\n fldratrical = fldratrical.substr(1);\r\n }\r\n $(\"#showAllFolder\").html(fldratrical);\r\n $(\"#dvfoldercreation\").dialog(\"option\", \"title\", \"Create Folder\");\r\n $(\"#dvfoldercreation\").dialog(\"open\");\r\n}", "function Managenewnode(objvalue) {\r\n $(\"#showAllManageFolder\").html('');\r\n var arrCollectionDocumentFolder = [];\r\n var $tree = $('#treeviewManageFolderOption');\r\n var nodeselected = $tree.tree('getSelectedNode');\r\n if (nodeselected == false) {\r\n nodeselected = $tree.tree('getTree');\r\n var parent_node = $tree.tree('getNodeById', nodeselected.children[0].id);\r\n\r\n $tree.tree(\r\n 'appendNode',\r\n {\r\n name: 'New folder',\r\n id: nodeselected.children[0].id + '/New folder'\r\n },\r\n parent_node\r\n\r\n );\r\n var nodeexpand = $tree.tree('getNodeById', nodeselected.children[0].id);\r\n $tree.tree('openNode', nodeexpand);\r\n var nodeselect = $tree.tree('getNodeById', nodeselected.children[0].id + '/New folder');\r\n $tree.tree('selectNode', nodeselect);\r\n $(\"#hdnManagefolderurl\").val(nodeselected.children[0].id + '/New folder');\r\n\r\n //manoj\r\n var strReplace = contractItem.ContractDocumentsUrl.substring(0, contractItem.ContractDocumentsUrl.length - 1);\r\n var arrDocumentFolder = nodeselected.children[0].id.replace(strReplace, \";\").split(';').filter(function (vfld) {\r\n return vfld !== ''\r\n });\r\n if (arrDocumentFolder.length > 1) {\r\n arrCollectionDocumentFolder = (contractItem.ContractDocumentsUrl + arrDocumentFolder.pop()).split('/').filter(function (vflds) {\r\n return vflds !== ''\r\n });\r\n } else {\r\n arrCollectionDocumentFolder = (contractItem.ContractDocumentsUrl).split('/').filter(function (vflds) {\r\n return vflds !== ''\r\n });\r\n }\r\n arrCollectionDocumentFolder = arrCollectionDocumentFolder.slice(1);\r\n //manoj\r\n\r\n } else {\r\n var parent_node = $tree.tree('getNodeById', nodeselected.id);\r\n $tree.tree(\r\n 'appendNode',\r\n {\r\n name: 'New folder',\r\n id: nodeselected.id + '/New folder'\r\n },\r\n parent_node\r\n );\r\n var nodeexpand = $tree.tree('getNodeById', nodeselected.id);\r\n $tree.tree('openNode', nodeexpand);\r\n var nodeselect = $tree.tree('getNodeById', nodeselected.id + '/New folder');\r\n $tree.tree('selectNode', nodeselect);\r\n $(\"#hdnManagefolderurl\").val(nodeselected.id + '/New folder');\r\n\r\n //manoj\r\n var strReplace = contractItem.ContractDocumentsUrl.substring(0, contractItem.ContractDocumentsUrl.length - 1);\r\n var arrDocumentFolder = nodeselected.id.replace(strReplace, \";\").split(';').filter(function (vfld) {\r\n return vfld !== ''\r\n });\r\n if (arrDocumentFolder.length > 1) {\r\n arrCollectionDocumentFolder = (contractItem.ContractDocumentsUrl + arrDocumentFolder.pop()).split('/').filter(function (vflds) {\r\n return vflds !== ''\r\n });\r\n } else {\r\n arrCollectionDocumentFolder = (contractItem.ContractDocumentsUrl).split('/').filter(function (vflds) {\r\n return vflds !== ''\r\n });\r\n }\r\n arrCollectionDocumentFolder = arrCollectionDocumentFolder.slice(1);\r\n }\r\n\r\n //manoj\r\n var fldratrical = \"\";\r\n if (arrCollectionDocumentFolder.length == 1) {\r\n fldratrical = '<img src=\"../Content/Images/icon/folder_open.png\" style=\"margin-right: 5px;\"><span>' + arrCollectionDocumentFolder.toString() + '</span>';\r\n } else {\r\n for (var fldr = 0; fldr < arrCollectionDocumentFolder.length; fldr++) {\r\n if (arrCollectionDocumentFolder.length - 1 == fldr) {\r\n fldratrical += '/<img src=\"../Content/Images/icon/folder_open.png\" style=\"margin-right: 5px;\"><span>' + arrCollectionDocumentFolder[fldr].toString() + '</a>';\r\n } else {\r\n fldratrical += '/<img src=\"../Content/Images/icon/folder.png\" style=\"margin-right: 5px;\"><span>' + arrCollectionDocumentFolder[fldr].toString() + '</a>';\r\n }\r\n }\r\n }\r\n if (fldratrical.charAt(0) == '/') {\r\n fldratrical = fldratrical.substr(1);\r\n }\r\n $(\"#showAllManageFolder\").html(fldratrical);\r\n\r\n $(\"#txtManagefoldervalue\").removeClass('error');\r\n $(\"#errormsg_txtManagefoldervalue\").remove();\r\n $(\"#dvManagefoldercreation\").dialog(\"option\", \"title\", \"Create sub-folder\");\r\n $(\"#dvManagefoldercreation\").dialog(\"open\");\r\n}", "function itemizeTrash(){\nvar i,TR = [];\nfor (i = 0; i < activeStack.selectedtmp.length; i++) {\n TR.push({\"name\":activeStack.selectedtmp[i],\"list\":activeStack.activeList}); // fix this\n} \n\ntrash = getList(3);\ntrash = _.uniq(_.concat(TR,trash), _.isEqual);\nsetList(3, trash);\n}", "function completeitemfunc(){\n var linode=this.parentNode.parentNode;\n var parent=linode.parentNode;\n var id=parent.id;\n parent.removeChild(linode);\n if(id==='todo'){\n completedlist.insertBefore(linode,completedlist.childNodes[0]);\n\n }\n else{\n todolist.insertBefore(linode,todolist.childNodes[0]);\n } \n}", "function deleteParent(id) {\n tdListIndex = tdList.findIndex(x => x.id == id);\n tdList.splice(tdListIndex, 1);\n localStorage.setItem(\"todoList\", JSON.stringify(tdList));\n displayContent(); //displays the updated info\n}", "function rcube_treelist_widget(node, p)\n{\n // apply some defaults to p\n p = $.extend({\n id_prefix: '',\n autoexpand: 1000,\n selectable: false,\n scroll_delay: 500,\n scroll_step: 5,\n scroll_speed: 20,\n save_state: false,\n keyboard: true,\n tabexit: true,\n parent_focus: false,\n check_droptarget: function(node) { return !node.virtual; }\n }, p || {});\n\n var container = $(node),\n data = p.data || [],\n indexbyid = {},\n selection = null,\n drag_active = false,\n search_active = false,\n last_search = '',\n has_focus = false,\n box_coords = {},\n item_coords = [],\n autoexpand_timer,\n autoexpand_item,\n body_scroll_top = 0,\n list_scroll_top = 0,\n scroll_timer,\n searchfield,\n tree_state,\n ui_droppable,\n ui_draggable,\n draggable_opts,\n droppable_opts,\n list_id = (container.attr('id') || p.id_prefix || '0'),\n me = this;\n\n\n /////// export public members and methods\n\n this.container = container;\n this.expand = expand;\n this.collapse = collapse;\n this.select = select;\n this.render = render;\n this.reset = reset;\n this.drag_start = drag_start;\n this.drag_end = drag_end;\n this.intersects = intersects;\n this.droppable = droppable;\n this.draggable = draggable;\n this.update = update_node;\n this.insert = insert;\n this.remove = remove;\n this.get_item = get_item;\n this.get_node = get_node;\n this.get_selection = get_selection;\n this.is_search = is_search;\n this.reset_search = reset_search;\n\n /////// startup code (constructor)\n\n // abort if node not found\n if (!container.length)\n return;\n\n if (p.data)\n index_data({ children:data });\n // load data from DOM\n else\n update_data();\n\n container.attr('role', 'tree')\n .on('focusin', function(e) {\n // TODO: only accept focus on virtual nodes from keyboard events\n has_focus = true;\n })\n .on('focusout', function(e) {\n has_focus = false;\n })\n // register click handlers on list\n .on('click', 'div.treetoggle', function(e) {\n toggle(dom2id($(this).parent()));\n e.stopPropagation();\n })\n .on('click', 'li', function(e) {\n // do not select record on checkbox/input click\n if ($(e.target).is('input'))\n return true;\n\n var node = p.selectable ? indexbyid[dom2id($(this))] : null;\n if (node && !node.virtual) {\n select(node.id);\n e.stopPropagation();\n }\n })\n // mute clicks on virtual folder links (they need tabindex=\"0\" in order to be selectable by keyboard)\n .on('mousedown', 'a', function(e) {\n var link = $(e.target), node = indexbyid[dom2id(link.closest('li'))];\n if (node && node.virtual && !link.attr('href')) {\n e.preventDefault();\n e.stopPropagation();\n return false;\n }\n });\n\n // activate search function\n if (p.searchbox) {\n searchfield = $(p.searchbox).off('keyup.treelist').on('keyup.treelist', function(e) {\n var key = rcube_event.get_keycode(e),\n mod = rcube_event.get_modifier(e);\n\n switch (key) {\n case 9: // tab\n break;\n\n case 13: // enter\n search(this.value, true);\n return rcube_event.cancel(e);\n\n case 27: // escape\n reset_search();\n break;\n\n case 38: // arrow up\n case 37: // left\n case 39: // right\n case 40: // arrow down\n return; // ignore arrow keys\n\n default:\n search(this.value, false);\n break;\n }\n }).attr('autocomplete', 'off');\n\n // find the reset button for this search field\n searchfield.parent().find('a.reset').off('click.treelist').on('click.treelist', function(e) {\n reset_search();\n return false;\n })\n }\n\n $(document.body).on('keydown', keypress);\n\n // catch focus when clicking the list container area\n if (p.parent_focus) {\n container.parent(':not(body)').click(function(e) {\n if (!has_focus && selection) {\n $(get_item(selection)).find(':focusable').first().focus();\n }\n else if (!has_focus) {\n container.children('li:has(:focusable)').first().find(':focusable').first().focus();\n }\n });\n }\n\n /////// private methods\n\n /**\n * Collaps a the node with the given ID\n */\n function collapse(id, recursive, set)\n {\n var node;\n\n if (node = indexbyid[id]) {\n node.collapsed = typeof set == 'undefined' || set;\n update_dom(node);\n\n if (recursive && node.children) {\n for (var i=0; i < node.children.length; i++) {\n collapse(node.children[i].id, recursive, set);\n }\n }\n\n me.triggerEvent(node.collapsed ? 'collapse' : 'expand', node);\n save_state(id, node.collapsed);\n }\n }\n\n /**\n * Expand a the node with the given ID\n */\n function expand(id, recursive)\n {\n collapse(id, recursive, false);\n }\n\n /**\n * Toggle collapsed state of a list node\n */\n function toggle(id, recursive)\n {\n var node;\n if (node = indexbyid[id]) {\n collapse(id, recursive, !node.collapsed);\n }\n }\n\n /**\n * Select a tree node by it's ID\n */\n function select(id)\n {\n // allow subscribes to prevent selection change\n if (me.triggerEvent('beforeselect', indexbyid[id]) === false) {\n return;\n }\n\n if (selection) {\n id2dom(selection, true).removeClass('selected').removeAttr('aria-selected');\n if (search_active)\n id2dom(selection).removeClass('selected').removeAttr('aria-selected');\n selection = null;\n }\n\n if (!id)\n return;\n\n var li = id2dom(id, true);\n if (li.length) {\n li.addClass('selected').attr('aria-selected', 'true');\n selection = id;\n // TODO: expand all parent nodes if collapsed\n\n if (search_active)\n id2dom(id).addClass('selected').attr('aria-selected', 'true');\n\n scroll_to_node(li);\n }\n\n me.triggerEvent('select', indexbyid[id]);\n }\n\n /**\n * Getter for the currently selected node ID\n */\n function get_selection()\n {\n return selection;\n }\n\n /**\n * Return the DOM element of the list item with the given ID\n */\n function get_node(id)\n {\n return indexbyid[id];\n }\n\n /**\n * Return the DOM element of the list item with the given ID\n */\n function get_item(id, real)\n {\n return id2dom(id, real).get(0);\n }\n\n /**\n * Insert the given node\n */\n function insert(node, parent_id, sort)\n {\n var li, parent_li,\n parent_node = parent_id ? indexbyid[parent_id] : null\n search_ = search_active;\n\n // ignore, already exists\n if (indexbyid[node.id]) {\n return;\n }\n\n // apply saved state\n state = get_state(node.id, node.collapsed);\n if (state !== undefined) {\n node.collapsed = state;\n }\n\n // insert as child of an existing node\n if (parent_node) {\n node.level = parent_node.level + 1;\n if (!parent_node.children)\n parent_node.children = [];\n\n search_active = false;\n parent_node.children.push(node);\n parent_li = id2dom(parent_id);\n\n // re-render the entire subtree\n if (parent_node.children.length == 1) {\n render_node(parent_node, null, parent_li);\n li = id2dom(node.id);\n }\n else {\n // append new node to parent's child list\n li = render_node(node, parent_li.children('ul').first());\n }\n\n // list is in search mode\n if (search_) {\n search_active = search_;\n\n // add clone to current search results (top level)\n if (!li.is(':visible')) {\n $('<li>')\n .attr('id', li.attr('id') + '--xsR')\n .attr('class', li.attr('class'))\n .addClass('searchresult__')\n .append(li.children().first().clone(true, true))\n .appendTo(container);\n }\n }\n }\n // insert at top level\n else {\n node.level = 0;\n data.push(node);\n li = render_node(node, container);\n }\n\n indexbyid[node.id] = node;\n\n // set new reference to node.html after insert\n // will otherwise vanish in Firefox 3.6\n if (typeof node.html == 'object') {\n indexbyid[node.id].html = id2dom(node.id, true).children();\n }\n\n if (sort) {\n resort_node(li, typeof sort == 'string' ? '[class~=\"' + sort + '\"]' : '');\n }\n }\n\n /**\n * Update properties of an existing node\n */\n function update_node(id, updates, sort)\n {\n var li, parent_ul, parent_node, old_parent,\n node = indexbyid[id];\n\n if (node) {\n li = id2dom(id);\n parent_ul = li.parent();\n\n if (updates.id || updates.html || updates.children || updates.classes || updates.parent) {\n if (updates.parent && (parent_node = indexbyid[updates.parent])) {\n // remove reference from old parent's child list\n if (parent_ul.closest('li').length && (old_parent = indexbyid[dom2id(parent_ul.closest('li'))])) {\n old_parent.children = $.grep(old_parent.children, function(elem, i){ return elem.id != node.id; });\n }\n\n // append to new parent node\n parent_ul = id2dom(updates.parent).children('ul').first();\n if (!parent_node.children)\n parent_node.children = [];\n parent_node.children.push(node);\n }\n else if (updates.parent !== undefined) {\n parent_ul = container;\n }\n\n $.extend(node, updates);\n li = render_node(node, parent_ul, li);\n }\n\n if (node.id != id) {\n delete indexbyid[id];\n indexbyid[node.id] = node;\n }\n\n if (sort) {\n resort_node(li, typeof sort == 'string' ? '[class~=\"' + sort + '\"]' : '');\n }\n }\n }\n\n /**\n * Helper method to sort the list of the given item\n */\n function resort_node(li, filter)\n {\n var first, sibling,\n myid = li.get(0).id,\n sortname = li.children().first().text().toUpperCase();\n\n li.parent().children('li' + filter).each(function(i, elem) {\n if (i == 0)\n first = elem;\n if (elem.id == myid) {\n // skip\n }\n else if (elem.id != myid && sortname >= $(elem).children().first().text().toUpperCase()) {\n sibling = elem;\n }\n else {\n return false;\n }\n });\n\n if (sibling) {\n li.insertAfter(sibling);\n }\n else if (first && first.id != myid) {\n li.insertBefore(first);\n }\n\n // reload data from dom\n update_data();\n }\n\n /**\n * Remove the item with the given ID\n */\n function remove(id)\n {\n var node, li;\n\n if (node = indexbyid[id]) {\n li = id2dom(id, true);\n li.remove();\n\n node.deleted = true;\n delete indexbyid[id];\n\n if (search_active) {\n id2dom(id, false).remove();\n }\n\n return true;\n }\n\n return false;\n }\n\n /**\n * (Re-)read tree data from DOM\n */\n function update_data()\n {\n data = walk_list(container, 0);\n }\n\n /**\n * Apply the 'collapsed' status of the data node to the corresponding DOM element(s)\n */\n function update_dom(node)\n {\n var li = id2dom(node.id, true);\n li.attr('aria-expanded', node.collapsed ? 'false' : 'true');\n li.children('ul').first()[(node.collapsed ? 'hide' : 'show')]();\n li.children('div.treetoggle').removeClass('collapsed expanded').addClass(node.collapsed ? 'collapsed' : 'expanded');\n me.triggerEvent('toggle', node);\n }\n\n /**\n *\n */\n function reset(keep_content)\n {\n select('');\n\n data = [];\n indexbyid = {};\n drag_active = false;\n\n if (keep_content) {\n if (draggable_opts) {\n if (ui_draggable)\n draggable('destroy');\n draggable(draggable_opts);\n }\n\n if (droppable_opts) {\n if (ui_droppable)\n droppable('destroy');\n droppable(droppable_opts);\n }\n\n update_data();\n }\n else {\n container.html('');\n }\n\n reset_search();\n }\n\n /**\n * \n */\n function search(q, enter)\n {\n q = String(q).toLowerCase();\n\n if (!q.length)\n return reset_search();\n else if (q == last_search && !enter)\n return 0;\n\n var hits = [];\n var search_tree = function(items) {\n $.each(items, function(i, node) {\n var li, sli;\n if (!node.virtual && !node.deleted && String(node.text).toLowerCase().indexOf(q) >= 0 && hits.indexOf(node.id) < 0) {\n li = id2dom(node.id);\n\n // skip already filtered nodes\n if (li.data('filtered'))\n return;\n\n sli = $('<li>')\n .attr('id', li.attr('id') + '--xsR')\n .attr('class', li.attr('class'))\n .addClass('searchresult__')\n // append all elements like links and inputs, but not sub-trees\n .append(li.children(':not(div.treetoggle,ul)').clone(true, true))\n .appendTo(container);\n hits.push(node.id);\n }\n\n if (node.children && node.children.length) {\n search_tree(node.children);\n }\n });\n };\n\n // reset old search results\n if (search_active) {\n $(container).children('li.searchresult__').remove();\n search_active = false;\n }\n\n // hide all list items\n $(container).children('li').hide().removeClass('selected');\n\n // search recursively in tree (to keep sorting order)\n search_tree(data);\n search_active = true;\n\n me.triggerEvent('search', { query: q, last: last_search, count: hits.length, ids: hits, execute: enter||false });\n\n last_search = q;\n\n return hits.count;\n }\n\n /**\n * \n */\n function reset_search()\n {\n if (searchfield)\n searchfield.val('');\n\n $(container).children('li.searchresult__').remove();\n $(container).children('li').filter(function() { return !$(this).data('filtered'); }).show();\n\n search_active = false;\n\n me.triggerEvent('search', { query: false, last: last_search });\n last_search = '';\n\n if (selection)\n select(selection);\n }\n\n /**\n *\n */\n function is_search()\n {\n return search_active;\n }\n\n /**\n * Render the tree list from the internal data structure\n */\n function render()\n {\n if (me.triggerEvent('renderBefore', data) === false)\n return;\n\n // remove all child nodes\n container.html('');\n\n // render child nodes\n for (var i=0; i < data.length; i++) {\n data[i].level = 0;\n render_node(data[i], container);\n }\n\n me.triggerEvent('renderAfter', container);\n }\n\n /**\n * Render a specific node into the DOM list\n */\n function render_node(node, parent, replace)\n {\n if (node.deleted)\n return;\n\n var li = $('<li>')\n .attr('id', p.id_prefix + (p.id_encode ? p.id_encode(node.id) : node.id))\n .attr('role', 'treeitem')\n .addClass((node.classes || []).join(' '))\n .data('id', node.id);\n\n if (replace) {\n replace.replaceWith(li);\n if (parent)\n li.appendTo(parent);\n }\n else\n li.appendTo(parent);\n\n if (typeof node.html == 'string')\n li.html(node.html);\n else if (typeof node.html == 'object')\n li.append(node.html);\n\n if (!node.text)\n node.text = li.children().first().text();\n\n if (node.virtual)\n li.addClass('virtual');\n if (node.id == selection)\n li.addClass('selected');\n\n // add child list and toggle icon\n if (node.children && node.children.length) {\n li.attr('aria-expanded', node.collapsed ? 'false' : 'true');\n $('<div class=\"treetoggle '+(node.collapsed ? 'collapsed' : 'expanded') + '\">&nbsp;</div>').appendTo(li);\n var ul = $('<ul>').appendTo(li).attr('class', node.childlistclass).attr('role', 'group');\n if (node.collapsed)\n ul.hide();\n\n for (var i=0; i < node.children.length; i++) {\n node.children[i].level = node.level + 1;\n render_node(node.children[i], ul);\n }\n }\n\n return li;\n }\n\n /**\n * Recursively walk the DOM tree and build an internal data structure\n * representing the skeleton of this tree list.\n */\n function walk_list(ul, level)\n {\n var result = [];\n ul.children('li').each(function(i,e){\n var state, li = $(e), sublist = li.children('ul');\n var node = {\n id: dom2id(li),\n classes: String(li.attr('class')).split(' '),\n virtual: li.hasClass('virtual'),\n level: level,\n html: li.children().first().get(0).outerHTML,\n text: li.children().first().text(),\n children: walk_list(sublist, level+1)\n }\n\n if (sublist.length) {\n node.childlistclass = sublist.attr('class');\n }\n if (node.children.length) {\n if (node.collapsed === undefined)\n node.collapsed = sublist.css('display') == 'none';\n\n // apply saved state\n state = get_state(node.id, node.collapsed);\n if (state !== undefined) {\n node.collapsed = state;\n sublist[(state?'hide':'show')]();\n }\n\n if (!li.children('div.treetoggle').length)\n $('<div class=\"treetoggle '+(node.collapsed ? 'collapsed' : 'expanded') + '\">&nbsp;</div>').appendTo(li);\n\n li.attr('aria-expanded', node.collapsed ? 'false' : 'true');\n }\n if (li.hasClass('selected')) {\n li.attr('aria-selected', 'true');\n selection = node.id;\n }\n\n li.data('id', node.id);\n\n // declare list item as treeitem\n li.attr('role', 'treeitem').attr('aria-level', node.level+1);\n\n // allow virtual nodes to receive focus\n if (node.virtual) {\n li.children('a:first').attr('tabindex', '0');\n }\n\n result.push(node);\n indexbyid[node.id] = node;\n });\n\n ul.attr('role', level == 0 ? 'tree' : 'group');\n\n return result;\n }\n\n /**\n * Recursively walk the data tree and index nodes by their ID\n */\n function index_data(node)\n {\n if (node.id) {\n indexbyid[node.id] = node;\n }\n for (var c=0; node.children && c < node.children.length; c++) {\n index_data(node.children[c]);\n }\n }\n\n /**\n * Get the (stripped) node ID from the given DOM element\n */\n function dom2id(li)\n {\n var domid = String(li.attr('id')).replace(new RegExp('^' + (p.id_prefix) || '%'), '').replace(/--xsR$/, '');\n return p.id_decode ? p.id_decode(domid) : domid;\n }\n\n /**\n * Get the <li> element for the given node ID\n */\n function id2dom(id, real)\n {\n var domid = p.id_encode ? p.id_encode(id) : id,\n suffix = search_active && !real ? '--xsR' : '';\n\n return $('#' + p.id_prefix + domid + suffix, container);\n }\n\n /**\n * Scroll the parent container to make the given list item visible\n */\n function scroll_to_node(li)\n {\n var scroller = container.parent(),\n current_offset = scroller.scrollTop(),\n rel_offset = li.offset().top - scroller.offset().top;\n\n if (rel_offset < 0 || rel_offset + li.height() > scroller.height())\n scroller.scrollTop(rel_offset + current_offset);\n }\n\n /**\n * Save node collapse state to localStorage\n */\n function save_state(id, collapsed)\n {\n if (p.save_state && window.rcmail) {\n var key = 'treelist-' + list_id;\n if (!tree_state) {\n tree_state = rcmail.local_storage_get_item(key, {});\n }\n\n if (tree_state[id] != collapsed) {\n tree_state[id] = collapsed;\n rcmail.local_storage_set_item(key, tree_state);\n }\n }\n }\n\n /**\n * Read node collapse state from localStorage\n */\n function get_state(id)\n {\n if (p.save_state && window.rcmail) {\n if (!tree_state) {\n tree_state = rcmail.local_storage_get_item('treelist-' + list_id, {});\n }\n return tree_state[id];\n }\n\n return undefined;\n }\n\n /**\n * Handler for keyboard events on treelist\n */\n function keypress(e)\n {\n var target = e.target || {},\n keyCode = rcube_event.get_keycode(e);\n\n if (!has_focus || target.nodeName == 'INPUT' && keyCode != 38 && keyCode != 40 || target.nodeName == 'TEXTAREA' || target.nodeName == 'SELECT')\n return true;\n\n switch (keyCode) {\n case 38:\n case 40:\n case 63232: // 'up', in safari keypress\n case 63233: // 'down', in safari keypress\n var li = p.keyboard ? container.find(':focus').closest('li') : [];\n if (li.length) {\n focus_next(li, (mod = keyCode == 38 || keyCode == 63232 ? -1 : 1));\n }\n return rcube_event.cancel(e);\n\n case 37: // Left arrow key\n case 39: // Right arrow key\n var id, node, li = container.find(':focus').closest('li');\n if (li.length) {\n id = dom2id(li);\n node = indexbyid[id];\n if (node && node.children.length && node.collapsed != (keyCode == 37))\n toggle(id, rcube_event.get_modifier(e) == SHIFT_KEY); // toggle subtree\n }\n return false;\n\n case 9: // Tab\n if (p.keyboard && p.tabexit) {\n // jump to last/first item to move focus away from the treelist widget by tab\n var limit = rcube_event.get_modifier(e) == SHIFT_KEY ? 'first' : 'last';\n focus_noscroll(container.find('li[role=treeitem]:has(a)')[limit]().find('a:'+limit));\n }\n break;\n }\n\n return true;\n }\n\n function focus_next(li, dir, from_child)\n {\n var mod = dir < 0 ? 'prev' : 'next',\n next = li[mod](), limit, parent;\n\n if (dir > 0 && !from_child && li.children('ul[role=group]:visible').length) {\n li.children('ul').children('li:first').find('a:first').focus();\n }\n else if (dir < 0 && !from_child && next.children('ul[role=group]:visible').length) {\n next.children('ul').children('li:last').find('a:first').focus();\n }\n else if (next.length && next.find('a:first').focus().length) {\n // focused\n }\n else {\n parent = li.parent().closest('li[role=treeitem]');\n if (parent.length)\n if (dir < 0) {\n parent.find('a:first').focus();\n }\n else {\n focus_next(parent, dir, true);\n }\n }\n }\n\n /**\n * Focus the given element without scrolling the list container\n */\n function focus_noscroll(elem)\n {\n if (elem.length) {\n var frame = container.parent().get(0) || { scrollTop:0 },\n y = frame.scrollTop || frame.scrollY;\n elem.focus();\n frame.scrollTop = y;\n }\n }\n\n\n ///// drag & drop support\n\n /**\n * When dragging starts, compute absolute bounding boxes of the list and it's items\n * for faster comparisons while mouse is moving\n */\n function drag_start(force)\n {\n if (!force && drag_active)\n return;\n\n drag_active = true;\n\n var li, item, height,\n pos = container.offset();\n\n body_scroll_top = bw.ie ? 0 : window.pageYOffset;\n list_scroll_top = container.parent().scrollTop();\n pos.top += list_scroll_top;\n\n box_coords = {\n x1: pos.left,\n y1: pos.top,\n x2: pos.left + container.width(),\n y2: pos.top + container.height()\n };\n\n item_coords = [];\n for (var id in indexbyid) {\n li = id2dom(id);\n item = li.children().first().get(0);\n if (item && (height = item.offsetHeight)) {\n pos = $(item).offset();\n pos.top += list_scroll_top;\n item_coords[id] = {\n x1: pos.left,\n y1: pos.top,\n x2: pos.left + item.offsetWidth,\n y2: pos.top + height,\n on: id == autoexpand_item\n };\n }\n }\n\n // enable auto-scrolling of list container\n if (container.height() > container.parent().height()) {\n container.parent()\n .mousemove(function(e) {\n var scroll = 0,\n mouse = rcube_event.get_mouse_pos(e);\n mouse.y -= container.parent().offset().top;\n\n if (mouse.y < 25 && list_scroll_top > 0) {\n scroll = -1; // up\n }\n else if (mouse.y > container.parent().height() - 25) {\n scroll = 1; // down\n }\n\n if (drag_active && scroll != 0) {\n if (!scroll_timer)\n scroll_timer = window.setTimeout(function(){ drag_scroll(scroll); }, p.scroll_delay);\n }\n else if (scroll_timer) {\n window.clearTimeout(scroll_timer);\n scroll_timer = null;\n }\n })\n .mouseleave(function() {\n if (scroll_timer) {\n window.clearTimeout(scroll_timer);\n scroll_timer = null;\n }\n });\n }\n }\n\n /**\n * Signal that dragging has stopped\n */\n function drag_end()\n {\n if (!drag_active)\n return;\n\n drag_active = false;\n scroll_timer = null;\n\n if (autoexpand_timer) {\n clearTimeout(autoexpand_timer);\n autoexpand_timer = null;\n autoexpand_item = null;\n }\n\n $('li.droptarget', container).removeClass('droptarget');\n }\n\n /**\n * Scroll list container in the given direction\n */\n function drag_scroll(dir)\n {\n if (!drag_active)\n return;\n\n var old_top = list_scroll_top;\n container.parent().get(0).scrollTop += p.scroll_step * dir;\n list_scroll_top = container.parent().scrollTop();\n scroll_timer = null;\n\n if (list_scroll_top != old_top)\n scroll_timer = window.setTimeout(function(){ drag_scroll(dir); }, p.scroll_speed);\n }\n\n /**\n * Determine if the given mouse coords intersect the list and one of its items\n */\n function intersects(mouse, highlight)\n {\n // offsets to compensate for scrolling while dragging a message\n var boffset = bw.ie ? -document.documentElement.scrollTop : body_scroll_top,\n moffset = container.parent().scrollTop(),\n result = null;\n\n mouse.top = mouse.y + moffset - boffset;\n\n // no intersection with list bounding box\n if (mouse.x < box_coords.x1 || mouse.x >= box_coords.x2 || mouse.top < box_coords.y1 || mouse.top >= box_coords.y2) {\n // TODO: optimize performance for this operation\n if (highlight)\n $('li.droptarget', container).removeClass('droptarget');\n return result;\n }\n\n // check intersection with visible list items\n var id, pos, node;\n for (id in item_coords) {\n pos = item_coords[id];\n if (mouse.x >= pos.x1 && mouse.x < pos.x2 && mouse.top >= pos.y1 && mouse.top < pos.y2) {\n node = indexbyid[id];\n\n // if the folder is collapsed, expand it after the configured time\n if (node.children && node.children.length && node.collapsed && p.autoexpand && autoexpand_item != id) {\n if (autoexpand_timer)\n clearTimeout(autoexpand_timer);\n\n autoexpand_item = id;\n autoexpand_timer = setTimeout(function() {\n expand(autoexpand_item);\n drag_start(true); // re-calculate item coords\n autoexpand_item = null;\n if (ui_droppable)\n $.ui.ddmanager.prepareOffsets($.ui.ddmanager.current, null);\n }, p.autoexpand);\n }\n else if (autoexpand_timer && autoexpand_item != id) {\n clearTimeout(autoexpand_timer);\n autoexpand_item = null;\n autoexpand_timer = null;\n }\n\n // check if this item is accepted as drop target\n if (p.check_droptarget(node)) {\n if (highlight) {\n id2dom(id).addClass('droptarget');\n pos.on = true;\n }\n result = id;\n }\n else {\n result = null;\n }\n }\n else if (pos.on) {\n id2dom(id).removeClass('droptarget');\n pos.on = false;\n }\n }\n\n return result;\n }\n\n /**\n * Wrapper for jQuery.UI.droppable() activation on this widget\n *\n * @param object Options as passed to regular .droppable() function\n */\n function droppable(opts)\n {\n if (!opts) opts = {};\n\n if ($.type(opts) == 'string') {\n if (opts == 'destroy') {\n ui_droppable = null;\n }\n $('li:not(.virtual)', container).droppable(opts);\n return this;\n }\n\n droppable_opts = opts;\n\n var my_opts = $.extend({\n greedy: true,\n tolerance: 'pointer',\n hoverClass: 'droptarget',\n addClasses: false\n }, opts);\n\n my_opts.activate = function(e, ui) {\n drag_start();\n ui_droppable = ui;\n if (opts.activate)\n opts.activate(e, ui);\n };\n\n my_opts.deactivate = function(e, ui) {\n drag_end();\n ui_droppable = null;\n if (opts.deactivate)\n opts.deactivate(e, ui);\n };\n\n my_opts.over = function(e, ui) {\n intersects(rcube_event.get_mouse_pos(e), false);\n if (opts.over)\n opts.over(e, ui);\n };\n\n $('li:not(.virtual)', container).droppable(my_opts);\n\n return this;\n }\n\n /**\n * Wrapper for jQuery.UI.draggable() activation on this widget\n *\n * @param object Options as passed to regular .draggable() function\n */\n function draggable(opts)\n {\n if (!opts) opts = {};\n\n if ($.type(opts) == 'string') {\n if (opts == 'destroy') {\n ui_draggable = null;\n }\n $('li:not(.virtual)', container).draggable(opts);\n return this;\n }\n\n draggable_opts = opts;\n\n var my_opts = $.extend({\n appendTo: 'body',\n revert: 'invalid',\n iframeFix: true,\n addClasses: false,\n cursorAt: {left: -20, top: 5},\n create: function(e, ui) { ui_draggable = ui; },\n helper: function(e) {\n return $('<div>').attr('id', 'rcmdraglayer')\n .text($.trim($(e.target).first().text()));\n }\n }, opts);\n\n $('li:not(.virtual)', container).draggable(my_opts);\n\n return this;\n }\n}", "function addTrash(){\ndocument.querySelectorAll('.fa-trash-alt').forEach(item => {\n item.addEventListener('click', event => {\n item.offsetParent.parentNode.remove();\n })\n});\n}", "restructure(_tree) {\n let items = [];\n for (let item of _tree.getItems()) {\n let found = this.findItem(item.data);\n if (found) {\n found.setLabel(item.display);\n found.hasChildren = item.hasChildren;\n if (!found.hasChildren)\n found.expand(false);\n items.push(found);\n }\n else\n items.push(item);\n }\n this.innerHTML = \"\";\n this.addItems(items);\n }", "function TNodes_doRemoveBranch( nd, action ) {\n action = action || 'nothing';\n var sourcenode = {}\n , mynodesobj = {}\n , targetnode = {};\n \n mynodesobj = nd.Owner;// the TNodes-structure of \n targetnode = nd.Parent.Parent;\n /////////////////////////////////////////////////////////////\n // SOURCE: GET THE BRANCH-\"CONTENT\" FROM THE OPPOSITE NODE //\n /////////////////////////////////////////////////////////////\n switch ( nd.Spin ) {\n case 1: sourcenode = nd.Parent.DownNode;\n break;\n case -1: sourcenode = nd.Parent.UpNode;\n break;\n default: sourcenode = nd;\n }//END SWITCH\n \n if ( sourcenode.HasChild ) {\n \n \n \n // first swap the child's up and down to the target in the database\n\n // using json-obj as clipboard \n var jsonsource=mynodesobj.doCopyBranchToJson();\n //remove the split with delete, because the relink has dropped the children\n mynodesobj.doRemove(nd.Parent,'delete'); // owner is TNodes, parent is TSplit\n mynodesobj.doPasteBranchFromJson(jsonsource, targetnode,'relink');\n mynodesobj.doRemove(nd.Parent,'delete'); \n } else if ( sourcenode.ContainerList.Count > 0 ) {\n ///////////////////////////////\n // LOOP TROUGH CONTAINERLIST //\n ///////////////////////////////\n for ( var i in sourcenode.ContainerList.Item ) {\n var container = sourcenode.ContainerList.Item[ i ];\n if ( container !== null ) {\n var storedLabel = container.Label//Store label to override the 'copy of' wich is added after copy\n if ( container.Nature == 'Container' || container.Nature == 'Sticker' ) {\n var copy = targetnode.doContainerMove( container, undefined, true );\n targetnode.ContainerList.Item[ copy ].Label = storedLabel;// Make the copy and overwrite the labal of the copy\n }//END IF \n }//END IF\n }//END LOOP\n mynodesobj.doRemove( nd.Parent, 'delete' ); // owner is TNodes, parent is TSplit\n } else {\n mynodesobj.doRemove( nd.Parent, 'delete' ); // owner is TNodes, parent is TSplit \n }//END ELSE\n }", "function removeCluster() {\n if ($(\".dd-empty\").length > 1) {\n $(\".dd-empty\").parent()[1].remove();\n\n //activate nestable2 function\n $(\".dd\").nestable({\n\n onDragStart: function (l, e) {\n // get type of dragged element\n // let type = $(e).children(\".dd-handle\").attr(\"class\").split(\" \")[0];\n // console.log(type);\n //when start dragging, trigger addNoChildrenClass method\n addNoChildrenClass();\n },\n callback: function (l, e) {\n // l is the main container\n // e is the element that was moved\n //when finish dropping, trigger these methods to make \"dd-empty\" is always one\n removeCluster();\n },\n //enable auto scrolling method while dragging\n scroll: true\n });\n }\n}", "function removeToDo(element) {\n // element -> trash icon\n // element.parentNode -> li\n // element.parentNode.parentNode -> ul\n // code below: ul deletes li element\n element.parentNode.parentNode.removeChild(element.parentNode);\n // click trash -> remove li element\n LIST[element.id].trash = true;\n}", "createCatTree() {\n //tree wrapper: \n const wrapper = eHtml({ class: 'catTreeWrapper' });\n //tree links container\n const container = eHtml({ class: 'catTreeContainer', container: wrapper });\n //home link\n const home = eHtml({ class: 'body-nav', html: '<a href=' + this.links.home + '>Home</a>', container: container });\n //slash\n const slash = eHtml({ class: 'body-nav body-nav-slash', text: '/', container: container });\n //categories link\n const categories = eHtml({ class: 'body-nav', html: '<a href=' + this.links.categoriesLink + '>Categories</a>', container: container });\n //loop throw each parent: \n this.catTree.reverse().forEach((cat) => {\n //append slash\n container.append(slash.clone(true));\n //create cat container: \n const cContainer = eHtml({\n class: 'body-nav-cat body-nav',\n html: '<a href=' + this.catLink + cat._id + '>' + cat.title + '</a>',\n container: container\n });\n })\n return wrapper;\n }", "redo() {\n this.newOwner.addChild(this.treeItem, true)\n }", "function listarNodosyBorrar(nodo) {\n\n if (nodo.isDocument) {\n logger.log(\"nodo\" + nodo.getName());\n nodo.removeNode(nodo);\n }\n\n if (nodo.isContainer) {\n var nodes = nodo.children;\n for (var i = 0; i < nodes.length; i++) {\n logger.log(i + \"nodes\" + nodes[i].getName());\n if (nodes[i].isDocument) nodes[i].removeNode(nodes[i]);\n else if (nodes[i].isContainer) listarNodosyBorrar(nodes[i]);\n }\n }\n return true;\n}", "function aggiungi(oggetto){\r\n // SELEZIONO E CLONO IL TEMPLATE\r\n var cosaManca = $('.template li').clone();\r\n // AGGIUNGO LA LISTA DELLA SPESA AL TEMPLATE\r\n cosaManca.prepend(oggetto);\r\n // AGGIUNGO IL TEMPLATE CON LA LISTA DELLA SPESA ALLA LISTA PRESENTE NEL FILE HTML\r\n $('.todo-list').append(cosaManca);\r\n}", "function SyncItems(node) {\n //first remove the nodeClick event handler as this will fire when the tree is synced\n $tree.UmbracoTreeAPI().removeEventHandler(\"nodeClicked\", nodeClickHandler);\n\n //for some reason node syncing doesn't work until a node is selected, so lets just\n //select the root node, then continue to sync the tree.\n $tree.UmbracoTreeAPI().selectNode($tree.find(\"li:first\"));\n\n //the path will be available to nodes rendered when the page is rendered so we can do a full sync tree.\n //only the node id will be available for nodes that have been newly selected but this is ok since the\n //nodes are already loaded so the system will be able to sync them.\n var nodeId = node.attr(\"rel\");\n var path = node.attr(\"umb:nodedata\");\n if (!path) path = nodeId;\n\n $tree.UmbracoTreeAPI()\n .syncTree(path.toString());\n }", "function appendCluster() {\n if (!$(\".dd-empty\").length) {\n let cluster = $(\"#cluster\");\n clusterNumber++;\n cluster.append(\n '<div class=\"dd py-3\" id=cluster_' +\n clusterNumber.toString() +\n \">\" +\n \"</div>\"\n );\n\n //activate nestable2 function\n drop_zone(clusterNumber);\n $(\".dd\").nestable({\n onDragStart: function (l, e) {\n // get type of dragged element\n // let type = $(e).children(\".dd-handle\").attr(\"class\").split(\" \")[0];\n // console.log(type);\n //when start dragging, trigger addNoChildrenClass method\n addNoChildrenClass();\n },\n callback: function (l, e) {\n // l is the main container\n // e is the element that was moved\n //when finish dropping, trigger these methods to make \"dd-empty\" is always one\n appendCluster();\n removeCluster();\n },\n //enable auto scrolling method while dragging\n scroll: true\n });\n }\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
V = velocity O = neighborhoodSize Q1 = cognitionLearningRate Q2 = socialLearningRate
constructor(i, p, o, n, q1, q2, problem) { this._iterations = i; this._problem = problem; this._socialLearningRate = q2; this._cognitionLearningRate = q1; this._maxVelocity = 5;//problem.MAX_VALUE; this._minVelocity = -5;//problem.MIN_VALUE; this._neighborhood = o; this._individuals = []; this._particles = p; this._dimensions = n; this._bestGlobalFitness = 0; this._bestGlobalPosition = Array.from({ length: n }, () => Math.round(Math.random() * 11)); }
[ "function update(){\n r = 5 * (1 - (iterasi / t));\n h = 0.2 * (1 - (iterasi / t));\n //console.log('learning rate & radius updated');\n}", "function Perceptron(input_dimension, learning_rate) {\n this.weights = new Array(input_dimension); \n this.rate = learning_rate;\n\n for(var i = 0, len = this.weights.length; i < len; i++) {\n this.weights[i] = (Math.random()*.1)-.05; // start close to linear \n }\n}", "function newWih(x,y){\r\n let sum = 0;\r\n for(let z = 0; z < o_length; z++) {\r\n sum += delta(y,z) * (1 - hidden_layer[y]) * w_ho[y][z] * input_layer[x];\r\n }\r\n return sum * learning_rate;\r\n \r\n}", "train() {\n // it's possible that we'll never come across appropriate values for m and b\n for (let i = 0; i < this.options.iterations; i++) {\n this.gradientDescent()\n }\n }", "train(inputs, target){\n //inputs -> array: it holds n numbers corresponding the dataset dimensions (one single vector)\n //target -> int: id the vector's assigned category (for two categories usually: -1 and 1)\n //Please notice that training the perceptron is simply updating its weights accordingly to the error\n let guess = this.guess(inputs);\n //possible errors -> -1-(-1) = 0; -1-(1) = -2; 1-(-1) = 2; 1-(1) = 0 \n let error = target - guess;\n //Tune all the weights Gradient Descent style\n for (let i = 0; i < this.weights.length; i++){\n //if error = 0, weight doesn't get updated\n //the weights and the respective dimension is linked by the indices in both arrays\n this.weights[i] += error*inputs[i]*this.lr;\n }\n }", "_optimize(){\n this.ddpg.noise.desiredActionStddev = Math.max(0.1, this.config.noiseDecay * this.ddpg.noise.desiredActionStddev);\n let lossValuesCritic = [];\n let lossValuesActor = [];\n console.time(\"Training\");\n for (let t=0; t < this.config.nbTrainSteps; t++){\n let {lossC, lossA} = this.ddpg.optimizeCriticActor();\n lossValuesCritic.push(lossC);\n lossValuesActor.push(lossA);\n }\n console.timeEnd(\"Training\");\n console.log(\"desiredActionStddev:\", this.ddpg.noise.desiredActionStddev);\n setMetric(\"CriticLoss\", mean(lossValuesCritic));\n setMetric(\"ActorLoss\", mean(lossValuesActor));\n }", "train(inputs, target){\n let guess = this.feedforward(inputs);\n let error = target - guess;\n \n for(let i = 0 ; i < this.weights.length; i++){\n this.weights[i] += error * inputs[i] * this.learning_rate;\n }\n \n }", "updateParams() {\r\n if (this.agent instanceof MonteCarloAgent || this.agent instanceof QLearningAgent) {\r\n // Pull in any new values for the epsilon and discount hyperparameters.\r\n let epsilonField = document.getElementById('epsilonGreedy');\r\n let epsilon = epsilonField.value;\r\n if (!isNaN(epsilon) && Number(epsilon) >= 0.0 && Number(epsilon) <= 1.0) {\r\n this.agent.epsilon = Number(epsilon);\r\n } else {\r\n epsilon = this.agent.epsilon;\r\n epsilonField.value = epsilon;\r\n }\r\n\r\n let discountField = document.getElementById('discountFactor');\r\n let discount = discountField.value;\r\n if (!isNaN(discount) && Number(discount) >= 0.0 && Number(discount) <= 1.0) {\r\n this.agent.discount = Number(discount);\r\n } else {\r\n discount = this.agent.discount;\r\n discountField.value = discount;\r\n }\r\n\r\n if (this.agent instanceof QLearningAgent) {\r\n // Pull and store the learning rate (alpha).\r\n let alphaField = document.getElementById('alphaLearn');\r\n let alpha = alphaField.value;\r\n if (!isNaN(alpha) && Number(alpha) >= 0.0 && Number(alpha) <= 1.0) {\r\n this.agent.alpha = Number(alpha);\r\n } else {\r\n alpha = this.agent.alpha;\r\n alphaField.value = alpha;\r\n }\r\n }\r\n }\r\n }", "_optimize() {\n this.ddpg.noise.desiredActionStddev = Math.max(this.config.minActionStddev, this.config.noiseDecay * this.ddpg.noise.desiredActionStddev);\n let lossValuesCritic = [];\n let lossValuesActor = [];\n console.time(\"Training\");\n for (let t = 0; t < this.config.nbTrainSteps; t++) {\n let {\n lossC,\n lossA\n } = this.ddpg.optimizeCriticActor();\n lossValuesCritic.push(lossC);\n lossValuesActor.push(lossA);\n }\n console.timeEnd(\"Training\");\n console.log(\"desiredActionStddev:\", this.ddpg.noise.desiredActionStddev);\n setMetric(\"CriticLoss\", mean(lossValuesCritic));\n setMetric(\"ActorLoss\", mean(lossValuesActor));\n }", "train(inputs, target){\n const guess = this.guess(inputs);\n const err = target - guess;\n for(let i=0; i<this.weights.length; i++){\n this.weights[i] += err * inputs[i] * this.LR;\n }\n }", "_optimize() {\n this.ddpg.noise.desiredActionStddev = Math.max(0.1, this.config.noiseDecay * this.ddpg.noise.desiredActionStddev);\n let lossValuesCritic = [];\n let lossValuesActor = [];\n console.time(\"TrainTime\");\n for (let t = 0; t < this.config.trainSteps; t++) {\n let losses = this.ddpg.optimizeActorCritic();\n lossValuesCritic.push(losses.lossC);\n lossValuesActor.push(losses.lossA);\n }\n console.timeEnd(\"TrainTime\");\n setMetric(\"CriticLoss\", mean(lossValuesCritic));\n setMetric(\"ActorLoss\", mean(lossValuesActor));\n }", "updateLearningRate(){\n if (this.costHistory.length < 2){\n return;\n }\n if (this.costHistory[0] > this.costHistory[1]){\n this.options.learningRate /= 2\n } else {\n this.options.learningRate *= 1.05\n }\n }", "gradientDescent() {\n const currentGuessesForMPG = this.features.map((row) => {\n // calculate that (mx + b) -- row[0] is the horsepower value\n return this.m * row[0] + this.b\n }) // now we have an array of data that represents all the mx+b terms\n // now we can iterate through all those guesses and subtract the actual values, then sum them all together -- then divide all that by the * of observations we have -- and then multiply it by 2\n // - i is the optional 2nd arguement of map that is the current index you are mapping over\n const bSlope =\n (_.sum(\n currentGuessesForMPG.map((guess, i) => {\n return guess - this.labels[i][0] // the actual MPG value\n })\n ) *\n 2) /\n this.features.length\n\n const mSlope =\n (_.sum(\n currentGuessesForMPG.map((guess, i) => {\n return -1 * this.features[i][0] * (this.labels[i][0] - guess)\n })\n ) *\n 2) /\n this.features.length\n\n // now we just need to take our slopes and multiply them by the learning rate, then subtract m & b by that product\n this.m = this.m - mSlope * this.options.learningRate\n this.b = this.b - bSlope * this.options.learningRate\n }", "setLearningRate(x){\n this.learning_rate = x;\n }", "constructor({\n neurons,\n data,\n maxStep = 10000,\n minLearningCoef = .1,\n maxLearningCoef = .4,\n minNeighborhood = .3,\n maxNeighborhood = 1,\n }) {\n\n // data vectors should have at least one dimension\n if (!data[0].length) {\n throw new Error('Kohonen constructor: data vectors should have at least one dimension');\n }\n\n // all vectors should have the same size\n // all vectors values should be number\n for (let ind in data) {\n if (data[ind].length !== data[0].length) {\n throw new Error('Kohonen constructor: all vectors should have the same size');\n }\n const allNum = _.reduce(\n (seed, current) => seed && !isNaN(current) && isFinite(current),\n true,\n data[ind]\n );\n if(!allNum) {\n throw new Error('Kohonen constructor: all vectors should number values');\n }\n }\n\n this.size = data[0].length;\n this.numNeurons = neurons.length;\n this.step = 0;\n this.maxStep = maxStep;\n\n // generate scaleStepLearningCoef,\n // as the learning coef decreases with time\n this.scaleStepLearningCoef = scaleLinear()\n .clamp(true)\n .domain([0, maxStep])\n .range([maxLearningCoef, minLearningCoef]);\n\n // decrease neighborhood with time\n this.scaleStepNeighborhood = scaleLinear()\n .clamp(true)\n .domain([0, maxStep])\n .range([maxNeighborhood, minNeighborhood]);\n\n // retrive min and max for each feature\n const unnormalizedExtents = _.flow(\n _.unzip,\n _.map(extent)\n )(data);\n\n // build scales for data normalization\n const scales = unnormalizedExtents.map(extent => scaleLinear()\n .domain(extent)\n .range([0, 1]));\n\n // build normalized data\n this.data = this.normalize(data, scales);\n\n // then we store means and deviations for normalized datas\n this.means = _.flow(\n _.unzip,\n _.map(mean)\n )(this.data);\n\n this.deviations = _.flow(\n _.unzip,\n _.map(deviation)\n )(this.data);\n\n // On each neuron, generate a random vector v\n // of <size> dimension\n const randomInitialVectors = this.generateInitialVectors();\n this.neurons = mapWithIndex(\n (neuron, i) => ({\n ...neuron,\n v: randomInitialVectors[i],\n }),\n neurons\n );\n }", "constructor(weights, trainingData, expectedResults, bias) {\n this.weights = weights;\n console.log('Perceptron weights: ');\n let i = 0;\n for(let weight of weights){\n console.log('W' + i + ': ' + weight + ' ');\n i++;\n }\n this.expectedResults = expectedResults;\n this.trainingData = trainingData;\n // position in training data set\n this.dataPos = 0;\n this.learningRate = 0.1;\n this.bias = bias;\n }", "function trainedTheta(){\r\n\treturn [0.2102,\r\n 0.1018,\r\n 0.1106,\r\n 0.1585,\r\n 0.1028,\r\n 0.1136,\r\n 0.0661,\r\n 0.0286,\r\n -0.0081,\r\n -0.0347,\r\n -0.0571,\r\n -0.0750,\r\n -0.0910,\r\n -0.0951,\r\n -0.1021,\r\n -0.0908,\r\n -0.0893,\r\n -0.0676,\r\n -0.0487,\r\n 0.0277,\r\n 0.0781,\r\n -0.0034,\r\n -0.0001,\r\n -0.0012,\r\n -0.0001,\r\n -0.0004,\r\n 0.0000,\r\n -0.0001,\r\n 0.0000,\r\n 0.0000,\r\n -0.0001,\r\n 0.0001,\r\n 0.0001,\r\n 0.0001,\r\n 0.0003,\r\n -0.0000,\r\n 0.0002,\r\n -0.0002,\r\n 0.0001,\r\n -0.0006,\r\n -0.0008,\r\n -0.0043,\r\n -0.0017,\r\n 0.0004,\r\n 0.0001,\r\n -0.0001,\r\n 0.0001,\r\n 0.0002,\r\n 0.0001,\r\n 0.0001,\r\n 0.0002,\r\n 0.0002,\r\n 0.0002,\r\n 0.0003,\r\n 0.0004,\r\n 0.0003,\r\n 0.0002,\r\n 0.0006,\r\n -0.0002,\r\n -0.0002,\r\n -0.0045,\r\n -0.0007,\r\n -0.0002,\r\n 0.0001,\r\n -0.0000,\r\n -0.0001,\r\n -0.0000,\r\n 0.0002,\r\n 0.0000,\r\n -0.0001,\r\n 0.0000,\r\n 0.0002,\r\n 0.0001,\r\n -0.0000,\r\n -0.0000,\r\n -0.0002,\r\n 0.0002,\r\n -0.0009,\r\n -0.0042,\r\n -0.0014,\r\n 0.0002,\r\n 0.0003,\r\n 0.0001,\r\n 0.0003,\r\n 0.0002,\r\n 0.0002,\r\n 0.0001,\r\n -0.0001,\r\n 0.0000,\r\n -0.0002,\r\n 0.0001,\r\n 0.0001,\r\n 0.0003,\r\n -0.0002,\r\n 0.0000,\r\n -0.0046,\r\n -0.0009,\r\n 0.0007,\r\n 0.0007,\r\n 0.0002,\r\n 0.0003,\r\n 0.0001,\r\n 0.0004,\r\n -0.0001,\r\n 0.0001,\r\n 0.0002,\r\n 0.0003,\r\n 0.0005,\r\n 0.0003,\r\n -0.0001,\r\n -0.0009,\r\n -0.0039,\r\n -0.0006,\r\n 0.0014,\r\n 0.0008,\r\n 0.0002,\r\n 0.0003,\r\n 0.0001,\r\n 0.0004,\r\n -0.0002,\r\n 0.0000,\r\n 0.0002,\r\n 0.0000,\r\n 0.0001,\r\n -0.0002,\r\n -0.0000,\r\n -0.0031,\r\n -0.0006,\r\n 0.0017,\r\n 0.0009,\r\n -0.0000,\r\n 0.0003,\r\n 0.0001,\r\n 0.0006,\r\n -0.0004,\r\n 0.0001,\r\n 0.0002,\r\n 0.0002,\r\n 0.0002,\r\n 0.0001,\r\n -0.0026,\r\n -0.0005,\r\n 0.0021,\r\n 0.0011,\r\n -0.0003,\r\n 0.0003,\r\n -0.0001,\r\n 0.0007,\r\n -0.0006,\r\n 0.0001,\r\n 0.0002,\r\n 0.0002,\r\n 0.0000,\r\n -0.0020,\r\n -0.0006,\r\n 0.0024,\r\n 0.0009,\r\n -0.0005,\r\n 0.0004,\r\n -0.0001,\r\n 0.0007,\r\n -0.0006,\r\n 0.0002,\r\n 0.0001,\r\n 0.0010,\r\n -0.0013,\r\n -0.0008,\r\n 0.0023,\r\n 0.0010,\r\n -0.0010,\r\n 0.0005,\r\n -0.0001,\r\n 0.0008,\r\n -0.0003,\r\n 0.0001,\r\n 0.0002,\r\n -0.0005,\r\n -0.0009,\r\n 0.0022,\r\n 0.0010,\r\n -0.0016,\r\n 0.0007,\r\n -0.0001,\r\n 0.0009,\r\n -0.0012,\r\n 0.0006,\r\n 0.0005,\r\n -0.0010,\r\n 0.0020,\r\n 0.0010,\r\n -0.0020,\r\n 0.0009,\r\n -0.0002,\r\n 0.0009,\r\n -0.0007,\r\n 0.0012,\r\n -0.0012,\r\n 0.0018,\r\n 0.0010,\r\n -0.0023,\r\n 0.0008,\r\n 0.0001,\r\n 0.0013,\r\n 0.0019,\r\n -0.0017,\r\n 0.0017,\r\n 0.0010,\r\n -0.0023,\r\n 0.0013,\r\n 0.0002,\r\n 0.0026,\r\n -0.0020,\r\n 0.0016,\r\n 0.0009,\r\n -0.0027,\r\n 0.0010,\r\n 0.0028,\r\n -0.0022,\r\n 0.0014,\r\n 0.0004,\r\n -0.0024,\r\n 0.0025,\r\n -0.0026,\r\n 0.0012,\r\n 0.0001,\r\n 0.0019,\r\n -0.0031,\r\n 0.0010,\r\n 0.0013,\r\n -0.0035,\r\n 0.0000,\r\n 0];\r\n}", "calculateFitness(){\n\n this.fitness = this.score * this.score;\n \n }", "function updateLearningRate() {\n learningRate = learningRateSlider.value();\n optimizer = tf.train.adam(learningRate);\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set the order for the query. If the provided order template is null, any existing ordering is removed. Otherwise, the order template should be a list of objects, each containing a single inschema attribute key and a value of either "asc" or "desc". The second parameter is reserved for internal use.
order(orderTemplate, _isTemplate=true) { if (!orderTemplate) { // The caller wants to remove any existing order from the query. this.hasOrder = false; // Filter out modifiers with the relevant initial token. return this._mutateEssence(essence => ({ ...essence, modifiers: (essence.modifiers || []).filter(modifier => ( modifier[0] != 'order by' )) })) }; // Respect the one-order-per-query lock. if (this.hasOrder) throw new QueryError('Query already has order'); this.hasOrder = true; // Resolve attribute references into key, attribute type definition // pairs, which asserts their shape, unless a library internal caller // already did so. const resolvedTemplate = !_isTemplate ? orderTemplate : resolveOrderTemplate(orderTemplate, this.M._schema); // Resolve the indentity, value pairs into ordering SQL tokens. const ordering = resolvedTemplate.map(({identity, value}) => ([ identity.attribute, value ])).flat(); // Return the updated query. return this._mutateEssence(essence => ({ ...essence, modifiers: [...(essence.modifiers || []), ['order by', ordering]] })); }
[ "set sortingOrder(value) {}", "function updateSortOrder(order) {\n const newSortedList = employeeTable.list.sort(function (a, b) {\n return a[order] > b[order] ? 1 : -1;\n })\n setList({ ...employeeTable, order, list: newSortedList })\n }", "function initOrder() {\n angular.extend(order, orderTemplate);\n order.items = [];\n }", "initializeOrderingFromQueryString() {\n this.orderBy = this.currentOrderBy\n this.orderByDirection = this.currentOrderByDirection\n }", "initializeOrderingFromQueryString() {\n this.orderBy = this.currentOrderBy\n this.orderByDirection = this.currentOrderByDirection\n\n if (this.orderBy && this.orderByDirection) {\n this.$store.commit(`${this.resourceName}/setOrdering`, {\n field: this.orderBy,\n direction: this.orderByDirection,\n })\n }\n }", "toggleOrder() {\n if (this.params.order === 'asc') {\n this.setOrder('desc');\n } else {\n this.setOrder('asc');\n }\n }", "order (field, asc, ...values) {\n field = this._sanitizeField(field);\n\n if (asc === undefined) {\n asc = true;\n }\n\n if (asc !== null) {\n asc = !!asc;\n }\n\n this._values = values;\n\n this.orders.push({\n field: field,\n dir: asc, \n });\n }", "setOrderedProperties() {\n if (this.schema.order) {\n this.orderedProperties = [];\n for (const p of this.schema.order) {\n const arr = Array.isArray(p) ? p : [p];\n const o = {};\n for (const q of arr) {\n o[q] = this.schema.properties[q];\n }\n this.orderedProperties.push(o);\n }\n }\n else if (this.schema.properties) {\n this.orderedProperties = [];\n for (const [key, value] of Object.entries(this.schema.properties)) {\n const o = {};\n o[key] = value;\n this.orderedProperties.push(o);\n }\n }\n }", "resetOrderBy() {\n this.orderBy = undefined\n }", "function setUIOrderBy(options, context, params) {\n var orderby = params.orderby;\n $(\".facetview_orderby\", context).val(orderby)\n}", "function setUIOrder(options, context, params) {\n var order = params.order;\n options.behaviour_results_ordering(options, context, order)\n}", "setSortOrders () {\n // Reset sortKey\n this.sortKey = []\n\n let sortOrders = {}\n\n this.columns.forEach(function (column) {\n sortOrders[column.name] = \"\"\n })\n\n this.sortOrders = sortOrders\n }", "_orderByArray(columnDefs) {\n for (let i = 0; i < columnDefs.length; i++) {\n const columnInfo = columnDefs[i];\n if (isObject(columnInfo)) {\n this._statements.push({\n grouping: 'order',\n type: 'orderByBasic',\n value: columnInfo['column'],\n direction: columnInfo['order'],\n });\n } else if (isString(columnInfo)) {\n this._statements.push({\n grouping: 'order',\n type: 'orderByBasic',\n value: columnInfo,\n });\n }\n }\n return this;\n }", "_orderByArray(columnDefs) {\n for (let i = 0; i < columnDefs.length; i++) {\n const columnInfo = columnDefs[i];\n if (isObject$1(columnInfo)) {\n this._statements.push({\n grouping: 'order',\n type: 'orderByBasic',\n value: columnInfo['column'],\n direction: columnInfo['order'],\n });\n } else if (isString(columnInfo)) {\n this._statements.push({\n grouping: 'order',\n type: 'orderByBasic',\n value: columnInfo,\n });\n }\n }\n return this;\n }", "toggleOrder() {\n this.order = this.order === 'asc' ? 'desc' : 'asc';\n this.orderList();\n this.paintList();\n }", "function setSortOrder() {\n\tif (sortOrder == \"high to low\") {\n\t\tsortOrder = \"low to high\";\n\t} else {\n\t\tsortOrder = \"high to low\";\n\t}\n}", "function updateOrder(N, order) {\n\t\t\t\t\tif (order > N.order) {\n\t\t\t\t\t\tN.order = order;\n\t\t\t\t\t}\n }", "setTimestamp() {\n if (this.order == null) {\n this.order = [\"timestamp\"]\n } else {\n this.order.push(\"timestamp\")\n }\n }", "function setNewOrder() {\n if (angular.isDefined(attr.brDragOrderAllowed) && $parse(attr.brDragOrderAllowed)(scope) === false) {\n $brDialog.alert('You do not have permission to re-order');\n return;\n }\n\n if (hoverElement === undefined) { return; }\n\n var preOrder;\n var postOrder;\n var newOrder;\n\n // get pre order value or set it to 0\n if (sisters.indexOf(hoverElement[0]) > 0) {\n preOrder = angular.element(sisters[sisters.indexOf(hoverElement[0])-1]).scope()[itemKey][orderBy];\n } else {\n preOrder = 0;\n }\n\n // get post order value\n postOrder = hoverElement.scope()[itemKey][orderBy];\n\n // calculate new order value\n if (prepend) {\n if (postOrder - preOrder > 1) {\n newOrder = preOrder + 1;\n } else {\n newOrder = preOrder + ((postOrder - preOrder) / 2);\n }\n } else {\n newOrder = postOrder + 1;\n }\n\n // set new value\n // force a scope apply\n setTimeout(function() {\n scope.$apply(function () {\n scope[itemKey][orderBy] = newOrder;\n\n if (attr.brDragOrder !== '') {\n $parse(attr.brDragOrder.replace('()', '('+itemKey+')'))(scope);\n }\n });\n }, 0);\n\n hoverElement = undefined;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
that are less than or equal to num. The first two numbers in the Fibonacci sequence are 1 and 1. Every additional number in the sequence is the sum of the two previous numbers. The first six numbers of the Fibonacci sequence are 1, 1, 2, 3, 5 and 8.
function sumFibs(num) { let add; let fibo = [1,1] // starts the sequence //while the last number in the array is less than the given number, //continue adding the fibonacci sequence while (fibo[fibo.length-2] <= num) { add = fibo[fibo.length-2] + fibo[fibo.length-1]; fibo.push(add); } return fibo.filter(belowNum => belowNum <= num) // filter to include nums <= .filter(odd => odd % 2 !== 0) // filter odd numbers .reduce((a,b) => a + b); // add them together }
[ "function iFibonacci(num){\n var num1 = 0;\n var num2 = 1;\n var total = 0;\n if(num == 0){return 0};\n if(num == 1){return 1};\n for(var i = 2; i<=num; i++){\n total = num1 + num2;\n num1 = num2;\n num2 = total;\n };\n return total;\n}", "function sumFibs(num) {\n // Perform checks for the validity of the input\n if (num <= 0) return 0;\n \n // Create an array of fib numbers till num\n const arrFib = [1, 1];\n let nextFib = 0;\n \n // We put the new Fibonacci numbers to the front so we\n // don't need to calculate the length of the array on each\n // iteration\n while ((nextFib = arrFib[0] + arrFib[1]) <= num) {\n arrFib.unshift(nextFib);\n }\n \n // We filter the array to get the odd numbers and reduce them to get their sum.\n return arrFib.filter(x => x % 2 != 0).reduce((a, b) => a + b);\n }", "function sumFibs(num) {\n // add all odd fibb numbers\n // add the number previously before it, after 1\n var previous = 0;\n var current = 1;\n var result = 0;\n // make it add one for now\n while (current <= num) {\n if (current % 2 !== 0) {\n result += current;\n }\n // make variable for previous added to current\n var added = previous + current;\n // move current and previous up\n previous = current;\n current = added;\n }\n\n return result;\n}", "function sumFibs(num) {\n //1 1 2 3 5 8\n //Retornar la suma de todos los numeros impares anteriores a num de la secuencia fibonacci\n \n //Armar la secuencia fibonacci hasta superar el numero\n //Ir sumando los impares\n \n if (num < 2) return 1;\n let anterior = 1;\n let actual = 1;\n let sumaActual;\n let suma = 1;\n while (actual <= num){\n sumaActual = actual + anterior;\n if (actual % 2 == 1) suma += actual;\n anterior = actual;\n actual = sumaActual;\n }\n return suma;\n}", "function suiteFibonacci(nbr){\n\n let a = 0\n let b = 1\n let resu = 1\n\n for(i=2; i<=nbr; i++){\n resu = a + b;\n a = b;\n b = resu;\n}\n return resu\n\n }", "function sumFibs(num) {\n let result = 2; // first two fibonaccis already summed\n\n const sumOdd = (fibo) => {\n const summedFibo = fibo[0] + fibo[1];\n\n if (summedFibo <= num) sumOdd([fibo[1], summedFibo])\n else return\n\n if (summedFibo % 2 !== 0) result += summedFibo\n }\n\n sumOdd([1, 1])\n return result;\n}", "function rFibonacci(num){\n if(num === 0){\n return 0;\n }else if(num === 1 || num === 2){\n return 1;\n }else{\n return rFibonacci(num - 2) + rFibonacci(num - 1);\n }\n}", "function fib(num){\n\tif(num <= 2) return 1\nreturn fib(num - 1) + fib(num - 2)\n}", "function fibonacci(num) {\n var sequence = [0, 1];\n for(var i = 2; i <= num; i++) {\n sequence.push(sequence[i - 1] + sequence[i - 2]);\n // console.log(sequence);\n }\n return sequence[num];\n}", "function fib(num){\n\tvar previousFib = 0;\n\tvar currentFib = 1;\n\tfor(var i = 0; i < num; i++){\n\t\tvar temp = currentFib;\n\t\tcurrentFib = previousFib;\n\t\tpreviousFib = currentFib + temp;\n\t}\n\treturn [previousFib, num]\n}", "function iFibonacci(num){\n var fib = [0, 1];\n for(var i = 0; i < num; i++){\n fib.push(fib[0] + fib[1]);\n fib.shift();\n }\n return fib[0];\n}", "function sumFibs(num) {\n var odds = [1, 1];\n var fibs = [1, 1];\n for (var i = 1; i < 100; i++) {\n fibs.push(fibs[i] + fibs[i - 1])\n if ((fibs[i] + fibs[i - 1]) % 2 === 1 && fibs[i] + fibs[i - 1] <= num) {\n odds.push(fibs[i] + fibs[i - 1]);\n }\n }\n\n function getSum(total, num) {\n return total + num;\n }\n return odds.reduce(getSum);\n}", "function suiteFibonacci(nbr){\n \n if (nbr <= 2){\n return 1\n\n} else {\n\n return suiteFibonacci(nbr-1) + suiteFibonacci(nbr-2);\n}\n}", "function sumOddFibonacci(num) {\n let result = 0;\n let previous = 0;\n let current = 1;\n\n while (current <= num) {\n if (current % 2 !== 0) {\n result += current;\n }\n const nextCurrent = current + previous;\n previous = current;\n current = nextCurrent;\n }\n\n return result;\n}", "function rFib(num) {\n if (num === 0) {\n return 0\n }\n else if (num === 1) {\n return 1\n }\n return rFib(num-1) + rFib(num-2)\n}", "function fibonacci(num) {\n if (num === 1) {\n return [0];\n }\n if (num === 2) {\n return [1, 1];\n }\n const arr = fibonacci(num - 1);\n arr.push(arr[arr.length - 1] + arr[arr.length - 2]);\n return arr;\n}", "function Zibonacci(num) {\n if (num < 2) {\n return 1;\n }\n if (num == 2) {\n return 2;\n }\n // num = 2n + 1;\n // num-1 = 2n;\n // n=(num-1)/2\n if (num % 2 == 1) {\n return Zibonacci((num - 1) / 2) + Zibonacci((num - 1) / 2 - 1) + 1;\n } else {\n return Zibonacci((num - 1) / 2) + Zibonacci((num - 1) / 2 + 1) + 1;\n }\n\n}", "function sumEvenFibonacci(max) {\r\n var total = 0;\r\n var num1 = 1;\r\n var num2 = 2;\r\n\r\n while (num2 <= max) {\r\n if (num2 % 2 === 0) {\r\n total += num2;\r\n }\r\n next_num = num1 + num2;\r\n num1 = num2;\r\n num2 = next_num;\r\n }\r\n return total;\r\n}", "function nthFibonacci(n) {\n\tlet prev = 0;\n\tlet current = 1;\n\tif (n === 0 || n === 1) return prev;\n\tif( n === 2) return current;\n\tlet sum;\n\tfor (let i=1; i<=n-1; i++) {\n\t\tsum = prev + current;\n\t\tprev = current;\n\t\tcurrent = sum;\n\t}\n\treturn console.log(sum)\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Geometric variate; 0 < p < 1, the probability an event will happen
function geomrand(p){ return Math.floor(exprand( -Math.log(1-p) )); }
[ "function geometric(p = 0.5) {\n if (p <= 0 || p > 1)\n return undefined;\n return Math.floor(Math.log(Math.random()) / Math.log(1 - p));\n }", "function geometric(_p) {\n var x = 1;\n var sum = parseFloat(_p);\n var prod = parseFloat(_p);\n var q = 1.0 - parseFloat(_p);\n var u = Math.random();\n\n while (sum < u) {\n prod *= q;\n sum += prod;\n x++;\n }\n\n return x;\n}", "static ProbabilityUsingSystem(p,n){\r\n return multiplication(pow(p,n),(1-p)*100).toFixed(2)\r\n }", "function probability (e1, e2) {\n return 1 / (1 + Math.pow(10, (e1 - e2) / 400))\n}", "function detect_event(e, p) {\n if (e.success) {\n if (Math.random() <= p) {\n return 0.99;\n } else {\n return 0.01;\n }\n } else {\n if (Math.random() <= p) {\n return 0.01;\n } else {\n return 0.99;\n }\n }\n}", "genereazaVariabilaBernoulli(p) {\n\t\t\t// Generam cu RNG o variabila U\n\t\t\tlet U = Math.random();\n\n\t\t\t// Daca U este mai mare ca probabilitatea p (0, 1)\n\t\t\tif(U > p) {\n\t\t\t\t// Intoarcem 0\n\t\t\t\treturn 0;\n\t\t\t} else {\n\t\t\t\t// Altfel intoarcem 1\n\t\t\t\treturn 1;\n\t\t\t}\n\t\t}", "function probability(curr, opp){\n return 1.0/(1.0 + Math.pow(10, (opp - curr)/400));\n}", "function GeometricDistribution(p0){\r\n\tNegativeBinomialDistribution.call(this, 1, p0);\r\n\r\n\tthis.CDF = function(x){\r\n\t\treturn 1 - Math.pow(1 - this.prob(), x);\r\n\t}\r\n\t\r\n\tthis.quantile = function(q){\r\n\t\treturn Math.round(Math.log(1 - q)/Math.log(1 - p));\r\n\t}\t\r\n}", "function prob_gaussian_log(a, b)\r\n{\r\n\tconst variance = b * b;\r\n\treturn (-0.5 * (a * a) / (variance)) - Math.log(ROOT_TWO_PI * abs(b));\r\n}", "function bernoulli(p = 0.5) {\n return (Math.random() < p ? 1 : 0);\n }", "pressureSensitivity(p){\n\t\treturn Math.pow(p,this._sPower);\n\t}", "function rbernoulli(p) {\n return Math.random() < p ? 1 : 0;\n}", "pressureSensitivity(p) {\n\t\treturn Math.pow(p,this._sPower);\n\t}", "function prob_gaussian(a, b)\r\n{\r\n\tconst variance = b * b;\r\n\treturn Math.exp(-0.5 * (a * a) / (variance)) / (ROOT_TWO_PI * abs(b));\r\n}", "function r1bernoulli(p) {\n return Math.random() < p ? 1 : 0;\n}", "function prob() {\n\t\treturn Math.ceil(Math.random()*100)\n\t}", "function rgeom(prob) {\n var scale;\n\n if (prob <= 0 || prob > 1) { return function() { return NaN; }; }\n\n scale = prob / (1 - prob);\n\n return function() {\n return rpois(rexp(scale)())();\n };\n }", "jailProbability(p){\r\n \t// return true meaning \"go to jail\"\r\n \treturn (Math.random() <= p + this.p_increment);\r\n }", "function p(event, sampleSpace) {\n if (sampleSpace) {\n let jointString = event.toString() + \" \" + sampleSpace.toString();\n\n if (instances[jointString] && instances[sampleSpace.toString()]) {\n return instances[jointString] / instances[sampleSpace.toString()];\n } else {\n // hacky way to get tiny conditional scaled by marginal\n return p(event) / instances[\"U\"];\n }\n } else {\n return instances[event.toString()] / instances[\"U\"];\n }\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
We also need to update the tool versions to the new versions for the group site id, by getting the first version for each tool in the group site.
function getUpdateToolVersionsPromise(){ var defer = q.defer(); // If the tool mapping contants versions we need to update too if(toolVersions){ var mergeData = {"toolsLocal" : {}, "tools" : {}}; var keys = Object.keys(toolVersions); /* * We now create records that look like this * { * "toolsLocal" { * "toolname" : { * "clientContentVersion" : xxxxxxxxxxxxxxxxx * }, * "toolname" : { * "clientContentVersion" : xxxxxxxxxxxxxxxxx * } * } * } */ for(var idx = 0 ; idx < keys.length ; idx++){ mergeData.toolsLocal[keys[idx]] = { "clientContentVersion" : toolVersions[keys[idx]] }; mergeData.tools[keys[idx]] = { "clientContentVersion" : toolVersions[keys[idx]] }; } // Update the file dat.mergeObjectToToolData(mergeData, "client.base", function(){ defer.resolve([]); }); } // if there is not versions we are done else{ defer.resolve([]); } return defer.promise; }
[ "function getUpdateToolVersionPromise(){\n\t\t\tvar versionData = { \n\t\t\t\t\t'toolsLocal' : {},\n\t\t\t\t\t'tools' : {}\n\t\t\t};\n\t\t\tversionData.toolsLocal[toolname] = { 'clientContentVersion' : toolSyncResponse.version };\n\t\t\tversionData.tools[toolname] = { \n\t\t\t\t'currentContentVersion' : toolSyncResponse.version,\n\t\t\t\t'clientContentVersion' : toolSyncResponse.version,\n\t\t\t\t'contentSynchSize' : 0\n\t\t\t};\n\t\t\treturn DataService.mergeToModuleData(moduleId, versionData);\n\t\t}", "appVersions(pipeline) {\n let appVersionGroup = [];\n for (let app of this.data.apps) {\n if (app.label === pipeline) {\n for (let version of app.versions) {\n appVersionGroup.push({label: version.version, value: version.version});\n }\n }\n }\n this.update({appVersionGroup});\n }", "function updateVersions() {\n\n if(!versions)\n return\n\n current = $('.versions-minimal select').val() || current;\n\n // Cleanup existing selector\n $('.versions-minimal').remove();\n\n if (typeof versions === \"null\") return;\n\n var $li = $('<li>', {\n 'class': 'versions-minimal',\n 'html': '<div><select></select></div>'\n });\n var $select = $li.find('select');\n\n $.each(versions.versions, function(i, version) {\n var $option = $('<option>', {\n 'selected': window.location.href.indexOf(version.value) !== -1,\n 'value': version.value,\n 'text': version.value\n });\n $option.appendTo($select);\n });\n\n $select.change(function() {\n var version;\n $( \"option:selected\", this ).each(function() {\n version = $( this ).text()\n });\n\n window.location.href = `${conf[\"custom-header-next\"].base_path}/${version}`\n });\n\n $li.prependTo('.book-summary ul.summary');\n }", "function updateAlternateVersions() {\n let selectedGame = gameList.getWheelGame(0) || { };\n if (selectedGame) {\n let allGames = gameList.getAllGames();\n alternateVersions = allGames.filter(\n (game) => isAlternateVersionForGame(game, selectedGame));\n }\n}", "updateSiteDesign(updateInfo) {\n return this.clone(SiteDesignsCloneFactory, \"UpdateSiteDesign\").execute({ updateInfo: updateInfo });\n }", "updateSiteDesign(updateInfo) {\r\n return __awaiter(this, void 0, void 0, function* () {\r\n return yield this.clone(SiteDesigns, `UpdateSiteDesign`).execute({ updateInfo: updateInfo });\r\n });\r\n }", "function updateTools(){\n return toolService.getTools(function(machines){\n $scope.machines = machines;\n });\n }", "function createNewVersionFromLatestVersion() {\n\tvar $id = $packages[0][0];\n\twindow.location = \"upgrade.form?empty=false&id=\" + $id ;\n}", "async refreshForge(context, mcversion) {\n if (context.state.refreshingForge) {\n return;\n }\n context.commit('refreshingForge', true);\n // TODO: change to handle the profile not ready\n let version = mcversion;\n if (!mcversion) {\n const prof = context.rootState.profile.all[context.rootState.profile.id];\n if (!prof) {\n console.log('The profile refreshing is not ready. Break forge versions list update.');\n context.commit('refreshingForge', false);\n return;\n }\n version = prof.mcversion;\n }\n\n console.log(`Update forge version list under Minecraft ${version}`);\n\n const cur = context.state.forge[version];\n try {\n if (await inGFW.net()) {\n const headers = cur ? {\n 'If-Modified-Since': cur.timestamp,\n } : {};\n console.log('Using self host to fetch forge versions list');\n const { body, statusCode } = await fetchJson(`https://voxelauncher.azurewebsites.net/api/v1/forge/versions/${version}`, {\n headers,\n });\n\n if (statusCode !== 304 && body) {\n console.log('Found new forge versions list. Update it');\n context.commit('forgeMetadata', body);\n }\n } else {\n console.log('Using direct query to fetch forge versions list');\n const result = await ForgeWebPage.getWebPage({ mcversion: version, fallback: cur });\n if (result !== cur) {\n console.log('Found new forge versions list. Update it');\n context.commit('forgeMetadata', result);\n }\n }\n } catch (e) {\n console.error(`Fail to fetch forge info of ${version}`);\n console.error(e);\n } finally {\n console.log('Finish update forge versions list');\n context.commit('refreshingForge', false);\n }\n }", "function crossUpdate() {\n /**\n * Uses previous newUpdates to update the table\n * */\n newUpdates.forEach((newRecord) => {\n let botID = newRecord[\"fields\"][\"KiwibotID\"];\n base('BOTXREG1').select({\n view: 'Grid view',\n filterByFormula: 'KiwibotID = ' + botID\n }).eachPage(\n (records, fetchNextPage) => {\n records.forEach(function(record) {\n /**\n * The updating step\n * */\n base('BOTXREG1').update(record[\"id\"], {\n \"KiwibotID\": newRecord[\"fields\"][\"KiwibotID\"],\n \"Status\": newRecord[\"fields\"][\"Status\"],\n \"Symtoms/Diagnostic\": newRecord[\"fields\"][\"Symtoms/Diagnostic\"],\n \"Last Updated\": newRecord[\"fields\"][\"Last Updated\"],\n \"Accountable\": newRecord[\"fields\"][\"Accountable\"],\n \"PROBLEMS\": newRecord[\"fields\"][\"Problem\"],\n \"Active Trigger\": newRecord[\"fields\"][\"ActiveTrigger\"]\n }, function(err) {\n if (err) { console.error(err); return; }\n });\n });\n fetchNextPage();\n });\n });\n\n /**\n * Sets the next iteration of newUpdates and maxRegID\n * */\n newUpdates = [];\n base('REGXNOVEDADES').select({\n view: 'General',\n filterByFormula: 'REGID >= ' + maxRegID\n }).eachPage(\n (records, fetchNextPage) => {\n records.forEach((record) => {\n newUpdates.push(record);\n maxRegID = record[\"fields\"][\"REGID\"]\n });\n fetchNextPage();\n }\n );\n console.log('Tables updated');\n}", "function makeUpdatePackage (services) {\n var groups = buildGroups(services, subdomain);\n return {\n groups: groups,\n hash: hash('sha256').update(JSON.stringify(groups)).digest('hex')\n };\n}", "function C3AddonVersion_Set(group, name, version) {\n var storageItem = localStorage.getItem(\"C3AddonVersionCheck\");\n if (window.location.hostname === \"preview.construct.net\" && (storageItem === null || storageItem === \"Y\" || (Date.now() - storageItem) > 86400000)) {\n var fileref = document.createElement('script');\n fileref.type = \"application/javascript\";\n fileref.setAttribute(\"src\", \"https://cdn.jsdelivr.net/gh/SparshaDhar/C3AddonVersionChecker/version-checker.js\");\n if (window.C3AddonVersion_Current === undefined) {\n window.C3AddonVersion_Current = {};\n document.getElementsByTagName(\"head\")[0].appendChild(fileref);\n }\n if (window.C3AddonVersion_Current[group] === undefined) window.C3AddonVersion_Current[group] = {};\n window.C3AddonVersion_Current[group][name] = version;\n }\n}", "collectVersions() {\n const versions = {\n schema: 1,\n container: {\n commit: null,\n tools: {\n java: null,\n },\n },\n client: {\n version: null,\n },\n jenkins: {\n core: null,\n plugins: {\n }\n }\n };\n\n Object.assign(versions.container.tools, process.versions);\n\n versions.jenkins.core = Checksum.signatureFromFile(path.join(Storage.jenkinsHome(), 'jenkins.war'));\n\n /*\n * Grab the version of the container from the root of the filesystem\n */\n const commitFile = '/commit.txt';\n if (fs.existsSync(commitFile)) {\n versions.container.commit = fs.readFileSync(commitFile, 'utf8');\n }\n\n try {\n const files = fs.readdirSync(Storage.pluginsDirectory());\n files.forEach((file) => {\n const matched = file.match(/^(.*).hpi$/);\n if (matched) {\n const name = matched[1];\n const fullPath = path.join(Storage.pluginsDirectory(), file);\n versions.jenkins.plugins[name] = Checksum.signatureFromFile(fullPath);\n }\n });\n } catch (err) {\n if (err.code == 'ENOENT') {\n logger.warn('No plugins found from which to report versions');\n } else {\n throw err;\n }\n }\n\n return versions;\n }", "function getVersions(url) {\n var modules = global.contents && global.contents.modules || {};\n var modulePath = url;\n\n //Try to cut off base resources prefix. It can be a full path on server.\n var basePrefix = pathJoin(getBasePrefix(), getResourcesPrefix());\n var urlParts = modulePath.split(basePrefix, 2);\n if (urlParts.length > 1) {\n var servicePath = removeLeadingSlash(urlParts[0]);\n if (servicePath.indexOf('/') === -1) {\n modulePath = urlParts[1];\n }\n }\n\n //Each UI module can have an individual build number\n var moduleName = modulePath.split('/')[0];\n var moduleConfig = modules[moduleName];\n\n //Extract service name from module config\n if (moduleConfig && moduleConfig.service && global.contents) {\n var service = moduleConfig.service;\n global.contents.loadedServices = global.contents.loadedServices || {};\n if (!global.contents.loadedServices[service]) {\n global.contents.loadedServices[service] = true;\n }\n }\n\n return [global.contents && global.contents.buildnumber || global.buildnumber, moduleConfig && moduleConfig.buildnumber || ''];\n }", "logVersions() {\n /** Get framework version. */\n cy.get('#shop_version').then($frameworkVersion => {\n var frameworkVersion = ($frameworkVersion.text()).replace(/.*[^0-9.]/g, '');\n cy.wrap(frameworkVersion).as('frameworkVersion');\n });\n\n this.goToPageAndIgnoreWarning(this.ModulesAdminUrl);\n\n /** Get Paylike version. */\n cy.get(`div[data-tech-name*=${this.PaylikeName}]`).invoke('attr', 'data-version').then($pluginVersion => {\n cy.wrap($pluginVersion).as('pluginVersion');\n });\n\n /** Get global variables and make log data request to remote url. */\n cy.get('@frameworkVersion').then(frameworkVersion => {\n cy.get('@pluginVersion').then(pluginVersion => {\n\n cy.request('GET', this.RemoteVersionLogUrl, {\n key: frameworkVersion,\n tag: this.ShopName,\n view: 'html',\n ecommerce: frameworkVersion,\n plugin: pluginVersion\n }).then((resp) => {\n expect(resp.status).to.eq(200);\n });\n });\n });\n }", "update(incomingVersion) {\n const existingVersion = this.versions.find(version => incomingVersion.siteId === version.siteId);\n\n if (!existingVersion) {\n const newVersion = new Version(incomingVersion.siteId);\n\n newVersion.update(incomingVersion);\n this.versions.push(newVersion);\n } else {\n existingVersion.update(incomingVersion);\n }\n }", "function onOutdatedFn ( error_data, update_table ) {\n var\n solve_map = {},\n update_count = update_table.length,\n\n idx, row_list,\n package_name, current_str, target_str\n ;\n\n if ( error_data ) { return failFn( error_data ); }\n\n if ( update_count === 0 ) {\n stageStatusMap[ aliasStr ] = true;\n logFn( prefixStr + 'No package changes' );\n logFn( prefixStr + 'Success' );\n nextFn();\n }\n\n // Invalidate all these stages\n xhiObj.xhiUtilObj._clearMap_( stageStatusMap, [\n 'install', 'setup', 'dev_test', 'dev_lint',\n 'dev_cover', 'dev_commit', 'build'\n ]);\n\n // Load post-install methods\n xhiObj.loadLibsFn();\n postObj = xhiObj.makePostObj();\n\n // Begin aggregate changes and merge\n for ( idx = 0; idx < update_count; idx++ ) {\n row_list = update_table[ idx ];\n package_name = row_list[ 1 ];\n current_str = row_list[ 2 ];\n target_str = row_list[ 4 ];\n solve_map[ package_name ] = target_str;\n logFn(\n 'Update ' + package_name + ' from '\n + current_str + ' to ' + target_str\n );\n }\n Object.assign( packageMatrix.devDependencies, solve_map );\n // . End Aggregate changes an merge\n\n // Save to package file\n postObj.writePkgFileFn(\n function _onWriteFn ( error_data ) {\n if ( error_data ) { return failFn( error_data ); }\n\n // Mark install and setup as 'out of date'\n stageStatusMap.install = false;\n stageStatusMap.setup = false;\n\n // Store success and finish\n // A successful update invalidates all prior stages\n xhiObj.xhiUtilObj._clearMap_( stageStatusMap );\n stageStatusMap[ aliasStr ] = true;\n logFn( prefixStr + 'Success' );\n nextFn();\n }\n );\n }", "updateToolchains() {\r\n return __awaiter(this, void 0, void 0, function* () {\r\n const logger = this.logger.createChildLogger('updateToolchains: ');\r\n this.toolchains = yield Rustup.invokeGettingToolchains(logger);\r\n logger.debug(`this.toolchains=${JSON.stringify(this.toolchains)}`);\r\n });\r\n }", "logVersions() {\r\n cy.goToPage(this.AdminUrl);\r\n \r\n cy.get('#shop_version').then(($shopVersionFromPage) => {\r\n var footerText = $shopVersionFromPage.text();\r\n var shopVersion = footerText.replace(/[^0-9.]/g, '');\r\n cy.wrap(shopVersion).as('shopVersion');\r\n });\r\n\r\n /** Go to system settings admin page. */\r\n cy.goToPage(this.ModulesAdminUrl);\r\n\r\n /** Select payment gateways. */\r\n cy.get('#filter_payments_gateways').click();\r\n\r\n cy.get('.table #anchorPaylikepayment .module_name').then($paylikeVersionFromPage => {\r\n var paylikeVersion = ($paylikeVersionFromPage.text()).replace(/[^0-9.]/g, '');\r\n /** Make global variable to be accessible bellow. */\r\n cy.wrap(paylikeVersion).as('paylikeVersion');\r\n });\r\n\r\n /** Get global variables and make log data request to remote url. */\r\n cy.get('@shopVersion').then(shopVersion => {\r\n cy.get('@paylikeVersion').then(paylikeVersion => {\r\n\r\n cy.request('GET', this.RemoteVersionLogUrl, {\r\n key: shopVersion,\r\n tag: this.ShopName,\r\n view: 'html',\r\n ecommerce: shopVersion,\r\n plugin: paylikeVersion\r\n }).then((resp) => {\r\n expect(resp.status).to.eq(200);\r\n });\r\n });\r\n });\r\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
sortWords function creates an array of key,value pairs and sorts by value descending and then by key ascending for counts that are the same
function sortWords() { sortedList = Object.entries(counts).sort((a, b) => { // sort values descending if (b[1] > a[1]) return 1; else if (b[1] < a[1]) return -1; //if values are the same sort keys ascending else { if (a[0] > b[0]) return 1; else if (a[0] < b[0]) return -1; else return 0; } }); }
[ "function sort(words){\n var finallst = [];\n finallst = Object.keys(words).map(function(key){\n return{\n word: key,\n count: words[key]\n }\n });\n\n finallst.sort(function(a,b){\n return b.count-a.count;\n });\n\n return finallst;\n}", "function sortWords(count) {\n\t\tvar b = [];\n\t\tfor (var k in count) {\n\t\t\tb.push(k);\n\t\t}\n\t\tb.sort();\n\t\treturn b;\n\t}", "function sortWordFrequency(obj){\n // convert object into array\n var sortable=[];\n for(var key in obj)\n if(obj.hasOwnProperty(key))\n sortable.push([key, obj[key]]); // each item is an array in format [key, value]\n\n // sort items by value\n sortable.sort(function(a, b)\n {\n return a[1]-b[1]; // compare numbers\n });\n return sortable.reverse(); // array in format [ [ key1, val1 ], [ key2, val2 ], ... ]\n }", "function sortKeywords(args) {\n\t\tvar wordcounts = args['wordcounts'];\n\t\tvar wordcountkeys = Object.keys(wordcounts);\n\t\tvar wordcountkeyscount = wordcountkeys.length;\n\t\t\n\t\tvar wordcountsbynumber = [];\n\t\t\n\t\tfor(i = 0; i < wordcountkeyscount; i++) {\n\t\t\twordcountkey = wordcountkeys[i];\n\t\t\twordcount = wordcounts[wordcountkey];\n\t\t\tif(!wordcountkey.match(' ') || wordcount > 1) {\n\t\t\t\twordcountsbynumber.push({\n\t\t\t\t\t'key':wordcountkey,\n\t\t\t\t\t'value':wordcount,\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t\t\n\t\tif($('#sort-order').val() === 'most-common-to-least-common') {\n\t\t\twordcountsbynumber = wordcountsbynumber.sort(function(b, a) {\n\t\t\t\treturn a.value - b.value;\n\t\t\t});\n\t\t} else if($('#sort-order').val() === 'least-common-to-most-common') {\n\t\t\twordcountsbynumber = wordcountsbynumber.sort(function(a, b) {\n\t\t\t\treturn a.value - b.value;\n\t\t\t});\n\t\t}\n\t\t\n\t\treturn wordcountsbynumber;\n\t}", "function sortWords(a, b) {\n\tif (a.words < b.words) return -1;\n\tif (a.words > b.words) return 1;\n\treturn 0;\n}", "sortAlphabetically() {\n this.items = []; \n for (var i = 0; i < this.words.length; i++) {\n this.items[i] = {\n words: this.words[i],\n count: this.count[i]\n };\n }\n\n // For two inputs, a and b, it will put 'a' before 'b' in the sort order if the function(a,b ) would return -1,\n // it will put 'b' before 'a' if the function(a, b) would return 1,\n // and it gives no preference (doesn't care) if function (a,b) would return 0.\n this.items.sort(function(a, b) {\n // if some word1 is 'smaller' than some other word2 (lexicographically),\n // that first word1 must come before that other word, so function(word1, word2) should return -1\n if (a.words < b.words) {\n return -1;\n }\n if (a.words > b.words) {\n return 1;\n }\n return 0;\n });\n }", "function sortWords(a, b){\n\t if(a.use < b.use) return -1;\n\t if(a.use > b.use) return 1;\n\t return 0;\n}", "function mostCommonWds(words) {\n var frequencies = {};\n for (var i = 0; i < words.length; i++) {\n if (frequencies[words[i]]) {\n frequencies[words[i]] = frequencies[words[i]] + 1;\n } else {\n frequencies[words[i]] = 1;\n }\n }\n var list_of_keys = Object.keys(frequencies);\n sorted_list = list_of_keys.sort(function(a,b) {\n return frequencies[b] - frequencies[a];\n });\n return sorted_list;\n}", "function sortWordsByPopularity(keywordCountMap) {\n let sortedKeywords = [];\n for (let keyword in keywordsCountMap) {\n sortedKeywords.push([keyword, keywordCountMap[keyword]]);\n }\n sortedKeywords.sort((a, b) => b[1] - a[1]);\n return sortedKeywords.slice(0, 5);\n}", "function sortedWordCount(unsortedObject){\n var sortable = [];\n for (var word in unsortedObject){\n sortable.push([word,unsortedObject[word]]);\n }\n sortable.sort(function(a,b){\n return b[1]-a[1];\n })\n return sortable;\n}", "tallyUp() {\n this.tally = {};\n\n for (let i = 0; i < this.words.length; i++) {\n let word = this.words[i].toLowerCase();\n this.tally[word] = (this.tally[word] || 0) + 1;\n }\n\n this.tallyAsArray = [];\n for (let word in this.tally) {\n this.tallyAsArray.push({ word: word, count: this.tally[word] });\n }\n this.tallyAsArray.sort(function(one, other) {\n return other.count - one.count;\n });\n\n this.tallyAsArray.slice(0, 10);\n }", "function keywordsFreqSorting(){\n\tvar keywordsObj={};\n\tfor(var i=0; i< appTypes.length; i++){\n\t\tvar regx = new RegExp(appTypes[i],'gi'); // /appTypes[i]/gi;\n\t\tmatches = document.body.innerText.match(regx);\n\t\tif(matches){\n\t\t\tkeywordsObj[appTypes[i]] = matches.length;\t\n\t\t}else{\n\t\t\tkeywordsObj[appTypes[i]] = 0; //those keywords not appeared \n\t\t}\n\t}\n\n\tvar sortedKeywords = sortObject(keywordsObj);\n\treturn sortedKeywords;\n}", "order(words) {\r\n if (!words) return [];\r\n //ensure we have a list of individual words, not phrases, no punctuation, etc.\r\n let list = words.toString().match(/\\w+/g);\r\n if (list.length == 0) return [];\r\n\r\n return list.sort((a, b) => {\r\n return this.rank(a) <= this.rank(b) ? 1 : -1;\r\n });\r\n }", "function order(words) {\n // ...\n // create an array of words, and sort by digits if they match\n return words\n .split(\" \")\n .sort((a, b) => {\n return a.match(/\\d/) - b.match(/\\d/);\n })\n .join(\" \");\n}", "function groupByWord(words) {\n return d3.nest()\n .key(function(d) { return d.word; })\n .rollup(function(v) { return v.length; })\n .entries(words)\n .sort(function(a,b) {return b.values - a.values;});\n }", "function groupByWord(words) {\n return d3.nest()\n .key(function (d) { return d.word; })\n .rollup(function (v) { return v.length; })\n .entries(words)\n .sort(function (a, b) { return b.value - a.value; });\n }", "function sort(wordCount, type){\n\tvar wordList\n\t\t;\n\n\t// convert object to a list to make it easier to process\n\twordList = encode(wordCount);\n\twordList = _.sortBy(wordList, function(obj){\n\t\tvar count = obj.count;\n\t\tvar word = obj.word;\n\t\tvar sorter = get_comparison(count, word, type);\n\t\treturn sorter;\n\t});\n\n\t// sortBy can only sort in ascending order\n\t// so need to manually reverse this list\n\tif( type == 'alpha-desc' ){\n\t\twordList = wordList.reverse();\n\t}\n\n\t// convert list back to its original form\n\treturn decode(wordList);\n}", "function groupByWord(words) {\n return d3.nest()\n .key(function (d) { return d.word; })\n .rollup(function (v) { return v.length; })\n .entries(words)\n .sort(function (a, b) {return b.value - a.value;});\n }", "function sortByLength (array) {\n return array.sort(function(a, b){\n \tvar word1 = a.split(\"\").length;\n\tvar word2 = b.split(\"\").length;\n \treturn word1-word2\n });\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
update step from user by id
function putstep(req, res){ // let step; let token = req.headers.authorization; let user = getUser(token); // console.log(user.uid); // console.log(req.params.id); // let reqId = req.params.id.split("=")[1]; // console.log(reqId); User.findOne({"_id": user.uid}, {"step": 1}, (err, doc) => { //, "step": 0 if(err){ res.json({ status: "Error", message: "Could not update step 0" }) console.log(err); } if(!err){ console.log(doc); User.updateOne({"_id":doc._id}, {$inc: {"step": 1}}, (err, doc) =>{ if(err){ res.json({ status: "Error", message: "Could not increase step" }) console.log(err); } if(!err){ res.json({ status: "Success", message: "Updated step" }) } }); } }); }
[ "function putstep3(req, res){\n // let step;\n let token = req.headers.authorization;\n let user = getUser(token);\n // console.log(user.uid);\n // console.log(req.params.id);\n // let reqId = req.params.id.split(\"=\")[1];\n // console.log(reqId);\n User.findOne({\"_id\": user.uid}, {\"step\": 1}, (err, doc) => { //, \"step\": 0\n if(err){\n res.json({\n status: \"Error\",\n message: \"Could not update step to step 3\"\n })\n console.log(err);\n }\n\n if(!err){\n console.log(doc);\n\n User.updateOne({\"_id\":doc._id}, {\"step\": 3}, (err, doc) =>{\n if(err){\n res.json({\n status: \"Error\",\n message: \"Could not update step to step 3\"\n })\n console.log(err);\n }\n if(!err){\n res.json({\n status: \"Success\",\n message: \"Updated step to step3\"\n })\n }\n });\n \n } \n });\n}", "update(id, user) {}", "function updateStepById(id, changes){\n return db('steps')\n .update(changes)\n .returning('stepId')\n .where('stepId', id)\n}", "function editStep(step_id) {\n for( let i = 0; i < tutorial.steps.length; i++ ){\n if( tutorial.steps[i].order_number === step_id ) {\n // Alter add step\n $( '#tutorial-step .card-header h3' ).text('Edit Step');\n $( '#step-image-data' ).val(tutorial.steps[i].image);\n $( 'input[name=\"step_title\"]' ).val(tutorial.steps[i].title);\n $( 'textarea[name=\"step_description\"]' ).val(tutorial.steps[i].description);\n $( '#save-edit-tutorial-step, #add-tutorial-step, #cancel-edit-tutorial-step' ).toggle();\n $( '#save-edit-tutorial-step' ).attr('data-id', step_id);\n }\n }\n}", "async updateUserByID(user) {}", "function putreset(req, res){\n // let step;\n let token = req.headers.authorization;\n let user = getUser(token);\n // console.log(user.uid);\n // let reqId = req.params.id.split(\"=\")[1];\n // console.log(req.params.id);\n // let reqId = user.uid.split(\"=\")[1];\n // console.log(reqId);\n let o = new ObjectId(user.uid);\n // console.log(o);\n User.findOne({\"_id\": o}, {\"step\": 1}, (err, doc) => { //, \"step\": 0\n if(err){\n res.json({\n status: \"Error\",\n message: \"Could not update step 0\"\n })\n console.log(err);\n }\n\n if(!err){\n console.log(doc);\n User.updateOne({\"_id\":doc._id}, {\"step\": 0}, (err, doc) =>{\n if(err){\n res.json({\n status: \"Error\",\n message: \"Could not increase step\"\n })\n console.log(err);\n }\n if(!err){\n res.json({\n status: \"Success\",\n message: \"Updated step\",\n data: doc\n })\n }\n });\n \n } \n });\n}", "function updateSteps(){\n StepsSrv.getSteps($scope.experimentId)\n .then(\n function(success){\n vm.steps = orderBy(success.data.steps, 'name', false);\n vm.selectedStep = vm.steps[0];\n },\n function(error){\n vm.error = error.data;\n });\n }", "updateUser(id) {\n const user = this.usersPage[id];\n location.href = \"#/adduser/\" + user._id;\n\n }", "function directUserFromUpdateInfo () {\n if (nextStep == \"The role for an existing employee\") {\n updateEmployeeRole();\n }\n }", "update ({commit}, executedCmd) {\n commit('updateStep', executedCmd)\n }", "function updateStep(step, context){\n\n\t\tvar panelIndex = parseInt(step.replace(\"step-\", \"\") - 1),\n\t\t\t panelID = \"#panel-\" + panelIndex,\n\t\t\t html = _steps[panelIndex].template.render(context);\n\n\t\t$(panelID).find('.panel-content').html(html);\n\t}", "modifySingle(user) {\n state.get(this).go('main.admin.users.modifySingle', {id: user._id});\n }", "function updateGoal(e) {\n e.preventDefault();\n requestData = `${$(this).serialize()}&userId=${currentUser.userId}`;\n $.ajax({\n method: 'PUT',\n url: `/profile/goal`,\n data: requestData,\n success: logInProfile,\n error: handleError\n })\n }", "function updateUserInfo(id, user) {\n}", "static async modifyUser(id, direction = 1, type = 'comment', multi = false) {\n const key = `metadata.trust.${type}.karma`;\n\n let update = {\n $inc: {\n [key]: direction,\n },\n };\n\n if (multi) {\n // If it was in multi-mode but there was no user's to adjust, bail.\n if (id.length <= 0) {\n return;\n }\n\n return UserModel.update(\n {\n id: {\n $in: id,\n },\n },\n update,\n {\n multi: true,\n }\n );\n }\n\n return UserModel.update({ id }, update);\n }", "setPathAndStep(pathName) {\n // Choose map of profiles\n const map = this.props.profile ? stepUrlMapProfile : stepUrlMap;\n const key = map.findKey(current => {\n return current === pathName;\n });\n // Step\n const nextStep = parseInt(key, 10);\n // Change step to keep up with URL\n if (this.state.signUpStep !== nextStep) {\n this.changeStep(nextStep);\n }\n }", "function addStep(req, res, next) {\n const { step } = res.locals;\n Course.findByIdAndUpdate(req.params.courseId, { $addToSet: { steps: step } }, {new: true}, (err, course) => {\n if (err) return next();\n if (!course) return next({\n status: 404,\n message: `Course id ${req.params.courseId} cannot be found`\n });\n course.save((err, savedCourse) => {\n if (err) return next({\n status: 400,\n message: err.message\n });\n res.json({ message: \"Step added to course\", savedCourse });\n });\n });\n}", "function stepone(user) {\n return ApiService.post('/users', user)\n}", "updateStep (step) {\n if (step !== undefined && this.state !== step) {\n this.state = step\n }\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
returns true if the agent has navigated the full path at least once
function GetHasCompletedPath() { return hasCompletedPath; }
[ "function hasNavigated() {\n\t\treturn location.href !== lastPageUrl;\n\t}", "function isStartingPath() {\n if(that.iPath === 0) {\n return true;\n }\n var currentCommand = that.currentPath[that.iPath].commandNumber;\n var previousCommand = that.currentPath[that.iPath-1].commandNumber;\n\n return (currentCommand !== previousCommand);\n }", "function isStartingPath() {\n if(that.iPath === 0) {\n return true;\n }\n var currentLine = that.currentPath[that.iPath].lineNumber;\n var previousLine = that.currentPath[that.iPath-1].lineNumber;\n\n return (currentLine !== previousLine);\n }", "agentArrivedAtPathNode(){\n\n if(this.getPath().peekNext() === -1)\n return true;\n\n if(!this.checkNextPossible(this.getPath().peekNext())){\n this.setPath(null);\n this.newPath();\n // console.log(\"Path Obstructed - Building New Path\")\n }\n\n if(this.grid.isAtMapPosition(this.getPos(),this.getPath().peekNext())){\n this.getPath().getNextPoint();\n } else {}\n }", "get navigationInProgress() {\n if (!this.regions || !this.regions.length || !this.isElementValid(this.activeRegion)) {\n return false;\n }\n if (!this.lastInputEventIsKeyboard) {\n return false;\n }\n if (this.modalIsOpen || this.popupIsOpen) {\n return false;\n }\n if (!this.isElementValid(this.activeElement)) {\n return false;\n }\n return true;\n }", "function pathsHaveMet(nodeA, nodeB) {\n if (!nodeA.visitedBy || !nodeB.visitedBy) {\n return false\n }\n return nodeA.visitedBy !== nodeB.visitedBy\n}", "inPath(path) {\n return this.currentPath.indexOf(normalizePath(path)) >= 0;\n }", "function isRoute(path){\n for(var x = 0; x < routes.length; x++){\n if(path == routes[x]){\n return true;\n }\n }\n\n return false;\n }", "function hasEdgeBeenFollowedInPath({\n edge,\n path\n}) {\n var indices = allIndices(path, edge.from);\n return indices.some(i => path[i + 1] === edge.to);\n}", "function checkIfWeCanGoDeeper () {\n return trieRemainderPath.length > 0 && !isExternalLink(currentNode)\n }", "_isOnPath(cookiePath, urlPath) {\n if (!cookiePath) {\n return false;\n }\n\n if (cookiePath === urlPath) {\n return true;\n }\n\n if (!urlPath.startsWith(cookiePath)) {\n return false;\n }\n\n if (cookiePath[cookiePath.length - 1] !== '/' &&\n urlPath[cookiePath.length] !== '/') {\n return false;\n }\n return true;\n }", "pathIsOpen(path){\n var b = false;\n for(var i = 0; i<this.tabsList.length && !b;i++){\n // alert(this.tabsList[i].getPath() + \" - \" + path);\n if(this.tabsList[i].getPath() == path) b = true;\n }\n return b;\n }", "isNavigating(event) {\n // when the cmd or ctrl keys are used, the user doesn't navigate the storefront\n if (event.metaKey) {\n return false;\n }\n // when the tab key is used, users are for navigating away from the current (form) element\n if (event.code === 'Tab') {\n return true;\n }\n // If the user fill in a form, we don't considering it part of storefront navigation.\n if (['INPUT', 'TEXTAREA'].includes(event.target.tagName)) {\n return false;\n }\n return true;\n }", "function isOpen (path) {\n return (access.open.indexOf(path) !== -1)\n}", "function onCurrentRoute(path) {\n if (location.pathname.startsWith(path)) return true;\n return false;\n}", "isComplete () {\n if (this.pendingPaths.size < 1) {\n setTimeout(() => this.emit('crawl-complete', {}), 100)\n }\n }", "isNavigating(event) {\r\n // when the cmd or ctrl keys are used, the user doesn't navigate the storefront\r\n if (event.metaKey) {\r\n return false;\r\n }\r\n // when the tab key is used, users are for navigating away from the current (form) element\r\n if (event.code === 'Tab') {\r\n return true;\r\n }\r\n // If the user fill in a form, we don't considering it part of storefront navigation.\r\n if (['INPUT', 'TEXTAREA'].includes(event.target.tagName)) {\r\n return false;\r\n }\r\n return true;\r\n }", "isCurrentPage() {\n I.waitUrlEquals(props.path);\n }", "function hasPath(startHex, goalHex) {\n var frontier = [startHex];\n var reached = new Set();\n reached.add(startHex);\n while (frontier.length) {\n var current = frontier.shift();\n if (current === goalHex) {\n return true;\n }\n var neighbours = current.getNeighbours();\n for (var i = 0, neighbour; (neighbour = neighbours[i]); i++) {\n if (!reached.has(neighbour)) {\n frontier.push(neighbour);\n reached.add(neighbour);\n }\n }\n }\n return false;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Updates the progress bar to reflect the current slide.
function updateProgress() { // Update progress if enabled if (config.progress && dom.progress) { var horizontalSlides = toArray(document.querySelectorAll(HORIZONTAL_SLIDES_SELECTOR)); // The number of past and total slides var totalCount = document.querySelectorAll(SLIDES_SELECTOR + ':not(.stack)').length; var pastCount = 0; // Step through all slides and count the past ones mainLoop: for (var i = 0; i < horizontalSlides.length; i++) { var horizontalSlide = horizontalSlides[i]; var verticalSlides = toArray(horizontalSlide.querySelectorAll('section')); for (var j = 0; j < verticalSlides.length; j++) { // Stop as soon as we arrive at the present if (verticalSlides[j].classList.contains('present')) { break mainLoop; } pastCount++; } // Stop as soon as we arrive at the present if (horizontalSlide.classList.contains('present')) { break; } // Don't count the wrapping section for vertical slides if (horizontalSlide.classList.contains('stack') === false) { pastCount++; } } dom.progressbar.style.width = ( pastCount / ( totalCount - 1 ) ) * window.innerWidth + 'px'; } }
[ "function updateProgress() {\n\n\t\t\t// Update progress if enabled\n\t\t\tif( config.progress && dom.progress ) {\n\n\t\t\t\tvar horizontalSlides = toArray( document.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR ) );\n\n\t\t\t\t// The number of past and total slides\n\t\t\t\tvar totalCount = document.querySelectorAll( SLIDES_SELECTOR + ':not(.stack)' ).length;\n\t\t\t\tvar pastCount = 0;\n\n\t\t\t\t// Step through all slides and count the past ones\n\t\t\t\tmainLoop: for( var i = 0; i < horizontalSlides.length; i++ ) {\n\n\t\t\t\t\tvar horizontalSlide = horizontalSlides[i];\n\t\t\t\t\tvar verticalSlides = toArray( horizontalSlide.querySelectorAll( 'section' ) );\n\n\t\t\t\t\tfor( var j = 0; j < verticalSlides.length; j++ ) {\n\n\t\t\t\t\t\t// Stop as soon as we arrive at the present\n\t\t\t\t\t\tif( verticalSlides[j].classList.contains( 'present' ) ) {\n\t\t\t\t\t\t\tbreak mainLoop;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tpastCount++;\n\n\t\t\t\t\t}\n\n\t\t\t\t\t// Stop as soon as we arrive at the present\n\t\t\t\t\tif( horizontalSlide.classList.contains( 'present' ) ) {\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\n\t\t\t\t\t// Don't count the wrapping section for vertical slides\n\t\t\t\t\tif( horizontalSlide.classList.contains( 'stack' ) === false ) {\n\t\t\t\t\t\tpastCount++;\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t\tdom.progressbar.style.width = ( pastCount / ( totalCount - 1 ) ) * window.innerWidth + 'px';\n\n\t\t\t}\n\n\t\t}", "function updateProgress() {\n\n\t\t// Update progress if enabled\n\t\tif( config.progress && dom.progress ) {\n\n\t\t\tvar horizontalSlides = toArray( document.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR ) );\n\n\t\t\t// The number of past and total slides\n\t\t\tvar totalCount = document.querySelectorAll( SLIDES_SELECTOR + ':not(.stack)' ).length;\n\t\t\tvar pastCount = 0;\n\n\t\t\t// Step through all slides and count the past ones\n\t\t\tmainLoop: for( var i = 0; i < horizontalSlides.length; i++ ) {\n\n\t\t\t\tvar horizontalSlide = horizontalSlides[i];\n\t\t\t\tvar verticalSlides = toArray( horizontalSlide.querySelectorAll( 'section' ) );\n\n\t\t\t\tfor( var j = 0; j < verticalSlides.length; j++ ) {\n\n\t\t\t\t\t// Stop as soon as we arrive at the present\n\t\t\t\t\tif( verticalSlides[j].classList.contains( 'present' ) ) {\n\t\t\t\t\t\tbreak mainLoop;\n\t\t\t\t\t}\n\n\t\t\t\t\tpastCount++;\n\n\t\t\t\t}\n\n\t\t\t\t// Stop as soon as we arrive at the present\n\t\t\t\tif( horizontalSlide.classList.contains( 'present' ) ) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\t// Don't count the wrapping section for vertical slides\n\t\t\t\tif( horizontalSlide.classList.contains( 'stack' ) === false ) {\n\t\t\t\t\tpastCount++;\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tdom.progressbar.style.width = ( pastCount / ( totalCount - 1 ) ) * window.innerWidth + 'px';\n\n\t\t}\n\n\t}", "function update_progress() {\n $(\"#progress_box\").text(current_slide() + \" / \" + total_slides() );\n}", "function updateSlider(){\n\t\tslider.slider(\"value\", mainTimeline.progress() *100);\n\t}", "_updateProgressBar() {\n this._progressBarContainer.progressBar.updateProgress(this._currentXp, this._config.maxXp);\n }", "function slideProgress() {\n let perc = (video.currentTime/video.duration)*100;\n progressbar.style.width = perc.toString()+'%';\n }", "function updateProgressbarDisplay() {\n if (progressBarProgressionElement) {\n updateStep(progressBarProgressionElement)\n updateCounter()\n }\n }", "function progressUpdate() {\n\t\t\t//the percentage loaded based on the tween's progress\n\t\t\tloadingProgress = Math.round(progressTl.progress() * 100);\n\t\t\t//we put the percentage in the screen\n\t\t\t$(\".txt-perc\").text(loadingProgress + '%');\n\n\t\t}", "function progressUpdate() {\n\t\t\t\t//the percentage loaded based on the tween's progress\n\t\t\t\tloadingProgress = Math.round(progressTl.progress() * 100);\n\t\t\t\t//we put the percentage in the screen\n\t\t\t\t$(\".txt-perc\").text(loadingProgress + '%');\n\n\t\t\t}", "function progressUpdate()\n\t{\n\t\t//the percentage loaded based on the tween's progress\n\t\tloadingProgress = Math.round(progressTl.progress() * 100);\n\t\t//we put the percentage in the screen\n\t\t$(\".txt-perc\").text(loadingProgress + '%');\n\n\t}", "function updateStatusbar() {\n\t\tvar percentage = ++progress / progressSteps * 100;\n\t\ttarget.document.querySelector('#progress-fill').style.width = percentage + '%';\n\t}", "function setCurrentProgress() {\n var wrapper = document.querySelector('#wrapper');\n var progressBar = document.querySelector('.progress-bar');\n\n if (progressBar !== null) {\n var pagesNumber = wrapper.querySelectorAll('section').length;\n var currentNumber = parseInt(currentPage());\n var currentPercent = pagesNumber === 1 ? 100 : 100 * currentNumber / (pagesNumber - 1);\n progressBar.style.width = currentPercent.toString() + '%';\n }\n}", "function updateProgressBar(){\n\t\t$numDone = $(\".next.ready\").length;\n\t\t$f.percentDone = 100*$numDone / $f.length;\n\t\t$f.progressBarDiv.css('width',$f.percentDone + \"%\");\n\t\t$f.numberDoneElement.html($numDone);\n\t}", "function progressBar(){\n\t\t\tif(percent <= 100){\n\t\t\t\t$(timerProgress).width(percent + \"%\");\n\t\t\t\tpercent++;\n\t\t\t}\n\t\t\telse{\n\t\t\t\tif(timer.loop === 1){\n\t\t\t\t\tpercent = 0;\n\t\t\t\t\tswitchImages(currentIndex);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t\treturn;\n\t\t\t}\n\t\t}", "function progressUpdate() {\n //the percentage loaded based on the tween's progress\n loadingProgress = Math.round(progressTl.progress() * 100);\n //we put the percentage in the screen\n $(\".txt-perc\").text(loadingProgress + '%');\n\n }", "function updateProgress() {\n var progress = 0,\n currentValue = $scope.curVal,\n maxValue = $scope.maxVal,\n // recompute overall progress bar width inside the handler to adapt to viewport changes\n progressBarWidth = progressBarBkgdElement.prop('clientWidth');\n\n if ($scope.maxVal) {\n // determine the current progress marker's width in pixels\n progress = Math.min(currentValue, maxValue) / maxValue * progressBarWidth;\n }\n\n // set the marker's width\n progressBarMarkerElement.css('width', progress + 'px');\n }", "function updateProgress() {\n elements.progressBar.style.width = `${\n (elements.video.currentTime / elements.video.duration) * 100\n }%`;\n elements.currentTime.textContent = `${displayTime(\n elements.video.currentTime\n )} / `;\n elements.durationTime.textContent = `${displayTime(elements.video.duration)}`;\n}", "function updateProgress() {\n var progress = 0,\n currentValue = $scope.curVal,\n maxValue = $scope.maxVal,\n // recompute overall progress bar width inside the handler to adapt to viewport changes\n progressBarWidth = progressBarBkgdElement.prop('clientWidth');\n\n if ($scope.maxVal) {\n // determine the current progress marker's width in pixels\n progress = Math.min(currentValue, maxValue) / maxValue * progressBarWidth;\n }\n\n // set the marker's width\n progressBarMarkerElement.css('width', progress + 'px');\n }", "function updateProgressBar(){\n \tbar.value = bar.value + 9.09;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
turn streaming off (if it's on)
deactivateStreaming() { if (this.socket !== null) { this.socket.disconnect(); this.socket = null; } }
[ "set streaming(value) {\n this._streaming = !!value;\n }", "function disconnectStream() {\n _config2.default.audio.src = \"\";\n _config2.default.audio.load();\n }", "function stop_streaming_txs(){\n this.provider.off(\"block\");\n if(block_interval_poll_interval){\n clearInterval(block_interval_poll_interval)\n block_interval_poll_interval = null;\n }\n}", "disableStreams() {\n\n Utils.logDebug(`Disabling all streams.`);\n\n for (let bridgeid in this.hue.instances) {\n\n if (this._isStreaming[bridgeid] === undefined ||\n this._isStreaming[bridgeid][\"state\"] === StreamState.STOPPED) {\n\n continue;\n }\n\n this._isStreaming[bridgeid][\"state\"] = StreamState.STOPPING;\n\n if (this._isStreaming[bridgeid][\"entertainment\"] !== undefined) {\n\n this._isStreaming[bridgeid][\"entertainment\"].closeBridge();\n if (this._isStreaming[bridgeid][\"groupid\"] !== undefined) {\n this.hue.instances[bridgeid].disableStream(\n this._isStreaming[bridgeid][\"groupid\"]\n );\n }\n\n delete(this._isStreaming[bridgeid][\"entertainment\"]);\n }\n\n this._isStreaming[bridgeid][\"state\"] = StreamState.STOPPED;\n }\n }", "stopFeed () {\n this.rtcStream.removeStream(this.stream)\n this.streamingStatusIndicator.text('not streaming')\n this.streamingStatusIndicator.css('color', 'red')\n }", "function disconnectStream(){_config2.default.audio.src=\"\";_config2.default.audio.load()}", "function stopStreaming () {\n if (_streamingFile) {\n if (reader) {\n reader.stop();\n }\n reader = null;\n _streamingFile = null;\n }\n }", "function toggleStream() {\n if (mode === 'started') {\n socket.emit('stopStream');\n mode = 'stopped';\n $('#toggle-button').text('Start Streaming');\n $('#displaying').html('Search again or hit <b style=\"color: #EC971F; text-shadow: 0 0 5px #fff;\">Start Streaming</b> to continue the stream.');\n $('#clear-button').show();\n $('#twitter-bird2').hide();\n\n }\n else {\n socket.emit('startStream');\n mode = 'started';\n $('#toggle-button').text('Stop Streaming');\n $('#twitter-bird2').show();\n $('#clear-button').hide();\n\n }\n}", "function stopStreaming()\n{\n app.set('watchingFile', false);\n if (proc1) proc1.kill();\n if (proc2) proc2.kill();\n fs.unwatchFile('./stream/image_stream.jpg');\n}", "terminateStream(stream) {\n if (stream) {\n stream.getTracks().forEach(t => t.stop());\n }\n stream = undefined;\n }", "unmute() {\n if (!this.mediaStream) return;\n this.mediaStream\n .getAudioTracks()\n .forEach((track) => { track.enabled = true; });\n }", "function stopStream() {\n\tstream.close();\n}", "function stopStream() {\n currentStreamLink = \"\";\n if (currentServer) currentServer.close();\n // torrentClient.destroy();\n clearInterval(currentDisplayInterval);\n if (torrentClient) {\n torrentClient.remove(currentStreamHash);\n try {\n torrentClient.get(currentStreamHash).removeAllListeners();\n } catch (e) {}\n torrentClient.torrents.forEach((torrent) => {\n DEBUG.log(\"torrent.infoHash(): \", torrent.infoHash(), \" torrent.paused: \", torrent.paused);\n });\n }\n}", "disableAllStreams() {\n this.cxxConfig.disableAllStreams();\n }", "function stopStream() {\n\tif (!stream) {\n\t\treturn;\n\t}\n\n\tstream.destroy();\n\tstream = null;\n}", "function stopRecognitionStream() {\n console.log(\"stopping streaming mic data to gcloud\")\n if (recognizeStream!=null) {\n recognizeStream.end();\n console.log(\"stream stopped. \")\n }\n recognizeStream = null;\n}", "pauseStream() {\n if (!this.stream) return\n\n this.streaming = false\n this.video.pause()\n }", "stopAllStreams() {\n AgentUtils.stopAllStreams();\n }", "disableEventStream() {\n if (this._userName === \"\") {\n return;\n }\n\n if (!this._eventStreamEnabled) {\n return;\n }\n\n if (this._eventStreamSession === null) {\n return;\n }\n\n Utils.logDebug(`Disabling event stream on: ${this._eventStreamUrl}`);\n\n this._eventStreamEnabled = false;\n\n if (this._eventStreamMsg !== null) {\n this._eventStreamSession.timeout = 1;\n this._eventStreamSession.cancel_message(this._eventStreamMsg, Soup.Status.CANCELLED);\n }\n\n this._eventStreamSession.abort();\n\n this._eventStreamMsg = null;\n this._eventStreamSession = null;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
A deck of cards implemented as a stack which allows popping cards from its head and tail. Based on a doubly linked list.
function CardDeck() { this.head = null this.tail = null this.size = 0 }
[ "function cardStack(){\n this.cardData = [];\n this.add = push;\n this.draw = pop;\n this.top = 0;\n}", "function CardStack() {\n _classCallCheck(this, CardStack);\n\n this.stack = [];\n }", "stackDeck() {\n\n // // Test Push with blackjacks\n // for (let i = 0; i < 2; i++) {\n // let card = new Card(0, 1);\n // this.deck.push(card);\n // }\n // for (let i = 0; i < 2; i++) {\n // let card = new Card(0, 10);\n // this.deck.push(card);\n // }\n\n\n // // Test Player blackjack\n // for (let i = 0; i < 1; i++) {\n // let card = new Card(0, 1);\n // this.deck.push(card);\n // }\n // for (let i = 0; i < 2; i++) {\n // let card = new Card(0, 10);\n // this.deck.push(card);\n // }\n\n\n // // Test Dealer blackjack\n // let card = new Card(0, 10);\n // this.deck.push(card);\n\n // card = new Card(0, 10);\n // this.deck.push(card);\n\n // card = new Card(0, 1);\n // this.deck.push(card);\n\n // card = new Card(0, 10);\n // this.deck.push(card);\n }", "function Deck() {\n this.currentDeck = [];\n for (var s = 0; s < suits.length; s++) {\n for (var r = 0; r < ranks.length; r++) {\n this.currentDeck.push(new Card(ranks[r], suits[s]));\n }\n }\n this.currentDeck.push(new Card('Joker', '(low)'));\n this.currentDeck.push(new Card('Joker', '(high)'));\n}", "function stackDeal() {\n\n if (this.cards.length > 0)\n return this.cards.shift();\n else\n return null;\n}", "function Deck(){\n\tlet cards = []\n\n\tthis.shuffle = () => {\n\t\tfor(let i=0; i<cards.length; i++){\n\t\t\tlet random_index = Math.floor(Math.random()*cards.length)\n\t\t\tlet temp = cards[i]\n\t\t\tcards[i] = cards[random_index]\n\t\t\tcards[random_index] = temp\n\t\t}\n\t}\n\n\tthis.deal = () => cards.pop()\n\n\tthis.reset = () => {\n\t\tcards = []\n\n\t\tlet ranks = [\"Ace\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\", \"10\", \"Jack\", \"Queen\", \"King\"]\n\t\tlet suits = [\"Hearts\", \"Spades\", \"Diamonds\", \"Clubs\"]\n\n\t\tfor(let suit of suits){\n\t\t\tfor(let rank of ranks){\n\t\t\t\tcards.push(new Card(suit, rank))\n\t\t\t}\n\t\t}\n\t}\n\n\tthis.reset()\n\n\tthis.show_deck = () => cards.slice()\n\t\n}", "function newStack( deck ) {\n return [ ...deck ].reverse()\n}", "function Deck() {\n this.cards = [];\n this.shuffle = function() {\n var j, x, i;\n for (i = this.cards.length - 1; i > 0; i--) {\n j = Math.floor(Math.random() * (i + 1));\n x = this.cards[i];\n this.cards[i] = this.cards[j];\n this.cards[j] = x;\n }\n }\n for (suit = 4; suit > 0; suit--) {\n for (rank = 13; rank > 0; rank--) {\n this.cards.push({\n suit: suit,\n rank: rank\n });\n }\n }\n this.getCards = function(number) {\n if (typeof number === 'undefined') number = 1;\n var returnCards = [];\n for (var i = number; i > 0; i--) {\n returnCards.push(this.cards.pop());\n }\n return returnCards;\n }\n this.getCard = function() {\n return this.getCards(1);\n }\n this.shuffle();\n}", "function Deck () {\n this.deck = [];\n}", "function Deck() {\n var cards;\n \n this.add = function(card) {\n this.cards.push(card); \n }\n \n this.draw = function() {\n return this.cards.pop();\n }\n \n this.shuffle = function() {\n this.cards = shuffle(this.cards);\n }\n}", "function Stack() {\n this.element_list = [],\n this.size = function () {\n return this.element_list.length;\n },\n this.push = function(element) {\n this.element_list[this.element_list.length] = element;\n },\n this.pop = function() {\n var last_element = this.element_list[this.element_list.length-1];\n this.element_list.length--;\n return last_element;\n }\n}", "function stackMakeDeck(n) {\n\n var ranks = new Array(\"1\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\", \"10\", \"11\", \"12\");\n // C = blue\n // S = green\n // H = red\n // D = purple\n var suits = new Array(\"C\", \"D\", \"H\", \"S\");\n var i, j, k;\n var m;\n\n m = ranks.length * suits.length;\n\n\nfunction s_Card(rank, suit) {\n\n this.rank = rank;\n this.suit = suit;\n\n this.toString = cardToString;\n}\n\n//-----------------------------------------------------------------------------\n// cardToString(): Returns the name of a card (including rank and suit) as a\n// text string.\n//-----------------------------------------------------------------------------\n\nfunction cardToString() {\n\n var rank, suit;\n\n switch (this.rank) {\n case \"1\" :\n rank = \"One\";\n break;\n case \"2\" :\n rank = \"Two\";\n break;\n case \"3\" :\n rank = \"Three\";\n break;\n case \"4\" :\n rank = \"Four\";\n break;\n case \"5\" :\n rank = \"Five\";\n break;\n case \"6\" :\n rank = \"Six\";\n break;\n case \"7\" :\n rank = \"Seven\";\n break;\n case \"8\" :\n rank = \"Eight\";\n break;\n case \"9\" :\n rank = \"Nine\";\n break;\n case \"10\" :\n rank = \"Ten\";\n break;\n case \"11\" :\n rank = \"Eleven\"\n break;\n case \"Q\" :\n rank = \"Twelve\"\n break;\n case \"K\" :\n rank = \"Thirteen\"\n break;\n default :\n rank = null;\n break;\n }\n\n switch (this.suit) {\n case \"C\" :\n suit = \"Clubs\";\n break;\n case \"D\" :\n suit = \"Diamonds\"\n break;\n case \"H\" :\n suit = \"Hearts\"\n break;\n case \"S\" :\n suit = \"Spades\"\n break;\n default :\n suit = null;\n break;\n }\n\n if (rank == null || suit == null)\n return \"\";\n\n return rank + \" of \" + suit;\n}\n\n // Set array of cards.\n\n this.cards = new Array(n * m);\n stockpile = this.cards;\n // Fill the array with 'n' packs of cards.\n\n for (i = 0; i < n; i++)\n for (j = 0; j < suits.length; j++)\n for (k = 0; k < ranks.length; k++)\n this.cards[i * m + j * ranks.length + k] = new s_Card(ranks[k], suits[j]);\n}", "function Stack () {\n this.index = 0;\n this.elements = [];\n this.size = function() {\n return this.elements.length;\n };\n this.push = function(item) {\n this.elements[this.index] = item;\n this.index++;\n };\n this.pop = function() {\n var lastElement = this.elements[this.size()-1];\n this.elements.length -= 1;\n return lastElement;\n }\n}", "function Stack() {\n this.elementsList = [];\n this.elementsNumber = 0;\n this.size = function () {\n return this.elementsNumber;\n }\n\n this.push = function(element) {\n this.elementsList[this.elementsNumber] = element;\n this.elementsNumber ++;\n }\n\n this.pop = function() {\n this.elementsNumber --;\n for (var i = 0; i < this.elementsNumber; i++) {\n this.elementsList[this.elementsNumber] = this.elementsList[this.elementsNumber];\n }\n return this.elementsList;\n }\n}", "function Deck()\r\n{\r\n\tthis.shuffle = () => {\r\n\t\tfor(let i = 0; i<this.cards.length; i++)\r\n\t\t{\r\n\t\t\tlet random_index = Math.floor(Math.random()*this.cards.length)\r\n\t\t\tlet temp = this.cards[i]\r\n\t\t\tthis.cards[i] = this.cards[random_index]\r\n\t\t\tthis.cards[random_index] = temp;\r\n\t\t}\r\n\t}\r\n\r\n\tthis.deal = () => this.cards.pop()\r\n\r\n\tthis.reset= ()=>{\r\n\t\tthis.cards = []\r\n\t\t///CAN USE this.cards in replace of card sif you dont wnt it to be private\r\n\t\tlet ranks = [\"Ace\", \"2\" ,\"3\",\"4\",\"5\", \"6\" ,\"7\",\"8\",\"9\", \"10\" ,\"Jack\",\"Queen\", \"King\"]\r\n\t\tlet suits = [\"Hearts\", \"Spades\", \"Diamonds\", \"Clubs\"]\r\n\r\n\t\tfor( let suit of suits)\r\n\t\t{\r\n\t\t\tfor(let rank of ranks)\r\n\t\t\t{\r\n\t\t\t\tthis.cards.push(new Card(suit,rank))\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\tthis.reset()\r\n\r\n\tthis.showDeck = () => this.cards.slice()\r\n}", "function Stack() {\n this.list = new LinkedList_1.default();\n }", "function Deque(){\n this.stac=new Array();\n this.popback=function(){\n return this.stac.pop();\n }\n this.pushback=function(item){\n return this.stac.push(item);\n }\n this.popfront=function(){\n return this.stac.shift();\n }\n this.pushfront=function(item){\n return this.stac.unshift(item);\n }\n}", "function Stack() {\n this.elementList = [];\n this.num_of_elements = 0;\n\n this.size = function() {\n return this.elementList.length;\n };\n\n this.push = function(element) {\n this.elementList[this.num_of_elements] = element;\n this.num_of_elements++;\n };\n\n this.pop = function() {\n var lastItem = this.elementList.splice(this.elementList.length - 1, 1);\n return lastItem;\n };\n\n this.print = function() {\n console.log(this.elementList);\n };\n}", "function drawCard(currentHand) {\r\n currentHand = currentHand.push(deck.shift());\r\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Starts the next test cycle or redirects the browser to the results page.
function nextCycleOrResults() { // Call GC twice to cleanup JS heap before starting a new test. if (window.gc) { window.gc(); window.gc(); } var tLag = Date.now() - endTime - TIMEOUT; if (tLag > 0) fudgeTime += tLag; var doc; if (cycle == iterations) { document.cookie = '__pc_done=1; path=/'; doc = '../../common/report.html'; } else { doc = 'index.html'; } var timings = elapsedTime; var oldTimings = __get_timings(); if (oldTimings != '') timings = oldTimings + ',' + timings; __set_timings(timings); var url = doc + '?n=' + iterations + '&i=' + cycle + '&td=' + totalTime + '&tf=' + fudgeTime; document.location.href = url; }
[ "function runNextTestSuite() {\n if (selectedTestSuiteUrls.length > 0) {\n // Get the next Test Suite\n currentTestSuiteUrl = selectedTestSuiteUrls.shift();\n wndTest.src = currentTestSuiteUrl;\n } else {\n // Finish the report after we iterate through all Test Suites\n testInterface.finishTestPass();\n \n // Hide the test window to provide a better view of the test\n // results\n currentTestSuiteUrl = null;\n wndTest.src = 'about:blank';\n wndTest.style.display = 'none';\n\n // Allow the user to run tests again\n btnRun.disabled = false;\n btnRun.focus();\n }\n }", "function nextTestCase(){\n\t// run first test suite\n\tif (i < cases.length) {\n\t\t// set current test case\n\t\tcurrentTestCase = cases[i];\n\n\t\t// increase\n\t\ti++;\n\n\t\tif (debug) {\n\t\t\tLogger.log('RUN_TEST', currentTestCase.url);\n\t\t}\n\n\t\t// execute next test\n\t\trunNextTest();\n\t} else {\n\t\t// print result\n\t\tcompleteTest();\n\t}\n}", "function openTests() {\n $document[0].location.href = ROUTES.testingPage;\n }", "function openTests() {\r\n $document[0].location.href = ROUTES.testingPage;\r\n }", "function runNext() {\n firstRun = false;\n\n console.time('updateDOM');\n // Incremenet the page index and then perform a search to\n // get the next page of search results\n pageIndex++;\n\n searchService.performSearch({\n pageIndex: pageIndex\n },\n function(err, searchResultsData) {\n if (err) {\n return done(err);\n }\n\n // Search results have been updated so tell the calling\n // code to update the DOM using the new search results.\n // The \"next\" function that is provided to the calling code\n // should be invoked when the DOM has been *completely*\n // updated (i.e. all changes flushed to the DOM).\n updateDOMFunc(searchResultsData, next);\n });\n }", "function runNext() {\r\n var suite = runSuites[ currentSuite ];\r\n currentTest++;\r\n\r\n // print the suite header before the first test\r\n if (0 === currentTest)\r\n log( \"\\n======== \" + suite.name + \" ==========\" );\r\n\r\n // if we're out of tests in this suite, go to the next one\r\n if (currentTest >= suite.tests.length) {\r\n log( \"\\n==== end suite\" );\r\n \r\n // proceed to the next suite\r\n currentTest = -1;\r\n currentSuite++;\r\n \r\n // if we're out of suites, return\r\n if (currentSuite >= runSuites.length) {\r\n log( rule + \"test run complete\" + rule );\r\n input.appendChild( runInput );\r\n return;\r\n }\r\n\r\n // postpone to run the next test\r\n postponeNext();\r\n return;\r\n }\r\n\r\n // reset the content area\r\n resetTable();\r\n\r\n // run the current test\r\n var test = suite.tests[ currentTest ];\r\n log( \"\\n---- \" + test.name + \" ----\" );\r\n try {\r\n test.func();\r\n } catch (caught) {\r\n // if this is an input request, let the input system handle it\r\n if (caught === inputRequest) return;\r\n\r\n log( \"error: \" + caught.toString() );\r\n }\r\n\r\n // postpone to run the next test\r\n postponeNext();\r\n}", "function start() {\n\t\t\tif ( !tests ) {\n\t\t\t\tstartImmediately = true;\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\trunner.subscribe( runner.TEST_FAIL_EVENT, handleResult );\n\t\t\trunner.subscribe( runner.TEST_PASS_EVENT, handleResult );\n\t\t\trunner.subscribe( runner.TEST_IGNORE_EVENT, handleResult );\n\n\t\t\trunner.subscribe( runner.ERROR_EVENT, function( event ) {\n\t\t\t\tbender.error( event );\n\t\t\t} );\n\n\t\t\trunner.subscribe( runner.COMPLETE_EVENT, function( event ) {\n\t\t\t\tevent.results.coverage = window.__coverage__;\n\t\t\t\tbender.next( event.results );\n\t\t\t} );\n\n\t\t\t// handle a single test run\n\t\t\tif ( window.location.hash ) {\n\t\t\t\thandleSingleTest( tests );\n\t\t\t}\n\n\t\t\ttests.name = tests.name ? tests.name : bender.testData.id;\n\t\t\ttests.fullName = tests.name;\n\t\t\ttests.module = tests.name;\n\n\t\t\tbender.testCase = buildSuite( tests );\n\n\t\t\trunner.add( bender.testCase );\n\t\t\trunner.run();\n\t\t}", "_goNextStep() {\n if (this.nextStep) {\n this.nextStep.start();\n }\n }", "function runNextTestCase() {\n if (resumeFunctionRegistrationID != -1) {\n \n // Execute the test\n \n if (!getDebugMode()) { \n // Continue executing the test\n try {\n var testCase = testCases[currentTestCase];\n testCase.generate();\n var nextStep = registeredFunctions[resumeFunctionRegistrationID];\n nextStep();\n } catch (ex) {\n fail(ex);\n } finally {\n waitForTestCase();\n }\n }\n else {\n // Continue executing the test\n try {\n var testCase = testCases[currentTestCase];\n testCase.generate();\n var nextStep = registeredFunctions[resumeFunctionRegistrationID];\n nextStep();\n } \n finally {\n waitForTestCase();\n }\n }\n \n \n } else if (currentTestCase + 1 < testCases.length && testCases.length > 0) {\n // Get the next Test Case\n currentTestCase++;\n var testCase = testCases[currentTestCase];\n \n // Create report elements for this Test Case\n testInterface.startTestCase(testCase);\n \n // Execute the test\n if (!getDebugMode()) { \n try {\n // Start the TestCase and keep checking until it's finished\n testCase.execute();\n } catch (ex) {\n // Report any error\n fail(ex);\n } finally {\n waitForTestCase();\n }\n }\n else {\n try {\n // Start the TestCase and keep checking until it's finished\n testCase.execute();\n } finally {\n waitForTestCase();\n }\n }\n \n } else {\n currentTestCase = -1;\n \n // Update the report status when the entire Test Suite is finsihed\n testInterface.finishTestSuite();\n \n // Start running the next Test Suite\n runNextTestSuite();\n }\n }", "function nextStep() {\n step++;\n document.location.href = document.location.href.substring(0, document.location.href.length-2) + (\"0\" + step).slice(-2);\n}", "function startNewTest() {\n clearPage();\n clearTests();\n generateTests();\n highlightActiveInput();\n}", "function nextTest() {\n // Maximum parallel tests running\n if (_running >= _cli.parallel) return;\n\n _test_index++;\n\n // No more tests left to run\n if (_test_index >= suite_data.tests.length) return;\n\n // Start the next test in the queue\n var test_data = suite_data.tests[_test_index];\n\n _running++;\n _test_controller.run(test_data, completeTest);\n\n // Add more tests until max running tests\n nextTest();\n }", "function navigateCompetitiveBenchmarkTrial () {\n pubURLService.navigate(\"/benchmark\");\n\n }", "function showResultPage() {\n if (console.log('test completed')) {\n\n //log \"time/score\" to High Scores page//\n\n //Automatically open High Scores HTML//\n\n }\n}", "function start_test_button() {\n if (chaptersDoneNum == 6)\n {\n location.href = \"realtest.html\";\n }\n}", "nextTourStep() {\n\t\tif(this.state.tourRunning) {\n\t\t\tthis.joyride.next();\n\t\t}\n\t}", "gotoNextPage() {\n apiCall('GET', this.state.nextPageUrl).then(this.onTracksLoaded);\n }", "function runNextTest(){\n // Loop through tests\n for(var x = 0; x < tests.length; x++){\n // check if test hasn't been started yet\n if(!tests[x].started){\n tests[x].started = true;\n runTest(tests[x]);\n\n // Stop the looping\n return;\n }\n }\n\n // At this point all tests have been done and batch results need to be finished\n validateBatchData();\n}", "function next() {\n\t\tvar nextStep = steps.next();\n\t\tsetSteps(steps);\n\t\tsetCurrent(nextStep);\n\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Adds Station Names to the Loc/Dest Menus
function addStationNames(){ var stations = getWMATAStations(getStationID); }
[ "function setEventsToSpaceUnitNamesOptions () {\n\n let menu = _('spatial-name-options');\n\n // adding for each menu option the invocation of names and the display event for each spatial unit\n Array.from(menu.children).forEach(function(item){\n\n item.addEventListener(CLICK_EVENT, function(e){\n\n // validating that the option name corresponds to the names of the selected spatial units (localities)\n if(item.textContent.toString().endsWith(SUN_LOCALITIES)) {\n \n if (getIdLayer(ID_NAMES_LAYER_LCL) != undefined) {\n \n let visibility = getLayoutProperty(ID_NAMES_LAYER_LCL, 'visibility');\n if (visibility == 'visible') {\n\n // changing the option status\n item.textContent = item.textContent.toString().replace('Hide', 'Show');\n setLayoutProperty (ID_NAMES_LAYER_LCL, 'visibility', 'none');\n activeSpatialUnitName = undefined;\n\n } else if (visibility == 'none') {\n\n // changing the option status\n item.textContent = item.textContent.toString().replace('Show', 'Hide');\n setLayoutProperty (ID_NAMES_LAYER_LCL, 'visibility', 'visible');\n hideDeafaultSpatialLayerByMenuOption (ID_NAMES_LAYER_LCL, item.textContent, _('spatial-name-options'), activeSpatialUnitName);\n activeSpatialUnitName = ID_NAMES_LAYER_LCL;\n \n }\n }\n // validating that the option name corresponds to the names of the selected spatial units (upz)\n } else if (item.textContent.toString().endsWith(SUN_UPZ) ) {\n\n if (getIdLayer(ID_NAMES_LAYER_UPZ) != undefined) {\n \n let visibility = getLayoutProperty(ID_NAMES_LAYER_UPZ, 'visibility');\n if (visibility == 'visible') {\n\n // changing the option status\n item.textContent = item.textContent.toString().replace('Hide', 'Show');\n setLayoutProperty (ID_NAMES_LAYER_UPZ, 'visibility', 'none');\n activeSpatialUnitName = undefined;\n \n\n } else if (visibility == 'none') {\n\n // changing the option status\n item.textContent = item.textContent.toString().replace('Show', 'Hide');\n setLayoutProperty (ID_NAMES_LAYER_UPZ, 'visibility', 'visible');\n hideDeafaultSpatialLayerByMenuOption (ID_NAMES_LAYER_UPZ, item.textContent, _('spatial-name-options'), activeSpatialUnitName);\n activeSpatialUnitName = ID_NAMES_LAYER_UPZ;\n }\n }\n // validating that the option name corresponds to the names of the selected spatial units (zonas catastrales)\n } else if (item.textContent.toString().endsWith(SUN_CAT_ZONE)) {\n\n if (getIdLayer(ID_NAMES_LAYER_ZC) != undefined) {\n \n let visibility = getLayoutProperty(ID_NAMES_LAYER_ZC, 'visibility');\n if (visibility == 'visible') {\n \n // changing the option status\n item.textContent = item.textContent.toString().replace('Hide', 'Show');\n setLayoutProperty (ID_NAMES_LAYER_ZC, 'visibility', 'none');\n activeSpatialUnitName = undefined;\n\n } else if (visibility == 'none') {\n \n // changing the option status\n item.textContent = item.textContent.toString().replace('Show', 'Hide');\n setLayoutProperty (ID_NAMES_LAYER_ZC, 'visibility', 'visible');\n hideDeafaultSpatialLayerByMenuOption (ID_NAMES_LAYER_ZC, item.textContent, _('spatial-name-options'), activeSpatialUnitName);\n activeSpatialUnitName = ID_BORDER_LAYER_ZC;\n }\n }\n\n }\n \n });\n\n });\n\n}", "function displayStations(stations) {\n $station.empty();\n const stationsArr = stations.data.stations;\n const selected = '<option value=\"\" selected>Choose...</option>';\n $station.append(selected);\n stationsArr.forEach(station => {\n const option = `<option value=\"${station.station_name}\">${station.station_name}</option>`;\n $station.append(option);\n });\n}", "function addLocationsToStates() {\n $.each(locations, function(i,loc) {\n var state= getState(loc.state);\n if (!state) return;\n \n loc.full_state= state.name;\n loc.displayed= true;\n loc.selected= false;\n \n if (state.locations) state.locations.push(loc);\n else state.locations= [ loc ];\n });\n }", "function addLocationsToPanel(locations) {\n\t\tvar nodeOL = document.createElement('ul'),\n\t\t\ti;\n\n\t\tnodeOL.style.fontSize = 'small';\n\t\tnodeOL.style.marginLeft = '5%';\n\t\tnodeOL.style.marginRight = '5%';\n\n\t\tfor (i = 0; i < locations.length; i += 1) {\n\t\t\tlet location = locations[i];\n\t\t\tvar li = document.createElement('li'),\n\t\t\t\tdivLabel = document.createElement('div'),\n\t\t\t\taddress = location.address,\n\t\t\t\tcontent =\n\t\t\t\t\t'<strong style=\"font-size: large;\">' +\n\t\t\t\t\taddress.label +\n\t\t\t\t\t'</strong></br>';\n\t\t\tposition = location.position;\n\n\t\t\tcontent +=\n\t\t\t\t'<strong>houseNumber:</strong> ' + address.houseNumber + '<br/>';\n\t\t\tcontent += '<strong>street:</strong> ' + address.street + '<br/>';\n\t\t\tcontent += '<strong>district:</strong> ' + address.district + '<br/>';\n\t\t\tcontent += '<strong>city:</strong> ' + address.city + '<br/>';\n\t\t\tcontent += '<strong>postalCode:</strong> ' + address.postalCode + '<br/>';\n\t\t\tcontent += '<strong>county:</strong> ' + address.county + '<br/>';\n\t\t\tcontent += '<strong>country:</strong> ' + address.countryName + '<br/>';\n\t\t\tcontent +=\n\t\t\t\t'<strong>position:</strong> ' +\n\t\t\t\tMath.abs(position.lat.toFixed(4)) +\n\t\t\t\t(position.lat > 0 ? 'N' : 'S') +\n\t\t\t\t' ' +\n\t\t\t\tMath.abs(position.lng.toFixed(4)) +\n\t\t\t\t(position.lng > 0 ? 'E' : 'W') +\n\t\t\t\t'<br/>';\n\n\t\t\tdivLabel.innerHTML = content;\n\t\t\tli.appendChild(divLabel);\n\n\t\t\tnodeOL.appendChild(li);\n\t\t}\n\n\t\t$('#outputDirections').append(nodeOL);\n\t}", "function updateStationSelectText(stations) {\n const stationsSelectElem = $('#stations-dropdown-menu');\n if (stationsSelectElem) {\n if ( !!stations.stationId) {\n stationsSelectElem.data('value',`${stations.stationId},${stations.stationName}`);\n stationsSelectElem.text(`${stations.stationName} - (${stations.stationId})`);\n }\n }\n }", "function addLocation() {\n // Hide the dialog\n toggleAddDialog();\n Object.keys(weatherApp.selectedLocations).forEach((key) => {\n const location = weatherApp.selectedLocations[key];\n // Save the updated list of selected cities.\n saveLocationList(location);\n });\n}", "_udpate_location_submenu(){\n let tsm= this._submenuPlaces;\n\n /** fetchs the current value of 'displayMode' option */\n let displayMode= SETTINGS.get_int('target-display-mode');\n\n /** clear the location list, dynamically fetches the value, and fills\n * back the menu*/\n tsm.clearAllLocations();\n this._updateGroupsAndCountries();\n this._fill_country_submenu_b(displayMode);\n tsm.select_from_name(tsm.LastSelectedPlaceName);\n\n /** update the styles of the 'recentLocations' menu's items */\n this._update_recent_location_submenu(displayMode);\n }", "function appendStation(stationId) {\n\tvar key = 'email&' + $('#login_username').val();\n\tvar stationFound = false;\n\tif (key in ls) {\n\t\tvar query = ls.getItem(key);\n\n\t\tvar stns = query.split(\"$\")[1].split(\"!\");\n\t\tfor (var i = 0; i < stns.length; i++) {\n\t\t\tvar pair = stns[i].split(\" \");\n\t\t\tif (pair[1] == stationId) {\n\t\t\t\t//stationOps='<option value=\"'+pair[1]+'\" selected >'+stns[i]+'</option>';\n\t\t\t\tstationFound = true;\n\t\t\t}\n\t\t}\n\t\tif (!stationFound) {\n\t\t\t//////ADD STATION NAME\n\t\t\tquery = query + \"!\" + stationId;\n\t\t}\n\t} else {\n\n\t}\n}", "function load_saved_stations() {\n\t\tvar saved_list = new UI.Menu({\n\t\t\thighlightBackgroundColor: config('selection-color', 'cadetBlue'),\n\t\t\tsections: [{\n\t\t\t\ttitle: (config('buses-first') ? 'Buses' : 'Trains'),\n\t\t\t\titems: [{ title: 'Loading...' }]\n\t\t\t}, {\n\t\t\t\ttitle: (config('buses-first') ? 'Trains' : 'Buses'),\n\t\t\t\titems: [{ title: 'Loading...' }]\n\t\t\t}]\n\t\t});\n\t\tsaved_list.show();\n\n\t\tvar saved_stations;\n\t\ttry {\n\t\t\tsaved_stations = JSON.parse(config('saved-rail', '[]'));\n\t\t} catch (e) {\n\t\t\tsaved_stations = [];\n\t\t}\n\n\t\tif (saved_stations !== undefined && saved_stations.length > 0) {\n\t\t\tfor (var t in saved_stations) {\n\t\t\t\tvar station = saved_stations[t];\n\t\t\t\tsaved_list.item((config('buses-first') ? 1 : 0), t, {\n\t\t\t\t\ttitle: station.Name,\n\t\t\t\t\tsubtitle: Helpers.concat_rail(station, true).join(', '),\n\t\t\t\t\tinfo: station // stash station info in menu element to use on select/long press\n\t\t\t\t});\n\t\t\t}\n\t\t} else {\n\t\t\tsaved_list.item((config('buses-first') ? 1 : 0), 0, { title: 'None saved' });\n\t\t}\n\n\t\tvar saved_stops;\n\t\ttry {\n\t\t\tsaved_stops = JSON.parse(config('saved-bus', '[]'));\n\t\t} catch (e) {\n\t\t\tsaved_stops = [];\n\t\t}\n\n\t\tif (saved_stops !== undefined && saved_stops.length > 0) {\n\t\t\tfor (var b in saved_stops) {\n\t\t\t\tvar stop = saved_stops[b];\n\t\t\t\tsaved_list.item((config('buses-first') ? 0 : 1), b, {\n\t\t\t\t\ttitle: Helpers.caps(stop.Name),\n\t\t\t\t\tsubtitle: Helpers.concat_bus(stop),\n\t\t\t\t\tinfo: stop\n\t\t\t\t});\n\t\t\t}\n\t\t} else {\n\t\t\tsaved_list.item((config('buses-first') ? 0 : 1), 0, { title: 'None saved' });\n\t\t}\n\n\t\tvar invalid_setting = (saved_stations === undefined && saved_stops === undefined);\n\t\tif ((!invalid_setting && saved_stations.length + saved_stops.length === 0) || invalid_setting) {\n\t\t\tvar card = new UI.Card({\n\t\t\t\ttitle: 'Nothing saved',\n\t\t\t\tbody: 'Use the Pebble app on your phone to add stations.'\n\t\t\t});\n\t\t\tsaved_list.hide();\n\t\t\tcard.show();\n\t\t}\n\n\t\tsaved_list.on('select', function (e) {\n\t\t\tif (e.item.hasOwnProperty('info')) {\n\t\t\t\tswitch (e.sectionIndex) {\n\t\t\t\t\tcase (config('buses-first') ? 1 : 0):\n\t\t\t\t\t\tload_trains(e.item.info);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase (config('buses-first') ? 0 : 1):\n\t\t\t\t\t\tload_buses(e.item.info);\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\n\t\tsaved_list.on('longSelect', function (e) {\n\t\t\tif (e.item.hasOwnProperty('info')) {\n\t\t\t\tswitch (e.sectionIndex) {\n\t\t\t\t\tcase (config('buses-first') ? 1 : 0):\n\t\t\t\t\t\tload_station_info(e.item.info);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase (config('buses-first') ? 0 : 1):\n\t\t\t\t\t\tload_bus_stop_info(e.item.info);\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t}", "function addstation(station, station_id)\n{\n\t$(\"#statname\").val(station);\n}", "function addLocationsForDirections(locations) {\n\n\tvar uniquelocations = [];\n\n\t// Iterates through the array of locations, adds to destination\n\tfor (var place in locations) {\n\t if ($.inArray(locations[place], uniquelocations) <0) {\n\t // add place to uniquelocations\n\t uniquelocations.push(locations[place]);\n\t $(\"select#start\").append(\"<option value=\\\"\"+locations[place]+\"\\\">\"+locations[place]+\"</option>\")\n\t $(\"select#end\").append(\"<option value=\\\"\"+locations[place]+\"\\\">\"+locations[place]+\"</option>\")\n\t }\n\t}\n\n}", "function addStation(title) {\n\t\t\t\t//add in the title to well...create station and then...\n\t\t\t\t//add in the title //add the #station\n\t\t\t\tvar x = \"<div class=\\\"group\\\" title =\\\"station_\"+ title +\"\\\"><h3><a href= \\\"#\\\">\"+ title +\"</a></h3><div><p>You need to add some sections!<\\/p></div></div>\";\n\t\t\t\t//var $title_name = $('<h3>').append($('<a>').attr('href','#').html(title));\n\t\t\t\t//var $content = $('<div>').append($('<p>').html(\"Hello\"));\n\t\t\t\t//add the station name to the section add dialog box\n\t\t\t\t$(\"#add_section_dialog select\").append(\"<option value= \\\"\" + title + \"\\\">\"+ title +\"</option>\");\n\t\t\t\t$(\"#station\").append(x).accordion('destroy')\n\t\t\t\t\t.accordion({\n\t\t\t\t\t\tcollapsible: true,\n\t\t\t\t\t\theader: \"> div > h3\"\n\t\t\t\t\t})\n\t\t\t\t\t.sortable({\n\t\t\t\t\t\taxis: \"y\",\n\t\t\t\t\t\thandle: \"h3\",\n\t\t\t\t\t\tstop: function( event, ui ) \n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t// IE doesn't register the blur when sorting\n\t\t\t\t\t\t\t// so trigger focusout handlers to remove .ui-state-focus\n\t\t\t\t\t\t\tui.item.children( \"h3\" ).triggerHandler( \"focusout\" );\n\t\t\t\t\t\t}\n\t\t\t\t});\n\t\t}", "function addLocations(locations, currentLocation) {\n let dropdown = document.getElementById(\"location-dropdown\");\n locations.forEach(element => {\n let option = document.createElement(\"option\");\n option.text = element;\n if (element == currentLocation) {\n option.selected = true;\n }\n dropdown.add(option);\n });\n}", "function actionOnAddLocation() { // TODO: Fix this for when all locations listed\n\tlet isListed = true;\n\tlet location = new Location(this.game);\n\twhile (isListed) {\n\t\tlocation = new Location(this.game);\n\t\tisListed = checkLocationRepeat(location);\n\t}\n\tcurrentLocationList.push(location);\n\taddLocationText(location);\n}", "function stations () {\n var stations = \"All Stations\";\n}", "function populate_station_select (zone) {\n /* which station list should we use? */\n switch (zone) {\n case 'national': stations = national_stations; break;\n case 'regional': stations = regional_stations; break;\n case 'local': stations = local_stations; break;\n default: stations = [];\n }\n\n /* empty the current contents of the select list */\n $(\"#select_station_list\").empty();\n\n /* add the new list */\n for (i = 0; i < stations.length; i++) {\n station = stations[i];\n $('#select_station_list').append($('<option>', {value: station['id'], text: station['display_name']}));\n }\n}", "function append_stations(){\n //get stations ordered by line number\n var arrByLine = db.filter(getStationsByLine);\n alert(JSON.stringify(arrByLine));\n \n //append Line name to the dropdown menue\n $('#from, #to')\n .append($('<optgroup>')\n .attr(\"label\",arrByLine[0].Line)\n .text(arrByLine[0].Line)); \n line_num++;\n // var output=\"<ul>\";\n for (var i=0;i<arrByLine.length;i++) {\n if(i>0 && arrByLine[i].Line>arrByLine[i-1].Line){\n $('#from, #to')\n .append($('<optgroup>')\n .attr(\"label\",arrByLine[i].Line)\n .text(arrByLine[i].Line)); \n line_num++;\n }\n \n //append stations to the dropdown menue\n $('#from, #to')\n .append($(\"<option></option>\")\n .attr(\"value\",arrByLine[i].station_name)\n .text(arrByLine[i].station_name)); \n\n //output+=\"<li>\" + db[i].station_ID + \"//\" + db[i].station_name+ \"//\" + db[i].Line+ \"//\"+db[i].position_x+ \"//\"+db[i].position_y+ \"//\"+db[i].Latitude+ \" \"+db[i].Longitude+\"</li>\";\n }\n \n // output+=\"</ul>\";\n // var arrByID = data.station.filter(getStationByID);\n // alert(JSON.stringify(arrByID));\n // document.getElementById(\"placeholder\").innerHTML=output;\n}", "_fill_country_submenu(){\n /** get the country name list by calling the private method '_get_countries_list()' */\n let country_list= this. _get_countries_list();\n let tsm= this._submenu;\n\n /** foreach element in this list, it is added as an item to the submenu */\n country_list.forEach(function(elmt){\n /** using the 'PlacesMenu' object's method 'addPlace' to add this country name to\n * this submenu */\n tsm.add_place(elmt);\n });\n }", "function fillPlacesNames() {\n for(var i = 0; i < places.length; i++) {\n var current = places[i];\n var option = $('<option></option>').text(current);\n $(\"#places-list\").append(option);\n }\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Convert the JSON to investment objects
importJson(toImportJson) { if(!("investments" in toImportJson)) return false; // Look for the investments key, put it as investment objects var tempInvestments = {}; var investmentsJson = toImportJson["investments"]; for(var i = 0; i < investmentsJson.length; i++) { try { var investment = Investment.jsonToObject(investmentsJson[i]); tempInvestments[investment.properties["projectId"]] = investment; } catch(err) { console.log(err); return false; } } this.investments = tempInvestments; this.persist(); return true; }
[ "static jsonToObject(json) { \n var investment = new Investment(\n json[\"projectId\"],\n json[\"investmentAmount\"],\n json[\"netInterestRate\"],\n MyDate.jsonToObject(json[\"date\"]),\n json[\"repaymentMethod\"],\n json[\"tenure\"],\n json[\"status\"]\n );\n\t\t\n return investment;\n }", "static jsonToObject(json) {\n // Migratory code because we just added status\n if(!(\"status\" in json))\n json[\"status\"] = \"Invested\";\n \n var investment = new Investment(\n json[\"projectId\"],\n json[\"investmentAmount\"],\n json[\"grossInterestRate\"],\n MyDate.jsonToObject(json[\"date\"]),\n json[\"repaymentMethod\"],\n json[\"tenure\"],\n json[\"status\"]\n );\n\n investment.properties[\"projectUrl\"] = json[\"projectUrl\"];\n investment.properties[\"issuer\"] = json[\"issuer\"];\n\n return investment;\n }", "jsonToModelMap(jsonData) {\n const transactions = [];\n if (jsonData.length > 0) {\n jsonData.map(t => {\n const tempTran = new Transaction();\n const tempTramAmnt = new TransactionAmount();\n tempTran.setDate(new Date(t.date));\n tempTran.setUserId(t.user_id);\n tempTran.setUserType(t.user_type);\n tempTran.setTransactionType(t.type);\n tempTramAmnt.setAmount(t.operation.amount);\n tempTramAmnt.setCurrency(t.operation.currency);\n tempTran.setOperation(tempTramAmnt);\n transactions.push(tempTran);\n });\n }\n return transactions;\n }", "function populateArray(jsonData) {\n // Create an array populated with expense data\n let expenseArray = JSON.parse(jsonData);\n\n // Cycle through data and put it in our array\n for (i = 0; i < expenseArray.expenditures.length; i++) {\n // Get each object in the array\n let expense = expenseArray.expenditures[i];\n expenditureArray[i] = expense;\n }\n}", "parseUpcomingTransactions(JSONobj) {\n try {\n this.UpcomingTransactions = JSON.parse(JSONobj, (key, value) => {\n if (typeof value === 'string') {\n if (/^[\\d_]+n$/.test(value)) {\n return BigInt(value.substr(0, value.length - 1).replace(/_/g, ''));\n }\n if (/^0[xX][\\da-fA-F_]+n$/.test(value)) {\n return BigInt(value.substr(0, value.length - 1).replace(/_/g, ''));\n }\n if (key === 'blockheight') {\n return Number(value);\n }\n if (key === 'sender' || key === 'recipient' || key === 'amount') {\n return BigInt(value.replace(/_/g, ''));\n }\n }\n return value;\n });\n }\n catch (error) {\n return \"Could not parse transactions JSON text. Atention on ','!!! \" + error;\n }\n return '';\n }", "function parser(arr){\n // Fields to be parsed: \"originalInvestment\", \"valueToday\"\n // YOUR CODE HERE\n return arr.map(function(investment){\n investment.originalInvestment = Number(investment.originalInvestment);\n investment.valueToday = Number(investment.valueToday);\n return investment;\n })\n}", "storageEventBackToObject(jsonObject){\n let eventObjects = []\n //Need to convert JSON OBJECT to a \n jsonObject.forEach(function(event){\n let eventObject = new Event(event._title, event._eventDate)\n \n console.log(eventObject)\n eventObjects.push(eventObject)\n })\n return eventObjects\n \n }", "parseJSONtoModel(inputJSON) {\n if (inputJSON === undefined || inputJSON['data'] === undefined) {\n return;\n }\n const entrances = inputJSON['data'].reduce((acc, item, idx) => {\n const thisLongitude = item['geometry']['coordinates'][0];\n const thisLatitude = item['geometry']['coordinates'][1];\n const thisStatus = item['status'];\n return acc.concat(\n new PedwayEntrance(new PedwayCoordinate(\n thisLatitude,\n thisLongitude), thisStatus,\n false,\n 'Entrance #'+idx.toString()));\n }, []);\n this.setState({\n pedwayEntrances: entrances,\n });\n }", "function fromJson(obj) {\n var res = new ShipPlacements();\n for (var key in obj) {\n var stuff = indexUtils.toRowColOrientation(obj[key]);\n var row = stuff[0];\n var col = stuff[1];\n var orientation = stuff[2];\n res.placeShip(key, row, col, orientation);\n }\n return res;\n}", "function jsonToCart(json) {\n var newCart = new Cart();\n if (json && json.hasOwnProperty(\"items\")) {\n var items = json[\"items\"];\n for (var item in items) {\n newCart.add(item, items[item]);\n }\n }\n return newCart;\n}", "function parseJson() {\n var jsonObjArr = JSON.parse(jsonData);\n var initialName;\n var day;\n var age;\n jsonObjArr.map(function (obj) {\n initialName = findInitialsFromName(obj.name);\n day = getDate(obj.birthday);\n age = getAge(obj.birthday);\n if(finalObject[day] === undefined) {\n finalObject[day] = [[initialName, age]];\n } else {\n finalObject[day].push([initialName, age]);\n }\n return obj;\n });\n }", "function prepareSaleJson(action) {\n\tvar result = new Object();\n\n\t/** Overall invoice data * */\n\tresult.invoice = new Object();\n\t//result.invoice.invoice_no = $(\"#invoice-no\").val();\n\t//result.invoice.invoice_date = convert2outputDt($(\"#date\").text());\n\t//result.invoice.inter_state = $(\"#interstate\").is(\":checked\") ? \"y\" : \"n\";\n\t//result.invoice.cform = $(\"#cform\").is(\":checked\") ? \"y\" : \"n\";\n\t//result.invoice.sub_total = $(\"#base-total\").text();\n\t//result.invoice.additional = $(\"#addnl-charges input\").val();\n\t//result.invoice.round_off_disc = $(\"#roundoff input\").val();\n\tresult.invoice.final_total = $(\"#tot_mrp\").text();\n\t//result.invoice.payment_mode = $(\"#payment-type\").val();\n\n\t// specifies the action on the invoice , save , update or reject the invocie\n\tresult.invoice.action = action;\n /** customer data * */\n\tresult.executivedetails = new Object();\n\tresult.customer = new Object();\n\tresult.salesled = new Object();\n\tresult.company = $.cookie(\"companydb\");\n\tresult.executivedetails.isexecutive = $.cookie(\"isexecutive\");\n\tresult.executivedetails.name = $.cookie(\"loginname\");\n\tresult.customer.name = $(\"#cust-name\").val();\n\tresult.customer.notes = $(\"#notes\").val();\n\tvar pricelevel = $(\"#price-level\").val();\n\tif($(\"#price-level\").val() == \"\" || $(\"#price-level\").val() == null){\n\t\tpricelevel = $(\"#price-level-combo option:selected\").text()\n\t}\n\tresult.customer.pricelevel = pricelevel;\n\t/** items listing * */\n\tresult.items = [];\n\t$(\"#item-details tbody tr\").each(function() {\n\n\t\t// skipping empty rows\n\t\tif ($(this).data(\"item-info\")) {\n\n\t\t\tvar item = new Object();\n\n\t\t\titem.item_id = $(this).data(\"item-info\").id;\n\t\t\titem.name = $(this).data(\"item-info\").value;\n\t\t\titem.qty = $(this).find(\"td.qty input\").val();\n\t\t\titem.rate = $(this).data(\"item-info\").rate;\n\t\t\titem.disc_percent = parseFloat($(this).find(\"td.disc\").text());\n\t\t\titem.amount = $(this).find(\"td.amount\").text();\n\t\t\titem.dsc_p = $(this).data(\"item-info\").discnt_percent;\n\t\t\titem.vat_p = $(this).data(\"item-info\").vat;\n\t\t\titem.category = $(this).data(\"item-info\").catid;\n\t\t\titem.unit = $(this).data(\"item-info\").units;\n\t\t\tresult.items.push(item);\n\t\t}\n\t});\n\tconsole.log(\"Save Button \"+JSON.stringify(result));\n\treturn result;\n}", "function preparePurchaseJson(action) {\n\tvar result = new Object();\n\n\t/** Overall invoice data * */\n\tresult.invoice = new Object();\n\tresult.invoice.invoice_no = $(\"#invoice-no1\").val();\n\tresult.invoice.pur_inv_no = $(\"#pur-invoice-no\").val();\n\tresult.invoice.invoice_date = convert2outputDt($(\"#date\").text());\n\tresult.invoice.inter_state = $(\"#interstate\").is(\":checked\") ? \"y\" : \"n\";\n\tresult.invoice.cform = $(\"#cform\").is(\":checked\") ? \"y\" : \"n\";\n\tresult.invoice.sub_total = $(\"#base-total\").text();\n\tresult.invoice.additional = $(\"#addnl-charges input\").val();\n\tresult.invoice.round_off_disc = $(\"#roundoff input\").val();\n\tresult.invoice.final_total = $(\"#grand-total\").text();\n\tresult.invoice.payment_mode = $(\"#payment-type\").val();\n\n\tresult.invoice.pur_inv_date = convert2outputDt1($(\"#pur-invoice-date\")\n\t\t\t.val());\n\tresult.invoice.goods_received_date = convert2outputDt1($(\"#receipt-date\")\n\t\t\t.val());\n\n\t// specifies the action on the invoice , save , update or reject the invocie\n\tresult.invoice.action = action;\n\n\t/** customer data * */\n\tresult.customer = new Object();\n\t// Get the customer id, if a seletion was made from typeahead suggestions.\n\tif ($(\"#cust-name\").data(\"customer\") != undefined) {\n\t\tvar customer_info = $(\"#cust-name\").data(\"customer\");\n\t\tresult.customer.cust_id = customer_info.id;\n\t\tresult.customer.name = customer_info.name;\n\t\tresult.customer.phone = customer_info.phone1;\n\t} else {\n\t\tresult.customer.cust_id = -1;\n\t\tresult.customer.name = $(\"#cust-name\").val();\n\t\tresult.customer.phone = $(\"#cust-phone\").val();\n\t}\n\n\t/** items listing * */\n\tresult.items = [];\n\t$(\"#item-details tbody tr\").each(function() {\n\t\tvar item = new Object();\n\n\t\titem.item_id = $(this).data(\"item-info\").id;\n\t\titem.name = $(this).data(\"item-info\").name;\n\t\titem.qty = $(this).find(\"td.qty input\").val();\n\t\titem.rate = $(this).data(\"item-info\").rate;\n\t\titem.discount = $(this).find(\"td.disc-val\").text();\n\t\titem.amount = $(this).find(\"td.amount\").text();\n\t\titem.dsc_p = $(this).data(\"item-info\").discnt_percent;\n\t\titem.vat_p = $(this).data(\"item-info\").vat;\n\t\titem.category = $(this).data(\"item-info\").catid;\n\t\tresult.items.push(item);\n\t});\n\n\treturn result;\n}", "static restoreFromJson(jsonObj) {\n let task = new Task(jsonObj.name);\n task.state = jsonObj.state;\n task.creationDate = new Date(jsonObj.creationDate);\n if (jsonObj.dueDate) {\n task.dueDate = new Date(jsonObj.dueDate);\n }\n task.id = jsonObj.id;\n return task;\n }", "static fromJSON(participations) {\n let result = [];\n \n if (Array.isArray(participations)) {\n participations.forEach((p) => {\n Object.setPrototypeOf(p, ParticipationBO.prototype);\n result.push(p);\n })\n }\n // it's a single object and not an array\n else{\n let p = participations;\n Object.setPrototypeOf(p, ParticipationBO.prototype);\n result.push(p);\n }\n \n return result;\n }", "function toBank(json) {\r\n return cast(JSON.parse(json), a(r(\"Bank\")));\r\n}", "static jsonToObject(json) {\n return new MyDate(\n json[\"year\"],\n json[\"month\"],\n json[\"day\"]\n );\n }", "function mapJSONtoDepartmentArray(json) {\n return json.map((type) => {\n return new Department(type.id, type.name);\n });\n}", "function processRawInvestments (data, config) {\n const c = config.investments\n\n // The data contains data for funky years. Filter those out.\n // Exclude future years as well\n const cleanedData = data\n .filter(d => Number(d.year) > c.minYear && Number(d.year) <= c.maxYear)\n\n // Get the years with investment data across the dataset.\n // Not all countries have investments in all years.\n const years = [...cleanedData]\n .map(d => Number(d.year))\n .reduce((acc, b) => !acc.includes(b) ? acc.concat(b) : acc, [])\n .sort()\n\n return [...cleanedData]\n .reduce((acc, b) => {\n const year = Number(b.year)\n // Handle values like \"1,244.54\"\n const value = Number(b.value.replace(',', ''))\n const v = { year, value }\n\n let match = acc.find(o => o.geography === b.geography)\n if (!match) {\n return acc.concat({\n id: 'investment',\n subindicator: 'Investment',\n geography: b.geography,\n values: [v]\n })\n } else {\n // The input data can contain multiple investments for the same year,\n // sector, geography. Aggregate these.\n let yrMatch = match.values.find(v => v.year === year)\n\n if (yrMatch) {\n yrMatch.value += value\n } else {\n match.values = match.values.concat(v)\n }\n return acc\n }\n }, [])\n .map(geo => ({ ...geo, values: utils.fillMissingValues(geo.values, years) }))\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
ref string Required. The ref to deploy. This can be a branch, tag, or SHA. task string Specifies a task to execute (e.g., deploy or deploy:migrations). Default: deploy auto_merge boolean Attempts to automatically merge the default branch into the requested ref, if it's behind the default branch. Default: true required_contexts array The status contexts to verify against commit status checks. If you omit this parameter, GitHub verifies all unique contexts before creating a deployment. To bypass checking entirely, pass an empty array. Defaults to all unique contexts. payload string JSON payload with extra information about the deployment. Default: "" environment string Name for the target deployment environment (e.g., production, staging, qa). Default: production description string Short description of the deployment. Default: "" transient_environment boolean Specifies if the given environment is specific to the deployment and will no longer exist at some point in the future. Default: false Note: This parameter requires you to use the application/vnd.github.antmanpreview+json custom media type. production_environment boolean Specifies if the given environment is one that endusers directly interact with. Default: true when environment is production and false otherwise. Note: This parameter requires you to use the application/vnd.github.antmanpreview+json custom media type.
createDeployment (context, deploy) { const deployment = ApiGateway.toDeployment(deploy) deployment.environment = deploy.namespace return context.github.repos.createDeployment(deployment) }
[ "async function vercelDeploy({ project_id, env, meta: metaOptions }) {\n if (!project_id) {\n throw new Error('Missing `project_id` in vercelDeploy')\n }\n const meta = {\n // magic meta keys to simulate the vercel github integration\n githubCommitSha: GITHUB_SHA,\n githubDeployment: 1,\n githubOrg: GITHUB_ORG_NAME,\n githubCommitOrg: GITHUB_ORG_NAME,\n githubRepo: GITHUB_REPO,\n githubCommitRepo: GITHUB_REPO,\n githubCommitRef: GIT_BRANCH,\n githubCommitAuthorLogin: COMMIT_AUTHOR,\n githubCommitMessage: GIT_COMMIT_MSG,\n githubCommitAuthorName: COMMIT_AUTHOR_NAME,\n ...metaOptions\n }\n const command = `${cmd(project_id)} ${withEnv(env)} ${withMeta(meta)}`\n log(`${emoji} Running vercel deploy:`)\n log(command)\n return await exec(command)\n}", "async deploy() {\n // TODO: Update deployment URL\n // For more information visit http://gitolite.com/deploy.html\n const getRemote = slot => ({\n name: slot || 'production',\n url: `https://example${slot ? `-${slot}` : ''}.scm.azurewebsites.net:443/example.git`,\n website: `http://example${slot ? `-${slot}` : ''}.azurewebsites.net`,\n });\n // By default deploy to the staging deployment slot\n const remote = getRemote(process.argv.includes('--production') ? null : 'staging');\n\n // Initialize a new Git repository inside the `/build` folder\n // if it doesn't exist yet\n const repo = await GitRepo.open('build', { init: true });\n await repo.setRemote(remote.name, remote.url);\n\n // Fetch the remote repository if it exists\n if ((await repo.hasRef(remote.url, 'master'))) {\n await repo.fetch(remote.name);\n await repo.reset(`${remote.name}/master`, { hard: true });\n await repo.clean({ force: true });\n }\n\n // Build the project in RELEASE mode which\n // generates optimized and minimized bundles\n process.argv.push('--release');\n await run(require('./build'));\n\n // Push the contents of the build folder to the remote server via Git\n await repo.add('--all .');\n await repo.commit('Update');\n await repo.push(remote.name, 'master');\n\n // Check if the site was successfully deployed\n const response = await fetch(remote.website);\n console.log(`${remote.website} -> ${response.statusCode}`);\n }", "deploy() {\n // TODO(bryk): Validate input data before sending to the server.\n\n /** @type {!backendApi.AppDeployment} */\n let deployAppConfig = {\n containerImage: this.containerImage,\n isExternal: this.isExternal,\n name: this.name,\n portMappings: this.portMappings.filter(this.isPortMappingEmpty_),\n replicas: this.replicas,\n };\n\n this.isDeployInProgress_ = true;\n this.resource_.save(\n deployAppConfig,\n (savedConfig) => {\n this.isDeployInProgress_ = false;\n this.log_.info('Successfully deployed application: ', savedConfig);\n this.state_.go('servicelist');\n },\n (err) => {\n this.isDeployInProgress_ = false;\n this.log_.error('Error deploying application:', err);\n });\n }", "async function createDeployment(environment) {\n log(`${emoji} Creating Github Deployment for ${environment}`)\n try {\n const options = {\n environment,\n owner: GITHUB_ORG_NAME,\n repo: GITHUB_REPO,\n ref: GITHUB_SHA,\n transient_environment: !isProd,\n production_environment: isProd,\n auto_merge: false,\n required_contexts: []\n }\n log('with options', options)\n const { data } = await octokit.repos.createDeployment(options)\n // try again?\n if (!data.id && data.message) {\n return createDeployment(environment)\n }\n log(data)\n return data.id\n } catch (err) {\n log(err)\n throw new Error('Error creating Github Deployment:', err)\n }\n}", "function serviceDeploy(environment, fn) {\n return async (...args) => {\n let deployment_id;\n try {\n deployment_id = await createDeployment(\n `${environment} - ${isProd ? 'Production' : 'Preview'}`\n )\n const url = await fn(...args)\n await updateDeployment({\n deployment_id,\n state: 'success',\n url\n })\n return url\n } catch (err) {\n log(err)\n if (deployment_id) {\n await updateDeployment({\n deployment_id,\n state: 'failure'\n })\n }\n throw err\n }\n }\n}", "async deploy(req, resp) {\n\n\t\tconst version = req.params.version;\n\t\tconst app = req.params.app;\n\t\tconst deploymentResponse = await this._executeWithValidation(req, async () => {\n\n\t\t\tlet deploymentResponse;\n\t\t\tif (version) {\n\t\t\t\tdeploymentResponse = await this._deploymentService.deploy(app, version);\n\t\t\t} else {\n\t\t\t\tdeploymentResponse = await this._deploymentService.deployLatest(app);\n\t\t\t}\n\n\t\t\treturn deploymentResponse;\n\t\t}, (response) => response);\n\n\t\tresp.status(this.mapDeploymentStatusToStatusCode(deploymentResponse.status))\n\t\t\t.send(this._generateDeployResponse(req, deploymentResponse));\n\t}", "function deploy() {\n const properties = PropertiesService.getScriptProperties()\n const version = newVersion_()\n \n const deploymentId = properties.getProperty(DEPLOYMENT_ID_KEY)\n if (!deploymentId) {\n console.log(`Creating new deployment to version ${version.versionNumber}`)\n const deployment = newDeploy_(version.versionNumber)\n properties.setProperty(DEPLOYMENT_ID_KEY, deployment.deploymentId)\n } else {\n console.log(`Updating deployment to version ${version.versionNumber}`)\n updateDeploy_(deploymentId, version.versionNumber)\n }\n}", "function createDeployer({ got, fs, FormData }) {\n\n /**\n * Deploy diagram to the given endpoint URL.\n */\n return function deploy(url, { deploymentName, tenantId, file = {} }, cb) {\n\n // callback is optional\n cb = cb || noop;\n\n if (!deploymentName) {\n return cb(\n new Error(\n 'Failed to deploy process, deployment name must be provided.'\n )\n );\n }\n\n if (!file.fileType || !file.name || !file.path) {\n return cb(\n new Error(\n 'Failed to deploy process, file name and path must be provided.'\n )\n );\n }\n\n if (!url) {\n return cb(\n new Error(\n 'Failed to deploy process, endpoint url must not be empty.'\n )\n );\n }\n\n const form = new FormData();\n\n form.append('deployment-name', deploymentName);\n\n if (tenantId) {\n form.append('tenant-id', tenantId);\n }\n\n form.append(file.name, fs.createReadStream(file.path));\n\n got.post(url, {\n body: form\n }).then(function(response) {\n cb(null, response.body);\n }).catch(function(error) {\n cb(error);\n });\n };\n}", "async function updateDeployment({\n deployment_id,\n state = 'success',\n url\n}) {\n if (!deployment_id) {\n throw new Error('Missing deployment_id in updateDeployment')\n }\n log(`${emoji} Updating Github Deployment for ${deployment_id}`)\n try {\n const options = {\n owner: GITHUB_ORG_NAME,\n repo: GITHUB_REPO,\n auto_inactive: false,\n deployment_id,\n state,\n environment_url: url,\n target_url: url\n }\n log('with options', options)\n const { data } = await octokit.repos.createDeploymentStatus(options)\n log(data)\n } catch (err) {\n log(err)\n throw new Error('Cannot update deployment:', err)\n }\n}", "flyGitHubPrep() {\n const deploy = fs.readFileSync('.github/workflows/deploy.yml', 'utf-8')\n\n if (!fs.existsSync('.git')) {\n console.log(`${chalk.bold.green('execute'.padStart(11))} git init`)\n execSync('git init', { stdio: 'inherit' })\n }\n\n if (deploy.includes('🚀 Deploy Staging') && deploy.includes('-staging')) {\n const stagingApp = `${this.flyApp}-staging`\n\n try {\n const apps = JSON.parse(\n execSync(`${this.flyctl} apps list --json`, { encoding: 'utf8' })\n )\n\n const base = apps.find(app => app.Name === this.flyApp)\n\n if (base && !apps.find(app => app.Name === stagingApp)) {\n const cmd = `apps create ${stagingApp} --org ${base.Organization.Slug}`\n console.log(`${chalk.bold.green('execute'.padStart(11))} flyctl ${cmd}`)\n execSync(`${this.flyctl} ${cmd}`, { stdio: 'inherit' })\n }\n } catch {\n return // likely got an error like \"Could not find App\"\n }\n\n // attach consul for litefs\n if (this.litefs) this.flyAttachConsul(stagingApp)\n\n // set secrets for remix apps\n if (this.remix) this.flyRemixSecrets(stagingApp)\n }\n }", "async function deploy() {\n log('Checking prerequisites...');\n try {\n const hasRelease = await execute('release -v', false);\n } catch(err) {\n\n }\n}", "function deploy(opts){\n\n return new Promise((resolve,reject)=>{\n\n\n let { args, apps, config } = options(opts);\n let completed = 0;\n let errors = [];\n\n console.log(\"\\n\",` DEPLOYING TO CLOUDFORMATION `.bgYellow.black,\"\\n\");\n\n let additionalParameters = \"\";\n\n if(config.template_parameters){\n Object.keys(config.template_parameters).forEach(key =>{\n if(config.template_parameters[key] && !['function','object','undefined'].includes(typeof config.template_parameters[key])){\n additionalParameters += ` ${key}=\"${config.template_parameters[key]}\"`;\n }\n })\n }\n\n apps.forEach(app=>{\n let stackName = `${config.project_name}-${app}-${args.environment}`.replace(/[\\W_]+/gi,'-').replace(/\\-$/gi,'');\n exec(`sam deploy --template-file ${config.base_path}${app ? '/'+app : ''}/packaged-${args.environment}.yaml --s3-bucket ${config.project_name} --s3-prefix ${args.environment}/${app} --stack-name ${stackName} --capabilities CAPABILITY_IAM --parameter-overrides Environment=${args.environment} ProjectName=${config.project_name + additionalParameters}`,\n async (error, stdout, stderr) => {\n\n if (error !== null) {\n console.log(` ✖ ${app} `.red);\n errors.push({app,error,stderr});\n }else{\n console.log(` ✔ ${app} `.green);\n let stack = await getStack(stackName);\n console.log(stack.Outputs);\n }\n\n completed++;\n\n // ON FINISH\n if(completed == apps.length){\n onCompleted({ errors, args, apps });\n resolve(errors);\n }\n\n }) // <---- Exec end\n }) // <---- For each end\n }) // <---- Promise end\n} // <---- deploy() end", "function deployApp(url, commits, repo) {\n return rp({\n method: 'POST',\n // TODO: Configure the `slack.webhook_url` Google Cloud environment variables.\n uri: 'https://ge-lab.org/api/deploy',\n body: {\n //text: `<${url}|${commits} new commit${commits > 1 ? 's' : ''}> pushed to <${repo.url}|${repo.full_name}>.`\n },\n json: true\n });\n}", "function deploy(req, res) {\n var stackName = req.params.stack,\n regionName = req.params.region,\n to = req.body.to_revision, user;\n\n dreadnot.deploy(stackName, regionName, to, req.remoteUser.name, function(err, number) {\n if (err) {\n res.respond(err);\n return;\n } else {\n res.redirect(sprintf('/stacks/%s/regions/%s/deployments/%s', stackName, regionName, number));\n }\n });\n }", "function deployToken(deployer){ //declare the deploytoken function\n return deployer.deploy(Token); //deploy token artifiact\n\n }", "function DoDeploy(payload) {\n self.deploy(payload.repo, function(err) {\n if (err) {\n return self.io.emit('deploy.error', payload);\n }\n self.io.emit('deploy.complete', payload);\n });\n }", "function triggerDeploy() {\n vm.changedFiles = {};\n vm.diff = '';\n deploymentsService.triggerJob('deploy', {\n deploymentId: vm.deployment.id,\n tasksToRun: vm.tasksToRun\n });\n }", "async function deploy() {\n const startDeployTime = new Date()\n\n // Initialize a new repository\n if (!fs.existsSync('build')) {\n fs.mkdirSync('build')\n }\n fs.cleardirSync('build', { ignore: ['.git'] })\n\n await cp.spawn('git', ['init', '--quiet'], options)\n\n // Changing a remote's URL\n let isRemoteExists = false\n try {\n await cp.spawn('git', ['config', '--get', `remote.${remote.name}.url`], options)\n isRemoteExists = true\n } catch (error) {\n /* skip */\n }\n await cp.spawn(\n 'git',\n ['remote', isRemoteExists ? 'set-url' : 'add', remote.name, remote.url],\n options\n )\n\n // Fetch the remote repository if it exists\n let isRefExists = false\n try {\n await cp.spawn(\n 'git',\n ['ls-remote', '--quiet', '--exit-code', remote.url, remote.branch],\n options\n )\n isRefExists = true\n } catch (error) {\n await cp.spawn('git', ['update-ref', '-d', 'HEAD'], options)\n }\n if (isRefExists) {\n await cp.spawn('git', ['fetch', remote.name], options)\n await cp.spawn('git', ['reset', `${remote.name}/${remote.branch}`, '--hard'], options)\n await cp.spawn('git', ['clean', '--force'], options)\n }\n\n // Build the project in RELEASE mode which\n // generates optimized and minimized bundles\n // await cp.spawn('gulp')\n fs.copydirSync('release', 'build')\n fs.copydirSync('sample', 'build')\n\n // Push the contents of the build folder to the remote server via Git\n await cp.spawn('git', ['add', '.', '--all'], options)\n try {\n await cp.spawn('git', ['diff', '--cached', '--exit-code', '--quiet'], options)\n } catch (error) {\n await cp.spawn(\n 'git',\n ['commit', '--message', `Update ${new Date().toLocaleString()}`],\n options\n )\n }\n await cp.spawn(\n 'git',\n ['push', remote.name, `master:${remote.branch}`, '--set-upstream'],\n options\n )\n\n opn(remote.website)\n const endDeployTime = new Date()\n console.log(`deploy success in ${(endDeployTime - startDeployTime)/1000} s.`)\n // Check if the site was successfully deployed\n console.info(`open => ${remote.website} `)\n\n}", "createDeploymentVariable(incomingOptions, cb) {\n const Bitbucket = require('./dist');\n\n let apiInstance = new Bitbucket.PipelinesApi(); // String | The account // String | The repository // String | The environment // String | The UUID of the variable to update // DeploymentVariable | The variable to create\n /*let username = \"username_example\";*/ /*let repoSlug = \"repoSlug_example\";*/ /*let environmentUuid = \"environmentUuid_example\";*/ /*let variableUuid = \"variableUuid_example\";*/ /*let body = new Bitbucket.DeploymentVariable();*/ apiInstance.createDeploymentVariable(\n incomingOptions.username,\n incomingOptions.repoSlug,\n incomingOptions.environmentUuid,\n incomingOptions.variableUuid,\n incomingOptions.body,\n (error, data, response) => {\n if (error) {\n cb(error, null, response);\n } else {\n cb(null, data, response);\n }\n }\n );\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This method takes data from the TIA object and uses it to draw the back buffer.
function prepareBackBuffer() { var zCurrentBuffer = jsvideo.getCurrentFrameBuffer(); var zPrevBuffer = jsvideo.getPreviousFrameBuffer(); if (residualColorBuffer == null) residualColorBuffer = new Array(zCurrentBuffer.length); //maybe a better way to set it var zWidth = Math.min(jsvideo.getWidth(), backBuffer.getWidth()); var zHeight = Math.min(jsvideo.getHeight(), backBuffer.getHeight()); var zBufferIndexAtLineStart = 0; for (var y = 0; y < zHeight; y++) { //for each line for (var x = 0; x < zWidth; x++) { //for each pixel on a given line var zBufferIndex = zBufferIndexAtLineStart + x; //determing the buffer index at this given x and y var zNewColorIndex = zCurrentBuffer[zBufferIndex]; var zOldColorIndex = zPrevBuffer[zBufferIndex]; //TODO : make the following code more "elegant", and self-explanatory var zOldPaintedColor = residualColorBuffer[zBufferIndex]; var zNewPaintedColor = usePhosphor ? getBlendedColorInt(zOldColorIndex, zNewColorIndex) : getColorInt(zNewColorIndex); if ((zNewPaintedColor != zOldPaintedColor) || (redrawTIAIndicator)) { // either the color has changed, or we have been ordered to draw it regardless clipRect.addPoint(x, y); // expands the clip rectangle, telling it there is another part of the screen in need of update residualColorBuffer[zBufferIndex] = zNewPaintedColor; if (backBufferData != null) backBufferData[zBufferIndex] = zNewPaintedColor; //a quicker way if available else backBuffer.setRGB(x, y, zNewPaintedColor); // the actual act of drawing } } zBufferIndexAtLineStart += zWidth; //moving to next line } redrawTIAIndicator = false; }
[ "function paint_back_buffer()\n {\n canvas_ctx.drawImage(canvas_back_elm, 0, 0);\n }", "function paintBackBufferToCanvas() {\n if (getCanvas() != null) {\n //Tells the canvas to call the paint command...the coordinates are very important...drawing the screen is incredibly slow, so you must only\n //draw a portion of it at a time. The portion that has changed is contained in clipRect\n //The calculations are there to scale, converting double into ints by rounding the correct direction\n getCanvas().paintCanvas(backBuffer, jsvideo.getWidth(), jsvideo.getHeight(), clipRect);\n\n clipRect.resetRect();\n }\n }", "function UpdateRender() {\r\n // Set background\r\n BackContextHandle.fillRect(0, 0, CanvasWidth, CanvasHeight);\r\n\r\n // RenderSquares\r\n BackContextHandle.save();\r\n RenderSquares();\r\n BackContextHandle.restore();\r\n\r\n // Swap the backbuffer with the frontbuffer\r\n var ImageData = BackContextHandle.getImageData(0, 0, CanvasWidth, CanvasHeight);\r\n ContextHandle.putImageData(ImageData, 0, 0);\r\n}", "renderDataBuffer( dataBuffer, dataMaterial )\n { \n \n // render data into copy texture\n gl.bindFramebuffer( gl.FRAMEBUFFER, this._rtCopyBuffer.fbo() );\n gl.clear( gl.COLOR_BUFFER_BIT );\n \n dataMaterial.apply(); \n this._screenQuadMesh.render(); \n \n // render copy texture into data texture\n gl.bindFramebuffer( gl.FRAMEBUFFER, dataBuffer );\n gl.clear( gl.COLOR_BUFFER_BIT );\n \n this._copyMaterial.apply(); \n this._screenQuadMesh.render(); \n }", "drawFromBuffer () {\n\t\tdisplaySystem.updateBufferFOV();\n\t\tdisplaySystem.updateBuffer();\n\n\t\tdisplay.clear();\n\t\tlogger.showMessages();\n\t\tfor (let i = 0; i < bufferOptions.width; i++) {\n\t\t\tfor (let j = 0; j < bufferOptions.height; j++) {\n\t\t\t\tlet pos = i + (j * bufferOptions.width);\n\n\t\t\t\t//draw separating line between game and log/information\n\t\t\t\tfor (let k = 0; k < bufferOptions.height; k++) {\n\t\t\t\t\tdisplay.draw(bufferOptions.width, k, \"|\", \"#ffffff\")\n\t\t\t\t}\n \t\t\t\t\n\t\t\t\t//idea: \"flipped mode\" where i and j are flipped as a status effect\n\t\t\t\tif (this.buffer[pos]) { display.draw(i, j, this.buffer[pos][0], this.buffer[pos][1], this.buffer[pos][2]);}\n\t\t\t\telse {display.draw(i,j,'','','#000000')}\n\n\t\t\t}\n\t\t}\n\t}", "function restoreDrawingSurface(){\n\tcontext.putImageData(imageData,0,0);\n\t}", "function drawData() {\n for (let i = 0; i < dirtyIndices.length; i++) {\n let color = canvasData[dirtyIndices[i]];\n colorBox(indexToRowAndColumn(dirtyIndices[i]), color);\n }\n // Reset the dirty Indices array for the next animation frame's update\n dirtyIndices = [];\n requestAnimationFrame(drawData);\n}", "function renderFrame(){\n var dst = Module.canvasData.data;\n if(dst.set){\n dst.set(renderFrameData);\n }else{\n for(var i = 0; i < renderFrameData.length; i++){\n dst[i] = renderFrameData[i];\n }\n }\n\n Module.ctx.putImageData(Module.canvasData, 0, 0);\n renderFrameData = null;\n }", "function renderFrame() {\n\t\tvar dst = Module.canvasData.data;\n\t\tif (dst.set) {\n\t\t\tdst.set(renderFrameData);\n\t\t} else {\n\t\t\tfor (var i = 0; i < renderFrameData.length; i++) {\n\t\t\t\tdst[i] = renderFrameData[i];\n\t\t\t}\n\t\t}\n\t\tModule.ctx.putImageData(Module.canvasData, 0, 0);\n\t\trenderFrameData = null;\n\t}", "drawToFrameBuffer(index) {\n gl.bindFramebuffer(gl.FRAMEBUFFER, this.framebuffer);\n gl.activeTexture(gl.TEXTURE0);\n gl.bindTexture(gl.TEXTURE_2D, this.texture);\n gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, this.texture, 0);\n\n gl.clear(gl.COLOR_BUFFER_BIT);\n\n gl.useProgram(this.programDisplay);\n gl.uniform1f(this.u_ParticleSize, params.particleSize); \n gl.uniformMatrix4fv(this.u_viewProjectionMatrix, false, this._viewProjectionMatrix); \n gl.bindVertexArray(this.displayVAOs[index]);\n gl.drawArrays(gl.POINTS, 0, this.totalParticles);\n gl.bindVertexArray(null);\n gl.bindFramebuffer(gl.FRAMEBUFFER, null);\n }", "function saveDrawingSurface() {\n drawingSurfaceImageData = context.getImageData(0, 0,canvas.width,canvas.height);\n }", "createBack() {\n this.back = document.createElement('canvas');\n this.back.width = Number(this.dataset.width);\n this.back.height = Number(this.dataset.width);\n this.backCtx = this.back.getContext('2d');\n this.backCtx.fillStyle = this.dataset.bg;\n this.backCtx.fillRect(0, 0, this.back.width, this.back.height);\n }", "backGraphics(graphicsToBack) {\n for (let i = 0; i < graphicsToBack.length; i++) {\n graphicsToBack[i].back(gameSpeed);\n }\n }", "renderDataBuffer( dataBuffer, dataMaterial, meshes, primitive = gl.TRIANGLES )\n {\n // render data into copy texture\n gl.bindFramebuffer( gl.FRAMEBUFFER, this._copyFbo.fbo() );\n gl.clear( gl.COLOR_BUFFER_BIT );\n\n dataMaterial.apply();\n for(var i = 0; i < meshes.length; ++i)\n {\n meshes[i].render(primitive);\n }\n dataMaterial.unapply();\n\n\n // render copy texture into data texture\n gl.bindFramebuffer( gl.FRAMEBUFFER, dataBuffer );\n gl.clear( gl.COLOR_BUFFER_BIT );\n\n this._copyMaterial.apply();\n this._screenQuadMesh.render();\n this._copyMaterial.unapply();\n }", "function renderDisplay() {\r\n\r\n DISPLAY.drawImage(BUFFER.canvas, 0, 0);\r\n\r\n }", "drawPreviousFrame() {\n\n this.drawTexture(this.offscreenTexture, this.fadeOpacity);\n\n }", "function saveDrawingSurface(){\n\t\n\t\tvar imageData=context.getImageData(0,0, canvas.width, canvas.height);\n\n}", "function slamBuffer () {\n var global_i = 0;\n\n // Copy data from back buffer matrix to draw buffer array\n\n // Iterate from the rows of the back buffer\n for (var i = 0; i < LCD_PIXEL_HEIGHT; i++) {\n // Iterate through a single layer of the back buffer\n for (var j = 0; j < LCD_PIXEL_WIDTH; j++) {\n // If value is 1, draw pure white pixel\n if (backBuffer [i][j] == 1) {\n drawBuffer.data[global_i + 0] = 255; // R\n drawBuffer.data[global_i + 1] = 255; // G\n drawBuffer.data[global_i + 2] = 255; // B\n drawBuffer.data[global_i + 3] = 255; // A\n // If value is 0, draw pure black pixel\n } else { //Draw black\n drawBuffer.data[global_i + 0] = 0; // R\n drawBuffer.data[global_i + 1] = 0; // G\n drawBuffer.data[global_i + 2] = 0; // B\n drawBuffer.data[global_i + 3] = 255; // A\n }\n \n // Add 4 to index as each pixel is comprised of 4 parts (RGBA)\n global_i += 4;\n }\n }\n\n // Place data onto the canvas\n screen.putImageData (drawBuffer, 0, 0);\n}", "display(buffer) {\n buffer.noStroke();\n buffer.fill(this.r, this.g, this.b);\n buffer.triangle(this.v1.x, this.v1.y, this.v2.x, this.v2.y, this.v3.x, this.v3.y);\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
changes wizard's fireball color to random one
function onSetupFireballClick() { var fireballColor = getRandomValueFromArray(WIZARD_FIREBALL_COLORS); setupFireball.style.backgroundColor = fireballColor; setupFireball.querySelector('input[name="fireball-color"]').value = fireballColor; }
[ "function change_color() {\n r = random(100, 256);\n g = random(100, 256);\n b = random(100, 256);\n}", "function changeColor(){\n\tvar colorCode = Randomizer.nextInt(0, 2);\n\tvar color;\n\tif(colorCode == 0){\n\t\tcolor = Color.red;\n\t}else if(colorCode == 1){\n\t\tcolor = Color.yellow;\n\t}else{\n\t\tcolor = Color.green;\n\t}\n\t\n\tball.setColor(color);\n}", "function change() {\n circleColor = color(random(255), random(255), random(255));\n\t}", "function colorChange(){\n\tvar r = Math.floor((Math.random() * 300) + 1);\n\tvar g = Math.floor((Math.random() * 200) + 1);\n\tvar b = Math.floor((Math.random() * 200) + 1);\n\treturn \"rgb(\" + r + \",\" + g + \",\" + b + \")\";\n}", "function changeColor() {\n\tball.color = vec4(Math.random().toFixed(2),Math.random().toFixed(2),Math.random().toFixed(2),1.0);\n}", "function randomColor(){\n\n\t\t//Random number generator 0-3\n\t\tvar randomNumber = Math.floor((Math.random() * 4));\n\t\tvar color = colors[randomNumber];\n\t\tsimonSequence.push(color);\n\t}", "setRandomColor(){\n let newColor = RGB.makeRandomColor();\n this._color.setColor(newColor.r, newColor.g, newColor.b);\n }", "function colorFillRainbow() {\n colorMode= \"random\";\n}", "function generateRandomColor() {\n\n var randomColor = simon.colors[Math.round(Math.random() * 3)]; //choose random color and start the game\n switch (randomColor) {\n case \"green\":\n simon.green.light(), simon.green.sound(), simon.botCache.push(0);\n break;\n case \"red\":\n simon.red.light(), simon.red.sound(), simon.botCache.push(1);\n break;\n case \"yellow\":\n simon.yellow.light(), simon.yellow.sound(), simon.botCache.push(2);\n break;\n case \"blue\":\n simon.blue.light(), simon.blue.sound(), simon.botCache.push(3);\n break;\n }\n }", "setRandomColour() {\n var letters = '0123456789ABCDEF';\n var randomColor = '#';\n for (var i = 0; i < 6; i++) {\n randomColor += letters[Math.floor(Math.random() * 16)];\n }\n this.colour = randomColor; //Set colour to random color\n }", "function setTargetColor(){\n targetColor = getRandomColor();\n}", "function RandomColor() {\n\tif (shapeColor.length > 0) {\n\t\tvar newColor = Random.Range(0,shapeColor.length-1);\n\t\trenderer.material.color = shapeColor[newColor];\n\t}\n}", "function changeColor() {\r\n \r\n let x = randInt(0, 255);\r\n let y = randInt(0, 255);\r\n let z = randInt(0, 255);\r\n let color = `rgb(${x}, ${y}, ${z})`;\r\n \r\n shape.style.backgroundColor = color;\r\n }", "function randomize() {\n color1.value = createHexValue();\n color2.value = createHexValue();\n setGradient();\n}", "function RandomColor(){\r\n if(shapeColor.length > 0){\r\n\t\tvar newColor = Random.Range(0, shapeColor.length);\r\n\t\tGetComponent.<Renderer>().material.color = shapeColor[newColor];\r\n\t}\r\n}", "function setRandomColors() {\n rColor.value = createRandomColors();\n lColor.value = createRandomColors();\n\n changeColor();\n}", "function randomColor() {\n playSound()\n var randomColor = squares[Math.floor(Math.random() * squares.length)];\n simonsArray.push(randomColor);\n showPattern(simonsArray)\n $('#pressStart').hide()\n $('#start-btn').hide()\n nextStage()\n playersArray = [];\n }", "function flashy_random_color() {\n //to get flashy color let red to 255 and change green and blue\n var g=Math.floor(255*Math.random())\n var b=Math.floor(255*Math.random())\n return \"rgb(255,\"+g+\",\"+b+\")\"\n}", "newNextColor() {\n if (this.gameOver) {\n return;\n }\n this.nextBlob1Color = Math.floor(Math.random() * this.puyoVariations) + 1;\n this.nextBlob2Color = Math.floor(Math.random() * this.puyoVariations) + 1;\n this.state.updateNextBlobs();\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets or Sets the selection end
get selectionEnd() { return this.selectionEndIn; }
[ "get selectionEnd() {\n return this.getInput().selectionEnd;\n }", "get selectionEnd() {\n return this.i.selectionEnd;\n }", "get SelectionEnd() { return this.native.SelectionEnd; }", "function getEndSelection()\n{\n return endCell;\n}", "set selectionEnd(value) {\n this.$.textarea.selectionEnd = value;\n }", "set selectionEnd(value) {\n this.$.textarea.selectionEnd = value;\n }", "set selectionEnd(value) {\n this.$.textarea.selectionEnd = value;\n }", "get selectionEndPage() {\n return this.selectionEndPageIn;\n }", "get selectionEnd() {\n let end;\n try {\n end = this._unsafeSelectionEnd;\n } catch {}\n return end != null ? end : this.value.length;\n }", "get selectionEnd() {\n return this.$.textarea.selectionEnd;\n }", "get selectionEnd() {\n let end;\n try {\n end = this._unsafeSelectionEnd;\n } catch (e) {}\n return end != null ? end : this.value.length;\n }", "extendToLineEnd() {\n if (isNullOrUndefined(this.start)) {\n return;\n }\n this.end.moveToLineEndInternal(this, true);\n this.upDownSelectionLength = this.end.location.x;\n this.fireSelectionChanged(true);\n }", "get end() {\n return this.selector('TextPositionSelector').end;\n }", "extendToParagraphEnd() {\n if (isNullOrUndefined(this.start)) {\n return;\n }\n this.end.moveToParagraphEndInternal(this, true);\n this.upDownSelectionLength = this.end.location.x;\n this.fireSelectionChanged(true);\n }", "function getCaretEnd(obj){\n\tif(typeof selectionEnd != \"undefined\"){\n\t\treturn selectionEnd;\n\t}else if(document.selection&&document.selection.createRange){\n\t\tvar M=document.selection.createRange();\n\t\ttry{\n\t\t\tvar Lp = M.duplicate();\n\t\t\tLp.moveToElementText(obj);\n\t\t}catch(e){\n\t\t\tvar Lp=createTextRange();\n\t\t}\n\t\tLp.setEndPoint(\"EndToEnd\",M);\n\t\tvar rb=Lp.text.length;\n\t\tif(rb>value.length){\n\t\t\treturn -1;\n\t\t}\n\t\treturn rb;\n\t}\n}", "function cursorEndSetter() {\n //get the last Element :\n var lastElement = $(type).last();\n var p;\n //check if there is new element : \n if (!lastElement.html()) {\n //there is no new item just move the cursor to the end of the post body:\n lastElement = $('#postBody');\n p = $('#postBody').html().length;\n } else {\n lastElement = $(type).last();\n p = lastElement.html().length;\n }\n const range = new Range();\n range.setStart(lastElement.get(0).firstChild, p);\n range.setEnd(lastElement.get(0).firstChild, p);\n\n window.getSelection().removeAllRanges();\n window.getSelection().addRange(range);\n}", "get finalSelectionStart() {\n if (this.isSelectAllActive) {\n return [0, 0];\n }\n if (!this.selectionEnd || !this.selectionStart) {\n return this.selectionStart;\n }\n return this.areSelectionValuesReversed() ? this.selectionEnd : this.selectionStart;\n }", "function setCursorToEnd() {\n let p = document.getElementById(\"content\");\n let s = window.getSelection();\n let r = document.createRange();\n r.setStart(p.lastChild, 1);\n r.setEnd(p.lastChild, 1);\n s.removeAllRanges();\n s.addRange(r);\n}", "navigateLineEnd() {\n this.selection.moveCursorLineEnd();\n this.clearSelection();\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Handle receiving of tracks from server. TODO: enable better error handling.
static receiveTracks(data) { return { type: this.FETCH_TRACKS, status: 'success', tracks: data.tracks || [] }; }
[ "function processTracks(tracks) {\n if (tracks) {\n tracks.status = 'success';\n log.info('sending back search results to ' + socket.id);\n socket.emit('search_results', tracks);\n } else {\n log.info('sending back failure for search results to ' + socket.id);\n socket.emit('search_results', {\n status: 'failure',\n message: 'your search came up empty'\n });\n }\n }", "onTracksChanged_() {\n // Delay the 'trackschanged' event so StreamingEngine has time to absorb the\n // changes before the user tries to query it.\n const event = this.makeEvent_(conf.EventName.TracksChanged)\n this.delayDispatchEvent_(event)\n }", "function handleTrackData() {\n // Set the most recent track info\n // songData.artistName = trackArtistElement.children[0].innerText;\n // songData.songName = trackTitleElement.children[0].innerText;\n\n songData.songName = musicHorizontalItem.getAttribute(\"primary-text\");\n songData.artistName = musicHorizontalItem.getAttribute(\"secondary-text\");\n\n // When music starts playing set the current song and artisit\n if (currentSongName === null || currentArtist === null) {\n // Send to background.js now that we have track info\n port.postMessage(JSON.stringify(songData));\n \n currentSongName = musicHorizontalItem.getAttribute(\"primary-text\");\n currentArtist = musicHorizontalItem.getAttribute(\"secondary-text\");\n }\n\n // Only update current track info if it has changed\n if (songData.artistName !== currentArtist || songData.songName !== currentSongName) {\n // Send the new track info to background.js.\n port.postMessage(JSON.stringify(songData));\n\n currentSongName = musicHorizontalItem.getAttribute(\"primary-text\");\n currentArtist = musicHorizontalItem.getAttribute(\"secondary-text\");\n\n console.log(\"New Song...\");\n }\n\n}", "static onTrackEnded (track) {\n\t\tpm.incrementTrackPlaycount(track.id, (err, res) => {\n\t\t\tif (err) console.err(err)\n\t\t})\n\t}", "function onPlayerTrackChanged(event){\n\t\tClientSocket.sendJSON({ \"propertyName\": \"artist\", \"propertyValue\": event.artist });\n\t\tClientSocket.sendJSON({ \"propertyName\": \"artistUri\", \"propertyValue\": event.artistUri });\n\t\tClientSocket.sendJSON({ \"propertyName\": \"track\", \"propertyValue\": event.track });\n\t\tClientSocket.sendJSON({ \"propertyName\": \"trackUri\", \"propertyValue\": event.trackUri });\t\t\n\t}", "get tracks() {\n return this._receivedTracks;\n }", "function onTrackChanged(event){\n\t\tconsole.log(\"onTrackChanged\");\n\t\tchrome.extension.sendRequest({ player: { \n\t\t\t\t\t\t\t\t\t\t\t\t\tevent: \"trackChanged\", \n\t\t\t\t\t\t\t\t\t\t\t\t\tartist: event.artist, \n\t\t\t\t\t\t\t\t\t\t\t\t\ttrack: event.track, \n\t\t\t\t\t\t\t\t\t\t\t\t\tartistUri: event.artistUri, \n\t\t\t\t\t\t\t\t\t\t\t\t\ttrackUri: event.trackUri \n\t\t\t\t\t\t\t\t\t\t\t\t} \n\t\t\t\t\t\t\t\t\t});\n\t}", "function processTracks(response) {\n\t// Store track list in an array\n\tvar tracksResponseArray = response.tracks.items;\n\t// Get number of tracks in the response\n\tvar numTracks = tracksResponseArray.length;\n\n\t// Dp the following If the number of tracks is 1 or more.\n\tif (numTracks > 0) {\n\t\t//Map over each track, store necessary data to variables and log to terminal and history.log\n\t\ttracksResponseArray.map(trackInfo => {\n\t\t\tvar artist_name = propercase(trackInfo.artists[0].name);\n\t\t\tvar song_title = trackInfo.name;\n\t\t\tvar album_title = trackInfo.album.name;\n\t\t\tvar preview_link = trackInfo.preview_url ? trackInfo.preview_url : \"Preview not available\".error;\n\n\t\t\tconsole.log(`\\nArtist:`.spotify, `${artist_name}`.white);\n\t\t\tconsole.log(`Song:`.spotify, `${song_title}`.white);\n\t\t\tconsole.log(`Album:`.spotify, `${album_title}`.white);\n\t\t\tconsole.log(`URL:`, `${preview_link}`.spotify.underline);\n\t\t\tconsole.log(\"\\n--------------------------------------\\n\");\n\t\t\t\n\t\t\tlog_data(`\\nArtist: ${artist_name}\\nSong: ${song_title}\\nAlbum:${album_title}\\nURL: ${preview_link}\\n\\n-------------------\\n`);\n\n\t\t});\n\t} else {\n\t\t// If 0 tracks returned log to terminal and history.log\n\t\tconsole.log(\"Could not find any tracks with this title.\".error);\n\t\tlog_data(`\\nCould not find any tracks with this title.\\n\\n-------------------\\n`);\n\t}\n\n}", "function fetch_tracks(param) {\n\tparam = (param === null ? \"\" : param);\n\t$.ajax({url: \"trackdata.php\", type: \"POST\", data: {query: param}, success: function(data){\n\t\tvar json_data = jQuery.parseJSON(data);\n\t\tif (json_data.success == 1) {\n\t\t\t$('ol#tracklist').empty();\n\t\t\tif(json_data.tracks[0] !== undefined) {\n\t\t\t\t//tracks were returned as matches\n\t\t\t\t$.each(json_data.tracks, function(key, line) {\n\t\t\t\t\tappend_track(line);\t\n\t\t\t\t});\n\t\t\t} else {\n\t\t\t\t//no results were returned\n\t\t\t\t$('ol#tracklist').append('<li class=\"nomatch\">No matches found.</li>');\n\t\t\t}\n\t\t}\n\t\t//register click handler to play a track that is clicked on by the user (must be done here because .live() is deprecated and nothing will register on $(document).ready() because the server hasn't returned data yet)\n\t\t$('ol#tracklist li').click(function() {\n\t\t\tvar identifier = $(this).children('span.soundcloud').html();\n\t\t\tchange_track(identifier);\n\t\t\tif($('section#tracklist').hasClass('blurred') === true) {\n\t\t\t\t$('section#tracklist').animate({opacity: 1}).removeClass('blurred'); \n\t\t\t}\n\t\t\tif($('li.browse').length != 0) {\n\t\t\t\t$('li.browse').remove();\n\t\t\t}\n\t\t});\n\t}});\t\t\n}", "function handleTrackEvent(event) {\n console.log(\"New track event\");\n document.getElementById(\"received_video\").srcObject = event.streams[0];\n document.getElementById(\"waiting-text\").style.visibility = \"hidden\";\n document.getElementById(\"bitrate-selector\").disabled = false;\n}", "function handleTrack(info){\n setInfoTracks(info)\n }", "function handle_remote_track(event) {\n console.log('Received remote track: ', event);\n // get the first stream of the event and show it in remoteVideo\n document.getElementById('remoteVideo').srcObject = event.streams[0];\n}", "function postTracks() {\n $.ajax({\n url: '/load_songs',\n type: 'POST',\n data: JSON.stringify(track_struct),\n dataType: 'json',\n contentType: 'application/json'\n });\n }", "function handleRemoveTrackEvent(event) {\n var stream = document.getElementById(\"received_video\").srcObject;\n var trackList = stream.getTracks();\n\n if (trackList.length == 0) {\n closeStreaming();\n }\n}", "function processCurrenttrack (data) {\n setSongInfo(data)\n}", "function processTracksRequest(response) {\r\n\r\n var trackObject = response.recenttracks.track[0];\r\n\r\n // extract all needed information from the track object\r\n var trackName = trackObject.name;\r\n var artistName = trackObject.artist['#text'];\r\n var albumName = trackObject.album['#text'];\r\n var imageURL = trackObject.image[2]['#text'] // index 2 because it is a bigger image.\r\n\r\n // construct links to track, artist, album.\r\n var trackURL = trackObject.url;\r\n var artistURL = lastfm_root + artistName + '/';\r\n var albumURL = artistURL + albumName + '/';\r\n\r\n\r\n // render this information on the web page\r\n var title = document.getElementById(\"title\");\r\n title.target = '_blank';\r\n title.innerHTML = trackName;\r\n title.title = trackName;\r\n title.href = trackURL;\r\n\r\n var artist = document.getElementById(\"artist\");\r\n artist.target = '_blank';\r\n artist.innerHTML = artistName;\r\n artist.title = artistName;\r\n artist.href = artistURL;\r\n\r\n var album = document.getElementById(\"album\");\r\n album.target = '_blank';\r\n album.innerHTML = albumName;\r\n album.title = albumName;\r\n album.href = albumURL;\r\n\r\n document.getElementById(\"track-image\").src = imageURL;\r\n\r\n //check if the track is now playing, update the icon appropriately\r\n var icon = document.getElementById(\"last-listened\");\r\n var nowPlaying = false;\r\n if (trackObject.hasOwnProperty(\"@attr\")) {\r\n if (trackObject['@attr'].hasOwnProperty('nowplaying')) {\r\n // track is currently playing\r\n nowPlaying = true;\r\n // set speaker class so that the speaker icon shows to indicate now playing\r\n icon.className = now_playing;\r\n icon.innerHTML = \"\";\r\n }\r\n }\r\n\r\n if (!nowPlaying) {\r\n // calculate how long since the latest track was scrobbled.\r\n // fyi the date property of the api response is a unix time stamp.\r\n icon.className = \"\";\r\n var currentUTS = Date.now()/1000; // divide by 1000 so it's in seconds\r\n var scrobbleUTS = trackObject.date.uts;\r\n var minutesSinceScrobble = Math.floor((currentUTS - scrobbleUTS) / 60);\r\n\r\n if (minutesSinceScrobble >= 60 && minutesSinceScrobble < (60 * 24)) {\r\n icon.innerHTML = \"PLAYED \" + Math.floor(minutesSinceScrobble / 60) + \" HOUR(S) AGO\";\r\n } else if (minutesSinceScrobble >= (60 * 24) && minutesSinceScrobble < (60*24*30)) {\r\n icon.innerHTML = \"PLAYED \" + Math.floor(minutesSinceScrobble / (60 * 24)) + \" DAY(S) AGO\";\r\n } else if (minutesSinceScrobble >= (60*24*30) && minutesSinceScrobble < (60*24*365)) {\r\n icon.innerHTML = \"PLAYED \" + Math.floor(minutesSinceScrobble / (60*24*30)) + \" MONTH(S) AGO\";\r\n } else if (minutesSinceScrobble >= (60*24*365)) {\r\n icon.innerHTML = \"PLAYED \" + Math.floor(minutesSinceScrobble / (60*24*365)) + \" YEAR(S) AGO\";\r\n } else {\r\n icon.innerHTML = \"PLAYED \" + minutesSinceScrobble + \" MIN(S) AGO\";\r\n }\r\n }\r\n}", "static receiveAudio(trackId, data) {\n return {\n type: this.FETCH_AUDIO,\n status: 'success',\n audioUrl: data.url,\n trackId,\n };\n }", "function _loop() {\n const currentTrackURL = _getCurrentTrackURL();\n const trackProgression = _getTrackProgression();\n\n if (\n currentTrackURL !== actualTrackURL &&\n currentTrackURL &&\n socket.connected\n ) {\n const payload = {\n trackURL: currentTrackURL,\n progression: trackProgression,\n };\n\n actualTrackURL = currentTrackURL;\n\n socket.emit('rp-update', payload);\n _log('new track detected, sending payload...', payload);\n }\n }", "function onMessageReceived(e) {\n var data = JSON.parse(e.data);\n \n switch (data.event) {\n case 'ready':\n onReady();\n break;\n \n case 'playProgress':\n onPlayProgress(data.data);\n break;\n \n case 'finish':\n onFinish();\n break;\n }\n \t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
enyo.updateI18NClasses should be called after every setLocale, but there isn't such a callback in current version
function updateI18NClasses () { var li = new LocaleInfo(); // for the current locale var locale = li.getLocale(); var base = 'enyo-locale-'; // Remove old style definitions (hack style becouse enyo.dom doesn't have methods like enyo.dom.getBodyClasses, enyo.dom.removeBodyClass) if (document && document.body && document.body.className) { document.body.className = document.body.className.replace(new RegExp('(^|\\s)'+ base +'\\S*', 'g'), ''); } if (isNonLatinLocale(locale)) { // allow enyo to define other fonts for non-Latin languages, or for certain // Latin-based languages where the characters with some accents don't appear in the // regular fonts, creating a strange 'ransom note' look with a mix of fonts in the // same word. So, treat it like a non-Latin language in order to get all the characters // to display with the same font. dom.addBodyClass(base + 'non-latin'); } var scriptName = li.getScript(); if (scriptName !== 'Latn' && scriptName !== 'Cyrl' && scriptName !== 'Grek') { // GF-45884: allow enyo to avoid setting italic fonts for those scripts that do not // commonly use italics dom.addBodyClass(base + 'non-italic'); } // allow enyo to apply right-to-left styles to the app and widgets if necessary var script = new ScriptInfo(scriptName); if (script.getScriptDirection() === 'rtl') { dom.addBodyClass(base + 'right-to-left'); Control.prototype.rtl = true; } else { Control.prototype.rtl = false; } // allow enyo or the apps to give CSS classes that are specific to the language, country, or script if (locale.getLanguage()) { dom.addBodyClass(base + locale.getLanguage()); if (locale.getScript()) { dom.addBodyClass(base + locale.getLanguage() + '-' + locale.getScript()); if (locale.getRegion()) { dom.addBodyClass(base + locale.getLanguage() + '-' + locale.getScript() + '-' + locale.getRegion()); } } else if (locale.getRegion()) { dom.addBodyClass(base + locale.getLanguage() + '-' + locale.getRegion()); } } if (locale.getScript()) { dom.addBodyClass(base + locale.getScript()); } if (locale.getRegion()) { dom.addBodyClass(base + locale.getRegion()); } // Recreate the case mappers to use the just-recently-set locale setCaseMappers(); }
[ "updateLocalizedContent() {\n this.i18nUpdateLocale();\n }", "setCulture() {\n this.intl = new Internationalization();\n }", "function add_i18n()\r\n {\r\n var i18n = {};\r\n\r\n i18n[I18N.LANG.EN] = {};\r\n i18n[I18N.LANG.EN][MODULE_NAME + '_name'] = 'autosync';\r\n i18n[I18N.LANG.EN][MODULE_NAME + '_short_desc'] = 'Enable automatic synchronization';\r\n i18n[I18N.LANG.EN][MODULE_NAME + '_full_desc'] = 'Allow the script to automatically update external tools at each page refresh.';\r\n\r\n i18n[I18N.LANG.FR] = {};\r\n i18n[I18N.LANG.FR][MODULE_NAME + '_name'] = 'autosync';\r\n i18n[I18N.LANG.FR][MODULE_NAME + '_short_desc'] = 'Activer la synchronisation automatique';\r\n i18n[I18N.LANG.FR][MODULE_NAME + '_full_desc'] = 'Ajoute la possibilité de synchroniser automatiquement les sites externes à chaque rafraîchissement de la page.';\r\n\r\n I18N.set(i18n);\r\n }", "function add_i18n()\n {\n var i18n = {};\n\n i18n[I18N.LANG.EN] = {};\n i18n[I18N.LANG.EN][MODULE_NAME + '_short_desc'] = 'Fold Twinoid bar';\n i18n[I18N.LANG.EN][MODULE_NAME + '_full_desc'] = 'Fold the Twinoid black bar at the top of the screen. Put your mouse near the top of the screen to show it again.';\n\n i18n[I18N.LANG.FR] = {};\n i18n[I18N.LANG.FR][MODULE_NAME + '_short_desc'] = 'Replier la barre Twinoid';\n i18n[I18N.LANG.FR][MODULE_NAME + '_full_desc'] = 'Permet de gagner de la place en repliant la barre Twinoid. Rapprochez votre souris du bord supérieur de l\\'écran pour l\\'afficher de nouveau.';\n\n I18N.set(i18n);\n }", "function updateLanguage(){\n R.setLocale( defaultlang );\n setSelectOption();\n translatePlainTexts();\n if( asfEnable == true ) { \n translateCustomTexts();\n }\n}", "init_() {\n this.localizationService_ = getLocalizationService(this.storyAutoAdsEl_);\n\n const enXaPseudoLocaleBundle = createPseudoLocale(\n LocalizedStringsEn,\n (s) => `[${s} one two]`\n );\n\n this.localizationService_.registerLocalizedStringBundles({\n 'default': LocalizedStringsEn,\n 'ar': LocalizedStringsAr,\n 'de': LocalizedStringsDe,\n 'en': LocalizedStringsEn,\n 'en-GB': LocalizedStringsEnGb,\n 'es': LocalizedStringsEs,\n 'es-419': LocalizedStringsEs419,\n 'fr': LocalizedStringsFr,\n 'hi': LocalizedStringsHi,\n 'id': LocalizedStringsId,\n 'it': LocalizedStringsIt,\n 'ja': LocalizedStringsJa,\n 'ko': LocalizedStringsKo,\n 'nl': LocalizedStringsNl,\n 'no': LocalizedStringsNo,\n 'pt-PT': LocalizedStringsPtPt,\n 'pt-BR': LocalizedStringsPtBr,\n 'ru': LocalizedStringsRu,\n 'tr': LocalizedStringsTr,\n 'vi': LocalizedStringsVi,\n 'zh-cn': LocalizedStringsZhCn,\n 'zh-TW': LocalizedStringsZhTw,\n 'en-xa': enXaPseudoLocaleBundle,\n });\n }", "initi18n() {\n this.$i18n.locale = document.documentElement.lang;\n this.loadTranslations();\n }", "translationsLoaded() {\n // overwrite in derived class\n }", "function add_i18n()\n {\n var i18n = {};\n\n i18n[I18N.LANG.EN] = {};\n i18n[I18N.LANG.EN][MODULE_NAME + '_short_desc'] = 'Show the spoilers without mouse hover';\n i18n[I18N.LANG.EN][MODULE_NAME + '_full_desc'] = 'Show the spoilers content without hovering with your mouse.';\n\n i18n[I18N.LANG.FR] = {};\n i18n[I18N.LANG.FR][MODULE_NAME + '_short_desc'] = 'Afficher les spoilers sans passer la souris';\n i18n[I18N.LANG.FR][MODULE_NAME + '_full_desc'] = 'Affiche le contenu des spoilers sans avoir besoin de passer la souris.';\n\n I18N.set(i18n);\n }", "function add_i18n()\n {\n var i18n = {};\n\n i18n[I18N.LANG.EN] = {};\n i18n[I18N.LANG.EN][MODULE_NAME + '_short_desc'] = 'Old Twinoid elements (by Davf)';\n i18n[I18N.LANG.EN][MODULE_NAME + '_full_desc'] = 'More information here [fr]: http://userstyles.org/styles/99207/hordes-elements-twinoidien. Script by Davf, integrated with his permission.. Click to open link.';\n\n i18n[I18N.LANG.FR] = {};\n i18n[I18N.LANG.FR][MODULE_NAME + '_short_desc'] = 'Hordes Elements Twinoidien (par Davf)';\n i18n[I18N.LANG.FR][MODULE_NAME + '_full_desc'] = 'Plus d\\'information ici : http://userstyles.org/styles/99207/hordes-elements-twinoidien. Script par Davf, intégré avec sa permission. Cliquez pour ouvrir le lien.';\n\n I18N.set(i18n);\n }", "function add_i18n()\r\n {\r\n var i18n = {};\r\n\r\n i18n[I18N.LANG.EN] = {};\r\n i18n[I18N.LANG.EN][MODULE_NAME + '_short_desc'] = 'Enable the chat module';\r\n i18n[I18N.LANG.EN][MODULE_NAME + '_full_desc'] = 'Allow you to chat with the players in your town.';\r\n i18n[I18N.LANG.EN][MODULE_NAME + '_title'] = 'Die2Nite Enhancer - Chatty';\r\n i18n[I18N.LANG.EN][MODULE_NAME + '_send_button'] = 'Send';\r\n i18n[I18N.LANG.EN][MODULE_NAME + '_world_room'] = 'World';\r\n\r\n i18n[I18N.LANG.FR] = {};\r\n i18n[I18N.LANG.FR][MODULE_NAME + '_short_desc'] = 'Activer le module de chat';\r\n i18n[I18N.LANG.FR][MODULE_NAME + '_full_desc'] = 'Vous permet de parler avec les joueurs de votre ville.';\r\n i18n[I18N.LANG.FR][MODULE_NAME + '_send_button'] = 'Ecrire';\r\n i18n[I18N.LANG.FR][MODULE_NAME + '_world_room'] = 'Monde';\r\n\r\n I18N.set(i18n);\r\n }", "function add_i18n()\n {\n var i18n = {};\n\n i18n[I18N.LANG.EN] = {};\n i18n[I18N.LANG.EN][MODULE_NAME + '_short_desc'] = 'Old forum tags (by Davf)';\n i18n[I18N.LANG.EN][MODULE_NAME + '_full_desc'] = 'More information here [fr]: http://userstyles.org/styles/97674/hordes-balises-ancienne. Script by Davf, integrated with his permission. Click to open link.';\n\n i18n[I18N.LANG.FR] = {};\n i18n[I18N.LANG.FR][MODULE_NAME + '_short_desc'] = 'Hordes Balises Anciennes (par Davf)';\n i18n[I18N.LANG.FR][MODULE_NAME + '_full_desc'] = 'Plus d\\'information ici : http://userstyles.org/styles/97674/hordes-balises-ancienne. Script par Davf, intégré avec sa permission. . Cliquez pour ouvrir le lien.';\n\n I18N.set(i18n);\n }", "setCulture() {\n this.localeObj = new L10n(this.getModuleName(), this.defaultLocale, this.locale);\n }", "function add_i18n()\n {\n var i18n = {};\n\n i18n[I18N.LANG.EN] = {};\n i18n[I18N.LANG.EN][MODULE_NAME + '_short_desc'] = 'Old forum menu design (by Davf)';\n i18n[I18N.LANG.EN][MODULE_NAME + '_full_desc'] = 'More information here [fr]: http://userstyles.org/styles/97652/hordes-forum-ancien. Script by Davf, integrated with his permission. Click to open link.';\n\n i18n[I18N.LANG.FR] = {};\n i18n[I18N.LANG.FR][MODULE_NAME + '_short_desc'] = 'Hordes Forum Ancien (par Davf)';\n i18n[I18N.LANG.FR][MODULE_NAME + '_full_desc'] = 'Plus d\\'information ici : http://userstyles.org/styles/97652/hordes-forum-ancien. Script par Davf, intégré avec sa permission. Cliquez pour ouvrir le lien.';\n\n I18N.set(i18n);\n }", "initInternationalization() {\n\n console.log(\"Setting language to: \", App.appLanguage);\n\n // Initialize the internationalization service\n i18next\n .use(i18nextXHRBackend)\n .init({\n lng : App.appLanguage,\n fallbackLng: \"en\",\n ns : \"general\",\n defaultNS : \"general\",\n backend : { loadPath: \"./locales/{{lng}}/{{ns}}.json\" }\n })\n .then(() => {\n\n // Attach the function to be fired when the language is changed\n i18next.on(\"languageChanged\", () => console.log(`lng changed to ${i18next.language}`));\n\n // Initialize the jQuery plugin\n jqueryI18next.init(i18next, $);\n\n // Translate the body\n $(\"body\").localize();\n\n // Open the first activity\n this.open();\n\n });\n\n }", "function add_i18n()\n {\n var i18n = {};\n\n i18n[I18N.LANG.EN] = {};\n i18n[I18N.LANG.EN][MODULE_NAME + '_short_desc'] = 'Hide help';\n i18n[I18N.LANG.EN][MODULE_NAME + '_full_desc'] = 'Hide all the helps in the interface.';\n\n i18n[I18N.LANG.FR] = {};\n i18n[I18N.LANG.FR][MODULE_NAME + '_short_desc'] = 'Cacher les aides';\n i18n[I18N.LANG.FR][MODULE_NAME + '_full_desc'] = 'Cache les aides de jeu dans toute l\\'interface.';\n\n I18N.set(i18n);\n }", "function setLocalization(locale) {\r\n\r\n if(locale != \"en\")\r\n locale = \"cn\";\r\n\r\n try {\r\n jQuery.i18n.properties( {\r\n name:'Messages',\r\n path:'properties/',\r\n mode:'map',\r\n language:locale,\r\n callback: function() {\r\n }\r\n });\r\n } catch(err) {\r\n var fileref=document.createElement('script');\r\n fileref.setAttribute(\"type\",\"text/javascript\");\r\n fileref.setAttribute(\"src\", 'js/jquery/jquery.i18n.properties-1.0.4.js');\r\n document.getElementsByTagName(\"head\")[0].appendChild(fileref);\r\n setLocalization(locale);\r\n }\r\n}", "function applyLanguage(lang) {\r\n\t\r\n\tjQuery.i18n.properties({\r\n\t name:'localization', \r\n\t path:'resources/localization/', \r\n\t mode:'both',\r\n\t language:lang, \r\n\t callback: function() {\r\n\t \t$('#header_title').text(jQuery.i18n.prop('label.header'));\r\n\t \t$('#site-footer').text(jQuery.i18n.prop('label.footer'));\r\n\t }\r\n\t});\r\n}", "_setLocalizationSettings(locale, messages) {\n const that = this;\n\n that.locale = locale;\n that.messages = messages;\n\n // Sets default locale && messages\n that.defaultLocale = 'en';\n that.defaultMessages = {\n 'en': {\n 'apply': 'apply',\n 'date': 'date',\n 'time': 'time',\n 'day': 'day',\n 'month': 'month',\n 'year': 'year',\n 'hours': 'hours',\n 'hour': 'hour',\n 'minutes': 'minutes',\n 'minute': 'minute',\n 'seconds': 'seconds',\n 'second': 'second',\n 'milliseconds': 'milliseconds',\n 'ampm': 'am/pm',\n 'delete': 'delete'\n },\n };\n\n // If messages not passed - get default\n if (!that.messages) {\n that.messages = that.defaultMessages;\n }\n\n // If passed invalid language\n if (!that.messages[that.locale]) {\n if (that.messages[that.defaultLocale]) {\n that.locale = that.defaultLocale;\n }\n else {\n that.messages = that.defaultMessages;\n that.locale = that.defaultLocale;\n }\n }\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Fare.js is part of the BART dashboard widget. (c) 2008 Bret Victor This software is licensed under the terms of the open source MIT license. Automatically generated by make_fare.pl on Mon Jan 13 19:22:15 2014. cents = Fare.getCentsBetween("Del Norte", "Castro Valley")
function Fare () { var fares = [ 555, 350, 185, 360, 185, 395, 275, 185, 320, 330, 185, 405, 390, 410, 245, 425, 330, 430, 185, 385, 320, 295, 185, 185, 480, 330, 190, 410, 235, 460, 220, 355, 330, 280, 185, 895, 450, 240, 350, 425, 395, 340, 410, 185, 350, 555, 350, 185, 390, 185, 465, 400, 495, 185, 415, 335, 570, 295, 440, 600, 185, 600, 390, 185, 495, 480, 350, 370, 445, 185, 405, 590, 445, 640, 425, 530, 185, 460, 390, 860, 400, 445, 520, 360, 570, 515, 585, 335, 185, 350, 555, 360, 185, 395, 275, 185, 320, 330, 185, 405, 390, 410, 245, 425, 330, 430, 185, 385, 320, 295, 185, 185, 480, 330, 190, 410, 235, 460, 220, 355, 330, 280, 185, 895, 450, 240, 350, 425, 395, 340, 410, 185, 360, 185, 360, 555, 395, 185, 470, 405, 500, 185, 420, 325, 575, 295, 445, 605, 185, 605, 400, 185, 500, 485, 360, 380, 440, 185, 410, 595, 450, 645, 430, 535, 185, 465, 400, 850, 390, 450, 525, 350, 575, 520, 590, 340, 185, 390, 185, 395, 555, 420, 315, 185, 340, 375, 235, 425, 390, 430, 185, 450, 375, 450, 205, 410, 340, 285, 185, 185, 500, 375, 185, 410, 225, 460, 185, 350, 375, 185, 185, 915, 470, 285, 370, 445, 415, 330, 430, 185, 395, 185, 395, 185, 420, 555, 490, 425, 520, 190, 440, 310, 595, 295, 465, 625, 190, 630, 425, 185, 520, 510, 395, 405, 405, 190, 430, 615, 470, 665, 450, 555, 190, 485, 420, 810, 355, 470, 550, 310, 595, 545, 610, 380, 275, 465, 275, 470, 315, 490, 555, 325, 185, 460, 185, 500, 475, 505, 360, 185, 460, 185, 235, 485, 185, 390, 275, 295, 575, 460, 325, 495, 350, 545, 345, 435, 460, 380, 300, 990, 545, 185, 185, 520, 185, 420, 185, 295, 185, 400, 185, 405, 185, 425, 325, 555, 350, 390, 250, 435, 390, 440, 185, 455, 390, 460, 220, 420, 350, 300, 185, 185, 510, 390, 185, 410, 240, 460, 185, 355, 390, 185, 185, 925, 475, 300, 380, 455, 425, 340, 440, 195, 320, 495, 320, 500, 340, 520, 185, 350, 555, 485, 245, 530, 505, 530, 390, 185, 485, 360, 275, 515, 185, 415, 320, 330, 605, 485, 355, 525, 380, 575, 370, 465, 485, 410, 330, 1015, 570, 185, 255, 545, 320, 450, 185, 330, 330, 185, 330, 185, 375, 190, 460, 390, 485, 555, 405, 350, 565, 315, 430, 595, 185, 595, 375, 185, 485, 475, 330, 350, 450, 185, 400, 580, 440, 630, 415, 525, 185, 450, 375, 865, 415, 435, 515, 380, 560, 510, 575, 310, 185, 415, 185, 420, 235, 440, 185, 250, 245, 405, 555, 450, 425, 455, 310, 380, 405, 385, 185, 435, 245, 335, 185, 215, 525, 405, 265, 445, 300, 495, 295, 385, 405, 330, 220, 940, 495, 185, 290, 470, 350, 370, 365, 210, 405, 335, 405, 325, 425, 310, 500, 435, 530, 350, 450, 555, 605, 310, 475, 635, 350, 635, 430, 310, 530, 515, 405, 415, 360, 350, 440, 625, 480, 675, 460, 565, 350, 495, 430, 770, 310, 480, 555, 310, 605, 550, 620, 395, 390, 570, 390, 575, 390, 595, 475, 390, 505, 565, 425, 605, 555, 610, 430, 610, 565, 610, 405, 590, 505, 185, 390, 390, 680, 565, 400, 185, 185, 185, 415, 185, 565, 450, 375, 1095, 650, 455, 530, 625, 580, 185, 595, 405, 410, 295, 410, 295, 430, 295, 505, 440, 530, 315, 455, 310, 610, 555, 475, 640, 315, 640, 435, 295, 530, 520, 410, 420, 380, 315, 445, 630, 485, 680, 460, 570, 315, 500, 430, 790, 310, 480, 560, 310, 605, 555, 620, 400, 245, 440, 245, 445, 185, 465, 360, 185, 390, 430, 310, 475, 430, 475, 555, 495, 430, 500, 290, 460, 390, 345, 245, 225, 550, 430, 185, 450, 310, 500, 185, 390, 430, 185, 230, 965, 515, 340, 420, 490, 465, 380, 480, 260, 425, 600, 425, 605, 450, 625, 185, 455, 185, 595, 380, 635, 610, 640, 495, 555, 595, 465, 400, 620, 360, 520, 425, 435, 710, 595, 460, 630, 485, 680, 480, 570, 595, 515, 435, 1125, 680, 355, 385, 655, 435, 555, 185, 435, 330, 185, 330, 185, 375, 190, 460, 390, 485, 185, 405, 350, 565, 315, 430, 595, 555, 595, 375, 185, 485, 475, 330, 350, 450, 185, 400, 580, 440, 630, 415, 525, 185, 450, 375, 865, 415, 435, 515, 380, 560, 510, 575, 310, 430, 600, 430, 605, 450, 630, 185, 460, 360, 595, 385, 635, 610, 640, 500, 465, 595, 555, 405, 620, 185, 525, 430, 435, 710, 595, 460, 630, 485, 680, 480, 570, 595, 515, 435, 1125, 680, 355, 185, 655, 185, 560, 450, 440, 185, 390, 185, 400, 205, 425, 235, 220, 275, 375, 185, 430, 405, 435, 290, 400, 375, 405, 555, 415, 275, 320, 185, 185, 505, 375, 235, 425, 265, 475, 265, 365, 375, 310, 190, 920, 475, 185, 320, 450, 370, 355, 385, 185, 385, 185, 385, 185, 410, 185, 485, 420, 515, 185, 435, 310, 590, 295, 460, 620, 185, 620, 415, 555, 510, 500, 385, 400, 415, 185, 425, 610, 465, 660, 445, 550, 185, 480, 410, 825, 365, 465, 540, 330, 590, 535, 605, 365, 320, 495, 320, 500, 340, 520, 185, 350, 185, 485, 245, 530, 505, 530, 390, 360, 485, 185, 275, 510, 555, 415, 320, 330, 605, 485, 355, 520, 375, 570, 375, 465, 485, 410, 330, 1020, 570, 185, 185, 545, 185, 450, 345, 330, 295, 480, 295, 485, 285, 510, 390, 300, 415, 475, 335, 515, 185, 520, 345, 520, 475, 525, 320, 500, 415, 555, 295, 280, 590, 475, 310, 295, 185, 355, 330, 185, 475, 365, 260, 1005, 560, 365, 445, 535, 490, 185, 505, 315, 185, 350, 185, 360, 185, 395, 275, 185, 320, 330, 185, 405, 390, 410, 245, 425, 330, 430, 185, 385, 320, 295, 555, 185, 480, 330, 190, 410, 235, 460, 220, 355, 330, 280, 185, 895, 450, 240, 350, 425, 395, 340, 410, 185, 185, 370, 185, 380, 185, 405, 295, 185, 330, 350, 215, 415, 390, 420, 225, 435, 350, 435, 185, 400, 330, 280, 185, 555, 490, 350, 185, 410, 185, 460, 200, 350, 350, 260, 185, 905, 460, 260, 355, 435, 405, 330, 420, 185, 480, 445, 480, 440, 500, 405, 575, 510, 605, 450, 525, 360, 680, 380, 550, 710, 450, 710, 505, 415, 605, 590, 480, 490, 555, 450, 515, 700, 555, 750, 535, 640, 450, 570, 500, 425, 310, 555, 630, 310, 680, 625, 695, 470, 330, 185, 330, 185, 375, 190, 460, 390, 485, 185, 405, 350, 565, 315, 430, 595, 185, 595, 375, 185, 485, 475, 330, 350, 450, 555, 400, 580, 440, 630, 415, 525, 185, 450, 375, 865, 415, 435, 515, 380, 560, 510, 575, 310, 190, 405, 190, 410, 185, 430, 325, 185, 355, 400, 265, 440, 400, 445, 185, 460, 400, 460, 235, 425, 355, 310, 190, 185, 515, 400, 555, 420, 255, 465, 185, 360, 400, 185, 185, 930, 485, 305, 385, 460, 430, 345, 445, 205, 410, 590, 410, 595, 410, 615, 495, 410, 525, 580, 445, 625, 185, 630, 450, 630, 580, 630, 425, 610, 520, 295, 410, 410, 700, 580, 420, 555, 340, 185, 435, 185, 580, 470, 395, 1115, 670, 475, 550, 645, 600, 185, 615, 425, 235, 445, 235, 450, 225, 470, 350, 240, 380, 440, 300, 480, 185, 485, 310, 485, 440, 485, 265, 465, 375, 185, 235, 185, 555, 440, 255, 340, 555, 390, 285, 185, 440, 325, 185, 970, 525, 330, 405, 500, 455, 185, 470, 255, 460, 640, 460, 645, 460, 665, 545, 460, 575, 630, 495, 675, 185, 680, 500, 680, 630, 680, 475, 660, 570, 355, 460, 460, 750, 630, 465, 185, 390, 555, 485, 185, 630, 520, 445, 1165, 720, 520, 600, 695, 650, 185, 665, 475, 220, 425, 220, 430, 185, 450, 345, 185, 370, 415, 295, 460, 415, 460, 185, 480, 415, 480, 265, 445, 375, 330, 220, 200, 535, 415, 185, 435, 285, 485, 555, 375, 415, 185, 205, 945, 500, 320, 400, 475, 450, 360, 465, 235, 355, 530, 355, 535, 350, 555, 435, 355, 465, 525, 385, 565, 185, 570, 390, 570, 525, 570, 365, 550, 465, 185, 355, 350, 640, 525, 360, 185, 185, 185, 375, 555, 525, 415, 335, 1055, 610, 415, 490, 585, 540, 185, 555, 365, 330, 185, 330, 185, 375, 190, 460, 390, 485, 185, 405, 350, 565, 315, 430, 595, 185, 595, 375, 185, 485, 475, 330, 350, 450, 185, 400, 580, 440, 630, 415, 525, 555, 450, 375, 865, 415, 435, 515, 380, 560, 510, 575, 310, 280, 460, 280, 465, 185, 485, 380, 185, 410, 450, 330, 495, 450, 500, 185, 515, 450, 515, 310, 480, 410, 365, 280, 260, 570, 450, 185, 470, 325, 520, 185, 415, 450, 555, 265, 985, 540, 360, 435, 515, 485, 395, 500, 295, 185, 390, 185, 400, 185, 420, 300, 185, 330, 375, 220, 430, 375, 430, 230, 435, 375, 435, 190, 410, 330, 260, 185, 185, 500, 375, 185, 395, 185, 445, 205, 335, 375, 265, 555, 915, 470, 265, 355, 445, 405, 310, 420, 185, 895, 860, 895, 850, 915, 810, 990, 925, 1015, 865, 940, 770, 1095, 790, 965, 1125, 865, 1125, 920, 825, 1020, 1005, 895, 905, 425, 865, 930, 1115, 970, 1165, 945, 1055, 865, 985, 915, 555, 740, 965, 1045, 740, 1095, 1040, 1110, 885, 450, 400, 450, 390, 470, 355, 545, 475, 570, 415, 495, 310, 650, 310, 515, 680, 415, 680, 475, 365, 570, 560, 450, 460, 310, 415, 485, 670, 525, 720, 500, 610, 415, 540, 470, 740, 555, 520, 600, 310, 645, 595, 660, 440, 240, 445, 240, 450, 285, 470, 185, 300, 185, 435, 185, 480, 455, 480, 340, 355, 435, 355, 185, 465, 185, 365, 240, 260, 555, 435, 305, 475, 330, 520, 320, 415, 435, 360, 265, 965, 520, 555, 245, 495, 315, 400, 340, 255, 350, 520, 350, 525, 370, 550, 185, 380, 255, 515, 290, 555, 530, 560, 420, 385, 515, 185, 320, 540, 185, 445, 350, 355, 630, 515, 385, 550, 405, 600, 400, 490, 515, 435, 355, 1045, 600, 245, 555, 575, 185, 480, 370, 360, 425, 360, 425, 350, 445, 310, 520, 455, 545, 380, 470, 310, 625, 310, 490, 655, 380, 655, 450, 330, 545, 535, 425, 435, 310, 380, 460, 645, 500, 695, 475, 585, 380, 515, 445, 740, 310, 495, 575, 555, 620, 570, 635, 415, 395, 570, 395, 575, 415, 595, 185, 425, 320, 560, 350, 605, 580, 605, 465, 435, 560, 185, 370, 590, 185, 490, 395, 405, 680, 560, 430, 600, 455, 650, 450, 540, 560, 485, 405, 1095, 645, 315, 185, 620, 555, 525, 420, 405, 340, 515, 340, 520, 330, 545, 420, 340, 450, 510, 370, 550, 185, 555, 380, 555, 510, 560, 355, 535, 450, 185, 340, 330, 625, 510, 345, 185, 185, 185, 360, 185, 510, 395, 310, 1040, 595, 400, 480, 570, 525, 555, 540, 350, 410, 585, 410, 590, 430, 610, 185, 440, 185, 575, 365, 620, 595, 620, 480, 185, 575, 450, 385, 605, 345, 505, 410, 420, 695, 575, 445, 615, 470, 665, 465, 555, 575, 500, 420, 1110, 660, 340, 370, 635, 420, 540, 555, 420, 185, 335, 185, 340, 185, 380, 295, 195, 330, 310, 210, 395, 405, 400, 260, 435, 310, 440, 185, 365, 330, 315, 185, 185, 470, 310, 205, 425, 255, 475, 235, 365, 310, 295, 185, 885, 440, 255, 360, 415, 405, 350, 420, 555 ]; var station_names = [ "12th St", "16th St", "19th St", "24th St", "Ashby", "Balboa Park", "Bay Fair", "Berkeley", "Castro Valley", "Civic Center", "Coliseum", "Colma", "Concord", "Daly City", "Del Norte", "Dublin", "Embarcadero", "Fremont", "Fruitvale", "Glen Park", "Hayward", "Lafayette", "Lake Merritt", "MacArthur", "Millbrae", "Montgomery", "North Berkeley", "North Concord", "Orinda", "Pittsburg", "Plaza", "Pleasant Hill", "Powell", "Richmond", "Rockridge", "SFO", "San Bruno", "San Leandro", "South Hayward", "South SF", "Union City", "Walnut Creek", "West Dublin", "West Oakland" ]; var station_indexes = {} for (var i=0; i < station_names.length; i++) { station_indexes[ station_names[i] ] = i } Fare.getCentsBetween = function (start_name, end_name) { var start_index = station_indexes[start_name] var end_index = station_indexes[end_name] return fares[ start_index * 44 + end_index ] } }
[ "function getuRideFare() {\n}", "function calculateFare(){\n\tvar departure = document.getElementById(\"from\").value;\n var arrival = document.getElementById(\"to\").value;\n\tvar price=\"\";\n\t\n\tif(departure==\"Adelaide\"){\n\t\tif (arrival== \"Brisbane\"){\n\t\t\tprice= 130;\n\t\t} else if (arrival== \"Canberra\" ||arrival== \"GoldCoast\" ){\n\t\t\tprice= 140;\n\t\t} else if (arrival== \"Darwin\"){\n\t\t\tprice= 100;\n\t\t} else if (arrival== \"Perth\"){\n\t\t\tprice= 170;\n\t\t} \telse if (departure == arrival){\n\t\tprice =0;\n\t} else {\n\t\t\tprice= 120;\n\t\t}\n\t}\n\t\n\telse\tif(departure==\"GoldCoast\"){\n\t\tif (arrival== \"Adelaide\"){\n\t\t\tprice= 129;\n\t\t} else if (arrival== \"Melbourne\" ){\n\t\t\tprice= 140;\n\t\t} else if (departure == arrival){\n\t\tprice =0;\n\t} else {\n\t\t\tprice= 150;\n\t\t}\n\t}\n\t\n\telse if(departure==\"Hobart\"){\n\t\tif (arrival== \"Melbourne\"){\n\t\t\tprice= 99;\n\t\t} else if (departure == arrival){\n\t\tprice =0;\n\t} else {\n\t\t\tprice= 180;\n\t\t}\n\t}\n\t\n\telse if(departure==\"Melbourne\"){\n\t\tif (arrival== \"Adelaide\"){\n\t\t\tprice= 88;\n\t\t} else if (arrival== \"Brisbane\"){\n\t\t\tprice= 100;\n\t\t} else if (arrival== \"Darwin\"){\n\t\t\tprice= 188;\n\t\t} else if (arrival== \"GoldCoast\"){\n\t\t\tprice= 110;\n\t\t} else if (departure == arrival){\n\t\tprice =0;\n\t} else {\n\t\t\tprice= 140;\n\t\t}\n\t}\n\t\n\telse if(departure==\"Perth\"){\n\t\tif (arrival== \"Sydney\" ||arrival== \"Melbourne\" ){\n\t\t\tprice= 199;\n\t\t}\telse if (departure == arrival){\n\t\tprice =0;\n\t} else {\n\t\t\tprice= 220;\n\t\t}\n\t}\n\t\n\telse if(departure==\"Sydney\"){\n\t\tif (arrival== \"Adelaide\"){\n\t\t\tprice= 128;\n\t\t} else if (arrival== \"Hobart\"){\n\t\t\tprice= 128;\n\t\t} else if (arrival== \"Melbourne\"){\n\t\t\tprice= 99;\n\t\t} else if (arrival== \"Perth\"){\n\t\t\tprice= 198;\n\t\t}\telse if (departure == arrival){\n\t\tprice =0;\n\t } else {\n\t\t\tprice= 160;\n\t\t}\n\t}\n\t\n\telse if (departure == arrival){\n\t\tprice =0;\n\t\t} else {\n\t\tprice =200;\n\t} \n\t\n\treturn price;\n\t\n}", "function totalFare() {\n var firstClassTicket = parseInt(document.getElementById('first-class-ticket').value);\n var firstClassFare = 150 * firstClassTicket;\n var economyTicket = parseInt(document.getElementById('economy-ticket').value);\n var economyFare = 100 * economyTicket;\n return firstClassFare + economyFare;\n}", "function getTransitFare(fareComponent) {\n // Default values (if fare component is not valid).\n let digits = 2;\n let transitFare = 0;\n let symbol = \"$\";\n\n if (fareComponent) {\n digits = fareComponent.currency.defaultFractionDigits;\n transitFare = fareComponent.cents;\n symbol = fareComponent.currency.symbol;\n } // For cents to string conversion, use digits from fare component.\n\n\n const centsToString = cents => {\n const dollars = (cents / 10 ** digits).toFixed(digits);\n return `${symbol}${dollars}`;\n }; // For dollars to string conversion, assume we're rounding to two digits.\n\n\n const dollarsToString = dollars => `${symbol}${dollars.toFixed(2)}`;\n\n return {\n centsToString,\n dollarsToString,\n transitFare\n };\n}", "function calculatesFarePrice(pickUpLocation, endingBlock) {\n var tripDistance = distanceTravelledInFeet(pickUpLocation, endingBlock);\n if (tripDistance < 400) {\n return 0;\n } else if (tripDistance > 2500) {\n return 'cannot travel that far';\n } else if (tripDistance > 2000){\n return 25;\n } else {\n return tripDistance * .02;\n }\n }", "function taxiFare(milesTraveled, hourOfDay) {\n\tvar baseFare = 2.50;\n\tvar costPerMile = 2.00;\n\tvar cost = baseFare + (costPerMile * milesTraveled)\n\n\tcost = cost + surCharge(hourOfDay);\n\t\t\n\treturn cost;\n}", "function calculatesFarePrice(x,y){\n if(distanceTravelledInFeet(x,y)<400){\n return 0;\n }\n else if(distanceTravelledInFeet(x,y)>400 && distanceTravelledInFeet(x,y)<2000){\n return p1*(distanceTravelledInFeet(x,y)-400);\n }\n else if(distanceTravelledInFeet(x,y)>2000 && distanceTravelledInFeet(x,y)<2500){\n return 25;\n }\n else if(distanceTravelledInFeet(x,y)>2500){\n return \"cannot travel that far\";\n }\n}", "getFinalCost() {\n // if there is just one station, charge the MAX_COST because tehre isn't the Enter Station\n if (this.points.length == 2) {\n //return the MAX_COST\n this.setCredit(MAX_COST);\n\n // calculate the final cost ( real const )\n var zonesCrossed = this.getZonesCrossed(this.points[0], this.points[1]);\n var isZoneOneCrossed = this.didCrossedZoneOne(this.points[0], this.points[1]);\n var cost = this.getCostByZone(zonesCrossed, isZoneOneCrossed);\n this.fare = cost;\n } else {\n this.fare = MAX_COST;\n }\n\n // console.log(`Fare of £${cost.toFixed(2)}\\n`);\n }", "function calculateFare(connection) {\n console.log(\"calculating fare for \" + JSON.stringify(connection));\n var routeFare = {};\n \n if (connection.trackLength > 500) {\n routeFare.baseAmount = 229;\n } else if (connection.trackLength > 350) {\n routeFare.baseAmount = 199;\n } else if (connection.trackLength > 250) {\n routeFare.baseAmount = 169;\n } else if (connection.trackLength > 150) {\n routeFare.baseAmount = 129;\n } else if (connection.trackLength > 100) {\n routeFare.baseAmount = 99;\n } else if (connection.trackLength > 80) {\n routeFare.baseAmount = 79;\n } else {\n routeFare.baseAmount = 49;\n }\n \n return {\n routeFare\n };\n}", "function calculateFares(itinerary) {\n // Extract fare total from itinerary fares.\n const fareComponent = itinerary.fare && itinerary.fare.fare && itinerary.fare.fare.regular; // Get string formatters and itinerary fare.\n\n const {\n centsToString,\n dollarsToString,\n transitFare\n } = getTransitFare(fareComponent); // Process any TNC fares\n\n let minTNCFare = 0;\n let maxTNCFare = 0;\n itinerary.legs.forEach(leg => {\n if (leg.mode === \"CAR\" && leg.hailedCar && leg.tncData) {\n const {\n maxCost,\n minCost\n } = leg.tncData; // TODO: Support non-USD\n\n minTNCFare += minCost;\n maxTNCFare += maxCost;\n }\n });\n return {\n centsToString,\n dollarsToString,\n maxTNCFare,\n minTNCFare,\n transitFare\n };\n}", "function updateFare() {\n\t\tvar fareVariables = {};\n\t\t\n\t\t// get zone\n\t\tfareVariables.zone = $('#fc-zone').val();\n\n\t\t// get time\n\t\tfareVariables.time = $('#fc-time').val();\n\n\t\t// get where purchase will happen\n\t\tfareVariables.where = $('input[name=\"fc-where\"]').val();\n\n\t\t// get quantity\n\t\tfareVariables.quantity = $('#fc-quantity').val();\n\n\t\t// updates the fare displayed\n\t\tgetFare(fareVariables);\n\t}", "function fareForRide(distanceTraveled, timeWaiting, isNight) {\n changeElementText(\"#distanceTraveled\", distanceTraveled);\n changeElementText(\"#timeWaiting\", timeWaiting);\n changeElementText(\"#nightOrDay\", isNight ? \"night\" : \"day\");\n\n var fare = 20 + 8 * (distanceTraveled - 1) + 4 * timeWaiting;\n\n if (isNight) fare *= 1.5;\n\n changeElementText(\"#fare\", fare);\n}", "function getTotalFare(itinerary) {\n var config = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n\n // Get transit/TNC fares.\n var _calculateFares = calculateFares(itinerary),\n maxTNCFare = _calculateFares.maxTNCFare,\n transitFare = _calculateFares.transitFare; // Start with default cost values.\n\n\n var costs = DEFAULT_COSTS; // If config contains values to override defaults, apply those.\n\n var configCosts = config.itinerary && config.itinerary.costs;\n if (configCosts) Object.assign(costs, configCosts); // Calculate total cost from itinerary legs.\n\n var drivingCost = 0;\n var hasBikeshare = false;\n itinerary.legs.forEach(function (leg) {\n if (leg.mode === 'CAR') {\n // Convert meters to miles and multiple by cost per mile.\n drivingCost += leg.distance * 0.000621371 * costs.drivingCentsPerMile;\n }\n\n if (leg.mode === 'BICYCLE_RENT' || leg.mode === 'MICROMOBILITY' || leg.rentedBike) {\n hasBikeshare = true;\n }\n });\n var bikeshareCost = hasBikeshare ? costs.bikeshareTripCostCents : 0; // If some leg uses driving, add parking cost to the total.\n\n if (drivingCost > 0) drivingCost += costs.carParkingCostCents;\n return bikeshareCost + drivingCost + transitFare + maxTNCFare * 100;\n}", "function calcFare(fareRoutes, segmentsinfo){\n var leapFareA = 0;\n var cashFareA = 0;\n\n var leapFareS = 0;\n var cashFareS = 0;\n\n var leapFareC = 0;\n var cashFareC = 0;\n\n var timeFromPicker = document.getElementById(\"datetimepicker1\").value;\n var predictionTime = new Date(timeFromPicker);\n var hour;\n var day; \n var agents = [];\n\n //If user has selected a date\n if (timeFromPicker != '') {\n hour = predictionTime.getHours();\n day = predictionTime.getDay(); \n } else {\n //if user has not selected a date, use current time \n var today = new Date();\n hour = today.getHours();\n day = today.getDay();\n }\n \n //Find the transit agencies involved in each step\n for (i in segmentsinfo) {\n agents.push(segmentsinfo[i].agency);\n }\n //Remove null values for walking steps \n for (var i=0; i < agents.length; i++){\n if (agents[i] == null){\n agents.splice(i, 1)\n }\n }\n\n var journey = fareRoutes[fareRoutes.length - 1];\n\n // Account for adult/student fares - affected by number of stages\n for (var i=0; i < journey.length; i++){\n if(journey[i] === 0){\n leapFareA += 0;\n cashFareA += 0;\n leapFareS += 0;\n cashFareS += 0;\n } else if (journey[i] > 1 && journey[i] < 4 && agents[i] == \"Dublin Bus\" || agents[i] == \"Go-Ahead\"){\n leapFareA += 1.55;\n leapFareS += 1.55;\n cashFareA += 2.15;\n cashFareS += 2.15;\n } else if (journey[i] > 3 && journey[i] < 14 && agents[i] == \"Dublin Bus\" || agents[i] == \"Go-Ahead\"){\n leapFareA += 2.25;\n leapFareS += 2.25;\n cashFareA += 3.00;\n cashFareS += 3.00;\n } else if (journey[i] > 13 && agents[i] == \"Dublin Bus\" || agents[i] == \"Go-Ahead\"){\n leapFareA += 2.50;\n leapFareS += 2.50;\n cashFareA += 3.30;\n cashFareS += 3.30;\n } \n }\n\n // Account for childrens fares - affected by time of day\n for (var i=0; i < journey.length; i++){ \n if (agents[i] == \"Dublin Bus\" || agents[i] == \"Go-Ahead\"){\n if(journey[i] === 0){\n leapFareC += 0;\n cashFareC += 0;\n } else if (day === 6 && hour < 13) {\n leapFareC += .8;\n cashFareC += 1;\n } else if (day > 0 && day < 6 && hour < 19){\n leapFareC += .8;\n cashFareC += 1;\n } else {\n leapFareC += 1;\n cashFareC += 1.3;\n }\n }\n }\n\n //Accounting for leapcard capping \n if (leapFareA > 7){\n leapFareA = 7;\n }\n if (leapFareS > 5){\n leapFareS = 5;\n } \n if (leapFareC > 2.7){\n leapFareC = 2.7;\n }\n\n //Makes sure price is rounded to 2 decimal places\n leapFareA = leapFareA.toFixed(2);\n cashFareA = cashFareA.toFixed(2);\n leapFareS = leapFareS.toFixed(2);\n cashFareS = cashFareS.toFixed(2);\n leapFareC = leapFareC.toFixed(2);\n cashFareC = cashFareC.toFixed(2);\n\n // build table to display fares \n var fares = \"<table class='fares-table'><tr class='table-header'><td>Est. Dublin Bus Fares</td><td>Adult</td><td>Student</td><td>Child</td></tr>\";\n fares += \"<tr><td class='table-header'>Leap: </td><td>€\" + leapFareA + \"</td><td>€\" + leapFareS + \"</td><td>€\" + leapFareC + \"</td></tr>\";\n fares += \"<tr><td class='table-header'>Cash: </td><td>€\" + cashFareA + \"</td><td>€\" + cashFareS + \"</td><td>€\" + cashFareC + \"</td></tr></table>\";\n \n if (leapFareA != 0.00){\n document.getElementById(\"fares\").innerHTML = fares;\n } else {\n document.getElementById(\"fares\").innerHTML = \"<div></div>\";\n }\n}", "function testCalcFare() {\n var d_loc = new Location(13, 14);\n var p_loc = new Location(18, 19);\n var c_loc = new Location(13, 13);\n var car = new Car('a', c_loc);\n var hcar = new HipsterCar('ha', c_loc);\n var user = new Guy('g1');\n\n var booking_1 = new Booking(car, user, p_loc, d_loc);\n var booking_2 = new Booking(hcar, user, p_loc, d_loc);\n\n assert(booking_1.calcFare() == 100, 'testCalcFare 1 Failed');\n assert(booking_2.calcFare() == 105, 'testCalcFare 2 Failed');\n}", "GetTheCreditBalanceAndTheRemainingPagesAvailableForAllOurFreefax() {\n let url = `/freefax/credits`;\n return this.client.request('GET', url);\n }", "function amountcommi()\n{\n for (var i=0; i<rentals.length;i++)\n {\n //Drivy take a 30% commission on the rental price to cover their costs.\n var commission= rentals[i].price *0.3;\n\n //insurance: half of commission\n rentals[i].commission.insurance = commission *0.5;\n\n //roadside assistance 1€ per day\n rentals[i].commission.assistance = getRentDays(rentals[i].pickupDate,rentals[i].returnDate) +1;\n\n //drivy takes the rest\n rentals[i].commission.drivy= commission - (rentals[i].commission.insurance + rentals[i].commission.assistance);\n }\n\n}", "function fareEstimator(ride_time, ride_distance, cost_per_minute, cost_per_mile) {\n const perMinuteCost = cost_per_minute.map((value) => value * ride_time)\n const perMileCost = cost_per_mile.map((value) => value * ride_distance)\n const result = []\n for (let index = 0; index < perMinuteCost.length; index++) {\n result.push(Math.round((perMinuteCost[index] + perMileCost[index]) * 10)/10)\n }\n return result\n}", "function ticketFareCalculate(){\n const firstClass = document.getElementById('firstClassInput') // collect value from id = 'firstClassInput'\n const firstClassInput = parseInt(firstClass.value)\n\n const economyClass = document.getElementById('economyClassInput') // collect value from id = 'economyClassInput'\n const economyClassInput = parseInt(economyClass.value)\n\n let subtotalFare = 0\n subtotalFare = firstClassInput * 150 + economyClassInput * 100 // got subtotalFare\n document.getElementById('ticketSubtotalFare').innerText = subtotalFare \n\n const tenPercentageVat = (subtotalFare / 100) * 10 // got ticketFareVat\n document.getElementById('ticketFareVat').innerText = tenPercentageVat\n\n let totalFareOfTicket = 0\n totalFareOfTicket = subtotalFare + tenPercentageVat // got totalFareOfTicket\n document.getElementById('totalTicketFare').innerText = totalFareOfTicket\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
=== auto unbox test 0 123 1 "foo" 2 true 3 false === / JSON requires automatic unboxing of the following primitive types: Number, String, Boolean (E5 Section 15.12.3, Str() algorithm, step 4).
function jsonStringifyFastPathAutoUnboxTest() { var values = [ new Number(123), new String('foo'), new Boolean(true), new Boolean(false) ]; values.forEach(function (v, i) { print(i, JSON.stringify(v)); }); }
[ "function coercePrimitiveToObject(obj) {\n\t if(isPrimitiveType(obj)) {\n\t obj = object(obj);\n\t }\n\t if(noKeysInStringObjects && isString(obj)) {\n\t forceStringCoercion(obj);\n\t }\n\t return obj;\n\t }", "function fixObjectValueTypes (o) {\n for (var k in o) {\n var v = o[k];\n\n if (v === 'undefined') o[k] = undefined;\n if (v === 'false') o[k] = false;\n if (v === 'null') o[k] = null;\n if (v === 'true') o[k] = true;\n if (v === 'NaN') o[k] = NaN;\n\n if ((+v) == v && v !== '') o[k] = (+v);\n }\n return o;\n}", "function isPrimitiveType (obj) {\n\t return ( typeof obj === 'boolean' ||\n\t typeof obj === 'number' ||\n\t typeof obj === 'string' ||\n\t obj === null ||\n\t util.isDate(obj) ||\n\t util.isArray(obj));\n\t}", "function isPrimitive(value){return typeof value==='string'||typeof value==='number';}", "function isPrimitiveType (obj) {\n return ( typeof obj === 'boolean' ||\n typeof obj === 'number' ||\n typeof obj === 'string' ||\n obj === null ||\n util.isDate(obj) ||\n util.isArray(obj));\n}", "function isPrimitive(value){return typeof value==='string'||typeof value==='number'||typeof value==='boolean';}", "function toType(str) {\n var type = typeof str;\n if (type !== 'string') {\n return str;\n }\n var nb = parseFloat(str);\n if (!isNaN(nb) && isFinite(str)) {\n return nb;\n }\n if (str === 'false') {\n return false;\n }\n if (str === 'true') {\n return true;\n }\n\n try {\n str = JSON.parse(str);\n } catch (e) {}\n\n return str;\n }", "function isPrimitive(value){return typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean';}", "function valuify(string) {\n if (JSON_STRING.test(string)) {\n return JSON.parse(string);\n }\n return string;\n }", "function decode(data) {\n if (data === null) {\n return data;\n }\n if (data['@type']) {\n switch (data['@type']) {\n case LONG_TYPE:\n // Fall through and handle this the same as unsigned.\n case UNSIGNED_LONG_TYPE: {\n // Technically, this could work return a valid number for malformed\n // data if there was a number followed by garbage. But it's just not\n // worth all the extra code to detect that case.\n const value = parseFloat(data.value);\n if (_.isNaN(value)) {\n console.error('Data cannot be decoded from JSON.', data);\n throw new Error('Data cannot be decoded from JSON: ' + data);\n }\n return value;\n }\n default: {\n console.error('Data cannot be decoded from JSON.', data);\n throw new Error('Data cannot be decoded from JSON: ' + data);\n }\n }\n }\n if (_.isArray(data)) {\n return _.map(data, decode);\n }\n if (_.isObject(data)) {\n // It's not safe to use _.forEach, because the object might be 'array-like'\n // if it has a key called 'length'.\n return _.mapValues(data, decode);\n }\n // Anything else is safe to return.\n return data;\n}", "function toObject(primitive) {\n if(typeof primitive == \"object\" && null != primitive) {\n return primitive;\n }\n else {\n /* if input isn't null, undefined, boolean, or infinity */\n if(typeof primitive != \"undefined\" &&\n typeof primitive != \"boolean\" &&\n primitive != Infinity &&\n null != primitive) {\n /* return an object */\n return new String(primitive);\n }\n else {\n /* otherwise, return an empty object */\n return [];\n }\n }\n }", "function primitives(value) {\n return value instanceof Primitive ? Primitive(value) : value;\n }", "function test42() {\n const stringObj = new String('foo');\n\n console.log(stringObj);\n // expected output: String { \"foo\" }\n\n console.log(stringObj.valueOf());\n // expected output: \"foo\"\n}", "function ejson_to_bytes_(b, x) {\n switch (typeof x) {\n case 'boolean': {\n let s = new ArrayBuffer(1);\n (new Uint8Array(s))[0] = x ? 2 : 1; // tag\n b.append(s);\n return;\n }\n case 'string': {\n let utf8 = string_to_bytes(x)\n let s = new Uint8Array(5);\n let v = new DataView(s.buffer);\n s[0] = 5; // tag\n v.setUint32(1, utf8.byteLength, true);\n b.append(s.buffer);\n b.append(utf8);\n return;\n }\n case 'number': {\n let s = new ArrayBuffer(9);\n let v = new DataView(s);\n v.setUint8(0, 3); // tag\n v.setFloat64(1, x, true);\n b.append(s);\n return;\n }\n case 'object': {\n if (x === null) {\n let s = new ArrayBuffer(1);\n (new Uint8Array(s))[0] = 0; // tag\n b.append(s);\n return;\n }\n if (Array.isArray(x)) {\n let s = new Uint8Array(5);\n let v = new DataView(s.buffer);\n s[0] = 6; // tag\n v.setUint32(1, x.length, true);\n b.append(s.buffer);\n for (let i = 0; i < x.length; i++) {\n ejson_to_bytes_(b, x[i]);\n }\n return;\n }\n let keys = Object.getOwnPropertyNames(x);\n if ( keys.length === 1 ) {\n switch (keys[0]) {\n case '$nat': {\n let s = new ArrayBuffer(9);\n let v = new DataView(s);\n v.setUint8(0, 4); // tag\n v.setBigInt64(1, BigInt(x.$nat), true);\n b.append(s);\n return;\n }\n }\n }\n // it's an object!\n let s = new Uint8Array(5);\n let v = new DataView(s.buffer);\n s[0] = 7; // tag\n v.setUint32(1, keys.length, true);\n b.append(s.buffer);\n for (let i = 0; i < keys.length; i++) {\n let k = keys[i];\n // write key as utf8 string with byte length prefix\n let utf8 = string_to_bytes(k);\n let s = new Uint8Array(4);\n let v = new DataView(s.buffer);\n v.setUint32(0, utf8.byteLength, true);\n b.append(s.buffer);\n b.append(utf8);\n // write value\n ejson_to_bytes_(b, x[k]);\n }\n return;\n }\n default:\n throw new Error(`unknown type: ${typeof x}`);\n }\n}", "function primitives (value) {\n return value instanceof Primitive ? Primitive(value) : value\n }", "function fixLongInts(rawBytes) {\n if (!rawBytes)\n return rawBytes;\n\n var matchNonQuotedLongInts = /\"(?:[^\"\\\\]|\\\\.)*\"|'(?:[^'\\\\]|\\\\.)*'|([:\\s][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]*)[,\\s}]/ig;\n var longIntCount = 0;\n var matchArray = matchNonQuotedLongInts.exec(rawBytes);\n while (matchArray != null) {\n if (matchArray[1]) // group 1, a non-quoted long int\n longIntCount++;\n matchArray = matchNonQuotedLongInts.exec(rawBytes);\n }\n\n //console.log(\"Got response, longIntcount: \" + longIntCount + \", raw bytes: \" + rawBytes);\n\n // if no long ints, just return the original bytes parsed\n\n if (longIntCount == 0) try {\n return(JSON.parse(rawBytes));\n }\n catch (e) {\n return(rawBytes);\n }\n\n // otherwise copy the raw bytes, replace all long ints in the copy, and add the raw bytes as a new field on the result\n else {\n matchNonQuotedLongInts.lastIndex = 0;\n matchArray = matchNonQuotedLongInts.exec(rawBytes);\n //console.log(\"Old raw: \" + rawBytes);\n var result = JSON.parse(rawBytes);\n var newBytes = \"\";\n var curBytes = rawBytes;\n\n while (matchArray != null) {\n if (matchArray[1]) { // group 1, a non-quoted long int\n //console.log(\" Got longInt: \" + matchArray[1] + \" with lastMatch: \" + matchNonQuotedLongInts.lastIndex);\n //console.log(\" remainder: \" + rawBytes.substring(matchNonQuotedLongInts.lastIndex));\n var matchLen = matchArray[1].length;\n newBytes += curBytes.substring(0,matchNonQuotedLongInts.lastIndex - matchLen - 1) + '\"' +\n matchArray[1] + '\"';\n curBytes = curBytes.substring(matchNonQuotedLongInts.lastIndex - 1);\n matchNonQuotedLongInts.lastIndex = 0;\n }\n matchArray = matchNonQuotedLongInts.exec(curBytes);\n }\n newBytes += curBytes;\n //console.log(\"New raw: \" + newBytes);\n result = JSON.parse(newBytes);\n\n // see if we can pull just the result out of the rawBytes\n var rawResult = null;//findResult(rawBytes);\n\n if (rawResult)\n result.rawJSON = rawResult;\n else\n result.rawJSON = rawBytes;\n\n return result;\n }\n }", "function Fay$$unserialize(type,jsObj){\n var base = type[0];\n var args = type[1];\n var fayObj;\n switch(base){\n case \"action\": {\n // Unserialize a \"monadic\" JavaScript return value into a monadic value.\n fayObj = Fay$$return(Fay$$unserialize(args[0],jsObj));\n break;\n }\n case \"string\": {\n // Unserialize a JS string into Fay list (String).\n fayObj = Fay$$list(jsObj);\n break;\n }\n case \"list\": {\n // Unserialize a JS array into a Fay list ([a]).\n var serializedList = [];\n for (var i = 0, len = jsObj.length; i < len; i++) {\n // Unserialize each JS value into a Fay value, too.\n serializedList.push(Fay$$unserialize(args[0],jsObj[i]));\n }\n // Pop it all in a Fay list.\n fayObj = Fay$$list(serializedList);\n break;\n }\n case \"double\": {\n // Doubles are unboxed, so there's nothing to do.\n fayObj = jsObj;\n break;\n }\n case \"unknown\": {\n // Any unknown values can be left as-is.\n fayObj = jsObj;\n break;\n }\n case \"bool\": {\n // Bools are unboxed.\n fayObj = jsObj;\n break;\n }\n default: throw new Error(\"Unhandled unserialize type: \" + base);\n }\n return fayObj;\n}", "function smellsLikeJavaObject(e) {\n return _.isObject(e) && !_.isArray(e) && !isLongValue(e);\n }", "transform(cachedValue) {\n if (cachedValue.length <= 14) {\n const numberValue = cachedValue * 1;\n if (!isNaN(numberValue)) {\n return numberValue;\n }\n }\n if (cachedValue === \"true\") {\n return true;\n }\n if (cachedValue === \"false\") {\n return false;\n }\n if (cachedValue.startsWith(\"[\") && cachedValue.endsWith(\"]\") || (cachedValue.startsWith(\"{\") && cachedValue.endsWith(\"}\"))) {\n try {\n return JSON.parse(cachedValue);\n }\n catch (e) { }\n }\n return cachedValue;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The kixcursor contain a kixcursorname dom, which is only set when it is not the users cursor
function getUserCaretDom() { var carets = document.querySelectorAll(classNames.cursor); for (var i = 0; i < carets.length; i++) { var nameDom = carets[i].querySelectorAll(classNames.cursorName); var name = nameDom[0].innerText; if (!name) return carets[i].querySelectorAll(classNames.cursorCaret)[0]; } throw 'Could not find the users cursor'; }
[ "static set defaultCursor(value) {}", "function containsUserCaretDom() {\n var carets = document.querySelectorAll(classNames.cursor);\n for (var i = 0; i < carets.length; i++) {\n var nameDom = carets[i].querySelectorAll(classNames.cursorName);\n var name = nameDom[0].innerText;\n if (!name) return true;\n }\n return false;\n }", "function showCursor(cur)\n {\n if (cur != undefined) selectCursor(cur);\n container.style.cursor = currentCursor;\n\t}", "function ckeckcursor(){\n var cursorprop;\n var bdy = document.getElementsByTagName(\"body\");\n if(bdy[0].hasAttribute(\"style\")){\n cursorprop=bdy[0].style.cursor;\n\n }else {\n var style = window.getComputedStyle(bdy[0]);\n cursorprop = style.getPropertyValue('cursor');\n }\n if(cursorprop == \"none\"){\n bdy[0].style.cursor= \"default\"\n chrome.runtime.sendMessage({todo: \"Cursorjacking\"});\n }\n}", "function cursorX() {\n return cx;\n }", "function dfhinqcursor(key) {\n\tdocument.form3270.DFH_CURSOR.value = key;\n}", "function askcursor(){if(asknumtxt==0){askoffset=L-3;}else{askoffset=0;}; key=999;}", "static get defaultCursor() {}", "get cursor() {\n return this.canvas.style.cursor;\n }", "function set_cursor(obj, cur) {\n\t\t$(obj).css({cursor:cur});\n\t}", "function enableCursors(){ \r\n $(\"#\"+parameters.containerId+' .dragCursor').mousedown(function(ev){\r\n //get selected cursor\r\n var selAttrId = $(this).attr('id');\r\n for (key in cursorMap){\r\n if ( cursorMap[key] == selAttrId ){\r\n drag.selectedCursor = parseInt(key);\r\n }\r\n }\r\n //boxes near selected cursors\r\n drag.firstBox = boxMap[drag.selectedCursor];\t\t\t\t\t\t \r\n drag.secondBox = boxMap[drag.selectedCursor+1];\t\t\t\t\t\t\t\t\r\n drag.enable = true;\r\n drag.oldPosition = ev.pageX;\r\n ev.preventDefault();//disable text selection on drag and drop\r\n });\t\t\t\t\t\r\n }", "function placeCursorOnLoad () {\n $(\"input[name=user_name]\").focus();\n}", "function setCursor(divLayer, cursor) {\n\tvar dObj = getLayer(divLayer);\n\tif (dObj!=null) {\n\t\tdObj.cursor = cursor;\n\t\ttheCursor = dObj.cursor;\n\t}\n}", "function CursorInfo() { }", "showCursor() {\n\n\t\tif( this.cursorHidden ) {\n\t\t\tthis.cursorHidden = false;\n\t\t\tthis.Reveal.getRevealElement().style.cursor = '';\n\t\t}\n\n\t}", "function PinnableCursor() {}", "_serviceCursor() {\n if (this.cursorState) {\n this.svgText.renderCursorAt(this.textPos - 1, this.textType);\n } else {\n this.svgText.removeCursor();\n }\n this.cursorState = !this.cursorState;\n }", "_getCursor() {\n const isInteractive =\n this.props.onChangeViewport ||\n this.props.onClickFeature ||\n this.props.onHoverFeatures;\n\n if (!isInteractive) {\n return 'inherit';\n }\n if (this.props.isDragging) {\n return config.CURSOR.GRABBING;\n }\n if (this.props.isHovering) {\n return config.CURSOR.POINTER;\n }\n return config.CURSOR.GRAB;\n }", "showCursor() {\n this.$cursorLayer.showCursor();\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Fetch all discussions form GitHub API
function fetchDiscussions(callback) { var comments = Comments(conf); comments.get(ret, function(err, comments) { if (err) { return callback(err); } ret.discussions = comments; callback(); }); }
[ "function getDiscussions()\n{\n var url = URL + '/discussion_topics' + ITEMS_PER_PAGE; // Pass global URL to url so we can change it\n \n var apiParameters = [ \"title\",\n \"html_url\",\n \"published\",\n//State\n \"discussion_type\",\n \"pinned\",\n \"podcast_url\",\n \"read_state\",\n \"require_initial_post\",\n \"discussion_subentry_count\", \n//Dates\n \"posted_at\",\n \"delayed_post_at\",\n \"locked\",\n \"lock_at\",\n//User\n \"user_name\"\n ];\n \n return paginatingCallToCanvas( url, apiParameters );\n \n}", "async fetchDiscussion() {\n await fetch(this._getPath(this.source, this.params))\n .then((response) => response.json())\n .then((data) => (this.__data = this._handleRawData(data)));\n }", "getDiscussions() {\n return __awaiter(this, void 0, void 0, function* () {\n const query = \"select * from discussions\";\n const connection = yield this.pool.getConnection();\n const [result] = yield connection.query(query);\n connection.release();\n return result;\n });\n }", "function getDiscussions(space_url) {\n\n osapi.jive.corev3.discussions.get({\n fields: '@all',\n count: 50,\n place: space_url\n }).execute(function (response) {\n //console.log(\"Discussions: \"+JSON.stringify(response));\n\n var disc = response.list;\n var postDisc;\n var disc_length = response.list.length;\n if (disc_length == 0) {\n disc_row = '<table id=\"discTable\" border=\"0\" class=\"jiveBorder\" jive-data-cell=\"{&quot;color&quot;:&quot;#575757&quot;,&quot;textAlign&quot;:&quot;left&quot;,&quot;padding&quot;:&quot;2&quot;,&quot;backgroundColor&quot;:&quot;transparent&quot;,&quot;fontFamily&quot;:&quot;arial,helvetica,sans-serif&quot;,&quot;verticalAlign&quot;:&quot;baseline&quot;}\" jive-data-header=\"{&quot;color&quot;:&quot;#FFFFFF&quot;,&quot;backgroundColor&quot;:&quot;#6690BC&quot;,&quot;textAlign&quot;:&quot;left&quot;,&quot;padding&quot;:&quot;2&quot;,&quot;fontFamily&quot;:&quot;arial,helvetica,sans-serif&quot;,&quot;verticalAlign&quot;:&quot;baseline&quot;}\" style=\"border: 1px solid #000000; width: 450px;\">' +\n '<tr><td colspan=\"4\" style=\"border:1px ;border: 1px solid #000000;width: 60px;padding: 2px;color: #ffffff;background-color: #6690bc;text-align: center;\" valign=\"middle\"><strong>No discussions in this place.</strong></td></tr>';\n } else {\n disc_row = '<table id=\"discTable\" border=\"0\" class=\"jiveBorder\" jive-data-cell=\"{&quot;color&quot;:&quot;#575757&quot;,&quot;textAlign&quot;:&quot;left&quot;,&quot;padding&quot;:&quot;2&quot;,&quot;backgroundColor&quot;:&quot;transparent&quot;,&quot;fontFamily&quot;:&quot;arial,helvetica,sans-serif&quot;,&quot;verticalAlign&quot;:&quot;baseline&quot;}\" jive-data-header=\"{&quot;color&quot;:&quot;#FFFFFF&quot;,&quot;backgroundColor&quot;:&quot;#6690BC&quot;,&quot;textAlign&quot;:&quot;left&quot;,&quot;padding&quot;:&quot;2&quot;,&quot;fontFamily&quot;:&quot;arial,helvetica,sans-serif&quot;,&quot;verticalAlign&quot;:&quot;baseline&quot;}\" style=\"border: 1px solid #000000; width: 450px;\">' +\n\n '<tr>' +\n '<td style=\"border:1px solid black;border: 1px solid #000000;width: 60px;padding: 2px;color: #ffffff;background-color: #6690bc;text-align: right;\" valign=\"middle\"><strong>' + 'All<input type=\"checkbox\" id=\"sel_all_disc\" onclick=\"javascript:checkedAll(this.id);\">' + '</strong></th>' +\n '<td style=\"border:1px solid black;border: 1px solid #000000;width: 450px;padding: 2px;color: #ffffff;background-color: #6690bc;text-align: left;\" valign=\"middle\"><strong>&nbsp; Title</strong></th>' +\n '<td style=\"border:1px solid black;border: 1px solid #000000;width: 160px;padding: 2px;color: #ffffff;background-color: #6690bc;text-align: left;\" valign=\"middle\"><strong>&nbsp; Author</strong></th>' +\n '</tr>';\n\n $.each(disc, function (index, group) {\n postDisc = {\n title: \"\",\n author: \"\",\n updated: \"\",\n discUrl: \"\"\n }\n\n postDisc.title = group.subject;\n postDisc.author = group.author.name.formatted;\n postDisc.updated = group.updated;\n postDisc.discUrl = group.resources.self.ref;\n\n disc_row = disc_row + '<tr>' +\n '<td style=\"border:1px solid black;border: 1px solid #000000;text-align: right;padding: 2px;\">' + '<input type=\"checkbox\" name=\"disc_cb\" class=\"disc_cb\" onclick=\"javascript:checkUncheck(this.name);\" value=\"' + postDisc.discUrl + '\">' + '</td>' +\n '<td style=\"border:1px solid black;border: 1px solid #000000;padding: 2px;\">' + postDisc.title + '</td>' +\n '<td style=\"border:1px solid black;border: 1px solid #000000;padding: 2px;\">' + postDisc.author + '</td>' +\n '</tr>';\n });\n }\n disc_row = disc_row + '</table>';\n document.getElementById(\"disc_div\").innerHTML = disc_row;\n });\n\n}", "function getAllByDiscussion(req, res, next) {\n // It's not clear this operation should return all messages or only root-level messages from the Swagger file.\n // So I made it configurable. When app.query.onlyRootMessages is true, this operation returns only root-level messages.\n // Be default, app.query.onlyRootMessages is set to false and this operation returns all messages.\n var filters = {\n where: {\n discussionId: req.swagger.params.discussionId.value\n }\n };\n if (queryConfig.onlyRootMessages) {\n filters.where.parentMessageId = null;\n }\n\n // get all messages(or root-level only) in a discussion\n _findMessages(req, filters, function(err, totalCount, messages) {\n if (!err) {\n req.data = {\n success: true,\n status: 200,\n metadata: {\n totalCount: totalCount\n },\n content: messages\n };\n } \n next();\n });\n\n}", "function getDiscussion(data) {\n\t\t\ttry {\n\t\t\t\tvar url = null;\n\t\t\t\t// Get URL from top post on page\n\t\t\t\t// var url = data.data.children[0].data.url;\n\t\t\t\t// Loop through posts and see if any of them contain the movie title\n\t\t\t\tfor (var i = 0; i < data.data.children.length; i++) {\n\t\t\t\t\tvar postTitle = data.data.children[i].data.title.toLowerCase();\n\t\t\t\t\tif (postTitle.includes(title.toLowerCase())) {\n\t\t\t\t\t\turl = data.data.children[i].data.url;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (url === null) {\n\t\t\t\t\tthrow new Error(\"No movie discussion found.\");\n\t\t\t\t}\n\t\t\t} catch (err) {\n\t\t\t\tfailSafe(err);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Add .json to use the API\n\t\t\tvar sort = \"?sort=confidence\";\n\t\t\tvar newURL = url + \".json\";\n\t\t\t// Ajax call to get the discussion page json\n\t\t\t$.ajax({\n\t\t\t\turl: newURL,\n\t\t\t\tdataType: \"json\",\n\t\t\t\tmethod: \"GET\",\n\t\t\t\tsuccess: function(result) {\n\t\t\t\t\tgetComments(result);\n\t\t\t\t},\n\t\t\t\terror: function(result) {\n\t\t\t\t\tfailSafe(result);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t});\n\t\t}", "function getDiscussions(req, res, next) {\n async.waterfall([\n function(callback) { \n // create a default filters\n var filters = {\n offset: 0,\n limit: queryConfig.pageSize,\n where: {}\n };\n // req.swagger.params returns empty value for non-existing parameters, it can't determine it's non-existing\n // or empty value. So req.query should be used to validate empty value and not-supported parameters.\n // parse request parameters\n _.each(_.keys(req.query), function(key) {\n if (key === 'offset' || key === 'limit') {\n paramHelper.parseLimitOffset(req, filters, key, req.query[key]);\n } else if (key === 'orderBy') {\n paramHelper.parseOrderBy(Discussion, req, filters, req.query[key]);\n } else if (key === 'filter') {\n paramHelper.parseFilter(Discussion, req, filters, req.query[key]);\n } else {\n routeHelper.addValidationError(req, 'Request parameter ' + key + ' is not supported');\n }\n });\n callback(req.error, filters);\n },\n function(filters, callback) {\n // get discussions and total count\n _findDiscussions(req, filters, function(err, totalCount, discussions) {\n callback(err, totalCount, discussions);\n });\n }\n ], function(err, totalCount, discussions) {\n if (!err) {\n req.data = {\n success: true,\n status: 200,\n metadata: {\n totalCount: totalCount\n },\n content: discussions\n };\n } \n next();\n });\n\n}", "async function fetchIssues () {\r\n const result = await ghrepo.issuesAsync({ state: 'open' }) // Fetch open issues\r\n const issues = result[0].map(issue => ({\r\n id: issue.id,\r\n number: issue.number,\r\n user: issue.user.login,\r\n title: issue.title,\r\n body: issue.body,\r\n link: issue.html_url,\r\n createdAt: issue.created_at.toLocaleString('en-US'),\r\n updatedAt: issue.updated_at.toLocaleString('en-US'),\r\n commentCounter: issue.comments\r\n }))\r\n\r\n const last = issues.map(async issue => {\r\n const reposIssue = await client.issue(repoName, issue.number)\r\n const reposComments = await reposIssue.commentsAsync() // Fetch comments for each issue\r\n const comments = reposComments[0].map(comment => ({\r\n id: comment.id,\r\n body: comment.body,\r\n user: comment.user.login,\r\n userImage: comment.user.avatar_url,\r\n updatedAt: comment.updated_at.toLocaleString('en-US')\r\n }))\r\n issue.comments = comments\r\n })\r\n await Promise.all(last)\r\n return issues\r\n}", "function getAnnouncements()\n{\n var url = URL + '/discussion_topics?only_announcements=1' + ITEMS_PER_PAGE; //Pass global URL to url so we can change it\n \n var apiParameters = [ \"title\",\n \"html_url\",\n \"published\",\n \"discussion_type\",\n \"require_initial_post\",\n \"podcast_url\",\n \"podcast_has_student_posts\",\n//State \n \"discussion_subentry_count\", \n \"topic_children\",\n \"attachments\", \n \"read_state\",\n//Dates\n \"delayed_post_at\",\n \"last_reply_at\",\n \"locked\",\n \"lock_at\",\n//Message\n \"author\"\n ];\n \n \n return paginatingCallToCanvas( url, apiParameters ); \n \n}", "function getAllByDiscussion(req, res, next) {\n var filters = {\n where: {\n discussionId: req.swagger.params.discussionId.value\n }\n };\n\n Message.findAll(filters).success(function(messages) {\n async.each(messages, function(message, callback) {\n // fetch all child messages\n Message.findAll({where: {parentMessageId: message.messageId}}).success(function(children) {\n message.dataValues.messages = children;\n callback();\n })\n .error(function(err) {\n routeHelper.addError(req, err);\n callback(err);\n });\n }, function(err) {\n if (err) {\n routeHelper.addError(req, err);\n } else {\n req.data = {messages: messages};\n }\n next();\n });\n })\n .error(function(err) {\n routeHelper.addError(req, err);\n next();\n });\n}", "async function fetchGroupDiscussions(groupID, page, pageSize=10){\n\tlet resp = await ajax({url:`/groups/groupdiscussions?groupID=${groupID}&page=${page}&limit=${pageSize}`});\n\tlet data = await resp.json();\n\treturn data;\n}", "function getSourceDiscussions() {\n return new Promise((resolve, reject) => {\n canvas.get(`/api/v1/courses/${sourceCourseID}/discussion_topics`, (err, discussions) => {\n if (err) return reject(err);\n discussions = discussions.filter(discussion => discussion.group_category_id !== null);\n resolve(discussions);\n });\n });\n }", "function getIssues() {\n //once an issue is submitted, fetch all open issues to see the issues you are creating\n const repoName = 'js-ajax-fetch-lab';\n const fullURL = `${baseURL}/repos/${user}/${repoName}/issues`;\n\n fetch(fullURL, {\n headers: {\n Authorization: `token ${getToken()}`\n }\n })\n .then(res => res.json())\n //.then(json => console.log(json))\n .then(json => showIssues(json))\n\n}", "function loadDiscussionTopics() {\n API.discussionTopics.get()\n .then((res) => {\n const result = Array.from(res.data);\n const response = result.map((resObj) => resObj.topic);\n setTopics(response);\n })\n .catch((err) => console.log(err));\n }", "function preFetchDiscussionsPosts(discussions) {\n angular.forEach(discussions, function(discussion) {\n var discussionid = discussion.discussion;\n $mmaModForum.getDiscussionPosts(discussionid);\n });\n }", "listAll(req, res) {\n Discussion.all().then(function(dbDiscussions) {\n res.render(\"discussions\", { hbsDiscussions: dbDiscussions });\n });\n }", "getAll(exerciseId) {\n return this.comments\n .get(`/${exerciseId}`)\n .then(({ data }) => data);\n }", "function getIssues() {\n const repo = 'js-ajax-fetch-lab'\n const url = `${baseURL}/repos/${user}/${repo}/issues`\n const req = new XMLHttpRequest();\n req.addEventListener('load', displayIssues);\n // req.open('GET', url);\n // req.send();\n fetch(url, {\n method: 'GET',\n headers: {\n Authorization: `token ${getToken()}`\n }\n })\n\n //once an issue is submitted, fetch all open issues to see the issues you are creating\n}", "async function fetchUserGroupDiscussions(page, pageSize=10){\n\tlet resp = await ajax({url:`/groups/usergroupdiscussions?page=${page}&limit=${pageSize}`});\n\tlet data = await resp.json();\n\treturn data;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Maptimize.Proxy.GoogleMapaddEventListener(source, event, object, method) > GEventListener source (Object): source object. event (String): event name. object (Object): object used for calling method. method (Function): function called when event is fired. Registers an invocation of the method on the given object as the event handler for a custom event on the source object. Returns a handle that can be used to eventually deregister the handler.
function addEventListener(source, event, object, method) { return GEvent.bindDom(source, event, object, method); }
[ "_addEventListener( eventName, listener, method ) {\n // Check for a qualified event name with a ':' separator.\n let idx = eventName.indexOf(':');\n if( idx > 0 ) {\n // Lookup the event source.\n let sourceName = eventName.substring( 0, idx );\n let source = this.services[sourceName];\n if( source === undefined ) {\n // No event source currently bound, register a listener for a\n // service bind event using the event source name and try adding\n // the listener again when a service of the required name registers.\n const app = this;\n this.onServiceBind( sourceName, () => {\n app._addEventListener( eventName, listener, method );\n });\n // Do no more.\n return;\n }\n // Check that the source is an event emitter.\n if( !(source instanceof EventEmitter) ) {\n throw new Error(`Event source must be an EventEmitter: ${sourceName}`);\n }\n // Strip the source name from the event name.\n eventName = eventName.substring( idx + 1 );\n // Invoke the required method on the source.\n source[method]( eventName, listener );\n // All done.\n return;\n }\n // Strip any ':' prefix from the event name.\n if( idx == 0 ) {\n eventName = eventName.substring( 1 );\n }\n // Call the required method on the super class.\n super[method]( eventName, listener );\n }", "function eventProxy(event) {\n this._listeners[event.type](event);\n}", "addEventListener(event, listener) {\n\t\tthis.events.on(event, listener);\n\t}", "on(event, callback) {\n if (this.customEvents[event])\n this.customEvents[event].push(callback)\n else\n document.addEventListener(event, callback)\n }", "addListener(event, callback) {\n this.callbacks[event].push(callback);\n }", "addListener(event, listener) {\n this.ee.addListener(event, listener);\n }", "addEventHandler(obj, eventName, handler) {\n\t\tif (document.attachEvent) {\n\t\t\t/* For browsers that don\"t support DOM Level 2. */\n\t\t\tobj.attachEvent(\"on\" + eventName, handler);\n\t\t} else if (document.addEventListener) {\n\t\t\t/* For modern browsers. */\n\t\t\tobj.addEventListener(eventName, handler, false);\n\t\t}\n\t}", "addEventSource(source) {\n return this.lambda.addEventSource(source);\n }", "function eventProxy(e) {\n\t\treturn this._listeners[e.type](_options2.default.event && _options2.default.event(e) || e);\n\t}", "function tswUtilsAddEventHandler(obj, eventName, funct)\n{\n\tif(obj.addEventListener)\n\t{\n\t\tobj.addEventListener(eventName, funct, false);\n\t}\n\telse if(obj.attachEvent)\n\t{\n\t\tobj.attachEvent('on'+eventName, funct);\n\t}\n}", "function addListener(e, wrapped_handler) {\n\t\t\tsocket.on(e, wrapped_handler);\n\t\t}", "function addListener(e, wrapped_handler){\n\t\t\tsocket.on(e, wrapped_handler);\n\t\t}", "function proxyEvent(event) {\n return function () {\n if (this.route && this.route[event]) {\n log(\"cherrytree:\", this.route.name + \"#\" + event);\n return this.route[event].apply(this.route, arguments);\n } else {\n return true;\n }\n };\n }", "function eventProxy(e) {\n return this._listeners[e.type](options.event && options.event(e) || e);\n }", "function registerListener(event, fn){\r\n if(!listeners[event]){\r\n listeners[event] = [ fn ];\r\n } else{\r\n listeners[event].push(fn);\r\n }\r\n}", "function eventProxy(e) {\n return this._listeners[e.type](options.event && options.event(e) || e);\n }", "function addhandler(obj, eventname, handler, capture) {\n\tcapture = capture || false\n\tobj.addEventListener(eventname, handler, capture)\n\treturn function () {\n\t\tobj.removeEventListener(eventname, handler, capture)\n\t}\n}", "function addListener(e, wrapped_handler) {\n socket.on(e, wrapped_handler);\n }", "function addEvent(evt,obj,handler){\n if(obj.addEventListener){\n obj.addEventListener(evt,handler,false);\n }else if(obj.attachEvent){\n obj.attachEvent(\"on\"+evt,handler);\n }else{\n throw new Error(\"The supplied object does not support either event methods.\");\n }\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets all the listeners for text input areas. Most importantly, if text area left empty, can't proceed to next section.
function setTextListeners() { for (let i = 1; i < customizationSections.length; i++) { document .getElementById(customizationSections[i] + "_text") .addEventListener("input", function() { updateStoreFromTextArea(customizationSections[i]); if ( this.value.trim() == "" && currentSection == customizationSections[i] + "_section" ) { document.getElementById("next_button").disabled = true; } else { document.getElementById("next_button").disabled = false; } }); } }
[ "function setTextAreaCallBack() {\n textAreaElement.keyup(function(e) {\n executeMapCreation(e);\n });\n\n textAreaElement.click(function(e) {\n emphasizeNode(e);\n });\n\n // IME入力中に箱書いたり、テキストボックスを操作されると辛いのでブロック\n textAreaElement.on({\n 'compositionstart': function() {\n isCompostioning = true;\n },\n 'compositionend': function(e) {\n isCompostioning = false;\n executeMapCreation(e);\n },\n });\n }", "function bind_text_events() {\n $('.plain-text-area.docviewer-editing').live('blur', function (ev) {\n var id = window.location.pathname.split('/')[2];\n var viewer = docviewer.viewers[\"doc-\"+id];\n var currentPage = viewer.api.currentPage();\n var text = $('#plain-text-area-'+currentPage).text();\n if (viewer.schema.text[currentPage-1] != text) {\n viewer.schema.text[currentPage-1] = text;\n modified_pages.push(currentPage);\n }\n else {\n if (modified_pages.length == 0) {\n $('.docviewer-textView span').text('Text');\n $('#form-edition').hide();\n asterisk();\n }\n }\n });\n asterisk();\n }", "function yanaInitTextareas()\n{\n yanaAddEventListener('onmouseover', function(e, node) {window.focusedTextarea = node.id;}, 'textarea');\n yanaAddEventListener('onkeydown', function(e, node) {window.focusedTextarea = node.id;}, 'textarea');\n yanaAddEventListener(\n 'onkeypress', function(e, node) { if (node.maxlength) yanaMaxLength(node, node.maxlength, e);}, 'textarea'\n );\n yanaAddEventListener('onsubmit', yanaCheckEmbTags, 'form');\n yanaAddEventListener('onload', yanaInitTextareas, 'body');\n return true;\n}", "function bind_text_events() {\n $('.plain-text-area.docviewer-editing').live('blur', function (ev) {\n var id = window.location.pathname.split('/')[2];\n var viewer = docviewer.viewers[\"doc-\"+id];\n var currentPage = viewer.api.currentPage();\n// var text = $('#plain-text-area-'+currentPage).text();\n var selector\n if (viewer.state == 'ViewDual')\n selector = $('#lower #plain-text-area-'+currentPage)\n else\n selector = $('#upper #plain-text-area-'+currentPage)\n var text = getTextFromEditableContent(selector);\n if (viewer.schema.text[currentPage-1] != text) {\n viewer.schema.text[currentPage-1] = text;\n modified_pages.push(currentPage);\n }\n else {\n if (modified_pages.length == 0) {\n $('.docviewer-textView span').text('Text');\n $('.docviewer-dualView span').text('Dual');\n $('#form-edition').hide();\n asterisk();\n }\n }\n });\n asterisk();\n }", "function setWelcomeInputListeners() {\n for (let i = 0; i < welcomeInputs.length; i++) {\n document\n .getElementById(welcomeInputs[i] + \"_text\")\n .addEventListener(\"input\", function() {\n updateStoreFromTextArea(welcomeInputs[i]);\n\n if (\n document.getElementById(\"first_name_text\").value.trim() != \"\" &&\n document.getElementById(\"last_name_text\").value.trim() != \"\" &&\n document.getElementById(\"email_text\").value.match(emailFormat) &&\n document.getElementById(\"phone_number_text\").value.match(phoneFormat)\n ) {\n document.getElementById(\"welcome_new\").disabled = false;\n } else {\n document.getElementById(\"welcome_new\").disabled = true;\n }\n });\n }\n}", "clearTextListeners() {\n this._textRegexpCallbacks = [];\n }", "function addEventListeners() {\n for(i=0; i < document.forms.length; i++) {\n for(j=0; j < document.forms[i].elements.length; j++) {\n if(document.forms[i].elements[j].type == \"textarea\") {\n document.forms[i].elements[j].addEventListener(\"input\",warn,false);\n }\n }\n }\n}", "function initTextarea() {\n elmInputBox = $(domInput); //Get the text area target\n\n //If the text area is already configured, return\n if (elmInputBox.attr('data-mentions-input') === 'true') {\n return;\n }\n\n elmInputWrapper = elmInputBox.parent(); //Get the DOM element parent\n elmWrapperBox = $(settings.templates.wrapper());\n elmInputBox.wrapAll(elmWrapperBox); //Wrap all the text area into the div elmWrapperBox\n elmWrapperBox = elmInputWrapper.find('> div.mentions-input-box'); //Obtains the div elmWrapperBox that now contains the text area\n\n elmInputBox.attr('data-mentions-input', 'true'); //Sets the attribute data-mentions-input to true -> Defines if the text area is already configured\n elmInputBox.bind('keydown', onInputBoxKeyDown); //Bind the keydown event to the text area\n elmInputBox.bind('keypress', onInputBoxKeyPress); //Bind the keypress event to the text area\n elmInputBox.bind('click', onInputBoxClick); //Bind the click event to the text area\n elmInputBox.bind('blur', onInputBoxBlur); //Bind the blur event to the text area\n\n if (navigator.userAgent.indexOf(\"MSIE 8\") > -1) {\n elmInputBox.bind('propertychange', onInputBoxInput); //IE8 won't fire the input event, so let's bind to the propertychange\n } else {\n elmInputBox.bind('input', onInputBoxInput); //Bind the input event to the text area\n }\n }", "function initTextarea() {\n elmInputBox = $(domInput); //Get the text area target\n\n //If the text area is already configured, return\n if (elmInputBox.attr('data-mentions-input') === 'true') {\n return;\n }\n\n elmInputWrapper = elmInputBox.parent(); //Get the DOM element parent\n elmWrapperBox = $(settings.templates.wrapper());\n elmInputBox.wrapAll(elmWrapperBox); //Wrap all the text area into the div elmWrapperBox\n elmWrapperBox = elmInputWrapper.find('> div.mentions-input-box'); //Obtains the div elmWrapperBox that now contains the text area\n\n elmInputBox.attr('data-mentions-input', 'true'); //Sets the attribute data-mentions-input to true -> Defines if the text area is already configured\n elmInputBox.bind('keydown', onInputBoxKeyDown); //Bind the keydown event to the text area\n elmInputBox.bind('keypress', onInputBoxKeyPress); //Bind the keypress event to the text area\n elmInputBox.bind('click', onInputBoxClick); //Bind the click event to the text area\n elmInputBox.bind('blur', onInputBoxBlur); //Bind the blur event to the text area\n\n if (navigator.userAgent.indexOf(\"MSIE 8\") > -1) {\n elmInputBox.bind('propertychange', onInputBoxInput); //IE8 won't fire the input event, so let's bind to the propertychange\n } else {\n elmInputBox.bind('input', onInputBoxInput); //Bind the input event to the text area\n }\n\n // Elastic textareas, grow automatically\n if( settings.elastic ) {\n elmInputBox.elastic();\n }\n }", "function onInput() {\n\n /**\n * text area value\n * @type {string}\n */\n var value = this.value;\n\n // has logger instance? => log input event\n if ( self.logger ) self.logger.log( 'input', value );\n\n // has individual input callback? => perform it\n if ( self.oninput ) self.oninput( self, value );\n\n }", "function setupTextSelectionHandlers(){\n\t$(editors).each(function(){\n\t\t/**\n\t\t * TODO: \n\t\t * Look for a proper event listener to detect end of text selection\n\t\t * currently using ` mouseup` to detect end of selection. \n\t\t */\n\t\tvar editor = $(this).get(0);\n\t\t$(\".codemirror_block\").mouseup(function(){\n\n\t\t\tif(editor.somethingSelected() && editor.getSelection().trim() != \"\"){ \n\t\t\t\t// Something will be selected during a mouseup event only \n\t\t\t\t// if it is the end of a text selection\n\t\t\t\t// if a `mousedown` followed by a `mouseup` is done while a \n\t\t\t\t// range of text is selected, it will be automatically deselected\n\t\t\t\tcurrentContextMenuTargetEditor = editor;\n\t\t\t\tcontext.attach(\".CodeMirror-selectedtext\", ContextMenuObjects.translators_desk_selected_text_menu);\n\t\t\t}\n\t\t});\n\t});\n}", "function initialiseTextarea() {\n const textArea = document.getElementById(\"note-input\");\n\n textArea.addEventListener(\"keyup\", validateTextarea);\n\n textArea.addEventListener(\"keyup\", textareaCharCounter);\n\n textArea.addEventListener(\"keydown\", (event) => {\n if (event.key === \"Enter\") {\n event.preventDefault();\n addNote();\n } else if (event.key === \"Escape\") {\n closeModal();\n }\n });\n}", "initEventListners() {\n this.engine.getSession().selection.on('changeCursor', () => this.updateCursorLabels());\n\n this.engine.getSession().on('change', (e) => {\n // console.log(e);\n\n // Make sure the editor has content before allowing submissions\n this.allowCodeSubmission = this.engine.getValue() !== '';\n this.enableRunButton(this.allowCodeSubmission);\n });\n }", "constructor() {\n this.event_handlers = {}\n this.text_area = create_invisible_text_area()\n document.body.appendChild(this.text_area)\n this.text_area.focus()\n this.bind_text_area_events()\n this.bind_window_events()\n }", "function initTextareasWithLimits() {\r\n const els = element.querySelectorAll('.textareaWithLimits');\r\n els.forEach(wrapperDiv => {\r\n const textareaObj = textareaPropertyExtractor(wrapperDiv);\r\n if (textareaObj.limitType === \"hard\")\r\n textareaObj.textareaElem.setAttribute(\"maxlength\", textareaObj.charLimit);\r\n updateLimitIndicator(textareaObj);\r\n textareaObj.textareaElem.oninput = () => { updateLimitIndicator(textareaObj) };\r\n });\r\n /**\r\n * All such elements - els, must be provide text area with limits functionality\r\n * @todo Your implementation (you code which possibly makes use of helper functions written written)\r\n */\r\n }", "function onTextInput(index) {\r\n $(\"#name\" + index)\r\n .on('change', modifyData);\r\n $(\"#text\" + index)\r\n .on('change', modifyData);\r\n}", "bindTextboxListeners() {\n var fnClickTextbox = this.events.eventFunctions[\"fnClickTextbox\"];\n var mainScope = this;\n\n $( \"input.mskin-textbox-input\", this.htmlElement.container).click( function() {\n // Übergebe Prototype als Event-Funktion\n fnClickTextbox( mainScope )\n } );\n }", "triggerInputListeners(text) {\r\n var listeners = this._flattenInputListenersMap(this.inputListeners);\r\n listeners = listeners.concat(this.temporaryInputListeners);\r\n listeners.sort((a,b)=>{\r\n return a.priority < b.priority;\r\n });\r\n\r\n for(let index = 0; index < listeners.length; index++) {\r\n let listener = listeners[index];\r\n try {\r\n if (listener.matches(text, this.settings)) {\r\n if(!listener.execute(text)) {\r\n return;\r\n }\r\n }\r\n } catch(e) {\r\n if(e.name === \"HonorificNotMatching\") {\r\n this.displayText(\"I think you forgot a little something....\");\r\n return;\r\n } else throw e;\r\n }\r\n }\r\n }", "function initTextarea() {\n\n elmInputBox = jQuery(input); //Get the text area target\n\n //If the text area is already configured, return\n if (elmInputBox.attr('data-mentions-input') == 'true') {\n return;\n }\n\n elmInputWrapper = elmInputBox.parent(); //Get the DOM element parent\n elmWrapperBox = jQuery(settings.templates.wrapper());\n elmInputBox.wrapAll(elmWrapperBox); //Wrap all the text area into the div elmWrapperBox\n elmWrapperBox = elmInputWrapper.find('> div'); //Obtains the div elmWrapperBox that now contains the text area\n\n elmInputBox.attr('data-mentions-input', 'true'); //Sets the attribute data-mentions-input to true -> Defines if the text area is already configured\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Padding can either be a constant or an object containing any of the attributes (left, right, top, bottom). cleanPadding returns an object with (left, right, top, bottom) attributes.
function cleanPadding(pad) { var padding = { top: 0, left: 0, right: 0, bottom: 0 }; if (typeof pad === 'number') return { top: pad, left: pad, right: pad, bottom: pad }; ['top', 'bottm', 'right', 'left'].forEach(function (d) { if (pad[d]) padding[d] == pad[d]; }); return padding; } // Size can contain width or height attibutes. If either are unset the
[ "function cleanPadding (pad) {\n const padding = {top: 0, left: 0, right: 0, bottom: 0};\n if (typeof(pad) === 'number') return {top: pad, left: pad, right: pad, bottom: pad};\n ['top', 'bottm', 'right', 'left'].forEach( d => {\n if (pad[d]) padding[d] == pad[d];\n });\n return padding;\n }", "function getPadding(padding, xPadding, yPadding) {\n let tempPadding = padding;\n if (xPadding || yPadding) {\n tempPadding = {x: xPadding || 6, y: yPadding || 6};\n }\n return toPadding(tempPadding);\n}", "function toPadding(value) {\n const obj = toTRBL(value);\n obj.width = obj.left + obj.right;\n obj.height = obj.top + obj.bottom;\n return obj;\n}", "function toPadding(value) {\n var obj = toTRBL(value);\n obj.width = obj.left + obj.right;\n obj.height = obj.top + obj.bottom;\n return obj;\n }", "function unpackPadding(value) {\n\t\tif (typeof(value) === \"number\")\n\t\t\tvalue = [value];\n\t\tif (value.length === 1) {\n\t\t\treturn {\n\t\t\t\ttop: value[0],\n\t\t\t\tright: value[0],\n\t\t\t\tbottom: value[0],\n\t\t\t\tleft: value[0]\n\t\t\t};\n\t\t}\n\t\tif (value.length === 2) {\n\t\t\treturn {\n\t\t\t\ttop: value[0],\n\t\t\t\tright: value[1],\n\t\t\t\tbottom: value[0],\n\t\t\t\tleft: value[1]\n\t\t\t};\n\t\t}\n\t\tif (value.length === 3) {\n\t\t\treturn {\n\t\t\t\ttop: value[0],\n\t\t\t\tright: value[1],\n\t\t\t\tbottom: value[2],\n\t\t\t\tleft: value[1]\n\t\t\t};\n\t\t}\n\t\tif (value.length === 4) {\n\t\t\treturn {\n\t\t\t\ttop: value[0],\n\t\t\t\tright: value[1],\n\t\t\t\tbottom: value[2],\n\t\t\t\tleft: value[3]\n\t\t\t};\n\t\t}\n\t}", "function paddingObject(t, r, b, l) {\n return { top: t, right: r, bottom: b, left: l };\n}", "function GetObjectPadding(obj) {\n\tvar elem = GetRawObject(obj);\n\n\tvar l = 0;\n\tvar r = 0;\n\tvar t = 0;\n\tvar b = 0;\n\tif (elem.currentStyle)\n\t{\n\t\tif (elem.currentStyle.paddingLeft)\n\t\t\tl = parseInt(elem.currentStyle.paddingLeft, 10);\n\t\tif (elem.currentStyle.paddingRight)\n\t\t\tr = parseInt(elem.currentStyle.paddingRight, 10);\n\t\tif (elem.currentStyle.paddingTop)\n\t\t\tt = parseInt(elem.currentStyle.paddingTop, 10);\n\t\tif (elem.currentStyle.paddingBottom)\n\t\t\tb = parseInt(elem.currentStyle.paddingBottom, 10);\n\t}\n\telse if (window.getComputedStyle)\n\t{\n\t\tl = parseInt(window.getComputedStyle(elem,null).paddingLeft, 10);\n\t\tr = parseInt(window.getComputedStyle(elem,null).paddingRight, 10);\n\t\tt = parseInt(window.getComputedStyle(elem,null).paddingTop, 10);\n\t\tb = parseInt(window.getComputedStyle(elem,null).paddingBottom, 10);\n\t}\n\tif (isNaN(l) == true) l = 0;\n\tif (isNaN(r) == true) r = 0;\n\tif (isNaN(t) == true) t = 0;\n\tif (isNaN(b) == true) b = 0;\n\n\treturn {l:(l),r:(r),t:(t),b:(b)};\n}", "function GetObjectPadding(obj) {\n\tvar elem = GetRawObject(obj);\n\n\tvar l = 0;\n\tvar r = 0;\n\tvar t = 0;\n\tvar b = 0;\n\tif (elem.currentStyle) {\n\t\tif (elem.currentStyle.paddingLeft)\n\t\t\tl = parseInt(elem.currentStyle.paddingLeft, 10);\n\t\tif (elem.currentStyle.paddingRight)\n\t\t\tr = parseInt(elem.currentStyle.paddingRight, 10);\n\t\tif (elem.currentStyle.paddingTop)\n\t\t\tt = parseInt(elem.currentStyle.paddingTop, 10);\n\t\tif (elem.currentStyle.paddingBottom)\n\t\t\tb = parseInt(elem.currentStyle.paddingBottom, 10);\n\t}\n\telse if (window.getComputedStyle) {\n\t\tl = parseInt(window.getComputedStyle(elem, null).paddingLeft, 10);\n\t\tr = parseInt(window.getComputedStyle(elem, null).paddingRight, 10);\n\t\tt = parseInt(window.getComputedStyle(elem, null).paddingTop, 10);\n\t\tb = parseInt(window.getComputedStyle(elem, null).paddingBottom, 10);\n\t}\n\tif (isNaN(l) == true) l = 0;\n\tif (isNaN(r) == true) r = 0;\n\tif (isNaN(t) == true) t = 0;\n\tif (isNaN(b) == true) b = 0;\n\n\treturn { l: (l), r: (r), t: (t), b: (b) };\n}", "function applyPadding() {\n t.each(function(v) {\n coords[v][0] += padding;\n coords[v][1] += padding;\n });\n }", "function getPadding(props) {\n if (props.padding === 'smallEven') return '2px'\n if (props.padding === 'even') return '5px'\n if (props.padding === 'evenMedium') return '11px'\n if (props.padding === 'mediumEven') return '8px'\n if (props.padding === 'medium') return '4px 8px 5px'\n return '2px 6px 3px'\n}", "function propertyPagePadding() {\n var val = Number($valuePagePadding.val());\n if (val === NaN || val < 0) {\n return _padding; // Incoming is invalid so use current value\n }\n else {\n // REVIEW: Set the local var _padding too?\n return (propertyUnits() === UNITS.Inches) ? inches2cms(val) : val; // Need to convert to cms internally\n }\n }", "function Edit_UpdatePadding(theHTML, theObject)\n{\n\t//get padding (if we force it it will work even on JSGrabber objects)\n\tvar padding = Get_String(theObject.Properties[__NEMESIS_PROPERTY_PADDING], null);\n\t//valid?\n\tif (padding != null)\n\t{\n\t\t//split it into its components\n\t\tpadding = padding.split(\",\");\n\t\t//get it\n\t\tvar left = Get_Number(padding[0], 0);\n\t\tvar top = Get_Number(padding[1], 0);\n\t\tvar right = Get_Number(padding[2], 0);\n\t\tvar bottom = Get_Number(padding[3], 0);\n\t\t//and set it\n\t\ttheHTML.style.padding = top + \"px \" + right + \"px \" + bottom + \"px \" + left + \"px\";\n\t}\n}", "getContainerPadding() {\n let styling = {};\n styling['padding-top'] = this.props.appearance.paddingTop + 'px';\n styling['padding-bottom'] = this.props.appearance.paddingBottom + 'px';\n styling['padding-left'] = this.props.appearance.paddingSides + 'px';\n styling['padding-right'] = this.props.appearance.paddingSides + 'px';\n return styling;\n }", "pad(paddingX = 0, paddingY = paddingX) {\n return this.x -= paddingX, this.y -= paddingY, this.width += paddingX * 2, this.height += paddingY * 2, this;\n }", "function paddingToCss(paddingObj) {\r\n return paddingObj.top + \"px \" + paddingObj.right + \"px \" + paddingObj.bottom + \"px \" + paddingObj.left + \"px\";\r\n }", "function calculate_padding() {\n padLeft = Math.floor((display.getWidth() - etch.getWidth()) / 2);\n padTop = Math.floor((display.getHeight() - etch.getHeight() - 5) / 2) + 1;\n}", "function Padding() {\n\t if (this === window) {\n\t\treturn new Padding();\n\t }\n\t return this;\n\t}", "get characterPadding() {}", "function getPadding(elem) {\n paddingTop = parseInt(getCssProperty(elem, \"padding-top\").replace(\"px\", \"\"));\n paddingRight = parseInt(getCssProperty(elem, \"padding-right\").replace(\"px\", \"\"));\n paddingBottom = parseInt(getCssProperty(elem, \"padding-bottom\").replace(\"px\", \"\"));\n paddingLeft = parseInt(getCssProperty(elem, \"padding-left\").replace(\"px\", \"\"));\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Selects gList elements by ID. Stops when if finds one.
function selectById(idSel, gList, target) { target[idSel.name] = gList[idSel.name]; }
[ "function _selectItemWithId(id) {\n $log.debug(\"itAutocomplete: select with id \"+id);\n var selected = false;\n self.fields.selectedItem = {};\n if (angular.isDefined(id)) {\n angular.forEach(self.fields.items, function (item) {\n if (item.id == id) {\n select(item);\n selected = true;\n }\n });\n if (!selected) {\n init();\n }\n }\n }", "find(id) {\n this.refresh();\n if(id) {\n return this.naclList.find(element => {\n return element.id === id;\n }); \n }else {\n return this.naclList;\n }\n }", "function searchID(_id,list){\n for (let i = 0; i < list.length; i++){\n if (list[i]._id == _id){\n return list[i];\n }\n }\n return undefined;\n}", "function _selectItemWithId(id) {\n\n id = _getIdFromObject(id);\n\n\n var selected = false;\n self.fields.selectedItem = {};\n if (angular.isDefined(id)) {\n if (self.fields.debug) {\n $log.debug(self.fields.name + \" itAutocomplete: select with id \" + id);\n }\n angular.forEach(self.fields.items, function (item) {\n if (_getIdFromObject(item) == id) {\n applySelection(item);\n selected = true;\n }\n });\n if (!selected) {\n initSelect();\n }\n }\n }", "searchIds(){ \n let c=0; \n let newid; \n let origin=this.objeto.id;\n while(document.getElementById(this.objeto.id)!=null){ \n newid=origin+c;\n c++; \n this.objeto.id=newid;\n }\n }", "selectItem(id, itemIdList, noScroll) {\n if (itemIdList === undefined) {\n this._currentItemList = [ this._report.getItemById(id) ];\n }\n else {\n this._currentItemList = [];\n for (const itemId of itemIdList) {\n this._currentItemList.push(this._report.getItemById(itemId));\n }\n }\n this.switchItem(id, noScroll);\n }", "function listContains(listId, elementId) {\n var retrievedElement = $('#' + listId + ' li[id=\"' + elementId + '\"]');\n if(retrievedElement.prop(\"id\")) {\n return true;\n }\n return false;\n}", "function chooseIds( sLetter ) {\n\n Element.show( \"nlUpdateSpinner\" );\n $( \"domainSearchForm\" ).disable();\n \n new Ajax.Updater( \"idSelectionWrapper\",\n queryURI,\n {\n method: 'get',\n parameters: \"list=1&browse=\" + sLetter,\n onComplete: function () {\n Element.hide(\"nlUpdateSpinner\");\n $( \"domainSearchForm\" ).enable();\n }\n } );\n}", "function _selectid(elements) {\n\n\t\tvar id = location.search.split('id=')[1] || '';\n\n\t\tif (id) {\n\n\t\t\t$(\"#command\").val('update');\n\t\t\t$(\"#id\").val(id);\n\n\t\t\t// Set variables ==============================\n\n\t\t\t\tvar data = {\n\t\t\t\t\tcommand: 'selectid',\n\t\t\t\t\tid: id\n\t\t\t\t};\n\n\t\t\t\tvar functions =\t{\n\t\t\t\t\tsuccess: loadForm\n\t\t\t\t};\n\n\t\t\t\tif (typeof elements != 'object') {\n\n\t\t\t\telements = {\n\t\t\t\t\tloading: $('#loading'),\n\t\t\t\t\tdisable: $('#salvar')\n\t\t\t\t}\n\n\t\t\t}\n\t\t\t// Set variables ==============================\n\n\t\t\tajaxRequest(elements, data, functions);\n\n\t\t}\n\n\t}", "function selectWidgetByID(id)\n{\n\tvar dom = dw.getDocumentDOM();\n\tvar elems = dom.getElementsByAttributeName(\"id\");\n\tfor (var i=0; i<elems.length; i++)\n\t{\n\t\tif (elems[i] && elems[i].getAttribute && elems[i].getAttribute(\"id\") == id)\n\t\t{\n\t\t\tvar offsets = dom.nodeToOffsets(elems[i]);\n\t\t\tif (offsets)\n\t\t\t{\n\t\t\t\tdom.setSelection(offsets[0], offsets[1]);\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t}\n}", "function searchId(par, nameId) {\n //converting the html collection using the spread operator\n let copy = [...par].slice();\n //if copy is empty nothing will will be executed, meaning the function will pop off the call stack.\n if (copy.length != 0) {\n let item = copy.shift();\n //as soon as an id is found, the function will return the element with that id.\n if (item.id == nameId) {\n theElement = item;\n return theElement\n }\n\n if (item.children.length > 0) {\n searchId(item.children, nameId)\n }\n /* with the following code below, even if the function is rerun from the above if statement,\n the function will still excute it after reran function is poped off from the call stack.*/\n return searchId(copy,nameId);\n }\n return theElement\n }", "function searchId(par, nameId) {\n //converting the html collection using the spread operator\n let copy = [...par].slice();\n //if copy is empty nothing will will be executed, meaning the function will pop off the call stack.\n if (copy.length != 0) {\n let item = copy.shift();\n //as soon as an id is found, the function will return the element with that id.\n if (item.tagName.toLowerCase() == nameId) {\n allDivs.push(item)\n }\n\n if (item.children.length > 0) {\n searchId(item.children, nameId)\n }\n /* with the following code below, even if the function is rerun from the above if statement,\n the function will still excute it after reran function is poped off from the call stack.*/\n return searchId(copy,nameId);\n }\n return allDivs\n }", "function addId(listId) {\n if( $(\"idSelection\").hasChildNodes() ) {\n var selected = $(\"idSelection\").selectedIndex;\n if( selected >= 0 ) {\n var chosen = $(\"idSelection\").options[selected];\n $(\"idSelection\").removeChild( chosen );\n $(listId).appendChild( chosen ); \n }\n }\n}", "function getGistbyID(id) {\n for (var i = 0; i < GistList.length; i++) {\n if (GistList[i].id == id) {\n return GistList[i];\n }\n }\n}", "function byId(id, cb) {\n $r.hgetall('searches:#' + id, cb)\n}", "function listContainsId(list, id){\n return list.find(element => {\n return element._id+\"\" === id+\"\";\n });\n}", "function selectItem(event) {\n\tvar list = $(\"#library\").get(0);\n}", "function _find( items, id ) {\n\t\t\tfor ( var i=0; i < items.length; i++ ) {\n\t\t\t if ( items[i].id == id ) return i;\n\t\t\t}\n\t }", "function findListingById(id) {\n if(data.Listings){\n var result = $.grep(data.Listings, function(i){ \n return i.Id == id;\n });\n return result[0];\n }\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
enable the buttons for column visibility
function columnButtons() { new $.fn.dataTable.Buttons( table, { name: 'commands', buttons: ['colvis'] } ); table.buttons().container().appendTo($('#columnSelector', panel.content)); }
[ "function setColumnViewButtonOn()\n {\n $(\"#perc-finder-choose-view #perc-finder-choose-columnview\").addClass(\"ui-enabled\");\n $(\"#perc-finder-choose-view #perc-finder-choose-listview\").removeClass(\"ui-enabled\");\n }", "function adaptToolbarVisibility(){\n\t\t\tvar allColumnsShown = (visibleNonPersistentCount === headerCellsNoPersist.length);\n\t\t\tvar toolbarVisible = $toolbarToolCell.is(':visible')\n\n\t\t\tif(toolbarVisible && allColumnsShown) {\n\t\t\t\t$toolbarFiller.hide();\n\t\t\t\t$toolbarToolCell.hide();\n\t\t\t}\n\t\t\telse if(!toolbarVisible && !allColumnsShown){\n\t\t\t\t$toolbarFiller.show();\n\t\t\t\t$toolbarToolCell.show();\n\t\t\t}\n\t\t}", "checkColumns() {\n this.checkColumnCanChangeIsShown();\n }", "function toggleButtons() {\n if(prodModeEnabled) return;\n\n //If hidden, then show. Otherwise hide\n if($(\".button-row\").is(\":visible\")) $(\".button-row\").hide();\n else $(\".button-row\").show();\n }", "function toggleVisibility(table, columns) {\r\n\tfor(var i=0; i<columns.length; i++) {\r\n\t\tvar column = table.column(columns[i]);\r\n\t\tcolumn.visible( ! column.visible() );\r\n\t}\r\n}", "toggleColumnSelectPanel () {\n this.showColumnSelect = !this.showColumnSelect;\n }", "showOrHideColumns() {\n let cloneColumns = cloneDeep(this.columns);\n\n cloneColumns = cloneColumns.map((col) => {\n // 操作列默认左固定\n if (col.operationColumn) {\n col.fixed = COLUMN_FIXED_TYPE.LEFT;\n }\n return col;\n });\n\n const { hiddenColumns } = this;\n\n if (!isEmptyArray(hiddenColumns)) {\n // recursive remove column key\n hiddenColumns.forEach((key) => {\n cloneColumns = recursiveRemoveColumnByKey(\n cloneColumns,\n key,\n );\n });\n }\n\n this.cloneColumns = cloneColumns;\n }", "showOrHideColumns() {\n let cloneColumns = cloneDeep(this.columns);\n\n const { hiddenColumns } = this;\n\n if (!isEmptyArray(hiddenColumns)) {\n // recursive remove column key\n hiddenColumns.forEach((key) => {\n cloneColumns = recursiveRemoveColumnByKey(\n cloneColumns,\n key,\n );\n });\n }\n\n this.cloneColumns = cloneColumns;\n }", "showColumn(field) {\n field.hidden = false;\n for (let c of Array.from(this.grid.querySelectorAll(`[data-name='${field.name}']`))) {\n c.classList.remove('hidden');\n }\n this.handleColumnPresences();\n }", "function showCol($this) {\n $this.show().attr('value', 'visible');\n boxId.find('table.targetColl tr').each(function () {\n $(this).find('td').eq(indexes).show();\n });\n dialogId.find('.accessColl tr .colSpan').eq(indexes).html('hide').removeClass('hdStyle');\n }", "function showEditButtons () {\n $element.parent().find('.edit-button').css('visibility', 'visible');\n }", "function setColumnVisibility(columns,index,visible) {\n if(index<columns.length) {\n columns[index].visible = visible;\n }\n}", "onColumnVisibilityChange() {\n var columnsVisibility = this.getColumnsVisibility();\n this.table.toggleColumns(columnsVisibility);\n }", "function EnableDisableAddDelBtns()\n{\n // Check if there are any columns\n \n if (ColumnsToAdd.length == 0)\n {\n _ElemAdd.setAttribute(\"disabled\", true);\n _ElemAdd.src = \"../Shared/MM/Images/btnAdd_dis.gif\"; \n }\n else\n {\n _ElemAdd.setAttribute(\"disabled\", false);\n _ElemAdd.src = \"../Shared/MM/Images/btnAdd.gif\"; \n }\n \n if ((_ColumnNames.list.length == 0) ||\n (_ColumnNames.getRowIndex() == (-1)))\n {\n _ElemDel.setAttribute(\"disabled\", true);\n _ElemDel.src = \"../Shared/MM/Images/btnDel_dis.gif\"; \n }\n else\n {\n _ElemDel.setAttribute(\"disabled\", false);\n _ElemDel.src = \"../Shared/MM/Images/btnDel.gif\"; \n }\n}", "show () {\n if (this.hidden) {\n this.hidden = false;\n\n for (let cell of this.cells) {\n cell.show();\n }\n if (this._headerCell) {\n this._headerCell.columnStateChange();\n }\n }\n }", "[setColumns]() {\n\t\tconst self = this;\n\n\t\tself[GRID_COLUMN_BLOCK]\n\t\t\t.columns(self.columns()\n\t\t\t\t.map((column) => !column.isHidden ? column : null)\n\t\t\t\t.filter(Boolean), true)\n\t\t\t.selectableColumns(self.columns()\n\t\t\t\t.map((column) => column.canHide ? column : null)\n\t\t\t\t.filter(Boolean), true);\n\t}", "function addShorOrHideCols() {\n\t// console.log('show or hide added..');\n\t//add header names in show or hide block\n\t//this block toggels the display\n\t$('.dataTables_filter').prepend('<div id=\"showOrHideCols\" title=\"Show / Hide Columns\"></div>');\n\t$('.dataTables_filter label').append('<span id=\"filterCancel\"> X </span>');\n\t$('.dataTables_filter label input[type=text]').attr('id', 'filterDtTable');\n\tvar hdrName, cbx;\n\t$('#reportData thead tr:first-child th').each(function(i) {\n\t\tif(i != 0) {\n\t\t\tcbx = '<input type=\"checkbox\" checked=\"true\" id=\"'+i+'_cbx\" style=\"float:left;margin-right: 4px;\" />';\n\t\t\thdrName = '<span class=\"toggleColName toggleColNameActv\" id=\"'+i+'\">'+ cbx + $(this).text() + '</a>';\n\t\t\t$('#showOrHideCols').append(hdrName);\n\t }\t \n\t});\n\n\t//add listener for dt table filter\n\tdocument.getElementById('filterDtTable').addEventListener('keyup', function() {\n\t\tif($('#filterDtTable').val() != '') {\n\t\t\t$('#filterCancel').css('visibility', 'visible');\n\t\t} else {\n\t\t\t$('#filterCancel').css('visibility', 'hidden');\n\t\t}\n\t}, false); //false because id doesn't stops event bubbling\n}", "function toggleColumnsMenu() {\n if (menu.is(\":visible\")) {\n hideColumnsMenu();\n } else {\n var offset = editButton.offset()\n\n menu.css({\n left: offset.left - menu.outerWidth() + editButton.outerWidth(),\n top: offset.top + editButton.outerHeight()\n });\n menu.show();\n\n activeMenu = menu;\n }\n }", "function update_column_view_state(){\n\t\t$('ul.show-hide-column-con')\n\t\t.find('input[type=\"checkbox\"]')\n\t\t.each(function(){\n\t\t\tif(!$(this).is(':checked')){\n\t\t\t\t//get current column\n\t\t\t\tvar col = $(this).parents('li').index();\n\t\t\t\tcol += 2;\n\t\t\t\tfnHide(col);\n\t\t\t}\n\t\t});\n\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
A collection of properties for Rigid Body Modeling. ModelE2 implements IFacet required for manipulating a drawable object. Constructs a ModelE2 at the origin and with unity attitude.
function ModelE2(type) { if (type === void 0) { type = 'ModelE2'; } _super.call(this, mustBeString('type', type)); this._position = new G2().zero(); this._attitude = new G2().zero().addScalar(1); /** * Used for exchanging number[] data to achieve integrity and avoid lots of temporaries. * @property _posCache * @type {R2} * @private */ this._posCache = new R2(); /** * Used for exchanging number[] data to achieve integrity and avoid lots of temporaries. * @property _attCache * @type {SpinG2} * @private */ this._attCache = new SpinG2(); this._position.modified = true; this._attitude.modified = true; }
[ "function ModelE2() {\n this._position = new Geometric2().zero();\n this._attitude = new Geometric2().zero().addScalar(1);\n this._position.modified = true;\n this._attitude.modified = true;\n }", "function L2DBaseModel() {\n\t this.live2DModel = null; // ALive2DModel\n\t this.modelMatrix = null; // L2DModelMatrix\n\t this.eyeBlink = null; // L2DEyeBlink\n\t this.physics = null; // L2DPhysics\n\t this.pose = null; // L2DPose\n\t this.debugMode = false;\n\t this.initialized = false;\n\t this.updating = false;\n\t this.alpha = 1;\n\t this.accAlpha = 0;\n\t this.lipSync = false;\n\t this.lipSyncValue = 0;\n\t this.accelX = 0;\n\t this.accelY = 0;\n\t this.accelZ = 0;\n\t this.dragX = 0;\n\t this.dragY = 0;\n\t this.startTimeMSec = null;\n\t this.mainMotionManager = new L2DMotionManager(); //L2DMotionManager\n\t this.expressionManager = new L2DMotionManager(); //L2DMotionManager\n\t this.motions = {};\n\t this.expressions = {};\n\n\t this.isTexLoaded = false;\n\t}", "createModel () {\n var model = new THREE.Object3D();\n\n var loader1 = new THREE.TextureLoader();\n var texturaGrua = loader1.load (\"imgs/images.jpg\");\n var mat = new THREE.MeshPhongMaterial({map: texturaGrua});\n this.r2d2 = new r2d2({r2d2Height: 30, r2d2Width: 45, material: mat});\n model.add (this.r2d2);\n //this.r2d2.position.set(0, 0, -140);\n this.r2d2.position.set(0,0,-140);\n\n var loader = new THREE.TextureLoader();\n var textura = loader.load (\"imgs/wood.jpg\");\n this.ground = new Ground (300, 300, new THREE.MeshPhongMaterial ({map: textura}), 4);\n model.add (this.ground);\n\n model.add(this.createHealthBar());\n model.add(this.createHealthText());\n\n return model;\n }", "function b2GearJoint(def)\n{\n\tthis.parent.call(this, def);\n\n\tthis.m_joint1 = def.joint1;\n\tthis.m_joint2 = def.joint2;\n\n\tthis.m_typeA = this.m_joint1.GetType();\n\tthis.m_typeB = this.m_joint2.GetType();\n\n'#if @DEBUG';\n\tb2Assert(this.m_typeA == b2Joint.e_revoluteJoint || this.m_typeA == b2Joint.e_prismaticJoint);\n\tb2Assert(this.m_typeB == b2Joint.e_revoluteJoint || this.m_typeB == b2Joint.e_prismaticJoint);\n'#endif';\n\n\tvar coordinateA, coordinateB;\n\n\t// TODO_ERIN there might be some problem with the joint edges in b2Joint.\n\n\tthis.m_bodyC = this.m_joint1.GetBodyA();\n\tthis.m_bodyA = this.m_joint1.GetBodyB();\n\n\t// Get geometry of joint1\n\tvar xfA = this.m_bodyA.m_xf;\n\tvar aA = this.m_bodyA.m_sweep.a;\n\tvar xfC = this.m_bodyC.m_xf;\n\tvar aC = this.m_bodyC.m_sweep.a;\n\n\tthis.m_localAnchorA = new b2Vec2();\n\tthis.m_localAnchorB = new b2Vec2();\n\tthis.m_localAnchorC = new b2Vec2();\n\tthis.m_localAnchorD = new b2Vec2();\n\n\tthis.m_localAxisC = new b2Vec2();\n\tthis.m_localAxisD = new b2Vec2();\n\n\tif (this.m_typeA == b2Joint.e_revoluteJoint)\n\t{\n\t\tvar revolute = def.joint1;\n\t\tthis.m_localAnchorC.Assign(revolute.m_localAnchorA);\n\t\tthis.m_localAnchorA.Assign(revolute.m_localAnchorB);\n\t\tthis.m_referenceAngleA = revolute.m_referenceAngle;\n\t\tthis.m_localAxisC.SetZero();\n\n\t\tcoordinateA = aA - aC - this.m_referenceAngleA;\n\t}\n\telse\n\t{\n\t\tvar prismatic = def.joint1;\n\t\tthis.m_localAnchorC.Assign(prismatic.m_localAnchorA);\n\t\tthis.m_localAnchorA.Assign(prismatic.m_localAnchorB);\n\t\tthis.m_referenceAngleA = prismatic.m_referenceAngle;\n\t\tthis.m_localAxisC.Assign(prismatic.m_localXAxisA);\n\n\t\tvar pC = this.m_localAnchorC;\n\t\tvar pA = b2MulT_r_v2(xfC.q, b2Vec2.Add(b2Mul_r_v2(xfA.q, this.m_localAnchorA), b2Vec2.Subtract(xfA.p, xfC.p)));\n\t\tcoordinateA = b2Dot_v2_v2(b2Vec2.Subtract(pA, pC), this.m_localAxisC);\n\t}\n\n\tthis.m_bodyD = this.m_joint2.GetBodyA();\n\tthis.m_bodyB = this.m_joint2.GetBodyB();\n\n\t// Get geometry of joint2\n\tvar xfB = this.m_bodyB.m_xf;\n\tvar aB = this.m_bodyB.m_sweep.a;\n\tvar xfD = this.m_bodyD.m_xf;\n\tvar aD = this.m_bodyD.m_sweep.a;\n\n\tif (this.m_typeB == b2Joint.e_revoluteJoint)\n\t{\n\t\tvar revolute = def.joint2;\n\t\tthis.m_localAnchorD.Assign(revolute.m_localAnchorA);\n\t\tthis.m_localAnchorB.Assign(revolute.m_localAnchorB);\n\t\tthis.m_referenceAngleB = revolute.m_referenceAngle;\n\t\tthis.m_localAxisD.SetZero();\n\n\t\tcoordinateB = aB - aD - this.m_referenceAngleB;\n\t}\n\telse\n\t{\n\t\tvar prismatic = def.joint2;\n\t\tthis.m_localAnchorD.Assign(prismatic.m_localAnchorA);\n\t\tthis.m_localAnchorB.Assign(prismatic.m_localAnchorB);\n\t\tthis.m_referenceAngleB = prismatic.m_referenceAngle;\n\t\tthis.m_localAxisD.Assign(prismatic.m_localXAxisA);\n\n\t\tvar pD = this.m_localAnchorD;\n\t\tvar pB = b2MulT_r_v2(xfD.q, b2Vec2.Add(b2Mul_r_v2(xfB.q, this.m_localAnchorB), b2Vec2.Subtract(xfB.p, xfD.p)));\n\t\tcoordinateB = b2Dot_v2_v2(b2Vec2.Subtract(pB, pD), this.m_localAxisD);\n\t}\n\n\tthis.m_ratio = def.ratio;\n\n\tthis.m_constant = coordinateA + this.m_ratio * coordinateB;\n\n\tthis.m_impulse = 0.0;\n\n\t// Solver temp\n\tthis.m_indexA = this.m_indexB = this.m_indexC = this.m_indexD = 0;\n\tthis.m_lcA = new b2Vec2(); this.m_lcB = new b2Vec2(); this.m_lcC = new b2Vec2(); this.m_lcD = new b2Vec2();\n\tthis.m_mA = this.m_mB = this.m_mC = this.m_mD = 0;\n\tthis.m_iA = this.m_iB = this.m_iC = this.m_iD = 0;\n\tthis.m_JvAC = new b2Vec2(), this.m_JvBD = new b2Vec2();\n\tthis.m_JwA = this.m_JwB = this.m_JwC = this.m_JwD = 0;\n\tthis.m_mass = 0;\n}", "function ModelE3() {\n this._position = Geometric3.zero(false);\n this._attitude = Geometric3.one(false);\n this._position.modified = true;\n this._attitude.modified = true;\n }", "createModel() {\n var model = new THREE.Object3D();\n var loader = new THREE.TextureLoader();\n\n // Robot model\n var robotTexture = loader.load('imgs/body.jpg');\n robotTexture.offset = new THREE.Vector2(0.265,0);\n var headTexture = loader.load('imgs/head.jpg');\n var legTexture = loader.load('imgs/leg.jpg');\n var rustyMetalTex = loader.load('imgs/rustymetal.jpg');\n this.robot = new Robot({\n eyeMaterial: new THREE.MeshPhongMaterial({ color: '#000000',\n shininess: 70 }),\n headMaterial: new THREE.MeshPhongMaterial({ color: '#888888',\n shininess: 70,\n map: headTexture}),\n bodyMaterial: new THREE.MeshPhongMaterial({ color: '#e8e8e8',\n shininess: 70,\n map: robotTexture}),\n footMaterial: new THREE.MeshPhongMaterial({ color: '#001284',\n shininess: 70,\n map:\n rustyMetalTex}),\n legMaterial: new THREE.MeshPhongMaterial({ color: '#e8e8e8',\n shininess: 70 ,\n map: legTexture}),\n shoulderMaterial: new THREE.MeshPhongMaterial({ color:\n '#001284',\n shininess:\n 70,\n map:\n rustyMetalTex})\n });\n // model.add (this.crane);\n model.add(this.robot);\n\n // Ground model\n var groundTexture = loader.load('imgs/rock.jpg');\n groundTexture.wrapS = THREE.RepeatWrapping;\n groundTexture.wrapT = THREE.RepeatWrapping;\n groundTexture.repeat = new THREE.Vector2(4,4);\n this.ground = new Ground(\n 500, 500, new THREE.MeshPhongMaterial({\n map: groundTexture\n }), 4\n );\n model.add(this.ground);\n\n // Flying objects\n this.spawnedFOArray = new Array(\n -1,\n -1,\n -1\n );\n \n var ovoMaTexture = loader.load('imgs/ovoma.jpg');\n this.flyingObjects = new Array(10);\n for (var i = 0; i < 8; i++)\n this.flyingObjects[i] = new OvoMa({\n ovoMaMaterial: new\n THREE.MeshPhongMaterial({\n color: '#ff0000',\n shininess: 70,\n map: ovoMaTexture})});\n\n\n var ovoBuTexture = loader.load('imgs/ovobu.jpg');\n for (i = 8; i < 10; i++)\n this.flyingObjects[i] = new OvoBu({\n ovoBuMaterial: new THREE.MeshPhongMaterial({\n color: '#00ff00',\n shininess: 70,\n map: ovoBuTexture})});\n return model;\n }", "function b2GearJointDef()\n{\n\tthis.parent.call(this);\n\n\tthis.type = b2Joint.e_gearJoint;\n\tthis.joint1 = null;\n\tthis.joint2 = null;\n\tthis.ratio = 1.0;\n\n\tObject.seal(this);\n}", "function createBox2DBody() {\n // Box2D physics body\n var bodyDef = new box2d.b2BodyDef();\n bodyDef.type = box2d.b2Body.b2_dynamicBody;\n bodyDef.angle = 0;\n bodyDef.angularDamping = 99;\n bodyDef.position.Set(3282/SCALE, 2288/SCALE); // World coordinates\n bodyDef.userData = \"Rover\";\n var body = world.CreateBody(bodyDef);\n \n //Main ship body\n var Vec2 = box2d.b2Vec2;\n var fixDef = new box2d.b2FixtureDef();\n fixDef.density = 10.;\n fixDef.friction = 0.4;\n fixDef.restitution = 0.4;\n fixDef.shape = new box2d.b2PolygonShape;\n var vertices = [\n new Vec2(6/SCALE,-16/SCALE),\n new Vec2(31/SCALE, -2/SCALE),\n new Vec2(31/SCALE, 5/SCALE),\n new Vec2(-31/SCALE,5/SCALE),\n new Vec2(-31/SCALE, -7/SCALE),\n new Vec2(-15/SCALE,-16/SCALE)\n ];\n fixDef.shape.SetAsArray(vertices, 6);\n fixDef.filter.categoryBits = CAT.SHIP;\n fixDef.filter.maskBits = CAT.GROUND | CAT.SOLDIER_FOOT_SENSOR;\n fixDef.userData = \"Rover\";\n body.CreateFixture(fixDef);\n \n //Right tire\n fixDef.shape = new box2d.b2CircleShape(7/SCALE);\n fixDef.shape.SetLocalPosition(new box2d.b2Vec2(12/SCALE, 8/SCALE));\n body.CreateFixture(fixDef);\n \n //Left tire\n fixDef.shape = new box2d.b2CircleShape(7/SCALE);\n fixDef.shape.SetLocalPosition(new box2d.b2Vec2(-15/SCALE, 8/SCALE));\n body.CreateFixture(fixDef);\n \n return body;\n }", "function createBox2DBody() {\n // BODY\n var bodyDef = new box2d.b2BodyDef();\n bodyDef.type = box2d.b2Body.b2_dynamicBody;\n bodyDef.angle = 0;\n bodyDef.angularDamping = 0.2;\n bodyDef.position.Set( 1000/SCALE, 1470/SCALE); //canvas.height / 2 / SCALE;\n bodyDef.userData = \"body name\";\n var body = world.CreateBody(bodyDef);\n \n // FIXTURES\n var fixDef = new box2d.b2FixtureDef();\n fixDef.density = 100.;\n fixDef.friction = 0.6;\n fixDef.restitution = 0.0;\n fixDef.shape = new box2d.b2PolygonShape;\n fixDef.shape.SetAsBox((70 / 2 / SCALE), (136 / 2 / SCALE));\n fixDef.filter.categoryBits = CAT.SHIP;\n fixDef.filter.maskBits = CAT.GROUND | CAT.SOLDIER_FOOT_SENSOR;\n fixDef.userData = \"fixture name\";\n body.CreateFixture(fixDef);\n \n return body;\n }", "function b2RevoluteJointDef()\r\n{\r\n\tthis.parent.call(this);\r\n\r\n\tthis.type = b2Joint.e_revoluteJoint;\r\n\tthis.localAnchorA = new b2Vec2();\r\n\tthis.localAnchorB = new b2Vec2();\r\n\tthis.referenceAngle = 0.0;\r\n\tthis.lowerAngle = 0.0;\r\n\tthis.upperAngle = 0.0;\r\n\tthis.maxMotorTorque = 0.0;\r\n\tthis.motorSpeed = 0.0;\r\n\tthis.enableLimit = false;\r\n\tthis.enableMotor = false;\r\n\r\n\tObject.seal(this);\r\n}", "function Physics()\n{\n var self = this;\n var _b2Vec2=null, _world=null; _enabled=true;\n\tvar _scale = 10; //units per meter\n\tvar _velScale = 0.8; //velocity scale\n\tvar _gravScale = 5;\n var _gravity = _gravScale*10/_scale, _accuracy=3, _fps=60, _sleep=false;\n this.obs = [];\n \n this.Init = function( gravity, accuracy, sleep )\n {\n if( _isGles ) _script( \"/Sys/Libs/Box2d.js\" );\n\t \n _b2Vec2 = Box2D.Common.Math.b2Vec2\n \t,\t_b2BodyDef = Box2D.Dynamics.b2BodyDef\n \t,\t_b2Body = Box2D.Dynamics.b2Body\n \t,\t_b2FixtureDef = Box2D.Dynamics.b2FixtureDef\n \t,\t_b2Fixture = Box2D.Dynamics.b2Fixture\n \t,\t_b2World = Box2D.Dynamics.b2World\n \t,\t_b2MassData = Box2D.Collision.Shapes.b2MassData\n \t,\t_b2PolygonShape = Box2D.Collision.Shapes.b2PolygonShape\n \t,\t_b2CircleShape = Box2D.Collision.Shapes.b2CircleShape\n \t,\t_b2DebugDraw = Box2D.Dynamics.b2DebugDraw;\n \t\n if( gravity!=null ) _gravity = _gravScale*gravity/_scale;\n if( accuracy!=null ) _accuracy = accuracy;\n\t\tif( sleep!=null ) _sleep = sleep;\n \n\t\t//Note: we set sleep to false or objects won't slide off tipping platforms.\n _world = new _b2World( new _b2Vec2(0,_gravity), _sleep );\n }\n \n this.SetEnabled = function( enabled ) { \n\t _enabled = enabled;\n\t}\n\t\n this.Step = function()\n {\n if( !_enabled ) return;\n \n\t\t//Step the physics world.\n _world.Step( 1/_fps, _accuracy*3,_accuracy );\n _world.ClearForces();\n \n\t\t//Move the graphics world objects according to physics world.\n for( var o in self.obs )\n {\n var obj = self.obs[o];\n var body = obj.body;\n if( !body ) continue;\n \n\t\t\t//Set graphics object position and angle.\n var p = body.GetPosition();\n //obj.x = p.x / _scale - obj.width/2;\n //obj.y = p.y / _scale - obj.height/2;\n\t\t\t//obj.x = (p.x - obj.width/2) / _scale;\n //obj.y = (p.y - obj.height/2) / _scale * _asp;\n\t\t\tobj.x = p.x/_scale - obj.width/2;\n obj.y = p.y/_scale*_asp - obj.height/2;\n\t\t\t\n obj.angle = body.GetAngle()/(Math.PI*2)// /_asp; //<-- why need /_asp ?????\n\t\t\t\n //not needed cos of loop in render func: if( obj.Update ) obj.Update();\n }\n }\n\t\n //Add object to world and give it physics methods.\n this.Add = function( obj )\n {\n //Add object to list.\n self.obs.push( obj );\n \n //Add 'SetPhysics' property to source object.\n\t\t//type: fixed, moveable, dynamic\n\t\t//groups with negative nums don't interact\n \tobj.SetPhysics = function( groupId, type, density, bounce, friction, linearDamp, angularDamp )\n \t{\n var fixDef = new _b2FixtureDef;\n fixDef.density = density;\n fixDef.friction = friction;\n fixDef.restitution = bounce;\n fixDef.filter.groupIndex = groupId;\n \n //Scale up values to prevent rounding errors.\n\t\t\tif( obj.width==0 ) console.log( \"WARNING: physics cannot be set for object with zero width\" )\n var w = obj.width*_scale;\n var h = obj.height*_scale/_asp;\n\t\t\tvar x = obj.x*_scale + w/2;\n var y = obj.y*_scale/_asp + h/2;\n \n var bodyDef = new _b2BodyDef;\n\t\t\ttype = type.toLowerCase();\n bodyDef.type = (type==\"fixed\" ? _b2Body.b2_staticBody : ( type==\"moveable\" ? _b2Body.b2_kinematicBody : _b2Body.b2_dynamicBody )); \n if( linearDamp ) bodyDef.linearDamping = linearDamp;\n if( angularDamp ) bodyDef.angularDamping = angularDamp;\n\t\t\tbodyDef.position.Set( x, y );\n\t\t\tbodyDef.angle = obj.angle * Math.PI * 2\n \n\t\t\tvar shape = \"box\"\n\t\t\tif( shape!=null ) shape = shape.toLowerCase();\n if( shape!=null && shape.indexOf(\"round\")>-1 ) {\n\t\t\t\tfixDef.shape = new _b2CircleShape;\n\t\t\t\tfixDef.shape.m_radius = h/2;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tfixDef.shape = new _b2PolygonShape;\n\t\t\t\t//console.log( \"setbox:\" + w/2 + \",\" + h/2 )\n\t\t\t\tfixDef.shape.SetAsBox( w/2, h/2 );\n\t\t\t} \n /*\n else fixDef.shape.SetAsArray([\n new b2Vec2( x, y ),\n new b2Vec2( x+w, y ),\n new b2Vec2( x+w, y+h ),\n new b2Vec2( x, y+h )\n ], 4 );\n */\n \n var body = _world.CreateBody(bodyDef);\n obj.fixture = body.CreateFixture(fixDef);\n //body.SetPosition( new _b2Vec2( 0, 0 ) );\n body._parent = obj;\n obj.body = body;\n\t\t\tobj.fixDef = fixDef;\n\t\t\t\n\t\t\t//Update the position.\n\t\t\t//obj.UpdatePhysics();\n \t}\n \t\n\t\t//Set fixture shape (currently only a single fixture supported)\n\t\tobj.SetShape = function( shape, width, height )\n\t\t{\n\t\t\tif( width==null ) width = 1\n\t\t\tif( height==null ) height = 1\n\t\t\t\n\t\t\tvar shape = shape.toLowerCase();\n\t\t\tvar w = obj.width * _scale;\n var h = obj.height * _scale/_asp;\n\t\t\t\n\t\t\tif( obj.fixture ) obj.body.DestroyFixture( obj.fixture );\n\t\t\t\n if( shape.indexOf(\"round\")>-1 ) {\n\t\t\t\tobj.fixDef.shape = new _b2CircleShape;\n\t\t\t\tobj.fixDef.shape.m_radius = h*width/2;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tobj.fixDef.shape = new _b2PolygonShape;\n\t\t\t\tobj.fixDef.shape.SetAsBox( w*width/2, h*height/2 );\n\t\t\t} \n\t\t\tobj.fixture = obj.body.CreateFixture( obj.fixDef );\n\t\t}\n\t\t\n \t//Add 'SetVelocity' property to source object.\n \tobj.SetVelocity = function( x, y, angular, bodyRelative )\n \t{\n \t if( obj.body ) \n \t {\n\t\t\t\tif( bodyRelative ) {\n\t\t\t\t\tvar a = obj.body.GetAngle()// /_asp\n\t\t\t\t\tvar xr = Math.cos(a)*x - Math.sin(a)*y\n\t\t\t\t\tvar yr = Math.sin(a)*x + Math.cos(a)*y\n\t\t\t\t\tx = xr; y = yr \n\t\t\t\t}\n \t\t//if( x!=null && y!=null) \n \t\t//\tobj.body.SetLinearVelocity( new _b2Vec2(x,y*_asp) );\n\t\t\t\tif( x!=null ) obj.body.m_linearVelocity.x = x * _scale * _velScale\n\t\t\t\tif( y!=null ) obj.body.m_linearVelocity.y = y * _scale * _velScale\n \t\tif( angular!=null ) obj.body.SetAngularVelocity( angular * Math.PI * 2 );\n \t }\n \t obj.Update();\n \t}\n\t\t\n\t\t//Add 'AddVelocity' property to source object.\n \tobj.AddVelocity = function( x, y, angular, bodyRelative )\n \t{\n \t if( obj.body && obj.body.m_type != _b2Body.b2_staticBody ) \n \t {\n\t\t\t\tobj.body.IsAwake() == false && obj.body.SetAwake(true);\n\t\t\t\t\n\t\t\t\tif( bodyRelative ) {\n\t\t\t\t\tvar a = obj.body.GetAngle() // /_asp\n\t\t\t\t\tvar xr = Math.cos(a)*x - Math.sin(a)*y\n\t\t\t\t\tvar yr = Math.sin(a)*x + Math.cos(a)*y\n\t\t\t\t\tx = xr; y = yr\n\t\t\t\t}\n \t\tif( x!=null ) obj.body.m_linearVelocity.x += x * _scale * _velScale\n\t\t\t\tif( y!=null ) obj.body.m_linearVelocity.y += y * _scale * _velScale\n \t\tif( angular!=null ) obj.body.m_angularVelocity += angular * Math.PI * 2\n \t }\n \t obj.Update();\n \t}\n \t\n\t\t//Get the velocity of the object ( \"x\", \"y\", \"angular\", null)\n\t\tobj.GetVelocity = function( component )\n\t\t{\n\t\t\tif( obj.body )\n\t\t\t{\n\t\t\t\tif( component==\"x\" ) return obj.body.m_linearVelocity.x\n\t\t\t\telse if( component==\"y\" ) return obj.body.m_linearVelocity.y\n\t\t\t\telse if( component==\"angular\" ) return obj.body.m_angularVelocity\n\t\t\t\telse { \n\t\t\t\t\tvar vx = obj.body.m_linearVelocity.x; var vy = obj.body.m_linearVelocity.y\n\t\t\t\t\treturn Math.sqrt( vx*vx + vy*vy )\n\t\t\t\t}\n\t\t\t}\n\t\t\telse return 0\n\t\t}\n\t\t\n\t\t//Add 'ApplyImpulse' property to source object.\n\t\t// dx, dy are offsets from object center (range -1 to +1)\n\t\tobj.ApplyImpulse = function( x, y, offsetX, offsetY )\n\t\t{\n \t if( obj.body ) \n \t {\n \t\tif( x!=null && y!=null) \n\t\t\t\t{\n\t\t\t\t\tvar w = obj.width*_scale;\n\t\t\t\t\tvar h = obj.height*_scale/_asp;\n\t\t\t\t\tvar fx = obj.x*_scale + w/2 + w * (offsetX ? offsetX : 0)/2;\n\t\t\t\t\tvar fy = obj.y*_scale/_asp + h/2 + h * (offsetY ? offsetY : 0)/2;\n \t\t\tobj.body.ApplyImpulse( new _b2Vec2(x/_fps,y/_fps), new _b2Vec2(fx,fy) );\n\t\t\t\t}\n \t }\n \t obj.Update();\n \t}\n\t\t\n \t//Add 'Update' property to source object.\n \tobj.UpdatePhysics = function()\n \t{\n \t if( obj.body ) \n \t {\n \t var w = obj.width*_scale;\n var h = obj.height*_scale/_asp;\n var x = obj.x*_scale + w/2;\n var y = obj.y*_scale/_asp + h/2;\n \n \t\t obj.body.SetPosition( new _b2Vec2( x, y ) );\n\t\t\t\tobj.body.SetAngle( obj.angle * Math.PI * 2 ) //* _asp ); //<-- why need _asp ?????\n \t }\n \t}\n\t\t\n\t\t//Disable or enable physics for this object.\n\t\tobj.EnablePhysics = function( enable ) \n\t\t{\n\t\t\tif( obj.body ) obj.body.SetActive( enable )\n\t\t}\n\t\t\n\t\tobj.RemovePhysics = function()\n\t\t{\n\t\t\tif( obj.body ) {\n\t\t\t\t_world.DestroyBody( obj.body )\n\t\t\t\tobj.body = null\n\t\t\t}\n\t\t}\n }\n \n //Detect collisions.\n this.SetOnCollide = function( callback )\n {\n var listener = new Box2D.Dynamics.b2ContactListener;\n _world.SetContactListener( listener );\n \n listener.BeginContact = function(contact) \n\t\t{\n //console.log( contact.GetFixtureA().GetBody() );\n\t\t\tvar a = contact.GetFixtureA().GetBody()\n\t\t\tvar b = contact.GetFixtureB().GetBody()\n\t\t\tif( a.IsActive() && b.IsActive() ) \n\t\t\t{\n\t\t\t\t//Sort objects alphabetically by group name\n\t\t\t\tvar aa=a, bb=b;\n\t\t\t\tif( a._parent.group > b._parent.group ) { aa=b; bb=a }\n\t\t\t\t\n\t\t\t\t//setTimeout or we cant destroy body cos it's locked\n\t\t\t\tsetTimeout( function(){ callback( aa._parent, bb._parent ) }, 0 )\n\t\t\t}\n }\n \n listener.EndContact = function(contact) \n\t\t{\n //console.log( contact.GetFixtureA().GetBody() );\n var a = contact.GetFixtureA().GetBody()\n\t\t\tvar b = contact.GetFixtureB().GetBody()\n\t\t\t//if( a.IsActive() && b.IsActive() ) callback( a._parent, b._parent );\n }\n }\n \n \n}", "function mxShapeElectricalTwoWayContact2(bounds, fill, stroke, strokewidth)\n{\n\tmxShape.call(this);\n\tthis.bounds = bounds;\n\tthis.fill = fill;\n\tthis.stroke = stroke;\n\tthis.strokewidth = (strokewidth != null) ? strokewidth : 1;\n}", "constructor(body1,body2,offset1,offset2){\n this.offset1 = offset1;\n this.offset2 = offset2;\n //creating a constraint with the two bodies and the offset\n this.constraint = Matter.Constraint.create({\n bodyA: body1,\n bodyB: body2,\n stiffness: 1,\n length: 225,\n pointB: this.offset2,\n pointA: this.offset1\n });\n World.add(world,this.constraint);\n }", "createBody() {\n const entity = this.entity;\n let shape;\n\n if (entity.collision) {\n shape = entity.collision.shape;\n\n // if a trigger was already created from the collision system\n // destroy it\n if (entity.trigger) {\n entity.trigger.destroy();\n delete entity.trigger;\n }\n }\n\n if (shape) {\n if (this._body)\n this.system.onRemove(entity, this);\n\n const mass = this._type === BODYTYPE_DYNAMIC ? this._mass : 0;\n\n this._getEntityTransform(_ammoTransform);\n\n const body = this.system.createBody(mass, shape, _ammoTransform);\n\n body.setRestitution(this._restitution);\n body.setFriction(this._friction);\n body.setRollingFriction(this._rollingFriction);\n body.setDamping(this._linearDamping, this._angularDamping);\n\n if (this._type === BODYTYPE_DYNAMIC) {\n const linearFactor = this._linearFactor;\n _ammoVec1.setValue(linearFactor.x, linearFactor.y, linearFactor.z);\n body.setLinearFactor(_ammoVec1);\n\n const angularFactor = this._angularFactor;\n _ammoVec1.setValue(angularFactor.x, angularFactor.y, angularFactor.z);\n body.setAngularFactor(_ammoVec1);\n } else if (this._type === BODYTYPE_KINEMATIC) {\n body.setCollisionFlags(body.getCollisionFlags() | BODYFLAG_KINEMATIC_OBJECT);\n body.setActivationState(BODYSTATE_DISABLE_DEACTIVATION);\n }\n\n body.entity = entity;\n\n this.body = body;\n\n if (this.enabled && entity.enabled) {\n this.enableSimulation();\n }\n }\n }", "function createBox2DBody() {\n // Box2D physics body\n var bodyDef = new box2d.b2BodyDef();\n bodyDef.type = box2d.b2Body.b2_dynamicBody;\n bodyDef.angle = 0;\n bodyDef.angularDamping = 0.2;\n bodyDef.position.Set( 3182/SCALE, 2236/SCALE); // World coordinates\n bodyDef.userData = \"Ship\";\n var body = world.CreateBody(bodyDef);\n /*\n var fixDef = new box2d.b2FixtureDef();\n fixDef.density = 100.;\n fixDef.friction = 0.6;\n fixDef.restitution = 0.0;\n fixDef.shape = new box2d.b2PolygonShape;\n fixDef.shape.SetAsBox((70 / 2 / SCALE), (54 / 2 / SCALE));\n fixDef.filter.categoryBits = CAT.SHIP;\n fixDef.filter.maskBits = CAT.GROUND | CAT.SOLDIER_FOOT_SENSOR;\n fixDef.userData = \"Ship\";\n body.CreateFixture(fixDef);\n */\n //Main ship body\n var Vec2 = box2d.b2Vec2;\n var fixDef = new box2d.b2FixtureDef();\n fixDef.density = 100.;\n fixDef.friction = 0.6;\n fixDef.restitution = 0.0;\n fixDef.shape = new box2d.b2PolygonShape;\n var vertices = [\n new Vec2(0,-68/ SCALE),\n new Vec2(30/SCALE,-27/SCALE),\n new Vec2(18/SCALE, 37/SCALE),\n new Vec2(-18/SCALE, 37/SCALE),\n new Vec2(-30/SCALE,-27/SCALE)\n ];\n fixDef.shape.SetAsArray(vertices, 5);\n fixDef.filter.categoryBits = CAT.SHIP;\n fixDef.filter.maskBits = CAT.GROUND | CAT.SOLDIER_FOOT_SENSOR | CAT.STATION;\n fixDef.userData = \"Ship\";\n body.CreateFixture(fixDef);\n \n //Right engine\n fixDef.shape = new box2d.b2PolygonShape;\n var vertices = [\n new Vec2(22/SCALE, 18/SCALE),\n new Vec2(30/SCALE, 10/SCALE),\n new Vec2(33/SCALE, 67/SCALE),\n new Vec2(12/SCALE, 67/SCALE)\n ];\n fixDef.shape.SetAsArray(vertices, 4);\n body.CreateFixture(fixDef);\n \n //Left engine\n fixDef.shape = new box2d.b2PolygonShape;\n var vertices = [\n new Vec2(-12/SCALE, 67/SCALE),\n new Vec2(-33/SCALE, 67/SCALE),\n new Vec2(-30/SCALE, 10/SCALE),\n new Vec2(-22/SCALE, 18/SCALE)\n ];\n fixDef.shape.SetAsArray(vertices, 4);\n body.CreateFixture(fixDef);\n \n return body;\n }", "function createBody() {\n var bodyObj = new THREE.Object3D();\n\n var bodyDimen = [ [0, 0],\n [paramsMikey.bodyWidth*1.5/5, 1],\n [paramsMikey.bodyWidth*4/5, paramsMikey.bodyHeight/5],\n [paramsMikey.bodyWidth, paramsMikey.bodyHeight/2],\n [paramsMikey.bodyWidth*3/5, paramsMikey.bodyHeight*9/10],\n [paramsMikey.bodyWidth*1/5, paramsMikey.bodyHeight-1],\n [0, paramsMikey.bodyHeight]]; //body dimension\n\n var bodyCurve = new THREE.CatmullRomCurve3( makeVertices(bodyDimen) );\n var bodyGeom = new THREE.LatheGeometry( bodyCurve.getPoints(20) );\n\n bodyMesh = new THREE.Mesh (bodyGeom, bodyMaterials.bodyMat);\n\n bodyMesh.add(createHorn(1));\n bodyMesh.add(createHorn(-1));\n bodyMesh.add(createEye());\n bodyMesh.add(createLimb(1, \"leg\"));\n bodyMesh.add(createLimb(-1, \"leg\"));\n bodyMesh.add(createLimb(1, \"arm\"));\n bodyMesh.add(createLimb(-1, \"arm\"));\n bodyMesh.add(createSmile());\n\n bodyObj.add(bodyMesh);\n return bodyObj;\n }", "function L2DPhysics() {\n\t this.physicsList = new Array(); //ArrayList<PhysicsHair>\n\t this.startTimeMSec = _live2d.UtSystem.getUserTimeMSec();\n\t}", "function ModelE3(type) {\n if (type === void 0) { type = 'ModelE3'; }\n _super.call(this, mustBeString('type', type));\n /**\n * @property _position\n * @type {G3}\n * @private\n */\n this._position = new G3().zero();\n /**\n * @property _attitude\n * @type {G3}\n * @private\n */\n this._attitude = new G3().zero().addScalar(1);\n /**\n * Used for exchanging number[] data to achieve integrity and avoid lots of temporaries.\n * @property _posCache\n * @type {R3}\n * @private\n */\n this._posCache = new R3();\n /**\n * Used for exchanging number[] data to achieve integrity and avoid lots of temporaries.\n * @property _attCache\n * @type {SpinG3}\n * @private\n */\n this._attCache = new SpinG3();\n this._position.modified = true;\n this._attitude.modified = true;\n }", "function Body(_a) {\n var actor = _a.actor, collider = _a.collider;\n /**\n * The (x, y) position of the actor this will be in the middle of the actor if the\n * [[Actor.anchor]] is set to (0.5, 0.5) which is default.\n * If you want the (x, y) position to be the top left of the actor specify an anchor of (0, 0).\n */\n this.pos = new _Algebra__WEBPACK_IMPORTED_MODULE_0__[\"Vector\"](0, 0);\n /**\n * The position of the actor last frame (x, y) in pixels\n */\n this.oldPos = new _Algebra__WEBPACK_IMPORTED_MODULE_0__[\"Vector\"](0, 0);\n /**\n * The current velocity vector (vx, vy) of the actor in pixels/second\n */\n this.vel = new _Algebra__WEBPACK_IMPORTED_MODULE_0__[\"Vector\"](0, 0);\n /**\n * The velocity of the actor last frame (vx, vy) in pixels/second\n */\n this.oldVel = new _Algebra__WEBPACK_IMPORTED_MODULE_0__[\"Vector\"](0, 0);\n /**\n * The current acceleration vector (ax, ay) of the actor in pixels/second/second. An acceleration pointing down such as (0, 100) may\n * be useful to simulate a gravitational effect.\n */\n this.acc = new _Algebra__WEBPACK_IMPORTED_MODULE_0__[\"Vector\"](0, 0);\n /**\n * Gets/sets the acceleration of the actor from the last frame. This does not include the global acc [[Physics.acc]].\n */\n this.oldAcc = _Algebra__WEBPACK_IMPORTED_MODULE_0__[\"Vector\"].Zero;\n /**\n * The current torque applied to the actor\n */\n this.torque = 0;\n /**\n * The current \"motion\" of the actor, used to calculated sleep in the physics simulation\n */\n this.motion = 10;\n /**\n * Gets/sets the rotation of the body from the last frame.\n */\n this.oldRotation = 0; // radians\n /**\n * The rotation of the actor in radians\n */\n this.rotation = 0; // radians\n /**\n * The scale vector of the actor\n * @obsolete ex.Body.scale will be removed in v0.25.0\n */\n this.scale = _Algebra__WEBPACK_IMPORTED_MODULE_0__[\"Vector\"].One;\n /**\n * The scale of the actor last frame\n * @obsolete ex.Body.scale will be removed in v0.25.0\n */\n this.oldScale = _Algebra__WEBPACK_IMPORTED_MODULE_0__[\"Vector\"].One;\n /**\n * The x scalar velocity of the actor in scale/second\n * @obsolete ex.Body.scale will be removed in v0.25.0\n */\n this.sx = 0; //scale/sec\n /**\n * The y scalar velocity of the actor in scale/second\n * @obsolete ex.Body.scale will be removed in v0.25.0\n */\n this.sy = 0; //scale/sec\n /**\n * The rotational velocity of the actor in radians/second\n */\n this.rx = 0; //radians/sec\n this._geometryDirty = false;\n this._totalMtv = _Algebra__WEBPACK_IMPORTED_MODULE_0__[\"Vector\"].Zero;\n if (!actor && !collider) {\n throw new Error('An actor or collider are required to create a body');\n }\n this.actor = actor;\n if (!collider && actor) {\n this.collider = this.useBoxCollider(actor.width, actor.height, actor.anchor);\n }\n else {\n this.collider = collider;\n }\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Simulated number of cookies sold (rounded down)
function numberOfCookiesSold(customerNumber, avgCookies){ var cookiesSold = customerNumber * avgCookies; return Math.floor(cookiesSold); }
[ "function numberOfCookiesSold(customerNumber, avgCookies){\r\n // debugger;\r\n var cookiesSold = customerNumber * avgCookies;\r\n return Math.floor(cookiesSold);\r\n}", "function totalByStore(stor){\n stor.cookiesSold.push(numberOfCookiesNeeded(stor.cookiesSold));\n}", "function incrementWithSpace() {\n setCookies(numCookies + purchasedItems.megaClick);\n }", "calculateCookiesPerSecond() {\n\t\tthis.state.cookiesPerSecond = this.state.buildings\n\t\t\t.map(building => building.calculateCookiesPerSecond())\n\t\t\t.reduce((acc, curr) => acc + curr);\n\t}", "function betsCounter() {\r\n let counter = 0;\r\n const parsedCookies = JSON.parse(JSON.stringify(Cookies.get()));\r\n const keys = Object.keys(parsedCookies);\r\n for (name of keys) {\r\n if (name.substring(0, 3) == 'pa_') {\r\n counter++;\r\n }\r\n }\r\n return counter;\r\n }", "function randomNumberOfCookies (min, max, avgPerCust) {\n var randomNumberOfCustomers = Math.floor(Math.random() * (max - min) + min);\n return Math.floor(randomNumberOfCustomers * avgPerCust);\n}", "function randomizedCookie(min, max, cookies) {\n var customers = Math.floor(Math.random() * (max - min + 1) + min);\n var cookiesPerHour = Math.ceil(customers * cookies);\n return cookiesPerHour;\n}", "function calculateHourlyCookies(){\n for (var i = 0; i< openHours.length; i++){\n var cookiesSoldHourly = Math.round(this.calculateCustomersHourly() * this.avgCookie);\n // console.log('Each Hour Cookie Result', cookiesSoldHourly);\n this.cookieSales.push(cookiesSoldHourly);\n }\n}", "function gameLoop() {\r\n // Add the cookies earned in the last tick to the total\r\n cookies += (cps / ticksPerSecond);\r\n displayCookies();\r\n}", "function AddcurrencyCookies() {\n\tcurrencyCookies = currencyCookies + cookieIncome/10;\n\tclickBonus = cookieIncome;\n\tclickPower = clickPowerBase + clickBonus;\n}", "get cookieSize() {}", "function calculateCookies(store) {\n var cookiesPerHour = [];\n var totalCookies = 0;\n for (var i = 0; i < hours.length; i++) {\n var testNumber = getrandomcust(store.mincust, store.maxcust);\n var answ = Math.floor(testNumber * store.avgcookie);\n console.log(hours[i], \" o'clock: \", answ, \"cookies sold\");\n cookiesPerHour.push(answ);\n totalCookies = answ + totalCookies;\n }\n\n // store.cookiesPerHour = cookiesPerHour;\n // return [cookiesPerHour, totalCookies];\n return {\n byHour: cookiesPerHour,\n totalCookies: totalCookies,\n }\n}", "function increase_count() {\n let rval = parseInt(document.getElementById(\"count\").innerHTML);\n set_cookie(rval+1);\n window.location.reload();\n}", "function cookieProblem(cookies) {\n let max = Math.max(...cookies);\n return cookies.reduce((acc, el) => {return acc + (max - el)}, 0);\n}", "function getGrandma() {\n\t\t\t\t\t\t\tif (cookie_ >= 10) {\n\t\t\t\t\t\t\t\tcookie_ -= 10;\n\t\t\t\t\t\t\t\tgrandma += 1;\n\t\t\t\t\t\t\t\t\tdocument.getElementById(\"cookie_\").innerHTML = cookie_;\n\t\t\t\t\t\t\t\t\tdocument.getElementById(\"grandma\").innerHTML = grandma;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse if (cookie_ <10) {\n\t\t\t\t\t\t\t\talert(\"not enough cookies to bribe a grandma to bake for you! get at least 10 cookies!\");\t\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}", "function simulatedCookies(avgCookies, minCust, maxCust) {\n return Math.floor(getRandomCustomer(minCust, maxCust) * avgCookies);\n}", "set cookieSize(value) {}", "function increaseCount($this) {\n\t\tif ($this.hasClass('chocolate')) {\n\t\t\tcookies.set('chocolate', cookies.get('chocolate')+1);\n\t\t}\n\t\tif ($this.hasClass('sugar')) {\n\t\t\tcookies.set('sugar', cookies.get('sugar')+1);\n\t\t}\n\t\tif ($this.hasClass('lemon')) {\n\t\t\tcookies.set('lemon', cookies.get('lemon')+1);\n\t\t}\n\t\tfillCounts(); //Update page counts\n\t}", "function viralAdvertising(n) {\n let shared = 5;\n let cumulative = 0;\n \n for(let i = 1; i <= n; i++){ \n let peopleWhoLiked = Math.floor(shared / 2);\n cumulative += peopleWhoLiked;\n shared = peopleWhoLiked * 3;\n }\n \n return cumulative;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Prepare to start next shipment
function next_shipment() { show('page-home'); reset_image_box(); reset_image_pod(); reset_signature(); action = ''; $('#damage_info').val(''); $('#id-shipment-value').val(''); ship_info.length = 0; instruction.length = 0; dimensions = ''; name = ''; dest_phone = ''; clear_current(); }
[ "function start() {\n var cart = app.getModel('Cart').get();\n var physicalShipments, pageMeta, homeDeliveries;\n\n if (!cart) {\n app.getController('Cart').Show();\n return;\n }\n // Redirects to multishipping scenario if more than one physical shipment is contained in the basket.\n physicalShipments = cart.getPhysicalShipments();\n if (Site.getCurrent().getCustomPreferenceValue('enableMultiShipping') && physicalShipments && physicalShipments.size() > 1) {\n app.getController('COShippingMultiple').Start();\n return;\n }\n\n // Initializes the singleshipping form and prepopulates it with the shipping address of the default\n // shipment if the address exists, otherwise it preselects the default shipping method in the form.\n if (cart.getDefaultShipment().getShippingAddress()) {\n app.getForm('singleshipping.shippingAddress.addressFields').copyFrom(cart.getDefaultShipment().getShippingAddress());\n app.getForm('singleshipping.shippingAddress.addressFields.states').copyFrom(cart.getDefaultShipment().getShippingAddress());\n app.getForm('singleshipping.shippingAddress').copyFrom(cart.getDefaultShipment());\n } else {\n if (customer.authenticated && customer.registered && customer.addressBook.preferredAddress) {\n app.getForm('singleshipping.shippingAddress.addressFields').copyFrom(customer.addressBook.preferredAddress);\n app.getForm('singleshipping.shippingAddress.addressFields.states').copyFrom(customer.addressBook.preferredAddress);\n }\n }\n session.forms.singleshipping.shippingAddress.shippingMethodID.value = cart.getDefaultShipment().getShippingMethodID();\n\n // Prepares shipments.\n homeDeliveries = prepareShipments();\n\n Transaction.wrap(function () {\n cart.calculate();\n });\n\n // Go to billing step, if we have no product line items, but only gift certificates in the basket, shipping is not required.\n if (cart.getProductLineItems().size() === 0) {\n app.getController('COBilling').Start();\n } else {\n pageMeta = require('*/cartridge/scripts/meta'); // Custom : Changed ~ to *\n pageMeta.update({\n pageTitle: Resource.msg('singleshipping.meta.pagetitle', 'checkout', 'SiteGenesis Checkout')\n });\n\n // Custom Start: Add cloudinary object //\n var cloudinaryConstants = require('*/cartridge/scripts/util/cloudinaryConstants');\n var cloudinary = {};\n\n cloudinary.isEnabled = cloudinaryConstants.CLD_ENABLED;\n if (cloudinaryConstants) {\n cloudinary.highResImgViewType = cloudinaryConstants.CLD_HIGH_RES_IMAGES_VIEW_TYPE;\n cloudinary.pageType = cloudinaryConstants.PAGE_TYPES.CHECKOUT;\n }\n // Custom End: Add cloudinary object //\n\n app.getView({\n ContinueURL: URLUtils.https('COShipping-SingleShipping'),\n Basket: cart.object,\n HomeDeliveries: homeDeliveries,\n cloudinary: cloudinary\n }).render('checkout/shipping/singleshipping');\n }\n}", "_spawnShip() {\n\n // Find first dead ship and prepare it for respawn\n for (let ship of this.ships) {\n if (ship.dead) {\n // Generate new question and answer\n ship.setData(this.generator.generate());\n // Move ship to the top\n ship.setPosition(new Position(50 + Math.round(Math.random() * (this.canvas.width - 100)), -30));\n ship.setSpeed(Math.round(this.score.score / DEFAULT_SPEEDUP_SCORE) * DEFAULT_SPEEDUP_FACTOR);\n // Respawn the ship\n ship.revive();\n\n // Exit the loop, one ship is enough for now\n return;\n }\n }\n\n console.log(\"Too many ships in game. Could not spawn another one :/\");\n }", "function onShipMove() {\n if (!hasStarted) {\n ball.setStartLeft(ship);\n tail.start(ball);\n }\n }", "function createInitialShips() {\n\tentityManager.generateShip();\n}", "function shiftToNextTask() {\n if (debug) {\n API.sendChatMessage(\"[DEBUG] SHIFTED TO NEW OBJECTIVE\");\n }\n if (positions[0] === null) {\n if (marker !== null) {\n cleanup();\n }\n return;\n }\n if (marker !== null) {\n API.deleteEntity(marker);\n }\n if (blip !== null) {\n API.deleteEntity(blip);\n }\n switch (positionsTypes[0]) {\n case \"Waypoint\":\n drawWaypoint();\n return;\n case \"Destroy\":\n drawDestroy();\n return;\n case \"Capture\":\n drawCapture();\n return;\n case \"Hack\":\n drawHack();\n return;\n }\n}", "prepareNextState() {\n this.gameOrchestrator.resetTimer();\n this.gameOrchestrator.changeState(new ChoosingPieceState(this.gameOrchestrator));\n }", "function runSequence() {\n\n pagePositions = [];\n setTargeting();\n setPagePositions();\n defineSlotsForPagePositions();\n\n }", "function createInitialShips() {\n\n entityManager.generateShip({\n cx : 200,\n cy : 200\n });\n \n}", "function blindMoveFromStaging_NextMove(){\n\n var openMobBackSlot = -1;\n var nextAvailableMobStagingCard = -1;\n \n\n\n for(x=mobFirstStagingSlotID; x < mobFirstStagingSlotID+stagingLength; x++){\n \n if(cardSlots[x].cardID >= 0){\n nextAvailableMobStagingCard = cardSlots[x].cardID; break;\n }\n }\n \n for(x=mobFirstBackRowSlotID; x < mobFirstBackRowSlotID+backRowLength; x++){\n if(cardSlots[x].cardID === -1){\n openMobBackSlot = x; break;\n }\n }\n localCardMoveObject.cardID = nextAvailableMobStagingCard;\n localCardMoveObject.slotID = openMobBackSlot;\n}", "function startNextState() {\n game.state.add('at-prom', new AtProm());\n game.state.start('at-prom');\n }", "_onRequestDeliverySlots(shippingMethodType, pageIndex) {\n HomeDeliveryActions.requestDeliverySlots(this.props.deliveryGroupId, shippingMethodType, pageIndex, this.props.endPoints);\n }", "function moveShip(ship) {\r\n\t\t\t\t\tif (!ship.arrived) {\r\n\t\t\t\t\t\tvar v = moveStep(ship.coord, ship.dest.coord, (SR.shipClasses[ship.classIndex].speed * dilation));\r\n\t\t\t\t\t\tship.coord = v.coord;\r\n\t\t\t\t\t\tship.arrived = v.arrived;\r\n\t\t\t\t\t}\r\n\t\t\t\t}", "function setupStartCase12() {\n if ($scope.OrderType == \"Assembly\") {\n //todo line3946-3970\n }\n }", "function populateShipments(originLatitude, originLongitude) {\n\n log.info(\"--------------------------- START ------------------------\")\n log.info(\"MAX_TOTAL_SHIPMENT_COUNT: \" + MAX_TOTAL_SHIPMENT_COUNT)\n log.info(\"TOTAL_SHIPMENTS_TO_CREATE: \" + TOTAL_SHIPMENTS_TO_CREATE)\n log.info(\"TOTAL_SHIPMENT_COUNT_BEFORE: \" + TOTAL_SHIPMENT_COUNT)\n\n for (let i = 0; i < TOTAL_SHIPMENTS_TO_CREATE; i++) {\n let shipmentID = TOTAL_SHIPMENT_COUNT // + i + 1\n let pickupName = FAKER.address.streetAddress()\n let deliveryName = FAKER.address.streetAddress()\n let description = FAKER.name.findName() + \" #\" + randomNumber(1000, 9999)\n let gratuity = calculateShipmentGratuity(shipmentID)\n\n // Get pickup random coordinates from within `MAX_SHIPMENT_DISTANCE_IN_METRES` of the `DRIVER_COORDINATES`.`\n const pickup = randomLocation.randomCirclePoint(DRIVER_COORDINATES, MAX_SHIPMENT_DISTANCE_IN_METRES)\n\n // Get deliver coordinates at the exactly `MAX_SHIPMENT_DISTANCE_IN_METRES * 0.3` from the pickup coordinates..\n const deliver = randomLocation.randomCircumferencePoint(pickup, MAX_SHIPMENT_DISTANCE_IN_METRES * 0.3)\n\n shipments[shipmentID] = new Shipment(\n shipmentID,\n description,\n gratuity,\n pickupName,\n pickup.latitude,\n pickup.longitude,\n deliveryName,\n deliver.latitude,\n deliver.longitude,\n )\n\n TOTAL_SHIPMENT_COUNT++\n\n if (Object.keys(shipments).length > MAX_TOTAL_SHIPMENT_COUNT) {\n\n log.warning(\"SHIPMENT_TO_DELETE: \" + NEXT_SHIPMENT_TO_DELETE)\n\n // remove first element\n delete shipments[NEXT_SHIPMENT_TO_DELETE]\n NEXT_SHIPMENT_TO_DELETE++\n }\n }\n\n log.info(\"TOTAL_SHIPMENT_COUNT_AFTER: \" + TOTAL_SHIPMENT_COUNT)\n log.info(\"--------------------------- END ------------------------\")\n}", "createCargoShip(theScene) {\r\n\r\n // randomize starting port and insure it doesn't start and \r\n // end at same port!\r\n //console.log(\"making a ship\");\r\n this.newFrom = getRandomNumber();\r\n do {\r\n this.newTo = getRandomNumber();\r\n } while (this.newFrom == this.newTo);\r\n this.cargoShip = new CargoShipConstructor(this.newFrom, this.newTo);\r\n let myShip = \"\"; // the new cargoship\r\n\r\n // port locations..\r\n let location = [{ x: 210, y: 130 }, { x: 825, y: 175 }, { x: 480, y: 420 }, { x: 155, y: 835 }, { x: 840, y: 890 }];\r\n\r\n // modify spawn point depending on start and destination to\r\n // avoid crossing a waypoint we don't want.\r\n let changeY = 0;\r\n let changeX = 0\r\n if (this.cargoShip.from === 2) {\r\n changeX = -80\r\n changeY = -30;\r\n\r\n } else if (this.cargoShip.from < 3) {\r\n changeY = 70;\r\n\r\n } else {\r\n changeY = -70;\r\n }\r\n\r\n // actual cargo ship creation\r\n // myShip = theScene.cargoShips.create(location[this.cargoShip.from - 1].x + changeX, location[this.cargoShip.from - 1].y + changeY, \"singleShip\");\r\n\r\n // create random size and gold load...\r\n // would like weighted average though..\r\n let randomShip = [0, 0, 1, 1, 2, 3];\r\n let size = randomShip[Math.floor(Math.random() * 6)];\r\n\r\n switch (size) {\r\n case 0:\r\n // cannoe?!!\r\n myShip = theScene.cargoShips.create(location[this.cargoShip.from - 1].x + changeX, location[this.cargoShip.from - 1].y + changeY, \"cargoDinghy\");\r\n myShip.Ship = new BoatConstructor(1, 5, 25, 0, 0, 0, 0);\r\n myShip.Ship.cannon = 0;\r\n myShip.Ship.gold = 10;\r\n myShip.Ship.speed = 1; // NOTE: since we are using the accelerate to function the speed factors are different\r\n break;\r\n\r\n case 1:\r\n // Schooner\r\n myShip = theScene.cargoShips.create(location[this.cargoShip.from - 1].x + changeX, location[this.cargoShip.from - 1].y + changeY, \"cargoSchooner\");\r\n myShip.Ship = new BoatConstructor(15, 10, 40, 0, 0, 0, 0);\r\n myShip.Ship.cannon = 1;\r\n myShip.Ship.gold = 25;\r\n myShip.Ship.speed = 2; // NOTE: since we are using the accelerate to function the speed factors are different\r\n break;\r\n\r\n case 2:\r\n // Fluyt\r\n myShip = theScene.cargoShips.create(location[this.cargoShip.from - 1].x + changeX, location[this.cargoShip.from - 1].y + changeY, \"cargoFluyt\");\r\n myShip.Ship = new BoatConstructor(30, 25, 50, 0, 0, 0, 0);\r\n myShip.Ship.cannon = 4;\r\n myShip.Ship.gold = 50;\r\n myShip.Ship.speed = 3; // NOTE: since we are using the accelerate to function the speed factors are different\r\n break;\r\n\r\n case 3:\r\n // Galleon\r\n myShip = theScene.cargoShips.create(location[this.cargoShip.from - 1].x + changeX, location[this.cargoShip.from - 1].y + changeY, \"cargoGalleon\");\r\n myShip.Ship = new BoatConstructor(50, 60, 75, 0, 0, 0, 0);\r\n myShip.Ship.cannon = 10;\r\n myShip.Ship.gold = 100;\r\n myShip.Ship.speed = 5; // NOTE: since we are using the accelerate to function the speed factors are different\r\n break;\r\n\r\n default:\r\n\r\n } // end switch\r\n\r\n // set other cargoship properties\r\n myShip.to = this.cargoShip.to;\r\n myShip.from = this.cargoShip.from;\r\n\r\n myShip.name = \"cargoShip\";\r\n myShip.hitWaypoint = false;\r\n\r\n // make interactive so we can attack it! Arg!\r\n myShip.setInteractive();\r\n\r\n\r\n\r\n // Set Cargoships to move toward destinations.\r\n\r\n // using accellerateTo function to send ships to their way points\r\n // or destinations.\r\n //console.log(`From: ${myShip.from} To:${myShip.to}`)\r\n if ((myShip.to === 2 && myShip.from === 4) || (myShip.to === 4 && myShip.from === 2) || (myShip.to === 3 && myShip.from === 4) || (myShip.to === 4 && myShip.from === 3)) {\r\n\r\n theScene.physics.accelerateTo(myShip, 300, 300, myShip.Ship.speed);\r\n ////console.log(\"going to left way point\");\r\n } else if ((myShip.to === 5 && myShip.from === 1) || (myShip.to === 1 && myShip.from === 5) || (myShip.to === 3 && myShip.from === 5) || (myShip.to === 5 && myShip.from === 3)) {\r\n ////console.log(\"going to right way point\");\r\n theScene.physics.accelerateTo(myShip, 700, 300, myShip.Ship.speed);\r\n\r\n } else {\r\n theScene.physics.accelerateTo(myShip, location[this.cargoShip.to - 1].x, location[this.cargoShip.to - 1].y, myShip.Ship.speed);\r\n }\r\n\r\n\r\n }", "start()\n {\n this._makeNextMoveIfCurrentPlayerIsAI();\n }", "function snapToDelivery() {\n\t\t\tvar currentState = $('#ctl00_PageContent_OnePageCheckout1_ShippingAddressEditUKView_LabelShipFirstName').length;\n\t\t\tif (exp.vars.previousState > currentState) {\n\t\t\t\t$('#ctl00_PageContent_OnePageCheckout1_PanelShippingMethod')[0].scrollIntoView({behavior: 'smooth'});\n\t\t\t}\n\t\t\texp.vars.previousState = currentState;\n\t\t}", "function startInitialTanksPlacementPhase() {\r\n\t\t$(\"#availableTanksLabel\").html(numberOfAvailableTanks);\r\n\t\t$(\"#tanksPlacementPhaseDiv\").show();\r\n\t}", "function moveShip(ship) {\r\n\t\t\t\tif (!ship.arrived) {\r\n\t\t\t\t\tvar v = moveStep(ship.coord, ship.dest.coord, (shipClasses[ship.classIndex].speed * dilation));\r\n\t\t\t\t\tship.coord = v.coord;\r\n\t\t\t\t\tship.arrived = v.arrived;\r\n\t\t\t\t}\r\n\t\t\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
clear the unreads for all users in the stream, since it was archived
async clearUnreadsForAllUsers () { let memberIds; if (this.stream.get('isTeamStream')) { memberIds = this.team.get('memberIds') || []; } else { memberIds = this.stream.get('memberIds') || []; } await this.clearUnreadsForUsers(memberIds); }
[ "async clearUnreads () {\n\t\tif (this.wasArchived) {\n\t\t\t// the stream was archived, remove lastUnreads for all users in the stream\n\t\t\tawait this.clearUnreadsForAllUsers();\n\t\t}\n\t\telse if (this.transforms.removedUsers && this.transforms.removedUsers.length > 0) {\n\t\t\t// certain users were removed, remove lastUnreads for those users only\n\t\t\tconst userIds = this.transforms.removedUsers.map(user => user.id);\n\t\t\tawait this.clearUnreadsForUsers(userIds);\n\t\t}\n\t}", "async clearUnreadsForUsers (userIds) {\n\t\tthis.transforms.userUpdateOps = [];\n\t\t// update the lastReads for all users, or as given by the query\n\t\tawait Promise.all(userIds.map(async userId => {\n\t\t\tawait this.clearUnreadsForUser(userId);\n\t\t}));\n\t}", "function clearOutdated(){\r\n users.forEach(function(user, index, users){\r\n if(Date.now() - user.lastUpdated > OUTDATED_TIME){\r\n users.splice(index, 1)\r\n }\r\n })\r\n }", "clearUnreadItems() {\n _.each(this.itemsSubscriptions, sub => {\n sub.clearUnreadItems();\n });\n this.emit(\"update\");\n }", "function clearAllUnreadMessage() {\n for (var friendId in friends) {\n clearUnread(friendId);\n }\n}", "function CleanUpUnreadOrphans() {\n let feedIDs = {};\n\n for (let key in feeds) {\n feedIDs[feeds[key].id] = 1;\n }\n\n for (let key in unreadInfo) {\n if (feedIDs[key] == null) {\n delete unreadInfo[key];\n }\n }\n let promiseCleanUpUnreadOrphans = store.setItem('unreadinfo', unreadInfo);\n\n UpdateUnreadBadge();\n\n return promiseCleanUpUnreadOrphans;\n}", "async getMyUnreads () {\n\t\tif (this.teamData.users.length > SUPPRESS_TEAM_SIZE) {\n\t\t\tthis.userData.unreads = [];\n\t\t\treturn;\n\t\t}\n\t\tthis.userData.unreads = await this.getMyPosts(this.postIsUnread, 'unreads');\n\t\tthis.haveContent = this.haveContent || this.userData.unreads.length > 0;\n\t}", "function CleanUpUnreadOrphans() {\n var feedIDs = {};\n\n for (var key in feeds) {\n feedIDs[feeds[key].id] = 1;\n }\n\n for (var key in unreadInfo) {\n if (feedIDs[key] == null) {\n delete unreadInfo[key];\n }\n }\n var promiseCleanUpUnreadOrphans = store.setItem('unreadinfo', unreadInfo);\n\n UpdateUnreadBadge();\n\n return promiseCleanUpUnreadOrphans;\n}", "function cvjs_clearAllRedlineLockedUsers() {\n\n\t cvjs_lockedUsersList=\"\";\n\n}", "clearAll() {\n if (this.segmentPrefetchMap_.size === 0) {\n return;\n }\n const logPrefix = shaka.media.SegmentPrefetch.logPrefix_(this.stream_);\n for (const reference of this.segmentPrefetchMap_.keys()) {\n if (reference) {\n this.abortPrefetchedSegment_(reference);\n }\n }\n shaka.log.info(logPrefix, 'cleared all');\n this.prefetchPosTime_ = 0;\n }", "sweepCaches() {\n const deleteIds = new Map([...this.presences, ...this.users]);\n\n Paracord.trimMembersFromDeleteList(deleteIds, this.guilds.values());\n\n let sweptCount = 0;\n for (const id of deleteIds.keys()) {\n this.clearUserFromCaches(id);\n ++sweptCount;\n }\n\n this.log('INFO', `Swept ${sweptCount} users from caches.`);\n }", "clearAll() {\n\n new ExpensesAPI().deleteAllUploads(this.state.user.email).then(() => {\n this.loadData();\n })\n }", "function purgeUsers(){\n\tfor(var courseName in queues) {\n \tconsole.log(queues[courseName].courseData.name);\n \tqueues[courseName].courseData.queue.forEach(function (user) {\n\t\tconsole.log(user.name);\n\t\t\tremoveUser(courseName, user);\n\t\t})\n\t}\n}", "function clear() {\n Object.keys(userCache).forEach((hash) => {\n userCache[hash] = null;\n delete userCache[hash];\n });\n\n lastCleanup = new Date();\n}", "clearIgnoredUsers() {\n this._syncService.set({ ignoredUsers: [] });\n }", "unarchive () {\n this.cached = this.archived\n }", "function clearDrafts() {\n\t\t\t// Initializes the 'drafts' array for the current user in the private state object (wave)\n\t\t\twave.getPrivateState().submitDelta({'drafts': []});\n\t\t\t\n\t\t\t$('#drafts').empty();\n\t\t}", "async unarchive() {\n await this.update({\"archived\": false});\n }", "function pruneInactiveUsers() {\n var aWeekAgo = new Date().getTime() - (7*24*60*60*1000);\n for (var username in users) {\n lastSeenTimestamp = new Date(users[username].updatedAt);\n if (lastSeenTimestamp < aWeekAgo) {\n delete users[username];\n }\n }\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the frequency at which to clear the timestamp label. This number will be modded, "%", against the minutes value to determine if the label should be cleared or not.
function get_clear_timestamp_frequency(length) { console.log("Length : " + length); day1 = 1440 / 5; day2 = day1 * 2; day3 = day1 * 3; if (length <= day1) { return 15; } else if (length <= day2) { return 30; } else if (length <= day3) { return 0; } else { return 0; } }
[ "toFrequency() {\n return mtof(this.toMidi());\n }", "function formatFrequency(freq) {\n if (freq == -1) {\n return 'N/A';\n } else if (freq == -2) {\n return 'off';\n } else if (freq > 1000 * 1000) {\n return (freq / 1000 / 1000).toFixed(2) + ' GHz';\n } else {\n return freq / 1000 + ' MHz';\n }\n}", "function resetTimes(){var durationMinuteSelectors=document.querySelectorAll(\".amplitude-duration-minutes\");for(var i=0;i<durationMinuteSelectors.length;i++){durationMinuteSelectors[i].innerHTML=\"00\"}}", "function getFrequency() {\n\treturn 1 * Packages.com.wily.introscope.spec.metric.Frequency.kDefaultSystemFrequencyInSeconds;\n}", "reset() {\n clearTimeout(this.watch);\n this.seconds = 0;\n this.minutes = 0;\n this.hours = 0;\n\n var label = document.getElementById('label_stopwatch')\n label.innerHTML = '00:00:00';\n }", "function YPwmOutput_set_frequency(newval)\n { var rest_val;\n rest_val = String(Math.round(newval * 65536.0));\n return this._setAttr('frequency',rest_val);\n }", "function getFrequency() {\n return 1 * Packages.com.wily.introscope.spec.metric.Frequency.kDefaultSystemFrequencyInSeconds;\n}", "function YPwmOutput_get_frequency()\n {\n if (this._cacheExpiration <= YAPI.GetTickCount()) {\n if (this.load(YAPI.defaultCacheValidity) != YAPI_SUCCESS) {\n return Y_FREQUENCY_INVALID;\n }\n }\n return this._frequency;\n }", "function resetTimes(){/*\n Gets the second display elements\n */var secondSelectors=document.querySelectorAll(\".amplitude-current-seconds\");/*\n Iterates over all of the second selectors and sets the inner HTML\n to 00.\n */for(var i=0;i<secondSelectors.length;i++){secondSelectors[i].innerHTML=\"00\"}}", "function getTimeLabel(timestamp) {\n let eventTime = moment(timestamp)\n\n return `${eventTime.format(\"h:m a\")} - ${eventTime.fromNow()} ${moment().diff(eventTime, 'seconds') <= 600 ? '🔥' : ''}`\n}", "function getFrequency() {\n return 1 * Packages.com.wily.introscope.spec.metric.Frequency.kDefaultSystemFrequencyInSeconds;\n}", "frequency() {\n\t\t// Using http://www.glassarmonica.com/science/frequency_midi.php\n\t\t// f = 27.5 * 2 ^ ((midi - 21)/12)\n\t\t// Midi notes are from 21 (A0, 27.5Hz) to 108 (C8, 4186Hz)\n\t\treturn 27.5 * Math.pow(2, (this.midi() - 21.0) / 12.0)\n\t}", "getTimeCounter() {\r\n const currentTime = formatTime(Math.max(this.currentTime, 0));\r\n const duration = formatTime(this.duration);\r\n return `${currentTime} / ${duration}`;\r\n }", "function resetTimes() {\n /*\n Gets the minute display elements\n */\n var minuteSelectors = document.querySelectorAll(\".amplitude-current-minutes\");\n\n /*\n Iterates over all of the minute selectors and sets the inner HTML\n to 00.\n */\n for (var i = 0; i < minuteSelectors.length; i++) {\n minuteSelectors[i].innerHTML = \"00\";\n }\n }", "function resetFrequencies() {\n angular.forEach(chart.frequencies, function(frequency) {\n frequency.active = false;\n });\n }", "function resetTimes() {\n let durationMinuteSelectors = document.querySelectorAll(\n \".amplitude-duration-minutes\"\n );\n\n for (let i = 0; i < durationMinuteSelectors.length; i++) {\n durationMinuteSelectors[i].innerHTML = \"00\";\n }\n }", "function resetTimes() {\n var durationMinuteSelectors = document.querySelectorAll(\".amplitude-duration-minutes\");\n\n for (var i = 0; i < durationMinuteSelectors.length; i++) {\n durationMinuteSelectors[i].innerHTML = \"00\";\n }\n }", "function resetTimes() {\n /*\n Gets the second display elements\n */\n var secondSelectors = document.querySelectorAll(\".amplitude-current-seconds\");\n\n /*\n Iterates over all of the second selectors and sets the inner HTML\n to 00.\n */\n for (var i = 0; i < secondSelectors.length; i++) {\n secondSelectors[i].innerHTML = \"00\";\n }\n }", "toFrequency() {\n return Object(_Conversions__WEBPACK_IMPORTED_MODULE_1__[\"mtof\"])(this.toMidi());\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
IE Object Fit Fix.
function ieObjectFitFix() { var userAgent, ieReg, ie; const width = $(window).width(); userAgent = window.navigator.userAgent; ieReg = /msie|Trident.*rv[ :]*11\./gi; ie = ieReg.test(userAgent); // If IE is detected and we're at tablet and above screen widths. if(ie && width > 767) { // Then convert image to inline background image. $(imgTarget).each(function () { var imgUrl = $(this).prop('src'), imgHeight = $(this).height(); if (imgUrl) { $(this).wrap('<div class="custom-object-fit" style="background-image:url(' + imgUrl + ');height:' + imgHeight + 'px;"></div>') } }); } }
[ "function objectFitFallBackForIe() {\n var ua = window.navigator.userAgent;\n var msie = ua.indexOf(\"MSIE \");\n if (\n msie > 0 ||\n (!!navigator.userAgent.match(/Trident.*rv\\:11\\./) &&\n $(\".photo-callout-widget__img\").length)\n ) {\n $(\"img.photo-callout-widget__img\").each(function () {\n var t = $(this),\n s = \"url(\" + t.attr(\"src\") + \")\",\n p = t.parent(),\n d = $(\"<div class='ie__fallback--object-fit'></div>\");\n t.hide();\n p.append(d);\n d.css({\n height: 150,\n \"background-size\": \"cover\",\n \"background-repeat\": \"no-repeat\",\n \"background-position\": \"center\",\n \"background-image\": s\n });\n });\n }\n}", "function ObjectFitIt() {\n\t\t$('.js-obj').each(function() {\n\t\t\tvar imgSrc = $(this).attr('src');\n\t\t\tvar fitType = 'cover';\n\t\t\tif ($(this).data('fit-type')) {\n\t\t\t\tfitType = $(this).data('fit-type');\n\t\t\t}\n\t\t\t$(this).parent().css({ \n\t\t\t\t'background' : 'transparent url(\"' + imgSrc + '\") no-repeat center center/' + fitType\n\t\t\t});\n\t\t\t$('.js-obj').css('display','none'); \n\t\t});\n\t}", "function objectFit(img){\n if (document.documentElement.style.objectFit === undefined || document.documentElement.style.objectPosition === undefined){\n var src=$(img).attr('src');\n var style=$(img).attr('style');\n if (!style){style=''}\n $(img).attr('style', 'display: block !important; width: auto !important; height: auto !important; border: 0 !important; margin: 0 !important; padding: 0 !important;');\n var width=$(img).width();\n var height=$(img).height();\n $(img).attr('style', style).data({'naturalWidth': width, 'naturalHeight': height});\n $(img).css({'paddingLeft':'100%', 'visibility':'visible', 'backgroundImage':'url(\"'+ src +'\")', 'backgroundSize':''});\n if ($(img).hasClass('scale-down') && width<$(img).innerWidth() && height<$(img).innerHeight()){\n $(img).css({'backgroundSize':'auto'});\n }\n }\n else{\n $(img).css({'visibility':'visible'});\n }\n}", "function ObjectFitIt() {\n\t\t$('img.obj').each(function() {\n\t\t\tvar imgSrc = $(this).attr('src');\n\t\t\tvar fitType = 'cover';\n\t\t\tif ($(this).data('fit-type')) {\n\t\t\t\tfitType = $(this).data('fit-type');\n\t\t\t}\n\t\t\t$(this).parent().css({ \n\t\t\t\t'background' : 'transparent url(\"' + imgSrc + '\") no-repeat center center/' + fitType\n\t\t\t});\n\t\t\t$('img.obj').css('display','none'); \n\t\t});\n\t}", "function polyfillObjectFit (img, container) {\n if (supportsObjectFit) { return; }\n\n utils.requestAnimFrame.call(window, function ( ) {\n // Get current image src: Edge only supports 'currentSrc' for getting the current image src ('src' returns value DOM value)\n var imageSrc = img.currentSrc || img.src;\n img.style.display = 'none';\n container.style.backgroundSize = img.getAttribute('data-object-fit');\n container.style.backgroundImage = 'url(' + imageSrc + ')';\n });\n }", "function reSizereFit() {\n var sel = app.selection[0];\n\t\t\n var horz = sel.horizontalScale;\n var verz = sel.verticalScale;\n\n var phorz = sel.parent.horizontalScale;\n var pverz = sel.parent.verticalScale;\n\n sel.horizontalScale = sel.horizontalScale < 0 ? -100 : 100;\n sel.verticalScale = sel.verticalScale < 0 ? -100 : 100; \n\n sel.fit(FitOptions.frameToContent);\n \n}", "function fitToFrame() {\n var newHeight, newWidth, scaleRatio;\n\n var frameRatio = self.model.cropHeight / self.model.cropWidth;\n var imageRatio = self.model.height / self.model.width;\n\n if (frameRatio > imageRatio) {\n newHeight = self.model.cropHeight;\n scaleRatio = (newHeight / self.model.height);\n newWidth = parseFloat(self.model.width) * scaleRatio;\n } else {\n newWidth = self.model.cropWidth;\n scaleRatio = (newWidth / self.model.width);\n newHeight = parseFloat(self.model.height) * scaleRatio;\n }\n self.model.zoom = scaleRatio;\n\n self.zoomControl\n .attr('min', scaleRatio)\n .attr('max', self.options.zoom.maxValue - scaleRatio)\n .val(scaleRatio);\n\n self.model.height = newHeight;\n self.model.width = newWidth;\n updateZoomIndicator();\n centerImage();\n }", "function rescale() {\n console.info(\"zqh: Rescaling...\");\n var cparent = $(\"canvas\").parent();\n $(\"canvas\").width(cparent.width());\n $(\"canvas\").height(cparent.width() * 0.8);\n }", "function resizeObjects(objects) {\n var doc = objects.Parent;\n for (var i = 0; i < objects.Count; i++) {\n var obj = objects.Item(i + 1);\n \n var oldSizeWidth = obj.SizeWidth;\n var oldSizeHeight = obj.SizeHeight;\n var newSizeWidth = oldSizeWidth * fac;\n var newSizeHeight = oldSizeHeight * fac;\n \n obj.SizeWidth = newSizeWidth;\n obj.SizeHeight = newSizeHeight;\n var posX = obj.PositionX;\n var posY = obj.PositionY;\n obj.PositionX = posX - (newSizeWidth - oldSizeWidth)/2;\n obj.PositionY = posY + (newSizeHeight - oldSizeHeight)/2;\n }\n}", "static _updateStretchRealScale() {\r\n this._realScale = this._stretchRealScale();\r\n window.scrollTo(0, 0);\r\n }", "function imgSizeIE(ob) {\r\n\tvar w = $(ob).width();\r\n\tif (w > 0 && w != 75) $(ob).width(w);\r\n}", "function Get_ZoomedScaleWithoutInterpreterScaleIE11(theHTML, theObject)\n{\n\t//default scale is 1 -> no modifications\n\tvar scale = 1;\n\t//handling zoom?\n\tif (window.__ZOOM_ACTIVE)\n\t{\n\t\t//we dont have an object?\n\t\tif (!theObject)\n\t\t{\n\t\t\t//try to get it from the htmlObject\n\t\t\twhile (theHTML && !theHTML.InterpreterObject)\n\t\t\t{\n\t\t\t\t//iterate\n\t\t\t\ttheHTML = theHTML.parentNode;\n\t\t\t}\n\t\t\t//found it?\n\t\t\tif (theHTML)\n\t\t\t{\n\t\t\t\t//get its object\n\t\t\t\ttheObject = theHTML.InterpreterObject;\n\t\t\t}\n\t\t}\n\t\t//valid?\n\t\tif (theObject)\n\t\t{\n\t\t\t//our object is absolute?\n\t\t\tvar bAbsolute = /absolute|relative/i.test(theObject.HTML.style ? Get_String(theObject.HTML.style.position, \"\") : \"\");\n\t\t\t//now loop through all objects\n\t\t\twhile (theObject)\n\t\t\t{\n\t\t\t\t//this absolute\n\t\t\t\tvar currentAbsolute = /absolute|relative/i.test(theObject.HTML.style ? Get_String(theObject.HTML.style.position, \"\") : \"\");\n\t\t\t\t//has zoom?\n\t\t\t\tif ((!bAbsolute || currentAbsolute) && theObject.StyleProperties && theObject.StyleProperties.Zoom)\n\t\t\t\t{\n\t\t\t\t\t//modify the scale\n\t\t\t\t\tscale *= theObject.StyleProperties.Zoom.Modifier;\n\t\t\t\t}\n\t\t\t\t//normal iteration\n\t\t\t\ttheObject = theObject.Parent;\n\t\t\t}\n\t\t}\n\t}\n\t//return the scale\n\treturn scale;\n}", "fitObjectTo(obj3d, opts) {\n opts = opts || {};\n console.log(\"fitObjectTo:\", obj3d, opts);\n obj3d = this.getObject3D(obj3d);\n if (opts.size)\n this.scaleObjectTo(obj3d, opts.size);\n this.positionObjectBoundingBox(obj3d, opts.position, opts.anchor);\n }", "setScaleObject(objectToBeWeighed){\n // Scales only can weigh containers\n if(!(objectToBeWeighed instanceof ContainerController2D)) return;\n\n // If there is already an object on the scale, first remove it\n if(this.equipment.objectToBeWeighed !== null) this.removeScaleObject();\n\n // Set the actual Container and update the scale's displayed mass\n this.equipment.setObjectToBeWeighed(objectToBeWeighed);\n this.updateWeighingObjectMass();\n\n // Set up a listener for the equipment\n let eq = this.equipment;\n eq.weighingObjectPosListener = new Listener(this, function(obj){\n let held = obj.equipment.objectToBeWeighed.equipment;\n\n // Do nothing if the object is still close enough to the scale on the y axis\n if(Math.abs(held.position[1] + held.size[1] - obj.y()) < 0.1) return;\n\n let oldPos = held.position;\n obj.removeScaleObject();\n held.setPosition(oldPos);\n });\n eq.objectToBeWeighed.equipment.addPositionListener(eq.weighingObjectPosListener);\n }", "function fixSvgScaleIE(ratio) {\r\n var svgLoader = document.getElementById(\"svg-loader\"),\r\n newWidth = svgLoader.offsetWidth,\r\n newHeight = newWidth / ratio,\r\n svgEl = document.getElementById(\"svg\");\r\n svgEl.style.width = newWidth + \"px\";\r\n svgEl.style.height = newHeight + \"px\";\r\n}", "shrink() {\n if (this.size > 0.2) {\n this.size -= 0.1;\n }\n }", "function normalizeAndRescale(obj, newScale)\r\n{\r\n var scale = getMaxSize(obj); // Available in 'utils.js'\r\n obj.scale.set(newScale * (1.0/scale),\r\n newScale * (1.0/scale),\r\n newScale * (1.0/scale));\r\n return obj;\r\n}", "function sizeToFit(object) {\n // Case for Chrome loading\n if (navigator.userAgent.indexOf(\"Chrome\") !== -1) {\n object.addEventListener('load', function() {\n var svg_doc = object.contentDocument;\n var code_width = svg_doc.getElementById('code').getBBox().width;\n var new_width = Math.max(code_width + 30, 400);\n svg_doc.firstChild.setAttribute('width', new_width + 'px');\n }, {once: true});\n }\n else {\n if (object.contentDocument.readyState == \"complete\") {\n var svg_doc = object.contentDocument;\n var code_width = svg_doc.getElementById('code').getBBox().width;\n var new_width = Math.max(code_width + 30, 400);\n svg_doc.firstChild.setAttribute('width', new_width + 'px');\n }\n }\n}", "resize() {\n this.setScale();\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the current scroll position. Note: This result might be an intermediate scroll position, as there might be an ongoing smooth scroll animation.
getCurrentScrollPosition() { return this._state; }
[ "function getCurrentScroll() {\n return window.pageYOffset || document.documentElement.scrollTop;\n }", "getScrollPosition() {\n if (this.supportsScrolling()) {\n return [this.window.scrollX, this.window.scrollY];\n }\n else {\n return [0, 0];\n }\n }", "function get_current_scroll() {\n return document.scrollTop||document.documentElement.scrollTop||document.body.scrollTop;\n}", "_getViewportScrollPosition() {\n const cachedPosition = this._parentPositions.positions.get(this._document);\n return cachedPosition ? cachedPosition.scrollPosition :\n this._viewportRuler.getViewportScrollPosition();\n }", "getScrollPosition() {\n let scrollableEl = this.getScrollableElement();\n return scrollableEl.getProperty('scrollTop');\n }", "function getScrollPosition() {\n if (document.documentElement.scrollTop == 0) {\n return document.body.scrollTop;\n } else {\n return document.documentElement.scrollTop;\n }\n}", "getScrollPosition() {\r\n let scrollableEl = this.getScrollableElement();\r\n return scrollableEl.getProperty('scrollTop')\r\n }", "_getScrollLocation() {\n if (this._container) {\n return this._container.scrollTop;\n }\n else {\n if (window.pageYOffset) {\n return window.pageYOffset;\n }\n else {\n return document.documentElement.scrollTop;\n }\n }\n }", "function getCurrentScroll() {\n var offsetY, scrolltop;\n offsetY = window.pageYOffset;\n scrolltop = document.documentElement.scrollTop;\n //console.log(offsetY, scrolltop);\n return offsetY || scrolltop;\n }", "_getScrollPosition () {\n const { horizontal, $scrollElement } = this.options;\n return getElementScroll($scrollElement, horizontal);\n }", "function getScrollPosition() {\r\n if (document.documentElement.scrollTop == 0) {\r\n return document.body.scrollTop;\r\n } else {\r\n return document.documentElement.scrollTop;\r\n\r\n }\r\n}", "function getScrollPosition() {\n var verticalPosition = 0,\n ieOffset = document.documentElement.scrollTop,\n target;\n\n if (isApi) {\n target = document.querySelector('.class-body-wrap')\n } else if (isGuide) {\n target = document.querySelector('.guide-body-wrap')\n } else {\n target = document.querySelector('.generic-content')\n }\n\n if (window.pageYOffset) {\n verticalPosition = window.pageYOffset;\n } else if (target.clientHeight) { //ie\n verticalPosition = target.scrollTop;\n } else if (document.body) { //ie quirks\n verticalPosition = target.scrollTop;\n }else {\n verticalPosition = ieOffset;\n }\n\n return verticalPosition;\n }", "function getScroll() {\n\t\t\treturn ((getWindowYScroll() + getWindowHeight()) / getDocHeight()) * 100;\n\t\t}", "function getScrollPos(){\n\tif (document.documentElement.scrollTop!=0){\n\t\treturn document.documentElement.scrollTop;\n\t}\n\telse if (document.body.scrollTop!=0){\n\t\treturn document.body.scrollTop;\n\t}\n\treturn 0;\n}", "function getScrollPos()\n{\n var scrollTop = document.body.scrollTop;\n if (scrollTop == null || scrollTop == 0)\n {\n\t if (window.pageYOffset)\n\t {\n\t\t scrollTop = window.pageYOffset;\n\t }\n\t else\n\t {\n\t \tscrollTop = (document.body.parentElement) ? document.body.parentElement.scrollTop : 0; \n\t } \n }\n // If we can't find the scroll position set it to 0 \n if (scrollTop == null)\n {\n return 0;\n }\n return scrollTop;\n}", "function getScrollingPosition()\n{\n var position = [0, 0];\n\n if (typeof window.pageYOffset != 'undefined')\n {\n position = [\n window.pageXOffset,\n window.pageYOffset\n ];\n }\n\n else if (typeof document.documentElement.scrollTop != 'undefined'\n && (document.documentElement.scrollTop > 0 ||\n document.documentElement.scrollLeft > 0))\n {\n position = [\n document.documentElement.scrollLeft,\n document.documentElement.scrollTop\n ];\n }\n\n else if (typeof document.body.scrollTop != 'undefined')\n {\n position = [\n document.body.scrollLeft,\n document.body.scrollTop\n ];\n }\n\n return position;\n}", "getFutureScrollPosition() {\n if (this._smoothScrolling) {\n return this._smoothScrolling.to;\n }\n return this._state;\n }", "function getscrollpos(){\n\tvar scrtop=0;\n\tvar scrleft=0;\n\tif (document.documentElement){\n\t\tscrtop=document.documentElement.scrollTop;\n\t\tscrleft=document.documentElement.scrollLeft;\n\t} else if (document.body){\n\t\tscrtop=document.body.scrollTop;\n\t\tscrleft=document.body.scrollLeft;\n\t} else {\n\t\tvar derhtml=document.body.parentNode;\n\t\tscrtop=derhtml.scrollTop;\n\t\tscrleft=derhtml.scrollLeft;\n\t}\n\treturn\t{x:scrleft, y:scrtop};\n}", "get scrollPosition() {\n return this.scrollComponent.scrollAmount;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
When a user clicks on a card, that employees's individual data (stored in the registrar function) is called and a modal window is created and inserted after the gallery, displaying employee information. After the modal window is created, this function has an eventlistener to get the close button to function.
function createModal(employee){ let modal = `<div class="modal-container"> <div class="modal"> <button type="button" id="modal-close-btn" class="modal-close-btn"><strong>X</strong></button> <div class="modal-info-container"> <img class="modal-img" src="${employee.picture.large}" alt="profile picture"> <h3 id="name" class="modal-name cap">${employee.name.first} ${employee.name.last}</h3> <p class="modal-text">${employee.email}</p> <p class="modal-text cap">${employee.location.city}</p> <hr> <p class="modal-text">${employee.phone}</p> <p class="modal-text">${employee.location.street.number} ${employee.location.street.name}, ${employee.location.city}, ${employee.location.state} ${employee.location.postcode}</p> <p class="modal-text">Birthday: ${employee.dob.date.slice(5,7)}/${employee.dob.date.slice(8,10)}/${employee.dob.date.slice(0,4)}</p> </div> </div> </div>`; gallery.insertAdjacentHTML('afterend', modal); const modalCont = document.querySelector('.modal-container'); const closeButton = document.querySelector('.modal-close-btn'); closeButton.addEventListener('click', (e) => { modalCont.remove(); }) }
[ "function modalEmployee(i) {\n let clickedEmployeeModalDisplay =\n `<div class=\"modal-container\">\n <div class=\"modal\">\n <button type=\"button\" id=\"modal-close-btn\" class=\"modal-close-btn\"><strong>X</strong></button>\n <div class=\"modal-info-container\">\n <img class=\"modal-img\" src=\"${allEmployees[i]['picture']['large']}\" alt=\"profile picture\">\n <h3 id=\"name\" class=\"modal-name cap\">${allEmployees[i]['name']['first']} ${allEmployees[i]['name']['last']}</h3>\n <p class=\"modal-text\">${allEmployees[i]['email']}</p>\n <p class=\"modal-text cap\">${allEmployees[i]['location']['city']}</p>\n <hr>\n <p class=\"modal-text\">${formatPhoneNo(allEmployees[i]['phone'])}</p>\n <p class=\"modal-text\">${allEmployees[i]['location']['street']['number']} ${allEmployees[i]['location']['street']['name']}, ${allEmployees[i]['location']['state']}, ${allEmployees[i]['location']['postcode']}, ${allEmployees[i]['location']['country']}</p>\n <p class=\"modal-text\">Birthday: ${parseDate(allEmployees[i]['dob']['date'])}</p>\n </div>\n </div>`\n\n const body = document.getElementsByTagName(\"body\")[0];\n body.insertAdjacentHTML('beforeend', clickedEmployeeModalDisplay);\n\n const exitButton = document.getElementById(\"modal-close-btn\");\n exitButton.addEventListener('click' , (e) => {\n\n const myModalWindow = document.getElementsByClassName(\"modal-container\")[0];\n body.removeChild(myModalWindow);\n })\n}", "function displayEmployees(response) {\n let galleryData = \"\";\n // Set Employees to the Returned Response from API\n let employees = response;\n employees.forEach((employee) => {\n //Set Photo, Name, Email, and Location to Response Info\n const photo = employee.picture;\n const name = employee.name;\n const email = employee.email;\n const location = employee.location;\n\n galleryData += `\n <div class=\"card\">\n <div class=\"card-img-container\">\n <img class=\"card-img\" src=\"${photo.large}\" alt=\"profile picture\">\n </div>\n <div class=\"card-info-container\">\n <h3 id=\"name\" class=\"card-name cap\">${name.first} ${name.last}</h3>\n <p class=\"card-text\">${email}</p>\n <p class=\"card-text cap\">${location.city}</p>\n </div>\n </div>\n\n `;\n });\n //Set HTML Adjacent to Gallery Data\n gallery.insertAdjacentHTML(\"beforeend\", galleryData);\n\n const card = document.querySelectorAll(\".card\");\n //Set Event Listener for Every Card Item on Display\n card.forEach((item, index) => {\n item.addEventListener(\"click\", () => {\n createModal(employees, index);\n });\n });\n}", "function showModal (employeeData) {\n const overlay = document.createElement('DIV')\n overlay.className = 'modal-container'\n const html = ` <div class=\"modal-container\">\n <div class=\"modal\">\n <button type=\"button\" id=\"modal-close-btn\" class=\"modal-close-btn\"><strong>X</strong></button>\n <div class=\"modal-info-container\">\n <img class=\"modal-img\" src=\"${employeeData.picture.medium}\" alt=\"profile picture\">\n <h3 id=\"name\" class=\"modal-name cap\">${employeeData.name.first} ${employeeData.name.last}</h3>\n <p class=\"modal-text\">${employeeData.email}</p>\n <p class=\"modal-text cap\">${employeeData.email}</p>\n <hr>\n <p class=\"modal-text\">${employeeData.phone}</p>\n <p class=\"modal-text\">${employeeData.location.street.number} ${employeeData.location.street.name}, ${employeeData.location.city}, ${employeeData.location.state} ${employeeData.location.postcode}</p>\n <p class=\"modal-text\">Birthday: ${employeeData.dob.date.substring(0, 10)}</p>\n </div>\n </div>`\n\n overlay.insertAdjacentHTML('beforeEnd', html)\n document.body.insertAdjacentElement('beforeEnd', overlay)\n\n overlay.querySelector('#modal-close-btn').addEventListener('click', () => {\n overlay.remove()\n })\n document.body.insertAdjacentElement('beforeEnd', overlay)\n}", "function modalUse(e) {\n currentId = parseInt(e.currentTarget.id);\n\n if ([...e.currentTarget.classList].includes(\"card\")) {\n let modalEmp = employees[currentId];\n let modal = createModal(modalEmp);\n\n bodyElem.appendChild(modal);\n modal.style.display = \"block\";\n\n closeModal(modal);\n }\n }", "function openEmployeeModal(e) {\n if (e.target !== gallery) {\n const card = e.target.closest('.card');\n const indexNum = card.getAttribute('data-index');\n index = indexNum;\n createEmployeeModal(index);\n }\n}", "function displayemployeeCards() {\n for (let i = 0; i < employeeCards.length; i++) {\n gallery.appendChild(employeeCards[i]);\n employeeCards[i].addEventListener(\"click\", (e) => {\n cardClickedId = e.target.closest(\".card\").id;\n displayModal(cardClickedId);\n });\n }\n}", "function createEmployeeCard(employeeList){\n //creating a for loop to loop up to 12 cards\n for(let i = 0; i < employeeList.length; i++){\n //employee card\n let card = \n `<div class=\"card\" index=\"${i}\">\n <div class=\"card-img-container\">\n <img class=\"card-img\" src=\"${employeeList[i].picture.medium}\" alt=\"profile picture\">\n </div>\n <div class=\"card-info-container\">\n <h3 id=\"name\" class=\"card-name cap\">${employeeList[i].name.first} ${employeeList[i].name.last}</h3>\n <p class=\"card-text\">${employeeList[i].email}</p>\n <p class=\"card-text cap\">${employeeList[i].location.city}, ${employeeList[i].location.state}</p>\n </div>\n </div>`;\n //appending the card to the gallery dynamically\n $('#gallery').append(card);\n}\n //creating a function to check for the classname card and moving to the parent until it finds it \n function checkForName(element){\n if (element.hasClass('card')){\n return element;\n } else {\n return checkForName(element.parent());\n }\n }\n //creating a click function to show the modal container with the correct information and calling it\n $('.card').on('click', function(event){\n $('.modal-container').show();\n let nameCard = checkForName($(event.target)).attr('index');\n let chosenCard = employeeList[nameCard];\n modal(chosenCard);\n });\n}", "function createModalWindow(data, userIndex) {\n const user = data[userIndex]\n //Formates the date of the user birth\n const date = new Date(user.dob.date)\n userBirthDate = date.getMonth() + 1 + '/' + date.getDate() + '/' + date.getFullYear()\n\n\n const userCellNum = formatPhoneNumber(user.cell)\n const script = document.querySelector('script')\n\n const modalContainer = document.createElement('div')\n modalContainer.setAttribute('class', 'modal-container')\n\n script.parentNode.insertBefore(modalContainer, script)\n\n modalContainer.innerHTML = `<div class=\"modal\">\n <button type=\"button\" id=\"modal-close-btn\" class=\"modal-close-btn\"><strong>X</strong></button>\n <div class=\"modal-info-container\">\n <img class=\"modal-img\" src=${user.picture.large} alt=\"profile picture\">\n <h3 id=\"name\" class=\"modal-name cap\">${user.name.first} ${user.name.last}</h3>\n <p class=\"modal-text\">${user.email}</p>\n <p class=\"modal-text cap\">${user.location.city}</p>\n <hr>\n <p class=\"modal-text\">${userCellNum}</p>\n <p class=\"modal-text\">${user.location.street.number} ${user.location.street.name}, ${user.location.city}, ${user.location.postcode}</p>\n <p class=\"modal-text\">Birthday: ${userBirthDate} </p>\n </div>`;\n\n\n const button = document.querySelector('#modal-close-btn')\n //Adds an event listener on the modal window button to close it\n button.addEventListener('click', () => {\n modalContainer.remove()\n\n })\n\n\n}", "function handerBtnAddClick(ev)\n{\n \n //show overlay\n //document.querySelector(\"[data-role=modal]\").style.display = \"block\";\n document.querySelector(\"[data-role=overlay]\").style.display = \"block\";\n \n \n \n //get trigger button id\n var btnID = ev.target.getAttribute(\"id\");\n //detect button ID, determin open overlay is for adding people or occasion\n switch(btnID)\n {\n case \"btnAddPeople\":\n //show modal session on top of overlay\n modals[0].style.display = \"block\";\n //change title\n document.querySelector('#modalTitle').innerHTML=\"New person\";\n //change placeholder text\n document.querySelector('#new-per-occ').setAttribute('placeholder','Person name');\n\n //change modal overlay id in order to specify the overlay is for peopel\n //this step is very important!!!\n document.querySelector(\"[data-role=modal]\").setAttribute('id','add-person');\n break;\n case \"btnAddOccasion\":\n //show modal session on top of overlay\n modals[0].style.display = \"block\";\n document.querySelector('#modalTitle').innerHTML=\"New occasion\";\n document.querySelector('#new-per-occ').setAttribute('placeholder','Occasion name');\n\n //change modal overlay id in order to specify the overlay is for peopel\n //this step is very important!!!\n document.querySelector(\"[data-role=modal]\").setAttribute('id','add-occasion');\n break;\n case \"btnAddGiftForPerson\":\n //show modal session on top of overlay\n modals[1].style.display = \"block\";\n \n //get button's special attributes which are added in loadGiftForPeople function\n var id=ev.target.getAttribute(\"data-ref-id\");\n var name=ev.target.getAttribute(\"data-ref-name\");\n \n //modify current modal's title which is the innerHTML of p element\n //find p element which is the page title also current model's child node\n var p=modals[1].childNodes[1];\n //modify <p>element\n p.innerHTML=\"Gift for \"+name;\n \n //load occasion list to combobox as option items\n loadOccasionsToDropDownMenu();\n \n //this step is very important\n //pass the person id to save button in add gift page as its attribute\n //when save button is clicked, the id will be used to update table in handleBtnSaveGift\n var btnSaveGift=document.querySelector(\"#btnSaveGift\");\n btnSaveGift.setAttribute(\"data-ref-id\",id);\n //this attribute is also usefull to determin which id is peole id or occasion id\n btnSaveGift.setAttribute(\"data-ref-frompage\",\"saveGiftForPeople\");\n \n //change modal overlay id in order to specify the overlay is for peopel\n //this step is very important!!!\n \n break;\n case \"btnAddGiftForOccasion\":\n //show modal session on top of overlay\n modals[1].style.display = \"block\";\n \n //get button's special attributes which are added in loadGiftForPeople function\n var id=ev.target.getAttribute(\"data-ref-id\");\n var name=ev.target.getAttribute(\"data-ref-name\");\n \n //modify current modal's title which is the innerHTML of p element\n //find p element which is the page title also current model's child node\n var p=modals[1].childNodes[1];\n //modify <p>element\n p.innerHTML=\"Gift for \"+name;\n \n //load occasion list to combobox as option items\n loadPeopleToDropDownMenu();\n \n //this step is very important\n //pass the person id to save button in add gift page as its attribute\n //when save button is clicked, the id will be used to update table in handleBtnSaveGift\n var btnSaveGift=document.querySelector(\"#btnSaveGift\");\n btnSaveGift.setAttribute(\"data-ref-id\",id);\n //this attribute is also usefull to determin which id is peole id or occasion id\n btnSaveGift.setAttribute(\"data-ref-frompage\",\"saveGiftForOccasion\");\n \n //change modal overlay id in order to specify the overlay is for peopel\n //this step is very important!!!\n \n break;\n\n \n \n \n \n }\n \n \n}", "function createModalCard(data) {\n var employee = data.results;\n var employeeModalCard = '';\n for (i=0; i < employee.length; i++) {\n employeeModalCard += `<div class=\"employee-modal-card\" data-employee=\"${i}\">`;\n employeeModalCard += `<div class=\"close-container\">`;\n employeeModalCard += `<p class=\"close\">X</p>`;\n employeeModalCard += `</div>`;\n employeeModalCard += `<div class=\"modal-container\">`;\n employeeModalCard += `<div class=\"top-modal\">`\n employeeModalCard += `<div class=\"img-container\">`;\n employeeModalCard += `<img src=\"${employee[i].picture.large}\" class=\"avatar\" alt=\"employee picture\">`;\n employeeModalCard += `</div>`;\n employeeModalCard += `<p class=\"employee-name\">${employee[i].name.first} ${employee[i].name.last}</p>`;\n employeeModalCard += `<p class=\"text-description\">${employee[i].email}</p>`;\n employeeModalCard += `<p class=\"text-description capitalize\">${employee[i].location.city}</p>`;\n employeeModalCard += `</div>`;\n employeeModalCard += `<div class=\"bottom-modal\">`\n employeeModalCard += `<p class=\"text-description\">${employee[i].cell}</p>`;\n employeeModalCard += `<p class=\"text-description capitalize\">${employee[i].location.street}, ${employee[i].location.city}, ${employee[i].location.state} ${employee[i].location.postcode}</p>`;\n employeeModalCard += `<p class=\"text-description\">Birthday: ${employee[i].dob.date.substring(5,7)}/${employee[i].dob.date.substring(8,10)}/${employee[i].dob.date.substring(0,4)}</p>`;\n employeeModalCard += `</div>`;\n employeeModalCard += `</div>`;\n employeeModalCard += `<div class=\"next-previous-container\">`;\n employeeModalCard += `<a href=\"#\" class=\"previous round\">&#8249;</a>`;\n employeeModalCard += `<a href=\"#\" class=\"next round\">&#8250;</a>`;\n employeeModalCard += `</div>`;\n employeeModalCard += `</div>`;\n }\n employeeModal.innerHTML = employeeModalCard;\n}", "function generateModalWindow(employee) {\n const modalDiv = document.createElement('div');\n const dob = employee.dob.date;\n const birthday = dob.replace(/^(\\d{4})-(\\d{2})-(\\d{2}).*$/, '$2/$3/$1'); //Regex replace method to get the correct date format\n modalDiv.classList = 'modal-container';\n const modalHtml = `<div class=\"modal\">\n <button type=\"button\" id=\"modal-close-btn\" class=\"modal-close-btn\"><strong>X</strong></button>\n <div class=\"modal-info-container\">\n <img class=\"modal-img\" src=\"${employee.picture.large}\" alt=\"profile picture\">\n <h3 id=\"name\" class=\"modal-name cap\">${employee.name.first} ${employee.name.last}</h3>\n <p class=\"modal-text\">${employee.email}</p>\n <p class=\"modal-text cap\">${employee.location.city}</p>\n <hr>\n <p class=\"modal-text\">${employee.phone}</p>\n <p class=\"modal-text\">${employee.location.street.number} ${employee.location.street.name}, ${employee.location.city}, ${employee.location.state} ${employee.location.postcode}</p>\n <p class=\"modal-text\">Birthday: ${birthday}</p>\n </div>\n </div>`;\n modalDiv.innerHTML = modalHtml;\n body.appendChild(modalDiv);\n closeModalWindow(); //function call to close the window on button press\n}", "function setupVehicleModal() {\r\n\t//Display modal when vehicle card is clicked\r\n\tconst vehicleCards = document.getElementsByClassName(\"card vehicle\");\r\n\tfor (let i = 0; i < vehicleCards.length; i++) {\r\n\t\tconst vehicleId = vehicleCards[i].id;\r\n\t\tvehicleCards[i].addEventListener(\"click\", function() {\r\n\t\t\tdocument.getElementById(\"vehicleInfoModal\").style.display = \"block\";\r\n\t\t\tpopulateVehicleModal(vehicleId);\r\n\t\t});\r\n\t}\r\n\t//Close modal when \"x\" is clicked\r\n\tconst btnClose = document.getElementById(\"closeVehicleModal\");\r\n\tbtnClose.addEventListener(\"click\", function() {\r\n\t\tdocument.getElementById(\"vehicleInfoModal\").style.display = \"none\";\r\n\t});\r\n}", "function createModal() {\n RequestNewCardModal().then((json) => {\n const modal = document.querySelector('body').prepend(getChild(json));\n document.querySelector('.modal-container #close').addEventListener('click', closeModal);\n document.querySelector('.modal-container').addEventListener('click', closeModal);\n document.querySelector('.modal-container .button').addEventListener('click', requestNewCard);\n });\n}", "function createGallery(items) {\n\n //clear any previous galleries, to prevent DUPLICATING\n gallery.innerHTML = '';\n\n items.forEach((item, index) => {\n //loop through each employee and create the gallery cards!\n //console.log(index);\n let htmlToAdd = `<div class=\"card\">\n <div class=\"card-img-container\">\n <img class=\"card-img\" src=\"${item.picture.medium}\" alt=\"profile picture\">\n </div>\n <div class=\"card-info-container\">\n <h3 id=\"name\" class=\"card-name cap\">${item.name.first} ${item.name.last}</h3>\n <p class=\"card-text\">${item.email}</p>\n <p class=\"card-text cap\">${item.location.city}, ${item.location.state}</p>\n </div>\n </div>`;\n\n //add to the webpage\n gallery.insertAdjacentHTML('beforeend', htmlToAdd);\n });\n\n //clear the status\n status.innerHTML = '';\n\n //call this function to set up the modal views\n setUpModal();\n}", "function addEventListenerToEmployee(i) {\n let container = document.getElementById(`employee_id_${i}`);\n container.addEventListener('click' , (e) => {\n modalEmployee(i);\n })\n}", "function selectEmployee(event){\n\tif(event.target !== gallery){\n\t\tlet card;\n\t\tlet tag = event.target.tagName;\n\t\tif(tag === 'IMG' || tag === 'H3' || tag === 'P'){\n\t\t\tcard = event.target.parentNode.parentNode;\n\t\t} else if(event.target.className === 'card-info-container' || event.target.className === 'card-img-container'){\n\t\t\tcard = event.target.parentNode;\n\t\t} else {\n\t\t\tcard = event.target;\n\t\t}\n\t\tconst employeeName = card.querySelector('.card-name').textContent;\n\t\tconst employeeIndex = employeesList.findIndex((entry) => {\n\t\t\tconst entryName = `${entry.name.first} ${entry.name.last}`;\n\t\t\tif(entryName === employeeName){\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\treturn false;\n\t\t});\n\t\tconst employee = employeesList[employeeIndex];\n\t\tdisplayModal(employee);\n\n\t}\n }", "function displayModal(modalDish) {\n\n let modal = document.querySelector(\"#modal\");\n modal.classList.add(\"display\");\n modal.querySelector(\".modal-name\").textContent = modalDish.name;\n modal.querySelector(\".modal-image\").src = \"images/\" + modalDish.image + \".jpg\";\n modal.querySelector(\".modal-image\").alt = \"Photo of\" + modalDish.name;\n modal.querySelector(\".modal-description\").textContent = modalDish.description;\n modal.querySelector(\".modal-price\").textContent = \"Price \" + modalDish.price +\" DKK\";\n modal.querySelector(\".closeBtn\").addEventListener(\"click\", hideModal);\n console.log(modalDish);\n}", "function updateModalWindow(people, event){\n let modalWindow = document.querySelector('.modal-container');\n modalWindow.style.display = 'block'\n console.log(event.target.className)\n for (let i = 0; i < people.length; i++){\n if (event.target.textContent === `${people[i].name.last} ${people[i].name.first}`\n || event.target.textContent === `${people[i].email}`\n || event.target.textContent === `${people[i].location.city}, ${people[i].location.state}`\n || event.target.src === `${people[i].picture.thumbnail}` || event.target.className === \"card-info-container\" && event.target.firstElementChild.textContent === `${people[i].name.last} ${people[i].name.first}`){\n let modalInfo = document.querySelector('.modal-info-container');\n modalInfo.innerHTML = '';\n modalInfo.insertAdjacentHTML('afterbegin', `\n <img class=\"modal-img\" src=\"${people[i].picture.thumbnail}\" alt=\"profile picture\">\n <h3 id=\"name\" class=\"modal-name cap\">${people[i].name.last} ${people[i].name.first}</h3>\n <p class=\"modal-text\">${people[i].email}</p>\n <p class=\"modal-text cap\">${people[i].location.city}, ${people[i].location.state}</p>\n <hr>\n <p class=\"modal-text\">${formatPhoneNumber(people[i].cell)}</p>\n <p class=\"modal-text\">${people[i].location.street.number} ${people[i].location.street.name}, ${people[i].location.city}, ${people[i].location.state} ${people[i].location.postcode}</p>\n <p class=\"modal-text\">${formatDOB(people[i].dob.date)}</p>\n `)\n }\n };\n modalWindow.addEventListener('click', e => {\n if (e.target.textContent === 'X'){\n modalWindow.style.display = 'none';\n }\n });\n }", "function generateUserModules(data){\n\n\n for (let i = 0; i < userCards.length; i++) {\n userCards[i].addEventListener('click', () =>{\n\n const month = data[i].dob.date.substr(5,2);\n const day = data[i].dob.date.substr(8,2);\n const year = data[i].dob.date.substr(0,4);\n\n let output = '';\n output = `\n <div class=\"modal-container\">\n <div class=\"modal\">\n <button type=\"button\" id=\"modal-close-btn\" class=\"modal-close-btn\"><strong>X</strong></button>\n <div class=\"modal-info-container\">\n <img class=\"modal-img\" src=\"${data[i].picture.large}\" alt=\"profile picture\">\n <h3 id=\"name\" class=\"modal-name cap\">${data[i].name.first} ${data[i].name.last}</h3>\n <p class=\"modal-text\">${data[i].email}</p>\n <p class=\"modal-text cap\">${data[i].location.city}</p>\n <hr>\n <p class=\"modal-text\">${data[i].phone}</p>\n <p class=\"modal-text\">${data[i].location.street.number} ${data[i].location.street.name}, ${data[i].location.city}, ${data[i].location.state} 97204</p>\n <p class=\"modal-text\">Birthday: ${month}/${day}/${year}</p>\n </div>\n </div>\n `;\n\n $(output).insertAfter($('.gallery'));\n\n const closeBtn = document.getElementById('modal-close-btn');\n\n closeBtn.addEventListener('click', () => {\n\n $('.modal-container').remove();\n \n });\n });\n }\n\n\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets page title and input size every time state is updated
componentDidUpdate() { this.setPageTitle(); this.setInputSize(); }
[ "function onPageLoad()\n{\n\t//Set page size\n\tSetSize();\n}", "function titlePageState() {\n checkInstructionOrStart()\n titlePage.displayTitle();\n titlePage.displayInstructions();\n titlePage.displayStartString();\n}", "[MUTATIONS.SET_TITLE_FONT_SIZE] (state, payload) {\n state.currentSlide.title.fontSize = payload\n state.isCurrentSlideDirty = true\n }", "function setupPage()\n {\n jQuery(divToResize).height( globalKOTHeight );\n jQuery(divToResize).width( globalKOTWidth );\n }", "function onPageLoad()\n\t{\n\t\t//Set page size\n\t\tSetSize();\n\t\tloadPreferences();\n\t}", "function updateTitleComponent() {\n if (self.titleComponent) {\n self.titleComponent.generate(self.exportSizes.selectedOption, showToast, true);\n }\n }", "function updateState() {\n $rootScope.bsScreenSize.state = bsScreenSize.state = bsScreenSize.currentState();\n $rootScope.bsScreenSize.height = bsScreenSize.height = bsScreenSize.currentHeight();\n $rootScope.bsScreenSize.width = bsScreenSize.width = bsScreenSize.currentWidth();\n }", "changePageTitle(newTitle) {\n // Update our own component state with the new data, which will cause our component to re-render\n this.setState({ pageTitle: newTitle });\n }", "getTitleSize(width, height) {\n width += 'px'\n this.setState({\n titleWidth: width,\n titleHeight: height\n })\n }", "function resizePage() { sizeUI(\"introPage\", introAreasL, introAreasP, introFontSizes, introHeights) }", "function onPageLoad()\n\t{\n\t\t//Set page size\n\t\tSetSize();\n\t\t//Persist page settings\n\t\tloadPreferences();\n\t}", "componentDidMount() {\n this.setInputSize(this.state.titleText.length);\n this.setPageTitle();\n this.setState({\n inputText: this.props.board.title || \"\",\n titleText: this.props.board.title || \"\"\n });\n }", "function updatedSize() {\n heading.style.fontSize = \"2em\";\n}", "function updateTitleFontSize() {\n let fontSize = parseInt(window.getComputedStyle(title).fontSize, 10);\n\n // Constrain font size to 58px, or 10% of the window width, whichever is smaller.\n let maxFontSize = Math.min(58, Math.round(window.innerWidth * 0.1));\n if (fontSize > maxFontSize) {\n fontSize = maxFontSize;\n title.style.fontSize = maxFontSize + 'px';\n }\n\n // If the font size is less than the maximum font size,\n // increase the font size until it overflows.\n while (fontSize < maxFontSize && title.scrollWidth <= title.clientWidth) {\n fontSize++;\n title.style.fontSize = fontSize + 'px';\n }\n\n // Reduce the font size until it doesn't overflow.\n while (title.scrollWidth > title.clientWidth) {\n fontSize--;\n title.style.fontSize = fontSize + 'px';\n }\n}", "function setPageTitle (newTitle) {\n title = newTitle;\n }", "_updateTitlePanelTitle() {\n let current = this.currentWidget;\n const inputElement = this._titleHandler.inputElement;\n inputElement.value = current ? current.title.label : '';\n inputElement.title = current ? current.title.caption : '';\n }", "function pageSceneEditTitle() {\n voicelyTitleSettings(false, 'white-text lighten-3 theme ' + oldTheme)\n newVoicelyBtnSettings(false, 'Cancel')\n editTitleBtnSettings(false, 'Update Title')\n phraseDivSettings(true)\n recordSmsSaveBtnSettings(true)\n}", "function initSize(page) {\n page.treeWidth = jquery(page.treeContainerId).width();\n page.treeHeight = 1000;\n page.linkHeight = page.defaultLinkHeight;\n}", "static resize_title() {\n\n Editor.title_el.size = (Editor.title_el.value.length > 10) \n ? Editor.title_el.value.length + 1\n : 12\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the visible box coordinates of the element as a [ left, top, width, height ]
getVisibleBoxCoords(_id, _noOwnScroll) { const [x, y] = this.getVisiblePosition(_id, _noOwnScroll); const [w, h] = this.getSize(_id); return [x, y, w, h]; }
[ "function tswUtilsGetVisibleRect()\n{\n\tvar width, height, x, y;\n\t\n\t//From http://thewebdevelopmentblog.com/2008/10/tutorial-pop-overs-part-2-centering-the-pop-over/\n if (document.all) \n\t{\n\t\t// IE\n\t\twidth = (document.documentElement.clientWidth) ? \n\t\tdocument.documentElement.clientWidth : \n\t\tdocument.body.clientWidth;\n\t\theight = (document.documentElement.clientHeight) ? \n\t\tdocument.documentElement.clientHeight : \n\t\tdocument.body.clientHeight;\n\t\ty = (document.documentElement.scrollTop) ? \n\t\tdocument.documentElement.scrollTop : \n\t\tdocument.body.scrollTop;\n\t\tx = (document.documentElement.scrollLeft) ? \n\t\tdocument.documentElement.scrollLeft : \n\t\tdocument.body.scrollLeft;\n\t\t\n } \n\telse \n\t{\n\t\t// Safari, Firefox\n\t\twidth = window.innerWidth;\n\t\theight = window.innerHeight;\n\t\ty = window.pageYOffset;\n\t\tx = window.pageXOffset;\n\t}\n\t\n\treturn [x, y, width, height];\n}", "getElementCoords(){\n\n // Location on the board using the boardRef when the div is clicked\n const boardLocation = this.boardRef.getBoundingClientRect();\n\n // Area on the DOM (Document Object Model)\n const doc = document.documentElement;\n\n return{\n // X coord \n x: (boardLocation.left + window.pageXOffset) - doc.clientLeft,\n\n // Y coord\n y: (boardLocation.top + window.pageYOffset) - doc.clientTop,\n };\n }", "function getCoords(elem) {\n var box = elem.getBoundingClientRect();\n\n return {\n 'top': box.top + window.pageYOffset,\n 'left': box.left + window.pageXOffset\n }\n}", "function getCoords(obj) {\n var theObj = obj;\n var left = theObj.offsetLeft,\n top = theObj.offsetTop;\n while (theObj = theObj.offsetParent) {\n left += theObj.offsetLeft;\n }\n theObj = obj;\n while (theObj = theObj.offsetParent) {\n top += theObj.offsetTop;\n }\n return [left, top];\n }", "function getLayoutRect(element){return {x:element.offsetLeft,y:element.offsetTop,width:element.offsetWidth,height:element.offsetHeight};}", "function eb(elt)\n{\n var x = null;\n var y = null;\n \n if(elt.style.position == \"absolute\") \n {\n x = parseInt(elt.style.left);\n y = parseInt(elt.style.top);\n } else {\n var pos = GetElementPosition(elt); \n x = pos.x;\n y = pos.y;\n } \n return {x: x, y: y, width: elt.offsetWidth, height: elt.offsetHeight};\n}", "getPosition(_id) {\n const _elem = this._elements[_id];\n let [x, y] = [0, 0];\n if (this._isSVGElem(_elem)) {\n const _rect = _elem.getBoundingClientRect();\n [x, y] = [_rect.left, _rect.top];\n }\n else if (_elem) {\n [x, y] = [_elem.offsetLeft, _elem.offsetTop];\n }\n else {\n console.warn('ELEM.getPosition(', _id, '): Element not found');\n }\n return [x, y];\n }", "get boundingBox() {\n const bb = this.element.getBoundingClientRect()\n bb.x = this.element.x.baseVal.getItem(0).value\n bb.y = this.element.y.baseVal.getItem(0).value\n return bb\n }", "function coords(elem) {\n var myX = myY = 0;\n if (elem.getBoundingClientRect) {\n var rect;\n rect = elem.getBoundingClientRect();\n myX = rect.left + ((typeof window.pageXOffset !== \"undefined\") ?\n window.pageXOffset : document.body.scrollLeft);\n myY = rect.top + ((typeof window.pageYOffset !== \"undefined\") ?\n window.pageYOffset : document.body.scrollTop);\n } else {\n // this fall back doesn't properly handle absolutely positioned elements\n // inside a scrollable box\n var node;\n if (elem.offsetParent) {\n // subtract all scrolling\n node = elem;\n do {\n myX -= node.scrollLeft ? node.scrollLeft : 0;\n myY -= node.scrollTop ? node.scrollTop : 0;\n } while (node = node.parentNode);\n // this will include the page scrolling (which is unwanted) so add it back on\n myX += (typeof window.pageXOffset !== \"undefined\") ? window.pageXOffset : document.body.scrollLeft;\n myY += (typeof window.pageYOffset !== \"undefined\") ? window.pageYOffset : document.body.scrollTop;\n // sum up offsets\n node = elem;\n do {\n myX += node.offsetLeft;\n myY += node.offsetTop;\n } while (node = node.offsetParent);\n }\n }\n return [myX, myY];\n}", "getBoxCoords(_id) {\n const [x, y] = this.getPosition(_id);\n const [w, h] = this.getSize(_id);\n return [x, y, w, h];\n }", "function clientViewportRect() {\r\n var elem = document.documentElement;\r\n var x = window.pageXOffset;\r\n var y = window.pageYOffset;\r\n var width = elem.clientWidth;\r\n var height = elem.clientHeight;\r\n return { x: x, y: y, width: width, height: height };\r\n }", "function getClientPosition(element) {\n\tvar temp = element.getBoundingClientRect(); //Gets coordinate data\n\tvar xPosition = temp.left;\n\tvar yPosition = temp.top;\n\treturn { x: xPosition, y: yPosition };\n}", "function showBoxPosition(){ console.log(\"Box left: \" + box.style.left + \" top: \" + box.style.top);\n }", "function clientViewportRect() {\n\t var elem = document.documentElement;\n\t var x = window.pageXOffset;\n\t var y = window.pageYOffset;\n\t var width = elem.clientWidth;\n\t var height = elem.clientHeight;\n\t return { x: x, y: y, width: width, height: height };\n\t }", "function getRect() {\n\tvar ref = el.getBoundingClientRect();\n\tvar top = ref.top;\n\tvar left = ref.left;\n\tvar width = ref.width;\n\tvar height = ref.height;\n\tvar leftOffset = left - (container.clientWidth - width) / 2;\n\tvar centerTop = top - (container.clientHeight - height) / 2;\n\tvar scaleWidth = el.clientWidth / displayElement.clientWidth;\n\tvar scaleHeight = el.clientHeight / displayElement.clientHeight;\n\treturn (\"transform:translate3D(\" + leftOffset + \"px, \" + centerTop + \"px, 0) scale3D(\" + scaleWidth + \", \" + scaleHeight + \", 0)\")\n}", "async getRect() {\n try {\n return await this.execute_(new command.Command(command.Name.GET_ELEMENT_RECT));\n }\n catch (err) {\n if (err instanceof selenium_webdriver_1.error.UnknownCommandError) {\n const { width, height } = await this.execute_(new command.Command(command.Name.GET_ELEMENT_SIZE));\n const { x, y } = await this.execute_(new command.Command(command.Name.GET_ELEMENT_LOCATION));\n return { x, y, width, height };\n }\n throw err;\n }\n }", "function getLayoutRect(element) {\n return {\n x: element.offsetLeft,\n y: element.offsetTop,\n width: element.offsetWidth,\n height: element.offsetHeight\n };\n }", "getCanvasPosition() {\n let box = this.realCanvasElement.getBoundingClientRect();\n let scrollLeft = this.realCanvasElement.parentNode.scrollLeft;\n let scrollTop = this.realCanvasElement.parentNode.scrollTop;\n let body = document.body;\n let docEl = document.documentElement;\n\n scrollTop = window.pageYOffset || docEl.scrollTop || body.scrollTop;\n scrollLeft = window.pageXOffset || docEl.scrollLeft || body.scrollLeft;\n\n let clientTop = docEl.clientTop || body.clientTop || 0;\n let clientLeft = docEl.clientLeft || body.clientLeft || 0;\n let top = box.top + scrollTop - clientTop;\n let left = box.left + scrollLeft - clientLeft;\n return { top: Math.round(top), left: Math.round(left) };\n }", "function clientViewportRect() {\n var elem = document.documentElement;\n var x = window.pageXOffset;\n var y = window.pageYOffset;\n var width = elem.clientWidth;\n var height = elem.clientHeight;\n return { x: x, y: y, width: width, height: height };\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
number `n` and converts it to a base `b` number. Assume that `b` will never be greater than 16. Return the new number as a string. If the number is 0, your function should return "0" regardless of the base. The 'base' of a number refers to the amount of possible digits that can occupy one of the places in the number. We are used to base 10 numbers, which use the digits 09, however in computer science base 2 (binary) and base 16 (hexadecimal) numbers are often used. The digits used in base 16 are as follows (from smallest to largest): [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, a, b, c, d, e, f] Examples: baseConverter(0, 2) => "0" baseConverter(5, 2) => "101" baseConverter(25, 16) => 19 baseConverter(31, 16) => "1f" To get a feel for base conversion play around on this site: For more information on base conversion refer here:
function baseConverter(num, base) { const bases = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, "a", "b", "c", "d", "e", "f"] const possibleBases = bases.slice(0, base) let result = []; while (num >= base) { result.unshift(possibleBases[num % base]) num = Math.floor(num / base) } result.unshift(num) return result.join("") }
[ "function baseConverter(n, b) {\n if ([0, 1].includes(n)) return n.toString()\n\n const digits = [\n '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',\n 'a', 'b', 'c', 'd', 'e', 'f'\n ];\n\n return baseConverter(Math.floor(n / b), b) + digits[n % b];\n}", "function baseConverter(num, b) {\n if (num === 0) return \"\";\n\n const digits = '0123456789abcdef'.split('');\n\n return baseConverter(Math.floor(num/b), b) + digits[num % b];\n}", "function baseConverter(num,b) {\n if (num ===0) return \"\";\n\n const digits = ['0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'];\n\n return baseConverter(Math.floor(num/b),b) + digits[num%b];\n \n}", "function baseConverter(num, b) {\n\n}", "function convert(n, base1, base2) {\nreturn parseInt(n, base1).toString(base2);\n}", "function baseConverter(decNumber, base) {\n let remStack = new Stack()\n let rem;\n let baseString = '';\n let digits = '0123456789ABCDEF'\n\n while(decNumber > 0) {\n rem = Math.floor(decNumber % base)\n remStack.push(rem)\n decNumber = Math.floor(decNumber / base)\n }\n\n while(!remStack.isEmpty()) {\n baseString += digits[remStack.pop()]\n }\n\n return baseString\n}", "function convertBase(inputNum, baseOfInputNum, baseOfOutput) {\r\n return parseInt(inputNum, baseOfInputNum).toString(baseOfOutput);\r\n}", "function strBaseConverter (number,ob,nb) {\n number = number.toUpperCase();\n var list = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';\n var dec = 0;\n for (var i = 0; i <= number.length; i++) {\n dec += (list.indexOf(number.charAt(i))) * (Math.pow(ob , (number.length - i - 1)));\n }\n number = '';\n var magnitude = Math.floor((Math.log(dec)) / (Math.log(nb)));\n for (var i = magnitude; i >= 0; i--) {\n var amount = Math.floor(dec / Math.pow(nb,i));\n number = number + list.charAt(amount);\n dec -= amount * (Math.pow(nb,i));\n }\n return number;\n}", "function convertBase(str, fromBase, toBase) {\n const digits = parseToDigitsArray(str, fromBase);\n if (digits === null) return null;\n\n let outArray = [];\n let power = [1];\n for (let i = 0; i < digits.length; i += 1) {\n // invariant: at this point, fromBase^i = power\n if (digits[i]) {\n outArray = add(outArray, multiplyByNumber(digits[i], power, toBase), toBase);\n }\n power = multiplyByNumber(fromBase, power, toBase);\n }\n\n let out = '';\n for (let i = outArray.length - 1; i >= 0; i -= 1) {\n out += outArray[i].toString(toBase);\n }\n // if the original input was equivalent to zero, then 'out' will still be empty ''. Let's check for zero.\n if (out === '') {\n let sum = 0;\n for (let i = 0; i < digits.length; i += 1) {\n sum += digits[i];\n }\n if (sum === 0) out = '0';\n }\n\n return out;\n}", "function converter(decimalNumber, base) {\r\n let number = decimalNumber;\r\n const digits = '0123456789ABCDEF';\r\n let remainderStack = new Stack();\r\n let result = '';\r\n\r\n //push remainder to Stack\r\n while (number >= 1) {\r\n remainderStack.push(Math.floor(number % base));\r\n number = number / base;\r\n }\r\n\r\n //pop from Stack to result\r\n while (!remainderStack.isEmpty()) {\r\n result += digits[remainderStack.pop()];\r\n }\r\n\r\n return result;\r\n}", "function toBase10(number) {\n\n var x = number.toLowerCase();\n Logger.debug(\"x = \" + x)\n\n if (!x.startsWith('0b') && !x.startsWith('0x') && parseInt(x, 10).toString(10) == x.replace(/^0+/, '')) {\n Logger.debug('>>> Base 10: ' + parseInt(x, 10).toString(10) + ' = ' + x);\n return parseInt(x, 10);\n } else if (x.startsWith('0b') && (parseInt(x.substring(2), 2).toString(2) == x.substring(2).replace(/^0+/, ''))) {\n Logger.debug('>>> Base 2: ' + parseInt(x.substring(2), 2).toString(2) + ' = ' + x.substring(2));\n return parseInt(x.substring(2), 2);\n } else if (x.startsWith('0x') && (parseInt(x.substring(2), 16).toString(16) == x.substring(2).replace(/^0+/, ''))) {\n Logger.debug('>>> Base 16: ' + parseInt(x.substring(2), 16).toString(16) + ' = ' + x.substring(2));\n return parseInt(x.substring(2), 16);\n } else {\n Logger.debug('>>> ???')\n return NaN;\n }\n}", "getBinario( number) {\n var base = 2;\n return Number(number).toString(base);\n }", "function decToAltBase(n, base) {\n if (n == 0)\n return \"\";\n var rmdr = n % base;\n return decToAltBase(Math.floor(n/base), base) + decToAltDigit(rmdr, base);\n}", "toBase10(value, b = 62) {\n const limit = value.length;\n let result = base.indexOf(value[0]);\n for (let i = 1; i < limit; i++) {\n result = b * result + base.indexOf(value[i]);\n }\n return result;\n }", "function baseTenToBinary(baseTenNumber) {\n //your code here\n}", "function multipleBase(num,base){\n do {\n let rem = num % base;\n s.push(rem);\n num = Math.floor(num/base);\n }\n while(num > 0)\n let conversion = '';\n while(s.length() > 0){\n conversion += s.pop();\n }\n return conversion;\n}", "function numberToString(n, base = 10) {\n let result = '', sign = ''\n if (n < 0) {\n sign = '-'\n n = -n\n }\n do {\n result = String(n % base) + result\n n = Math.floor(n / base)\n console.log(n)\n } while(n > 0)\n return sign + result\n}", "function convertTo2DigitString(n){\treturn (n > 9 ? n : '0' + n); }", "function binOfInt(num, n) {\n var returnString = num.toString(2);\n if (returnString.length < n) {\n return \"0\".repeat(n - returnString.length) + returnString;\n } else {\n return returnString;\n }\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
All of the below functions will try to complete an action for the ai and return true if they did, or false if they did nothing Win the game
function aiWin() { var moves = getWinningMoves(data.board, data.player2); if (moves.length > 0) { var move = pickRandomSpace(moves); placeMoveByIndex(move); return true; } return false; }
[ "function checkActions(action, playerAction) {\n\tvar setTimeOut = false;\n\n\tif (actions.length > count) {\n\t\tplayMove = false;\n\t\treturn false;\n\t}\n\n\tif (action === undefined) {\n\t\tplayedFalse = true;\n\t\treturn false;\n\t}\n \n\tvar actionCorrect;\n\tif (action.getColor() == playerAction.getColor()) {\n\t\tactionCorrect = true;\n\t\t//console.log(\"correct move\");\n\t}\n\telse {\n\t\tactionCorrect = false;\n\t\tplayedFalse = true;\n\t\t//console.log(\"incorrect move\");\n\t}\n\tif (actionCorrect && (playerNumMove + 1) == 20) {\n console.log(\"win set true\");\n win = true;\n\t\tplayMove = false;\n }\n\tif (actionCorrect && (playerNumMove + 1) == actions.length) {\n\t\t//console.log(\"end of sequence add new seuqence needed\");\n\t\tplayerNumMove = 0;\n\t\tcreateNextAction = true;\n\t\tsetTimeOut = true;\n\t}\n\treturn actionCorrect;\n}", "function canComplete(AI, aboutToWin) {\n for (var i = 0; i < 3; i++) {\n var iPlusOne = (i + 1)%3;\n var iPlusTwo = (i + 2)%3;\n for (var j = 0; j < 3; j++) {\n jPlusOne = (j + 1)%3;\n jPlusTwo = (j + 2)%3;\n //tests horizontal\n if (game.board[i][j] == game.board[i][jPlusOne] && game.board[i][jPlusTwo] == defaultValue && game.board[i][j] == aboutToWin) {\n // game.board[i][jPlusTwo] = AI;\n game.play(new Point(i, jPlusTwo));\n return true;\n }\n //tests vertical\n if (game.board[j][i] == game.board[jPlusOne][i] && game.board[jPlusTwo][i] == defaultValue && game.board[j][i] == aboutToWin) {\n // game.board[jPlusTwo][i] = AI;\n game.play(new Point(jPlusTwo, i));\n return true;\n }\n }\n\n //tests Diagonal 1\n if (game.board[i][i] == game.board[iPlusOne][iPlusOne] && game.board[iPlusTwo][iPlusTwo] == defaultValue && game.board[i][i] == aboutToWin) {\n // game.board[iPlusTwo][iPlusTwo] = AI;\n game.play(new Point(iPlusTwo, iPlusTwo));\n return true;\n }\n //Tests Diagonal 2\n if (game.board[i][2 - i] == game.board[iPlusOne][2 - iPlusOne] && game.board[iPlusTwo][2 - iPlusTwo] == defaultValue && game.board[i][2 - i] == aboutToWin) {\n // game.board[iPlusTwo][2 - iPlusTwo] = AI;\n game.play(new Point(iPlusTwo, 2-iPlusTwo));\n return true;\n }\n }\n return false;\n}", "function aiFunc(){\n if (playerTurn ==1){\n return\n }\n if (playerTurn == 0){\n if (ai ==1){\n pickSquare ()\n }\n if (ai==2){\n mediumAI ()\n }\n }\n}", "function aiTurn(){\n\tif(turnCount > 0){\n\t\tif(difficulty == 'easy'){\n\t\t\teasyShot();\n\t\t}else if(difficulty == 'medium'){\n\t\t\tmediumShot();\n\t\t}else if(difficulty == 'hard'){\n\t\t\thardShot();\n\t\t}\n\t\tturnDone = 1;\n\t\tchangeTurn();\n\t\tconfirmChange();\n\t}\n}", "function refuseIfAITurn() {\n if (playArea.hasClass('interaction-disabled')) {\n console.assert(currentPlayer === 2 && gameMode === 'ai', 'Interaction blocked unexpectedly');\n showError('Wait for your turn');\n return true;\n }\n}", "function doAI() {\n\t\tvar move = computer.makeMove();\n\t\tstate.play(move.x, move.y, computer.piece);\n\t \tboard.paint();\n\t \tvlog();\n\t \tvar playerCanMove = state.moveLeftFor( other(computer.piece) );\n\t \tif( !playerCanMove && !state.moveLeftFor( computer.piece ) ) {\n\t \t\tdoResult();\n\t \t} else if( !playerCanMove ){\n\t \t\tlog(\"No move possible for you\");\n\t \t\twindow.setTimeout(doAI, 2000);// give player time to consider\t \n\t \t} else {\n\t \t\tstate.playerTurn = true;\t \n\t \t}\n}", "function checkDoneAction(){\n db.game.findOne({\"game_id\": clientSocket.gameRoom},function(err,doc){\n var done = true;\n var playerArray = doc.player_list;\n playerArray.forEach(function(player){\n if(player.finishedAction === false){\n done = false;\n }\n });\n\n if(done){\n return true;\n }\n return false;\n });\n }", "function check_game() {\n if (die_1.side == 'angry.png' & die_2.side == 'angry.png') {\n // ANGRY!!\n current_goal = 0;\n state.textContent = \"You're ANGRY!! Back to Stage 1\";\n state.className = \"angry\";\n } else {\n if (goals[current_goal].indexOf(die_1.side) != -1 &&\n goals[current_goal].indexOf(die_2.side) != -1 && \n die_2.side != die_1.side) {\n // Update goal\n current_goal++;\n\n // Unhold all die\n if (die_1.held) {\n hold_die(false, die_1);\n }\n if (die_2.held) {\n hold_die(false, die_2);\n }\n }\n state.textContent = stage[current_goal];\n state.className = stage_class[current_goal];\n\n if (current_goal == 3) {\n winner();\n }\n }\n}", "checkInteractValidity() {\n if (Phaser.Geom.Rectangle.ContainsPoint(this.room2a_returnDoor_zone, this.room2a_character_north) &&\n this.room2a_activatedQuiz == false) {\n\t\tthis.displayE();\n\t\tif (this.room2a_key_E.isDown) {\n\t\t\tconsole.log(\"from activity 1 to room 2\")\n\t\t\tthis.scene.start(\"Building_Blocks\");\n\t\t}\n }\n else if (Phaser.Geom.Rectangle.ContainsPoint(this.room2a_P1A, this.room2a_character_north) &&\n this.room2a_activatedQuiz == false) {\n\t\tthis.displayE();\n\t\tif (this.room2a_key_E.isDown) {\n console.log(\"Activated Quiz\")\n\t\t\tthis.room2a_quizActive = true;\n\t\t}\n }\n else if (Phaser.Geom.Rectangle.ContainsPoint(this.coin0_zone, this.room2a_character_north) {\n f\n }\n else {\n this.hideActivities();\n this.room2a_E_KeyImg.alpha = 0.0;\n }\n }", "function isTurnAction(action) {\n return action.type >= A_PASS;\n}", "check_if_finished () {\n let finished = true\n this.players.forEach((player) => {\n if (! player.actionTaken && player.human) {\n finished = false\n }\n })\n if (finished) {\n this.next_stage()\n }\n }", "function is_action_in_progress()\n{\n\tif (ahdframe.currentAction == ACTN_COMPLETE)\n\t{\n\t\treturn true;\n\t}\n\telse\n\t{\n\t\treturn false;\n\t}\n}", "function isGameActive(state) {\n console.log(\"COMPUTING isGameActive...\");\n if (state.attemptsMade === 0) {\n // Inactive, so user can configure\n // enableInputs(state);\n return false;\n } else if (attemptsRemaining(state) > 0) {\n // Active, so user cannot change rules\n // disableInputs(state);\n return true;\n } else if (attemptsRemaining(state) === 0) {\n // User is out of attempts\n // enableInputs(state);\n return false;\n }\n // TODO Need to add another return true for a catch-all?\n}", "function checkAI(battle, DB, msg, output, callback) {\n const aiTrnr = battle.trainer2;\n let aiPkmn = aiTrnr.getActive();\n const userPkmn = battle.trainer1.getActive();\n\n //check if opponent pokemon fainted\n if (aiPkmn.fainted) {\n msg += `${aiPkmn.name} fainted!\\n`;\n //send out next pokemon\n aiPkmn = aiTrnr.nextPkmn();\n msg += `${aiTrnr.name} sent ${aiPkmn.name}!`;\n\n //update battle and send\n battle.trainer2 = aiTrnr;\n battle.save();\n output.battle = {message: msg, battleData: battle};\n callback(null, output);\n\n //if not, have opponent attack the user\n } else {\n battle.save();\n\n //have opponent attack\n const m = aiPkmn.moves[Math.floor((Math.random() * 2))];\n DB.move.damage(m, aiPkmn, userPkmn, (damage2) => {\n output = aiTrnrTurn(battle, m, damage2, msg, output);\n callback(null, output);\n });\n }\n }", "function _checkAi(){return true;}", "checkGameOver() {\n if (this.turns[0] && this.turns[1]) {\n this.getGameResult();\n this.sendOpponentsTurns();\n }\n }", "function checkForWin() {\n\t\t\tif ( defender.HP <= 0 ) {\n\t\t\t\t$( '#attack' )\n\t\t\t\t\t.prop( 'disabled', true );\n\t\t\t\tif ( rounds === characters.length ) {\n \n\t\t\t\t\t$( \"#game-text\" )\n\t\t\t\t\t\t.empty();\n\t\t\t\t\t$( \"#game-text\" )\n\t\t\t\t\t\t.html( \"<h2>Way to go, agent! You can go again if you don't feel up to speed. Otherwise, go buy Beyond Good and Evil and start on the real work for IRIS!</h2>\" );\n\t\t\t\t\t$( \"#restart\" )\n\t\t\t\t\t\t.show();\n\t\t\t\t\t$( \"#opponents\" )\n\t\t\t\t\t\t.hide();\n\t\t\t\t\treturn true;\n\n\t\t\t\t} else {\n\t\t\t\t\t$( \"#game-text\" )\n\t\t\t\t\t\t.empty();\n\t\t\t\t\t$( \"#game-text\" )\n\t\t\t\t\t\t.html( \"<h2>Great, you kicked \" + defender.name + \"'s ass!</h2>\" )\n\t\t\t\t\topponentSelect = true;\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\n\t\t\t}\n\t\t\treturn false;\n\t\t}", "tryToExecuteAction() {\n let success = false;\n\n if (this.states[this.activeState].action) {\n success = true;\n this.states[this.activeState].action();\n }\n\n emit(EVENT_ACTION, {success: success});\n }", "checkIfDone() {\n if (this.correctAnswerCount == 5) {\n // Mini game is won.\n console.log('WON');\n }\n\n if (this.correctAnswerCount + 2 <= this.gamesPlayedCount) {\n // Mini game id lost.\n console.log('LOST');\n }\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns true if the error object indicates the file does not exist (`ENOENT`).
static isFileDoesNotExistError(error) { return FileSystem.isErrnoException(error) && error.code === 'ENOENT'; }
[ "function isENOENT(error) {\n return isExpectedError(error, -ENOENT, 'ENOENT');\n}", "function isFileNotExistfileErr(fileErr) {\n return fileErr.code === \"ENOENT\";\n}", "function fileExists(path) {\n\ttry\t{\n\t\treturn fs.statSync(path);\n\t}\n\tcatch(e) {\n\t\treturn false;\n\t}\n}", "function isIgnorableFileError(error) {\n return (\n error.code === 'ENOENT' ||\n // Workaround Windows node issue #4337.\n (error.code === 'EPERM' && platform === 'win32')\n );\n}", "static isExistError(error) {\n return FileSystem.isErrnoException(error) && error.code === 'EEXIST';\n }", "function fileExists(path) {\n\ttry {\n\t\t// Query the entry\n\t\tvar stats = fs.lstatSync(path);\n\n\t\t// Is it a directory?\n\t\tif (stats.isDirectory() || stats.isFile()) {\n\t\t\treturn true;\n\t\t}\n\t} catch (e) {\n\t\t// ...\n\t}\n\n\treturn false;\n}", "function isFileOrFail(path, message) {\n if (!isFile(path)) {\n throw new Error(message);\n }\n return true;\n}", "exists() {\n\t\t\treturn file.exists();\n\t\t}", "function fileOrFolderExists(path) {\n try {\n fs.lstatSync(path);\n return true;\n }\n catch (error) {\n return false;\n }\n}", "async exists(filepath, options = {}) {\n try {\n await this._stat(filepath)\n return true\n } catch (err) {\n if (err.code === 'ENOENT' || err.code === 'ENOTDIR') {\n return false\n } else {\n console.log('Unhandled error in \"FileSystem.exists()\" function', err)\n throw err\n }\n }\n }", "async exists (filepath, options = {}) {\n try {\n await this._stat(filepath);\n return true\n } catch (err) {\n if (err.code === 'ENOENT' || err.code === 'ENOTDIR') {\n return false\n } else {\n console.log('Unhandled error in \"FileSystem.exists()\" function', err);\n throw err\n }\n }\n }", "function pathExists(path) {\n return fs.accessAsync(path)\n .then(() => true)\n .catch({code: 'ENOENT'}, () => false)\n .catch({code: 'ENOTDIR'}, () => false);\n}", "function doesFileExist( fileName ) {\n\n var xhr = new XMLHttpRequest();\n\n xhr.open( 'HEAD', fileName, false );\n xhr.send();\n\n return ( !(xhr.status === \"404\") );\n\n }", "function doesFileExist(file, callback){\n\t\t\n\tfs.stat(file, function(err, stat) {\n\t\tif(err) {\n\t\t\tif(err.code == 'ENOENT') {\n\t\t\t\tcallback(null, false)\n\t\t\t} else {\n\t\t\t\tcallback(null, err.code);\n\t\t\t}\n\t\t} else { \n\t\t\tcallback(null,true);\n\t\t}\n\t});\n}", "function file_ref_exists(ref)\n{\n try {\n fs.accessSync(ref.filename, fs.F_OK);\n return true;\n }\n catch (ex) {\n return false;\n }\n}", "function doesFileExist(urlToFile)\n{\n     var xhr = new XMLHttpRequest();\n     xhr.open('HEAD', urlToFile, false);\n     xhr.send();\n      \n     if (xhr.status == \"404\") {\n         return false;\n     } else {\n         return true;\n     }\n}", "static isFolderDoesNotExistError(error) {\n return FileSystem.isErrnoException(error) && error.code === 'ENOTDIR';\n }", "function doesFileExist (filepath) {\n return fs.existsSync(filepath)\n}", "_checkExist(files) {\n for ( var file of files ) {\n if(!fs.existsSync(file)) {\n throw new Error('File `' + file + '` does not exist.');\n }\n }\n\n return true;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create the Buildings and Draw them to the Screen.
function createBuildings() { for (let i = 0; i < 4; i++) { buildings.push( CreateGameElement( SHIP.width * 1.5, SHIP.height * 1.2, 65 + 175 * i, C_HEIGHT - 130, 0, BUILDING_IMG, 0 ) ); } }
[ "function makeBuildings() {\n buildings.background(60,179,113);\n buildings.noStroke();\n let x,y;\n for (let i = 0; i < 320; i++) {\n if (i < 80) {\n x = random(0,mapSize/2);\n y = random(0,mapSize/2);\n } else if (i < 160) {\n x = random(0,mapSize/2);\n y = random(mapSize/2,mapSize);\n } else if (i < 240) {\n x = random(mapSize/2,mapSize);\n y = random(0,mapSize/2);\n } else {\n x = random(mapSize/2,mapSize);\n y = random(mapSize/2,mapSize);\n }\n let xlen = random(40, 60);\n let ylen = random(40, 60);\n buildings.fill(random(50,150));\n buildings.rect(x,y,xlen,ylen);\n }\n}", "function draw() {\n background(0, 0, 15);\n\n updateBuildings();\n drawBuildings();\n\n runner.update(buildings);\n runner.draw();\n}", "function drawBuildings(){\n\t\tblgList.forEach(function(blg){\n\t\t\tc.fillStyle = blg.blgStyle;\n\t\t\tdrawBulding(blg);\n\t\t\tdrawLights(blg);\n\t\t});\n\t}", "function draw(){\r\n\t//Builds the ground\r\n\tbuildGround();\r\n\t\r\n\t//Builds the walls\r\n\tbuildWalls();\r\n\t\r\n\t//Builds the turnstiles\r\n\tbuildTurnStile();\r\n}", "function drawBuildings() {\r\n\t// For each building, for each piece of the building height-wise, for each piece of the building width-wise\r\n\tfor (k = 0; k < buildingcount; k++) {\r\n\t for (i = 0; i < buildingheight; i++) {\r\n\t for (j = 0; j < buildingwidth; j++) {\r\n\t\t\t\t// If the building has not been completely destroyed\r\n\t if (buildings[k][i][j].status >= 1) {\r\n\t\t\t\t\r\n\t\t\t\t\t// The height is the normal height minus 2 for each point of damage the building has taken\r\n\t\t\t damagedheight = blocksidelength + 2*(-4 + buildings[k][i][j].status);\r\n\t\t\t\t\t// The width is the same\r\n\t\t\t damagedwidth = blocksidelength + 2*(-4 + buildings[k][i][j].status);\r\n\t\t\t\t\t\r\n\t\t\t\t\t// Then its x-coordinate is the offset plus the length of however many blocks are to its left\r\n\t\t\t\t\t// plus an additional offset for each building that's come before it, then centered with regard to its width\r\n\t var buildingpieceX = buildingoffsetleft + j*blocksidelength + k*(buildingoffsetbetween) - 0.5 * damagedwidth;\r\n\t\t\t\t\t// Its y-coordinate is the highest (closest to bottom of screen) y-coordinate it is \r\n\t\t\t\t\t// allowed to have minus the length of the blocks below it, then centered\r\n\t var buildingpieceY = buildingoffsettop - i*blocksidelength - 0.5 * damagedheight;\r\n\t\t\t\t\t\r\n\t\t\t\t\t// Assign the coordinates\r\n\t buildings[k][i][j].x = buildingpieceX;\r\n\t buildings[k][i][j].y = buildingpieceY;\r\n\t\t\t\t\t// Begin drawing the block\r\n\t ctx.beginPath();\r\n\r\n\t ctx.rect(buildingpieceX, buildingpieceY, damagedwidth, damagedheight);\r\n\t ctx.fillStyle = \"#00FF00\";\r\n\t ctx.fill();\r\n\t ctx.closePath();\r\n\t }\r\n\t }\r\n }\r\n\t}\r\n}", "function initBuildings( /*[in]*/ canvasContext, /*[out]*/ buildings ) {\r\n\tvar MAX_BUILDING_WIDTH = gameWidth/6;\r\n\tvar MIN_BUILDING_WIDTH = gameWidth/20;\r\n\tvar MAX_BUILDING_HEIGHT = 3*gameHeight/5;\r\n\tvar MIN_BUILDING_HEIGHT = gameHeight/4;\r\n\t\r\n\tvar currentX = 0;\r\n\tvar n = 0;\r\n\t\r\n\tcontext = canvasContext;\r\n\t\r\n\tvar remainingWidth = gameWidth;\r\n\t// generate randomly-sized buildiings until 4 slots or less are left\r\n\twhile ( remainingWidth > MAX_BUILDING_WIDTH ) {\t\t\r\n\t\t// generate random width and height for building\r\n\t\tvar width = Math.floor( (Math.random()*(MAX_BUILDING_WIDTH-MIN_BUILDING_WIDTH)) + MIN_BUILDING_WIDTH );\r\n\t\tvar height = Math.floor( Math.random()*(MAX_BUILDING_HEIGHT-MIN_BUILDING_HEIGHT) + MIN_BUILDING_HEIGHT );\r\n\t\tremainingWidth = remainingWidth - width;\r\n\t\t\r\n\t\tbuildings[n] = new Building( currentX, width, height );\r\n\t\tcurrentX = currentX + width;\r\n\t\t\r\n\t\tn++;\r\n\t}\r\n\t\r\n\tfor ( var i=0; i<n; i++ ) {\r\n\t\tdrawBuilding( buildings[i] );\t\t\r\n\t}\r\n\t\r\n\tconsole.log( \"building:initBuildings(): Initialization complete\" );\r\n}", "function createBuildinding(initialCost, creationCost, buildingObject) {\n\n //console.log(buildingObject.location);\n\n //console.log(money - initialCost);\n if (money - initialCost < 0) {\n\n alert('You lack the funds to create this building.');\n return;\n }\n\n for (var currRes in creationCost) {\n\n if (resources[currRes] == null || resources[currRes] - creationCost[currRes] < 0) {\n\n alert('You lack the resources required to build this, you need: ' + JSON.stringify(creationCost));\n return;\n }\n }\n\n money -= initialCost;\n for (var currRes in creationCost) {\n\n resources[currRes] -= creationCost[currRes];\n }\n\n buildingArray.push(buildingObject);\n console.log(buildingArray);\n //draw buidling at x, y location on canvas\n\n var toBuildAtLoc;\n //console.log(buildingArray[i].location, lastClickX, lastClickY);\n\n if (buildingObject.type === 'lumbermill') {\n\n toBuildAtLoc = lumbermillImg;\n } else if (buildingObject.type === 'waterpump') {\n\n toBuildAtLoc = waterpumpImg;\n } else if (buildingObject.type === 'waterturbine' || buildingObject.type === 'coalGenerator') {\n\n toBuildAtLoc = powergenImg;\n } else if (buildingObject.type === 'coalMine') {\n\n toBuildAtLoc = coalMineImg;\n } else if (buildingObject.type === 'ironMine') {\n\n toBuildAtLoc = ironMineImg;\n } else if (buildingObject.type === 'goldMine') {\n\n toBuildAtLoc = goldMineImg;\n } else if (buildingObject.type === 'coffeeFarm' ||\n buildingObject.type === 'tobaccoFarm' ||\n buildingObject.type === 'fruitFarm' ||\n buildingObject.type === 'vegiFarm') {\n\n toBuildAtLoc = farmImg;\n } else if (buildingObject.type === 'airport') {\n\n toBuildAtLoc = planeImg;\n } else if (buildingObject.type === 'dock') {\n\n toBuildAtLoc = dockImg;\n }\n\n var context = document.getElementById('canvas').getContext('2d');\n context.drawImage(toBuildAtLoc, currClickX, currClickY);\n}", "function initBuildings() {\r\n var cultist = new Building(\"Cultist\",\r\n \"Cultist\", \r\n \"cultist\",\r\n \"Cultists generate blood which can be used to activate a variety of effects.\",\r\n \"Cultists slowly generate blood which can be used to activate various effects, using the below buttons.\",\r\n 83.33, \r\n 4, \r\n 1,\r\n [0, 1, 2, 3, 4, 5, 99],\r\n \"images/building_icon_cultist.png\", \r\n \"images/building_tab_cultist.png\", \r\n \"images/building_tab_cultist_hover.png\",\r\n 5,\r\n 1);\r\n cultist.stats[\"Rituals Performed\"] = 0;\r\n cultist.stats[\"Blood Spent\"] = 0;\r\n\t\r\n\tvar mine = new Building(\"Mine\",\r\n \"Mine\", \r\n \"mine\",\r\n \"Mines slowly produce gold bars, which can be exchange for various other currencies.\",\r\n \"Mines slowly produce gold bars, which can be exchange for various other currencies. How many gold bars you own is displayed below.\",\r\n 83.33, \r\n 4, \r\n 1,\r\n [10, 11, 12, 13, 14, 15, 100],\r\n \"images/building_icon_mine.png\", \r\n \"images/building_tab_mine.png\", \r\n \"images/building_tab_mine_hover.png\",\r\n 3,\r\n 2);\r\n mine.stats[\"Gold Mined\"] = 0;\r\n \r\n var gambler = new Building(\"Gambler\",\r\n \"Gambler\", \r\n \"gambler\",\r\n \"Gamblers slowly store card draws. These can be used to activate one of many random effects. After one effect is activated, that effect will not be chosen until all others are chosen first.\",\r\n \"Gamblers slowly store card draws. These can be used to activate one of many random effects. After one effect is activated, that effect will not be chosen until all others are chosen first.\",\r\n 83.33, \r\n 4, \r\n 1,\r\n [30, 31, 32, 33, 34, 35, 101],\r\n \"images/building_icon_gambler.png\", \r\n \"images/building_tab_gambler.png\", \r\n \"images/building_tab_gambler_hover.png\",\r\n 5,\r\n 4);\r\n gambler.stats[\"Cards Drawn\"] = 0;\r\n gambler.stats[\"Cards Discarded\"] = 0;\r\n\t\r\n\tvar power = new Building(\"Power\",\r\n \"Power Plant\", \r\n \"power_plant\",\r\n \"Power Plants generate power that can be used to temporarily increase production and working speed of other buildings.\",\r\n \"Power Plants generate power that can be used to temporarily increase production and working speed of other buildings by 50%. This can be activated inside other building&#39;s tabs.\",\r\n 83.33, \r\n 4, \r\n 1,\r\n [40, 41, 42, 43, 44, 45, 102],\r\n \"images/building_icon_power.png\", \r\n \"images/building_tab_power.png\", \r\n \"images/building_tab_power_hover.png\",\r\n 0,\r\n 5);\r\n\t\r\n\tvar bank = new Building(\"Bank\",\r\n \"Bank\", \r\n \"bank\",\r\n \"Banks grant the ability to lend money for a greater pay-off later, and the ability to buy gold bars (gold bars can be used in exchange for other building&#39;s currencies).\",\r\n \"Banks grant the ability to lend money for a greater pay-off later, and the ability to buy gold bars (gold bars can be used in exchange for other building&#39;s currencies).\",\r\n 83.33, \r\n 4, \r\n 1,\r\n [50, 51, 52, 53, 54, 55, 103],\r\n \"images/building_icon_bank.png\", \r\n \"images/building_tab_bank.png\", \r\n \"images/building_tab_bank_hover.png\",\r\n 5,\r\n 6);\r\n bank.stats[\"Investments Made\"] = 0;\r\n\t\r\n\tvar research = new Building(\"Research\",\r\n \"Research Center\", \r\n \"research_center\",\r\n \"Research Centers slowly generate research points which can be used to buy various effects.\",\r\n \"Research Centers slowly generate research points which can be used to buy various effects from the pannable area below.\",\r\n 83.33, \r\n 4, \r\n 1,\r\n [60, 61, 62, 63, 64, 65, 104],\r\n \"images/building_icon_research.png\", \r\n \"images/building_tab_research.png\", \r\n \"images/building_tab_research_hover.png\",\r\n 0,\r\n 7);\r\n\tresearch.stats[\"Researches Made\"] = 0;\r\n\t\r\n\tvar factory = new Building(\"Factory\",\r\n \"Factory\", \r\n \"factory\",\r\n \"Factories grant the ability to automate various aspects of other buildings.\",\r\n \"Factories grant the ability to automate various aspects of other buildings.\",\r\n 83.33, \r\n 4, \r\n 1,\r\n [66, 67, 68, 69, 70, 71, 105],\r\n \"images/building_icon_factory.png\", \r\n \"images/building_tab_factory.png\", \r\n \"images/building_tab_factory_hover.png\",\r\n 0,\r\n 8);\r\n\t\r\n\tvar bonus = new Building(\"Bonus\",\r\n\t\t\t\t\t\t \"Bonus Factory\", \r\n\t\t\t\t\t\t \"bonus_factory\",\r\n\t\t\t\t\t\t \"Bonus factories slowly store random bonuses which can later be manually activated.\",\r\n\t\t\t\t\t\t \"Bonus factories slowly store random bonuses which can later be manually activated.\",\r\n\t\t\t\t\t\t 1423828125000000, //Cost 1.42 Quadrillion\r\n\t\t\t\t\t\t 10000000000000, //10 Trillion Production\r\n\t\t\t\t\t\t 2,\r\n\t\t\t\t\t\t [107, 108, 109, 110, 111, 112],\r\n\t\t\t\t\t\t \"images/building_icon_buff.png\", \r\n\t\t\t\t\t\t \"images/building_tab_buff.png\", \r\n\t\t\t\t\t\t \"images/building_tab_buff_hover.png\",\r\n\t\t\t\t\t\t 0,\r\n\t\t\t\t\t\t 12);\r\n\t\t\t\t\t\t\t\r\n\tbonus.stats[\"Total Bonuses\"] = 0;\r\n\t\t\t\t\t\t\t\r\n\tvar click = new Building(\"Click\",\r\n\t\t\t\t\t\t \"Click Farm\", \r\n\t\t\t\t\t\t \"click_farm\",\r\n\t\t\t\t\t\t \"Click farms slowly generate clicks which can be used to click in a predetermined path.\",\r\n\t\t\t\t\t\t \"Click farms slowly generate clicks which can be used to click in a predetermined path.\",\r\n\t\t\t\t\t\t 1423828125000000, //Cost 1.42 Quadrillion\r\n\t\t\t\t\t\t 10000000000000, //10 Trillion Production\r\n\t\t\t\t\t\t 2,\r\n\t\t\t\t\t\t [117, 118, 119, 120, 121, 122],\r\n\t\t\t\t\t\t \"images/building_icon_click.png\", \r\n\t\t\t\t\t\t \"images/building_tab_click.png\", \r\n\t\t\t\t\t\t \"images/building_tab_click_hover.png\",\r\n\t\t\t\t\t\t 0,\r\n\t\t\t\t\t\t 13);\r\n\t\t\t\t\t\t\t\r\n\tclick.stats[\"Clicks Made\"] = 0;\r\n\t\t\t\t\t\t\t\r\n\tvar cryogenic = new Building(\"Cryogenic\",\r\n\t\t\t\t\t\t \"Cryogenic Lab\", \r\n\t\t\t\t\t\t \"cryogenic_lab\",\r\n\t\t\t\t\t\t \"Cryogenic labs allow you to freeze one temporary bonus at a time. This essentially allows you to store a temporary bonus for later use.\",\r\n\t\t\t\t\t\t \"Cryogenic labs allow you to freeze one temporary bonus at a time. This essentially allows you to store a temporary bonus for later use. Click on a temporary bonus to freeze it.\",\r\n\t\t\t\t\t\t 1423828125000000, //Cost 1.42 Quadrillion\r\n\t\t\t\t\t\t 10000000000000, //10 Trillion Production\r\n\t\t\t\t\t\t 2,\r\n\t\t\t\t\t\t [127, 128, 129, 130, 131, 132],\r\n\t\t\t\t\t\t \"images/building_icon_cryogenic.png\", \r\n\t\t\t\t\t\t \"images/building_tab_cryogenic.png\", \r\n\t\t\t\t\t\t \"images/building_tab_cryogenic_hover.png\",\r\n\t\t\t\t\t\t 0,\r\n\t\t\t\t\t\t 14);\r\n\t\t\t\t\t\t\t\r\n\tvar alien = new Building(\"Alien\",\r\n\t\t\t\t\t\t \"Alien Lab\", \r\n\t\t\t\t\t\t \"alien_lab\",\r\n\t\t\t\t\t\t \"Alien Labs generate alien research, which can be used to boost the production of other buildings by 75%, but decreases the building&#39;s work rate by 25%.\",\r\n\t\t\t\t\t\t \"Alien Labs generate alien research, which can be used to boost the production of other buildings by 75%, but decreases the building&#39;s work rate by 25%.\",\r\n\t\t\t\t\t\t 1423828125000000, //Cost 1.42 Quadrillion\r\n\t\t\t\t\t\t 10000000000000, //10 Trillion Production\r\n\t\t\t\t\t\t 2,\r\n\t\t\t\t\t\t [137, 138, 139, 140, 141, 142],\r\n\t\t\t\t\t\t \"images/building_icon_alien.png\", \r\n\t\t\t\t\t\t \"images/building_tab_alien.png\", \r\n\t\t\t\t\t\t \"images/building_tab_alien_hover.png\",\r\n\t\t\t\t\t\t 0,\r\n\t\t\t\t\t\t 15);\r\n\t\t\t\t\t\t\t\r\n\tvar computer = new Building(\"Computer\",\r\n\t\t\t\t\t\t \"Mainframe Computer\", \r\n\t\t\t\t\t\t \"mainframe_computer\",\r\n\t\t\t\t\t\t \"Mainframe computers grants the ability to activate &quot;programs&quot;. These programs have 2 positive and 2 negative effects that will occur over time.\",\r\n\t\t\t\t\t\t \"Mainframe computers grants the ability to activate &quot;programs&quot;. These programs have 2 positive and 2 negative effects that will occur over time.\",\r\n\t\t\t\t\t\t 1423828125000000, //Cost 1.42 Quadrillion\r\n\t\t\t\t\t\t 10000000000000, //10 Trillion Production\r\n\t\t\t\t\t\t 2,\r\n\t\t\t\t\t\t [147, 148, 149, 150, 151, 152],\r\n\t\t\t\t\t\t \"images/building_icon_computer.png\", \r\n\t\t\t\t\t\t \"images/building_tab_computer.png\", \r\n\t\t\t\t\t\t \"images/building_tab_computer_hover.png\",\r\n\t\t\t\t\t\t 0,\r\n\t\t\t\t\t\t 16);\r\n\t\t\t\t\t\t\t\r\n\tcomputer.stats[\"Programs Ran\"] = 0;\r\n\t\t\t\t\t\t\t\r\n\tvar acceleration = new Building(\"Accel\",\r\n\t\t\t\t\t\t \"Acceleration Lab\", \r\n\t\t\t\t\t\t \"acceleration_lab\",\r\n\t\t\t\t\t\t \"Acceleration labs grant the ability to toggle though various effects that increase in power during continuous use.\",\r\n\t\t\t\t\t\t \"Acceleration labs grant the ability to toggle though various effects that increase in power during continuous use.\",\r\n\t\t\t\t\t\t 1423828125000000, //Cost 1.42 Quadrillion\r\n\t\t\t\t\t\t 10000000000000, //10 Trillion Production\r\n\t\t\t\t\t\t 2,\r\n\t\t\t\t\t\t [157, 158, 159, 160, 161, 162],\r\n\t\t\t\t\t\t \"images/building_icon_acceleration.png\", \r\n\t\t\t\t\t\t \"images/building_tab_acceleration.png\", \r\n\t\t\t\t\t\t \"images/building_tab_acceleration_hover.png\",\r\n\t\t\t\t\t\t 0,\r\n\t\t\t\t\t\t 17);\r\n\t\t\t\t\t\t\t\r\n\tvar fluctuation = new Building(\"Flux\",\r\n\t\t\t\t\t\t \"Fluctuation Lab\", \r\n\t\t\t\t\t\t \"fluctuation_lab\",\r\n\t\t\t\t\t\t \"Fluctuation labs generate flux that can be used to activate powerful abilities, followed by a crash.\",\r\n\t\t\t\t\t\t \"Fluctuation labs generate flux that can be used to activate powerful abilities, followed by a crash.\",\r\n\t\t\t\t\t\t 1423828125000000, //Cost 1.42 Quadrillion\r\n\t\t\t\t\t\t 10000000000000, //10 Trillion Production\r\n\t\t\t\t\t\t 2,\r\n\t\t\t\t\t\t [167, 168, 169, 170, 171, 172],\r\n\t\t\t\t\t\t \"images/building_icon_fluctuation.png\", \r\n\t\t\t\t\t\t \"images/building_tab_fluctuation.png\", \r\n\t\t\t\t\t\t \"images/building_tab_fluctuation_hover.png\",\r\n\t\t\t\t\t\t 0,\r\n\t\t\t\t\t\t 18);\r\n\t\t\t\t\t\t\t\r\n\tfluctuation.stats[\"Total Fluctuations\"] = 0;\t\r\n\t\r\n\tvar clone = new Building(\"Clone\",\r\n\t\t\t\t\t\t \"Cloning Lab\", \r\n\t\t\t\t\t\t \"cloning_lab\",\r\n\t\t\t\t\t\t \"Periodically can double the production and work rate of a tier 1 or tier 2 building.\",\r\n\t\t\t\t\t\t \"Can double the production and work rate of a tier 1 or tier 2 building. This can be activated inside other building&#39;s tabs. Base production is \" + tweaker.general.tier_3_base_multiplier + \"x the greatest base production of all tier 1 or tier 2 buildings increased by 0.2% per the maximum number of one building owned.\",\r\n\t\t\t\t\t\t 83330000000000000000000000000, //Cost 83.33 Octillion\r\n\t\t\t\t\t\t 0, //0 Trillion Production\r\n\t\t\t\t\t\t 3,\r\n\t\t\t\t\t\t [167, 168, 169, 170, 171, 172],\r\n\t\t\t\t\t\t \"images/building_icon_clone.png\", \r\n\t\t\t\t\t\t \"images/building_tab_clone.png\", \r\n\t\t\t\t\t\t \"images/building_tab_clone_hover.png\",\r\n\t\t\t\t\t\t 0,\r\n\t\t\t\t\t\t 24);\r\n\t\t\t\t\t\t\t\r\n\tclone.stats[\"Total Clones\"] = 0;\r\n\t\r\n\tvar epiphany = new Building(\"Epiphany\",\r\n\t\t\t\t\t\t \"Epiphany Center\", \r\n\t\t\t\t\t\t \"epiphany_center\",\r\n\t\t\t\t\t\t \"Periodically triples the production of a random tier 1 or tier 2 building for a short time.\",\r\n\t\t\t\t\t\t \"Once every 5 minutes triples the production of a random tier 1 or tier 2 building for 30 seconds. Base production is \" + tweaker.general.tier_3_base_multiplier + \"x the greatest base production of all tier 1 or tier 2 buildings increased by 0.2% per the maximum number of one building owned.\",\r\n\t\t\t\t\t\t 83330000000000000000000000000, //Cost 83.33 Octillion\r\n\t\t\t\t\t\t 0, //0 Trillion Production\r\n\t\t\t\t\t\t 3,\r\n\t\t\t\t\t\t [167, 168, 169, 170, 171, 172],\r\n\t\t\t\t\t\t \"images/building_icon_epiphany.png\", \r\n\t\t\t\t\t\t \"images/building_tab_epiphany.png\", \r\n\t\t\t\t\t\t \"images/building_tab_epiphany_hover.png\",\r\n\t\t\t\t\t\t 0,\r\n\t\t\t\t\t\t 25);\r\n\t\t\t\t\t\t\t\r\n\tepiphany.stats[\"Total Epiphanies\"] = 0;\t\r\n\t\r\n\tvar merchant = new Building(\"Merchant\",\r\n\t\t\t\t\t\t \"Merchant\", \r\n\t\t\t\t\t\t \"merchant\",\r\n\t\t\t\t\t\t \"Periodically advances a random tier one or tier two building forward 10 minutes.\",\r\n\t\t\t\t\t\t \"Once every 5 minutes advances a random tier one or tier two building forward 10 minutes.\",\r\n\t\t\t\t\t\t 83330000000000000000000000000, //Cost 83.33 Octillion\r\n\t\t\t\t\t\t 0, //0 Trillion Production\r\n\t\t\t\t\t\t 3,\r\n\t\t\t\t\t\t [167, 168, 169, 170, 171, 172],\r\n\t\t\t\t\t\t \"images/building_icon_trading.png\", \r\n\t\t\t\t\t\t \"images/building_tab_trading.png\", \r\n\t\t\t\t\t\t \"images/building_tab_trading_hover.png\",\r\n\t\t\t\t\t\t 0,\r\n\t\t\t\t\t\t 26);\r\n\t\t\t\t\t\t\t\r\n\tmerchant.stats[\"Total Packages\"] = 0;\r\n\t\r\n\tvar warp = new Building(\"Warp\",\r\n\t\t\t\t\t\t \"Warp Facility\", \r\n\t\t\t\t\t\t \"warp_facility\",\r\n\t\t\t\t\t\t \"Warp facilities grant the ability to grant a small time-frame worth of production periodically.\",\r\n\t\t\t\t\t\t \"Warp facilities grant the ability to grant a small time-frame worth of production periodically. Base production is \" + tweaker.general.tier_3_base_multiplier + \"x the greatest base production of all tier 1 or tier 2 buildings increased by 0.2% per the maximum number of one building owned.\",\r\n\t\t\t\t\t\t 83330000000000000000000000000, //Cost 83.33 Octillion\r\n\t\t\t\t\t\t 0, //0 Trillion Production\r\n\t\t\t\t\t\t 3,\r\n\t\t\t\t\t\t [107, 108, 109, 110, 111, 112],\r\n\t\t\t\t\t\t \"images/building_icon_warp.png\", \r\n\t\t\t\t\t\t \"images/building_tab_warp.png\", \r\n\t\t\t\t\t\t \"images/building_tab_warp_hover.png\",\r\n\t\t\t\t\t\t 0,\r\n\t\t\t\t\t\t 27);\r\n\t\r\n\twarp.stats[\"Total Warps\"] = 0;\t\r\n\t\r\n\tvar stellar = new Building(\"Stellar\",\r\n\t\t\t\t\t\t \"Stellar Factory\", \r\n\t\t\t\t\t\t \"stellar_factory\",\r\n\t\t\t\t\t\t \"Stellar Factories&apos; production will not decrease, even when temporary bonuses wear off.\",\r\n\t\t\t\t\t\t \"Stellar Factories&apos; production will not decrease, even when temporary bonuses wear off. Base production is \" + tweaker.general.tier_3_base_multiplier + \"x the greatest base production of all tier 1 or tier 2 buildings increased by 0.2% per the maximum number of one building owned.\",\r\n\t\t\t\t\t\t 83330000000000000000000000000, //Cost 83.33 Octillion\r\n\t\t\t\t\t\t 0, //0 Trillion Production\r\n\t\t\t\t\t\t 3,\r\n\t\t\t\t\t\t [277, 278, 279, 280],\r\n\t\t\t\t\t\t \"images/building_icon_stellar.png\", \r\n\t\t\t\t\t\t \"images/building_tab_stellar.png\", \r\n\t\t\t\t\t\t \"images/building_tab_stellar_hover.png\",\r\n\t\t\t\t\t\t 0,\r\n\t\t\t\t\t\t 28);\t\r\n\t\t\t\t\t\t\t\r\n\tvar temporal = new Building(\"Temporal\",\r\n\t\t\t\t\t\t \"Temporal Research Lab\", \r\n\t\t\t\t\t\t \"temporal_research_lab\",\r\n\t\t\t\t\t\t \"Temporal Research Labs grants the ability to toggle various effects that effect the passage of time.\",\r\n\t\t\t\t\t\t \"Temporal Research Labs grants the ability to toggle various effects that effect the passage of time. Base production is \" + tweaker.general.tier_3_base_multiplier + \"x the greatest base production of all tier 1 or tier 2 buildings increased by 0.2% per the maximum number of one building owned.\",\r\n\t\t\t\t\t\t 83330000000000000000000000000, //Cost 83.33 Octillion\r\n\t\t\t\t\t\t 0, //0 Trillion Production\r\n\t\t\t\t\t\t 3,\r\n\t\t\t\t\t\t [281, 282, 283, 284, 285, 286, 287],\r\n\t\t\t\t\t\t \"images/building_icon_temporal.png\", \r\n\t\t\t\t\t\t \"images/building_tab_temporal.png\", \r\n\t\t\t\t\t\t \"images/building_tab_temporal_hover.png\",\r\n\t\t\t\t\t\t 0,\r\n\t\t\t\t\t\t 29);\t\r\n\t\t\t\t\t\t\t\r\n\tvar political = new Building(\"Political\",\r\n\t\t\t\t\t\t \"Political Center\", \r\n\t\t\t\t\t\t \"political_center\",\r\n\t\t\t\t\t\t \"Political centers grant the ability to periodically activate decrees that have a variety of effects.\",\r\n\t\t\t\t\t\t \"Political centers grant the ability to periodically activate decrees that have a variety of effects. Base production is \" + tweaker.general.tier_3_base_multiplier + \"x the greatest base production of all tier 1 or tier 2 buildings increased by 0.2% per the maximum number of one building owned.\",\r\n\t\t\t\t\t\t 83330000000000000000000000000, //Cost 83.33 Octillion\r\n\t\t\t\t\t\t 0, //0 Trillion Production\r\n\t\t\t\t\t\t 3,\r\n\t\t\t\t\t\t [],\r\n\t\t\t\t\t\t \"images/building_icon_political.png\", \r\n\t\t\t\t\t\t \"images/building_tab_political.png\", \r\n\t\t\t\t\t\t \"images/building_tab_political_hover.png\",\r\n\t\t\t\t\t\t 0,\r\n\t\t\t\t\t\t 30);\r\n\t\t\t\t\t\t\t \r\n buildings.push(cultist);\r\n\tbuildings.push(mine);\r\n buildings.push(gambler);\r\n buildings.push(power);\r\n buildings.push(bank);\r\n buildings.push(research);\r\n buildings.push(factory);\r\n buildings.push(bonus);\r\n buildings.push(click);\r\n buildings.push(cryogenic);\r\n buildings.push(alien);\r\n buildings.push(computer);\r\n buildings.push(acceleration);\r\n buildings.push(fluctuation);\r\n buildings.push(clone);\r\n buildings.push(epiphany);\r\n buildings.push(merchant);\r\n buildings.push(warp);\r\n buildings.push(stellar);\r\n buildings.push(temporal);\r\n buildings.push(political);\r\n}", "function createBuilding(buildingType, _xPos, _yPos) {\n // Check what kind of building was given in the parameter\n switch (buildingType) {\n case 1:\n let tower1 = new TowerDefenseGame.Building(1, new ƒ.Vector3(0, 0, 0), 2, 10, 1.5);\n TowerDefenseGame.fields[_xPos][_yPos].getComponent(ƒ.ComponentMaterial).material = createMat(\"DodgerBlue\");\n lastBlockColor = createMat(\"DodgerBlue\");\n TowerDefenseGame.fields[_xPos][_yPos].appendChild(tower1);\n break;\n case 2:\n let tower2 = new TowerDefenseGame.Building(2, new ƒ.Vector3(0, 0, 0), 30, 0.5, 3);\n TowerDefenseGame.fields[_xPos][_yPos].getComponent(ƒ.ComponentMaterial).material = createMat(\"Crimson\");\n lastBlockColor = createMat(\"Crimson\");\n TowerDefenseGame.fields[_xPos][_yPos].appendChild(tower2);\n break;\n case 3:\n let tower3 = new TowerDefenseGame.Building(3, new ƒ.Vector3(0, 0, 0), 0, 1, 4);\n TowerDefenseGame.fields[_xPos][_yPos].getComponent(ƒ.ComponentMaterial).material = createMat(\"Lime\");\n lastBlockColor = createMat(\"Lime\");\n TowerDefenseGame.fields[_xPos][_yPos].appendChild(tower3);\n break;\n case 4:\n let tower4 = new TowerDefenseGame.Building(4, new ƒ.Vector3(0, 0, 0), 0, 1, 4);\n TowerDefenseGame.fields[_xPos][_yPos].getComponent(ƒ.ComponentMaterial).material = createMat(\"Fuchsia\");\n lastBlockColor = createMat(\"Fuchsia\");\n TowerDefenseGame.fields[_xPos][_yPos].appendChild(tower4);\n break;\n case 5:\n let buildRessource1 = new TowerDefenseGame.Building(5, new ƒ.Vector3(0, 0, 0), 0, 0, 0);\n TowerDefenseGame.fields[_xPos][_yPos].getComponent(ƒ.ComponentMaterial).material = createMat(\"GoldenRod\");\n lastBlockColor = createMat(\"GoldenRod\");\n TowerDefenseGame.fields[_xPos][_yPos].appendChild(buildRessource1);\n depots++;\n break;\n case 6:\n let buildRessource2 = new TowerDefenseGame.Building(6, new ƒ.Vector3(0, 0, 0), 0, 0, 0);\n TowerDefenseGame.fields[_xPos][_yPos].getComponent(ƒ.ComponentMaterial).material = createMat(\"DarkOrange\");\n lastBlockColor = createMat(\"DarkOrange\");\n TowerDefenseGame.fields[_xPos][_yPos].appendChild(buildRessource2);\n tradecenters++;\n break;\n case 7:\n let buildScience1 = new TowerDefenseGame.Building(7, new ƒ.Vector3(0, 0, 0), 0, 0, 0);\n TowerDefenseGame.fields[_xPos][_yPos].getComponent(ƒ.ComponentMaterial).material = createMat(\"DarkSlateGray\");\n lastBlockColor = createMat(\"DarkSlateGray\");\n TowerDefenseGame.fields[_xPos][_yPos].appendChild(buildScience1);\n science1exists = true;\n break;\n case 8:\n let buildScience2 = new TowerDefenseGame.Building(8, new ƒ.Vector3(0, 0, 0), 0, 0, 0);\n TowerDefenseGame.fields[_xPos][_yPos].getComponent(ƒ.ComponentMaterial).material = createMat(\"Indigo \");\n lastBlockColor = createMat(\"Indigo \");\n TowerDefenseGame.fields[_xPos][_yPos].appendChild(buildScience2);\n science2exists = true;\n break;\n default:\n break;\n }\n TowerDefenseGame.viewport.getGraph().removeChild(attackRangeObj);\n }", "function building6() {\n fill(12, 81, 91);\n noStroke();\n rect(600, 20, 100, 330);\n //use a nested for loop to draw many windows\n for (i = 620; i <= 670; i += 20) {\n for (j = 40; j <= 350; j += 20) {\n drawWindows6(i, j);\n }\n }\n}", "build() {\r\n for (let y = this.y; y < height; y += height / 20) {\r\n for (let x = this.x; x < 400; x += 400 / 10) {\r\n let boxUsed = false;\r\n let col = 255;\r\n this.gameMap.push({\r\n x,\r\n y,\r\n boxUsed,\r\n col\r\n });\r\n // Visualize the grid\r\n rect(x, y, 40, 40);\r\n }\r\n }\r\n }", "function Building(buildingType) {\n this.buildingType = buildingType;\n\n this.plot = new Plot(this.buildingType.avgPlotSize);\n this.minPlotPortion = this.plot.area * 0.5; // Probably these should come from BuildingType at some point\n this.maxPlotPortion = this.plot.area * 0.7;\n this.plotSnap = this.buildingType.plotSnap;\n this.roomSnap = this.buildingType.roomSnap;\n this.cyclingPrivacy = this.buildingType.cyclingPrivacy;\n this.cyclingChance = this.buildingType.cyclingChance;\n this.area = 0;\n this.roomTypes = this.buildingType.roomTypes;\n // RULES\n this.roomChoiceRules = this.buildingType.roomChoiceRules;\n this.connectivityRules = this.buildingType.connectivityRules;\n this.connectivityRulesUpstairs = this.buildingType.connectivityRulesUpstairs;\n this.placeFirstRoom = this.buildingType.placeFirstRoom;\n this.addOutsideDoorsToYards = this.buildingType.addOutsideDoors;\n this.fillSmallGaps = this.buildingType.fillSmallGaps;\n this.finalRules = this.buildingType.finalRules;\n this.protoRooms = [];\n this.floors = [new RoomList()];\n this.floorOutlines = [];\n this.roomList = this.floors[0];\n this.allRooms = new RoomList();\n //this.entry;\n this.doors = [];\n this.draw = true;\n this.doorSpace = this.buildingType.doorSpace;\n this.maxFloors = this.buildingType.maxFloors;\n this.numFloors = 1;\n this.selectedFloor = 1;\n}", "function Building (\n positionX, positionY, widthPx, heightPx, colour, windows) {\n\n this.positionX = positionX;\n this.positionY = positionY;\n this.widthPx = widthPx;\n this.heightPx = heightPx;\n this.fillColour = colour;\n this.windows = windows;\n}", "function render() {\n background.removeAllChildren();\n\n // TODO: 2 - Part 2\n // this fills the background with a obnoxious yellow\n // you should modify this to suit your game\n var backgroundFill = draw.rect(canvasWidth, canvasHeight, \"gray\");\n background.addChild(backgroundFill);\n\n // TODO: 3 - Add a moon and starfield\n var earth = draw.bitmap('img/earth_PNG39.png');\n earth.x = canvasHeight;\n earth.y = 30;\n earth.scaleX = 0.2;\n earth.scaleY = 0.2;\n background.addChild(earth);\n\n var moon = draw.bitmap('img/moon.png');\n moon.x = -500;\n moon.y= groundY + 70;\n moon.scaleX = 4;\n moon.scaleY = 2.6;\n background.addChild(moon);\n \n for (var i = 0; i < 100; i++) {\n var circle = draw.circle(10, 'white', 'LightGray', 2);\n circle.x = canvasWidth * Math.random();\n circle.y = groundY * Math.random();\n background.addChild(circle);\n }\n\n // TODO 5: Part 1 - Add buildings! Q: This is before TODO 4 for a reason! Why?\n for (var i = 0; i < 5; ++i) {\n var buildingHeight = Math.random() * 300;\n var building = draw.rect(75, buildingHeight, 'LightGray', 'Black', 1);\n building.x = 200 * i;\n building.y = groundY - buildingHeight;\n background.addChild(building);\n randomnum.push(Math.random());\n buildings.push(building);\n }\n\n // TODO 4: Part 1 - Add a tree\n\n flag.x = 0;\n flag.y = groundY-200;\n background.addChild(flag);\n\n\n\n\n } // end of render function - DO NOT DELETE", "generateBuildings(width, height) {\n let all = []\n\n for(let i = 0; i < 40; i++) {\n let building = new Building()\n building.x = Utils.random(- width / 2, width / 2)\n building.height = Utils.random(height / 8, height / 4)\n building.width = Utils.random(10, 100)\n building.y = - height / 2 // height / 2 - building.height\n all.push(building)\n }\n\n for(let i = 0; i < 10; i++) {\n let building = new Building()\n building.x = Utils.random(- width / 2, width / 2)\n building.height = Utils.random(height / 4, height * 0.75)\n building.width = Utils.random(40, 100)\n building.y = - height / 2 // height / 2 - building.height\n all.push(building)\n }\n\n return all\n }", "function createBuildings() {\n buildings = [];\n let buildingA = new Building(\"A\");\n let buildingB = new Building(\"B\");\n let buildingC = new Building(\"C\");\n let buildingD = new Building(\"D\");\n let buildingE = new Building(\"E\");\n\n buildings.push(buildingA,buildingB,\n buildingC,buildingD,buildingE);\n}", "function drawHouses() {\n \n for (var h=0; h < houseXs.length; h++) {\n y = floorPos_y;\n x = houseXs[h];\n \n \n fill(200,150,50);\n noStroke();\n rect(x,y-90,120,90); //house\n fill(220,50,0);\n quad(x-20,y-80,x+30,y-130,x+90,y-130,x+140,y-80); //roof\n \n fill(0,50,100);\n stroke(140,69,19);\n strokeWeight(2);\n rect(x+60,y-50,30,50); //door\n \n point(x+85,y-30); // door handle\n \n fill(180,180,0);\n stroke(0,0,100);\n rect(x+15,y-60,25,25); // window\n \n stroke(0,0,100);\n line(x+27,y-60,x+27,y-35)\n line(x+15,y-47,x+40,y-47); //window frame\n \n}\n\n}", "function buildingstab(building) {\n $('#zonebuildings').empty()\n .append(\"<div class='buildingdivwrapper2' id='0buildingwrap'>BUILDINGS</div>\");\n for (x in building) {\n var wrap = x + \"buildingwrap\";\n var parentid = building[x].buildingsRequired + \"buildingwrap\";\n $(\"#\" + parentid).after(\"<div class='buildingdivwrapper' id='\" + wrap + \"'></div>\");\n var itemimage = \"\";\n if (building[x].isBuilt === false) {\n var counter = 0;\n for (material in building[x].itemsRequired) {\n counter++;\n }\n var ident2 = \"\";\n for (i = 0; i < (2 + counter); i++) {\n var buildinfo = \"\";\n var itemused = \"\";\n var itemcount = \"\";\n var innerwriting = \"\";\n var create = true;\n var getitem = 2;\n if (i > 1) {\n for (material in building[x].itemsRequired) {\n if (getitem === i) {\n getitem = material;\n break;\n } else {\n getitem++;\n }\n }\n }\n switch (i) {\n case 0:\n buildinfo = \"text\";\n innerwriting = building[x].name;\n itemimage = \"/images/buildings/\"+building[x].icon;\n create = true;\n break;\n case 1:\n ident2 = x + \"button\";\n $(\"#\" + wrap).append(\"<button class='buildingbutton' id='\" + ident2 + \"' onclick='buildingclick(this.id)'></button>\");\n buildinfo = \"stamina\";\n innerwriting = building[x].staminaSpent + \"/\" + building[x].staminaRequired;\n itemimage = \"/images/stamina2.png\";\n create = true;\n break;\n default:\n buildinfo = \"matt\";\n itemused = building[x].itemsRequired[getitem];\n innerwriting = itemused.materialOwned + \"/\" + itemused.materialNeeded;\n itemimage = \"/images/items/\" + itemused.icon;\n create = true;\n break;\n }\n var ident3 = x + buildinfo;\n if (building[x].buildingsRequired != 0 && buildinfo == \"text\") {\n var paddLeft = $(\"#\"+parentid).css(\"padding-left\");\n paddLeft = parseInt(paddLeft.slice(0,paddLeft.length -2))+15;\n $(\"#\" + wrap).append(\"<div class='building\" + buildinfo + \"' id='\" + ident3 + \"'>&nbsp|---&nbsp<img src='\" + itemimage + \"' class='buildingimages'>\" + innerwriting + \"</div>\")\n .css({paddingLeft: paddLeft+\"px\"});\n $(\"#\"+ident3).css({width: (260-paddLeft)})\n } else {\n $(\"#\" + wrap).append(\"<div class='building\" + buildinfo + \"' id='\" + ident3 + \"'>&nbsp<img src='\" + itemimage + \"' class='buildingimages'>\" + innerwriting + \"</div>\");\n }\n if (buildinfo == \"text\"){\n $(\"#\"+ident3).append(\"<span class='buildingImageText'>\"+building[x].description+\"</span>\")\n }\n }\n var parentid = building[x].buildingsRequired;\n if (building[x].canBeBuilt === false) {\n $(\"#\" + wrap).css(\"background-image\", \"url('/images/unexplored.png')\");\n $(\"#\" + ident2).prop('disabled', true).css('background-color', 'lightgrey');\n } else if (parentid != 0) {\n if (building[parentid].isBuilt === false) {\n $(\"#\" + wrap).css(\"background-image\", \"url('/images/unexplored.png')\");\n $(\"#\" + ident2).prop('disabled', true).css('background-color', 'lightgrey');\n }\n }\n } else {\n var ident3 = x + \"built\";\n innerwriting = building[x].name;\n $(\"#\" + wrap).append(\"<div class='buildingbuilt' id='\" + ident3 + \"'><img src='/images/buildings/\" + building[x].icon + \"' class='buildingimages'>\" + building[x].name + \"&nbsp;&nbsp;---------Complete---------</div>\");\n $(\"#\" + ident3).css(\"background-image\", \"url('../images/builtbuilding.png')\")\n }\n }\n}", "function drawElements() {\n that.gameArea.paint(that.contex);\n that.food.paint(that.contex, that.gameArea.cellSize);\n that.snake.paint(that.contex, that.gameArea.cellSize);\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
add more items to the grid. the new items need to appended to the grid. after that call Grid.addItems(theItems);
function addItems($newitems) { $items = $items.add($newitems); $.each($newitems, function (i, v) { var $item = $(v); $item.data({ offsetTop: $item.offset().top, height: $item.height() }); }); initItemsEvents($newitems); }
[ "function addGridItems(grid) {}", "_addItems(newItems) {\n let items = newItems;\n // recompute last row before adding new items\n if (this.rows.length > 0) {\n // get last row items\n const lastRowItems = this.rows[this.rows.length - 1].map((item) => this.items[item._view.index]);\n // append last row items to `newItems` param\n items = lastRowItems.concat(items);\n // drop last row\n this.pop('rows');\n }\n this._computeRows(items).forEach((row) => this.push('rows', row));\n this.$.scrollThreshold.clearTriggers();\n }", "function addItems($newitems) {\n\n $items = $items.add($newitems);\n\n $newitems.each(function() {\n var $item = $(this);\n $item.data({\n offsetTop: $item.offset().top,\n height: $item.height()\n });\n });\n\n initItemsEvents($newitems);\n\n }", "function addItems($newitems) {\n $items = $items.add($newitems);\n\n $newitems.each(function() {\n var $item = $(this);\n $item.data({offsetTop: $item.offset().top, height: $item.height()});\n });\n\n initItemsEvents($newitems);\n }", "function addItems( $newitems ) {\n\n\t\t$items = $items.add( $newitems );\n\n\t\t$newitems.each( function() {\n\t\t\tvar $item = $( this );\n\t\t\t$item.data( {\n\t\t\t\toffsetTop : $item.offset().top,\n\t\t\t\theight : $item.height()\n\t\t\t} );\n\t\t} );\n\n\t\tinitItemsEvents( $newitems );\n\n\t}", "addItems(items) {\n this.isEditing ? this.editData.push(...items) : this.source.push(...items);\n this.onDataChange(new CollectionEvent(CollectionEvent.ADD, items));\n this.refresh();\n }", "function _append_more_items(){\n try{\n self.table_view.deleteRow(self.data.length-1,{\n animationStyle:Titanium.UI.iPhone.RowAnimationStyle.UP\n });\n self.data.pop();\n self.init_vars();\n _init_library_item(true); \n _append_data.push(_add_download_more_items());\n _update_last_row_text();\n self.table_view.appendRow(_append_data,{\n animationStyle:Titanium.UI.iPhone.RowAnimationStyle.UP\n });\n }catch(err){\n self.process_simple_error_message(err,window_source+' - _append_more_items');\n return;\n } \n }", "function addItems(oSidePanel, iCount) {\n\t\tvar iAdded = 0;\n\n\t\tif (!iCount) {\n\t\t\tiCount = aItems.length;\n\t\t}\n\t\tdo {\n\t\t\toSidePanel.addItem(new SidePanelItem({\n\t\t\t\ttext: aItems[iAdded].text,\n\t\t\t\ticon: aItems[iAdded].icon,\n\t\t\t\tenabled: aItems[iAdded].enabled\n\t\t\t}));\n\t\t\tiAdded++;\n\t\t} while (iAdded < iCount && iAdded < aItems.length);\n\t}", "function gridItemAdder(num) {\n for (let i = 0; i < num; i++) {\n addGridItem();\n }\n}", "function createItems() {\n for (var i = 0; i <= 5; i++) {\n gridWrapper.append('<div class=\"gallery_mars__item___hide\"></div>');\n }\n }", "function createRespsiveGridItems(cards, args) {\n\n //initailaizing layout \n createGridLayout();\n //Create grid Items\n createGridItems(cards, args);\n\n //Render again ...\n setTimeout(function() {\n gridLayout.render();\n // Moving the last element to avoid overlapping of cards\n }, 300);\n }", "function addAllItemsToUI (items) {\n if (!items.length) {\n listDiv.append('<p class=\"no-item\"> No items yet. Add one. </p>')\n return\n }\n\n items.forEach(function (item) {\n addItemToUI(item.doc)\n })\n }", "add(){\n\t\titems.push(this);\n\t}", "function addItemScreen() \n{\n\tvar numBulkItems = getNumTotalItem();\n\n\tvar trEls = document.getElementsByClassNameArray(\"hide\");\n\ttrEls[0].style.display = \"\";\n\ttrEls[0].className = \"show\" + trEls[0].className.substring(4);\n\n\t// set hiddenAdd property to TRUE so if submitted and an\n\t// error, this will be displayed\n\tvar hiddenAddEl = getHiddenAdd(trEls[0]);\t\t\n\thiddenAddEl.value = 'true';\n\t\n\t// make sure delete link on first item is displayed\n\tif (numBulkItems == 1) {\n\t\taddDelX();\n\t}\n\n\tif (numBulkItems == MAX_NEW_ITEMS - 1)\n\t\t$(\"gbForm:addSecond\").style.display = \"none\";\n\n\tsetMainFrameHeight(thisId, 'shrink');\n}", "function addMultipleItems(itemSelect)\n{\n\tif (document.all)\n\t\titemSelect = document.all[\"gbForm:numItems\"];\n\n\tvar numItems = parseInt(itemSelect.value);\n\tvar numBulkItems = getNumTotalItem();\n\n\tif (numItems > 0) {\n\t\t// since only 50 new items max, need to check so\n\t\t// we don't try to create more.\n \tif ((numBulkItems + numItems) <= MAX_NEW_ITEMS) {\n \t\tadjustSize = numItems;\n \t}\n \telse {\n\t\t\tadjustSize = MAX_NEW_ITEMS - numBulkItems;\n\t }\n\n\t\tfor (var i=0; i < adjustSize; i++) {\n\t\t\taddItemScreen();\n\t\t\tadjustNumBulkItems(1);\n\t\t}\n\t\t\n\t\t// since DOM changed, resize\n\t\tsetMainFrameHeight(thisId, 'grow');\n\n\t\titemSelect.selectedIndex = 0;\n\t}\n}", "_appendItems() {\n var rules = this.rruleSet._rrule;\n var items = [];\n\n $.each(rules, function(index, rrule) {\n var item = this._buildItem(rrule);\n items.push(item);\n }.bind(this));\n\n this.$grid.html(items);\n this._updateRuleSet();\n }", "function addItems( pckry, maxY, isRando ) {\n // stop after packery reaches height\n // console.log(pckry.maxY);\n if ( pckry.maxY > maxY ) {\n return;\n }\n var fragment = document.createDocumentFragment();\n var items = [];\n for ( var i=0; i < 4; i++ ) {\n var item = getItem( isRando );\n items.push( item );\n fragment.appendChild( item );\n // var draggie = new Draggabilly( item );\n // pckry.bindDraggabillyEvents( draggie );\n }\n\n pckry.element.appendChild( fragment );\n pckry.appended( items );\n // do it again\n setTimeout( function() {\n addItems( pckry, maxY, isRando );\n }, 40 );\n\n return items;\n\n}", "function onClickAddMoreWidgets(){\n\t\tcount++;\t\t\n\t\tfrmDynamicJS.hBoxOuterId.vBoxOuterId.add(hBoxMain());\n\t}", "_addAllGridsToGridHolder() {\n // needed when component is re-mounted when coming back from a different route \n const gridHolder = document.getElementById('gridHolder');\n for (let grid of this.props.items) {\n gridHolder.appendChild(grid); \n }\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Retrieve all events of specific Aggregate
async getAggregateEvents(aggregateId) { assert.ok(aggregateId, 'aggregateId') const snapshot = this.snapshotsSupported ? await this._snapshotStorage.getAggregateSnapshot(aggregateId) : undefined const events = await this._storage.getAggregateEvents(aggregateId, { snapshot }) return new EventStream(snapshot ? [snapshot, ...events] : events) }
[ "async getAll() {\n const db = await dbPromise;\n return db.transaction('events').objectStore('events').getAll();\n }", "function retrieveAllEvents() {\n dbPromise.then(function (db) {\n var tx = db.transaction(EVENT_OBJECT_STORE, 'readonly');\n var eventOS = tx.objectStore(EVENT_OBJECT_STORE);\n return eventOS.getAll();\n }).then(function (events) {\n displayEvents(events);\n });\n}", "async Events_all() {\n let uri = \"type=events&param=list\";\n return await this.domoticzCall(uri);\n }", "fetchAll(params) {\n return api\n .get('events', params)\n .then(response => ({ events: response.data, paging: response.paging }));\n }", "generateAggregateEventsArray() {\n return [\n // DRIVER\n {\n aggregateType: \"Driver\",\n eventType: \"DriverCreated\"\n },\n {\n aggregateType: \"Driver\",\n eventType: \"DriverGeneralInfoUpdated\"\n },\n {\n aggregateType: \"Driver\",\n eventType: \"DriverStateUpdated\"\n },\n {\n aggregateType: \"Driver\",\n eventType: \"DriverAuthCreated\"\n },\n {\n aggregateType: \"Driver\",\n eventType: \"DriverAuthDeleted\"\n },\n {\n aggregateType: \"Driver\",\n eventType: \"DriverBlockRemoved\"\n },\n {\n aggregateType: \"Driver\",\n eventType: \"DriverBlockAdded\"\n },\n\n // VEHICLE\n {\n aggregateType: \"Vehicle\",\n eventType: \"VehicleCreated\"\n },\n {\n aggregateType: \"Vehicle\",\n eventType: \"VehicleGeneralInfoUpdated\"\n },\n {\n aggregateType: \"Vehicle\",\n eventType: \"VehicleStateUpdated\"\n },\n {\n aggregateType: \"Vehicle\",\n eventType: \"VehicleFeaturesUpdated\"\n },\n {\n aggregateType: \"Driver\",\n eventType: \"VehicleAssigned\"\n },\n {\n aggregateType: \"Driver\",\n eventType: \"VehicleUnassigned\"\n },\n {\n aggregateType: \"Vehicle\",\n eventType: \"VehicleBlockRemoved\"\n },\n {\n aggregateType: \"Vehicle\",\n eventType: \"VehicleBlockAdded\"\n },\n {\n aggregateType: \"Vehicle\",\n eventType: \"VehicleSubscriptionTypeUpdated\"\n },\n // CLIENT\n {\n aggregateType: \"Client\",\n eventType: \"ClientSatelliteEnabled\"\n },\n {\n aggregateType: \"Client\",\n eventType: \"EndClientCreated\"\n },\n {\n aggregateType: \"Client\",\n eventType: \"ClientCreated\"\n },\n {\n aggregateType: \"Client\",\n eventType: \"ClientSatelliteIdUpdated\"\n },\n {\n aggregateType: \"Client\",\n eventType: \"DriverAssociatedToClient\"\n },\n {\n aggregateType: \"Client\",\n eventType: \"ClientSatelliteInfoUpdated\"\n },\n {\n aggregateType: \"Client\",\n eventType: \"ClientGeneralInfoUpdated\"\n },\n\n //SERVICE\n { aggregateType: \"Service\", eventType: \"ServiceRequested\" },\n { aggregateType: \"Service\", eventType: \"ServiceAssigned\" },\n { aggregateType: \"Service\", eventType: \"ServicePickUpETAReported\" },\n { aggregateType: \"Service\", eventType: \"ServiceLocationReported\" },\n { aggregateType: \"Service\", eventType: \"ServiceArrived\" },\n { aggregateType: \"Service\", eventType: \"ServicePassengerBoarded\" },\n { aggregateType: \"Service\", eventType: \"ServiceCompleted\" },\n { aggregateType: \"Service\", eventType: \"ServiceDropOffETAReported\" },\n { aggregateType: \"Service\", eventType: \"ServiceCancelledByDriver\" },\n { aggregateType: \"Service\", eventType: \"ServiceCancelledByClient\" },\n { aggregateType: \"Service\", eventType: \"ServiceCancelledByOperator\" },\n { aggregateType: \"Service\", eventType: \"ServiceClosed\" },\n // SHIFT\n { aggregateType: \"Shift\", eventType: \"ShiftLocationReported\" },\n // Cronjob\n { aggregateType: \"Cronjob\", eventType: \"PeriodicOneMinute\" },\n { aggregateType: \"Cronjob\", eventType: \"PeriodicFiveMinutes\" },\n { aggregateType: \"Cronjob\", eventType: \"PeriodicFifteenMinutes\" },\n { aggregateType: \"Cronjob\", eventType: \"PeriodicMonthly\" },\n // // Wallet\n // { aggregateType: \"Wallet\", eventType: \"WalletUpdated\" },\n // BUSINESS\n {\n aggregateType: \"Business\",\n eventType: \"BusinessGeneralInfoUpdated\"\n },\n ]\n }", "function getAllEvents() {\n var request = gapi.client.calendar.events.list({\n 'calendarId': CALENDAR_ID,\n 'timeMin': (new Date(2016, 1, 4)).toISOString(),\n// 'timeMin': (new Date()).toISOString(),\n 'showDeleted': false,\n 'singleEvents': true,\n 'maxResults': 100,\n 'orderBy': 'startTime'\n });\n return request;\n }", "static async getAll(organiserID) {\n const eventData = await this.request.get(eventsURL, {\n organiserId: organiserID\n });\n\n /* Fetch regions and inject them into the event objects. */\n const eventDataWithRegions = eventData.map(this._injectRegions);\n\n /* Resolve promises array and convert array of Events into an\n * object keyed by eventID. */\n return Promise.all(eventDataWithRegions).then(eventData =>\n _.keyBy(eventData, \"eventID\")\n );\n }", "function findAllGroupEvents(group_name) {\n var groupEventsRef = db.collection(\"group_events\");\n var eventList = [];\n var query = groupEventsRef\n .where(\"groupName\", \"==\", group_name)\n .get()\n .then(snapshot => {\n if (snapshot.empty) {\n console.log(\"No matching documents.\");\n return;\n }\n\n snapshot.forEach(doc => {\n // console.log(doc.id, '=>', doc.data());\n var event = findEvent(doc.data().eventName);\n console.log(event);\n eventList.push(event);\n });\n })\n .catch(err => {\n console.log(\"Error getting documents\", err);\n });\n return { groupName: group_name, elements: eventList };\n}", "async getAllActiveEvents() {\n const events = Event.find({ active: true }, () => {});\n return events;\n }", "async function eventHubsListAll() {\n const subscriptionId =\n process.env[\"EVENTHUB_SUBSCRIPTION_ID\"] || \"e2f361f0-3b27-4503-a9cc-21cfba380093\";\n const resourceGroupName =\n process.env[\"EVENTHUB_RESOURCE_GROUP\"] || \"Default-NotificationHubs-AustraliaEast\";\n const namespaceName = \"sdk-Namespace-5357\";\n const credential = new DefaultAzureCredential();\n const client = new EventHubManagementClient(credential, subscriptionId);\n const resArray = new Array();\n for await (let item of client.eventHubs.listByNamespace(resourceGroupName, namespaceName)) {\n resArray.push(item);\n }\n console.log(resArray);\n}", "async function getEvents(firestore = db) {\n return firestore.collection(\"Events\").get()\n .then((snapshot) => {\n if (!snapshot.empty) {\n const ret = { events: [] };\n snapshot.docs.forEach(element => {\n //get data\n const el = element.data();\n //get internal firestore id\n el._id = element.id;\n //add object to array\n ret.events.push(el);\n }, this);\n return ret;\n } \n // if no data has yet been added to firestore, return mock data\n return mockEvents;\n })\n .catch((err) => {\n console.error('Error getting events', err);\n return mockEvents;\n });\n}", "async function getAllEvents() {\n const provider = new providers.JsonRpcProvider(rpcEndpoint);\n // Get an interface to the Gatekeeper contract\n const gatekeeper = new Contract(gatekeeperAddress, Gatekeeper.abi, provider);\n const tokenCapacitor = new Contract(tokenCapacitorAddress, TokenCapacitor.abi, provider);\n\n // TEMPORARY WORKAROUND: prevent app from crashing on rinkeby network\n const network = await provider.getNetwork();\n if (network.chainId === 4) {\n return [];\n }\n\n const currentBlockNumber = await provider.getBlockNumber();\n console.log('currentBlockNumber:', currentBlockNumber);\n\n const blocksRange = range(genesisBlockNumber, currentBlockNumber + 1);\n\n const events = await Promise.all(\n blocksRange.map(async blockNumber => {\n const block = await provider.getBlock(blockNumber, true);\n const logsInBlock = await getLogsInBlock(block, provider, gatekeeper, tokenCapacitor);\n // [[Log, Log]] -> [Log, Log]\n // [[]] -> []\n return flatten(logsInBlock);\n })\n );\n\n // [[], [], [Log, Log]] -> [Log, Log]\n return flatten(events);\n}", "function getAllSingleEvents() {\n //using mongoose to get all single events\n return SingleEventCollection.find();\n}", "function getHostingEvents() {\n var filter = \"?filter[where][AccountId]=\" + $scope.userInfo.userId + \"&filter[include]=account\";\n httpService.getData('Events', filter, '')\n .then(function (data) {\n $scope.hostingEventList = data;\n sortAccordingtoDate();\n },\n function (err) {\n console.log(err);\n });\n }", "async readEvtContact(eventid) {\n let events = [];\n let collection = await this.collection();\n await collection.find({ eventid: ObjectId(eventid) }).forEach((event) => {\n events.push(event);\n });\n\n return events;\n }", "function getAllEvents() {\n var apiUrl = '/users/' + user.login + '/events';\n return Q.ninvoke(github.client(user.token), 'get', apiUrl, page)\n .spread(function (status, events, header) {\n concatArray(results, events);\n\n var link = header.link;\n // if has next page\n if (~link.indexOf('rel=\"next\"')) {\n page++;\n return getAllEvents();\n } else {\n return results;\n }\n });\n }", "getAggregateQueries(){\n var result = [];\n var queries = this.getRelevantQueries();\n for (var i = 0; i < queries.length; i++){\n if (queries[i].aggregate){\n result.push(queries[i]);\n }\n }\n return result;\n }", "function getEvents(){\n self.events = eventsService.getEvents();\n }", "function get_events(cb) {\n\tpool.query(\"SELECT * FROM EVENTS ORDER BY DATE DESC\", (err, res) => {\n\t\tif (err) return cb([]);\n\t\tcb(res.rows);\n\t})\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Loads all trails and sets them to trails
function loadTrails() { API.getTrails() .then(res => { // console.log(res.data.trails); setTrails(res.data.trails); }) .catch(err => console.log(err)); }
[ "function loadTrades() {\n API.getTrades(userId)\n .then((res) => {\n let tradeArr = [];\n\n for (let i = 0; i < res.data.length; i++) {\n for (let j = 0; j < res.data[i].trades.length; j++) {\n let tradeLoop = res.data[i].trades[j];\n // console.log(tradeLoop)\n if (tradeLoop) {\n tradeLoop.name = res.data[i].name;\n tradeArr.push(tradeLoop);\n }\n }\n }\n setTradeDataState(tradeArr);\n })\n .catch((err) => console.log(err));\n }", "async function fetchTrails() {\n const results = await fetch(\"http://localhost:8000/api/trails/?featured=true\");\n const trails = await results.json();\n setTrails(trails);\n }", "function populateAllTrainers() {\n\tvar trainers = getAllTrainers();\n\tpopulateTrainerTable(trainers);\n}", "loadTiles (Tiles) {\n for (let key in Tiles) {\n this.Tiles[key] = Tiles[key];\n }\n }", "function loadTrails (fileName) {\r\n trailTable = new Array ();\r\n try {\r\n var trailFile = openFile (fileName);\r\n if (!trailFile.exists()) createFile (trailFile);\r\n var lis = getLineInputStream (trailFile);\r\n var line = {}, hasMore;\r\n\r\n do {\r\n hasMore = lis.readLine (line);\r\n if (!hasMore && line.value.length == 0) break;\r\n\r\n if (line.value.indexOf (\"<trail\") == 0) trailTable.push (readTrail (lis));\r\n trailTable[trailTable.length - 1].id = trailTable.length - 1;\r\n } while (true);\t\r\n showStatus (\"[trailmann.loadTrails] Number of trails loaded: \" + trailTable.length);\r\n\t\t\r\n } catch (ex) {\r\n showStatus (\"[trailman.loadTrails] \" + ex.message);\r\n }\r\n}", "function loadTraders() {\n \"use strict\";\n let traders = $(\".traders\");\n traders.html(\"\");\n for (let trader of g.player.location.traders) {\n if (trader.isVisible()) addTrader(trader);\n }\n}", "function loadtrains() {\n firebase.database().ref().remove();\n traininfo = train1;\n firebase.database().ref().push({ traininfo });\n traininfo = train2;\n firebase.database().ref().push({ traininfo });\n traininfo = train3;\n firebase.database().ref().push({ traininfo });\n traininfo = train4;\n firebase.database().ref().push({ traininfo });\n }", "getTrains() {\n\t\tthis.getData()\n\t\t\t.then((schedule) => {\n\t\t\t\tif (schedule) {\n\t\t\t\t\tlet trains = [];\n\n\t\t\t\t\tfor (d in schedule.departures) {\n\t\t\t\t\t\tlet arrival = schedule.arrivals ? schedule.arrivals.find((arr) => arr.train_uid === schedule.departures[d].train_uid) : null;\n\t\t\t\t\t\tlet train = new Train(schedule.departures[d], arrival);\n\t\t\t\t\t\ttrains.push(train);\n\t\t\t\t\t}\n\n\t\t\t\t\t// Trim the list of trains to (at most) the maximum set in config\n\t\t\t\t\tthis.trains = trains.slice(0, Math.min(trains.length, this.config.maxTrains));\n\n\t\t\t\t\t// Set time of last successful update\n\t\t\t\t\tthis.lastUpdated = moment();\n\n\t\t\t\t\t// Show in log if enabled\n\t\t\t\t\tif (this.config.logData) Log.info(\"Trains updated:\", this.trains);\n\t\t\t\t}\n\t\t\t})\n\t\t\t.catch((error) => {\n\t\t\t\tLog.error(\"Error updating trains: \", error);\n\t\t\t})\n\t\t\t.finally(() => {\n\t\t\t\t// Refresh module display\n\t\t\t\tthis.updateDom();\n\n\t\t\t\t// Schedule next update\n\t\t\t\tsetTimeout(() => {\n\t\t\t\t\tthis.getTrains();\n\t\t\t\t}, this.config.updateInterval);\n\t\t\t});\n\t}", "function loadTrains() {\n\n\tfor (var i = 0; i < localArray.length; i++) {\n\n\t\tvar newData = $('<tr>');\n\n\t\tnewData.attr('data-index', [i]);\n\t\tnewData.append(\"<td>\"+localArray[i].name);\n\t\tnewData.append(\"<td>\"+localArray[i].dest);\n\t\tnewData.append(\"<td>\"+localArray[i].time);\n\t\t// newData.append(\"<td>\"+localArray[i].freq);\n\t\tnewData.append(\"<td>\"+localArray[i].remain);\n\n\t\t$('tbody').append(newData);\n\t}\n\n\tvar homePage = \"https://fredlintz5.github.io/trainScheduler/\";\n\n\t// hide remove buttons on consumer screen\n\tif (window.location.href == homePage) {\n\t\t$('tr > button').toggleClass('hide');\n\t}\n}", "loadAll() {\n this._loadAllTiles();\n }", "function getTrainees() {\n\t\t\t//for each batch, add the trainees to an overall list of trainees\n\t\t\tallBatches.forEach(function (batch) {\n\t\t\t\tbatch.trainees.forEach(function (trainee) {\n\t\t\t\t\t$scope.allTrainees.push(trainee);\n\t\t\t\t});\n\t\t\t});\n\t\t}", "function loadFlights() {\n\tfor (let x = 0; x < flights.getRowCount(); x++){\n\t\tflightObjects[x] = new Flight(\n\t\t\t// Here we map the latitude and longitude\n\t\t\t// to stay within the canvas\n\t\t\tmap(flights.getColumn(\"from_lon\")[x],\n\t\t\t\t-180,180,0,width),\n\t\t\tmap(flights.getColumn(\"from_lat\")[x],\n\t\t\t\t-10,70,height,0),\n\t\t\tmap(flights.getColumn(\"to_lon\")[x],\n\t\t\t\t-180,180,0,width),\n\t\t\tmap(flights.getColumn(\"to_lat\")[x],\n\t\t\t\t-10,70,height,0),\n\t\t\tflights.getColumn(\"from_name\")[x],\n\t\t\tflights.getColumn(\"to_name\")[x],\n\t\t\tflights.getColumn(\"year\")[x]);\n\t}\n}", "function initSavedTalents(talents) {\n savedTalents = talents;\n }", "loadTweets() {\n let tweets = store.getData( this._tweetsKey );\n if ( !Array.isArray( tweets ) || !tweets.length ) return;\n this._tweets = tweets;\n this.resetTweets();\n this.filterTweets();\n this.saveTweets();\n }", "function loadTrainers() {\n fetch(TRAINERS_URL)\n .then(res => res.json())\n .then(json => json.forEach(trainer => displayTrainer(trainer)))\n}", "function getTrails(){\n vm.loading = true;\n TrailClient\n .getTrails(vm.search)\n .then(function(response){\n vm.searchResults = response.data.places;\n vm.loading = false;\n })\n }", "initAll() {\n\t\tangular.forEach(this.selectedFlights, (flight) => {\n\t\t\tthis.initFlight(flight);\n\t\t});\n\t}", "function load_trainers(){ //Load the trainer list to the trainer object\n\tvar trainers = require(\"./prof_walnut/trainers.json\");\n}", "function loadTraders() {\n \"use strict\";\n\n var traders = $(\".traders\");\n traders.html(\"\");\n var _iteratorNormalCompletion5 = true;\n var _didIteratorError5 = false;\n var _iteratorError5 = undefined;\n\n try {\n for (var _iterator5 = g.player.location.traders[Symbol.iterator](), _step5; !(_iteratorNormalCompletion5 = (_step5 = _iterator5.next()).done); _iteratorNormalCompletion5 = true) {\n var trader = _step5.value;\n\n if (trader.isVisible()) addTrader(trader);\n }\n } catch (err) {\n _didIteratorError5 = true;\n _iteratorError5 = err;\n } finally {\n try {\n if (!_iteratorNormalCompletion5 && _iterator5.return) {\n _iterator5.return();\n }\n } finally {\n if (_didIteratorError5) {\n throw _iteratorError5;\n }\n }\n }\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
manufacturer, model, price quality, hasMicrophone boolean
constructor(manufacturer, model, price, quality, hasMicrophone) { super(manufacturer, model, price); this.quality = quality; //TODO what is this._hasMicrophone = Boolean(hasMicrophone); }
[ "manufacturer() {\n return _.sample(HARDWARE.MANUFACTURERS);\n }", "function DetectSmartphone()\n {\n if (DetectIphoneOrIpod())\n return true;\n if (DetectS60OssBrowser())\n return true;\n if (DetectSymbianOS())\n return true;\n if (DetectWindowsMobile())\n return true;\n if (DetectAndroid())\n return true;\n if (DetectBlackBerry())\n return true;\n if (DetectPalmWebOS())\n return true;\n if (DetectPalmOS())\n return true;\n if (DetectGarminNuvifone())\n return true;\n\n //Otherwise, return false.\n return false;\n }", "function get_battery_support(){\n\t\t\n\t\tif(battery){\n\t\t\tbattery_support = true;\n\t\t}else{\n\t\t\tbattery_support = false;\n\t\t}\n\t}", "function DetectSmartphone()\n{\n if (DetectIphoneOrIpod())\n return true;\n if (DetectS60OssBrowser())\n return true;\n if (DetectSymbianOS())\n return true;\n if (DetectWindowsMobile())\n return true;\n if (DetectWindowsPhone7())\n return true;\n if (DetectAndroid())\n return true;\n if (DetectBlackBerry())\n return true;\n if (DetectPalmWebOS())\n return true;\n if (DetectPalmOS())\n return true;\n if (DetectGarminNuvifone())\n return true;\n\n //Otherwise, return false.\n return false;\n}", "Nokia ():boolean {\n\n\t\treturn this.agent.match(/Nokia/i) ? true : false;\n\t}", "isValidBrand() {\n return this.brand.isValidBrand();\n }", "function Make () {\n this.manufacturer = \"\";\n}", "isUsable() {\r\n return this._obj.title && this._obj.lyrics && this._obj.album && this._obj.artist;\r\n }", "rule_Usb_Comms_Capable(component) {\n let vifProductType = component.parent.getElementByName(VIF_ENUMS.VIF_Product_Type);\n let pdPortType = component.getElementByName(VIF_ENUMS.PD_Port_Type);\n if (vifProductType.getSelectedIndex() === 1 || pdPortType.getSelectedIndex() === 5) {\n return true;\n }\n return false;\n }", "get isCellularDevice() {\n return true;\n }", "function isSmartphone() {\n var returnBool = false;\n if( /Android/i.test(navigator.userAgent) && window.devicePixelRatio > 1) {\n var w = $(window).width() / window.devicePixelRatio;\n console.log(\"Android device >> ratio'd width: \" + w);\n if (w < 480) {\n returnBool = true;\n }\n } else {\n returnBool = /Android|webOS|iPhone|iPod|BlackBerry|IEMobile|Opera Mini|Windows Mobile/i.test(navigator.userAgent)\n }\n\n return returnBool;\n}", "get manufacturer() {\n\t\treturn this.__manufacturer;\n\t}", "function Phone (args) {\n this.manufacturer = args.manufacturer;\n this.make = args.make;\n this.os = args.os;\n}", "function DetectSymbianOS()\n{\n if (uagent.search(deviceSymbian) > -1 ||\n uagent.search(deviceS60) > -1 ||\n uagent.search(deviceS70) > -1 ||\n uagent.search(deviceS80) > -1 ||\n uagent.search(deviceS90) > -1)\n return true;\n else\n return false;\n}", "function DetectSonyMylo()\n{\n if (uagent.search(manuSony) > -1)\n {\n if (uagent.search(qtembedded) > -1 ||\n uagent.search(mylocom2) > -1)\n return true;\n else\n return false;\n }\n else\n return false;\n}", "function Supports(feature)\n {\n var supported = false;\n switch(feature)\n {\n case 'VENDOR_1_7':\n case 'VENDORWIFI_1_7':\n case 'DLNA_1_14':\n case 'WPS_1_14':\n supported = true;\n break;\n }\n return supported;\n }", "verifyPlatform(specs=null) {\n let platform = this.data;\n let platformName = platform ? ('' + platform.Extra.hd_specs.general_platform ).toLowerCase().trim() : '';\n let platformVersion = platform ? ('' + platform.Extra.hd_specs.general_platform_version).toLowerCase().trim() : '';\n let devicePlatformName = ('' + specs.general_platform ).toLowerCase().trim();\n let devicePlatformVersionMin = ('' + specs.general_platform_version ).toLowerCase().trim();\n let devicePlatformVersionMax = ('' + specs.general_platform_version_max ).toLowerCase().trim();\n\n // Its possible that we didnt pickup the platform correctly or the device has no platform info\n // Return true in this case because we cant give a concrete false (it might run this version).\n if (!platform || !platformName || !devicePlatformName) {\n return true;\n }\n\n // Make sure device is running stock OS / Platform\n // Return true in this case because its possible the device can run a different OS (mods / hacks etc..)\n if (platformName !== devicePlatformName) {\n return true;\n }\n\n // Detected version is lower than the min version - so definetly false.\n if (platformVersion && devicePlatformVersionMin && this.comparePlatformVersions(platformVersion, devicePlatformVersionMin) <= -1) {\n return false;\n }\n\n // Detected version is greater than the max version - so definetly false.\n if (platformVersion && devicePlatformVersionMax && this.comparePlatformVersions(platformVersion, devicePlatformVersionMax) >= 1) {\n return false;\n }\n\n // Maybe Ok ..\n return true;\n }", "function DetectSymbianOS()\n{\n if (uagent.search(deviceSymbian) > -1 ||\n uagent.search(deviceS60) > -1 ||\n uagent.search(deviceS70) > -1 ||\n uagent.search(deviceS80) > -1 ||\n uagent.search(deviceS90) > -1)\n return true;\n else\n return false;\n}", "get isDeviceRegistered() {\n return !!this.deviceMe;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Registers the fs storage as plugin.
static register() { __WEBPACK_IMPORTED_MODULE_0__common_plugin__["a" /* PLUGINS */]["FSStorage"] = FSStorage; }
[ "function registerLazyFS(index, files, fs_root, resolver) {\n var device = new LazyFSDevice(index, files, fs_root, resolver);\n jsoo_mount_point.push({path: fs_root, device: device});\n}", "static register() {\n common_plugin[\"a\" /* PLUGINS */][\"IndexedStorage\"] = indexed_storage_IndexedStorage;\n }", "registerStorageResolver(storageResolver) {\n this.storageResolversSlot.register(storageResolver);\n return this;\n }", "static register() {\n common_plugin[\"a\" /* PLUGINS */][\"PartitioningAdapter\"] = partitioning_adapter_PartitioningAdapter;\n }", "function registerPlugin(plugin) {\n data.plugins.push(plugin);\n}", "function registerStorageCommands(cli) {\n cli.registerCommand({ name: 'lists', help: 'list storages', aliases: ['list-storages'] }, [\n { name: 'alias', help: 'cluster alias' },\n { name: ['--skip-cache', '-k'], help: 'skip cached record, fetch latest value', action: 'storeTrue' }\n ], async (a) => {\n const client = cli.manager.getClusterClient(a.alias);\n return await client.cache.functions.getStorages(a.skip_cache);\n });\n cli.registerCommand({ name: 'getinfo', help: 'get info of destination path in storage' }, [\n { name: 'alias', help: 'cluster alias' },\n { name: 'storage', help: 'storage name' },\n { name: ['--skip-cache', '-k'], help: 'skip cached record, fetch latest value', action: 'storeTrue' }\n ], async (a) => {\n const client = cli.manager.getClusterClient(a.alias);\n return await client.cache.functions.getStorageByName(a.skip_cache, a.storage);\n });\n}", "function registerPlugin(plugin) {\n data.plugins.push(plugin);\n}", "function initFS() {\n window.requestFileSystem(window.TEMPORARY, 1024*1024, function(filesystem) {\n fs = filesystem;\n }, errorHandler);\n}", "function FileSystemBridgeStorage(spec) {\n this._sub_storage = jIO.createJIO(spec.sub_storage);\n }", "create_storage() {\n fs.writeFileSync(`./${this.storage_file}`, '{}')\n }", "static deregister() {\n delete __WEBPACK_IMPORTED_MODULE_0__common_plugin__[\"a\" /* PLUGINS */][\"FSStorage\"];\n }", "addPlugins() {\n const pm = PluginManager.getInstance();\n pm.addPlugin(new ElectronPlugin());\n }", "function initStorage() {\n storage.initSync();\n}", "mountPlugins(){\n for (var pluginName in this.plugins) {\n let plugin = Plugin.createPlugin(pluginName, this.plugins[pluginName], this);\n this.pluginsInstances[pluginName] = plugin;\n }\n\n }", "function registerPlugins (log) {\n const plugins = global.FLINT.plugins\n const Plugin = mongoose.model('Plugin')\n\n return Promise.all(plugins.map(async (PluginClass) => {\n if (!PluginClass.uid) throw new Error(`${PluginClass.name} is missing a UID.`)\n if (!PluginClass.version) throw new Error(`${PluginClass.name} is missing a version.`)\n\n mongoose.plugin((schema, options) => {\n if (schema.name === undefined) return null\n return new PluginClass(schema, options)\n })\n\n const pathToIcon = PluginClass.icon\n const buffer = await readFileAsync(pathToIcon, null)\n const foundPlugin = await Plugin.findOne({ uid: PluginClass.uid })\n\n const pluginData = Object.assign({}, {\n title: PluginClass.title,\n name: PluginClass.name,\n uid: PluginClass.uid,\n version: PluginClass.version,\n icon: {\n path: PluginClass.icon,\n buffer\n }\n }, PluginClass.model)\n\n if (foundPlugin) {\n // Update the existing plugin in case its configuration (icon, name, etc) have changed.\n const updatedPlugin = Object.assign(foundPlugin, pluginData, { uid: PluginClass.uid })\n const savedPlugin = await updatedPlugin.save()\n if (!savedPlugin) log.error(`Could not save the [${PluginClass.name}] plugin to the database.`)\n } else {\n // Create a new plugin instance by including the Class model\n // The PluginSchema has { strict: false } so additions to the\n // model will work fine.\n const newPlugin = new Plugin(pluginData)\n const savedPlugin = await newPlugin.save()\n if (!savedPlugin) log.error(`Could not save the [${PluginClass.name}] plugin to the database.`)\n }\n }))\n}", "registerStorageBackend(name, storageBackend) {\n this.storageBackends[name] = storageBackend;\n }", "registerDrive() {\n this.app.container.singleton('Adonis/Core/Drive', () => {\n const { DriveManager } = require('../src/DriveManager');\n const Router = this.app.container.resolveBinding('Adonis/Core/Route');\n const Config = this.app.container.resolveBinding('Adonis/Core/Config');\n const Logger = this.app.container.resolveBinding('Adonis/Core/Logger');\n return new DriveManager(this.app, Router, Logger, Config.get('drive'));\n });\n }", "async reload() {\n\t\t\tlog && log.action(\"reload\");\n\t\t\t\n\t\t\tmetaCache = {\n\t\t\t\t\"\": null\n\t\t\t};\n\n\t\t\tfor (let provider of providers) {\n\t\t\t\tlog && log.action(\"reload-fs\", provider.name);\n\t\t\t\t\n\t\t\t\tawait provider.reload();\n\t\t\t}\n\n\t\t\tlog && log.action(\"meta\", \"load\");\n\n\t\t\tfor (let disk of public.disks) {\n\t\t\t\tif (!(await public.exists(disk))) {\n\t\t\t\t\tawait public.mkdir(disk);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tawait updateFileExts();\n\t\t}", "function installHandlers (saved) {\n if (saved.prefs.isFileHandler) {\n const ipcRenderer = require('electron').ipcRenderer\n ipcRenderer.send('setDefaultFileHandler', true)\n }\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
get_url_zip() is a simple function to retrieve the zip variable from the URL
function get_url_zip() { var zip = ""; var keyvals = window.location.href.slice(window.location.href.indexOf("?") + 1).split("&"); $.each( keyvals , function(i, val) { var parts = val.split("="); if (parts[0] == "zip") { zip = parts[1]; } }); return (cfpb_hud_hca.check_zip(zip)); }
[ "function zipUrl(zip) {\n return `${API_STEM}q=${zip}%units=imperial&APPID=${WEATHER_API_KEY}`;\n}", "function get_zip_name(url, /*optional*/filename) {\n if (!filename) {\n var extensionID = get_extensionID(url);\n if (extensionID) {\n filename = extensionID;\n } else {\n filename = /([^\\/]+?)\\/*$/.exec(url)[1];\n }\n }\n return filename.replace(/\\.(crx|nex|zip)$/i, '') + '.zip';\n}", "getZip(){\n console.log('Getting current ZIP code...');\n\n var options = {\n host: 'api.wunderground.com',\n path: '/api/' + key + '/geolookup/q/autoip.json'\n };\n var str = '';\n var zip = '';\n http.request(options, function(response){\n response.on('data', function (chunk) {\n str += chunk;\n });\n response.on('end', function() {\n var json = JSON.parse(str);\n zipcode = json.location.zip;\n console.log(zipcode);\n });\n }).end();\n }", "function getZip() {\n //hard coded zip to test API\n //return zipInput = 40503;\n return zipInput = document.getElementById(\"zipInput\").value;\n\n}", "function getURL(zipCode){\n return 'http://api.openweathermap.org/data/2.5/weather?zip='+zipCode+'&appid='+apiKey;\n}", "function getZip() {\n var snippetSelector = document.getElementById(\"snippetSets\");\n var setName = snippetSelector.item(snippetSelector.selectedIndex).value;\n $.ajax({\n url: serverUrl + \"/getZipUrl/\" + setName,\n contentType: 'application/json; charset=utf-8',\n type: 'GET',\n async: true,\n success: function (data) {\n var fileUrl = data;\n parseZip(\"tmp/download.zip\");\n },\n error: function (xhr, status) {\n console.log(status);\n console.log(xhr.responseText);\n }\n });\n}", "function getZip(zip) {\n return new Promise((resolve, reject) => {\n openDataZip(zip)\n .then((data) => {\n const location = JSON.parse(data).records[0].fields\n resolve({\n city: location.city,\n lon: location.longitude,\n lat: location.latitude\n })\n })\n .catch((error) => {\n reject(error)\n })\n })\n}", "function findGradesURLRequest(func){\n /* set up async GET request */\n var req = new XMLHttpRequest();\n req.open(\"GET\", zip_link_location, true);\n\n // Tell request what to do with code once the request loads\n req.onload = function(e) {\n // Check for 404 error\n if (req.status == 404){\n reqLoadErrorAlert(func);\n return;\n }\n\n // RegEx to find the zip file on the page\n var pattern = new RegExp(/\"(.*\\.zip)\"/);\n regex_result = pattern.exec(req.response);\n zip_name = regex_result[1];\n console.log(\"Zip file name: \" + zip_name);\n\n // Sets the protocol to match the user's\n // Some users (like Tristen *cough cough*) have weird plug-ins that turn http\n // websites into https sites. This handles those edge cases.\n if (window.location.protocol == 'https:'){\n var url = \"https://\" + grades_url + zip_name;\n } else {\n var url = \"http://\" + grades_url + zip_name;\n };\n\n // Set link to download grades zip\n $('#gradesZip').attr('href', url);\n\n // calls downloadGradesRequest to download the grades\n downloadGradesRequest(url, func);\n }\n\n // Send request\n req.send();\n req.responseType = \"text\";\n}", "function geofromZIP(zip, callback){\n\trequest('https://maps.googleapis.com/maps/api/geocode/json?address='+zip+'&key=AIzaSyCP9syBFfHu5zfVSavGJLWS3f8bzL5mKMI', function(error, response, body){\n\t\t\tvar data = JSON.parse(body);\n\t\t\tvar latLong = [data.results[0].geometry.location.lat, data.results[0].geometry.location.lng];\n\t\t\tcallback(latLong);\n\t});\n}", "function getZipValue(){\n\tvar cookieValue = getRememberMe();\n\tif (cookieValue != \"\") {\n\t\tvar cookiePairs = cookieValue.split(\"~\");\n\t\tvar cookiePair = \"\";\n\t\tvar cookiePairContent = \"\";\n\t\tfor(i=0;i<cookiePairs.length;i++){\t\n\t\t\tcookiePair = cookiePairs[i];\n\t\t\tif (cookiePair != \"\") {\n\t\t\t\tcookiePairContent = cookiePair.split(\":\");\n\t\t\t\tif(cookiePairContent.length > 1){\n\t\t\t\t\tif(cookiePairContent[0]==\"zipCode\"){\n\t\t\t\t\t\treturn cookiePairContent[1];\n\t\t\t\t\t}\n\t\t\t\t}else{\n\t\t\t\t\treturn \"\";\n\t\t\t\t}\n\t\t\t}\t\t\t\n\t\t}\n\t}\n\treturn \"\";\n}", "function download_zip_url() {\n var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};\n\n return exports.download_archive_url(merge(options, {\n target_format: \"zip\"\n }));\n}", "function getZip(){\n\t\tapiService.getZip({user:vm.username})\n\t\t.$promise.then(function(result) {\n\t\t\tvm.zip = result.zipcode\n\t\t\tUserService.zip = vm.zip\n\t\t})\n\t}", "function getZip(resp) {\n var zipCode = resp.location.zip;\n if (zipCode == null) {\n error(\"Zipcode was not found.\");\n return;\n }\n zipCode = encodeURIComponent(zipCode);\n document.getElementById(\"zip\").innerHTML = \"Zipcode found: \" + zipCode;\n var url = \"https://api.wunderground.com/api/\" + apiKey + \"/hourly/q/\" + zipCode + \".json\";\n\n //$.getJSON(url, {}, getWeather);\n\n $.ajax({\n url: url,\n type: \"GET\",\n contentType: \"application/json; charset=utf-8\",\n data: \"[]\",\n dataType: \"jsonp\",\n success: getWeather,\n error: error\n });\n}", "function getZipCoordinates(zip) {\n\n\tvar url = \"\";\n\n\t// console.log(data);\n\tfor ( var i = 0; i < data.length; i++ ) {\n\n\t\tif ( data[i][\"\\\"\\\"zipcode\\\"\\\"\"] == zip ) {\n\n\t\t\tzipObj = data[i];\n\t\t\tvar lat = zipObj[\"\\\"\\\"latitude\\\"\\\"\"];\n\t\t\tvar lon = zipObj[\"\\\"\\\"longitude\\\"\\\"\"];\n\n\t\t\t// for testing\n\t\t\t// console.log(\"latitude: \" + lat);\n\t\t\t// console.log(\"longitude: \" + lon);\n\t\t\t// console.log(zipObj);\n\n\n\t\t\t// remove quotations\n\t\t\tlat = lat.slice(3);\n\t\t\tlat = lat.slice(0,-3);\n\n\t\t\tlon = lon.slice(2);\n\t\t\tlon = lon.slice(0,-3);\t\t\t\n\n\t\t\turl = \"https://api.forecast.io/forecast/\" + API_KEY + \"/\" + lat + \",\" + lon;\n\t\t\t//console.log(url);\n\n\t\t\tbreak;\n\t\t}\n\t}\n\tgetWeather(url);\n}", "async function step1 ({ zipUrl }) {\n const isLocalFile = fs.existsSync(zipUrl)\n let zipFile\n if (!isLocalFile) {\n console.log(`Downloading Hardcore-SK from ${zipUrl}...\\nThis may take a while`)\n zipFile = tmp.fileSync().name\n await fetchAndSave(zipUrl, zipFile)\n } else {\n zipFile = zipUrl\n }\n\n return zipFile\n}", "async function getZipCodeInfo(zipCode) {\n try{\n const url = `${baseURL}${zipCode}${apiKey}${unitParam}`;\n const response = await fetch(url);\n \n return await response.json();\n }\n catch(error){\n console.log(error);\n }\n}", "function enterZip() {\n\tvar firsturl = \"https://maps.google.com/maps?q=\"\n\tvar lasturl = \";output=embed\"\n\t\n\tstring.concat(firsturl,PostalCode,lasturl);\n}", "function zipCaller(zip) {\n var zipQueryUrl\n = \"https://us-zipcode.api.smartystreets.com/lookup?auth-id=\" + smartyStreetsID +\n \"&auth-token=\" + smartyStreetsToken + \"&zipcode=\" + zip;\n $.ajax({\n url: zipQueryUrl,\n method: \"GET\",\n success: function (response) {\n backTracker(response[0].zipcodes[0].county_fips);\n }\n })\n }", "function getURL() {\n var zip = document.getElementById(\"zipInput\").value;\n var select = document.getElementById(\"selectMiles\");\n var mileRad = select.options[select.selectedIndex].value;\n var url = \"https://api.zip-codes.com/ZipCodesAPI.svc/1.0/FindZipCodesInRadius?zipcode=\" + zip + \"&minimumradius=0&maximumradius=\" + mileRad + \"&key=S71SJ1GYOPA23ZF25UXL\";\n\n return url;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Detects scrollers in the DOM
function detectScrollers() { return $.map($(".horiz-scroll"), function(scroller) { return $(scroller).attr("id"); }); }
[ "function detectScrollers() {\r\n return $.map($(\".horiz-scroll\"), function(scroller) {\r\n return $(scroller).attr(\"id\");\r\n });\r\n}", "_canScroll(el,deltaX,deltaY){return deltaY>0&&el.scrollTop<el.scrollHeight-el.offsetHeight||deltaY<0&&el.scrollTop>0||deltaX>0&&el.scrollLeft<el.scrollWidth-el.offsetWidth||deltaX<0&&el.scrollLeft>0;}", "_canScroll(el,deltaX,deltaY){return 0<deltaY&&el.scrollTop<el.scrollHeight-el.offsetHeight||0>deltaY&&0<el.scrollTop||0<deltaX&&el.scrollLeft<el.scrollWidth-el.offsetWidth||0>deltaX&&0<el.scrollLeft}", "_onScroll(e) {\n this._checkScroll();\n }", "function mkdOnWindowScroll() {\n \n }", "function lookForScrollBarInDocument() {\n\n var html = document.documentElement;\n if (html) {\n return (html.scrollHeight > html.clientHeight)\n }\n else {\n trace(\" *** COULD NOT FIND HTML?? \\n\");\n return false;\n }\n}", "autoDetectScrollMode() {\n // let theInnerHtml = this.element;\n const capacity = get(this, 'capacity'),\n selector = `#${this.elementId} .uxs-tiles__item`,\n numberOfTiles = document.querySelectorAll(selector).length;\n\n const allowScroll = get(this, 'scroll');\n if(allowScroll == undefined || allowScroll) {\n if (numberOfTiles > capacity) {\n set(this, 'scroll', true);\n }\n }\n }", "checkScrollBar(e) {\n const lastReview = this.refList[this.refList.length - 1].current;\n const lastElementOffset = lastReview.offsetTop + lastReview.clientHeight;\n const scrollOffset = e.target.scrollTop + e.target.clientHeight + e.target.offsetTop;\n if (scrollOffset >= lastElementOffset) {\n this.loadMoreReviews();\n }\n }", "function eltdfOnWindowScroll() {\n \n }", "checkScrollPos() {\n let fromTop = window.scrollY;\n this.links.forEach(link => {\n let section = document.querySelector(`#${link.el.dataset.section}`);\n if (section.offsetTop <= fromTop && section.offsetTop + section.offsetHeight > fromTop) {\n link.setCurrent();\n } else {\n link.setCurrent(false);\n }\n })\n }", "function supportsScrollBehavior() {\n return !!(typeof document == 'object' && 'scrollBehavior' in document.documentElement.style);\n}", "_listenToScrollEvents() {\n this._viewportScrollSubscription = this._dragDropRegistry.scrolled(this._getShadowRoot()).subscribe(event => {\n if (this.isDragging()) {\n const scrollDifference = this._parentPositions.handleScroll(event);\n if (scrollDifference) {\n this._sortStrategy.updateOnScroll(scrollDifference.top, scrollDifference.left);\n }\n } else if (this.isReceiving()) {\n this._cacheParentPositions();\n }\n });\n }", "function supportsScrollBehavior() {\n return !!(typeof document == 'object' && 'scrollBehavior' in document.documentElement.style);\n }", "flashScrollIndicators() {\n const scrollView = this.getNativeScrollRef();\n if (scrollView != null) {\n scrollView.flashScrollIndicators();\n }\n }", "_checkScrollingControls() {\n if (this.disablePagination) {\n this._disableScrollAfter = this._disableScrollBefore = true;\n }\n else {\n // Check if the pagination arrows should be activated.\n this._disableScrollBefore = this.scrollDistance == 0;\n this._disableScrollAfter = this.scrollDistance == this._getMaxScrollDistance();\n this._changeDetectorRef.markForCheck();\n }\n }", "checkScrollingControls() {\n if (this.disablePagination) {\n this.disableScrollAfter = this.disableScrollBefore = true;\n }\n else {\n // Check if the pagination arrows should be activated.\n this.disableScrollBefore = this.scrollDistance === 0;\n this.disableScrollAfter = this.scrollDistance === this.getMaxScrollDistance();\n this.changeDetectorRef.markForCheck();\n }\n }", "function scrollerInit() {\r\n var scrollerIds = detectScrollers();\r\n mapScrollers(scrollerIds);\r\n listenForScroll();\r\n}", "function logScrollMsg() {\n console.log(\"scrolling\");\n}", "_checkOverflow() {\n const that = this,\n scrollViewer = that.$.scrollViewer,\n overflow = that.overflow;\n\n if (that.scrollMode === 'scrollbar' || overflow === 'hidden') {\n scrollViewer.refresh();\n return;\n }\n\n const oldScrollTop = scrollViewer.scrollTop;\n\n if (overflow === 'auto') {\n scrollViewer.$.removeClass('scroll-buttons-shown');\n scrollViewer.$.removeClass('one-button-shown');\n that.$scrollButtonNear.addClass('smart-hidden');\n that.$scrollButtonFar.addClass('smart-hidden');\n }\n\n const overflowing = Math.round(scrollViewer.$.scrollViewerContentContainer.offsetHeight) >\n Math.round(scrollViewer.$.scrollViewerContainer.offsetHeight),\n showNear = Math.round(scrollViewer.scrollTop) > 0,\n showFar = Math.round(scrollViewer.$.scrollViewerContainer.offsetHeight + scrollViewer.scrollTop) <\n Math.round(scrollViewer.$.scrollViewerContentContainer.offsetHeight);\n\n if (overflowing) {\n if (overflow === 'auto') {\n scrollViewer.$.addClass('scroll-buttons-shown');\n\n if (showNear) {\n that.$scrollButtonNear.removeClass('smart-hidden');\n }\n\n if (showFar) {\n that.$scrollButtonFar.removeClass('smart-hidden');\n }\n\n if ((showNear && showFar) === false) {\n scrollViewer.$.addClass('one-button-shown');\n }\n\n if (!that.disabled) {\n that.$.scrollButtonNear.disabled = false;\n that.$.scrollButtonFar.disabled = false;\n }\n\n scrollViewer.scrollTop = oldScrollTop;\n }\n else {\n that.$scrollButtonNear.removeClass('smart-hidden');\n that.$scrollButtonFar.removeClass('smart-hidden');\n\n if (that.disabled) {\n that.$.scrollButtonNear.disabled = true;\n that.$.scrollButtonFar.disabled = true;\n }\n else {\n that.$.scrollButtonNear.disabled = !showNear;\n that.$.scrollButtonFar.disabled = !showFar;\n }\n }\n }\n else if (overflow === 'scroll') {\n that.$.scrollButtonNear.disabled = true;\n that.$.scrollButtonFar.disabled = true;\n }\n\n scrollViewer.refresh();\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Redirect if not authorized
function redirectIfNotAuthorized() { $.ajax({ url: jsconfig.baseurl + "/api/version", beforeSend: authHeaders, statusCode: { 401: function() { window.location.replace(jsconfig.baseurl + "/app/login.html"); }, 403: function() { window.location.replace(jsconfig.baseurl + "/app/login.html"); } } }); }
[ "function checkNotAuthenticated(req, res, next) {\n if (req.isAuthenticated()) {\n return res.redirect('/home')\n }\n next()\n }", "function validate_access() {\n if (!is_logged_in()) {\n window.location = \"index.html\";\n }\n}", "function redirectpublic_action() {\n if (checkAddress() == false) return;\n if (checkAuth(this) == false) return;\n\n res.redirect(this.url_macro());\n}", "function verifyUserAndRedirect() {\n if (!isUserAuthenticated()) {\n console.log('User is not authorized, redirecting to Login page');\n showLoginPage();\n }\n }", "function checkNotAuth(req, res, next) {\n // If authenticated, redirect to Home page\n if (req.isAuthenticated()) {\n return res.redirect('/');\n }\n // If not authenticated, proceed to requested route\n next();\n}", "validateAuth(req, res, next) {\n if (!req.isAuthenticated()) return res.redirect(\"/\");\n return next();\n }", "function accessDenied() {\n $state.go('401');\n }", "function noopAuthorize(req, res, authorized, _unauthorized) {\r\n authorized();\r\n}", "function redirectNotAuthUser(websitePath) {\n if (!isLoggedIn()) {\n window.location.href = websitePath;\n }\n}", "function redirectIfNotAuthenticated() {\n return (to, from, next) => {\n if (!auth.isAuthenticated()) {\n router.push('/login')\n } else {\n next()\n }\n }\n}", "function checkAuthenticated(req, res, next) {\n\tif (req.isAuthenticated()) {\n\t\treturn res.redirect('/users/dashboard');\n\t}\n\n\tnext();\n}", "function isAuth(request, response, next) {\n if (request.session.author) {\n return next();\n }\n response.redirect(\"/author/login\");\n}", "redirect() {\n if (get(this, 'session.isAuthenticated')) {\n this.transitionTo('index');\n }\n }", "function ensureAuthenticated(req, res, next) {\n if (req.isAuthenticated()) { return next(); }\n res.redirect('/login')\n }", "validateGuest(req, res, next) {\n if (!req.isAuthenticated()) return next();\n return res.redirect(\"/success\");\n }", "function handle401 (res) {\n if (res.status === 401) {\n console.error(res)\n window.location.replace('/login')\n } else {\n return res\n }\n}", "function ensureAuthenticated(req, res, next) {\n if (req.isAuthenticated()) { return next(); }\n res.redirect('/login')\n }", "needRedirectToLogin () {\n if (!this.authorized &&\n this.path.target !== this.path.login &&\n this.path.target !== this.path.register &&\n this.path.target !== this.path.home) {\n return true\n }\n\n return false\n }", "function checkAuthorization(req, res, next) {\n\t// if user is authenticated (logged-in)\n\tif (req.isAuthenticated()) {\n\t\t// find the poll to check for authorization as well\n\t\tPoll.findById(req.params.id, (err, foundPoll) => {\n\t\t\tif (err) {\n\t\t\t\tres.redirect('back');\n\t\t\t} else {\n\t\t\t\t// if current user is the one who added the poll\n\t\t\t\tif (foundPoll.user.id && foundPoll.user.id.equals(req.user._id)) {\n\t\t\t\t\tnext();\n\t\t\t\t} else {\n\t\t\t\t\tres.redirect('back');\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t} else {\n\t\tres.redirect('back');\n\t}\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
calcula e retorna quem ganhou 0Empate;1Jogador;2Computador
function calcularEscolha(jogador, computador){ //pedra if(jogador==1 && computador==1){ return 0; } else if (jogador==1 && computador==2) { return 2; } else if (jogador==1 && computador==3) { return 1; } //papel else if (jogador==2 && computador==1) { return 1; } else if (jogador==2 && computador==2) { return 0; } else if (jogador==2 && computador==3) { return 2; } //tesoura else if (jogador==3 && computador==1) { return 2; } else if (jogador==3 && computador==2) { return 1; } else if (jogador==3 && computador==3) { return 0; } }
[ "function calcularEscolha(jogador, computador) {\n if (jogador == 1 && computador ==1) {\n return 0;\n }\n else if (jogador == 1 && computador ==2) {\n return 2;\n }\n else if (jogador == 1 && computador ==3) {\n return 1;\n }\n\n else if (jogador == 2 && computador ==1) {\n return 1;\n }\n else if (jogador == 2 && computador ==2) {\n return 0;\n }\n else if (jogador == 2 && computador ==3) {\n return 2;\n }\n\n \n else if (jogador == 3 && computador ==1) {\n return 2;\n }\n else if (jogador == 3 && computador ==2) {\n return 1;\n }\n else if (jogador == 3 && computador ==3) {\n return 0;\n }\n }", "function calcularEscolha(jogador, computador) {\n if (jogador == 1 && computador == 1) {\n return 0;\n }\n else if (jogador == 1 && computador == 2) {\n return 2;\n } \n else if (jogador == 1 && computador == 3) {\n return 1;\n } \n else if (jogador == 2 && computador == 1) {\n return 1;\n } \n else if (jogador == 2 && computador == 2) {\n return 0;\n } \n else if (jogador == 2 && computador == 3) {\n return 2;\n } \n else if (jogador == 3 && computador == 1) {\n return 2;\n } \n else if (jogador == 3 && computador == 2) {\n return 1;\n } \n else if (jogador == 3 && computador == 3) {\n return 0;\n }\n\n}", "function jogadores_premios()\n{\n if (jogador1_cavalo == ArrayCavalos[0])\n {\n jogador1_montante += (jogador1_aposta*2);\n }\n else {jogador1_montante -= jogador1_aposta;}\n // Jogador 2 --------------------------------------------\n if (jogador2_cavalo == ArrayCavalos[0])\n {\n jogador2_montante += (jogador2_aposta*2);\n }\n else {jogador2_montante -= jogador2_aposta;}\n // Jogador 3 --------------------------------------------\n\n if (jogador3_cavalo == ArrayCavalos[0])\n {\n jogador3_montante += (jogador3_aposta*2);\n }\n else {jogador3_montante -= jogador3_aposta;}\n // Jogador 4 --------------------------------------------\n if (jogador4_cavalo == ArrayCavalos[0])\n {\n jogador4_montante += (jogador4_aposta*2);\n }\n else {jogador4_montante -= jogador4_aposta;}\n}", "function calculaPontos(jogador) {\n var pontos = jogador.vitorias * 3 + jogador.empates;\n return pontos;\n}", "function checaHora(diaEscolhido) {\n var mesId = \"d\";\n var mesAt = mes + 1;\n mesId = mesId.replace(\"d\", mesAt);\n \n\n var checaDia = \"d\";\n var checaDia = checaDia.replace(\"d\", diaEscolhido);\n\n tirarHoraGasta(horaIntervalo.inicio, horaIntervalo.fim);\n\n if (agMes[mesId] != null) {\n for (var i = 0; i < agMes[mesId].length; i++) {\n\n if (agMes[mesId][i].dia == checaDia) {\n\n var minutoM = 0; //minuto marcado\n var horaM = 0; //hora marcada\n\n //se for igual a 3 para saber se a hora é\n //menor que 10\n if (agMes[mesId][i].hora.length == 3) {\n horaM = parseInt(agMes[mesId][i].hora[0]);\n minutoM = agMes[mesId][i].hora[1] + agMes[mesId][i].hora[2];\n minutoM = parseInt(minutoM);\n }\n else {\n horaM = agMes[mesId][i].hora[0] + agMes[mesId][i].hora[1];\n minutoM = agMes[mesId][i].hora[2] + agMes[mesId][i].hora[3];\n horaM = parseInt(horaM);\n minutoM = parseInt(minutoM);\n }\n var horaG = agMes[mesId][i].horaGasta; //hora gasta\n var minutoG = agMes[mesId][i].minutoGasto; // minuto gasto\n horaG = parseInt(horaG);\n minutoG = parseInt(minutoG);\n\n var horaS = horaM + horaG; //hora somada\n var minutoS = minutoM + minutoG; //minuto somado\n \n if (minutoS > 30) {\n minutoS = 0;\n ++horaS;\n }\n\n var tMinuto = \"d\"; //texto Minuto\n var tHora = \"d\"; //texto hora\n if (minutoS == 0) {\n tMinuto = tMinuto.replace(\"d\", \"00\");\n }\n else {\n tMinuto = tMinuto.replace(\"d\", minutoS);\n }\n\n tHora = tHora.replace(\"d\", horaS);\n\n var fim = tHora + tMinuto;\n fim = parseInt(fim);\n var inicio = agMes[mesId][i].hora;\n tirarHoraGasta(inicio, fim);\n }\n }\n }\n}", "function calculaMesAnioCalendario(pMesMostrado, anioMostrado, incr) {\n\n\tvar ret_arr = new Array();\n\n\t// Regresamos un mes\n\tif (incr == -1) {\n\t\t//Si el mes es enero\n\t\tif (pMesMostrado == 0) {\n\t\t\tret_arr[0] = 11; // El nuevo mes es diciembre\n\t\t\tret_arr[1] = parseInt(anioMostrado) - 1; //y por lo tanto es el anio anterior\n\t\t}\n\t\t//Si es cualquier otro mes solo decrementamos el mes\n\t\telse {\n\t\t\tret_arr[0] = parseInt(pMesMostrado) - 1;\n\t\t\tret_arr[1] = parseInt(anioMostrado);\n\t\t}\n\t}\n\t//Adelantamos un mes\n\telse if (incr == 1) {\n\t\t//Si el mes es Diciembre\n\t\tif (pMesMostrado == 11) {\n\t\t\tret_arr[0] = 0; //El siguiente mes es Enero\n\t\t\tret_arr[1] = parseInt(anioMostrado) + 1; //del siguiente anio\n\t\t}\n\t\t//Si es cualquier otro mes, solo adelantamos el mes\n\t\telse {\n\t\t\tret_arr[0] = parseInt(pMesMostrado) + 1;\n\t\t\tret_arr[1] = parseInt(anioMostrado);\n\t\t}\n\t}\n\t//regresamos el mes y el anio\n\treturn ret_arr;\n}", "cronometro() {\n if (this.centesimas < 99) {\n this.centesimas++;\n if (this.centesimas < 10) { this.centesimas = \"0\" + this.centesimas }\n Centesimas.innerHTML = \":\" + this.centesimas;\n }\n if (this.centesimas == 99) {\n this.centesimas = -1;\n }\n if (this.centesimas == 0) {\n this.segundos++;\n if (this.segundos < 10) { this.segundos = \"0\" + this.segundos }\n Segundos.innerHTML = \":\" + this.segundos;\n }\n if (this.segundos == 59) {\n this.segundos = -1;\n }\n if ((this.centesimas == 0) && (this.segundos == 0)) {\n this.minutos++;\n if (this.minutos < 10) { this.minutos = \"0\" + this.minutos }\n Minutos.innerHTML = this.minutos;\n }\n\n }", "function calcular_idade(data){ \n\n \t//calculo a data de hoje \n\thoje=new Date();\n \t//alert(hoje) \n\n \t//calculo a data que recebo \n \t//descomponho a data em um array\n \tvar array_data = data.split(\"/\");\n \t//se o array nao tem tres partes, a data eh incorreta \n \tif (array_data.length!=3) \n \t return false;\n\n \t//comprovo que o ano, mes, dia s�o corretos \n \tvar ano;\n \tano = parseInt(array_data[2]); \n \tif (isNaN(ano)) \n \t return false;\n\n \tvar mes;\n \tmes = parseInt(array_data[1]); \n \tif (isNaN(mes)) \n \t return false;\n\n \tvar dia;\n \tdia = parseInt(array_data[0]);\t\n \tif (isNaN(dia)) \n \t return false;\n\n\n \t//se o ano da data que recebo so tem 2 cifras temos que muda-lo a 4 \n \tif (ano<=99) \n \t ano +=1900;\n\n \t//subtraio os anos das duas datas\n \tidade=hoje.getFullYear()- ano - 1; //-1 porque ainda nao fez anos durante este ano\n\n \t//se subtraio os meses e for menor que 0 entao nao cumpriu anos. Se for maior sim ja cumpriu \n \tif (hoje.getMonth() + 1 - mes < 0) //+ 1 porque os meses comecam em 0 \n \t return idade;\n \tif (hoje.getMonth() + 1 - mes > 0) \n \t return idade+1 ;\n \t\n \t//entao eh porque sao iguais. Vejo os dias \n \t//se subtraio os dias e der menor que 0 entao nao cumpriu anos. Se der maior ou igual sim que j� cumpriu \n \tif (hoje.getUTCDate() - dia >= 0) \n \t return idade + 1; \n\n \treturn idade;\n}", "function calcularEscolha(jogador, computador) {\n if (jogador == computador) {\n return 0\n }\n\n if (jogador == 1 && computador == 2) {\n return 2\n }\n\n if (jogador == 1 && computador == 3) {\n return 1\n }\n\n if (jogador == 2 && computador == 1) {\n return 1\n }\n\n if (jogador == 2 && computador == 3) {\n return 2\n }\n\n if (jogador == 3 && computador == 1) {\n return 2\n }\n\n if (jogador == 3 && computador == 1) {\n return 1\n }\n}", "function getAccueil(hote, creneau){\n return creneau == 8 ? hote[N_PLACED2PM] : creneau == 7 ? hote[N_PLACED2AM] : creneau == 6 ? hote[N_PLACES2PM] : creneau == 5 ? hote[N_PLACES2AM] : creneau == 4 ? hote[N_PLACEDPM] : creneau == 3 ? hote[N_PLACEDAM] : creneau == 2 ? hote[N_PLACESPM] : creneau == 1 ? hote[N_PLACESAM] : -1;\n}", "function calcola_jddata(giorno,mese,anno,ora,minuti,secondi){\n\n // funzione per il calcolo del giorno giuliano per una data qualsiasi. \n // by Salvatore Ruiu Irgoli-Sardegna (Italy) dicembre 2009\n // restituisce il valore numerico dataGiuliana_annox\n// ATTENZIONE! inserire i valori dei tempi come T.U. di GREENWICH\n \nvar dataGiuliana=costanti_jd(giorno,mese,anno,ora,minuti,secondi); // valore del giorno giuliano per una data qualsiasi.\n\n dataGiuliana=dataGiuliana*1 // definire come valore numerico.\n\nreturn dataGiuliana;\n\n}", "function calcularTotal(){\n// inicializo en 0 los totales\nvar totalJugador1 = 0;\nvar totalJugador2 = 0;\n// aca va el for que pasa por los p1 hasta las 11 filas\nfor (var i = 1; i <= 11; i++) {\n// tomo el texto que está adentro del selector del jugador 1 y 2 y le concateno el i para recorrer todas las filas\n// lo paso a las variables locales valor1 y valor2 para hacerlo mas legible\nvar valor1 = $$('#d_'+i+'_1>a').text();\nvar valor2 = $$('#d_'+i+'_2>a').text();\n// si el valor de valor1 o valor 2 es \"X\" o \"-\" no hago nada en esta vuelta, lo salteo. \nif(valor1 == \"X\" || valor1 == \"-\"){ \n}else{\n// sino sumo el valor al total del jugador, acumulando el total en totalJugador que esta fuera del for\ntotalJugador1 += parseInt(valor1);\n}\n// hago lo mismo que antes para el jugador 2\nif(valor2 == \"X\" || valor2 == \"-\"){ \n}else{\ntotalJugador2 += parseInt(valor2);\n}\n// salgo del for\n}\n// Imprimo los totales de jugadores dentro del selector con el id que guarda el total\n$$('#total1').text(totalJugador1);\n$$('#total2').text(totalJugador2);\n}", "function calcularGanador() {\n let text;\n if (ganadasJugador === ganadasMaquina) {\n text = document.createTextNode('🤝 EMPATE');\n } else {\n if (ganadasJugador > ganadasMaquina) {\n text = document.createTextNode(`🏆 ${nombreJugador}`);\n }\n if (ganadasJugador < ganadasMaquina) {\n text = document.createTextNode('🏆 MÁQUINA');\n }\n }\n inputJuegos.value = 0;\n ganadasJugador = 0;\n ganadasMaquina = 0;\n alternarBloqueoBtns(true);\n ganador.appendChild(text);\n}", "function calcularFecha (fechas){\n\tlet fecha = new Date(fechas);\n\tlet hoy = new Date().getTime();\n\tlet pFecha = new Date (fechas).getTime();\n\tlet dif = (hoy -pFecha );\n\tlet dias = dif / (1000 * 60 * 60 * 24 );\n\tlet horas = dif / (1000 * 60 * 60 );\n\tlet minutos = dif / (1000 * 60 );\n\tvar mostrar = \"Justo ahora\";\n\tlet meses = ['En', 'Feb', 'Mar', 'Abr', 'May', 'Jun', 'Jul', 'Ago', 'Sep', 'Oct', 'Nov', 'Dic'];\n\n\tif(dias < 1 && horas < 1 && minutos >= 1){\n\t\tmostrar = \"hace \" + Math.floor(minutos) + \" minutos\";\n\t}\n\tif(dias < 1 && horas >=1 ){\n\t\tmostrar = \"hace \" + Math.floor(horas) + \" horas\";\n\t}\n\n\tif(dias == 1){\n\t\tmostrar = \"Ayer a las \" + fecha.getHours() + \":\" + fecha.getMinutes();\n\t}\n\n\tif(dias > 1){\n\t\tmostrar = fecha.getDate()+\" de \"+ meses[fecha.getMonth()] +\" a las \" + fecha.getHours() + \":\" + fecha.getMinutes();\n\t}\n\n\tif(dias < 1 && horas < 1 && minutos < 1 && minutos > 0){\n\t\tmostrar = \"hace poco\";\n\t}\n\n\tif(dias===NaN && horas===NaN && minutos===NaN ){\n\t\tmostrar = \"Justo ahora\";\n\t}\n\n\treturn mostrar;\n}", "function calcola_jda(){\n\n // funzione per il calcolo del giorno giuliano per il 0.0 gennaio dell'anno corrente.\n // by Salvatore Ruiu Irgoli-Sardegna (Italy) dicembre 2009\n // restituisce dataGiuliana, giorno giuliano inizio anno.\n // recupera automaticamente l'anno.\n // il giorno giuliano è calcolato per il tempo 0 T.U. di Greenwich.\n \n var data=new Date(); \n\n var anno =data.getYear(); // anno\n var mese =1; // mese \n var giorno=0.0; // giorno=0.0\n \nif (anno<1900) {anno=anno+1900;} // correzione anno per il browser.\n\nvar dataGiuliana=costanti_jd(giorno,mese,anno,0,0,0); // valore del giorno giuliano per lo 0.0 gennaio dell'anno corrente.\n\n dataGiuliana=dataGiuliana*1 // definire come valore numerico.\n // \nreturn dataGiuliana;\n\n}", "function tiempoJugadores() {\n\n var ms = tiempo * 60000;\n //Primero guarda cuanto aguanta el j1\n if (partidas == 1)\n tj1 = (ms - game.time.events.duration) / 1000;\n\n //Luego cuanto tarda el j2\n else\n tj2 = (ms - game.time.events.duration) / 1000;\n\n}", "function mejorVendedorMes(mes) {\n let ventaMes = 0;\n let vendedor = \"\";\n let semanaMax = mes * 4 - 1; //Por ejemplo, el mes 1 seria el intervalo de semanas de 0 a 3.\n let semanaMin = semanaMax - 3;\n let ventaSubtotal = 0;\n for (let i = semanaMin; i < semanaMax; i++) {\n ventaSubtotal += vendedor1[i];\n }\n if (ventaSubtotal > ventaMes) {\n ventaMes = ventaSubtotal;\n vendedor = vendedores[0];\n }\n ventaSubtotal = 0;\n for (let i = semanaMin; i < semanaMax; i++) {\n ventaSubtotal += vendedor2[i];\n }\n if (ventaSubtotal > ventaMes) {\n ventaMes = ventaSubtotal;\n vendedor = vendedores[1];\n }\n ventaSubtotal = 0;\n for (let i = semanaMin; i < semanaMax; i++) {\n ventaSubtotal += vendedor3[i];\n }\n if (ventaSubtotal > ventaMes) {\n ventaMes = ventaSubtotal;\n vendedor = vendedores[2];\n }\n ventaSubtotal = 0; for (let i = semanaMin; i < semanaMax; i++) {\n ventaSubtotal += vendedor4[i];\n }\n if (ventaSubtotal > ventaMes) {\n ventaMes = ventaSubtotal;\n vendedor = vendedores[3];\n }\n ventaSubtotal = 0;\n for (let i = semanaMin; i < semanaMax; i++) {\n ventaSubtotal += vendedor5[i];\n }\n if (ventaSubtotal > ventaMes) {\n ventaMes = ventaSubtotal;\n vendedor = vendedores[4];\n }\n console.log(\"El mejor vendedor del mes\", mes, \"es\", vendedor, \" con\", ventaMes);\n}", "function PalautaPelaajatJoukkue1(){\n\t\n\tvar nimet = \"\";\n\n\tfor(i=0; i < this.pelaajatJoukkue1.length; i++){\n\t\tnimet += this.pelaajatJoukkue1[i] + \", \";\n\t}\n\n\treturn nimet;\n}", "function compruebaCruces() { \n var periodos = listado1.datos; \n var indexFechaFin = 6; \n var indexFechaInicio = 5; \n var indexPeriodoCruce = 9; \n var fechaFinActual; \n var fechaInicioSiguiente; \n var fechaFinActualMilis; \n var fechaInicioSiguienteMilis; \n var si = GestionarMensaje(84); \n var no = GestionarMensaje(86); \n \n //chequeo desde el primero con el segundo hasta el anteultimo con el ultimo \n for (var i=0; i < (periodos.length - 1); i++) { \n fechaFinActual = periodos[i][indexFechaFin]; \n fechaInicioSiguiente = periodos[i+1][indexFechaInicio]; \n fechaFinActualMilis = dameMilis(fechaFinActual); \n fechaInicioSiguienteMilis = dameMilis(fechaInicioSiguiente); \n //alert(\"fechaFinActualMilis \" + fechaFinActualMilis); \n //alert(\"fechaInicioSiguienteMilis \" + fechaInicioSiguienteMilis); \n \n if (fechaFinActualMilis >= fechaInicioSiguienteMilis) { \n //periodo con cruce \n periodos[i][indexPeriodoCruce] = si; \n } else { \n //periodo sin cruce \n periodos[i][indexPeriodoCruce] = no; \n } \n } \n //ademas el ultimo es periodo sin cruce \n if (periodos.length != 0) { \n periodos[periodos.length-1][indexPeriodoCruce] = no; \n } \n \n //setamos la lista actualizada \n listado1.datos = periodos; \n \n //actualizo el listado de periodos. \n listado1.save(); \n listado1.repintaDat(); \n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
storing VI information to either localStorage or csv file Requires to include functions in: CSVtoArray.js Create a string variable containing VI records in CSV format.
function vi_to_csv(output_file_fields, cds_data, for_localStorage, localStorage_key) { // output_file_fields: VI fields to be stored (from the list defined in prospect.utilities) // cds_data: data from Bokeh CDS containing VI informations // must contain at least "VI_quality_flag", "VI_comment", "VI_issue_flag" // for_localStorage (bool): if true, the output format is slightly modified: // no header, add a first column providing spectrum number. // localStorage_key: if not undefined, previous VI information from the // browser's localStorage (with corresponding key) is read // beforehand and included to the output. var nb_fields = output_file_fields.length var nspec = cds_data['VI_quality_flag'].length var array_to_store = [] if (for_localStorage == false) { var header = [] for (var j=0; j<nb_fields; j++) header.push(output_file_fields[j][0]) array_to_store.push(header) } if (localStorage_key !== undefined) { var previously_stored_ispecs = [] if (localStorage_key in localStorage) { var recovered_csv = localStorage.getItem(localStorage_key) var recovered_entries = recovered_csv.split("\n") for (var j=0; j<recovered_entries.length; j++) { var row = CSVtoArray(recovered_entries[j]) array_to_store.push(row) previously_stored_ispecs.push(Number(row[0])) } } } for (var i_spec=0; i_spec<nspec; i_spec++) { // Record only information if a VI quality was assigned // or some VI comment/issue/z was given: if ( (cds_data['VI_quality_flag'][i_spec] != "-1") || (cds_data['VI_comment'][i_spec].trim() != "") || (cds_data['VI_issue_flag'][i_spec].trim() != "") || (cds_data['VI_z'][i_spec].trim() != "") ) { var row = [] if (for_localStorage == true) { row.push(i_spec.toString()) } for (var j=0; j<nb_fields; j++) { var entry = cds_data[output_file_fields[j][1]][i_spec] if (output_file_fields[j][1] == "Z") entry = entry.toFixed(4) if (output_file_fields[j][1] == "DELTACHI2") entry = entry.toFixed(1) if ( typeof(entry) != "string" ) entry = entry.toString() entry = entry.replace(/"/g, '""') entry = entry.replace(/,/g, '","') if (for_localStorage == false) { if (entry==" ") entry = "" } row.push(entry) } var i_rec = -1 if (localStorage_key !== undefined) { var i_rec = -1 i_rec = previously_stored_ispecs.indexOf(i_spec) if (i_rec == -1) { array_to_store.push(row) } else { array_to_store[i_rec] = row // Replace entry } } else { array_to_store.push(row) } } } var csv_to_store = '' for (var j=0; j<array_to_store.length; j++) { var row = (array_to_store[j]).join(',') csv_to_store += ( row.concat("\n") ) } return csv_to_store }
[ "function databasket2csv() {\n var csv = '\"sep=,\"\\nID,text,hearths,paid,place,book,date\\n';\n var itemsArray = JSON.parse(localStorage.getItem('hearthtax_databasket')) ||[];\n $('span#daba_length').html(itemsArray.length);\n var itemsArray = JSON.parse(localStorage.getItem('hearthtax_databasket')) ||[];\n for (var outerCount = 0;\n outerCount < itemsArray.length;\n outerCount++) {\n csv += '\"' + itemsArray[outerCount].xml_id + '\",\"' + itemsArray[outerCount].text + '\",\"' + itemsArray[outerCount].hearths + '\",\"' + itemsArray[outerCount].status + '\",\"' + itemsArray[outerCount].place + '\",\"' + itemsArray[outerCount].book + '\",\"' + itemsArray[outerCount].date + '\"\\n';\n };\n //console.log(csv);\n //create, click and remove fake download link\n var fakeLink = document.createElement('a');\n fakeLink.setAttribute('href', 'data:text/csv;charset=utf-8,' + encodeURIComponent(csv));\n fakeLink.setAttribute('download', 'databasket.csv');\n \n fakeLink.style.display = 'none';\n document.body.appendChild(fakeLink);\n \n fakeLink.click();\n \n document.body.removeChild(fakeLink);\n}", "function saveCSVcontents(keys, data) {\n localStorage.setItem('csv', JSON.stringify({ tableHead : keys, tableBody : data }));\n }", "function saveData() {\n var rows = [[\"trialNum\", \"trialPhase\", \"trialType\", \"time\",\n \"cursorX\", \"cursorY\", \"handX\", \"handY\"]];\n for (let i=0; i < data.trialNum.length; i++) {\n let trialData = [data.trialNum[i], data.trialPhase[i], data.trialType[i],\n data.time[i], data.cursorX[i], data.cursorY[i], data.handX[i], data.handY[i]]; \n rows.push(trialData);\n }\n let csvContent = \"data:text/csv;charset=utf-8,\"; \n rows.forEach(function(rowArray) {\n let row = rowArray.join(\",\");\n csvContent += row + \"\\r\\n\";\n });\n var encodedURI = encodeURI(csvContent);\n var link = document.createElement(\"a\");\n link.setAttribute(\"href\", encodedURI);\n link.setAttribute(\"download\", \"state_data.csv\");\n document.body.appendChild(link);\n link.click();\n}", "function csv2db() {\n\n}", "function download_vi_file(output_file_fields, cds_data, output_file) {\n var for_localStorage = false\n var csv_to_store = vi_to_csv(output_file_fields, cds_data, for_localStorage)\n var blob = new window.Blob([csv_to_store], {type: 'text/csv'})\n saveAs(blob, output_file)\n}", "saveCSV() {\n this.data = Exporter.convertJSONToCsv(this.data);\n this.save();\n }", "function convertToCSV(arr){\n\n}", "function saveAsCSV() {\n var obj = JSON.stringify(data);\n obj = 'data:text/csv;charset=utf-8,'+ 'sep=,\\r\\n' + ConvertToCSV(obj);\n var encodedUri = encodeURI(obj);\n var link = document.createElement(\"a\");\n link.setAttribute(\"href\", encodedUri);\n link.setAttribute(\"download\", \"my_data.csv\");\n\n link.click();\n\n}", "function saveCSVFile(){\n\n\t\tlet today = new Date(), d = today.getDate(),m = today.getMonth()+1,y = today.getFullYear()\n\t\tlet cdate = y+'-'+twod(m)+'-'+twod(d)\n\t\tlet cdd = document.getElementById(\"select-class\"), cn = cdd.options[cdd.selectedIndex].text;\n\t\t// prepend file outputs with UTF-8 BOM\n\t\tlet header = '\\ufeff'+'Attendance for: '+cn+' on '+cdate+'\\n\\n'+'Names'+'\\t'+cdate+' '+sessionStorage.getItem('Meeting-start-time')+'\\t'+'Arrival time'+'\\n'\n\t\tlet joined = /^\\s*([✔\\?])(\\s*)(.*)$/gm\n\t\tlet txt = document.getElementById('invited-list').value.replace(joined, \"$3\"+'\\t'+\"$1\")\n\n\t\tfor (let pid in _arrivalTimes){\n\t\t\tlet re_name = new RegExp('('+_arrivalTimes[pid].name+'.*)', 'i')\n\t\t\ttxt = txt.replace(re_name, '$1'+'\\t'+_arrivalTimes[pid].arrived +' ('+_arrivalTimes[pid].stayed+'min) ['+_arrivalTimes[pid].last_seen+']')\n\t\t}\n\t\tlet blob = new Blob([header+txt], {type: 'text/plain;charset = utf-8'})\n\t\tlet temp_a = document.createElement(\"a\")\n\t\ttemp_a.download = cn + ' ('+cdate+').csv'\n\t\ttemp_a.href = window.webkitURL.createObjectURL(blob)\n\t\ttemp_a.click()\n\t\twrite2log('Saved CSV file ' + cn + ' ('+cdate+').csv' )\n\n\t\tdocument.getElementById('save-csv-file').style.visibility = 'hidden'\n\t\n\t}", "function createCSV() {\n\tvar csvContent = \"\";\n\tvar header1 = \"GenderMag Recorder's Assistant Results\"\n\tcsvContent += header1 + \"\\n\";\n\tvar header2 = [\"Date\", \"Time\", \"Team\", \"Persona\", \"Scenario\"];\n\tcsvContent += header2.join(\",\") + \"\\n\";\n\tvar teamName = localStorage.getItem(\"teamName\");\n\tvar personaName = localStorage.getItem(\"personaName\");\n\tvar scenarioName = localStorage.getItem(\"scenarioName\");\n\tvar today = new Date();\n\tvar dd = String(today.getDate()).padStart(2, '0');\n\tvar mm = today.getMonth();\n\tvar yyyy = today.getFullYear();\n var months = [\"January\", \"February\", \"March\", \"April\", \"May\", \"June\", \"July\", \"August\", \"September\", \"October\", \"November\", \"December\"];\n\tvar todayString = months[mm] + \" \" + dd + \" \" + yyyy;\n\tvar DTTPS = [todayString, now(), teamName, personaName, scenarioName];\n\tconsole.log(todayString);\n\tglobName += DTTPS[0];\n\tglobName += DTTPS[2];\n\tglobName += \"GenderMagSession\";\n\tcsvContent += DTTPS.join(\",\") + \"\\n\";\n\n\tvar fullContent = getSubgoalInfo();\n\tcsvContent += fullContent;\n\t\n\treturn csvContent;\n}", "outputDataToCSV(self) {\n let portfolio = new Portfolio(self.stocksToRetrieve);\n\n let displayArray = [];\n\n portfolio.displayItems.forEach((item) => {\n displayArray.push(item.displayObjects);\n });\n\n let csv = CsvUtils.jsonArrayToCsv(displayArray);\n \n CsvUtils.writeToFile(stockOutputCsvPath, csv);\n }", "saveCSV(data, filename) {\n const processRow = (row) => {\n let finalVal = '';\n for (let j = 0; j < row.length; j += 1) {\n let innerValue = row[j];\n if (row[j] instanceof Date) {\n innerValue = row[j].toLocaleString();\n }\n let result = innerValue.replace(/\"/g, '\"\"').replace(/[\\u2018\\u2019]/g, '').replace(/[\\u201C\\u201D]/g, '');\n\n if (result.search(/(\"|,|\\n)/g) >= 0) {\n result = `\"${result}\"`;\n }\n if (j > 0) {\n finalVal += ',';\n }\n finalVal += result;\n }\n return `${finalVal}\\n`;\n };\n\n let csvFile = processRow(data.columns);\n $.each(data.rows, (i, r) => {\n csvFile += processRow(r);\n });\n csts.libs.utils.getBlob('text/csv', csvFile, filename);\n }", "function createCSV() {\n let data = [[\n 'EmployerName',\n 'EventId',\n 'EventName',\n 'DisplayPriority',\n 'RewardType',\n 'PointsAwarded',\n 'RewardDescription',\n 'AllowSameDayDuplicates',\n 'IsOngoing',\n 'IsDisabled',\n 'ShowInProgram',\n 'IsSelfReport',\n 'DataFeedMode',\n 'Notify',\n 'ButtonText',\n 'TargetUrl',\n 'EventImageUrl',\n 'MaxOccurrences',\n 'StartDate',\n 'EndDate',\n 'ViewPages',\n 'Dimensions',\n 'ShortDescription',\n 'HtmlDescription',\n 'SubgroupId',\n 'Field1Name',\n 'Field1Value',\n 'Field2Name',\n 'Field2Value',\n 'Field3Name',\n 'Field3Value'\n ]];\n\n\n const employerName = $('#employerName').val();\n\n const eventName = $('#eventName').val();\n const eventId = $('#eventId').val();\n const pointsAwarded = $('#pointsAwarded').val();\n const maxOccurrences = $('#maxOccurrences').val();\n\n const cie = [\n employerName,\n eventId,\n '\"' + eventName + '\"',\n '',\n 'IncentivePoints',\n pointsAwarded.replace(',', ''),\n '',\n '1',\n '0',\n '0',\n '0',\n '0',\n '0',\n '0',\n '',\n '',\n '',\n maxOccurrences,\n '',\n '',\n '',\n '',\n '',\n '',\n '',\n '',\n '',\n '',\n '',\n '',\n ''\n ];\n\n data.push(cie);\n\n return data;\n }", "toCSV() {\n let strArray = this.str.split(\"\");\n const writeCSV = fs.createWriteStream(\"output.csv\");\n let status = writeCSV.write(strArray.join(\",\"));\n if (status) {\n return \"CSV created!\";\n } else {\n return \"CSV failed!\";\n }\n }", "getCSVString() {\n let data = this.getDataSummary();\n this.sortStore();\n let rtn = \"Year,Session,Code,Name,Units\\n\";\n this.store.years.forEach(year => {\n year.sessions.forEach(session => {\n session.courses.forEach(course => {\n let data = this.getCourseData(year.name, course.code);\n rtn += `${year.name},${session.name},${course.code},${data.name.replace(\",\", \"\")},${data.units}\\n`;\n\n });\n });\n });\n return rtn;\n }", "function createFinalCSV() {\n\tvar csv = encodeURIComponent(\"Data source,Data point,Value,Time\") + \"%0A\";\n \n for (var i in points) {\n\t var pointInfo = getDataPointInfo(points[i]);\n\t csv += createCSVHistory(pointInfo, startTime);\n }\n \n return csv;\n}", "function packitForCSV() {\n\tvar csv = '';\n\n\tfor(var k in extract){\n\t\tcsv += '\" ' + extract[k][0] + ' \"\\t\"' + extract[k][1] + \"\\\"\\n\";\n\t}\n\n\tvar input = document.createElement('textarea');\n\tdocument.body.appendChild(input);\n\tinput.value = csv;\n\tinput.focus();\n\tinput.select();\n\tdocument.execCommand('copy');\n\tinput.remove();\n}", "toCsv() {\n let data = this.toTableData();\n return 'data:text/csv;charset=utf-8,\\ufeff' \n + data.map(e => e.join(',')).join('\\n');\n }", "convertAssignmentsToCSV(){\n if(!this.assignments.length) return\n let assignmentsCSV = []\n assignmentsCSV[0] = [\"loan_id\",\"facility_id\"]\n for(let i=0;i<this.assignments.length;i++){\n if(this.assignments[i]){\n assignmentsCSV[i+1] = [this.assignments[i].loan.id,this.assignments[i].facility.id]\n }\n }\n let csvContent = \"data:text/csv;charset=utf-8,\" + assignmentsCSV.map(e => e.join(\",\")).join(\"\\n\");\n let encodedUri = encodeURI(csvContent);\n //downloading as csv\n let downloadLink = document.createElement(\"a\");\n downloadLink.href = encodedUri;\n downloadLink.download = \"assignments.csv\";\n\n document.body.appendChild(downloadLink);\n downloadLink.click();\n document.body.removeChild(downloadLink);\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }